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

randombit / botan / 16247597625

13 Jul 2025 09:19AM UTC coverage: 90.574% (-0.001%) from 90.575%
16247597625

push

github

web-flow
Merge pull request #4974 from randombit/jack/fix-clang-tidy-modernize-loop-convert

Enable and fix clang-tidy warning modernize-loop-convert

99094 of 109407 relevant lines covered (90.57%)

12407263.12 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/tls_exceptn.h>
63
   #include <botan/internal/tls_cbc.h>
64
#endif
65

66
#if defined(BOTAN_HAS_ECDSA)
67
   #include <botan/ecdsa.h>
68
#endif
69

70
#if defined(BOTAN_HAS_SYSTEM_RNG)
71
   #include <botan/system_rng.h>
72
#endif
73

74
#if defined(BOTAN_HAS_CHACHA_RNG)
75
   #include <botan/chacha_rng.h>
76
#endif
77

78
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
79
   #include <signal.h>
80
   #include <stdlib.h>
81
#endif
82

83
namespace Botan_CLI {
84

85
namespace {
86

87
class TimingTestTimer {
88
   public:
89
      TimingTestTimer() { m_start = get_high_resolution_clock(); }
1,282✔
90

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

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

100
      uint64_t m_start;
101
};
102

103
}  // namespace
104

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

116
      virtual ~Timing_Test() = default;
×
117

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

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

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

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

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

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

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

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

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

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

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

168
#endif
169

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

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

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

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

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

210
#endif
211

212
#if defined(BOTAN_HAS_TLS_CBC)
213

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

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

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

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

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

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

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

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

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

269
#endif
270

271
#if defined(BOTAN_HAS_ECDSA)
272

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

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

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

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

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

299
   TimingTestTimer timer;
38✔
300

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

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

313
#endif
314

315
#if defined(BOTAN_HAS_ECC_GROUP)
316

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

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

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

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

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

335
#endif
336

337
#if defined(BOTAN_HAS_DL_GROUP)
338

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

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

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

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

353
   TimingTestTimer timer;
57✔
354

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

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

360
#endif
361

362
#if defined(BOTAN_HAS_NUMBERTHEORY)
363

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

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

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

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

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

382
#endif
383

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

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

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

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

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

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

411
      total_runs++;
190✔
412

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

420
   return all_results;
10✔
421
}
10✔
422

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

551
   BOTAN_UNUSED(test_type);
×
552

553
   return nullptr;
×
554
}
555

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

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

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

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

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

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

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

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

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

587
         struct sigaction sigaction {};
1✔
588

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

664
            shuffle(indexes, rng);
32✔
665

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

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

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

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

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

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

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

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

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

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

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

759
#endif
760

761
}  // 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