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