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

randombit / botan / 12735019797

12 Jan 2025 11:00AM UTC coverage: 91.244% (+0.005%) from 91.239%
12735019797

push

github

web-flow
Merge pull request #4525 from randombit/jack/entropy-is-optional

Let the entropy module be optional

93465 of 102434 relevant lines covered (91.24%)

11402871.62 hits per line

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

84.65
/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

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

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

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

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

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

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

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

143
         return result;
4✔
144
      }
2✔
145

146
      Test::Result test_broken_entropy_input() {
2✔
147
         Test::Result result(rng_name() + " Broken Entropy Input");
4✔
148

149
   #if defined(BOTAN_HAS_ENTROPY_SOURCE)
150
         class Broken_Entropy_Source final : public Botan::Entropy_Source {
2✔
151
            public:
152
               std::string name() const override { return "Broken Entropy Source"; }
×
153

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

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

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

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

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

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

176
   #if defined(BOTAN_HAS_ENTROPY_SOURCE)
177

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

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

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

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

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

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

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

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

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

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

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

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

218
         return result;
4✔
219
      }
12✔
220

221
      Test::Result test_check_nonce() {
2✔
222
         Test::Result result(rng_name() + " Nonce Check");
4✔
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
         return result;
2✔
244
      }
2✔
245

246
      Test::Result test_prediction_resistance() {
2✔
247
         Test::Result result(rng_name() + " Prediction Resistance");
4✔
248

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

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

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

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

262
         return result;
4✔
263
      }
2✔
264

265
      Test::Result test_fork_safety() {
×
266
         Test::Result result(rng_name() + " Fork Safety");
×
267

268
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1)
269
         const size_t reseed_interval = 1024;
×
270

271
         // make sure rng is reseeded after every fork
272
         Request_Counting_RNG counting_rng;
×
273
         auto rng = make_rng(counting_rng, reseed_interval);
×
274

275
         rng->random_vec(16);
×
276
         result.test_eq("first request", counting_rng.randomize_count(), size_t(1));
×
277

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

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

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

308
            parent_bytes = rng->random_vec(16);
×
309
            got = ::read(fd[0], &child_bytes[0], child_bytes.size());
×
310

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

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

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

350
      Test::Result test_randomize_with_ts_input() {
2✔
351
         Test::Result result(rng_name() + " Randomize With Timestamp Input");
4✔
352

353
         const size_t request_bytes = 64;
2✔
354
         const std::vector<uint8_t> seed(128);
2✔
355

356
         // check that randomize_with_ts_input() creates different output based on a timestamp
357
         // and possibly additional data, such as process id even with identical seeds
358
         Fixed_Output_RNG fixed_output_rng1(seed);
2✔
359
         Fixed_Output_RNG fixed_output_rng2(seed);
2✔
360

361
         auto rng1 = make_rng(fixed_output_rng1);
2✔
362
         auto rng2 = make_rng(fixed_output_rng2);
2✔
363

364
         Botan::secure_vector<uint8_t> output1(request_bytes);
2✔
365
         Botan::secure_vector<uint8_t> output2(request_bytes);
2✔
366

367
         rng1->randomize(output1.data(), output1.size());
2✔
368
         rng2->randomize(output2.data(), output2.size());
2✔
369

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

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

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

377
         return result;
2✔
378
      }
10✔
379

380
      Test::Result test_input_output_edge_cases() {
2✔
381
         Test::Result result(rng_name() + " randomize");
4✔
382

383
         const std::vector<uint8_t> seed(128);
2✔
384
         Fixed_Output_RNG fixed_output_rng(seed);
2✔
385

386
         auto rng = make_rng(fixed_output_rng);
2✔
387

388
         for(size_t i = 0; i != 4096; ++i) {
8,194✔
389
            std::vector<uint8_t> buf(i);
8,192✔
390
            rng->randomize(buf.data(), buf.size());
8,192✔
391
            rng->add_entropy(buf.data(), buf.size());
8,192✔
392

393
            result.test_success("RNG accepted input and output length");
16,384✔
394
         }
8,192✔
395

396
         return result;
2✔
397
      }
4✔
398
};
399

400
#endif
401

402
#if defined(BOTAN_HAS_HMAC_DRBG) && defined(BOTAN_HAS_SHA2_32)
403

404
class HMAC_DRBG_Unit_Tests final : public Stateful_RNG_Tests {
×
405
   public:
406
      std::string rng_name() const override { return "HMAC_DRBG"; }
6✔
407

408
      std::unique_ptr<Botan::Stateful_RNG> create_rng(Botan::RandomNumberGenerator* underlying_rng,
13✔
409
                                                      Botan::Entropy_Sources* underlying_es,
410
                                                      size_t reseed_interval) override {
411
         std::unique_ptr<Botan::MessageAuthenticationCode> mac =
13✔
412
            Botan::MessageAuthenticationCode::create("HMAC(SHA-256)");
13✔
413

414
         if(underlying_rng && underlying_es) {
13✔
415
            return std::make_unique<Botan::HMAC_DRBG>(std::move(mac), *underlying_rng, *underlying_es, reseed_interval);
3✔
416
         } else if(underlying_rng) {
10✔
417
            return std::make_unique<Botan::HMAC_DRBG>(std::move(mac), *underlying_rng, reseed_interval);
7✔
418
         } else if(underlying_es) {
3✔
419
            return std::make_unique<Botan::HMAC_DRBG>(std::move(mac), *underlying_es, reseed_interval);
2✔
420
         } else if(reseed_interval == 0) {
1✔
421
            return std::make_unique<Botan::HMAC_DRBG>(std::move(mac));
1✔
422
         } else {
423
            throw Test_Error("Invalid reseed interval in HMAC_DRBG unit test");
×
424
         }
425
      }
13✔
426

427
      Test::Result test_max_number_of_bytes_per_request() override {
1✔
428
         Test::Result result("HMAC_DRBG max_number_of_bytes_per_request");
1✔
429

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

432
         Request_Counting_RNG counting_rng;
1✔
433

434
         result.test_throws(
2✔
435
            "HMAC_DRBG does not accept 0 for max_number_of_bytes_per_request", [&mac_string, &counting_rng]() {
1✔
436
               Botan::HMAC_DRBG failing_rng(Botan::MessageAuthenticationCode::create(mac_string), counting_rng, 2, 0);
1✔
437
            });
×
438

439
         result.test_throws("HMAC_DRBG does not accept values higher than 64KB for max_number_of_bytes_per_request",
2✔
440
                            [&mac_string, &counting_rng]() {
1✔
441
                               Botan::HMAC_DRBG failing_rng(
1✔
442
                                  Botan::MessageAuthenticationCode::create(mac_string), counting_rng, 2, 64 * 1024 + 1);
1✔
443
                            });
×
444

445
         // set reseed_interval to 1 so we can test that a long request is split
446
         // into multiple, max_number_of_bytes_per_request long requests
447
         // for each smaller request, reseed_check() calls counting_rng::randomize(),
448
         // which we can compare with
449
         Botan::HMAC_DRBG rng(Botan::MessageAuthenticationCode::create(mac_string), counting_rng, 1, 64);
1✔
450

451
         rng.random_vec(63);
1✔
452
         result.test_eq("one request", counting_rng.randomize_count(), 1);
1✔
453

454
         rng.clear();
1✔
455
         counting_rng.clear();
1✔
456

457
         rng.random_vec(64);
1✔
458
         result.test_eq("one request", counting_rng.randomize_count(), 1);
1✔
459

460
         rng.clear();
1✔
461
         counting_rng.clear();
1✔
462

463
         rng.random_vec(65);
1✔
464
         result.test_eq("two requests", counting_rng.randomize_count(), 2);
1✔
465

466
         rng.clear();
1✔
467
         counting_rng.clear();
1✔
468

469
         rng.random_vec(1025);
1✔
470
         result.test_eq("17 requests", counting_rng.randomize_count(), 17);
1✔
471

472
         return result;
2✔
473
      }
1✔
474

475
      Test::Result test_reseed_interval_limits() override {
1✔
476
         Test::Result result("HMAC_DRBG reseed_interval limits");
1✔
477

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

480
         Request_Counting_RNG counting_rng;
1✔
481

482
         result.test_throws("HMAC_DRBG does not accept 0 for reseed_interval", [&mac_string, &counting_rng]() {
2✔
483
            Botan::HMAC_DRBG failing_rng(Botan::MessageAuthenticationCode::create(mac_string), counting_rng, 0);
1✔
484
         });
×
485

486
         result.test_throws("HMAC_DRBG does not accept values higher than 2^24 for reseed_interval",
2✔
487
                            [&mac_string, &counting_rng]() {
1✔
488
                               Botan::HMAC_DRBG failing_rng(Botan::MessageAuthenticationCode::create(mac_string),
2✔
489
                                                            counting_rng,
1✔
490
                                                            (static_cast<size_t>(1) << 24) + 1);
1✔
491
                            });
×
492

493
         return result;
1✔
494
      }
1✔
495

496
      Test::Result test_security_level() override {
1✔
497
         Test::Result result("HMAC_DRBG Security Level");
1✔
498

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

502
         for(size_t i = 0; i < approved_hash_fns.size(); ++i) {
7✔
503
            std::string hash_fn = approved_hash_fns[i];
6✔
504
            std::string mac_name = "HMAC(" + hash_fn + ")";
12✔
505
            auto mac = Botan::MessageAuthenticationCode::create(mac_name);
6✔
506
            if(!mac) {
6✔
507
               result.note_missing(mac_name);
1✔
508
               continue;
1✔
509
            }
510

511
            Botan::HMAC_DRBG rng(std::move(mac));
5✔
512
            result.test_eq(hash_fn + " security level", rng.security_level(), security_strengths[i]);
5✔
513
         }
6✔
514

515
         return result;
1✔
516
      }
3✔
517

518
      Test::Result test_reseed_kat() override {
1✔
519
         Test::Result result("HMAC_DRBG Reseed KAT");
1✔
520

521
         Request_Counting_RNG counting_rng;
1✔
522
         auto rng = make_rng(counting_rng, 2);
1✔
523

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

528
         result.test_eq("is_seeded", rng->is_seeded(), false);
1✔
529

530
         rng->initialize_with(seed_input.data(), seed_input.size());
1✔
531

532
         Botan::secure_vector<uint8_t> out(32);
1✔
533

534
         rng->randomize(out.data(), out.size());
1✔
535
         result.test_eq("underlying RNG calls", counting_rng.randomize_count(), size_t(0));
1✔
536
         result.test_eq("out before reseed", out, "48D3B45AAB65EF92CCFCB9427EF20C90297065ECC1B8A525BFE4DC6FF36D0E38");
1✔
537

538
         // reseed must happen here
539
         rng->randomize(out.data(), out.size());
1✔
540
         result.test_eq("underlying RNG calls", counting_rng.randomize_count(), size_t(1));
1✔
541
         result.test_eq("out after reseed", out, "2F8FCA696832C984781123FD64F4B20C7379A25C87AB29A21C9BF468B0081CE2");
1✔
542

543
         return result;
2✔
544
      }
3✔
545
};
546

547
std::vector<Test::Result> hmac_drbg_multiple_requests() {
1✔
548
   auto null_rng = Botan::Null_RNG();
1✔
549
   constexpr auto rng_max_output = 1024;
1✔
550
   const auto seed = Botan::hex_decode("deadbeefbaadcafedeadbeefbaadcafedeadbeefbaadcafedeadbeefbaadcafe");
1✔
551

552
   auto make_seeded_rng = [&](size_t reseed_interval) {
5✔
553
      auto rng = std::make_unique<Botan::HMAC_DRBG>(Botan::MessageAuthenticationCode::create("HMAC(SHA-256)"),
×
554
                                                    null_rng,
555
                                                    reseed_interval + 1 /* off by one */,
8✔
556
                                                    rng_max_output);
4✔
557
      rng->add_entropy(seed);
4✔
558
      return rng;
4✔
559
   };
×
560

561
   return {CHECK("bulk and split output without input",
1✔
562
                 [&](auto& result) {
1✔
563
                    auto rng1 = make_seeded_rng(2);
1✔
564
                    auto rng2 = make_seeded_rng(2);
1✔
565

566
                    result.confirm("RNG 1 is seeded and ready to go", rng1->is_seeded());
2✔
567
                    result.confirm("RNG 2 is seeded and ready to go", rng2->is_seeded());
2✔
568

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

571
                    auto split1 = rng2->random_vec<std::vector<uint8_t>>(rng_max_output);
1✔
572
                    auto split2 = rng2->random_vec<std::vector<uint8_t>>(rng_max_output);
1✔
573
                    split1.insert(split1.end(), split2.begin(), split2.end());
1✔
574

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

577
                    return result;
2✔
578
                 }),
3✔
579

580
           CHECK("bulk and split output with input", [&](auto& result) {
1✔
581
              auto rng1 = make_seeded_rng(3);
1✔
582
              auto rng2 = make_seeded_rng(3);
1✔
583

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

587
              std::vector<uint8_t> bulk(3 * rng_max_output);
1✔
588
              rng1->randomize_with_input(bulk, seed);
2✔
589

590
              std::vector<uint8_t> split(3 * rng_max_output);
1✔
591
              std::span<uint8_t> split_span(split);
1✔
592
              rng2->randomize_with_input(split_span.subspan(0, rng_max_output), seed);
2✔
593
              rng2->randomize_with_input(split_span.subspan(rng_max_output, rng_max_output), {});
2✔
594
              rng2->randomize_with_input(split_span.subspan(2 * rng_max_output), {});
2✔
595

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

598
              return result;
2✔
599
           })};
6✔
600
}
2✔
601

602
BOTAN_REGISTER_TEST("rng", "hmac_drbg_unit", HMAC_DRBG_Unit_Tests);
603
BOTAN_REGISTER_TEST_FN("rng", "hmac_drbg_multi_requst", hmac_drbg_multiple_requests);
604

605
#endif
606

607
#if defined(BOTAN_HAS_CHACHA_RNG)
608

609
class ChaCha_RNG_Unit_Tests final : public Stateful_RNG_Tests {
×
610
   public:
611
      std::string rng_name() const override { return "ChaCha_RNG"; }
6✔
612

613
      std::unique_ptr<Botan::Stateful_RNG> create_rng(Botan::RandomNumberGenerator* underlying_rng,
13✔
614
                                                      Botan::Entropy_Sources* underlying_es,
615
                                                      size_t reseed_interval) override {
616
         if(underlying_rng && underlying_es) {
13✔
617
            return std::make_unique<Botan::ChaCha_RNG>(*underlying_rng, *underlying_es, reseed_interval);
3✔
618
         } else if(underlying_rng) {
10✔
619
            return std::make_unique<Botan::ChaCha_RNG>(*underlying_rng, reseed_interval);
7✔
620
         } else if(underlying_es) {
3✔
621
            return std::make_unique<Botan::ChaCha_RNG>(*underlying_es, reseed_interval);
2✔
622
         } else if(reseed_interval == 0) {
1✔
623
            return std::make_unique<Botan::ChaCha_RNG>();
1✔
624
         } else {
625
            throw Test_Error("Invalid reseed interval in ChaCha_RNG unit test");
×
626
         }
627
      }
628

629
      Test::Result test_security_level() override {
1✔
630
         Test::Result result("ChaCha_RNG Security Level");
1✔
631
         Botan::ChaCha_RNG rng;
1✔
632
         result.test_eq("Expected security level", rng.security_level(), size_t(256));
1✔
633
         return result;
1✔
634
      }
1✔
635

636
      Test::Result test_max_number_of_bytes_per_request() override {
1✔
637
         Test::Result result("ChaCha_RNG max_number_of_bytes_per_request");
1✔
638
         // ChaCha_RNG doesn't have this notion
639
         return result;
1✔
640
      }
641

642
      Test::Result test_reseed_interval_limits() override {
1✔
643
         Test::Result result("ChaCha_RNG reseed_interval limits");
1✔
644
         // ChaCha_RNG doesn't apply any limits to reseed_interval
645
         return result;
1✔
646
      }
647

648
      Test::Result test_reseed_kat() override {
1✔
649
         Test::Result result("ChaCha_RNG Reseed KAT");
1✔
650

651
         Request_Counting_RNG counting_rng;
1✔
652
         auto rng = make_rng(counting_rng, 2);
1✔
653

654
         const Botan::secure_vector<uint8_t> seed_input(32);
1✔
655

656
         result.test_eq("is_seeded", rng->is_seeded(), false);
1✔
657

658
         rng->initialize_with(seed_input.data(), seed_input.size());
1✔
659

660
         Botan::secure_vector<uint8_t> out(32);
1✔
661

662
         rng->randomize(out.data(), out.size());
1✔
663
         result.test_eq("underlying RNG calls", counting_rng.randomize_count(), size_t(0));
1✔
664
         result.test_eq("out before reseed", out, "1F0E6F13429D5073B59C057C37CBE9587740A0A894D247E2596C393CE91DDC6F");
1✔
665

666
         // reseed must happen here
667
         rng->randomize(out.data(), out.size());
1✔
668
         result.test_eq("underlying RNG calls", counting_rng.randomize_count(), size_t(1));
1✔
669
         result.test_eq("out after reseed", out, "F2CAE73F22684D5D773290B48FDCDA0E6C0661EBA0A854AFEC922832BDBB9C49");
1✔
670

671
         return result;
2✔
672
      }
3✔
673
};
674

675
BOTAN_REGISTER_TEST("rng", "chacha_rng_unit", ChaCha_RNG_Unit_Tests);
676

677
#endif
678

679
#if defined(BOTAN_HAS_AUTO_RNG)
680

681
class AutoSeeded_RNG_Tests final : public Test {
×
682
   private:
683
      static Test::Result auto_rng_tests() {
1✔
684
         Test::Result result("AutoSeeded_RNG");
1✔
685

686
         Botan::Null_RNG null_rng;
1✔
687

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

690
         try {
1✔
691
            Botan::AutoSeeded_RNG rng(null_rng);
1✔
692
         } catch(Botan::PRNG_Unseeded&) {
1✔
693
            result.test_success("AutoSeeded_RNG rejected useless RNG");
1✔
694
         }
1✔
695

696
   #if defined(BOTAN_HAS_ENTROPY_SOURCE)
697
         Botan::Entropy_Sources no_entropy_for_you;
1✔
698

699
         try {
1✔
700
            Botan::AutoSeeded_RNG rng(no_entropy_for_you);
1✔
701
            result.test_failure("AutoSeeded_RNG should have rejected useless entropy source");
×
702
         } catch(Botan::PRNG_Unseeded&) {
1✔
703
            result.test_success("AutoSeeded_RNG rejected empty entropy source");
1✔
704
         }
1✔
705

706
         try {
1✔
707
            Botan::AutoSeeded_RNG rng(null_rng, no_entropy_for_you);
1✔
708
         } catch(Botan::PRNG_Unseeded&) {
1✔
709
            result.test_success("AutoSeeded_RNG rejected useless RNG+entropy sources");
1✔
710
         }
1✔
711
   #endif
712

713
         Botan::AutoSeeded_RNG rng;
1✔
714

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

717
         result.confirm("AutoSeeded_RNG starts seeded", rng.is_seeded());
2✔
718
         rng.random_vec(16);  // generate and discard output
1✔
719
         rng.clear();
1✔
720
         result.test_eq("AutoSeeded_RNG unseeded after calling clear", rng.is_seeded(), false);
1✔
721

722
         // AutoSeeded_RNG automatically reseeds as required:
723
         rng.random_vec(16);
1✔
724
         result.confirm("AutoSeeded_RNG can be reseeded", rng.is_seeded());
2✔
725

726
         result.confirm("AutoSeeded_RNG ", rng.is_seeded());
2✔
727
         rng.random_vec(16);  // generate and discard output
1✔
728
         rng.clear();
1✔
729
         result.test_eq("AutoSeeded_RNG unseeded after calling clear", rng.is_seeded(), false);
1✔
730

731
   #if defined(BOTAN_HAS_ENTROPY_SOURCE)
732
         const size_t no_entropy_bits = rng.reseed(no_entropy_for_you, 256, std::chrono::milliseconds(300));
1✔
733
         result.test_eq("AutoSeeded_RNG can't reseed from nothing", no_entropy_bits, 0);
1✔
734
         result.test_eq("AutoSeeded_RNG still unseeded", rng.is_seeded(), false);
1✔
735
   #endif
736

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

740
         for(size_t i = 0; i != 4096; ++i) {
4,097✔
741
            std::vector<uint8_t> buf(i);
4,096✔
742
            rng.randomize(buf.data(), buf.size());
4,096✔
743
            rng.add_entropy(buf.data(), buf.size());
4,096✔
744

745
            result.test_success("AutoSeeded_RNG accepted input and output length");
8,192✔
746
         }
4,096✔
747

748
         rng.clear();
1✔
749

750
         return result;
1✔
751
      }
1✔
752

753
   public:
754
      std::vector<Test::Result> run() override {
1✔
755
         std::vector<Test::Result> results;
1✔
756
         results.push_back(auto_rng_tests());
2✔
757
         return results;
1✔
758
      }
×
759
};
760

761
BOTAN_REGISTER_TEST("rng", "auto_rng_unit", AutoSeeded_RNG_Tests);
762

763
#endif
764

765
#if defined(BOTAN_HAS_SYSTEM_RNG)
766

767
class System_RNG_Tests final : public Test {
×
768
   public:
769
      std::vector<Test::Result> run() override {
1✔
770
         Test::Result result("System_RNG");
1✔
771

772
         Botan::System_RNG rng;
1✔
773

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

776
         result.confirm("System RNG always seeded", rng.is_seeded());
3✔
777
         rng.clear();  // clear is a noop for system rng
1✔
778
         result.confirm("System RNG always seeded", rng.is_seeded());
3✔
779

780
   #if defined(BOTAN_HAS_ENTROPY_SOURCE)
781
         rng.reseed(Botan::Entropy_Sources::global_sources(), 256, std::chrono::milliseconds(100));
1✔
782
   #endif
783

784
         for(size_t i = 0; i != 128; ++i) {
129✔
785
            std::vector<uint8_t> out_buf(i);
128✔
786
            rng.randomize(out_buf.data(), out_buf.size());
128✔
787
            rng.add_entropy(out_buf.data(), out_buf.size());
128✔
788
         }
128✔
789

790
         if(Test::run_long_tests() && Test::run_memory_intensive_tests() && (sizeof(size_t) > 4)) {
1✔
791
            // Pass buffer with a size greater than 32bit
792
            const size_t size32BitsMax = std::numeric_limits<uint32_t>::max();
1✔
793
            const size_t checkSize = 1024;
1✔
794
            std::vector<uint8_t> large_buf(size32BitsMax + checkSize);
1✔
795
            std::memset(large_buf.data() + size32BitsMax, 0xFE, checkSize);
1✔
796

797
            rng.randomize(large_buf.data(), large_buf.size());
1✔
798

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

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

805
         return std::vector<Test::Result>{result};
2✔
806
      }
2✔
807
};
808

809
BOTAN_REGISTER_TEST("rng", "system_rng", System_RNG_Tests);
810

811
#endif
812

813
#if defined(BOTAN_HAS_PROCESSOR_RNG)
814

815
class Processor_RNG_Tests final : public Test {
×
816
   public:
817
      std::vector<Test::Result> run() override {
1✔
818
         Test::Result result("Processor_RNG");
1✔
819

820
         if(Botan::Processor_RNG::available()) {
1✔
821
            Botan::Processor_RNG rng;
1✔
822

823
            result.test_ne("Has a name", rng.name(), "");
2✔
824
            result.confirm("CPU RNG always seeded", rng.is_seeded());
2✔
825
            rng.clear();  // clear is a noop for rdrand
1✔
826
            result.confirm("CPU RNG always seeded", rng.is_seeded());
2✔
827

828
   #if defined(BOTAN_HAS_ENTROPY_SOURCE)
829
            size_t reseed_bits = rng.reseed(Botan::Entropy_Sources::global_sources(), 256, std::chrono::seconds(1));
1✔
830
            result.test_eq("CPU RNG cannot consume inputs", reseed_bits, size_t(0));
1✔
831
   #endif
832

833
            /*
834
            Processor_RNG ignores add_entropy calls - confirm this by passing
835
            an invalid ptr/length field to add_entropy. If it examined its
836
            arguments, it would crash...
837
            */
838
            // NOLINTNEXTLINE(*-no-int-to-ptr)
839
            const uint8_t* invalid_ptr = reinterpret_cast<const uint8_t*>(static_cast<uintptr_t>(0xDEADC0DE));
1✔
840
            const size_t invalid_ptr_len = 64 * 1024;
1✔
841
            rng.add_entropy(invalid_ptr, invalid_ptr_len);
1✔
842

843
            for(size_t i = 0; i != 128; ++i) {
129✔
844
               std::vector<uint8_t> out_buf(i);
128✔
845
               rng.randomize(out_buf.data(), out_buf.size());
128✔
846
            }
128✔
847
         } else {
1✔
848
            result.test_throws("Processor_RNG throws if instruction not available", []() { Botan::Processor_RNG rng; });
×
849
         }
850

851
         return std::vector<Test::Result>{result};
3✔
852
      }
2✔
853
};
854

855
BOTAN_REGISTER_TEST("rng", "processor_rng", Processor_RNG_Tests);
856

857
#endif
858

859
}  // namespace
860

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

© 2026 Coveralls, Inc