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

randombit / botan / 21786344715

07 Feb 2026 08:25PM UTC coverage: 90.068% (-0.005%) from 90.073%
21786344715

Pull #5295

github

web-flow
Merge 8d5fc3b23 into ebf8f0044
Pull Request #5295: Reduce header dependencies in tests and cli

102234 of 113507 relevant lines covered (90.07%)

11372278.81 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 "tests.h"
9

10
#include "test_rng.h"
11

12
#include <botan/exceptn.h>
13
#include <botan/internal/target_info.h>
14
#include <cstring>
15

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

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

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

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

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

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

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

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

50
namespace Botan_Tests {
51

52
namespace {
53

54
#if defined(BOTAN_HAS_STATEFUL_RNG)
55

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

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

82
         return results;
2✔
83
      }
×
84

85
   protected:
86
      virtual std::string rng_name() const = 0;
87

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

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

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

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

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

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

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

114
      virtual Test::Result test_reseed_interval_limits() = 0;
115

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

120
         // test reseed_interval is enforced
121
         Request_Counting_RNG counting_rng;
2✔
122

123
         auto rng = make_rng(counting_rng, 2);
2✔
124

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

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

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

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

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

149
         return result;
4✔
150
      }
2✔
151

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

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

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

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

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

173
         // make sure no output is generated when the entropy input source is broken
174

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

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

182
   #if defined(BOTAN_HAS_ENTROPY_SOURCE)
183

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

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

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

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

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

204
         // one of or both underlying_rng and entropy_sources throw exception
205

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

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

212
         auto rng_with_good_rng_and_broken_es = make_rng(this->rng(), broken_entropy_sources);
2✔
213

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

217
         auto rng_with_broken_rng_and_broken_es = make_rng(broken_entropy_input_rng, broken_entropy_sources);
2✔
218

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

224
         return result;
4✔
225
      }
12✔
226

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

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

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

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

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

249
         return result;
2✔
250
      }
2✔
251

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

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

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

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

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

268
         return result;
4✔
269
      }
2✔
270

271
      Test::Result test_fork_safety() {
×
272
         Test::Result result(rng_name() + " Fork Safety");
×
273

274
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1)
275
         const size_t reseed_interval = 1024;
×
276

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

384
         return result;
2✔
385
      }
10✔
386

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

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

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

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

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

403
         return result;
2✔
404
      }
4✔
405
};
406

407
#endif
408

409
#if defined(BOTAN_HAS_HMAC_DRBG) && defined(BOTAN_HAS_SHA2_32)
410

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

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

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

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

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

439
         Request_Counting_RNG counting_rng;
1✔
440

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

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

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

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

462
         rng.clear();
1✔
463
         counting_rng.clear();
1✔
464

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

468
         rng.clear();
1✔
469
         counting_rng.clear();
1✔
470

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

474
         rng.clear();
1✔
475
         counting_rng.clear();
1✔
476

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

480
         return result;
2✔
481
      }
1✔
482

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

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

488
         Request_Counting_RNG counting_rng;
1✔
489

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

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

501
         return result;
1✔
502
      }
1✔
503

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

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

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

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

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

525
         return result;
1✔
526
      }
3✔
527

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

531
         Request_Counting_RNG counting_rng;
1✔
532
         auto rng = make_rng(counting_rng, 2);
1✔
533

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

538
         result.test_eq("is_seeded", rng->is_seeded(), false);
1✔
539

540
         rng->initialize_with(seed_input.data(), seed_input.size());
1✔
541

542
         Botan::secure_vector<uint8_t> out(32);
1✔
543

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

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

553
         return result;
2✔
554
      }
3✔
555
};
556

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

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

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

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

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

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

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

587
                    return result;
1✔
588
                 }),
5✔
589

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

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

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

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

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

608
              return result;
1✔
609
           })};
6✔
610
}
2✔
611

612
BOTAN_REGISTER_TEST("rng", "hmac_drbg_unit", HMAC_DRBG_Unit_Tests);
613
BOTAN_REGISTER_TEST_FN("rng", "hmac_drbg_multi_request", hmac_drbg_multiple_requests);
614

615
#endif
616

617
#if defined(BOTAN_HAS_CHACHA_RNG)
618

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

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

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

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

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

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

661
         Request_Counting_RNG counting_rng;
1✔
662
         auto rng = make_rng(counting_rng, 2);
1✔
663

664
         const Botan::secure_vector<uint8_t> seed_input(32);
1✔
665

666
         result.test_eq("is_seeded", rng->is_seeded(), false);
1✔
667

668
         rng->initialize_with(seed_input.data(), seed_input.size());
1✔
669

670
         Botan::secure_vector<uint8_t> out(32);
1✔
671

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

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

681
         return result;
2✔
682
      }
3✔
683
};
684

685
BOTAN_REGISTER_TEST("rng", "chacha_rng_unit", ChaCha_RNG_Unit_Tests);
686

687
#endif
688

689
#if defined(BOTAN_HAS_AUTO_RNG)
690

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

696
         Botan::Null_RNG null_rng;
1✔
697

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

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

706
   #if defined(BOTAN_HAS_ENTROPY_SOURCE)
707
         Botan::Entropy_Sources no_entropy_for_you;
1✔
708

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

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

723
         Botan::AutoSeeded_RNG rng;
1✔
724

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

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

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

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

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

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

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

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

758
         rng.clear();
1✔
759

760
         return result;
1✔
761
      }
1✔
762

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

771
BOTAN_REGISTER_TEST("rng", "auto_rng_unit", AutoSeeded_RNG_Tests);
772

773
#endif
774

775
#if defined(BOTAN_HAS_SYSTEM_RNG)
776

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

782
         Botan::System_RNG rng;
1✔
783

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

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

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

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

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

807
            rng.randomize(large_buf.data(), large_buf.size());
1✔
808

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

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

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

819
BOTAN_REGISTER_TEST("rng", "system_rng", System_RNG_Tests);
820

821
#endif
822

823
#if defined(BOTAN_HAS_PROCESSOR_RNG)
824

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

830
         if(Botan::Processor_RNG::available()) {
1✔
831
            Botan::Processor_RNG rng;
1✔
832

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

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

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

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

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

866
BOTAN_REGISTER_TEST("rng", "processor_rng", Processor_RNG_Tests);
867

868
#endif
869

870
}  // namespace
871

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