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

randombit / botan / 12869303872

20 Jan 2025 01:40PM UTC coverage: 91.213% (+0.01%) from 91.202%
12869303872

push

github

web-flow
Merge pull request #4569 from randombit/jack/mod-inv-distinguish-cases

When computing modular inverses distingush which case we are in

93546 of 102558 relevant lines covered (91.21%)

11542300.02 hits per line

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

91.61
/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/filesystem.h>
25
#include <botan/internal/fmt.h>
26
#include <botan/internal/loadstor.h>
27
#include <botan/internal/parsing.h>
28
#include <chrono>
29
#include <fstream>
30
#include <sstream>
31

32
#if defined(BOTAN_HAS_BIGINT)
33
   #include <botan/bigint.h>
34
#endif
35

36
#if defined(BOTAN_HAS_NUMBERTHEORY)
37
   #include <botan/numthry.h>
38
   #include <botan/internal/mod_inv.h>
39
#endif
40

41
#if defined(BOTAN_HAS_ECC_GROUP)
42
   #include <botan/ec_group.h>
43
#endif
44

45
#if defined(BOTAN_HAS_DL_GROUP)
46
   #include <botan/dl_group.h>
47
#endif
48

49
#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)
50
   #include <botan/pkcs8.h>
51
   #include <botan/pubkey.h>
52
#endif
53

54
#if defined(BOTAN_HAS_RSA)
55
   #include <botan/rsa.h>
56
#endif
57

58
#if defined(BOTAN_HAS_TLS_CBC)
59
   #include <botan/tls_exceptn.h>
60
   #include <botan/internal/tls_cbc.h>
61
#endif
62

63
#if defined(BOTAN_HAS_ECDSA)
64
   #include <botan/ecdsa.h>
65
#endif
66

67
namespace Botan_CLI {
68

69
namespace {
70

71
class TimingTestTimer {
72
   public:
73
      TimingTestTimer() { m_start = get_high_resolution_clock(); }
1,282✔
74

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

77
   private:
78
      static uint64_t get_high_resolution_clock() {
1,282✔
79
         // TODO use cpu clock where possible/relevant incl serializing instructions
80
         auto now = std::chrono::high_resolution_clock::now().time_since_epoch();
1,206✔
81
         return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
1,282✔
82
      }
83

84
      uint64_t m_start;
85
};
86

87
}  // namespace
88

89
class Timing_Test {
90
   public:
91
      Timing_Test() {
10✔
92
         /*
93
         A constant seed is ok here since the timing test rng just needs to be
94
         "random" but not cryptographically secure - even std::rand() would be ok.
95
         */
96
         const std::string drbg_seed(64, 'A');
10✔
97
         m_rng = cli_make_rng("", drbg_seed);  // throws if it can't find anything to use
10✔
98
      }
10✔
99

100
      virtual ~Timing_Test() = default;
×
101

102
      Timing_Test(const Timing_Test& other) = delete;
103
      Timing_Test(Timing_Test&& other) = delete;
104
      Timing_Test& operator=(const Timing_Test& other) = delete;
105
      Timing_Test& operator=(Timing_Test&& other) = delete;
106

107
      std::vector<std::vector<uint64_t>> execute_evaluation(const std::vector<std::string>& inputs,
108
                                                            size_t warmup_runs,
109
                                                            size_t measurement_runs);
110

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

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

115
   protected:
116
      Botan::RandomNumberGenerator& timing_test_rng() { return (*m_rng); }
2✔
117

118
   private:
119
      std::shared_ptr<Botan::RandomNumberGenerator> m_rng;
120
};
121

122
#if defined(BOTAN_HAS_RSA) && defined(BOTAN_HAS_EME_PKCS1) && defined(BOTAN_HAS_EME_RAW)
123

124
class Bleichenbacker_Timing_Test final : public Timing_Test {
×
125
   public:
126
      explicit Bleichenbacker_Timing_Test(size_t keysize) :
1✔
127
            m_privkey(timing_test_rng(), keysize),
1✔
128
            m_pubkey(m_privkey),
1✔
129
            m_enc(m_pubkey, timing_test_rng(), "Raw"),
1✔
130
            m_dec(m_privkey, timing_test_rng(), "PKCS1v15") {}
2✔
131

132
      std::vector<uint8_t> prepare_input(const std::string& input) override {
4✔
133
         const std::vector<uint8_t> input_vector = Botan::hex_decode(input);
4✔
134
         return m_enc.encrypt(input_vector, timing_test_rng());
4✔
135
      }
4✔
136

137
      uint64_t measure_critical_function(const std::vector<uint8_t>& input) override {
76✔
138
         TimingTestTimer timer;
76✔
139
         m_dec.decrypt_or_random(input.data(), m_ctext_length, m_expected_content_size, timing_test_rng());
76✔
140
         return timer.complete();
76✔
141
      }
142

143
   private:
144
      const size_t m_expected_content_size = 48;
145
      const size_t m_ctext_length = 256;
146
      Botan::RSA_PrivateKey m_privkey;
147
      Botan::RSA_PublicKey m_pubkey;
148
      Botan::PK_Encryptor_EME m_enc;
149
      Botan::PK_Decryptor_EME m_dec;
150
};
151

152
#endif
153

154
#if defined(BOTAN_HAS_RSA) && defined(BOTAN_HAS_EME_OAEP) && defined(BOTAN_HAS_EME_RAW)
155

156
/*
157
* Test Manger OAEP side channel
158
*
159
* "A Chosen Ciphertext Attack on RSA Optimal Asymmetric Encryption
160
* Padding (OAEP) as Standardized in PKCS #1 v2.0" James Manger
161
* http://archiv.infsec.ethz.ch/education/fs08/secsem/Manger01.pdf
162
*/
163
class Manger_Timing_Test final : public Timing_Test {
×
164
   public:
165
      explicit Manger_Timing_Test(size_t keysize) :
1✔
166
            m_privkey(timing_test_rng(), keysize),
1✔
167
            m_pubkey(m_privkey),
1✔
168
            m_enc(m_pubkey, timing_test_rng(), m_encrypt_padding),
1✔
169
            m_dec(m_privkey, timing_test_rng(), m_decrypt_padding) {}
2✔
170

171
      std::vector<uint8_t> prepare_input(const std::string& input) override {
2✔
172
         const std::vector<uint8_t> input_vector = Botan::hex_decode(input);
2✔
173
         return m_enc.encrypt(input_vector, timing_test_rng());
2✔
174
      }
2✔
175

176
      uint64_t measure_critical_function(const std::vector<uint8_t>& input) override {
38✔
177
         TimingTestTimer timer;
38✔
178
         try {
38✔
179
            m_dec.decrypt(input.data(), m_ctext_length);
38✔
180
         } catch(Botan::Decoding_Error&) {}
38✔
181
         return timer.complete();
38✔
182
      }
183

184
   private:
185
      const std::string m_encrypt_padding = "Raw";
186
      const std::string m_decrypt_padding = "EME1(SHA-256)";
187
      const size_t m_ctext_length = 256;
188
      Botan::RSA_PrivateKey m_privkey;
189
      Botan::RSA_PublicKey m_pubkey;
190
      Botan::PK_Encryptor_EME m_enc;
191
      Botan::PK_Decryptor_EME m_dec;
192
};
193

194
#endif
195

196
#if defined(BOTAN_HAS_TLS_CBC)
197

198
/*
199
* Test handling of countermeasure to the Lucky13 attack
200
*/
201
class Lucky13_Timing_Test final : public Timing_Test {
×
202
   public:
203
      Lucky13_Timing_Test(const std::string& mac_name, size_t mac_keylen) :
4✔
204
            m_mac_algo(mac_name),
8✔
205
            m_mac_keylen(mac_keylen),
4✔
206
            m_dec(Botan::BlockCipher::create_or_throw("AES-128"),
12✔
207
                  Botan::MessageAuthenticationCode::create_or_throw("HMAC(" + m_mac_algo + ")"),
12✔
208
                  16,
209
                  m_mac_keylen,
4✔
210
                  Botan::TLS::Protocol_Version::TLS_V12,
211
                  false) {}
8✔
212

213
      std::vector<uint8_t> prepare_input(const std::string& input) override;
214
      uint64_t measure_critical_function(const std::vector<uint8_t>& input) override;
215

216
   private:
217
      const std::string m_mac_algo;
218
      const size_t m_mac_keylen;
219
      Botan::TLS::TLS_CBC_HMAC_AEAD_Decryption m_dec;
220
};
221

222
std::vector<uint8_t> Lucky13_Timing_Test::prepare_input(const std::string& input) {
12✔
223
   const std::vector<uint8_t> input_vector = Botan::hex_decode(input);
12✔
224
   const std::vector<uint8_t> key(16);
12✔
225
   const std::vector<uint8_t> iv(16);
12✔
226

227
   auto enc = Botan::Cipher_Mode::create("AES-128/CBC/NoPadding", Botan::Cipher_Dir::Encryption);
12✔
228
   enc->set_key(key);
12✔
229
   enc->start(iv);
12✔
230
   Botan::secure_vector<uint8_t> buf(input_vector.begin(), input_vector.end());
12✔
231
   enc->finish(buf);
12✔
232

233
   return unlock(buf);
12✔
234
}
60✔
235

236
uint64_t Lucky13_Timing_Test::measure_critical_function(const std::vector<uint8_t>& input) {
228✔
237
   Botan::secure_vector<uint8_t> data(input.begin(), input.end());
228✔
238
   Botan::secure_vector<uint8_t> aad(13);
228✔
239
   const Botan::secure_vector<uint8_t> iv(16);
228✔
240
   Botan::secure_vector<uint8_t> key(16 + m_mac_keylen);
228✔
241

242
   m_dec.set_key(unlock(key));
228✔
243
   m_dec.set_associated_data(aad);
228✔
244
   m_dec.start(unlock(iv));
228✔
245

246
   TimingTestTimer timer;
228✔
247
   try {
228✔
248
      m_dec.finish(data);
228✔
249
   } catch(Botan::TLS::TLS_Exception&) {}
228✔
250
   return timer.complete();
228✔
251
}
912✔
252

253
#endif
254

255
#if defined(BOTAN_HAS_ECDSA)
256

257
class ECDSA_Timing_Test final : public Timing_Test {
×
258
   public:
259
      explicit ECDSA_Timing_Test(const std::string& ecgroup);
260

261
      uint64_t measure_critical_function(const std::vector<uint8_t>& input) override;
262

263
   private:
264
      const Botan::EC_Group m_group;
265
      const Botan::ECDSA_PrivateKey m_privkey;
266
      const Botan::EC_Scalar m_x;
267
      Botan::EC_Scalar m_b;
268
      Botan::EC_Scalar m_b_inv;
269
      std::vector<Botan::BigInt> m_ws;
270
};
271

272
ECDSA_Timing_Test::ECDSA_Timing_Test(const std::string& ecgroup) :
1✔
273
      m_group(Botan::EC_Group::from_name(ecgroup)),
1✔
274
      m_privkey(timing_test_rng(), m_group),
1✔
275
      m_x(m_privkey._private_key()),
1✔
276
      m_b(Botan::EC_Scalar::random(m_group, timing_test_rng())),
1✔
277
      m_b_inv(m_b.invert()) {}
2✔
278

279
uint64_t ECDSA_Timing_Test::measure_critical_function(const std::vector<uint8_t>& input) {
38✔
280
   const auto k = Botan::EC_Scalar::from_bytes_with_trunc(m_group, input);
38✔
281
   // fixed message to minimize noise
282
   const auto m = Botan::EC_Scalar::from_bytes_with_trunc(m_group, std::vector<uint8_t>{5});
38✔
283

284
   TimingTestTimer timer;
38✔
285

286
   // the following ECDSA operations involve and should not leak any information about k
287
   const auto r = Botan::EC_Scalar::gk_x_mod_order(k, timing_test_rng(), m_ws);
38✔
288
   const auto k_inv = k.invert();
38✔
289
   m_b.square_self();
38✔
290
   m_b_inv.square_self();
38✔
291
   const auto xr_m = ((m_x * m_b) * r) + (m * m_b);
38✔
292
   const auto s = (k_inv * xr_m) * m_b_inv;
38✔
293
   BOTAN_UNUSED(r, s);
38✔
294

295
   return timer.complete();
76✔
296
}
38✔
297

298
#endif
299

300
#if defined(BOTAN_HAS_ECC_GROUP)
301

302
class ECC_Mul_Timing_Test final : public Timing_Test {
×
303
   public:
304
      explicit ECC_Mul_Timing_Test(std::string_view ecgroup) : m_group(Botan::EC_Group::from_name(ecgroup)) {}
1✔
305

306
      uint64_t measure_critical_function(const std::vector<uint8_t>& input) override;
307

308
   private:
309
      const Botan::EC_Group m_group;
310
      std::vector<Botan::BigInt> m_ws;
311
};
312

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

316
   TimingTestTimer timer;
38✔
317
   const auto kG = Botan::EC_AffinePoint::g_mul(k, timing_test_rng(), m_ws);
38✔
318
   return timer.complete();
76✔
319
}
38✔
320

321
#endif
322

323
#if defined(BOTAN_HAS_DL_GROUP)
324

325
class Powmod_Timing_Test final : public Timing_Test {
×
326
   public:
327
      explicit Powmod_Timing_Test(std::string_view dl_group) : m_group(dl_group) {}
1✔
328

329
      uint64_t measure_critical_function(const std::vector<uint8_t>& input) override;
330

331
   private:
332
      Botan::DL_Group m_group;
333
};
334

335
uint64_t Powmod_Timing_Test::measure_critical_function(const std::vector<uint8_t>& input) {
57✔
336
   const Botan::BigInt x(input.data(), input.size());
57✔
337
   const size_t max_x_bits = m_group.p_bits();
57✔
338

339
   TimingTestTimer timer;
57✔
340

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

343
   return timer.complete();
57✔
344
}
114✔
345

346
#endif
347

348
#if defined(BOTAN_HAS_NUMBERTHEORY)
349

350
class Invmod_Timing_Test final : public Timing_Test {
×
351
   public:
352
      explicit Invmod_Timing_Test(size_t p_bits) { m_p = Botan::random_prime(timing_test_rng(), p_bits); }
2✔
353

354
      uint64_t measure_critical_function(const std::vector<uint8_t>& input) override;
355

356
   private:
357
      Botan::BigInt m_p;
358
};
359

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

363
   TimingTestTimer timer;
38✔
364
   const Botan::BigInt inv = Botan::inverse_mod_secret_prime(k, m_p);
38✔
365
   return timer.complete();
38✔
366
}
76✔
367

368
#endif
369

370
std::vector<std::vector<uint64_t>> Timing_Test::execute_evaluation(const std::vector<std::string>& raw_inputs,
10✔
371
                                                                   size_t warmup_runs,
372
                                                                   size_t measurement_runs) {
373
   std::vector<std::vector<uint64_t>> all_results(raw_inputs.size());
10✔
374
   std::vector<std::vector<uint8_t>> inputs(raw_inputs.size());
10✔
375

376
   for(auto& result : all_results) {
37✔
377
      result.reserve(measurement_runs);
27✔
378
   }
379

380
   for(size_t i = 0; i != inputs.size(); ++i) {
37✔
381
      inputs[i] = prepare_input(raw_inputs[i]);
27✔
382
   }
383

384
   // arbitrary upper bounds of 1 and 10 million resp
385
   if(warmup_runs > 1000000 || measurement_runs > 100000000) {
10✔
386
      throw CLI_Error("Requested execution counts too large, rejecting");
×
387
   }
388

389
   size_t total_runs = 0;
10✔
390
   std::vector<uint64_t> results(inputs.size());
10✔
391

392
   while(total_runs < (warmup_runs + measurement_runs)) {
200✔
393
      for(size_t i = 0; i != inputs.size(); ++i) {
703✔
394
         results[i] = measure_critical_function(inputs[i]);
513✔
395
      }
396

397
      total_runs++;
190✔
398

399
      if(total_runs > warmup_runs) {
190✔
400
         for(size_t i = 0; i != results.size(); ++i) {
592✔
401
            all_results[i].push_back(results[i]);
432✔
402
         }
403
      }
404
   }
405

406
   return all_results;
10✔
407
}
10✔
408

409
class Timing_Test_Command final : public Command {
410
   public:
411
      Timing_Test_Command() :
11✔
412
            Command(
413
               "timing_test test_type --test-data-file= --test-data-dir=src/tests/data/timing "
414
               "--warmup-runs=5000 --measurement-runs=50000") {}
22✔
415

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

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

420
      void go() override {
10✔
421
         const std::string test_type = get_arg("test_type");
10✔
422
         const size_t warmup_runs = get_arg_sz("warmup-runs");
10✔
423
         const size_t measurement_runs = get_arg_sz("measurement-runs");
10✔
424

425
         std::unique_ptr<Timing_Test> test = lookup_timing_test(test_type);
10✔
426

427
         if(!test) {
10✔
428
            throw CLI_Error("Unknown or unavailable test type '" + test_type + "'");
×
429
         }
430

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

433
         if(filename.empty()) {
10✔
434
            const std::string test_data_dir = get_arg("test-data-dir");
10✔
435
            filename = test_data_dir + "/" + test_type + ".vec";
20✔
436
         }
10✔
437

438
         std::vector<std::string> lines = read_testdata(filename);
10✔
439

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

442
         size_t unique_id = 0;
10✔
443
         std::ostringstream oss;
10✔
444
         for(size_t secret_id = 0; secret_id != results.size(); ++secret_id) {
37✔
445
            for(size_t i = 0; i != results[secret_id].size(); ++i) {
459✔
446
               oss << unique_id++ << ";" << secret_id << ";" << results[secret_id][i] << "\n";
432✔
447
            }
448
         }
449

450
         output() << oss.str();
10✔
451
      }
20✔
452

453
   private:
454
      static std::vector<std::string> read_testdata(const std::string& filename) {
10✔
455
         std::vector<std::string> lines;
10✔
456
         std::ifstream infile(filename);
10✔
457
         if(infile.good() == false) {
10✔
458
            throw CLI_Error("Error reading test data from '" + filename + "'");
×
459
         }
460
         std::string line;
10✔
461
         while(std::getline(infile, line)) {
70✔
462
            if(!line.empty() && line.at(0) != '#') {
60✔
463
               lines.push_back(line);
27✔
464
            }
465
         }
466
         return lines;
20✔
467
      }
10✔
468

469
      static std::unique_ptr<Timing_Test> lookup_timing_test(std::string_view test_type);
470

471
      std::string help_text() const override {
×
472
         // TODO check feature macros
473
         return (Command::help_text() +
×
474
                 "\ntest_type can take on values "
475
                 "bleichenbacher "
476
                 "manger "
477
                 "ecdsa "
478
                 "ecc_mul "
479
                 "inverse_mod "
480
                 "pow_mod "
481
                 "lucky13sec3 "
482
                 "lucky13sec4sha1 "
483
                 "lucky13sec4sha256 "
484
                 "lucky13sec4sha384 ");
×
485
      }
486
};
487

488
std::unique_ptr<Timing_Test> Timing_Test_Command::lookup_timing_test(std::string_view test_type) {
10✔
489
#if defined(BOTAN_HAS_RSA) && defined(BOTAN_HAS_EME_PKCS1) && defined(BOTAN_HAS_EME_RAW)
490
   if(test_type == "bleichenbacher") {
10✔
491
      return std::make_unique<Bleichenbacker_Timing_Test>(2048);
1✔
492
   }
493
#endif
494

495
#if defined(BOTAN_HAS_RSA) && defined(BOTAN_HAS_EME_OAEP) && defined(BOTAN_HAS_EME_RAW)
496
   if(test_type == "manger") {
9✔
497
      return std::make_unique<Manger_Timing_Test>(2048);
1✔
498
   }
499
#endif
500

501
#if defined(BOTAN_HAS_ECDSA)
502
   if(test_type == "ecdsa") {
8✔
503
      return std::make_unique<ECDSA_Timing_Test>("secp384r1");
1✔
504
   }
505
#endif
506

507
#if defined(BOTAN_HAS_ECC_GROUP)
508
   if(test_type == "ecc_mul") {
7✔
509
      return std::make_unique<ECC_Mul_Timing_Test>("brainpool512r1");
1✔
510
   }
511
#endif
512

513
#if defined(BOTAN_HAS_NUMBERTHEORY)
514
   if(test_type == "inverse_mod") {
6✔
515
      return std::make_unique<Invmod_Timing_Test>(512);
1✔
516
   }
517
#endif
518

519
#if defined(BOTAN_HAS_DL_GROUP)
520
   if(test_type == "pow_mod") {
5✔
521
      return std::make_unique<Powmod_Timing_Test>("modp/ietf/1024");
1✔
522
   }
523
#endif
524

525
#if defined(BOTAN_HAS_TLS_CBC)
526
   if(test_type == "lucky13sec3" || test_type == "lucky13sec4sha1") {
6✔
527
      return std::make_unique<Lucky13_Timing_Test>("SHA-1", 20);
2✔
528
   }
529
   if(test_type == "lucky13sec4sha256") {
2✔
530
      return std::make_unique<Lucky13_Timing_Test>("SHA-256", 32);
1✔
531
   }
532
   if(test_type == "lucky13sec4sha384") {
1✔
533
      return std::make_unique<Lucky13_Timing_Test>("SHA-384", 48);
1✔
534
   }
535
#endif
536

537
   BOTAN_UNUSED(test_type);
×
538

539
   return nullptr;
×
540
}
541

542
BOTAN_REGISTER_COMMAND("timing_test", Timing_Test_Command);
11✔
543

544
#if defined(BOTAN_HAS_RSA) && defined(BOTAN_HAS_EME_PKCS1) && defined(BOTAN_TARGET_OS_HAS_FILESYSTEM)
545

546
class MARVIN_Test_Command final : public Command {
547
   public:
548
      MARVIN_Test_Command() : Command("marvin_test key_file ctext_dir --runs=10 --output-nsec --expect-pt-len=0") {}
4✔
549

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

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

554
      void go() override {
1✔
555
         const std::string key_file = get_arg("key_file");
1✔
556
         const std::string ctext_dir = get_arg("ctext_dir");
1✔
557
         const size_t measurement_runs = get_arg_sz("runs");
1✔
558
         const size_t expect_pt_len = get_arg_sz("expect-pt-len");
1✔
559
         const bool output_nsec = flag_set("output-nsec");
1✔
560

561
         Botan::DataSource_Stream key_src(key_file);
1✔
562
         const auto key = Botan::PKCS8::load_key(key_src);
1✔
563

564
         if(key->algo_name() != "RSA") {
1✔
565
            throw CLI_Usage_Error("Unexpected key type for MARVIN test");
×
566
         }
567

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

570
         std::vector<std::string> names;
1✔
571
         std::vector<uint8_t> ciphertext_data;
1✔
572

573
         for(const auto& filename : Botan::get_files_recursive(ctext_dir)) {
5✔
574
            const auto contents = this->slurp_file(filename);
4✔
575

576
            if(contents.size() != modulus_bytes) {
4✔
577
               throw CLI_Usage_Error(
×
578
                  Botan::fmt("The ciphertext file {} had different size ({}) than the RSA modulus ({})",
×
579
                             filename,
580
                             contents.size(),
×
581
                             modulus_bytes));
×
582
            }
583

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

586
            names.push_back(parts[parts.size() - 1]);
4✔
587
            ciphertext_data.insert(ciphertext_data.end(), contents.begin(), contents.end());
4✔
588
         }
9✔
589

590
         if(names.empty()) {
1✔
591
            throw CLI_Usage_Error("Empty ciphertext directory for MARVIN test");
×
592
         }
593

594
         Botan::PK_Decryptor_EME op(*key, rng(), "PKCS1v15");
1✔
595

596
         std::vector<size_t> indexes;
1✔
597
         for(size_t i = 0; i != names.size(); ++i) {
5✔
598
            indexes.push_back(i);
4✔
599
         }
600

601
         std::vector<std::vector<uint64_t>> measurements(names.size());
1✔
602
         for(auto& m : measurements) {
5✔
603
            m.reserve(measurement_runs);
4✔
604
         }
605

606
         for(size_t r = 0; r != measurement_runs; ++r) {
33✔
607
            shuffle(indexes, rng());
32✔
608

609
            std::vector<uint8_t> ciphertext(modulus_bytes);
32✔
610
            for(size_t i = 0; i != indexes.size(); ++i) {
160✔
611
               const size_t testcase = indexes[i];
128✔
612

613
               // FIXME should this load be constant time?
614
               Botan::copy_mem(&ciphertext[0], &ciphertext_data[testcase * modulus_bytes], modulus_bytes);
128✔
615

616
               TimingTestTimer timer;
128✔
617
               op.decrypt_or_random(ciphertext.data(), modulus_bytes, expect_pt_len, rng());
128✔
618
               const uint64_t duration = timer.complete();
128✔
619
               BOTAN_ASSERT_NOMSG(measurements[testcase].size() == r);
128✔
620
               measurements[testcase].push_back(duration);
128✔
621
            }
622
         }
32✔
623

624
         for(size_t t = 0; t != names.size(); ++t) {
5✔
625
            if(t > 0) {
4✔
626
               output() << ",";
3✔
627
            }
628
            output() << names[t];
4✔
629
         }
630
         output() << "\n";
1✔
631

632
         for(size_t r = 0; r != measurement_runs; ++r) {
33✔
633
            for(size_t t = 0; t != names.size(); ++t) {
160✔
634
               if(t > 0) {
128✔
635
                  output() << ",";
96✔
636
               }
637

638
               const uint64_t dur_nsec = measurements[t][r];
128✔
639
               if(output_nsec) {
128✔
640
                  output() << dur_nsec;
×
641
               } else {
642
                  const double dur_s = static_cast<double>(dur_nsec) / 1000000000.0;
128✔
643
                  output() << dur_s;
128✔
644
               }
645
            }
646
            output() << "\n";
32✔
647
         }
648
      }
3✔
649

650
      template <typename T>
651
      void shuffle(std::vector<T>& vec, Botan::RandomNumberGenerator& rng) {
32✔
652
         const size_t n = vec.size();
32✔
653
         for(size_t i = 0; i != n; ++i) {
160✔
654
            uint8_t jb[sizeof(uint64_t)];
655
            rng.randomize(jb, sizeof(jb));
128✔
656
            uint64_t j8 = Botan::load_le<uint64_t>(jb, 0);
128✔
657
            size_t j = i + static_cast<size_t>(j8) % (n - i);
128✔
658
            std::swap(vec[i], vec[j]);
128✔
659
         }
660
      }
32✔
661
};
662

663
BOTAN_REGISTER_COMMAND("marvin_test", MARVIN_Test_Command);
2✔
664

665
#endif
666

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