Botan 3.5.0
Crypto and TLS for C&
ffi_cipher.cpp
Go to the documentation of this file.
1/*
2* (C) 2015,2017 Jack Lloyd
3*
4* Botan is released under the Simplified BSD License (see license.txt)
5*/
6
7#include <botan/ffi.h>
8
9#include <botan/aead.h>
10#include <botan/internal/bit_ops.h>
11#include <botan/internal/ffi_util.h>
12#include <botan/internal/stl_util.h>
13
14#include <limits>
15
16extern "C" {
17
18using namespace Botan_FFI;
19
20struct botan_cipher_struct final : public botan_struct<Botan::Cipher_Mode, 0xB4A2BF9C> {
21 public:
22 explicit botan_cipher_struct(std::unique_ptr<Botan::Cipher_Mode> x,
23 size_t update_size,
24 size_t ideal_update_size) :
25 botan_struct(std::move(x)), m_update_size(update_size), m_ideal_update_size(ideal_update_size) {
26 BOTAN_DEBUG_ASSERT(ideal_update_size >= update_size);
27 m_buf.reserve(m_ideal_update_size);
28 }
29
30 Botan::secure_vector<uint8_t>& buf() { return m_buf; }
31
32 size_t update_size() const { return m_update_size; }
33
34 size_t ideal_update_size() const { return m_ideal_update_size; }
35
36 private:
38 size_t m_update_size;
39 size_t m_ideal_update_size;
40};
41
42namespace {
43
44/**
45 * Select an update size so that the following constraints are satisfies:
46 *
47 * - greater than or equal to the mode's update granularity
48 * - greater than the mode's minimum final size
49 * - the mode's ideal update granularity is a multiple of this size
50 * - (optional) a power of 2
51 *
52 * Note that this is necessary mostly for backward-compatibility with previous
53 * versions of the FFI (prior to Botan 3.5.0). For Botan 4.0.0 we should just
54 * directly return the update granularity of the cipher mode and instruct users
55 * to switch to botan_cipher_get_ideal_update_granularity() instead. See also
56 * the discussion in GitHub Issue #4090.
57 */
58size_t ffi_choose_update_size(Botan::Cipher_Mode& mode) {
59 const size_t update_granularity = mode.update_granularity();
60 const size_t ideal_update_granularity = mode.ideal_granularity();
61 const size_t minimum_final_size = mode.minimum_final_size();
62
63 // If the minimum final size is zero, or the update_granularity is
64 // already greater, just use that.
65 if(minimum_final_size == 0 || update_granularity > minimum_final_size) {
66 BOTAN_ASSERT_NOMSG(update_granularity > 0);
67 return update_granularity;
68 }
69
70 // If the ideal granularity is a multiple of the minimum final size, we
71 // might be able to use that if it stays within the ideal granularity.
72 if(ideal_update_granularity % minimum_final_size == 0 && minimum_final_size * 2 <= ideal_update_granularity) {
73 return minimum_final_size * 2;
74 }
75
76 // Otherwise, try to use the next power of two greater than the minimum
77 // final size, if the ideal granularity is a multiple of that.
78 BOTAN_ASSERT_NOMSG(minimum_final_size <= std::numeric_limits<uint16_t>::max());
79 const size_t b1 = size_t(1) << Botan::ceil_log2(static_cast<uint16_t>(minimum_final_size));
80 if(ideal_update_granularity % b1 == 0) {
81 return b1;
82 }
83
84 // Last resort: Find the next integer greater than the minimum final size
85 // for which the ideal granularity is a multiple of.
86 // Most sensible cipher modes should never reach this point.
87 BOTAN_ASSERT_NOMSG(minimum_final_size < ideal_update_granularity);
88 size_t b2 = minimum_final_size + 1;
89 for(; b2 < ideal_update_granularity && ideal_update_granularity % b2 != 0; ++b2) {}
90
91 return b2;
92}
93
94} // namespace
95
96int botan_cipher_init(botan_cipher_t* cipher, const char* cipher_name, uint32_t flags) {
97 return ffi_guard_thunk(__func__, [=]() -> int {
100
101 std::unique_ptr<Botan::Cipher_Mode> mode(Botan::Cipher_Mode::create(cipher_name, dir));
102 if(!mode) {
104 }
105
106 const size_t update_size = ffi_choose_update_size(*mode);
107 const size_t ideal_update_size = std::max(mode->ideal_granularity(), update_size);
108
109 *cipher = new botan_cipher_struct(std::move(mode), update_size, ideal_update_size);
110 return BOTAN_FFI_SUCCESS;
111 });
112}
113
115 return BOTAN_FFI_CHECKED_DELETE(cipher);
116}
117
119 return BOTAN_FFI_VISIT(cipher, [](auto& c) { c.clear(); });
120}
121
123 return BOTAN_FFI_VISIT(cipher, [](auto& c) { c.reset(); });
124}
125
126int botan_cipher_output_length(botan_cipher_t cipher, size_t in_len, size_t* out_len) {
127 if(out_len == nullptr) {
129 }
130
131 return BOTAN_FFI_VISIT(cipher, [=](const auto& c) { *out_len = c.output_length(in_len); });
132}
133
134int botan_cipher_query_keylen(botan_cipher_t cipher, size_t* out_minimum_keylength, size_t* out_maximum_keylength) {
135 return BOTAN_FFI_VISIT(cipher, [=](const auto& c) {
136 *out_minimum_keylength = c.key_spec().minimum_keylength();
137 *out_maximum_keylength = c.key_spec().maximum_keylength();
138 });
139}
140
142 size_t* out_minimum_keylength,
143 size_t* out_maximum_keylength,
144 size_t* out_keylength_modulo) {
145 return BOTAN_FFI_VISIT(cipher, [=](const auto& c) {
146 if(out_minimum_keylength)
147 *out_minimum_keylength = c.key_spec().minimum_keylength();
148 if(out_maximum_keylength)
149 *out_maximum_keylength = c.key_spec().maximum_keylength();
150 if(out_keylength_modulo)
151 *out_keylength_modulo = c.key_spec().keylength_multiple();
152 });
153}
154
155int botan_cipher_set_key(botan_cipher_t cipher, const uint8_t* key, size_t key_len) {
156 return BOTAN_FFI_VISIT(cipher, [=](auto& c) { c.set_key(key, key_len); });
157}
158
159int botan_cipher_start(botan_cipher_t cipher_obj, const uint8_t* nonce, size_t nonce_len) {
160 return ffi_guard_thunk(__func__, [=]() -> int {
161 Botan::Cipher_Mode& cipher = safe_get(cipher_obj);
162 cipher.start(nonce, nonce_len);
163 return BOTAN_FFI_SUCCESS;
164 });
165}
166
168 uint32_t flags,
169 uint8_t output[],
170 size_t output_size,
171 size_t* output_written,
172 const uint8_t input[],
173 size_t input_size,
174 size_t* input_consumed) {
175 return ffi_guard_thunk(__func__, [=]() -> int {
176 using namespace Botan;
177 Cipher_Mode& cipher = safe_get(cipher_obj);
178 secure_vector<uint8_t>& mbuf = cipher_obj->buf();
179
180 // If the cipher object's internal buffer contains residual data from
181 // a previous invocation, we can be sure that botan_cipher_update() was
182 // called with the final flag set but not enough buffer space was provided
183 // to accommodate the final output.
184 const bool was_finished_before = !mbuf.empty();
185 const bool final_input = (flags & BOTAN_CIPHER_UPDATE_FLAG_FINAL);
186
187 // Bring the output variables into a defined state.
188 *output_written = 0;
189 *input_consumed = 0;
190
191 // Once the final flag was set once, it must always be set for
192 // consecutive invocations.
193 if(was_finished_before && !final_input) {
195 }
196
197 // If the final flag was set in a previous invocation, no more input
198 // data can be processed.
199 if(was_finished_before && input_size > 0) {
201 }
202
203 // Make sure that we always clear the internal buffer before returning
204 // or aborting this invocation due to an exception.
205 auto clean_buffer = scoped_cleanup([&mbuf] { mbuf.clear(); });
206
207 if(final_input) {
208 // If the final flag is set for the first time, we need to process the
209 // remaining input data and then finalize the cipher object.
210 if(!was_finished_before) {
211 *input_consumed = input_size;
212 mbuf.resize(input_size);
213 copy_mem(mbuf, std::span(input, input_size));
214
215 try {
216 cipher.finish(mbuf);
219 }
220 }
221
222 // At this point, the cipher object is finalized (potentially in a
223 // previous invocation) and we can copy the final output to the caller.
224 *output_written = mbuf.size();
225
226 // Not enough space to copy the final output out to the caller.
227 // Inform them how much space we need for a successful operation.
228 if(output_size < mbuf.size()) {
229 // This is the only place where mbuf is not cleared before returning.
230 clean_buffer.disengage();
232 }
233
234 // Copy the final output to the caller, mbuf is cleared afterwards.
235 copy_mem(std::span(output, mbuf.size()), mbuf);
236 } else {
237 // Process data in a streamed fashion without finalizing. No data is
238 // ever retained in the cipher object's internal buffer. If we run out
239 // of either input data or output capacity, we stop and report that not
240 // all bytes were processed via *output_written and *input_consumed.
241
242 BufferSlicer in({input, input_size});
243 BufferStuffer out({output, output_size});
244
245 // Helper function to do blockwise processing of data.
246 auto blockwise_update = [&](const size_t granularity) {
247 if(granularity == 0) {
248 return;
249 }
250
251 const size_t expected_output_per_iteration = cipher.requires_entire_message() ? 0 : granularity;
252 mbuf.resize(granularity);
253
254 while(in.remaining() >= granularity && out.remaining_capacity() >= expected_output_per_iteration) {
255 copy_mem(mbuf, in.take(granularity));
256 const auto written_bytes = cipher.process(mbuf);
257 BOTAN_DEBUG_ASSERT(written_bytes == expected_output_per_iteration);
258 if(written_bytes > 0) {
259 BOTAN_ASSERT_NOMSG(written_bytes <= granularity);
260 copy_mem(out.next(written_bytes), std::span(mbuf).first(written_bytes));
261 }
262 }
263 };
264
265 // First, process as much data as possible in chunks of ideal granularity
266 blockwise_update(cipher_obj->ideal_update_size());
267
268 // Then process the remaining bytes in chunks of update_size() or, in one go
269 // if update_size() is equal to 1 --> i.e. likely a stream cipher.
270 const bool is_stream_cipher = (cipher_obj->update_size() == 1);
271 const size_t tail_granularity =
272 is_stream_cipher ? std::min(in.remaining(), out.remaining_capacity()) : cipher_obj->update_size();
273 BOTAN_DEBUG_ASSERT(tail_granularity < cipher_obj->ideal_update_size());
274 blockwise_update(tail_granularity);
275
276 // Inform the caller about the amount of data processed.
277 *output_written = output_size - out.remaining_capacity();
278 *input_consumed = input_size - in.remaining();
279 }
280
281 return BOTAN_FFI_SUCCESS;
282 });
283}
284
285int botan_cipher_set_associated_data(botan_cipher_t cipher, const uint8_t* ad, size_t ad_len) {
286 return BOTAN_FFI_VISIT(cipher, [=](auto& c) {
287 if(Botan::AEAD_Mode* aead = dynamic_cast<Botan::AEAD_Mode*>(&c)) {
288 aead->set_associated_data(ad, ad_len);
289 return BOTAN_FFI_SUCCESS;
290 }
292 });
293}
294
296 return BOTAN_FFI_VISIT(cipher, [=](const auto& c) { return c.valid_nonce_length(nl) ? 1 : 0; });
297}
298
300 return BOTAN_FFI_VISIT(cipher, [=](const auto& c) { *nl = c.default_nonce_length(); });
301}
302
304 return BOTAN_FFI_VISIT(cipher, [=](const auto& /*c*/) { *ug = cipher->update_size(); });
305}
306
308 return BOTAN_FFI_VISIT(cipher, [=](const auto& c) { *ug = c.ideal_granularity(); });
309}
310
312 return BOTAN_FFI_VISIT(cipher, [=](const auto& c) { *tl = c.tag_size(); });
313}
314
316 return BOTAN_FFI_VISIT(cipher, [=](const auto& c) { return c.authenticated() ? 1 : 0; });
317}
318
320 return BOTAN_FFI_VISIT(cipher, [=](const auto& c) { return c.requires_entire_message() ? 1 : 0; });
321}
322
323int botan_cipher_name(botan_cipher_t cipher, char* name, size_t* name_len) {
324 return BOTAN_FFI_VISIT(cipher, [=](const auto& c) { return write_str_output(name, name_len, c.name()); });
325}
326}
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:59
#define BOTAN_DEBUG_ASSERT(expr)
Definition assert.h:98
Helper class to ease in-place marshalling of concatenated fixed-length values.
Definition stl_util.h:142
static std::unique_ptr< Cipher_Mode > create(std::string_view algo, Cipher_Dir direction, std::string_view provider="")
void start(std::span< const uint8_t > nonce)
Definition cipher_mode.h:89
void finish(secure_vector< uint8_t > &final_block, size_t offset=0)
virtual bool requires_entire_message() const
virtual size_t ideal_granularity() const =0
size_t process(std::span< uint8_t > msg)
virtual size_t minimum_final_size() const =0
virtual size_t update_granularity() const =0
Helper class to create a RAII-style cleanup callback.
Definition stl_util.h:353
std::string name
int(* final)(unsigned char *, CTX *)
#define BOTAN_CIPHER_INIT_FLAG_ENCRYPT
Definition ffi.h:527
#define BOTAN_CIPHER_UPDATE_FLAG_FINAL
Definition ffi.h:621
#define BOTAN_CIPHER_INIT_FLAG_MASK_DIRECTION
Definition ffi.h:526
@ BOTAN_FFI_ERROR_NOT_IMPLEMENTED
Definition ffi.h:124
@ BOTAN_FFI_ERROR_NULL_POINTER
Definition ffi.h:118
@ BOTAN_FFI_SUCCESS
Definition ffi.h:103
@ BOTAN_FFI_ERROR_INVALID_OBJECT_STATE
Definition ffi.h:122
@ BOTAN_FFI_ERROR_INSUFFICIENT_BUFFER_SPACE
Definition ffi.h:109
@ BOTAN_FFI_ERROR_BAD_MAC
Definition ffi.h:107
@ BOTAN_FFI_ERROR_BAD_PARAMETER
Definition ffi.h:119
struct botan_cipher_struct * botan_cipher_t
Definition ffi.h:524
int botan_cipher_valid_nonce_length(botan_cipher_t cipher, size_t nl)
int botan_cipher_requires_entire_message(botan_cipher_t cipher)
int botan_cipher_output_length(botan_cipher_t cipher, size_t in_len, size_t *out_len)
int botan_cipher_reset(botan_cipher_t cipher)
int botan_cipher_destroy(botan_cipher_t cipher)
int botan_cipher_name(botan_cipher_t cipher, char *name, size_t *name_len)
int botan_cipher_set_associated_data(botan_cipher_t cipher, const uint8_t *ad, size_t ad_len)
int botan_cipher_start(botan_cipher_t cipher_obj, const uint8_t *nonce, size_t nonce_len)
int botan_cipher_get_tag_length(botan_cipher_t cipher, size_t *tl)
int botan_cipher_update(botan_cipher_t cipher_obj, uint32_t flags, uint8_t output[], size_t output_size, size_t *output_written, const uint8_t input[], size_t input_size, size_t *input_consumed)
Encrypt/Decrypt some data and/or finalize the encryption/decryption.
int botan_cipher_get_keyspec(botan_cipher_t cipher, size_t *out_minimum_keylength, size_t *out_maximum_keylength, size_t *out_keylength_modulo)
int botan_cipher_set_key(botan_cipher_t cipher, const uint8_t *key, size_t key_len)
int botan_cipher_get_ideal_update_granularity(botan_cipher_t cipher, size_t *ug)
int botan_cipher_is_authenticated(botan_cipher_t cipher)
int botan_cipher_clear(botan_cipher_t cipher)
int botan_cipher_get_default_nonce_length(botan_cipher_t cipher, size_t *nl)
int botan_cipher_init(botan_cipher_t *cipher, const char *cipher_name, uint32_t flags)
int botan_cipher_query_keylen(botan_cipher_t cipher, size_t *out_minimum_keylength, size_t *out_maximum_keylength)
int botan_cipher_get_update_granularity(botan_cipher_t cipher, size_t *ug)
#define BOTAN_FFI_VISIT(obj, lambda)
Definition ffi_util.h:124
#define BOTAN_FFI_CHECKED_DELETE(o)
Definition ffi_util.h:143
int write_str_output(uint8_t out[], size_t *out_len, std::string_view str)
Definition ffi_util.h:205
T & safe_get(botan_struct< T, M > *p)
Definition ffi_util.h:63
int ffi_guard_thunk(const char *func_name, const std::function< int()> &thunk)
Definition ffi.cpp:116
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:61
constexpr uint8_t ceil_log2(T x)
Definition bit_ops.h:122