• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

randombit / botan / 21712952425

05 Feb 2026 01:16PM UTC coverage: 90.076% (+0.005%) from 90.071%
21712952425

Pull #5287

github

web-flow
Merge 1b320c06e into 8c9623340
Pull Request #5287: Split out BufferSlicer and BufferStuffer to their own headers

102242 of 113507 relevant lines covered (90.08%)

11534589.25 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

92.44
/src/lib/ffi/ffi_cipher.cpp
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/buffer_slicer.h>
12
#include <botan/internal/buffer_stuffer.h>
13
#include <botan/internal/ffi_util.h>
14
#include <botan/internal/scoped_cleanup.h>
15

16
#include <limits>
17

18
extern "C" {
19

20
using namespace Botan_FFI;
21

22
struct botan_cipher_struct final : public botan_struct<Botan::Cipher_Mode, 0xB4A2BF9C> {
23
   public:
24
      explicit botan_cipher_struct(std::unique_ptr<Botan::Cipher_Mode> x,
31✔
25
                                   size_t update_size,
26
                                   size_t ideal_update_size) :
31✔
27
            botan_struct(std::move(x)), m_update_size(update_size), m_ideal_update_size(ideal_update_size) {
31✔
28
         BOTAN_DEBUG_ASSERT(ideal_update_size >= update_size);
31✔
29
         m_buf.reserve(m_ideal_update_size);
31✔
30
      }
31✔
31

32
      Botan::secure_vector<uint8_t>& buf() { return m_buf; }
103✔
33

34
      size_t update_size() const { return m_update_size; }
92✔
35

36
      size_t ideal_update_size() const { return m_ideal_update_size; }
64✔
37

38
   private:
39
      Botan::secure_vector<uint8_t> m_buf;
40
      size_t m_update_size;
41
      size_t m_ideal_update_size;
42
};
43

44
namespace {
45

46
/**
47
 * Select an update size so that the following constraints are satisfies:
48
 *
49
 *   - greater than or equal to the mode's update granularity
50
 *   - greater than the mode's minimum final size
51
 *   - the mode's ideal update granularity is a multiple of this size
52
 *   - (optional) a power of 2
53
 *
54
 * Note that this is necessary mostly for backward-compatibility with previous
55
 * versions of the FFI (prior to Botan 3.5.0). For Botan 4.0.0 we should just
56
 * directly return the update granularity of the cipher mode and instruct users
57
 * to switch to botan_cipher_get_ideal_update_granularity() instead. See also
58
 * the discussion in GitHub Issue #4090.
59
 */
60
size_t ffi_choose_update_size(Botan::Cipher_Mode& mode) {
31✔
61
   const size_t update_granularity = mode.update_granularity();
31✔
62
   const size_t ideal_update_granularity = mode.ideal_granularity();
31✔
63
   const size_t minimum_final_size = mode.minimum_final_size();
31✔
64

65
   // If the minimum final size is zero, or the update_granularity is
66
   // already greater, just use that.
67
   if(minimum_final_size == 0 || update_granularity > minimum_final_size) {
31✔
68
      BOTAN_ASSERT_NOMSG(update_granularity > 0);
15✔
69
      return update_granularity;
70
   }
71

72
   // If the ideal granularity is a multiple of the minimum final size, we
73
   // might be able to use that if it stays within the ideal granularity.
74
   if(ideal_update_granularity % minimum_final_size == 0 && minimum_final_size * 2 <= ideal_update_granularity) {
16✔
75
      return minimum_final_size * 2;
76
   }
77

78
   // Otherwise, try to use the next power of two greater than the minimum
79
   // final size, if the ideal granularity is a multiple of that.
80
   BOTAN_ASSERT_NOMSG(minimum_final_size <= std::numeric_limits<uint16_t>::max());
×
81
   const size_t b1 = size_t(1) << Botan::ceil_log2(static_cast<uint16_t>(minimum_final_size));
×
82
   if(ideal_update_granularity % b1 == 0) {
×
83
      return b1;
84
   }
85

86
   // Last resort: Find the next integer greater than the minimum final size
87
   //              for which the ideal granularity is a multiple of.
88
   //              Most sensible cipher modes should never reach this point.
89
   BOTAN_ASSERT_NOMSG(minimum_final_size < ideal_update_granularity);
×
90
   size_t b2 = minimum_final_size + 1;
×
91
   for(; b2 < ideal_update_granularity && ideal_update_granularity % b2 != 0; ++b2) {}
×
92

93
   return b2;
94
}
95

96
}  // namespace
97

98
int botan_cipher_init(botan_cipher_t* cipher, const char* cipher_name, uint32_t flags) {
31✔
99
   return ffi_guard_thunk(__func__, [=]() -> int {
31✔
100
      const bool encrypt_p = ((flags & BOTAN_CIPHER_INIT_FLAG_MASK_DIRECTION) == BOTAN_CIPHER_INIT_FLAG_ENCRYPT);
31✔
101
      const Botan::Cipher_Dir dir = encrypt_p ? Botan::Cipher_Dir::Encryption : Botan::Cipher_Dir::Decryption;
31✔
102

103
      std::unique_ptr<Botan::Cipher_Mode> mode(Botan::Cipher_Mode::create(cipher_name, dir));
31✔
104
      if(!mode) {
31✔
105
         return BOTAN_FFI_ERROR_NOT_IMPLEMENTED;
106
      }
107

108
      const size_t update_size = ffi_choose_update_size(*mode);
31✔
109
      const size_t ideal_update_size = std::max(mode->ideal_granularity(), update_size);
31✔
110

111
      return ffi_new_object(cipher, std::move(mode), update_size, ideal_update_size);
31✔
112
   });
31✔
113
}
114

115
int botan_cipher_destroy(botan_cipher_t cipher) {
31✔
116
   return BOTAN_FFI_CHECKED_DELETE(cipher);
31✔
117
}
118

119
int botan_cipher_clear(botan_cipher_t cipher) {
8✔
120
   return BOTAN_FFI_VISIT(cipher, [](auto& c) { c.clear(); });
16✔
121
}
122

123
int botan_cipher_reset(botan_cipher_t cipher) {
4✔
124
   return BOTAN_FFI_VISIT(cipher, [](auto& c) { c.reset(); });
8✔
125
}
126

127
int botan_cipher_output_length(botan_cipher_t cipher, size_t in_len, size_t* out_len) {
4✔
128
   if(out_len == nullptr) {
4✔
129
      return BOTAN_FFI_ERROR_NULL_POINTER;
130
   }
131

132
   return BOTAN_FFI_VISIT(cipher, [=](const auto& c) { *out_len = c.output_length(in_len); });
8✔
133
}
134

135
int botan_cipher_query_keylen(botan_cipher_t cipher, size_t* out_minimum_keylength, size_t* out_maximum_keylength) {
13✔
136
   return BOTAN_FFI_VISIT(cipher, [=](const auto& c) {
26✔
137
      *out_minimum_keylength = c.key_spec().minimum_keylength();
138
      *out_maximum_keylength = c.key_spec().maximum_keylength();
139
   });
140
}
141

142
int botan_cipher_get_keyspec(botan_cipher_t cipher,
1✔
143
                             size_t* out_minimum_keylength,
144
                             size_t* out_maximum_keylength,
145
                             size_t* out_keylength_modulo) {
146
   return BOTAN_FFI_VISIT(cipher, [=](const auto& c) {
2✔
147
      if(out_minimum_keylength) {
148
         *out_minimum_keylength = c.key_spec().minimum_keylength();
149
      }
150
      if(out_maximum_keylength) {
151
         *out_maximum_keylength = c.key_spec().maximum_keylength();
152
      }
153
      if(out_keylength_modulo) {
154
         *out_keylength_modulo = c.key_spec().keylength_multiple();
155
      }
156
   });
157
}
158

159
int botan_cipher_set_key(botan_cipher_t cipher, const uint8_t* key, size_t key_len) {
43✔
160
   return BOTAN_FFI_VISIT(cipher, [=](auto& c) { c.set_key(key, key_len); });
86✔
161
}
162

163
int botan_cipher_start(botan_cipher_t cipher_obj, const uint8_t* nonce, size_t nonce_len) {
47✔
164
   return ffi_guard_thunk(__func__, [=]() -> int {
47✔
165
      Botan::Cipher_Mode& cipher = safe_get(cipher_obj);
47✔
166
      cipher.start(nonce, nonce_len);
47✔
167
      return BOTAN_FFI_SUCCESS;
47✔
168
   });
47✔
169
}
170

171
int botan_cipher_update(botan_cipher_t cipher_obj,
103✔
172
                        uint32_t flags,
173
                        uint8_t output[],
174
                        size_t output_size,
175
                        size_t* output_written,
176
                        const uint8_t input[],
177
                        size_t input_size,
178
                        size_t* input_consumed) {
179
   return ffi_guard_thunk(__func__, [=]() -> int {
103✔
180
      using namespace Botan;
103✔
181
      Cipher_Mode& cipher = safe_get(cipher_obj);
103✔
182
      secure_vector<uint8_t>& mbuf = cipher_obj->buf();
103✔
183

184
      // If the cipher object's internal buffer contains residual data from
185
      // a previous invocation, we can be sure that botan_cipher_update() was
186
      // called with the final flag set but not enough buffer space was provided
187
      // to accommodate the final output.
188
      const bool was_finished_before = !mbuf.empty();
103✔
189
      const bool final_input = (flags & BOTAN_CIPHER_UPDATE_FLAG_FINAL) != 0;
103✔
190

191
      // Bring the output variables into a defined state.
192
      *output_written = 0;
103✔
193
      *input_consumed = 0;
103✔
194

195
      // Once the final flag was set once, it must always be set for
196
      // consecutive invocations.
197
      if(was_finished_before && !final_input) {
103✔
198
         return BOTAN_FFI_ERROR_INVALID_OBJECT_STATE;
199
      }
200

201
      // If the final flag was set in a previous invocation, no more input
202
      // data can be processed.
203
      if(was_finished_before && input_size > 0) {
103✔
204
         return BOTAN_FFI_ERROR_BAD_PARAMETER;
205
      }
206

207
      // Make sure that we always clear the internal buffer before returning
208
      // or aborting this invocation due to an exception.
209
      auto clean_buffer = scoped_cleanup([&mbuf] { mbuf.clear(); });
301✔
210

211
      if(final_input) {
103✔
212
         // If the final flag is set for the first time, we need to process the
213
         // remaining input data and then finalize the cipher object.
214
         if(!was_finished_before) {
39✔
215
            *input_consumed = input_size;
34✔
216
            mbuf.resize(input_size);
34✔
217
            copy_mem(mbuf, std::span(input, input_size));
34✔
218

219
            try {
34✔
220
               cipher.finish(mbuf);
34✔
221
            } catch(Invalid_Authentication_Tag&) {
×
222
               return BOTAN_FFI_ERROR_BAD_MAC;
×
223
            }
×
224
         }
225

226
         // At this point, the cipher object is finalized (potentially in a
227
         // previous invocation) and we can copy the final output to the caller.
228
         *output_written = mbuf.size();
39✔
229

230
         // Not enough space to copy the final output out to the caller.
231
         // Inform them how much space we need for a successful operation.
232
         if(output_size < mbuf.size()) {
39✔
233
            // This is the only place where mbuf is not cleared before returning.
234
            clean_buffer.disengage();
235
            return BOTAN_FFI_ERROR_INSUFFICIENT_BUFFER_SPACE;
236
         }
237

238
         // Copy the final output to the caller, mbuf is cleared afterwards.
239
         copy_mem(std::span(output, mbuf.size()), mbuf);
34✔
240
      } else {
241
         // Process data in a streamed fashion without finalizing. No data is
242
         // ever retained in the cipher object's internal buffer. If we run out
243
         // of either input data or output capacity, we stop and report that not
244
         // all bytes were processed via *output_written and *input_consumed.
245

246
         BufferSlicer in({input, input_size});
64✔
247
         BufferStuffer out({output, output_size});
64✔
248

249
         // Helper function to do blockwise processing of data.
250
         auto blockwise_update = [&](const size_t granularity) {
192✔
251
            if(granularity == 0) {
128✔
252
               return;
253
            }
254

255
            const size_t expected_output_per_iteration = cipher.requires_entire_message() ? 0 : granularity;
100✔
256
            mbuf.resize(granularity);
100✔
257

258
            while(in.remaining() >= granularity && out.remaining_capacity() >= expected_output_per_iteration) {
262✔
259
               copy_mem(mbuf, in.take(granularity));
62✔
260
               const auto written_bytes = cipher.process(mbuf);
62✔
261
               BOTAN_DEBUG_ASSERT(written_bytes == expected_output_per_iteration);
62✔
262
               if(written_bytes > 0) {
62✔
263
                  BOTAN_ASSERT_NOMSG(written_bytes <= granularity);
42✔
264
                  copy_mem(out.next(written_bytes), std::span(mbuf).first(written_bytes));
42✔
265
               }
266
            }
267
         };
64✔
268

269
         // First, process as much data as possible in chunks of ideal granularity
270
         blockwise_update(cipher_obj->ideal_update_size());
64✔
271

272
         // Then process the remaining bytes in chunks of update_size() or, in one go
273
         // if update_size() is equal to 1 --> i.e. likely a stream cipher.
274
         const bool is_stream_cipher = (cipher_obj->update_size() == 1);
64✔
275
         const size_t tail_granularity =
64✔
276
            is_stream_cipher ? std::min(in.remaining(), out.remaining_capacity()) : cipher_obj->update_size();
64✔
277
         BOTAN_DEBUG_ASSERT(tail_granularity < cipher_obj->ideal_update_size());
64✔
278
         blockwise_update(tail_granularity);
64✔
279

280
         // Inform the caller about the amount of data processed.
281
         *output_written = output_size - out.remaining_capacity();
64✔
282
         *input_consumed = input_size - in.remaining();
64✔
283
      }
284

285
      return BOTAN_FFI_SUCCESS;
286
   });
103✔
287
}
288

289
int botan_cipher_set_associated_data(botan_cipher_t cipher, const uint8_t* ad, size_t ad_len) {
8✔
290
   return BOTAN_FFI_VISIT(cipher, [=](auto& c) {
16✔
291
      if(Botan::AEAD_Mode* aead = dynamic_cast<Botan::AEAD_Mode*>(&c)) {
292
         aead->set_associated_data(ad, ad_len);
293
         return BOTAN_FFI_SUCCESS;
294
      }
295
      return BOTAN_FFI_ERROR_BAD_PARAMETER;
296
   });
297
}
298

299
int botan_cipher_valid_nonce_length(botan_cipher_t cipher, size_t nl) {
6✔
300
   return BOTAN_FFI_VISIT(cipher, [=](const auto& c) { return c.valid_nonce_length(nl) ? 1 : 0; });
12✔
301
}
302

303
int botan_cipher_get_default_nonce_length(botan_cipher_t cipher, size_t* nl) {
12✔
304
   return BOTAN_FFI_VISIT(cipher, [=](const auto& c) { *nl = c.default_nonce_length(); });
24✔
305
}
306

307
int botan_cipher_get_update_granularity(botan_cipher_t cipher, size_t* ug) {
28✔
308
   return BOTAN_FFI_VISIT(cipher, [=](const auto& /*c*/) { *ug = cipher->update_size(); });
56✔
309
}
310

311
int botan_cipher_get_ideal_update_granularity(botan_cipher_t cipher, size_t* ug) {
28✔
312
   return BOTAN_FFI_VISIT(cipher, [=](const auto& c) { *ug = c.ideal_granularity(); });
56✔
313
}
314

315
int botan_cipher_get_tag_length(botan_cipher_t cipher, size_t* tl) {
16✔
316
   return BOTAN_FFI_VISIT(cipher, [=](const auto& c) { *tl = c.tag_size(); });
32✔
317
}
318

319
int botan_cipher_is_authenticated(botan_cipher_t cipher) {
15✔
320
   return BOTAN_FFI_VISIT(cipher, [=](const auto& c) { return c.authenticated() ? 1 : 0; });
30✔
321
}
322

323
int botan_cipher_requires_entire_message(botan_cipher_t cipher) {
5✔
324
   return BOTAN_FFI_VISIT(cipher, [=](const auto& c) { return c.requires_entire_message() ? 1 : 0; });
10✔
325
}
326

327
int botan_cipher_name(botan_cipher_t cipher, char* name, size_t* name_len) {
8✔
328
   return BOTAN_FFI_VISIT(cipher, [=](const auto& c) { return write_str_output(name, name_len, c.name()); });
16✔
329
}
330
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc