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

randombit / botan / 23225340130

18 Mar 2026 01:53AM UTC coverage: 89.677% (-0.001%) from 89.678%
23225340130

push

github

web-flow
Merge pull request #5456 from randombit/jack/clang-tidy-22

Fix various warnings from clang-tidy 22

104438 of 116460 relevant lines covered (89.68%)

11819947.55 hits per line

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

89.32
/src/cli/timing_tests.cpp
1
/*
2
* Timing Analysis Tests
3
*
4
* These tests are not for performance, but verifying that two inputs are not handled
5
* in a way that is vulnerable to simple timing attacks.
6
*
7
* Produces output which can be analyzed with the Mona reporting library
8
*
9
* $ git clone https://github.com/seecurity/mona-timing-report.git
10
* $ cd mona-timing-report && ant
11
* $ java -jar ReportingTool.jar --lowerBound=0.4 --upperBound=0.5 --inputFile=$file --name=$file
12
*
13
* (C) 2016 Juraj Somorovsky - juraj.somorovsky@hackmanit.de
14
* (C) 2017 Neverhub
15
* (C) 2017,2018,2019 Jack Lloyd
16
*
17
* Botan is released under the Simplified BSD License (see license.txt)
18
*/
19

20
#include "cli.h"
21

22
#include <botan/hex.h>
23
#include <botan/rng.h>
24
#include <botan/internal/ct_utils.h>
25
#include <botan/internal/filesystem.h>
26
#include <botan/internal/fmt.h>
27
#include <botan/internal/loadstor.h>
28
#include <botan/internal/parsing.h>
29
#include <botan/internal/target_info.h>
30
#include <chrono>
31
#include <fstream>
32
#include <iostream>
33
#include <sstream>
34

35
#if defined(BOTAN_HAS_BIGINT)
36
   #include <botan/bigint.h>
37
#endif
38

39
#if defined(BOTAN_HAS_NUMBERTHEORY)
40
   #include <botan/numthry.h>
41
   #include <botan/internal/mod_inv.h>
42
#endif
43

44
#if defined(BOTAN_HAS_ECC_GROUP)
45
   #include <botan/ec_group.h>
46
#endif
47

48
#if defined(BOTAN_HAS_DL_GROUP)
49
   #include <botan/dl_group.h>
50
#endif
51

52
#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)
53
   #include <botan/pkcs8.h>
54
   #include <botan/pubkey.h>
55
#endif
56

57
#if defined(BOTAN_HAS_RSA)
58
   #include <botan/rsa.h>
59
#endif
60

61
#if defined(BOTAN_HAS_TLS_CBC)
62
   #include <botan/block_cipher.h>
63
   #include <botan/mac.h>
64
   #include <botan/tls_exceptn.h>
65
   #include <botan/tls_version.h>
66
   #include <botan/internal/tls_cbc.h>
67
#endif
68

69
#if defined(BOTAN_HAS_ECDSA)
70
   #include <botan/ecdsa.h>
71
#endif
72

73
#if defined(BOTAN_HAS_SYSTEM_RNG)
74
   #include <botan/system_rng.h>
75
#endif
76

77
#if defined(BOTAN_HAS_CHACHA_RNG)
78
   #include <botan/chacha_rng.h>
79
#endif
80

81
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
82
   #include <signal.h>
83
   #include <stdlib.h>
84
#endif
85

86
namespace Botan_CLI {
87

88
namespace {
89

90
class TimingTestTimer {
91
   public:
92
      TimingTestTimer() : m_start(get_high_resolution_clock()) {}
641✔
93

94
      uint64_t complete() const { return get_high_resolution_clock() - m_start; }
1,282✔
95

96
   private:
97
      static uint64_t get_high_resolution_clock() {
1,282✔
98
         // TODO use cpu clock where possible/relevant incl serializing instructions
99
         auto now = std::chrono::high_resolution_clock::now().time_since_epoch();
1,206✔
100
         return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
1,282✔
101
      }
102

103
      uint64_t m_start;
104
};
105

106
class Timing_Test {
107
   public:
108
      Timing_Test() {
10✔
109
         /*
110
         A constant seed is ok here since the timing test rng just needs to be
111
         "random" but not cryptographically secure - even std::rand() would be ok.
112
         */
113
         const std::string drbg_seed(64, 'A');
10✔
114
         m_rng = cli_make_rng("", drbg_seed);  // throws if it can't find anything to use
10✔
115
      }
10✔
116

117
      virtual ~Timing_Test() = default;
×
118

119
      Timing_Test(const Timing_Test& other) = delete;
120
      Timing_Test(Timing_Test&& other) = delete;
121
      Timing_Test& operator=(const Timing_Test& other) = delete;
122
      Timing_Test& operator=(Timing_Test&& other) = delete;
123

124
      std::vector<std::vector<uint64_t>> execute_evaluation(const std::vector<std::string>& inputs,
125
                                                            size_t warmup_runs,
126
                                                            size_t measurement_runs);
127

128
      virtual std::vector<uint8_t> prepare_input(const std::string& input) { return Botan::hex_decode(input); }
9✔
129

130
      virtual uint64_t measure_critical_function(const std::vector<uint8_t>& input) = 0;
131

132
   protected:
133
      Botan::RandomNumberGenerator& timing_test_rng() { return (*m_rng); }
2✔
134

135
   private:
136
      std::shared_ptr<Botan::RandomNumberGenerator> m_rng;
137
};
138

139
#if defined(BOTAN_HAS_RSA) && defined(BOTAN_HAS_EME_PKCS1) && defined(BOTAN_HAS_EME_RAW)
140

141
class Bleichenbacker_Timing_Test final : public Timing_Test {
×
142
   public:
143
      explicit Bleichenbacker_Timing_Test(size_t keysize) :
1✔
144
            m_privkey(timing_test_rng(), keysize),
1✔
145
            m_pubkey(m_privkey.public_key()),
1✔
146
            m_enc(*m_pubkey, timing_test_rng(), "Raw"),
1✔
147
            m_dec(m_privkey, timing_test_rng(), "PKCS1v15") {}
2✔
148

149
      std::vector<uint8_t> prepare_input(const std::string& input) override {
4✔
150
         const std::vector<uint8_t> input_vector = Botan::hex_decode(input);
4✔
151
         return m_enc.encrypt(input_vector, timing_test_rng());
4✔
152
      }
4✔
153

154
      uint64_t measure_critical_function(const std::vector<uint8_t>& input) override {
76✔
155
         const TimingTestTimer timer;
76✔
156
         m_dec.decrypt_or_random(input.data(), m_ctext_length, m_expected_content_size, timing_test_rng());
76✔
157
         return timer.complete();
76✔
158
      }
159

160
   private:
161
      const size_t m_expected_content_size = 48;
162
      const size_t m_ctext_length = 256;
163
      Botan::RSA_PrivateKey m_privkey;
164
      std::unique_ptr<Botan::Public_Key> m_pubkey;
165
      Botan::PK_Encryptor_EME m_enc;
166
      Botan::PK_Decryptor_EME m_dec;
167
};
168

169
#endif
170

171
#if defined(BOTAN_HAS_RSA) && defined(BOTAN_HAS_EME_OAEP) && defined(BOTAN_HAS_EME_RAW)
172

173
/*
174
* Test Manger OAEP side channel
175
*
176
* "A Chosen Ciphertext Attack on RSA Optimal Asymmetric Encryption
177
* Padding (OAEP) as Standardized in PKCS #1 v2.0" James Manger
178
* http://archiv.infsec.ethz.ch/education/fs08/secsem/Manger01.pdf
179
*/
180
class Manger_Timing_Test final : public Timing_Test {
×
181
   public:
182
      explicit Manger_Timing_Test(size_t keysize) :
1✔
183
            m_privkey(timing_test_rng(), keysize),
1✔
184
            m_pubkey(m_privkey.public_key()),
1✔
185
            m_enc(*m_pubkey, timing_test_rng(), m_encrypt_padding),
1✔
186
            m_dec(m_privkey, timing_test_rng(), m_decrypt_padding) {}
2✔
187

188
      std::vector<uint8_t> prepare_input(const std::string& input) override {
2✔
189
         const std::vector<uint8_t> input_vector = Botan::hex_decode(input);
2✔
190
         return m_enc.encrypt(input_vector, timing_test_rng());
2✔
191
      }
2✔
192

193
      uint64_t measure_critical_function(const std::vector<uint8_t>& input) override {
38✔
194
         const TimingTestTimer timer;
38✔
195
         try {
38✔
196
            m_dec.decrypt(input.data(), m_ctext_length);
38✔
197
         } catch(Botan::Decoding_Error&) {}
38✔
198
         return timer.complete();
38✔
199
      }
200

201
   private:
202
      const std::string m_encrypt_padding = "Raw";
203
      const std::string m_decrypt_padding = "EME1(SHA-256)";
204
      const size_t m_ctext_length = 256;
205
      Botan::RSA_PrivateKey m_privkey;
206
      std::unique_ptr<Botan::Public_Key> m_pubkey;
207
      Botan::PK_Encryptor_EME m_enc;
208
      Botan::PK_Decryptor_EME m_dec;
209
};
210

211
#endif
212

213
#if defined(BOTAN_HAS_TLS_CBC)
214

215
/*
216
* Test handling of countermeasure to the Lucky13 attack
217
*/
218
class Lucky13_Timing_Test final : public Timing_Test {
×
219
   public:
220
      Lucky13_Timing_Test(const std::string& mac_name, size_t mac_keylen) :
4✔
221
            m_mac_algo(mac_name),
8✔
222
            m_mac_keylen(mac_keylen),
4✔
223
            m_dec(Botan::BlockCipher::create_or_throw("AES-128"),
12✔
224
                  Botan::MessageAuthenticationCode::create_or_throw("HMAC(" + m_mac_algo + ")"),
12✔
225
                  16,
226
                  m_mac_keylen,
4✔
227
                  Botan::TLS::Protocol_Version::TLS_V12,
228
                  false) {}
8✔
229

230
      std::vector<uint8_t> prepare_input(const std::string& input) override;
231
      uint64_t measure_critical_function(const std::vector<uint8_t>& input) override;
232

233
   private:
234
      const std::string m_mac_algo;
235
      const size_t m_mac_keylen;
236
      Botan::TLS::TLS_CBC_HMAC_AEAD_Decryption m_dec;
237
};
238

239
std::vector<uint8_t> Lucky13_Timing_Test::prepare_input(const std::string& input) {
12✔
240
   const std::vector<uint8_t> input_vector = Botan::hex_decode(input);
12✔
241
   const std::vector<uint8_t> key(16);
12✔
242
   const std::vector<uint8_t> iv(16);
12✔
243

244
   auto enc = Botan::Cipher_Mode::create("AES-128/CBC/NoPadding", Botan::Cipher_Dir::Encryption);
12✔
245
   enc->set_key(key);
12✔
246
   enc->start(iv);
12✔
247
   Botan::secure_vector<uint8_t> buf(input_vector.begin(), input_vector.end());
12✔
248
   enc->finish(buf);
12✔
249

250
   return unlock(buf);
12✔
251
}
60✔
252

253
uint64_t Lucky13_Timing_Test::measure_critical_function(const std::vector<uint8_t>& input) {
228✔
254
   Botan::secure_vector<uint8_t> data(input.begin(), input.end());
228✔
255
   Botan::secure_vector<uint8_t> aad(13);
228✔
256
   const Botan::secure_vector<uint8_t> iv(16);
228✔
257
   const Botan::secure_vector<uint8_t> key(16 + m_mac_keylen);
228✔
258

259
   m_dec.set_key(unlock(key));
228✔
260
   m_dec.set_associated_data(aad);
228✔
261
   m_dec.start(unlock(iv));
228✔
262

263
   const TimingTestTimer timer;
228✔
264
   try {
228✔
265
      m_dec.finish(data);
228✔
266
   } catch(Botan::TLS::TLS_Exception&) {}
228✔
267
   return timer.complete();
228✔
268
}
912✔
269

270
#endif
271

272
#if defined(BOTAN_HAS_ECDSA)
273

274
class ECDSA_Timing_Test final : public Timing_Test {
×
275
   public:
276
      explicit ECDSA_Timing_Test(const std::string& ecgroup);
277

278
      uint64_t measure_critical_function(const std::vector<uint8_t>& input) override;
279

280
   private:
281
      const Botan::EC_Group m_group;
282
      const Botan::ECDSA_PrivateKey m_privkey;
283
      const Botan::EC_Scalar m_x;
284
      Botan::EC_Scalar m_b;
285
      Botan::EC_Scalar m_b_inv;
286
};
287

288
ECDSA_Timing_Test::ECDSA_Timing_Test(const std::string& ecgroup) :
1✔
289
      m_group(Botan::EC_Group::from_name(ecgroup)),
1✔
290
      m_privkey(timing_test_rng(), m_group),
1✔
291
      m_x(m_privkey._private_key()),
1✔
292
      m_b(Botan::EC_Scalar::random(m_group, timing_test_rng())),
1✔
293
      m_b_inv(m_b.invert()) {}
2✔
294

295
uint64_t ECDSA_Timing_Test::measure_critical_function(const std::vector<uint8_t>& input) {
38✔
296
   const auto k = Botan::EC_Scalar::from_bytes_with_trunc(m_group, input);
38✔
297
   // fixed message to minimize noise
298
   const auto m = Botan::EC_Scalar::from_bytes_with_trunc(m_group, std::vector<uint8_t>{5});
38✔
299

300
   const TimingTestTimer timer;
38✔
301

302
   // the following ECDSA operations involve and should not leak any information about k
303
   const auto r = Botan::EC_Scalar::gk_x_mod_order(k, timing_test_rng());
38✔
304
   const auto k_inv = k.invert();
38✔
305
   m_b.square_self();
38✔
306
   m_b_inv.square_self();
38✔
307
   const auto xr_m = ((m_x * m_b) * r) + (m * m_b);
38✔
308
   const auto s = (k_inv * xr_m) * m_b_inv;
38✔
309
   BOTAN_UNUSED(r, s);
38✔
310

311
   return timer.complete();
76✔
312
}
38✔
313

314
#endif
315

316
#if defined(BOTAN_HAS_ECC_GROUP)
317

318
class ECC_Mul_Timing_Test final : public Timing_Test {
×
319
   public:
320
      explicit ECC_Mul_Timing_Test(std::string_view ecgroup) : m_group(Botan::EC_Group::from_name(ecgroup)) {}
1✔
321

322
      uint64_t measure_critical_function(const std::vector<uint8_t>& input) override;
323

324
   private:
325
      const Botan::EC_Group m_group;
326
};
327

328
uint64_t ECC_Mul_Timing_Test::measure_critical_function(const std::vector<uint8_t>& input) {
38✔
329
   const auto k = Botan::EC_Scalar::from_bytes_with_trunc(m_group, input);
38✔
330

331
   const TimingTestTimer timer;
38✔
332
   const auto kG = Botan::EC_AffinePoint::g_mul(k, timing_test_rng());
38✔
333
   return timer.complete();
76✔
334
}
38✔
335

336
#endif
337

338
#if defined(BOTAN_HAS_DL_GROUP)
339

340
class Powmod_Timing_Test final : public Timing_Test {
×
341
   public:
342
      explicit Powmod_Timing_Test(std::string_view dl_group) : m_group(Botan::DL_Group::from_name(dl_group)) {}
1✔
343

344
      uint64_t measure_critical_function(const std::vector<uint8_t>& input) override;
345

346
   private:
347
      Botan::DL_Group m_group;
348
};
349

350
uint64_t Powmod_Timing_Test::measure_critical_function(const std::vector<uint8_t>& input) {
57✔
351
   const Botan::BigInt x(input.data(), input.size());
57✔
352
   const size_t max_x_bits = m_group.p_bits();
57✔
353

354
   const TimingTestTimer timer;
57✔
355

356
   const Botan::BigInt g_x_p = m_group.power_g_p(x, max_x_bits);
57✔
357

358
   return timer.complete();
114✔
359
}
57✔
360

361
#endif
362

363
#if defined(BOTAN_HAS_NUMBERTHEORY)
364

365
class Invmod_Timing_Test final : public Timing_Test {
×
366
   public:
367
      explicit Invmod_Timing_Test(size_t p_bits) { m_p = Botan::random_prime(timing_test_rng(), p_bits); }
2✔
368

369
      uint64_t measure_critical_function(const std::vector<uint8_t>& input) override;
370

371
   private:
372
      Botan::BigInt m_p;
373
};
374

375
uint64_t Invmod_Timing_Test::measure_critical_function(const std::vector<uint8_t>& input) {
38✔
376
   const Botan::BigInt k(input.data(), input.size());
38✔
377

378
   const TimingTestTimer timer;
38✔
379
   const Botan::BigInt inv = Botan::inverse_mod_secret_prime(k, m_p);
38✔
380
   return timer.complete();
76✔
381
}
38✔
382

383
#endif
384

385
std::vector<std::vector<uint64_t>> Timing_Test::execute_evaluation(const std::vector<std::string>& raw_inputs,
10✔
386
                                                                   size_t warmup_runs,
387
                                                                   size_t measurement_runs) {
388
   std::vector<std::vector<uint64_t>> all_results(raw_inputs.size());
10✔
389
   std::vector<std::vector<uint8_t>> inputs(raw_inputs.size());
10✔
390

391
   for(auto& result : all_results) {
37✔
392
      result.reserve(measurement_runs);
27✔
393
   }
394

395
   for(size_t i = 0; i != inputs.size(); ++i) {
37✔
396
      inputs[i] = prepare_input(raw_inputs[i]);
27✔
397
   }
398

399
   // arbitrary upper bounds of 1 and 10 million resp
400
   if(warmup_runs > 1000000 || measurement_runs > 100000000) {
10✔
401
      throw CLI_Error("Requested execution counts too large, rejecting");
×
402
   }
403

404
   size_t total_runs = 0;
10✔
405
   std::vector<uint64_t> results(inputs.size());
10✔
406

407
   while(total_runs < (warmup_runs + measurement_runs)) {
200✔
408
      for(size_t i = 0; i != inputs.size(); ++i) {
703✔
409
         results[i] = measure_critical_function(inputs[i]);
513✔
410
      }
411

412
      total_runs++;
190✔
413

414
      if(total_runs > warmup_runs) {
190✔
415
         for(size_t i = 0; i != results.size(); ++i) {
592✔
416
            all_results[i].push_back(results[i]);
432✔
417
         }
418
      }
419
   }
420

421
   return all_results;
10✔
422
}
10✔
423

424
class Timing_Test_Command final : public Command {
425
   public:
426
      Timing_Test_Command() :
11✔
427
            Command(
428
               "timing_test test_type --test-data-file= --test-data-dir=src/tests/data/timing "
429
               "--warmup-runs=5000 --measurement-runs=50000") {}
22✔
430

431
      std::string group() const override { return "testing"; }
1✔
432

433
      std::string description() const override { return "Run various timing side channel tests"; }
1✔
434

435
      void go() override {
10✔
436
         const std::string test_type = get_arg("test_type");
10✔
437
         const size_t warmup_runs = get_arg_sz("warmup-runs");
10✔
438
         const size_t measurement_runs = get_arg_sz("measurement-runs");
10✔
439

440
         std::unique_ptr<Timing_Test> test = lookup_timing_test(test_type);
10✔
441

442
         if(!test) {
10✔
443
            throw CLI_Error("Unknown or unavailable test type '" + test_type + "'");
×
444
         }
445

446
         std::string filename = get_arg_or("test-data-file", "");
20✔
447

448
         if(filename.empty()) {
10✔
449
            const std::string test_data_dir = get_arg("test-data-dir");
10✔
450
            filename = test_data_dir + "/" + test_type + ".vec";
20✔
451
         }
10✔
452

453
         const std::vector<std::string> lines = read_testdata(filename);
10✔
454

455
         std::vector<std::vector<uint64_t>> results = test->execute_evaluation(lines, warmup_runs, measurement_runs);
10✔
456

457
         size_t unique_id = 0;
10✔
458
         std::ostringstream oss;
10✔
459
         for(size_t secret_id = 0; secret_id != results.size(); ++secret_id) {
37✔
460
            for(size_t i = 0; i != results[secret_id].size(); ++i) {
459✔
461
               oss << unique_id++ << ";" << secret_id << ";" << results[secret_id][i] << "\n";
432✔
462
            }
463
         }
464

465
         output() << oss.str();
10✔
466
      }
20✔
467

468
   private:
469
      static std::vector<std::string> read_testdata(const std::string& filename) {
10✔
470
         std::vector<std::string> lines;
10✔
471
         std::ifstream infile(filename);
10✔
472
         if(!infile.good()) {
10✔
473
            throw CLI_Error("Error reading test data from '" + filename + "'");
×
474
         }
475
         std::string line;
10✔
476
         while(std::getline(infile, line)) {
70✔
477
            if(!line.empty() && line.at(0) != '#') {
60✔
478
               lines.push_back(line);
27✔
479
            }
480
         }
481
         return lines;
20✔
482
      }
10✔
483

484
      static std::unique_ptr<Timing_Test> lookup_timing_test(std::string_view test_type);
485

486
      std::string help_text() const override {
×
487
         // TODO check feature macros
488
         return (Command::help_text() +
×
489
                 "\ntest_type can take on values "
490
                 "bleichenbacher "
491
                 "manger "
492
                 "ecdsa "
493
                 "ecc_mul "
494
                 "inverse_mod "
495
                 "pow_mod "
496
                 "lucky13sec3 "
497
                 "lucky13sec4sha1 "
498
                 "lucky13sec4sha256 "
499
                 "lucky13sec4sha384 ");
×
500
      }
501
};
502

503
std::unique_ptr<Timing_Test> Timing_Test_Command::lookup_timing_test(std::string_view test_type) {
10✔
504
#if defined(BOTAN_HAS_RSA) && defined(BOTAN_HAS_EME_PKCS1) && defined(BOTAN_HAS_EME_RAW)
505
   if(test_type == "bleichenbacher") {
10✔
506
      return std::make_unique<Bleichenbacker_Timing_Test>(2048);
1✔
507
   }
508
#endif
509

510
#if defined(BOTAN_HAS_RSA) && defined(BOTAN_HAS_EME_OAEP) && defined(BOTAN_HAS_EME_RAW)
511
   if(test_type == "manger") {
9✔
512
      return std::make_unique<Manger_Timing_Test>(2048);
1✔
513
   }
514
#endif
515

516
#if defined(BOTAN_HAS_ECDSA)
517
   if(test_type == "ecdsa") {
8✔
518
      return std::make_unique<ECDSA_Timing_Test>("secp384r1");
1✔
519
   }
520
#endif
521

522
#if defined(BOTAN_HAS_ECC_GROUP)
523
   if(test_type == "ecc_mul") {
7✔
524
      return std::make_unique<ECC_Mul_Timing_Test>("brainpool512r1");
1✔
525
   }
526
#endif
527

528
#if defined(BOTAN_HAS_NUMBERTHEORY)
529
   if(test_type == "inverse_mod") {
6✔
530
      return std::make_unique<Invmod_Timing_Test>(512);
1✔
531
   }
532
#endif
533

534
#if defined(BOTAN_HAS_DL_GROUP)
535
   if(test_type == "pow_mod") {
5✔
536
      return std::make_unique<Powmod_Timing_Test>("modp/ietf/1024");
1✔
537
   }
538
#endif
539

540
#if defined(BOTAN_HAS_TLS_CBC)
541
   if(test_type == "lucky13sec3" || test_type == "lucky13sec4sha1") {
6✔
542
      return std::make_unique<Lucky13_Timing_Test>("SHA-1", 20);
2✔
543
   }
544
   if(test_type == "lucky13sec4sha256") {
2✔
545
      return std::make_unique<Lucky13_Timing_Test>("SHA-256", 32);
1✔
546
   }
547
   if(test_type == "lucky13sec4sha384") {
1✔
548
      return std::make_unique<Lucky13_Timing_Test>("SHA-384", 48);
1✔
549
   }
550
#endif
551

552
   BOTAN_UNUSED(test_type);
×
553

554
   return nullptr;
×
555
}
556

557
BOTAN_REGISTER_COMMAND("timing_test", Timing_Test_Command);
11✔
558

559
#if defined(BOTAN_HAS_RSA) && defined(BOTAN_HAS_EME_PKCS1) && defined(BOTAN_TARGET_OS_HAS_FILESYSTEM) && \
560
   defined(BOTAN_HAS_SYSTEM_RNG)
561

562
class MARVIN_Test_Command final : public Command {
563
   public:
564
      MARVIN_Test_Command() :
2✔
565
            Command("marvin_test key_file ctext_dir --runs=1K --report-every=0 --output-nsec --expect-pt-len=0") {}
4✔
566

567
      std::string group() const override { return "testing"; }
1✔
568

569
      std::string description() const override { return "Run a test for MARVIN attack"; }
1✔
570

571
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1)
572
      static inline volatile sig_atomic_t g_sigint_recv = 0;
573

574
      static void marvin_sigint_handler(int /*signal*/) { g_sigint_recv = 1; }
×
575
   #endif
576

577
      void go() override {
1✔
578
         const std::string key_file = get_arg("key_file");
1✔
579
         const std::string ctext_dir = get_arg("ctext_dir");
1✔
580
         const size_t measurement_runs = parse_runs_arg(get_arg("runs"));
1✔
581
         const size_t expect_pt_len = get_arg_sz("expect-pt-len");
1✔
582
         const size_t report_every = get_arg_sz("report-every");
1✔
583
         const bool output_nsec = flag_set("output-nsec");
1✔
584

585
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1)
586
         ::setenv("BOTAN_THREAD_POOL_SIZE", "none", /*overwrite?*/ 1);
1✔
587

588
         struct sigaction sigaction {};
1✔
589

590
         sigaction.sa_handler = marvin_sigint_handler;
1✔
591
         sigemptyset(&sigaction.sa_mask);
1✔
592
         sigaction.sa_flags = 0;
1✔
593

594
         const int rc = ::sigaction(SIGINT, &sigaction, nullptr);
1✔
595
         if(rc != 0) {
1✔
596
            throw CLI_Error("Failed to set SIGINT handler");
×
597
         }
598
   #endif
599

600
         Botan::DataSource_Stream key_src(key_file);
1✔
601
         const auto key = Botan::PKCS8::load_key(key_src);
1✔
602

603
         if(key->algo_name() != "RSA") {
1✔
604
            throw CLI_Usage_Error("Unexpected key type for MARVIN test");
×
605
         }
606

607
         const size_t modulus_bytes = (key->key_length() + 7) / 8;
1✔
608

609
         std::vector<std::string> names;
1✔
610
         std::vector<uint8_t> ciphertext_data;
1✔
611

612
         for(const auto& filename : Botan::get_files_recursive(ctext_dir)) {
5✔
613
            const auto contents = this->slurp_file(filename);
4✔
614

615
            if(contents.size() != modulus_bytes) {
4✔
616
               throw CLI_Usage_Error(
×
617
                  Botan::fmt("The ciphertext file {} had different size ({}) than the RSA modulus ({})",
×
618
                             filename,
619
                             contents.size(),
×
620
                             modulus_bytes));
×
621
            }
622

623
            const auto parts = Botan::split_on(filename, '/');
4✔
624

625
            names.push_back(parts[parts.size() - 1]);
4✔
626
            ciphertext_data.insert(ciphertext_data.end(), contents.begin(), contents.end());
4✔
627
         }
9✔
628

629
         if(names.empty()) {
1✔
630
            throw CLI_Usage_Error("Empty ciphertext directory for MARVIN test");
×
631
         }
632

633
         auto& test_results_file = output();
1✔
634

635
         const size_t testcases = names.size();
1✔
636

637
   #if defined(BOTAN_HAS_CHACHA_RNG)
638
         auto rng = Botan::ChaCha_RNG(Botan::system_rng());
1✔
639
   #else
640
         auto& rng = Botan::system_rng();
641
   #endif
642

643
         const Botan::PK_Decryptor_EME op(*key, rng, "PKCS1v15");
1✔
644

645
         std::vector<size_t> indexes;
1✔
646
         for(size_t i = 0; i != testcases; ++i) {
5✔
647
            indexes.push_back(i);
4✔
648
         }
649

650
         std::vector<std::vector<uint64_t>> measurements(testcases);
1✔
651
         for(auto& m : measurements) {
5✔
652
            m.reserve(measurement_runs);
4✔
653
         }
654

655
         // This is only set differently if we exit early from the loop
656
         size_t runs_completed = measurement_runs;
1✔
657

658
         std::vector<uint8_t> ciphertext(modulus_bytes);
1✔
659

660
         for(size_t r = 0; r != measurement_runs; ++r) {
33✔
661
            if(r > 0 && report_every > 0 && (r % report_every) == 0) {
32✔
662
               std::cerr << "Gathering sample # " << r << "\n";
×
663
            }
664

665
            shuffle(indexes, rng);
32✔
666

667
            for(const size_t testcase : indexes) {
160✔
668
               // Load the test ciphertext in constant time to avoid cache pollution
669
               for(size_t j = 0; j != testcases; ++j) {
640✔
670
                  const auto j_eq_testcase = Botan::CT::Mask<size_t>::is_equal(j, testcase).as_choice();
512✔
671
                  const auto* testcase_j = &ciphertext_data[j * modulus_bytes];
512✔
672
                  Botan::CT::conditional_assign_mem(j_eq_testcase, ciphertext.data(), testcase_j, modulus_bytes);
1,024✔
673
               }
674

675
               const TimingTestTimer timer;
128✔
676
               op.decrypt_or_random(ciphertext.data(), modulus_bytes, expect_pt_len, rng);
128✔
677
               const uint64_t duration = timer.complete();
128✔
678
               BOTAN_ASSERT_NOMSG(measurements[testcase].size() == r);
128✔
679
               measurements[testcase].push_back(duration);
128✔
680
            }
681

682
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1)
683
            // Early exit check
684
            if(g_sigint_recv != 0) {
32✔
685
               std::cerr << "Exiting early after " << r << " measurements\n";
×
686
               runs_completed = r;
687
               break;
688
            }
689
   #endif
690
         }
691

692
         report_results(test_results_file, names, measurements, runs_completed, output_nsec);
1✔
693
      }
3✔
694

695
   private:
696
      static void report_results(std::ostream& output,
1✔
697
                                 std::span<const std::string> names,
698
                                 std::span<const std::vector<uint64_t>> measurements,
699
                                 size_t runs_completed,
700
                                 bool output_nsec) {
701
         for(size_t t = 0; t != names.size(); ++t) {
5✔
702
            if(t > 0) {
4✔
703
               output << ",";
3✔
704
            }
705
            output << names[t];
4✔
706
         }
707
         output << "\n";
1✔
708

709
         for(size_t r = 0; r != runs_completed; ++r) {
33✔
710
            for(size_t t = 0; t != names.size(); ++t) {
160✔
711
               if(t > 0) {
128✔
712
                  output << ",";
96✔
713
               }
714

715
               const uint64_t dur_nsec = measurements[t][r];
128✔
716
               if(output_nsec) {
128✔
717
                  output << dur_nsec;
×
718
               } else {
719
                  const double dur_s = static_cast<double>(dur_nsec) / 1000000000.0;
128✔
720
                  output << dur_s;
128✔
721
               }
722
            }
723
            output << "\n";
32✔
724
         }
725
      }
1✔
726

727
      static size_t parse_runs_arg(const std::string& param) {
1✔
728
         if(param.starts_with("-")) {
1✔
729
            throw CLI_Usage_Error("Cannot have a negative run count");
×
730
         }
731

732
         if(param.ends_with("m") || param.ends_with("M")) {
1✔
733
            return parse_runs_arg(param.substr(0, param.size() - 1)) * 1'000'000;
×
734
         } else if(param.ends_with("k") || param.ends_with("K")) {
1✔
735
            return parse_runs_arg(param.substr(0, param.size() - 1)) * 1'000;
×
736
         } else {
737
            try {
1✔
738
               return static_cast<size_t>(std::stoul(param));
1✔
739
            } catch(std::exception&) {
×
740
               throw CLI_Usage_Error("Unexpected syntax for --runs option (try 1000, 1K, or 2M)");
×
741
            }
×
742
         }
743
      }
744

745
      template <typename T>
746
      void shuffle(std::vector<T>& vec, Botan::RandomNumberGenerator& rng) {
32✔
747
         const size_t n = vec.size();
32✔
748
         for(size_t i = 0; i != n; ++i) {
160✔
749
            uint8_t jb[sizeof(uint64_t)];
750
            rng.randomize(jb, sizeof(jb));
128✔
751
            const uint64_t j8 = Botan::load_le<uint64_t>(jb, 0);
128✔
752
            const size_t j = i + static_cast<size_t>(j8) % (n - i);
128✔
753
            std::swap(vec[i], vec[j]);
128✔
754
         }
755
      }
32✔
756
};
757

758
BOTAN_REGISTER_COMMAND("marvin_test", MARVIN_Test_Command);
2✔
759

760
#endif
761

762
}  // namespace
763

764
}  // namespace Botan_CLI
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