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

randombit / botan / 24816487239

22 Apr 2026 02:55AM UTC coverage: 89.474%. Remained the same
24816487239

push

github

web-flow
Merge pull request #5538 from randombit/jack/timing-test-fix

In timing_test shuffle the inputs before measurement

106455 of 118979 relevant lines covered (89.47%)

11511767.11 hits per line

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

89.29
/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 <numeric>
34
#include <sstream>
35

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

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

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

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

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

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

62
#if defined(BOTAN_HAS_TLS_CBC)
63
   #include <botan/block_cipher.h>
64
   #include <botan/mac.h>
65
   #include <botan/tls_exceptn.h>
66
   #include <botan/tls_version.h>
67
   #include <botan/internal/tls_cbc.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
void shuffle_idx(std::vector<size_t>& vec, Botan::RandomNumberGenerator& rng) {
222✔
88
   const size_t n = vec.size();
222✔
89
   for(size_t i = 0; i != n; ++i) {
863✔
90
      uint8_t jb[sizeof(uint64_t)];
641✔
91
      rng.randomize(jb, sizeof(jb));
641✔
92
      const uint64_t j8 = Botan::load_le<uint64_t>(jb, 0);
641✔
93
      const size_t j = i + static_cast<size_t>(j8) % (n - i);
641✔
94
      std::swap(vec[i], vec[j]);
641✔
95
   }
96
}
222✔
97

98
class TimingTestTimer final {
99
   public:
100
      TimingTestTimer() : m_start(get_high_resolution_clock()) {}
641✔
101

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

104
   private:
105
      static uint64_t get_high_resolution_clock() {
1,282✔
106
         // TODO use cpu clock where possible/relevant incl serializing instructions
107
         auto now = std::chrono::high_resolution_clock::now().time_since_epoch();
1,206✔
108
         return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
1,282✔
109
      }
110

111
      uint64_t m_start;
112
};
113

114
class Timing_Test {
115
   public:
116
      Timing_Test() {
10✔
117
         /*
118
         A constant seed is ok here since the timing test rng just needs to be
119
         "random" but not cryptographically secure - even std::rand() would be ok.
120
         */
121

122
#if defined(BOTAN_HAS_CHACHA_RNG)
123
         m_rng = std::make_unique<Botan::ChaCha_RNG>(std::vector<uint8_t>(64, 0));
10✔
124
#else
125
         m_rng = std::make_unique<Botan::System_RNG>();
126
#endif
127
      }
10✔
128

129
      virtual ~Timing_Test() = default;
×
130

131
      Timing_Test(const Timing_Test& other) = delete;
132
      Timing_Test(Timing_Test&& other) = delete;
133
      Timing_Test& operator=(const Timing_Test& other) = delete;
134
      Timing_Test& operator=(Timing_Test&& other) = delete;
135

136
      std::vector<std::vector<uint64_t>> execute_evaluation(const std::vector<std::string>& inputs,
137
                                                            size_t warmup_runs,
138
                                                            size_t measurement_runs);
139

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

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

144
   protected:
145
      Botan::RandomNumberGenerator& timing_test_rng() { return (*m_rng); }
2✔
146

147
   private:
148
      std::unique_ptr<Botan::RandomNumberGenerator> m_rng;
149
};
150

151
#if defined(BOTAN_HAS_RSA) && defined(BOTAN_HAS_EME_PKCS1) && defined(BOTAN_HAS_EME_RAW)
152

153
class Bleichenbacker_Timing_Test final : public Timing_Test {
×
154
   public:
155
      explicit Bleichenbacker_Timing_Test(size_t keysize) :
1✔
156
            m_privkey(timing_test_rng(), keysize),
1✔
157
            m_pubkey(m_privkey.public_key()),
1✔
158
            m_enc(*m_pubkey, timing_test_rng(), "Raw"),
1✔
159
            m_dec(m_privkey, timing_test_rng(), "PKCS1v15") {}
2✔
160

161
      std::vector<uint8_t> prepare_input(const std::string& input) override {
4✔
162
         const std::vector<uint8_t> input_vector = Botan::hex_decode(input);
4✔
163
         return m_enc.encrypt(input_vector, timing_test_rng());
4✔
164
      }
4✔
165

166
      uint64_t measure_critical_function(const std::vector<uint8_t>& input) override {
76✔
167
         const TimingTestTimer timer;
76✔
168
         m_dec.decrypt_or_random(input.data(), m_ctext_length, m_expected_content_size, timing_test_rng());
76✔
169
         return timer.complete();
76✔
170
      }
171

172
   private:
173
      const size_t m_expected_content_size = 48;
174
      const size_t m_ctext_length = 256;
175
      Botan::RSA_PrivateKey m_privkey;
176
      std::unique_ptr<Botan::Public_Key> m_pubkey;
177
      Botan::PK_Encryptor_EME m_enc;
178
      Botan::PK_Decryptor_EME m_dec;
179
};
180

181
#endif
182

183
#if defined(BOTAN_HAS_RSA) && defined(BOTAN_HAS_EME_OAEP) && defined(BOTAN_HAS_EME_RAW)
184

185
/*
186
* Test Manger OAEP side channel
187
*
188
* "A Chosen Ciphertext Attack on RSA Optimal Asymmetric Encryption
189
* Padding (OAEP) as Standardized in PKCS #1 v2.0" James Manger
190
* http://archiv.infsec.ethz.ch/education/fs08/secsem/Manger01.pdf
191
*/
192
class Manger_Timing_Test final : public Timing_Test {
×
193
   public:
194
      explicit Manger_Timing_Test(size_t keysize) :
1✔
195
            m_privkey(timing_test_rng(), keysize),
1✔
196
            m_pubkey(m_privkey.public_key()),
1✔
197
            m_enc(*m_pubkey, timing_test_rng(), m_encrypt_padding),
1✔
198
            m_dec(m_privkey, timing_test_rng(), m_decrypt_padding) {}
2✔
199

200
      std::vector<uint8_t> prepare_input(const std::string& input) override {
2✔
201
         const std::vector<uint8_t> input_vector = Botan::hex_decode(input);
2✔
202
         return m_enc.encrypt(input_vector, timing_test_rng());
2✔
203
      }
2✔
204

205
      uint64_t measure_critical_function(const std::vector<uint8_t>& input) override {
38✔
206
         const TimingTestTimer timer;
38✔
207
         try {
38✔
208
            m_dec.decrypt(input.data(), m_ctext_length);
38✔
209
         } catch(Botan::Decoding_Error&) {}
38✔
210
         return timer.complete();
38✔
211
      }
212

213
   private:
214
      const std::string m_encrypt_padding = "Raw";
215
      const std::string m_decrypt_padding = "EME1(SHA-256)";
216
      const size_t m_ctext_length = 256;
217
      Botan::RSA_PrivateKey m_privkey;
218
      std::unique_ptr<Botan::Public_Key> m_pubkey;
219
      Botan::PK_Encryptor_EME m_enc;
220
      Botan::PK_Decryptor_EME m_dec;
221
};
222

223
#endif
224

225
#if defined(BOTAN_HAS_TLS_CBC)
226

227
/*
228
* Test handling of countermeasure to the Lucky13 attack
229
*/
230
class Lucky13_Timing_Test final : public Timing_Test {
×
231
   public:
232
      Lucky13_Timing_Test(const std::string& mac_name, size_t mac_keylen) :
4✔
233
            m_mac_algo(mac_name),
8✔
234
            m_mac_keylen(mac_keylen),
4✔
235
            m_dec(Botan::BlockCipher::create_or_throw("AES-128"),
12✔
236
                  Botan::MessageAuthenticationCode::create_or_throw("HMAC(" + m_mac_algo + ")"),
12✔
237
                  16,
238
                  m_mac_keylen,
4✔
239
                  Botan::TLS::Protocol_Version::TLS_V12,
240
                  false) {}
8✔
241

242
      std::vector<uint8_t> prepare_input(const std::string& input) override;
243
      uint64_t measure_critical_function(const std::vector<uint8_t>& input) override;
244

245
   private:
246
      const std::string m_mac_algo;
247
      const size_t m_mac_keylen;
248
      Botan::TLS::TLS_CBC_HMAC_AEAD_Decryption m_dec;
249
};
250

251
std::vector<uint8_t> Lucky13_Timing_Test::prepare_input(const std::string& input) {
12✔
252
   const std::vector<uint8_t> input_vector = Botan::hex_decode(input);
12✔
253
   const std::vector<uint8_t> key(16);
12✔
254
   const std::vector<uint8_t> iv(16);
12✔
255

256
   auto enc = Botan::Cipher_Mode::create("AES-128/CBC/NoPadding", Botan::Cipher_Dir::Encryption);
12✔
257
   enc->set_key(key);
12✔
258
   enc->start(iv);
12✔
259
   Botan::secure_vector<uint8_t> buf(input_vector.begin(), input_vector.end());
12✔
260
   enc->finish(buf);
12✔
261

262
   return unlock(buf);
12✔
263
}
60✔
264

265
uint64_t Lucky13_Timing_Test::measure_critical_function(const std::vector<uint8_t>& input) {
228✔
266
   Botan::secure_vector<uint8_t> data(input.begin(), input.end());
228✔
267
   Botan::secure_vector<uint8_t> aad(13);
228✔
268
   const Botan::secure_vector<uint8_t> iv(16);
228✔
269
   const Botan::secure_vector<uint8_t> key(16 + m_mac_keylen);
228✔
270

271
   m_dec.set_key(unlock(key));
228✔
272
   m_dec.set_associated_data(aad);
228✔
273
   m_dec.start(unlock(iv));
228✔
274

275
   const TimingTestTimer timer;
228✔
276
   try {
228✔
277
      m_dec.finish(data);
228✔
278
   } catch(Botan::TLS::TLS_Exception&) {}
228✔
279
   return timer.complete();
228✔
280
}
912✔
281

282
#endif
283

284
#if defined(BOTAN_HAS_ECDSA)
285

286
class ECDSA_Timing_Test final : public Timing_Test {
×
287
   public:
288
      explicit ECDSA_Timing_Test(const std::string& ecgroup);
289

290
      uint64_t measure_critical_function(const std::vector<uint8_t>& input) override;
291

292
   private:
293
      const Botan::EC_Group m_group;
294
      const Botan::EC_Scalar m_x;
295
      Botan::EC_Scalar m_b;
296
};
297

298
ECDSA_Timing_Test::ECDSA_Timing_Test(const std::string& ecgroup) :
1✔
299
      m_group(Botan::EC_Group::from_name(ecgroup)),
1✔
300
      m_x(Botan::EC_Scalar::random(m_group, timing_test_rng())),
1✔
301
      m_b(Botan::EC_Scalar::random(m_group, timing_test_rng())) {}
2✔
302

303
uint64_t ECDSA_Timing_Test::measure_critical_function(const std::vector<uint8_t>& input) {
38✔
304
   const auto k = Botan::EC_Scalar::from_bytes_with_trunc(m_group, input);
38✔
305
   // fixed message to minimize noise
306
   const auto m = Botan::EC_Scalar::from_bytes_with_trunc(m_group, std::vector<uint8_t>{5});
38✔
307

308
   const TimingTestTimer timer;
38✔
309

310
   // the following ECDSA operations involve and should not leak any information about k
311

312
   const auto r = Botan::EC_Scalar::gk_x_mod_order(k, timing_test_rng());
38✔
313

314
   const auto k_inv = (m_b * k).invert();
38✔
315

316
   const auto xr_m = ((m_x * m_b) * r) + (m * m_b);
38✔
317

318
   const auto s = (k_inv * xr_m);
38✔
319

320
   // Generate the next blinding value via modular squaring
321
   m_b.square_self();
38✔
322

323
   BOTAN_UNUSED(r, s);
38✔
324

325
   return timer.complete();
76✔
326
}
38✔
327

328
#endif
329

330
#if defined(BOTAN_HAS_ECC_GROUP)
331

332
class ECC_Mul_Timing_Test final : public Timing_Test {
×
333
   public:
334
      explicit ECC_Mul_Timing_Test(std::string_view ecgroup) : m_group(Botan::EC_Group::from_name(ecgroup)) {}
1✔
335

336
      uint64_t measure_critical_function(const std::vector<uint8_t>& input) override;
337

338
   private:
339
      const Botan::EC_Group m_group;
340
};
341

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

345
   const TimingTestTimer timer;
38✔
346
   const auto kG = Botan::EC_AffinePoint::g_mul(k, timing_test_rng());
38✔
347
   return timer.complete();
76✔
348
}
38✔
349

350
#endif
351

352
#if defined(BOTAN_HAS_DL_GROUP)
353

354
class Powmod_Timing_Test final : public Timing_Test {
×
355
   public:
356
      explicit Powmod_Timing_Test(std::string_view dl_group) : m_group(Botan::DL_Group::from_name(dl_group)) {}
1✔
357

358
      uint64_t measure_critical_function(const std::vector<uint8_t>& input) override;
359

360
   private:
361
      Botan::DL_Group m_group;
362
};
363

364
uint64_t Powmod_Timing_Test::measure_critical_function(const std::vector<uint8_t>& input) {
57✔
365
   const Botan::BigInt x(input.data(), input.size());
57✔
366
   const size_t max_x_bits = m_group.p_bits();
57✔
367

368
   const TimingTestTimer timer;
57✔
369

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

372
   return timer.complete();
114✔
373
}
57✔
374

375
#endif
376

377
#if defined(BOTAN_HAS_NUMBERTHEORY)
378

379
class Invmod_Timing_Test final : public Timing_Test {
×
380
   public:
381
      explicit Invmod_Timing_Test(size_t p_bits) { m_p = Botan::random_prime(timing_test_rng(), p_bits); }
2✔
382

383
      uint64_t measure_critical_function(const std::vector<uint8_t>& input) override;
384

385
   private:
386
      Botan::BigInt m_p;
387
};
388

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

392
   const TimingTestTimer timer;
38✔
393
   const Botan::BigInt inv = Botan::inverse_mod_secret_prime(k, m_p);
38✔
394
   return timer.complete();
76✔
395
}
38✔
396

397
#endif
398

399
std::vector<std::vector<uint64_t>> Timing_Test::execute_evaluation(const std::vector<std::string>& raw_inputs,
10✔
400
                                                                   size_t warmup_runs,
401
                                                                   size_t measurement_runs) {
402
   std::vector<std::vector<uint64_t>> all_results(raw_inputs.size());
10✔
403
   std::vector<std::vector<uint8_t>> inputs(raw_inputs.size());
10✔
404

405
   for(auto& result : all_results) {
37✔
406
      result.reserve(measurement_runs);
27✔
407
   }
408

409
   for(size_t i = 0; i != inputs.size(); ++i) {
37✔
410
      inputs[i] = prepare_input(raw_inputs[i]);
27✔
411
   }
412

413
   // arbitrary upper bounds of 1 and 10 million resp
414
   if(warmup_runs > 1000000 || measurement_runs > 100000000) {
10✔
415
      throw CLI_Error("Requested execution counts too large, rejecting");
×
416
   }
417

418
   size_t total_runs = 0;
10✔
419
   std::vector<uint64_t> results(inputs.size());
10✔
420

421
   std::vector<size_t> indexes(inputs.size());
10✔
422
   std::iota(indexes.begin(), indexes.end(), size_t{0});
10✔
423

424
   while(total_runs < (warmup_runs + measurement_runs)) {
200✔
425
      shuffle_idx(indexes, *m_rng);
190✔
426

427
      for(const size_t testcase : indexes) {
703✔
428
         results[testcase] = measure_critical_function(inputs[testcase]);
513✔
429
      }
430

431
      total_runs++;
190✔
432

433
      if(total_runs > warmup_runs) {
190✔
434
         for(size_t i = 0; i != results.size(); ++i) {
592✔
435
            all_results[i].push_back(results[i]);
432✔
436
         }
437
      }
438
   }
439

440
   return all_results;
10✔
441
}
10✔
442

443
class Timing_Test_Command final : public Command {
444
   public:
445
      Timing_Test_Command() :
11✔
446
            Command(
447
               "timing_test test_type --test-data-file= --test-data-dir=src/tests/data/timing "
448
               "--warmup-runs=5000 --measurement-runs=50000") {}
22✔
449

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

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

454
      void go() override {
10✔
455
         const std::string test_type = get_arg("test_type");
10✔
456
         const size_t warmup_runs = get_arg_sz("warmup-runs");
10✔
457
         const size_t measurement_runs = get_arg_sz("measurement-runs");
10✔
458

459
         std::unique_ptr<Timing_Test> test = lookup_timing_test(test_type);
10✔
460

461
         if(!test) {
10✔
462
            throw CLI_Error("Unknown or unavailable test type '" + test_type + "'");
×
463
         }
464

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

467
         if(filename.empty()) {
10✔
468
            const std::string test_data_dir = get_arg("test-data-dir");
10✔
469
            filename = test_data_dir + "/" + test_type + ".vec";
20✔
470
         }
10✔
471

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

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

476
         size_t unique_id = 0;
10✔
477
         std::ostringstream oss;
10✔
478
         for(size_t secret_id = 0; secret_id != results.size(); ++secret_id) {
37✔
479
            for(size_t i = 0; i != results[secret_id].size(); ++i) {
459✔
480
               oss << unique_id++ << ";" << secret_id << ";" << results[secret_id][i] << "\n";
432✔
481
            }
482
         }
483

484
         output() << oss.str();
10✔
485
      }
20✔
486

487
   private:
488
      static std::vector<std::string> read_testdata(const std::string& filename) {
10✔
489
         std::vector<std::string> lines;
10✔
490
         std::ifstream infile(filename);
10✔
491
         if(!infile.good()) {
10✔
492
            throw CLI_Error("Error reading test data from '" + filename + "'");
×
493
         }
494
         std::string line;
10✔
495
         while(std::getline(infile, line)) {
70✔
496
            if(!line.empty() && line.at(0) != '#') {
60✔
497
               lines.push_back(line);
27✔
498
            }
499
         }
500
         return lines;
20✔
501
      }
10✔
502

503
      static std::unique_ptr<Timing_Test> lookup_timing_test(std::string_view test_type);
504

505
      std::string help_text() const override {
×
506
         // TODO check feature macros
507
         return (Command::help_text() +
×
508
                 "\ntest_type can take on values "
509
                 "bleichenbacher "
510
                 "manger "
511
                 "ecdsa "
512
                 "ecc_mul "
513
                 "inverse_mod "
514
                 "pow_mod "
515
                 "lucky13sec3 "
516
                 "lucky13sec4sha1 "
517
                 "lucky13sec4sha256 "
518
                 "lucky13sec4sha384 ");
×
519
      }
520
};
521

522
std::unique_ptr<Timing_Test> Timing_Test_Command::lookup_timing_test(std::string_view test_type) {
10✔
523
#if defined(BOTAN_HAS_RSA) && defined(BOTAN_HAS_EME_PKCS1) && defined(BOTAN_HAS_EME_RAW)
524
   if(test_type == "bleichenbacher") {
10✔
525
      return std::make_unique<Bleichenbacker_Timing_Test>(2048);
1✔
526
   }
527
#endif
528

529
#if defined(BOTAN_HAS_RSA) && defined(BOTAN_HAS_EME_OAEP) && defined(BOTAN_HAS_EME_RAW)
530
   if(test_type == "manger") {
9✔
531
      return std::make_unique<Manger_Timing_Test>(2048);
1✔
532
   }
533
#endif
534

535
#if defined(BOTAN_HAS_ECDSA)
536
   if(test_type == "ecdsa") {
8✔
537
      return std::make_unique<ECDSA_Timing_Test>("secp384r1");
1✔
538
   }
539
#endif
540

541
#if defined(BOTAN_HAS_ECC_GROUP)
542
   if(test_type == "ecc_mul") {
7✔
543
      return std::make_unique<ECC_Mul_Timing_Test>("brainpool512r1");
1✔
544
   }
545
#endif
546

547
#if defined(BOTAN_HAS_NUMBERTHEORY)
548
   if(test_type == "inverse_mod") {
6✔
549
      return std::make_unique<Invmod_Timing_Test>(512);
1✔
550
   }
551
#endif
552

553
#if defined(BOTAN_HAS_DL_GROUP)
554
   if(test_type == "pow_mod") {
5✔
555
      return std::make_unique<Powmod_Timing_Test>("modp/ietf/1024");
1✔
556
   }
557
#endif
558

559
#if defined(BOTAN_HAS_TLS_CBC)
560
   if(test_type == "lucky13sec3" || test_type == "lucky13sec4sha1") {
6✔
561
      return std::make_unique<Lucky13_Timing_Test>("SHA-1", 20);
2✔
562
   }
563
   if(test_type == "lucky13sec4sha256") {
2✔
564
      return std::make_unique<Lucky13_Timing_Test>("SHA-256", 32);
1✔
565
   }
566
   if(test_type == "lucky13sec4sha384") {
1✔
567
      return std::make_unique<Lucky13_Timing_Test>("SHA-384", 48);
1✔
568
   }
569
#endif
570

571
   BOTAN_UNUSED(test_type);
×
572

573
   return nullptr;
×
574
}
575

576
BOTAN_REGISTER_COMMAND("timing_test", Timing_Test_Command);
11✔
577

578
#if defined(BOTAN_HAS_RSA) && defined(BOTAN_HAS_EME_PKCS1) && defined(BOTAN_TARGET_OS_HAS_FILESYSTEM) && \
579
   defined(BOTAN_HAS_SYSTEM_RNG)
580

581
class MARVIN_Test_Command final : public Command {
582
   public:
583
      MARVIN_Test_Command() :
2✔
584
            Command("marvin_test key_file ctext_dir --runs=1K --report-every=0 --output-nsec --expect-pt-len=0") {}
4✔
585

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

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

590
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1)
591
      static inline volatile sig_atomic_t g_sigint_recv = 0;
592

593
      static void marvin_sigint_handler(int /*signal*/) { g_sigint_recv = 1; }
×
594
   #endif
595

596
      void go() override {
1✔
597
         const std::string key_file = get_arg("key_file");
1✔
598
         const std::string ctext_dir = get_arg("ctext_dir");
1✔
599
         const size_t measurement_runs = parse_runs_arg(get_arg("runs"));
1✔
600
         const size_t expect_pt_len = get_arg_sz("expect-pt-len");
1✔
601
         const size_t report_every = get_arg_sz("report-every");
1✔
602
         const bool output_nsec = flag_set("output-nsec");
1✔
603

604
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1)
605
         ::setenv("BOTAN_THREAD_POOL_SIZE", "none", /*overwrite?*/ 1);
1✔
606

607
         struct sigaction sigaction {};
1✔
608

609
         sigaction.sa_handler = marvin_sigint_handler;
1✔
610
         sigemptyset(&sigaction.sa_mask);
1✔
611
         sigaction.sa_flags = 0;
1✔
612

613
         const int rc = ::sigaction(SIGINT, &sigaction, nullptr);
1✔
614
         if(rc != 0) {
1✔
615
            throw CLI_Error("Failed to set SIGINT handler");
×
616
         }
617
   #endif
618

619
         Botan::DataSource_Stream key_src(key_file);
1✔
620
         const auto key = Botan::PKCS8::load_key(key_src);
1✔
621

622
         if(key->algo_name() != "RSA") {
1✔
623
            throw CLI_Usage_Error("Unexpected key type for MARVIN test");
×
624
         }
625

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

628
         std::vector<std::string> names;
1✔
629
         std::vector<uint8_t> ciphertext_data;
1✔
630

631
         for(const auto& filename : Botan::get_files_recursive(ctext_dir)) {
5✔
632
            const auto contents = this->slurp_file(filename);
4✔
633

634
            if(contents.size() != modulus_bytes) {
4✔
635
               throw CLI_Usage_Error(
×
636
                  Botan::fmt("The ciphertext file {} had different size ({}) than the RSA modulus ({})",
×
637
                             filename,
638
                             contents.size(),
×
639
                             modulus_bytes));
×
640
            }
641

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

644
            names.push_back(parts[parts.size() - 1]);
4✔
645
            ciphertext_data.insert(ciphertext_data.end(), contents.begin(), contents.end());
4✔
646
         }
9✔
647

648
         if(names.empty()) {
1✔
649
            throw CLI_Usage_Error("Empty ciphertext directory for MARVIN test");
×
650
         }
651

652
         auto& test_results_file = output();
1✔
653

654
         const size_t testcases = names.size();
1✔
655

656
   #if defined(BOTAN_HAS_CHACHA_RNG)
657
         auto rng = Botan::ChaCha_RNG(Botan::system_rng());
1✔
658
   #else
659
         auto& rng = Botan::system_rng();
660
   #endif
661

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

664
         std::vector<size_t> indexes(testcases);
1✔
665
         std::iota(indexes.begin(), indexes.end(), size_t{0});
1✔
666

667
         std::vector<std::vector<uint64_t>> measurements(testcases);
1✔
668
         for(auto& m : measurements) {
5✔
669
            m.reserve(measurement_runs);
4✔
670
         }
671

672
         // This is only set differently if we exit early from the loop
673
         size_t runs_completed = measurement_runs;
1✔
674

675
         std::vector<uint8_t> ciphertext(modulus_bytes);
1✔
676

677
         for(size_t r = 0; r != measurement_runs; ++r) {
33✔
678
            if(r > 0 && report_every > 0 && (r % report_every) == 0) {
32✔
679
               std::cerr << "Gathering sample # " << r << "\n";
×
680
            }
681

682
            shuffle_idx(indexes, rng);
32✔
683

684
            for(const size_t testcase : indexes) {
160✔
685
               // Load the test ciphertext in constant time to avoid cache pollution
686
               for(size_t j = 0; j != testcases; ++j) {
640✔
687
                  const auto j_eq_testcase = Botan::CT::Mask<size_t>::is_equal(j, testcase).as_choice();
512✔
688
                  const auto* testcase_j = &ciphertext_data[j * modulus_bytes];
512✔
689
                  Botan::CT::conditional_assign_mem(j_eq_testcase, ciphertext.data(), testcase_j, modulus_bytes);
1,024✔
690
               }
691

692
               const TimingTestTimer timer;
128✔
693
               op.decrypt_or_random(ciphertext.data(), modulus_bytes, expect_pt_len, rng);
128✔
694
               const uint64_t duration = timer.complete();
128✔
695
               BOTAN_ASSERT_NOMSG(measurements[testcase].size() == r);
128✔
696
               measurements[testcase].push_back(duration);
128✔
697
            }
698

699
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1)
700
            // Early exit check
701
            if(g_sigint_recv != 0) {
32✔
702
               std::cerr << "Exiting early after " << r << " measurements\n";
×
703
               runs_completed = r;
704
               break;
705
            }
706
   #endif
707
         }
708

709
         report_results(test_results_file, names, measurements, runs_completed, output_nsec);
1✔
710
      }
3✔
711

712
   private:
713
      static void report_results(std::ostream& output,
1✔
714
                                 std::span<const std::string> names,
715
                                 std::span<const std::vector<uint64_t>> measurements,
716
                                 size_t runs_completed,
717
                                 bool output_nsec) {
718
         for(size_t t = 0; t != names.size(); ++t) {
5✔
719
            if(t > 0) {
4✔
720
               output << ",";
3✔
721
            }
722
            output << names[t];
4✔
723
         }
724
         output << "\n";
1✔
725

726
         for(size_t r = 0; r != runs_completed; ++r) {
33✔
727
            for(size_t t = 0; t != names.size(); ++t) {
160✔
728
               if(t > 0) {
128✔
729
                  output << ",";
96✔
730
               }
731

732
               const uint64_t dur_nsec = measurements[t][r];
128✔
733
               if(output_nsec) {
128✔
734
                  output << dur_nsec;
×
735
               } else {
736
                  const double dur_s = static_cast<double>(dur_nsec) / 1000000000.0;
128✔
737
                  output << dur_s;
128✔
738
               }
739
            }
740
            output << "\n";
32✔
741
         }
742
      }
1✔
743

744
      static size_t parse_runs_arg(const std::string& param) {
1✔
745
         if(param.starts_with("-")) {
1✔
746
            throw CLI_Usage_Error("Cannot have a negative run count");
×
747
         }
748

749
         if(param.ends_with("m") || param.ends_with("M")) {
1✔
750
            return parse_runs_arg(param.substr(0, param.size() - 1)) * 1'000'000;
×
751
         } else if(param.ends_with("k") || param.ends_with("K")) {
1✔
752
            return parse_runs_arg(param.substr(0, param.size() - 1)) * 1'000;
×
753
         } else {
754
            try {
1✔
755
               return static_cast<size_t>(std::stoul(param));
1✔
756
            } catch(std::exception&) {
×
757
               throw CLI_Usage_Error("Unexpected syntax for --runs option (try 1000, 1K, or 2M)");
×
758
            }
×
759
         }
760
      }
761
};
762

763
BOTAN_REGISTER_COMMAND("marvin_test", MARVIN_Test_Command);
2✔
764

765
#endif
766

767
}  // namespace
768

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