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

randombit / botan / 16248620128

13 Jul 2025 11:27AM UTC coverage: 90.565% (-0.01%) from 90.575%
16248620128

push

github

web-flow
Merge pull request #4983 from randombit/jack/clang-tidy-cppcoreguidelines-owning-memory

Enable and fix clang-tidy warning cppcoreguidelines-owning-memory

99026 of 109342 relevant lines covered (90.57%)

12444574.04 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/stl_util.h>
13

14
#include <limits>
15

16
extern "C" {
17

18
using namespace Botan_FFI;
19

20
struct 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,
31✔
23
                                   size_t update_size,
24
                                   size_t ideal_update_size) :
31✔
25
            botan_struct(std::move(x)), m_update_size(update_size), m_ideal_update_size(ideal_update_size) {
31✔
26
         BOTAN_DEBUG_ASSERT(ideal_update_size >= update_size);
31✔
27
         m_buf.reserve(m_ideal_update_size);
31✔
28
      }
31✔
29

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

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

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

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

42
namespace {
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
 */
58
size_t ffi_choose_update_size(Botan::Cipher_Mode& mode) {
31✔
59
   const size_t update_granularity = mode.update_granularity();
31✔
60
   const size_t ideal_update_granularity = mode.ideal_granularity();
31✔
61
   const size_t minimum_final_size = mode.minimum_final_size();
31✔
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) {
31✔
66
      BOTAN_ASSERT_NOMSG(update_granularity > 0);
15✔
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) {
16✔
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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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