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

randombit / botan / 21753596263

06 Feb 2026 02:13PM UTC coverage: 90.063% (-0.01%) from 90.073%
21753596263

Pull #5289

github

web-flow
Merge 587099284 into 8ea0ca252
Pull Request #5289: Further misc header reductions, forward declarations, etc

102237 of 113517 relevant lines covered (90.06%)

11402137.11 hits per line

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

85.62
/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
#include <botan/internal/target_info.h>
12
#include <cstring>
13

14
#if defined(BOTAN_HAS_STATEFUL_RNG)
15
   #include <botan/stateful_rng.h>
16
#endif
17

18
#if defined(BOTAN_HAS_HMAC_DRBG)
19
   #include <botan/hmac_drbg.h>
20
   #include <botan/mac.h>
21
#endif
22

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

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

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

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

39
#if defined(BOTAN_HAS_ENTROPY_SOURCE)
40
   #include <botan/entropy_src.h>
41
#endif
42

43
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
44
   #include <sys/wait.h>
45
   #include <unistd.h>
46
#endif
47

48
namespace Botan_Tests {
49

50
namespace {
51

52
#if defined(BOTAN_HAS_STATEFUL_RNG)
53

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

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

80
         return results;
2✔
81
      }
×
82

83
   protected:
84
      virtual std::string rng_name() const = 0;
85

86
      virtual std::unique_ptr<Botan::Stateful_RNG> create_rng(Botan::RandomNumberGenerator* underlying_rng,
87
                                                              Botan::Entropy_Sources* underlying_es,
88
                                                              size_t reseed_interval) = 0;
89

90
      std::unique_ptr<Botan::Stateful_RNG> make_rng(Botan::RandomNumberGenerator& underlying_rng,
14✔
91
                                                    size_t reseed_interval = 1024) {
92
         return create_rng(&underlying_rng, nullptr, reseed_interval);
14✔
93
      }
94

95
      std::unique_ptr<Botan::Stateful_RNG> make_rng(Botan::Entropy_Sources& underlying_srcs,
4✔
96
                                                    size_t reseed_interval = 1024) {
97
         return create_rng(nullptr, &underlying_srcs, reseed_interval);
4✔
98
      }
99

100
      std::unique_ptr<Botan::Stateful_RNG> make_rng(Botan::RandomNumberGenerator& underlying_rng,
6✔
101
                                                    Botan::Entropy_Sources& underlying_srcs,
102
                                                    size_t reseed_interval = 1024) {
103
         return create_rng(&underlying_rng, &underlying_srcs, reseed_interval);
6✔
104
      }
105

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

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

110
      virtual Test::Result test_max_number_of_bytes_per_request() = 0;
111

112
      virtual Test::Result test_reseed_interval_limits() = 0;
113

114
   private:
115
      Test::Result test_reseed() {
2✔
116
         Test::Result result(rng_name() + " Reseed");
6✔
117

118
         // test reseed_interval is enforced
119
         Request_Counting_RNG counting_rng;
2✔
120

121
         auto rng = make_rng(counting_rng, 2);
2✔
122

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

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

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

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

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

147
         return result;
4✔
148
      }
2✔
149

150
      Test::Result test_broken_entropy_input() {
2✔
151
         Test::Result result(rng_name() + " Broken Entropy Input");
6✔
152

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

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

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

167
               size_t poll(Botan::RandomNumberGenerator& /*rng*/) override { return 0; }
2✔
168
         };
169
   #endif
170

171
         // make sure no output is generated when the entropy input source is broken
172

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

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

180
   #if defined(BOTAN_HAS_ENTROPY_SOURCE)
181

182
         // entropy_sources throw exception
183
         auto broken_entropy_source_1 = std::make_unique<Broken_Entropy_Source>();
2✔
184
         auto broken_entropy_source_2 = std::make_unique<Broken_Entropy_Source>();
2✔
185

186
         Botan::Entropy_Sources broken_entropy_sources;
2✔
187
         broken_entropy_sources.add_source(std::move(broken_entropy_source_1));
2✔
188
         broken_entropy_sources.add_source(std::move(broken_entropy_source_2));
2✔
189

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

193
         // entropy source returns insufficient entropy
194
         Botan::Entropy_Sources insufficient_entropy_sources;
2✔
195
         auto insufficient_entropy_source = std::make_unique<Insufficient_Entropy_Source>();
2✔
196
         insufficient_entropy_sources.add_source(std::move(insufficient_entropy_source));
2✔
197

198
         auto rng_with_insufficient_es = make_rng(insufficient_entropy_sources);
2✔
199
         result.test_throws("insufficient entropy source",
4✔
200
                            [&rng_with_insufficient_es]() { rng_with_insufficient_es->random_vec(16); });
4✔
201

202
         // one of or both underlying_rng and entropy_sources throw exception
203

204
         auto rng_with_broken_rng_and_good_es =
2✔
205
            make_rng(broken_entropy_input_rng, Botan::Entropy_Sources::global_sources());
2✔
206

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

210
         auto rng_with_good_rng_and_broken_es = make_rng(this->rng(), broken_entropy_sources);
2✔
211

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

215
         auto rng_with_broken_rng_and_broken_es = make_rng(broken_entropy_input_rng, broken_entropy_sources);
2✔
216

217
         result.test_throws("underlying rng and entropy sources broken", [&rng_with_broken_rng_and_broken_es]() {
4✔
218
            rng_with_broken_rng_and_broken_es->random_vec(16);
2✔
219
         });
×
220
   #endif
221

222
         return result;
4✔
223
      }
12✔
224

225
      Test::Result test_check_nonce() {
2✔
226
         Test::Result result(rng_name() + " Nonce Check");
6✔
227

228
         // make sure the nonce has at least security_strength bits
229
         auto rng = create_rng(nullptr, nullptr, 0);
2✔
230

231
         for(const size_t nonce_size : {0, 4, 8, 16, 31, 32, 34, 64}) {
18✔
232
            rng->clear();
16✔
233
            result.test_eq("not seeded", rng->is_seeded(), false);
16✔
234

235
            const std::vector<uint8_t> nonce(nonce_size);
16✔
236
            rng->initialize_with(nonce.data(), nonce.size());
16✔
237

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

247
         return result;
2✔
248
      }
2✔
249

250
      Test::Result test_prediction_resistance() {
2✔
251
         Test::Result result(rng_name() + " Prediction Resistance");
6✔
252

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

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

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

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

266
         return result;
4✔
267
      }
2✔
268

269
      Test::Result test_fork_safety() {
×
270
         Test::Result result(rng_name() + " Fork Safety");
×
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);
×
285
         Botan::secure_vector<uint8_t> child_bytes(16);
×
286
         int fd[2];
×
287
         const int rc = ::pipe(fd);
×
288
         if(rc != 0) {
×
289
            result.test_failure("failed to create pipe");
×
290
         }
291

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

382
         return result;
2✔
383
      }
10✔
384

385
      Test::Result test_input_output_edge_cases() {
2✔
386
         Test::Result result(rng_name() + " randomize");
6✔
387

388
         const std::vector<uint8_t> seed(128);
2✔
389
         Fixed_Output_RNG fixed_output_rng(seed);
2✔
390

391
         auto rng = make_rng(fixed_output_rng);
2✔
392

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

398
            result.test_success("RNG accepted input and output length");
16,384✔
399
         }
8,192✔
400

401
         return result;
2✔
402
      }
4✔
403
};
404

405
#endif
406

407
#if defined(BOTAN_HAS_HMAC_DRBG) && defined(BOTAN_HAS_SHA2_32)
408

409
class HMAC_DRBG_Unit_Tests final : public Stateful_RNG_Tests {
1✔
410
   public:
411
      std::string rng_name() const override { return "HMAC_DRBG"; }
6✔
412

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

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

432
      Test::Result test_max_number_of_bytes_per_request() override {
1✔
433
         Test::Result result("HMAC_DRBG max_number_of_bytes_per_request");
1✔
434

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

437
         Request_Counting_RNG counting_rng;
1✔
438

439
         result.test_throws("HMAC_DRBG does not accept 0 for max_number_of_bytes_per_request",
2✔
440
                            [&mac_string, &counting_rng]() {
1✔
441
                               const Botan::HMAC_DRBG failing_rng(
1✔
442
                                  Botan::MessageAuthenticationCode::create(mac_string), counting_rng, 2, 0);
1✔
443
                            });
×
444

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

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

457
         rng.random_vec(63);
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(64);
1✔
464
         result.test_eq("one request", counting_rng.randomize_count(), 1);
1✔
465

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

469
         rng.random_vec(65);
1✔
470
         result.test_eq("two requests", counting_rng.randomize_count(), 2);
1✔
471

472
         rng.clear();
1✔
473
         counting_rng.clear();
1✔
474

475
         rng.random_vec(1025);
1✔
476
         result.test_eq("17 requests", counting_rng.randomize_count(), 17);
1✔
477

478
         return result;
2✔
479
      }
1✔
480

481
      Test::Result test_reseed_interval_limits() override {
1✔
482
         Test::Result result("HMAC_DRBG reseed_interval limits");
1✔
483

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

486
         Request_Counting_RNG counting_rng;
1✔
487

488
         result.test_throws("HMAC_DRBG does not accept 0 for reseed_interval", [&mac_string, &counting_rng]() {
2✔
489
            const Botan::HMAC_DRBG failing_rng(Botan::MessageAuthenticationCode::create(mac_string), counting_rng, 0);
1✔
490
         });
×
491

492
         result.test_throws("HMAC_DRBG does not accept values higher than 2^24 for reseed_interval",
2✔
493
                            [&mac_string, &counting_rng]() {
1✔
494
                               const Botan::HMAC_DRBG failing_rng(Botan::MessageAuthenticationCode::create(mac_string),
2✔
495
                                                                  counting_rng,
1✔
496
                                                                  (static_cast<size_t>(1) << 24) + 1);
1✔
497
                            });
×
498

499
         return result;
1✔
500
      }
1✔
501

502
      Test::Result test_security_level() override {
1✔
503
         Test::Result result("HMAC_DRBG Security Level");
1✔
504

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

508
         for(size_t i = 0; i < approved_hash_fns.size(); ++i) {
7✔
509
            const auto& hash_fn = approved_hash_fns[i];
6✔
510
            const size_t expected_security_level = security_strengths[i];
6✔
511

512
            const std::string mac_name = "HMAC(" + hash_fn + ")";
12✔
513
            auto mac = Botan::MessageAuthenticationCode::create(mac_name);
6✔
514
            if(!mac) {
6✔
515
               result.note_missing(mac_name);
1✔
516
               continue;
1✔
517
            }
518

519
            const Botan::HMAC_DRBG rng(std::move(mac));
5✔
520
            result.test_eq(hash_fn + " security level", rng.security_level(), expected_security_level);
5✔
521
         }
6✔
522

523
         return result;
1✔
524
      }
3✔
525

526
      Test::Result test_reseed_kat() override {
1✔
527
         Test::Result result("HMAC_DRBG Reseed KAT");
1✔
528

529
         Request_Counting_RNG counting_rng;
1✔
530
         auto rng = make_rng(counting_rng, 2);
1✔
531

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

536
         result.test_eq("is_seeded", rng->is_seeded(), false);
1✔
537

538
         rng->initialize_with(seed_input.data(), seed_input.size());
1✔
539

540
         Botan::secure_vector<uint8_t> out(32);
1✔
541

542
         rng->randomize(out.data(), out.size());
1✔
543
         result.test_eq("underlying RNG calls", counting_rng.randomize_count(), size_t(0));
1✔
544
         result.test_eq("out before reseed", out, "48D3B45AAB65EF92CCFCB9427EF20C90297065ECC1B8A525BFE4DC6FF36D0E38");
1✔
545

546
         // reseed must happen here
547
         rng->randomize(out.data(), out.size());
1✔
548
         result.test_eq("underlying RNG calls", counting_rng.randomize_count(), size_t(1));
1✔
549
         result.test_eq("out after reseed", out, "2F8FCA696832C984781123FD64F4B20C7379A25C87AB29A21C9BF468B0081CE2");
1✔
550

551
         return result;
2✔
552
      }
3✔
553
};
554

555
std::vector<Test::Result> hmac_drbg_multiple_requests() {
1✔
556
   auto null_rng = Botan::Null_RNG();
1✔
557
   constexpr auto rng_max_output = 1024;
1✔
558
   const auto seed = Botan::hex_decode("deadbeefbaadcafedeadbeefbaadcafedeadbeefbaadcafedeadbeefbaadcafe");
1✔
559

560
   auto make_seeded_rng = [&](size_t reseed_interval) {
5✔
561
      auto rng = std::make_unique<Botan::HMAC_DRBG>(Botan::MessageAuthenticationCode::create("HMAC(SHA-256)"),
×
562
                                                    null_rng,
563
                                                    reseed_interval + 1 /* off by one */,
8✔
564
                                                    rng_max_output);
4✔
565
      rng->add_entropy(seed);
4✔
566
      return rng;
4✔
567
   };
1✔
568

569
   return {CHECK("bulk and split output without input",
1✔
570
                 [&](auto& result) {
1✔
571
                    auto rng1 = make_seeded_rng(2);
1✔
572
                    auto rng2 = make_seeded_rng(2);
1✔
573

574
                    result.confirm("RNG 1 is seeded and ready to go", rng1->is_seeded());
2✔
575
                    result.confirm("RNG 2 is seeded and ready to go", rng2->is_seeded());
2✔
576

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

579
                    auto split1 = rng2->random_vec<std::vector<uint8_t>>(rng_max_output);
1✔
580
                    auto split2 = rng2->random_vec<std::vector<uint8_t>>(rng_max_output);
1✔
581
                    split1.insert(split1.end(), split2.begin(), split2.end());
1✔
582

583
                    result.test_eq("Output is equal, regardless bulk request", bulk, split1);
2✔
584

585
                    return result;
1✔
586
                 }),
5✔
587

588
           CHECK("bulk and split output with input", [&](auto& result) {
1✔
589
              auto rng1 = make_seeded_rng(3);
1✔
590
              auto rng2 = make_seeded_rng(3);
1✔
591

592
              result.confirm("RNG 1 is seeded and ready to go", rng1->is_seeded());
2✔
593
              result.confirm("RNG 2 is seeded and ready to go", rng2->is_seeded());
2✔
594

595
              std::vector<uint8_t> bulk(3 * rng_max_output);
1✔
596
              rng1->randomize_with_input(bulk, seed);
2✔
597

598
              std::vector<uint8_t> split(3 * rng_max_output);
1✔
599
              std::span<uint8_t> const split_span(split);
1✔
600
              rng2->randomize_with_input(split_span.subspan(0, rng_max_output), seed);
2✔
601
              rng2->randomize_with_input(split_span.subspan(rng_max_output, rng_max_output), {});
2✔
602
              rng2->randomize_with_input(split_span.subspan(2 * rng_max_output), {});
2✔
603

604
              result.test_eq("Output is equal, regardless bulk request", bulk, split);
2✔
605

606
              return result;
1✔
607
           })};
6✔
608
}
2✔
609

610
BOTAN_REGISTER_TEST("rng", "hmac_drbg_unit", HMAC_DRBG_Unit_Tests);
611
BOTAN_REGISTER_TEST_FN("rng", "hmac_drbg_multi_request", hmac_drbg_multiple_requests);
612

613
#endif
614

615
#if defined(BOTAN_HAS_CHACHA_RNG)
616

617
class ChaCha_RNG_Unit_Tests final : public Stateful_RNG_Tests {
1✔
618
   public:
619
      std::string rng_name() const override { return "ChaCha_RNG"; }
6✔
620

621
      std::unique_ptr<Botan::Stateful_RNG> create_rng(Botan::RandomNumberGenerator* underlying_rng,
13✔
622
                                                      Botan::Entropy_Sources* underlying_es,
623
                                                      size_t reseed_interval) override {
624
         if(underlying_rng != nullptr && underlying_es != nullptr) {
13✔
625
            return std::make_unique<Botan::ChaCha_RNG>(*underlying_rng, *underlying_es, reseed_interval);
3✔
626
         } else if(underlying_rng != nullptr) {
10✔
627
            return std::make_unique<Botan::ChaCha_RNG>(*underlying_rng, reseed_interval);
7✔
628
         } else if(underlying_es != nullptr) {
3✔
629
            return std::make_unique<Botan::ChaCha_RNG>(*underlying_es, reseed_interval);
2✔
630
         } else if(reseed_interval == 0) {
1✔
631
            return std::make_unique<Botan::ChaCha_RNG>();
1✔
632
         } else {
633
            throw Test_Error("Invalid reseed interval in ChaCha_RNG unit test");
×
634
         }
635
      }
636

637
      Test::Result test_security_level() override {
1✔
638
         Test::Result result("ChaCha_RNG Security Level");
1✔
639
         const Botan::ChaCha_RNG rng;
1✔
640
         result.test_eq("Expected security level", rng.security_level(), size_t(256));
1✔
641
         return result;
1✔
642
      }
1✔
643

644
      Test::Result test_max_number_of_bytes_per_request() override {
1✔
645
         Test::Result result("ChaCha_RNG max_number_of_bytes_per_request");
1✔
646
         // ChaCha_RNG doesn't have this notion
647
         return result;
1✔
648
      }
649

650
      Test::Result test_reseed_interval_limits() override {
1✔
651
         Test::Result result("ChaCha_RNG reseed_interval limits");
1✔
652
         // ChaCha_RNG doesn't apply any limits to reseed_interval
653
         return result;
1✔
654
      }
655

656
      Test::Result test_reseed_kat() override {
1✔
657
         Test::Result result("ChaCha_RNG Reseed KAT");
1✔
658

659
         Request_Counting_RNG counting_rng;
1✔
660
         auto rng = make_rng(counting_rng, 2);
1✔
661

662
         const Botan::secure_vector<uint8_t> seed_input(32);
1✔
663

664
         result.test_eq("is_seeded", rng->is_seeded(), false);
1✔
665

666
         rng->initialize_with(seed_input.data(), seed_input.size());
1✔
667

668
         Botan::secure_vector<uint8_t> out(32);
1✔
669

670
         rng->randomize(out.data(), out.size());
1✔
671
         result.test_eq("underlying RNG calls", counting_rng.randomize_count(), size_t(0));
1✔
672
         result.test_eq("out before reseed", out, "1F0E6F13429D5073B59C057C37CBE9587740A0A894D247E2596C393CE91DDC6F");
1✔
673

674
         // reseed must happen here
675
         rng->randomize(out.data(), out.size());
1✔
676
         result.test_eq("underlying RNG calls", counting_rng.randomize_count(), size_t(1));
1✔
677
         result.test_eq("out after reseed", out, "F2CAE73F22684D5D773290B48FDCDA0E6C0661EBA0A854AFEC922832BDBB9C49");
1✔
678

679
         return result;
2✔
680
      }
3✔
681
};
682

683
BOTAN_REGISTER_TEST("rng", "chacha_rng_unit", ChaCha_RNG_Unit_Tests);
684

685
#endif
686

687
#if defined(BOTAN_HAS_AUTO_RNG)
688

689
class AutoSeeded_RNG_Tests final : public Test {
1✔
690
   private:
691
      static Test::Result auto_rng_tests() {
1✔
692
         Test::Result result("AutoSeeded_RNG");
1✔
693

694
         Botan::Null_RNG null_rng;
1✔
695

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

698
         try {
1✔
699
            const Botan::AutoSeeded_RNG rng(null_rng);
1✔
700
         } catch(Botan::PRNG_Unseeded&) {
1✔
701
            result.test_success("AutoSeeded_RNG rejected useless RNG");
1✔
702
         }
1✔
703

704
   #if defined(BOTAN_HAS_ENTROPY_SOURCE)
705
         Botan::Entropy_Sources no_entropy_for_you;
1✔
706

707
         try {
1✔
708
            const Botan::AutoSeeded_RNG rng(no_entropy_for_you);
1✔
709
            result.test_failure("AutoSeeded_RNG should have rejected useless entropy source");
×
710
         } catch(Botan::PRNG_Unseeded&) {
1✔
711
            result.test_success("AutoSeeded_RNG rejected empty entropy source");
1✔
712
         }
1✔
713

714
         try {
1✔
715
            const Botan::AutoSeeded_RNG rng(null_rng, no_entropy_for_you);
1✔
716
         } catch(Botan::PRNG_Unseeded&) {
1✔
717
            result.test_success("AutoSeeded_RNG rejected useless RNG+entropy sources");
1✔
718
         }
1✔
719
   #endif
720

721
         Botan::AutoSeeded_RNG rng;
1✔
722

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

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

730
         // AutoSeeded_RNG automatically reseeds as required:
731
         rng.random_vec(16);
1✔
732
         result.confirm("AutoSeeded_RNG can be reseeded", rng.is_seeded());
2✔
733

734
         result.confirm("AutoSeeded_RNG ", rng.is_seeded());
2✔
735
         rng.random_vec(16);  // generate and discard output
1✔
736
         rng.clear();
1✔
737
         result.test_eq("AutoSeeded_RNG unseeded after calling clear", rng.is_seeded(), false);
1✔
738

739
   #if defined(BOTAN_HAS_ENTROPY_SOURCE)
740
         const size_t no_entropy_bits = rng.reseed_from(no_entropy_for_you, 256);
1✔
741
         result.test_eq("AutoSeeded_RNG can't reseed from nothing", no_entropy_bits, 0);
1✔
742
         result.test_eq("AutoSeeded_RNG still unseeded", rng.is_seeded(), false);
1✔
743
   #endif
744

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

748
         for(size_t i = 0; i != 4096; ++i) {
4,097✔
749
            std::vector<uint8_t> buf(i);
4,096✔
750
            rng.randomize(buf.data(), buf.size());
4,096✔
751
            rng.add_entropy(buf.data(), buf.size());
4,096✔
752

753
            result.test_success("AutoSeeded_RNG accepted input and output length");
8,192✔
754
         }
4,096✔
755

756
         rng.clear();
1✔
757

758
         return result;
1✔
759
      }
1✔
760

761
   public:
762
      std::vector<Test::Result> run() override {
1✔
763
         std::vector<Test::Result> results;
1✔
764
         results.push_back(auto_rng_tests());
2✔
765
         return results;
1✔
766
      }
×
767
};
768

769
BOTAN_REGISTER_TEST("rng", "auto_rng_unit", AutoSeeded_RNG_Tests);
770

771
#endif
772

773
#if defined(BOTAN_HAS_SYSTEM_RNG)
774

775
class System_RNG_Tests final : public Test {
1✔
776
   public:
777
      std::vector<Test::Result> run() override {
1✔
778
         Test::Result result("System_RNG");
1✔
779

780
         Botan::System_RNG rng;
1✔
781

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

784
         result.confirm("System RNG always seeded", rng.is_seeded());
3✔
785
         rng.clear();  // clear is a noop for system rng
1✔
786
         result.confirm("System RNG always seeded", rng.is_seeded());
3✔
787

788
   #if defined(BOTAN_HAS_ENTROPY_SOURCE)
789
         rng.reseed_from(Botan::Entropy_Sources::global_sources(), 256);
1✔
790
   #endif
791

792
         for(size_t i = 0; i != 128; ++i) {
129✔
793
            std::vector<uint8_t> out_buf(i);
128✔
794
            rng.randomize(out_buf.data(), out_buf.size());
128✔
795
            rng.add_entropy(out_buf.data(), out_buf.size());
128✔
796
         }
128✔
797

798
         if(Test::run_long_tests() && Test::run_memory_intensive_tests() && (sizeof(size_t) > 4)) {
1✔
799
            // Pass buffer with a size greater than 32bit
800
            constexpr size_t maximum_u32 = 0xFFFFFFFF;
1✔
801
            const size_t checkSize = 1024;
1✔
802
            std::vector<uint8_t> large_buf(maximum_u32 + checkSize);
1✔
803
            std::memset(large_buf.data() + maximum_u32, 0xFE, checkSize);
1✔
804

805
            rng.randomize(large_buf.data(), large_buf.size());
1✔
806

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

809
            result.confirm("System RNG failed to write after 4GB boundary",
2✔
810
                           std::memcmp(large_buf.data() + maximum_u32, check_buf.data(), checkSize) != 0);
1✔
811
         }
2✔
812

813
         return std::vector<Test::Result>{result};
2✔
814
      }
2✔
815
};
816

817
BOTAN_REGISTER_TEST("rng", "system_rng", System_RNG_Tests);
818

819
#endif
820

821
#if defined(BOTAN_HAS_PROCESSOR_RNG)
822

823
class Processor_RNG_Tests final : public Test {
1✔
824
   public:
825
      std::vector<Test::Result> run() override {
1✔
826
         Test::Result result("Processor_RNG");
1✔
827

828
         if(Botan::Processor_RNG::available()) {
1✔
829
            Botan::Processor_RNG rng;
1✔
830

831
            result.test_ne("Has a name", rng.name(), "");
2✔
832
            result.confirm("CPU RNG always seeded", rng.is_seeded());
2✔
833
            rng.clear();  // clear is a noop for rdrand
1✔
834
            result.confirm("CPU RNG always seeded", rng.is_seeded());
2✔
835

836
   #if defined(BOTAN_HAS_ENTROPY_SOURCE)
837
            const size_t reseed_bits = rng.reseed_from(Botan::Entropy_Sources::global_sources(), 256);
1✔
838
            result.test_eq("CPU RNG cannot consume inputs", reseed_bits, size_t(0));
1✔
839
   #endif
840

841
            /*
842
            Processor_RNG ignores add_entropy calls - confirm this by passing
843
            an invalid ptr/length field to add_entropy. If it examined its
844
            arguments, it would crash...
845
            */
846
            // NOLINTNEXTLINE(*-no-int-to-ptr)
847
            const uint8_t* invalid_ptr = reinterpret_cast<const uint8_t*>(static_cast<uintptr_t>(0xDEADC0DE));
1✔
848
            const size_t invalid_ptr_len = 64 * 1024;
1✔
849
            rng.add_entropy(invalid_ptr, invalid_ptr_len);
1✔
850

851
            for(size_t i = 0; i != 128; ++i) {
129✔
852
               std::vector<uint8_t> out_buf(i);
128✔
853
               rng.randomize(out_buf.data(), out_buf.size());
128✔
854
            }
128✔
855
         } else {
1✔
856
            result.test_throws("Processor_RNG throws if instruction not available",
×
857
                               []() { const Botan::Processor_RNG rng; });
×
858
         }
859

860
         return std::vector<Test::Result>{result};
3✔
861
      }
2✔
862
};
863

864
BOTAN_REGISTER_TEST("rng", "processor_rng", Processor_RNG_Tests);
865

866
#endif
867

868
}  // namespace
869

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