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

randombit / botan / 11844561993

14 Nov 2024 07:58PM UTC coverage: 91.178% (+0.1%) from 91.072%
11844561993

Pull #4435

github

web-flow
Merge 81dcb29da into e430f157a
Pull Request #4435: Test duration values ​​are now presented in seconds with six digits of precision. Tests without time measurements have been edited.

91856 of 100744 relevant lines covered (91.18%)

9311006.71 hits per line

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

85.29
/src/tests/test_rng_behavior.cpp
1
/*
2
* (C) 2014,2015,2017 Jack Lloyd
3
* (C) 2016 René Korthaus, Rohde & Schwarz Cybersecurity
4
*
5
* Botan is released under the Simplified BSD License (see license.txt)
6
*/
7

8
#include "test_rng.h"
9
#include "tests.h"
10

11
#if defined(BOTAN_HAS_STATEFUL_RNG)
12
   #include <botan/stateful_rng.h>
13
#endif
14

15
#if defined(BOTAN_HAS_HMAC_DRBG)
16
   #include <botan/hmac_drbg.h>
17
#endif
18

19
#if defined(BOTAN_HAS_AUTO_RNG)
20
   #include <botan/auto_rng.h>
21
#endif
22

23
#if defined(BOTAN_HAS_CHACHA_RNG)
24
   #include <botan/chacha_rng.h>
25
#endif
26

27
#if defined(BOTAN_HAS_SYSTEM_RNG)
28
   #include <botan/system_rng.h>
29
#endif
30

31
#if defined(BOTAN_HAS_PROCESSOR_RNG)
32
   #include <botan/processor_rng.h>
33
#endif
34

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

39
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
40
   #include <sys/wait.h>
41
   #include <unistd.h>
42
#endif
43

44
namespace Botan_Tests {
45

46
namespace {
47

48
#if defined(BOTAN_HAS_STATEFUL_RNG)
49

50
class Stateful_RNG_Tests : public Test {
2✔
51
   public:
52
      std::vector<Test::Result> run() override {
2✔
53
         std::vector<Test::Result> results;
2✔
54
         results.push_back(test_reseed_kat());
4✔
55
         results.push_back(test_reseed());
4✔
56
         results.push_back(test_reseed_interval_limits());
4✔
57
         results.push_back(test_max_number_of_bytes_per_request());
4✔
58
         results.push_back(test_broken_entropy_input());
4✔
59
         results.push_back(test_check_nonce());
4✔
60
         results.push_back(test_prediction_resistance());
4✔
61
         results.push_back(test_randomize_with_ts_input());
4✔
62
         results.push_back(test_security_level());
4✔
63
         results.push_back(test_input_output_edge_cases());
4✔
64

65
         /*
66
         * This test uses the library in both parent and child processes. But
67
         * this causes a race with other threads, where if any other test thread
68
         * is holding the mlock pool mutex, it is killed after the fork. Then,
69
         * in the child, any attempt to allocate or free memory will cause a
70
         * deadlock.
71
         */
72
         if(Test::options().test_threads() == 1) {
2✔
73
            results.push_back(test_fork_safety());
×
74
         }
75

76
         return results;
2✔
77
      }
×
78

79
   protected:
80
      virtual std::string rng_name() const = 0;
81

82
      virtual std::unique_ptr<Botan::Stateful_RNG> create_rng(Botan::RandomNumberGenerator* underlying_rng,
83
                                                              Botan::Entropy_Sources* underlying_es,
84
                                                              size_t reseed_interval) = 0;
85

86
      std::unique_ptr<Botan::Stateful_RNG> make_rng(Botan::RandomNumberGenerator& underlying_rng,
14✔
87
                                                    size_t reseed_interval = 1024) {
88
         return create_rng(&underlying_rng, nullptr, reseed_interval);
14✔
89
      }
90

91
      std::unique_ptr<Botan::Stateful_RNG> make_rng(Botan::Entropy_Sources& underlying_srcs,
4✔
92
                                                    size_t reseed_interval = 1024) {
93
         return create_rng(nullptr, &underlying_srcs, reseed_interval);
4✔
94
      }
95

96
      std::unique_ptr<Botan::Stateful_RNG> make_rng(Botan::RandomNumberGenerator& underlying_rng,
6✔
97
                                                    Botan::Entropy_Sources& underlying_srcs,
98
                                                    size_t reseed_interval = 1024) {
99
         return create_rng(&underlying_rng, &underlying_srcs, reseed_interval);
6✔
100
      }
101

102
      virtual Test::Result test_reseed_kat() = 0;
103

104
      virtual Test::Result test_security_level() = 0;
105

106
      virtual Test::Result test_max_number_of_bytes_per_request() = 0;
107

108
      virtual Test::Result test_reseed_interval_limits() = 0;
109

110
   private:
111
      Test::Result test_reseed() {
2✔
112
         Test::Result result(rng_name() + " Reseed");
4✔
113
         result.start_timer();
2✔
114

115
         // test reseed_interval is enforced
116
         Request_Counting_RNG counting_rng;
2✔
117

118
         auto rng = make_rng(counting_rng, 2);
2✔
119

120
         rng->random_vec(7);
2✔
121
         result.test_eq("initial seeding", counting_rng.randomize_count(), 1);
2✔
122
         rng->random_vec(9);
2✔
123
         result.test_eq("still initial seed", counting_rng.randomize_count(), 1);
2✔
124

125
         rng->random_vec(1);
2✔
126
         result.test_eq("first reseed", counting_rng.randomize_count(), 2);
2✔
127
         rng->random_vec(15);
2✔
128
         result.test_eq("still first reseed", counting_rng.randomize_count(), 2);
2✔
129

130
         rng->random_vec(15);
2✔
131
         result.test_eq("second reseed", counting_rng.randomize_count(), 3);
2✔
132
         rng->random_vec(1);
2✔
133
         result.test_eq("still second reseed", counting_rng.randomize_count(), 3);
2✔
134

135
         if(rng->max_number_of_bytes_per_request() > 0) {
2✔
136
            // request > max_number_of_bytes_per_request, do reseeds occur?
137
            rng->random_vec(64 * 1024 + 1);
1✔
138
            result.test_eq("request exceeds output limit", counting_rng.randomize_count(), 4);
1✔
139

140
            rng->random_vec(9 * 64 * 1024 + 1);
1✔
141
            result.test_eq("request exceeds output limit", counting_rng.randomize_count(), 9);
2✔
142
         }
143

144
         result.end_timer();
2✔
145
         return result;
4✔
146
      }
2✔
147

148
      Test::Result test_broken_entropy_input() {
2✔
149
         Test::Result result(rng_name() + " Broken Entropy Input");
4✔
150
         result.start_timer();
2✔
151

152
         class Broken_Entropy_Source final : public Botan::Entropy_Source {
2✔
153
            public:
154
               std::string name() const override { return "Broken Entropy Source"; }
×
155

156
               size_t poll(Botan::RandomNumberGenerator& /*rng*/) override {
4✔
157
                  throw Botan::Not_Implemented("polling not available");
4✔
158
               }
159
         };
160

161
         class Insufficient_Entropy_Source final : public Botan::Entropy_Source {
2✔
162
            public:
163
               std::string name() const override { return "Insufficient Entropy Source"; }
×
164

165
               size_t poll(Botan::RandomNumberGenerator& /*rng*/) override { return 0; }
2✔
166
         };
167

168
         // make sure no output is generated when the entropy input source is broken
169

170
         // underlying_rng throws exception
171
         Botan::Null_RNG broken_entropy_input_rng;
2✔
172
         result.test_eq("Null_RNG not seeded", broken_entropy_input_rng.is_seeded(), false);
2✔
173
         auto rng_with_broken_rng = make_rng(broken_entropy_input_rng);
2✔
174

175
         result.test_throws("broken underlying rng", [&rng_with_broken_rng]() { rng_with_broken_rng->random_vec(16); });
6✔
176

177
         // entropy_sources throw exception
178
         auto broken_entropy_source_1 = std::make_unique<Broken_Entropy_Source>();
2✔
179
         auto broken_entropy_source_2 = std::make_unique<Broken_Entropy_Source>();
2✔
180

181
         Botan::Entropy_Sources broken_entropy_sources;
2✔
182
         broken_entropy_sources.add_source(std::move(broken_entropy_source_1));
2✔
183
         broken_entropy_sources.add_source(std::move(broken_entropy_source_2));
2✔
184

185
         auto rng_with_broken_es = make_rng(broken_entropy_sources);
2✔
186
         result.test_throws("broken entropy sources", [&rng_with_broken_es]() { rng_with_broken_es->random_vec(16); });
6✔
187

188
         // entropy source returns insufficient entropy
189
         Botan::Entropy_Sources insufficient_entropy_sources;
2✔
190
         auto insufficient_entropy_source = std::make_unique<Insufficient_Entropy_Source>();
2✔
191
         insufficient_entropy_sources.add_source(std::move(insufficient_entropy_source));
2✔
192

193
         auto rng_with_insufficient_es = make_rng(insufficient_entropy_sources);
2✔
194
         result.test_throws("insufficient entropy source",
4✔
195
                            [&rng_with_insufficient_es]() { rng_with_insufficient_es->random_vec(16); });
4✔
196

197
         // one of or both underlying_rng and entropy_sources throw exception
198

199
         auto rng_with_broken_rng_and_good_es =
2✔
200
            make_rng(broken_entropy_input_rng, Botan::Entropy_Sources::global_sources());
2✔
201

202
         result.test_throws("broken underlying rng but good entropy sources",
4✔
203
                            [&rng_with_broken_rng_and_good_es]() { rng_with_broken_rng_and_good_es->random_vec(16); });
4✔
204

205
         auto rng_with_good_rng_and_broken_es = make_rng(this->rng(), broken_entropy_sources);
2✔
206

207
         result.test_throws("good underlying rng but broken entropy sources",
4✔
208
                            [&rng_with_good_rng_and_broken_es]() { rng_with_good_rng_and_broken_es->random_vec(16); });
4✔
209

210
         auto rng_with_broken_rng_and_broken_es = make_rng(broken_entropy_input_rng, broken_entropy_sources);
2✔
211

212
         result.test_throws("underlying rng and entropy sources broken", [&rng_with_broken_rng_and_broken_es]() {
4✔
213
            rng_with_broken_rng_and_broken_es->random_vec(16);
2✔
214
         });
×
215

216
         result.end_timer();
2✔
217
         return result;
4✔
218
      }
12✔
219

220
      Test::Result test_check_nonce() {
2✔
221
         Test::Result result(rng_name() + " Nonce Check");
4✔
222
         result.start_timer();
2✔
223

224
         // make sure the nonce has at least security_strength bits
225
         auto rng = create_rng(nullptr, nullptr, 0);
2✔
226

227
         for(size_t nonce_size : {0, 4, 8, 16, 31, 32, 34, 64}) {
18✔
228
            rng->clear();
16✔
229
            result.test_eq("not seeded", rng->is_seeded(), false);
16✔
230

231
            const std::vector<uint8_t> nonce(nonce_size);
16✔
232
            rng->initialize_with(nonce.data(), nonce.size());
16✔
233

234
            if(nonce_size < rng->security_level() / 8) {
16✔
235
               result.test_eq("not seeded", rng->is_seeded(), false);
10✔
236
               result.test_throws("invalid nonce size", [&rng]() { rng->random_vec(32); });
40✔
237
            } else {
238
               result.test_eq("is seeded", rng->is_seeded(), true);
6✔
239
               rng->random_vec(32);
12✔
240
            }
241
         }
16✔
242

243
         result.end_timer();
2✔
244
         return result;
2✔
245
      }
2✔
246

247
      Test::Result test_prediction_resistance() {
2✔
248
         Test::Result result(rng_name() + " Prediction Resistance");
4✔
249
         result.start_timer();
2✔
250

251
         // set reseed_interval = 1, forcing a reseed for every RNG request
252
         Request_Counting_RNG counting_rng;
2✔
253
         auto rng = make_rng(counting_rng, 1);
2✔
254

255
         rng->random_vec(16);
2✔
256
         result.test_eq("first request", counting_rng.randomize_count(), size_t(1));
2✔
257

258
         rng->random_vec(16);
2✔
259
         result.test_eq("second request", counting_rng.randomize_count(), size_t(2));
2✔
260

261
         rng->random_vec(16);
2✔
262
         result.test_eq("third request", counting_rng.randomize_count(), size_t(3));
2✔
263

264
         result.end_timer();
2✔
265
         return result;
4✔
266
      }
2✔
267

268
      Test::Result test_fork_safety() {
×
269
         Test::Result result(rng_name() + " Fork Safety");
×
270
         result.start_timer();
×
271

272
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1)
273
         const size_t reseed_interval = 1024;
×
274

275
         // make sure rng is reseeded after every fork
276
         Request_Counting_RNG counting_rng;
×
277
         auto rng = make_rng(counting_rng, reseed_interval);
×
278

279
         rng->random_vec(16);
×
280
         result.test_eq("first request", counting_rng.randomize_count(), size_t(1));
×
281

282
         // fork and request from parent and child, both should output different sequences
283
         size_t count = counting_rng.randomize_count();
×
284
         Botan::secure_vector<uint8_t> parent_bytes(16), child_bytes(16);
×
285
         int fd[2];
×
286
         int rc = ::pipe(fd);
×
287
         if(rc != 0) {
×
288
            result.test_failure("failed to create pipe");
×
289
         }
290

291
         pid_t pid = ::fork();
×
292
         if(pid == -1) {
×
293
      #if defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
294
            result.test_note("failed to fork process");
295
      #else
296
            result.test_failure("failed to fork process");
×
297
      #endif
298
            return result;
×
299
         } else if(pid != 0) {
×
300
            // parent process, wait for randomize_count from child's rng
301
            ::close(fd[1]);  // close write end in parent
×
302
            ssize_t got = ::read(fd[0], &count, sizeof(count));
×
303

304
            if(got > 0) {
×
305
               result.test_eq("expected bytes from child", got, sizeof(count));
×
306
               result.test_eq("parent not reseeded", counting_rng.randomize_count(), 1);
×
307
               result.test_eq("child reseed occurred", count, 2);
×
308
            } else {
309
               result.test_failure("Failed to read count size from child process");
×
310
            }
311

312
            parent_bytes = rng->random_vec(16);
×
313
            got = ::read(fd[0], &child_bytes[0], child_bytes.size());
×
314

315
            if(got > 0) {
×
316
               result.test_eq("expected bytes from child", got, child_bytes.size());
×
317
               result.test_ne("parent and child output sequences differ", parent_bytes, child_bytes);
×
318
            } else {
319
               result.test_failure("Failed to read RNG bytes from child process");
×
320
            }
321
            ::close(fd[0]);  // close read end in parent
×
322

323
            // wait for the child to exit
324
            int status = 0;
×
325
            ::waitpid(pid, &status, 0);
×
326
         } else {
327
            // child process, send randomize_count and first output sequence back to parent
328
            ::close(fd[0]);  // close read end in child
×
329
            rng->randomize(&child_bytes[0], child_bytes.size());
×
330
            count = counting_rng.randomize_count();
×
331
            ssize_t written = ::write(fd[1], &count, sizeof(count));
×
332
            BOTAN_UNUSED(written);
×
333
            try {
×
334
               rng->randomize(&child_bytes[0], child_bytes.size());
×
335
            } catch(std::exception& e) {
×
336
               static_cast<void>(fprintf(stderr, "%s", e.what()));
×
337
            }
×
338
            written = ::write(fd[1], &child_bytes[0], child_bytes.size());
×
339
            BOTAN_UNUSED(written);
×
340
            ::close(fd[1]);  // close write end in child
×
341

342
            /*
343
            * We can't call exit because it causes the mlock pool to be freed (#602)
344
            * We can't call _exit because it makes valgrind think we leaked memory.
345
            * So instead we execute something that will return 0 for us.
346
            */
347
            ::execl("/bin/true", "true", NULL);
×
348
            ::_exit(0);  // just in case /bin/true isn't available (sandbox?)
×
349
         }
350
   #endif
351
         result.end_timer();
×
352
         return result;
353
      }
×
354

355
      Test::Result test_randomize_with_ts_input() {
2✔
356
         Test::Result result(rng_name() + " Randomize With Timestamp Input");
4✔
357
         result.start_timer();
2✔
358

359
         const size_t request_bytes = 64;
2✔
360
         const std::vector<uint8_t> seed(128);
2✔
361

362
         // check that randomize_with_ts_input() creates different output based on a timestamp
363
         // and possibly additional data, such as process id even with identical seeds
364
         Fixed_Output_RNG fixed_output_rng1(seed);
2✔
365
         Fixed_Output_RNG fixed_output_rng2(seed);
2✔
366

367
         auto rng1 = make_rng(fixed_output_rng1);
2✔
368
         auto rng2 = make_rng(fixed_output_rng2);
2✔
369

370
         Botan::secure_vector<uint8_t> output1(request_bytes);
2✔
371
         Botan::secure_vector<uint8_t> output2(request_bytes);
2✔
372

373
         rng1->randomize(output1.data(), output1.size());
2✔
374
         rng2->randomize(output2.data(), output2.size());
2✔
375

376
         result.test_eq("equal output due to same seed", output1, output2);
2✔
377

378
         rng1->randomize_with_ts_input(output1.data(), output1.size());
2✔
379
         rng2->randomize_with_ts_input(output2.data(), output2.size());
2✔
380

381
         result.test_ne("output differs due to different timestamp", output1, output2);
4✔
382

383
         result.end_timer();
2✔
384
         return result;
2✔
385
      }
10✔
386

387
      Test::Result test_input_output_edge_cases() {
2✔
388
         Test::Result result(rng_name() + " randomize");
4✔
389
         result.start_timer();
2✔
390

391
         const std::vector<uint8_t> seed(128);
2✔
392
         Fixed_Output_RNG fixed_output_rng(seed);
2✔
393

394
         auto rng = make_rng(fixed_output_rng);
2✔
395

396
         for(size_t i = 0; i != 4096; ++i) {
8,194✔
397
            std::vector<uint8_t> buf(i);
8,192✔
398
            rng->randomize(buf.data(), buf.size());
8,192✔
399
            rng->add_entropy(buf.data(), buf.size());
8,192✔
400

401
            result.test_success("RNG accepted input and output length");
16,384✔
402
         }
8,192✔
403

404
         result.end_timer();
2✔
405
         return result;
2✔
406
      }
4✔
407
};
408

409
#endif
410

411
#if defined(BOTAN_HAS_HMAC_DRBG) && defined(BOTAN_HAS_SHA2_32)
412

413
class HMAC_DRBG_Unit_Tests final : public Stateful_RNG_Tests {
×
414
   public:
415
      std::string rng_name() const override { return "HMAC_DRBG"; }
6✔
416

417
      std::unique_ptr<Botan::Stateful_RNG> create_rng(Botan::RandomNumberGenerator* underlying_rng,
13✔
418
                                                      Botan::Entropy_Sources* underlying_es,
419
                                                      size_t reseed_interval) override {
420
         std::unique_ptr<Botan::MessageAuthenticationCode> mac =
13✔
421
            Botan::MessageAuthenticationCode::create("HMAC(SHA-256)");
13✔
422

423
         if(underlying_rng && underlying_es) {
13✔
424
            return std::make_unique<Botan::HMAC_DRBG>(std::move(mac), *underlying_rng, *underlying_es, reseed_interval);
3✔
425
         } else if(underlying_rng) {
10✔
426
            return std::make_unique<Botan::HMAC_DRBG>(std::move(mac), *underlying_rng, reseed_interval);
7✔
427
         } else if(underlying_es) {
3✔
428
            return std::make_unique<Botan::HMAC_DRBG>(std::move(mac), *underlying_es, reseed_interval);
2✔
429
         } else if(reseed_interval == 0) {
1✔
430
            return std::make_unique<Botan::HMAC_DRBG>(std::move(mac));
1✔
431
         } else {
432
            throw Test_Error("Invalid reseed interval in HMAC_DRBG unit test");
×
433
         }
434
      }
13✔
435

436
      Test::Result test_max_number_of_bytes_per_request() override {
1✔
437
         Test::Result result("HMAC_DRBG max_number_of_bytes_per_request");
1✔
438
         result.start_timer();
1✔
439

440
         const std::string mac_string = "HMAC(SHA-256)";
1✔
441

442
         Request_Counting_RNG counting_rng;
1✔
443

444
         result.test_throws(
2✔
445
            "HMAC_DRBG does not accept 0 for max_number_of_bytes_per_request", [&mac_string, &counting_rng]() {
1✔
446
               Botan::HMAC_DRBG failing_rng(Botan::MessageAuthenticationCode::create(mac_string), counting_rng, 2, 0);
1✔
447
            });
×
448

449
         result.test_throws("HMAC_DRBG does not accept values higher than 64KB for max_number_of_bytes_per_request",
2✔
450
                            [&mac_string, &counting_rng]() {
1✔
451
                               Botan::HMAC_DRBG failing_rng(
1✔
452
                                  Botan::MessageAuthenticationCode::create(mac_string), counting_rng, 2, 64 * 1024 + 1);
1✔
453
                            });
×
454

455
         // set reseed_interval to 1 so we can test that a long request is split
456
         // into multiple, max_number_of_bytes_per_request long requests
457
         // for each smaller request, reseed_check() calls counting_rng::randomize(),
458
         // which we can compare with
459
         Botan::HMAC_DRBG rng(Botan::MessageAuthenticationCode::create(mac_string), counting_rng, 1, 64);
1✔
460

461
         rng.random_vec(63);
1✔
462
         result.test_eq("one request", counting_rng.randomize_count(), 1);
1✔
463

464
         rng.clear();
1✔
465
         counting_rng.clear();
1✔
466

467
         rng.random_vec(64);
1✔
468
         result.test_eq("one request", counting_rng.randomize_count(), 1);
1✔
469

470
         rng.clear();
1✔
471
         counting_rng.clear();
1✔
472

473
         rng.random_vec(65);
1✔
474
         result.test_eq("two requests", counting_rng.randomize_count(), 2);
1✔
475

476
         rng.clear();
1✔
477
         counting_rng.clear();
1✔
478

479
         rng.random_vec(1025);
1✔
480
         result.test_eq("17 requests", counting_rng.randomize_count(), 17);
1✔
481

482
         result.end_timer();
1✔
483
         return result;
2✔
484
      }
1✔
485

486
      Test::Result test_reseed_interval_limits() override {
1✔
487
         Test::Result result("HMAC_DRBG reseed_interval limits");
1✔
488
         result.start_timer();
1✔
489

490
         const std::string mac_string = "HMAC(SHA-256)";
1✔
491

492
         Request_Counting_RNG counting_rng;
1✔
493

494
         result.test_throws("HMAC_DRBG does not accept 0 for reseed_interval", [&mac_string, &counting_rng]() {
2✔
495
            Botan::HMAC_DRBG failing_rng(Botan::MessageAuthenticationCode::create(mac_string), counting_rng, 0);
1✔
496
         });
×
497

498
         result.test_throws("HMAC_DRBG does not accept values higher than 2^24 for reseed_interval",
2✔
499
                            [&mac_string, &counting_rng]() {
1✔
500
                               Botan::HMAC_DRBG failing_rng(Botan::MessageAuthenticationCode::create(mac_string),
2✔
501
                                                            counting_rng,
1✔
502
                                                            (static_cast<size_t>(1) << 24) + 1);
1✔
503
                            });
×
504

505
         result.end_timer();
1✔
506
         return result;
1✔
507
      }
1✔
508

509
      Test::Result test_security_level() override {
1✔
510
         Test::Result result("HMAC_DRBG Security Level");
1✔
511
         result.start_timer();
1✔
512

513
         std::vector<std::string> approved_hash_fns{"SHA-1", "SHA-224", "SHA-256", "SHA-512/256", "SHA-384", "SHA-512"};
7✔
514
         std::vector<uint32_t> security_strengths{128, 192, 256, 256, 256, 256};
2✔
515

516
         for(size_t i = 0; i < approved_hash_fns.size(); ++i) {
7✔
517
            std::string hash_fn = approved_hash_fns[i];
6✔
518
            std::string mac_name = "HMAC(" + hash_fn + ")";
12✔
519
            auto mac = Botan::MessageAuthenticationCode::create(mac_name);
6✔
520
            if(!mac) {
6✔
521
               result.note_missing(mac_name);
1✔
522
               continue;
1✔
523
            }
524

525
            Botan::HMAC_DRBG rng(std::move(mac));
5✔
526
            result.test_eq(hash_fn + " security level", rng.security_level(), security_strengths[i]);
5✔
527
         }
6✔
528

529
         result.end_timer();
1✔
530
         return result;
1✔
531
      }
3✔
532

533
      Test::Result test_reseed_kat() override {
1✔
534
         Test::Result result("HMAC_DRBG Reseed KAT");
1✔
535
         result.start_timer();
1✔
536

537
         Request_Counting_RNG counting_rng;
1✔
538
         auto rng = make_rng(counting_rng, 2);
1✔
539

540
         const Botan::secure_vector<uint8_t> seed_input(
1✔
541
            {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF,
542
             0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF});
1✔
543

544
         result.test_eq("is_seeded", rng->is_seeded(), false);
1✔
545

546
         rng->initialize_with(seed_input.data(), seed_input.size());
1✔
547

548
         Botan::secure_vector<uint8_t> out(32);
1✔
549

550
         rng->randomize(out.data(), out.size());
1✔
551
         result.test_eq("underlying RNG calls", counting_rng.randomize_count(), size_t(0));
1✔
552
         result.test_eq("out before reseed", out, "48D3B45AAB65EF92CCFCB9427EF20C90297065ECC1B8A525BFE4DC6FF36D0E38");
1✔
553

554
         // reseed must happen here
555
         rng->randomize(out.data(), out.size());
1✔
556
         result.test_eq("underlying RNG calls", counting_rng.randomize_count(), size_t(1));
1✔
557
         result.test_eq("out after reseed", out, "2F8FCA696832C984781123FD64F4B20C7379A25C87AB29A21C9BF468B0081CE2");
1✔
558

559
         result.end_timer();
1✔
560
         return result;
2✔
561
      }
3✔
562
};
563

564
std::vector<Test::Result> hmac_drbg_multiple_requests() {
1✔
565
   auto null_rng = Botan::Null_RNG();
1✔
566
   constexpr auto rng_max_output = 1024;
1✔
567
   const auto seed = Botan::hex_decode("deadbeefbaadcafedeadbeefbaadcafedeadbeefbaadcafedeadbeefbaadcafe");
1✔
568

569
   auto make_seeded_rng = [&](size_t reseed_interval) {
5✔
570
      auto rng = std::make_unique<Botan::HMAC_DRBG>(Botan::MessageAuthenticationCode::create("HMAC(SHA-256)"),
×
571
                                                    null_rng,
572
                                                    reseed_interval + 1 /* off by one */,
8✔
573
                                                    rng_max_output);
4✔
574
      rng->add_entropy(seed);
4✔
575
      return rng;
4✔
576
   };
×
577

578
   return {CHECK("bulk and split output without input",
1✔
579
                 [&](auto& result) {
1✔
580
                    result.start_timer();
1✔
581

582
                    auto rng1 = make_seeded_rng(2);
1✔
583
                    auto rng2 = make_seeded_rng(2);
1✔
584

585
                    result.confirm("RNG 1 is seeded and ready to go", rng1->is_seeded());
2✔
586
                    result.confirm("RNG 2 is seeded and ready to go", rng2->is_seeded());
2✔
587

588
                    auto bulk = rng1->random_vec<std::vector<uint8_t>>(2 * rng_max_output);
1✔
589

590
                    auto split1 = rng2->random_vec<std::vector<uint8_t>>(rng_max_output);
1✔
591
                    auto split2 = rng2->random_vec<std::vector<uint8_t>>(rng_max_output);
1✔
592
                    split1.insert(split1.end(), split2.begin(), split2.end());
1✔
593

594
                    result.test_eq("Output is equal, regardless bulk request", bulk, split1);
1✔
595

596
                    result.end_timer();
1✔
597
                    return result;
2✔
598
                 }),
3✔
599

600
           CHECK("bulk and split output with input", [&](auto& result) {
1✔
601
              result.start_timer();
1✔
602
              auto rng1 = make_seeded_rng(3);
1✔
603
              auto rng2 = make_seeded_rng(3);
1✔
604

605
              result.confirm("RNG 1 is seeded and ready to go", rng1->is_seeded());
2✔
606
              result.confirm("RNG 2 is seeded and ready to go", rng2->is_seeded());
2✔
607

608
              std::vector<uint8_t> bulk(3 * rng_max_output);
1✔
609
              rng1->randomize_with_input(bulk, seed);
2✔
610

611
              std::vector<uint8_t> split(3 * rng_max_output);
1✔
612
              std::span<uint8_t> split_span(split);
1✔
613
              rng2->randomize_with_input(split_span.subspan(0, rng_max_output), seed);
2✔
614
              rng2->randomize_with_input(split_span.subspan(rng_max_output, rng_max_output), {});
2✔
615
              rng2->randomize_with_input(split_span.subspan(2 * rng_max_output), {});
2✔
616

617
              result.test_eq("Output is equal, regardless bulk request", bulk, split);
1✔
618

619
              result.end_timer();
1✔
620
              return result;
2✔
621
           })};
6✔
622
}
2✔
623

624
BOTAN_REGISTER_TEST("rng", "hmac_drbg_unit", HMAC_DRBG_Unit_Tests);
625
BOTAN_REGISTER_TEST_FN("rng", "hmac_drbg_multi_requst", hmac_drbg_multiple_requests);
626

627
#endif
628

629
#if defined(BOTAN_HAS_CHACHA_RNG)
630

631
class ChaCha_RNG_Unit_Tests final : public Stateful_RNG_Tests {
×
632
   public:
633
      std::string rng_name() const override { return "ChaCha_RNG"; }
6✔
634

635
      std::unique_ptr<Botan::Stateful_RNG> create_rng(Botan::RandomNumberGenerator* underlying_rng,
13✔
636
                                                      Botan::Entropy_Sources* underlying_es,
637
                                                      size_t reseed_interval) override {
638
         if(underlying_rng && underlying_es) {
13✔
639
            return std::make_unique<Botan::ChaCha_RNG>(*underlying_rng, *underlying_es, reseed_interval);
3✔
640
         } else if(underlying_rng) {
10✔
641
            return std::make_unique<Botan::ChaCha_RNG>(*underlying_rng, reseed_interval);
7✔
642
         } else if(underlying_es) {
3✔
643
            return std::make_unique<Botan::ChaCha_RNG>(*underlying_es, reseed_interval);
2✔
644
         } else if(reseed_interval == 0) {
1✔
645
            return std::make_unique<Botan::ChaCha_RNG>();
1✔
646
         } else {
647
            throw Test_Error("Invalid reseed interval in ChaCha_RNG unit test");
×
648
         }
649
      }
650

651
      Test::Result test_security_level() override {
1✔
652
         Test::Result result("ChaCha_RNG Security Level");
1✔
653
         result.start_timer();
1✔
654
         Botan::ChaCha_RNG rng;
1✔
655
         result.test_eq("Expected security level", rng.security_level(), size_t(256));
1✔
656
         result.end_timer();
1✔
657
         return result;
1✔
658
      }
1✔
659

660
      Test::Result test_max_number_of_bytes_per_request() override {
1✔
661
         Test::Result result("ChaCha_RNG max_number_of_bytes_per_request");
1✔
662
         result.start_timer();
1✔
663
         // ChaCha_RNG doesn't have this notion
664
         result.end_timer();
1✔
665
         return result;
1✔
666
      }
×
667

668
      Test::Result test_reseed_interval_limits() override {
1✔
669
         Test::Result result("ChaCha_RNG reseed_interval limits");
1✔
670
         result.start_timer();
1✔
671
         // ChaCha_RNG doesn't apply any limits to reseed_interval
672
         result.end_timer();
1✔
673
         return result;
1✔
674
      }
×
675

676
      Test::Result test_reseed_kat() override {
1✔
677
         Test::Result result("ChaCha_RNG Reseed KAT");
1✔
678
         result.start_timer();
1✔
679

680
         Request_Counting_RNG counting_rng;
1✔
681
         auto rng = make_rng(counting_rng, 2);
1✔
682

683
         const Botan::secure_vector<uint8_t> seed_input(32);
1✔
684

685
         result.test_eq("is_seeded", rng->is_seeded(), false);
1✔
686

687
         rng->initialize_with(seed_input.data(), seed_input.size());
1✔
688

689
         Botan::secure_vector<uint8_t> out(32);
1✔
690

691
         rng->randomize(out.data(), out.size());
1✔
692
         result.test_eq("underlying RNG calls", counting_rng.randomize_count(), size_t(0));
1✔
693
         result.test_eq("out before reseed", out, "1F0E6F13429D5073B59C057C37CBE9587740A0A894D247E2596C393CE91DDC6F");
1✔
694

695
         // reseed must happen here
696
         rng->randomize(out.data(), out.size());
1✔
697
         result.test_eq("underlying RNG calls", counting_rng.randomize_count(), size_t(1));
1✔
698
         result.test_eq("out after reseed", out, "F2CAE73F22684D5D773290B48FDCDA0E6C0661EBA0A854AFEC922832BDBB9C49");
1✔
699

700
         result.end_timer();
1✔
701
         return result;
2✔
702
      }
3✔
703
};
704

705
BOTAN_REGISTER_TEST("rng", "chacha_rng_unit", ChaCha_RNG_Unit_Tests);
706

707
#endif
708

709
#if defined(BOTAN_HAS_AUTO_RNG)
710

711
class AutoSeeded_RNG_Tests final : public Test {
×
712
   private:
713
      static Test::Result auto_rng_tests() {
1✔
714
         Test::Result result("AutoSeeded_RNG");
1✔
715
         result.start_timer();
1✔
716

717
         Botan::Entropy_Sources no_entropy_for_you;
1✔
718
         Botan::Null_RNG null_rng;
1✔
719

720
         result.test_eq("Null_RNG is null", null_rng.is_seeded(), false);
1✔
721

722
         try {
1✔
723
            Botan::AutoSeeded_RNG rng(no_entropy_for_you);
1✔
724
            result.test_failure("AutoSeeded_RNG should have rejected useless entropy source");
×
725
         } catch(Botan::PRNG_Unseeded&) {
1✔
726
            result.test_success("AutoSeeded_RNG rejected empty entropy source");
1✔
727
         }
1✔
728

729
         try {
1✔
730
            Botan::AutoSeeded_RNG rng(null_rng);
1✔
731
         } catch(Botan::PRNG_Unseeded&) {
1✔
732
            result.test_success("AutoSeeded_RNG rejected useless RNG");
1✔
733
         }
1✔
734

735
         try {
1✔
736
            Botan::AutoSeeded_RNG rng(null_rng, no_entropy_for_you);
1✔
737
         } catch(Botan::PRNG_Unseeded&) {
1✔
738
            result.test_success("AutoSeeded_RNG rejected useless RNG+entropy sources");
1✔
739
         }
1✔
740

741
         Botan::AutoSeeded_RNG rng;
1✔
742

743
         result.confirm("AutoSeeded_RNG::name", rng.name().starts_with("HMAC_DRBG(HMAC(SHA-"));
3✔
744

745
         result.confirm("AutoSeeded_RNG starts seeded", rng.is_seeded());
2✔
746
         rng.random_vec(16);  // generate and discard output
1✔
747
         rng.clear();
1✔
748
         result.test_eq("AutoSeeded_RNG unseeded after calling clear", rng.is_seeded(), false);
1✔
749

750
         // AutoSeeded_RNG automatically reseeds as required:
751
         rng.random_vec(16);
1✔
752
         result.confirm("AutoSeeded_RNG can be reseeded", rng.is_seeded());
2✔
753

754
         result.confirm("AutoSeeded_RNG ", rng.is_seeded());
2✔
755
         rng.random_vec(16);  // generate and discard output
1✔
756
         rng.clear();
1✔
757
         result.test_eq("AutoSeeded_RNG unseeded after calling clear", rng.is_seeded(), false);
1✔
758

759
         const size_t no_entropy_bits = rng.reseed(no_entropy_for_you, 256, std::chrono::milliseconds(300));
1✔
760
         result.test_eq("AutoSeeded_RNG can't reseed from nothing", no_entropy_bits, 0);
1✔
761
         result.test_eq("AutoSeeded_RNG still unseeded", rng.is_seeded(), false);
1✔
762

763
         rng.random_vec(16);  // generate and discard output
1✔
764
         result.confirm("AutoSeeded_RNG can be reseeded", rng.is_seeded());
2✔
765

766
         for(size_t i = 0; i != 4096; ++i) {
4,097✔
767
            std::vector<uint8_t> buf(i);
4,096✔
768
            rng.randomize(buf.data(), buf.size());
4,096✔
769
            rng.add_entropy(buf.data(), buf.size());
4,096✔
770

771
            result.test_success("AutoSeeded_RNG accepted input and output length");
8,192✔
772
         }
4,096✔
773

774
         rng.clear();
1✔
775

776
         result.end_timer();
1✔
777
         return result;
2✔
778
      }
1✔
779

780
   public:
781
      std::vector<Test::Result> run() override {
1✔
782
         std::vector<Test::Result> results;
1✔
783
         results.push_back(auto_rng_tests());
2✔
784
         return results;
1✔
785
      }
×
786
};
787

788
BOTAN_REGISTER_TEST("rng", "auto_rng_unit", AutoSeeded_RNG_Tests);
789

790
#endif
791

792
#if defined(BOTAN_HAS_SYSTEM_RNG)
793

794
class System_RNG_Tests final : public Test {
×
795
   public:
796
      std::vector<Test::Result> run() override {
1✔
797
         Test::Result result("System_RNG");
1✔
798
         result.start_timer();
1✔
799

800
         Botan::System_RNG rng;
1✔
801

802
         result.test_gte("Some non-empty name is returned", rng.name().size(), 1);
3✔
803

804
         result.confirm("System RNG always seeded", rng.is_seeded());
3✔
805
         rng.clear();  // clear is a noop for system rng
1✔
806
         result.confirm("System RNG always seeded", rng.is_seeded());
3✔
807

808
         rng.reseed(Botan::Entropy_Sources::global_sources(), 256, std::chrono::milliseconds(100));
1✔
809

810
         for(size_t i = 0; i != 128; ++i) {
129✔
811
            std::vector<uint8_t> out_buf(i);
128✔
812
            rng.randomize(out_buf.data(), out_buf.size());
128✔
813
            rng.add_entropy(out_buf.data(), out_buf.size());
128✔
814
         }
128✔
815

816
         if(Test::run_long_tests() && Test::run_memory_intensive_tests() && (sizeof(size_t) > 4)) {
1✔
817
            // Pass buffer with a size greater than 32bit
818
            const size_t size32BitsMax = std::numeric_limits<uint32_t>::max();
1✔
819
            const size_t checkSize = 1024;
1✔
820
            std::vector<uint8_t> large_buf(size32BitsMax + checkSize);
1✔
821
            std::memset(large_buf.data() + size32BitsMax, 0xFE, checkSize);
1✔
822

823
            rng.randomize(large_buf.data(), large_buf.size());
1✔
824

825
            std::vector<uint8_t> check_buf(checkSize, 0xFE);
1✔
826

827
            result.confirm("System RNG failed to write after 4GB boundry",
2✔
828
                           std::memcmp(large_buf.data() + size32BitsMax, check_buf.data(), checkSize) != 0);
1✔
829
         }
2✔
830

831
         result.end_timer();
1✔
832
         return std::vector<Test::Result>{result};
2✔
833
      }
2✔
834
};
835

836
BOTAN_REGISTER_TEST("rng", "system_rng", System_RNG_Tests);
837

838
#endif
839

840
#if defined(BOTAN_HAS_PROCESSOR_RNG)
841

842
class Processor_RNG_Tests final : public Test {
×
843
   public:
844
      std::vector<Test::Result> run() override {
1✔
845
         Test::Result result("Processor_RNG");
1✔
846
         result.start_timer();
1✔
847

848
         if(Botan::Processor_RNG::available()) {
1✔
849
            Botan::Processor_RNG rng;
1✔
850

851
            result.test_ne("Has a name", rng.name(), "");
2✔
852
            result.confirm("CPU RNG always seeded", rng.is_seeded());
2✔
853
            rng.clear();  // clear is a noop for rdrand
1✔
854
            result.confirm("CPU RNG always seeded", rng.is_seeded());
2✔
855

856
            size_t reseed_bits = rng.reseed(Botan::Entropy_Sources::global_sources(), 256, std::chrono::seconds(1));
1✔
857
            result.test_eq("CPU RNG cannot consume inputs", reseed_bits, size_t(0));
1✔
858

859
            /*
860
            Processor_RNG ignores add_entropy calls - confirm this by passing
861
            an invalid ptr/length field to add_entropy. If it examined its
862
            arguments, it would crash...
863
            */
864
            // NOLINTNEXTLINE(*-no-int-to-ptr)
865
            const uint8_t* invalid_ptr = reinterpret_cast<const uint8_t*>(static_cast<uintptr_t>(0xDEADC0DE));
1✔
866
            const size_t invalid_ptr_len = 64 * 1024;
1✔
867
            rng.add_entropy(invalid_ptr, invalid_ptr_len);
1✔
868

869
            for(size_t i = 0; i != 128; ++i) {
129✔
870
               std::vector<uint8_t> out_buf(i);
128✔
871
               rng.randomize(out_buf.data(), out_buf.size());
128✔
872
            }
128✔
873
         } else {
1✔
874
            result.test_throws("Processor_RNG throws if instruction not available", []() { Botan::Processor_RNG rng; });
×
875
         }
876

877
         result.end_timer();
1✔
878
         return std::vector<Test::Result>{result};
3✔
879
      }
2✔
880
};
881

882
BOTAN_REGISTER_TEST("rng", "processor_rng", Processor_RNG_Tests);
883

884
#endif
885

886
}  // namespace
887

888
}  // namespace Botan_Tests
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

© 2025 Coveralls, Inc