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

randombit / botan / 21712452049

05 Feb 2026 01:00PM UTC coverage: 90.071% (-0.003%) from 90.074%
21712452049

push

github

web-flow
Merge pull request #5286 from randombit/jack/scoped-cleanup-h

Split out scoped_cleanup to its own header

102233 of 113503 relevant lines covered (90.07%)

11479296.78 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/ffi_util.h>
12
#include <botan/internal/scoped_cleanup.h>
13
#include <botan/internal/stl_util.h>
14

15
#include <limits>
16

17
extern "C" {
18

19
using namespace Botan_FFI;
20

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

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

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

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

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

43
namespace {
44

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

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

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

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

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

92
   return b2;
93
}
94

95
}  // namespace
96

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

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

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

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

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

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

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

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

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

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

141
int botan_cipher_get_keyspec(botan_cipher_t cipher,
1✔
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) {
2✔
146
      if(out_minimum_keylength) {
147
         *out_minimum_keylength = c.key_spec().minimum_keylength();
148
      }
149
      if(out_maximum_keylength) {
150
         *out_maximum_keylength = c.key_spec().maximum_keylength();
151
      }
152
      if(out_keylength_modulo) {
153
         *out_keylength_modulo = c.key_spec().keylength_multiple();
154
      }
155
   });
156
}
157

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

326
int botan_cipher_name(botan_cipher_t cipher, char* name, size_t* name_len) {
8✔
327
   return BOTAN_FFI_VISIT(cipher, [=](const auto& c) { return write_str_output(name, name_len, c.name()); });
16✔
328
}
329
}
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