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

randombit / botan / 20579846577

29 Dec 2025 06:24PM UTC coverage: 90.415% (+0.2%) from 90.243%
20579846577

push

github

web-flow
Merge pull request #5167 from randombit/jack/src-size-reductions

Changes to reduce unnecessary inclusions

101523 of 112285 relevant lines covered (90.42%)

12817276.56 hits per line

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

85.44
/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
#endif
21

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

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

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

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

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

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

47
namespace Botan_Tests {
48

49
namespace {
50

51
#if defined(BOTAN_HAS_STATEFUL_RNG)
52

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

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

79
         return results;
2✔
80
      }
×
81

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

146
         return result;
4✔
147
      }
2✔
148

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

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

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

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

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

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

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

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

179
   #if defined(BOTAN_HAS_ENTROPY_SOURCE)
180

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

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

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

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

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

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

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

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

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

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

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

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

221
         return result;
4✔
222
      }
12✔
223

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

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

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

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

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

246
         return result;
2✔
247
      }
2✔
248

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

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

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

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

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

265
         return result;
4✔
266
      }
2✔
267

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

381
         return result;
2✔
382
      }
10✔
383

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

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

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

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

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

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

404
#endif
405

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

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

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

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

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

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

436
         Request_Counting_RNG counting_rng;
1✔
437

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

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

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

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

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

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

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

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

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

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

477
         return result;
2✔
478
      }
1✔
479

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

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

485
         Request_Counting_RNG counting_rng;
1✔
486

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

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

498
         return result;
1✔
499
      }
1✔
500

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

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

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

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

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

522
         return result;
1✔
523
      }
3✔
524

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

584
                    return result;
2✔
585
                 }),
3✔
586

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

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

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

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

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

605
              return result;
2✔
606
           })};
6✔
607
}
2✔
608

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

612
#endif
613

614
#if defined(BOTAN_HAS_CHACHA_RNG)
615

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

684
#endif
685

686
#if defined(BOTAN_HAS_AUTO_RNG)
687

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

693
         Botan::Null_RNG null_rng;
1✔
694

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

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

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

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

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

720
         Botan::AutoSeeded_RNG rng;
1✔
721

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

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

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

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

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

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

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

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

755
         rng.clear();
1✔
756

757
         return result;
1✔
758
      }
1✔
759

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

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

770
#endif
771

772
#if defined(BOTAN_HAS_SYSTEM_RNG)
773

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

779
         Botan::System_RNG rng;
1✔
780

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

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

787
   #if defined(BOTAN_HAS_ENTROPY_SOURCE)
788
         rng.reseed(Botan::Entropy_Sources::global_sources(), 256, std::chrono::milliseconds(100));
1✔
789
   #endif
790

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

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

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

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

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

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

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

818
#endif
819

820
#if defined(BOTAN_HAS_PROCESSOR_RNG)
821

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

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

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

835
   #if defined(BOTAN_HAS_ENTROPY_SOURCE)
836
            const size_t reseed_bits =
1✔
837
               rng.reseed(Botan::Entropy_Sources::global_sources(), 256, std::chrono::seconds(1));
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