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

randombit / botan / 5079590438

25 May 2023 12:28PM UTC coverage: 92.228% (+0.5%) from 91.723%
5079590438

Pull #3502

github

Pull Request #3502: Apply clang-format to the codebase

75589 of 81959 relevant lines covered (92.23%)

12139530.51 hits per line

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

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

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

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

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

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

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

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

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

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

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

44
namespace Botan_Tests {
45

46
namespace {
47

48
#if defined(BOTAN_HAS_STATEFUL_RNG)
49

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

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

75
         return results;
2✔
76
      }
×
77

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

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

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

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

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

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

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

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

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

109
   private:
110
      Test::Result test_reseed() {
2✔
111
         Test::Result result(rng_name() + " Reseed");
2✔
112

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

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

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

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

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

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

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

142
         return result;
4✔
143
      }
2✔
144

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

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

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

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

161
               size_t poll(Botan::RandomNumberGenerator& /*rng*/) override { return 0; }
2✔
162
         };
163

164
         // make sure no output is generated when the entropy input source is broken
165

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

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

173
         // entropy_sources throw exception
174
         auto broken_entropy_source_1 = std::make_unique<Broken_Entropy_Source>();
2✔
175
         auto broken_entropy_source_2 = std::make_unique<Broken_Entropy_Source>();
2✔
176

177
         Botan::Entropy_Sources broken_entropy_sources;
2✔
178
         broken_entropy_sources.add_source(std::move(broken_entropy_source_1));
2✔
179
         broken_entropy_sources.add_source(std::move(broken_entropy_source_2));
2✔
180

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

184
         // entropy source returns insufficient entropy
185
         Botan::Entropy_Sources insufficient_entropy_sources;
2✔
186
         auto insufficient_entropy_source = std::make_unique<Insufficient_Entropy_Source>();
2✔
187
         insufficient_entropy_sources.add_source(std::move(insufficient_entropy_source));
2✔
188

189
         auto rng_with_insufficient_es = make_rng(insufficient_entropy_sources);
2✔
190
         result.test_throws("insufficient entropy source",
4✔
191
                            [&rng_with_insufficient_es]() { rng_with_insufficient_es->random_vec(16); });
2✔
192

193
         // one of or both underlying_rng and entropy_sources throw exception
194

195
         auto rng_with_broken_rng_and_good_es =
2✔
196
            make_rng(broken_entropy_input_rng, Botan::Entropy_Sources::global_sources());
2✔
197

198
         result.test_throws("broken underlying rng but good entropy sources",
4✔
199
                            [&rng_with_broken_rng_and_good_es]() { rng_with_broken_rng_and_good_es->random_vec(16); });
2✔
200

201
         auto rng_with_good_rng_and_broken_es = make_rng(Test::rng(), broken_entropy_sources);
2✔
202

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

206
         auto rng_with_broken_rng_and_broken_es = make_rng(broken_entropy_input_rng, broken_entropy_sources);
2✔
207

208
         result.test_throws("underlying rng and entropy sources broken", [&rng_with_broken_rng_and_broken_es]() {
4✔
209
            rng_with_broken_rng_and_broken_es->random_vec(16);
2✔
210
         });
×
211

212
         return result;
4✔
213
      }
12✔
214

215
      Test::Result test_check_nonce() {
2✔
216
         Test::Result result(rng_name() + " Nonce Check");
2✔
217

218
         // make sure the nonce has at least security_strength bits
219
         auto rng = create_rng(nullptr, nullptr, 0);
2✔
220

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

225
            const std::vector<uint8_t> nonce(nonce_size);
16✔
226
            rng->initialize_with(nonce.data(), nonce.size());
16✔
227

228
            if(nonce_size < rng->security_level() / 8) {
16✔
229
               result.test_eq("not seeded", rng->is_seeded(), false);
10✔
230
               result.test_throws("invalid nonce size", [&rng]() { rng->random_vec(32); });
40✔
231
            } else {
232
               result.test_eq("is seeded", rng->is_seeded(), true);
6✔
233
               rng->random_vec(32);
12✔
234
            }
235
         }
16✔
236

237
         return result;
2✔
238
      }
2✔
239

240
      Test::Result test_prediction_resistance() {
2✔
241
         Test::Result result(rng_name() + " Prediction Resistance");
2✔
242

243
         // set reseed_interval = 1, forcing a reseed for every RNG request
244
         Request_Counting_RNG counting_rng;
2✔
245
         auto rng = make_rng(counting_rng, 1);
2✔
246

247
         rng->random_vec(16);
2✔
248
         result.test_eq("first request", counting_rng.randomize_count(), size_t(1));
2✔
249

250
         rng->random_vec(16);
2✔
251
         result.test_eq("second request", counting_rng.randomize_count(), size_t(2));
2✔
252

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

256
         return result;
4✔
257
      }
2✔
258

259
      Test::Result test_fork_safety() {
×
260
         Test::Result result(rng_name() + " Fork Safety");
×
261

262
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1)
263
         const size_t reseed_interval = 1024;
×
264

265
         // make sure rng is reseeded after every fork
266
         Request_Counting_RNG counting_rng;
×
267
         auto rng = make_rng(counting_rng, reseed_interval);
×
268

269
         rng->random_vec(16);
×
270
         result.test_eq("first request", counting_rng.randomize_count(), size_t(1));
×
271

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

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

294
            if(got > 0) {
×
295
               result.test_eq("expected bytes from child", got, sizeof(count));
×
296
               result.test_eq("parent not reseeded", counting_rng.randomize_count(), 1);
×
297
               result.test_eq("child reseed occurred", count, 2);
×
298
            } else {
299
               result.test_failure("Failed to read count size from child process");
×
300
            }
301

302
            parent_bytes = rng->random_vec(16);
×
303
            got = ::read(fd[0], &child_bytes[0], child_bytes.size());
×
304

305
            if(got > 0) {
×
306
               result.test_eq("expected bytes from child", got, child_bytes.size());
×
307
               result.test_ne("parent and child output sequences differ", parent_bytes, child_bytes);
×
308
            } else {
309
               result.test_failure("Failed to read RNG bytes from child process");
×
310
            }
311
            ::close(fd[0]);  // close read end in parent
×
312

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

330
            /*
331
            * We can't call exit because it causes the mlock pool to be freed (#602)
332
            * We can't call _exit because it makes valgrind think we leaked memory.
333
            * So instead we execute something that will return 0 for us.
334
            */
335
            ::execl("/bin/true", "true", NULL);
×
336
            ::_exit(0);  // just in case /bin/true isn't available (sandbox?)
×
337
         }
338
   #endif
339
         return result;
×
340
      }
×
341

342
      Test::Result test_randomize_with_ts_input() {
2✔
343
         Test::Result result(rng_name() + " Randomize With Timestamp Input");
2✔
344

345
         const size_t request_bytes = 64;
2✔
346
         const std::vector<uint8_t> seed(128);
2✔
347

348
         // check that randomize_with_ts_input() creates different output based on a timestamp
349
         // and possibly additional data, such as process id even with identical seeds
350
         Fixed_Output_RNG fixed_output_rng1(seed);
2✔
351
         Fixed_Output_RNG fixed_output_rng2(seed);
2✔
352

353
         auto rng1 = make_rng(fixed_output_rng1);
2✔
354
         auto rng2 = make_rng(fixed_output_rng2);
2✔
355

356
         Botan::secure_vector<uint8_t> output1(request_bytes);
2✔
357
         Botan::secure_vector<uint8_t> output2(request_bytes);
2✔
358

359
         rng1->randomize(output1.data(), output1.size());
2✔
360
         rng2->randomize(output2.data(), output2.size());
2✔
361

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

364
         rng1->randomize_with_ts_input(output1.data(), output1.size());
2✔
365
         rng2->randomize_with_ts_input(output2.data(), output2.size());
2✔
366

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

369
         return result;
2✔
370
      }
10✔
371

372
      Test::Result test_input_output_edge_cases() {
2✔
373
         Test::Result result(rng_name() + " randomize");
2✔
374

375
         const std::vector<uint8_t> seed(128);
2✔
376
         Fixed_Output_RNG fixed_output_rng(seed);
2✔
377

378
         auto rng = make_rng(fixed_output_rng);
2✔
379

380
         for(size_t i = 0; i != 4096; ++i) {
8,194✔
381
            std::vector<uint8_t> buf(i);
8,192✔
382
            rng->randomize(buf.data(), buf.size());
8,192✔
383
            rng->add_entropy(buf.data(), buf.size());
8,192✔
384

385
            result.test_success("RNG accepted input and output length");
16,384✔
386
         }
8,192✔
387

388
         return result;
2✔
389
      }
4✔
390
};
391

392
#endif
393

394
#if defined(BOTAN_HAS_HMAC_DRBG) && defined(BOTAN_HAS_SHA2_32)
395

396
class HMAC_DRBG_Unit_Tests final : public Stateful_RNG_Tests {
×
397
   public:
398
      std::string rng_name() const override { return "HMAC_DRBG"; }
6✔
399

400
      std::unique_ptr<Botan::Stateful_RNG> create_rng(Botan::RandomNumberGenerator* underlying_rng,
13✔
401
                                                      Botan::Entropy_Sources* underlying_es,
402
                                                      size_t reseed_interval) override {
403
         std::unique_ptr<Botan::MessageAuthenticationCode> mac =
13✔
404
            Botan::MessageAuthenticationCode::create("HMAC(SHA-256)");
13✔
405

406
         if(underlying_rng && underlying_es)
13✔
407
            return std::make_unique<Botan::HMAC_DRBG>(std::move(mac), *underlying_rng, *underlying_es, reseed_interval);
3✔
408
         else if(underlying_rng)
10✔
409
            return std::make_unique<Botan::HMAC_DRBG>(std::move(mac), *underlying_rng, reseed_interval);
7✔
410
         else if(underlying_es)
3✔
411
            return std::make_unique<Botan::HMAC_DRBG>(std::move(mac), *underlying_es, reseed_interval);
2✔
412
         else if(reseed_interval == 0)
1✔
413
            return std::make_unique<Botan::HMAC_DRBG>(std::move(mac));
1✔
414
         else
415
            throw Test_Error("Invalid reseed interval in HMAC_DRBG unit test");
×
416
      }
13✔
417

418
      Test::Result test_max_number_of_bytes_per_request() override {
1✔
419
         Test::Result result("HMAC_DRBG max_number_of_bytes_per_request");
1✔
420

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

423
         Request_Counting_RNG counting_rng;
1✔
424

425
         result.test_throws(
2✔
426
            "HMAC_DRBG does not accept 0 for max_number_of_bytes_per_request", [&mac_string, &counting_rng]() {
1✔
427
               Botan::HMAC_DRBG failing_rng(Botan::MessageAuthenticationCode::create(mac_string), counting_rng, 2, 0);
1✔
428
            });
×
429

430
         result.test_throws("HMAC_DRBG does not accept values higher than 64KB for max_number_of_bytes_per_request",
2✔
431
                            [&mac_string, &counting_rng]() {
1✔
432
                               Botan::HMAC_DRBG failing_rng(
1✔
433
                                  Botan::MessageAuthenticationCode::create(mac_string), counting_rng, 2, 64 * 1024 + 1);
1✔
434
                            });
×
435

436
         // set reseed_interval to 1 so we can test that a long request is split
437
         // into multiple, max_number_of_bytes_per_request long requests
438
         // for each smaller request, reseed_check() calls counting_rng::randomize(),
439
         // which we can compare with
440
         Botan::HMAC_DRBG rng(Botan::MessageAuthenticationCode::create(mac_string), counting_rng, 1, 64);
1✔
441

442
         rng.random_vec(63);
1✔
443
         result.test_eq("one request", counting_rng.randomize_count(), 1);
1✔
444

445
         rng.clear();
1✔
446
         counting_rng.clear();
1✔
447

448
         rng.random_vec(64);
1✔
449
         result.test_eq("one request", counting_rng.randomize_count(), 1);
1✔
450

451
         rng.clear();
1✔
452
         counting_rng.clear();
1✔
453

454
         rng.random_vec(65);
1✔
455
         result.test_eq("two requests", counting_rng.randomize_count(), 2);
1✔
456

457
         rng.clear();
1✔
458
         counting_rng.clear();
1✔
459

460
         rng.random_vec(1025);
1✔
461
         result.test_eq("17 requests", counting_rng.randomize_count(), 17);
1✔
462

463
         return result;
2✔
464
      }
1✔
465

466
      Test::Result test_reseed_interval_limits() override {
1✔
467
         Test::Result result("HMAC_DRBG reseed_interval limits");
1✔
468

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

471
         Request_Counting_RNG counting_rng;
1✔
472

473
         result.test_throws("HMAC_DRBG does not accept 0 for reseed_interval", [&mac_string, &counting_rng]() {
2✔
474
            Botan::HMAC_DRBG failing_rng(Botan::MessageAuthenticationCode::create(mac_string), counting_rng, 0);
1✔
475
         });
×
476

477
         result.test_throws("HMAC_DRBG does not accept values higher than 2^24 for reseed_interval",
2✔
478
                            [&mac_string, &counting_rng]() {
1✔
479
                               Botan::HMAC_DRBG failing_rng(Botan::MessageAuthenticationCode::create(mac_string),
1✔
480
                                                            counting_rng,
481
                                                            (static_cast<size_t>(1) << 24) + 1);
1✔
482
                            });
×
483

484
         return result;
1✔
485
      }
1✔
486

487
      Test::Result test_security_level() override {
1✔
488
         Test::Result result("HMAC_DRBG Security Level");
1✔
489

490
         std::vector<std::string> approved_hash_fns{"SHA-1", "SHA-224", "SHA-256", "SHA-512/256", "SHA-384", "SHA-512"};
7✔
491
         std::vector<uint32_t> security_strengths{128, 192, 256, 256, 256, 256};
1✔
492

493
         for(size_t i = 0; i < approved_hash_fns.size(); ++i) {
7✔
494
            std::string hash_fn = approved_hash_fns[i];
6✔
495
            std::string mac_name = "HMAC(" + hash_fn + ")";
6✔
496
            auto mac = Botan::MessageAuthenticationCode::create(mac_name);
6✔
497
            if(!mac) {
6✔
498
               result.note_missing(mac_name);
1✔
499
               continue;
1✔
500
            }
501

502
            Botan::HMAC_DRBG rng(std::move(mac));
5✔
503
            result.test_eq(hash_fn + " security level", rng.security_level(), security_strengths[i]);
5✔
504
         }
7✔
505

506
         return result;
2✔
507
      }
1✔
508

509
      Test::Result test_reseed_kat() override {
1✔
510
         Test::Result result("HMAC_DRBG Reseed KAT");
1✔
511

512
         Request_Counting_RNG counting_rng;
1✔
513
         auto rng = make_rng(counting_rng, 2);
1✔
514

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

519
         result.test_eq("is_seeded", rng->is_seeded(), false);
1✔
520

521
         rng->initialize_with(seed_input.data(), seed_input.size());
1✔
522

523
         Botan::secure_vector<uint8_t> out(32);
1✔
524

525
         rng->randomize(out.data(), out.size());
1✔
526
         result.test_eq("underlying RNG calls", counting_rng.randomize_count(), size_t(0));
1✔
527
         result.test_eq("out before reseed", out, "48D3B45AAB65EF92CCFCB9427EF20C90297065ECC1B8A525BFE4DC6FF36D0E38");
1✔
528

529
         // reseed must happen here
530
         rng->randomize(out.data(), out.size());
1✔
531
         result.test_eq("underlying RNG calls", counting_rng.randomize_count(), size_t(1));
1✔
532
         result.test_eq("out after reseed", out, "2F8FCA696832C984781123FD64F4B20C7379A25C87AB29A21C9BF468B0081CE2");
1✔
533

534
         return result;
2✔
535
      }
3✔
536
};
537

538
std::vector<Test::Result> hmac_drbg_multiple_requests() {
1✔
539
   auto null_rng = Botan::Null_RNG();
1✔
540
   constexpr auto rng_max_output = 1024;
1✔
541
   const auto seed = Botan::hex_decode("deadbeefbaadcafedeadbeefbaadcafedeadbeefbaadcafedeadbeefbaadcafe");
1✔
542

543
   auto make_seeded_rng = [&](size_t reseed_interval) {
5✔
544
      auto rng = std::make_unique<Botan::HMAC_DRBG>(Botan::MessageAuthenticationCode::create("HMAC(SHA-256)"),
8✔
545
                                                    null_rng,
4✔
546
                                                    reseed_interval + 1 /* off by one */,
8✔
547
                                                    rng_max_output);
4✔
548
      rng->add_entropy(seed);
4✔
549
      return rng;
4✔
550
   };
×
551

552
   return {Botan_Tests::CHECK("bulk and split output without input",
1✔
553
                              [&](auto& result) {
1✔
554
                                 auto rng1 = make_seeded_rng(2);
1✔
555
                                 auto rng2 = make_seeded_rng(2);
1✔
556

557
                                 result.confirm("RNG 1 is seeded and ready to go", rng1->is_seeded());
3✔
558
                                 result.confirm("RNG 2 is seeded and ready to go", rng2->is_seeded());
3✔
559

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

562
                                 auto split1 = rng2->random_vec<std::vector<uint8_t>>(rng_max_output);
1✔
563
                                 auto split2 = rng2->random_vec<std::vector<uint8_t>>(rng_max_output);
1✔
564
                                 split1.insert(split1.end(), split2.begin(), split2.end());
1✔
565

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

568
                                 return result;
2✔
569
                              }),
3✔
570

571
           Botan_Tests::CHECK("bulk and split output with input", [&](auto& result) {
1✔
572
              auto rng1 = make_seeded_rng(3);
1✔
573
              auto rng2 = make_seeded_rng(3);
1✔
574

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

578
              std::vector<uint8_t> bulk(3 * rng_max_output);
1✔
579
              rng1->randomize_with_input(bulk, seed);
2✔
580

581
              std::vector<uint8_t> split(3 * rng_max_output);
1✔
582
              std::span<uint8_t> split_span(split);
1✔
583
              rng2->randomize_with_input(split_span.subspan(0, rng_max_output), seed);
2✔
584
              rng2->randomize_with_input(split_span.subspan(rng_max_output, rng_max_output), {});
2✔
585
              rng2->randomize_with_input(split_span.subspan(2 * rng_max_output), {});
2✔
586

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

589
              return result;
2✔
590
           })};
6✔
591
}
1✔
592

593
BOTAN_REGISTER_TEST("rng", "hmac_drbg_unit", HMAC_DRBG_Unit_Tests);
594
BOTAN_REGISTER_TEST_FN("rng", "hmac_drbg_multi_requst", hmac_drbg_multiple_requests);
595

596
#endif
597

598
#if defined(BOTAN_HAS_CHACHA_RNG)
599

600
class ChaCha_RNG_Unit_Tests final : public Stateful_RNG_Tests {
×
601
   public:
602
      std::string rng_name() const override { return "ChaCha_RNG"; }
6✔
603

604
      std::unique_ptr<Botan::Stateful_RNG> create_rng(Botan::RandomNumberGenerator* underlying_rng,
13✔
605
                                                      Botan::Entropy_Sources* underlying_es,
606
                                                      size_t reseed_interval) override {
607
         if(underlying_rng && underlying_es)
13✔
608
            return std::make_unique<Botan::ChaCha_RNG>(*underlying_rng, *underlying_es, reseed_interval);
3✔
609
         else if(underlying_rng)
10✔
610
            return std::make_unique<Botan::ChaCha_RNG>(*underlying_rng, reseed_interval);
7✔
611
         else if(underlying_es)
3✔
612
            return std::make_unique<Botan::ChaCha_RNG>(*underlying_es, reseed_interval);
2✔
613
         else if(reseed_interval == 0)
1✔
614
            return std::make_unique<Botan::ChaCha_RNG>();
1✔
615
         else
616
            throw Test_Error("Invalid reseed interval in ChaCha_RNG unit test");
×
617
      }
618

619
      Test::Result test_security_level() override {
1✔
620
         Test::Result result("ChaCha_RNG Security Level");
1✔
621
         Botan::ChaCha_RNG rng;
1✔
622
         result.test_eq("Expected security level", rng.security_level(), size_t(256));
1✔
623
         return result;
1✔
624
      }
1✔
625

626
      Test::Result test_max_number_of_bytes_per_request() override {
1✔
627
         Test::Result result("ChaCha_RNG max_number_of_bytes_per_request");
1✔
628
         // ChaCha_RNG doesn't have this notion
629
         return result;
1✔
630
      }
631

632
      Test::Result test_reseed_interval_limits() override {
1✔
633
         Test::Result result("ChaCha_RNG reseed_interval limits");
1✔
634
         // ChaCha_RNG doesn't apply any limits to reseed_interval
635
         return result;
1✔
636
      }
637

638
      Test::Result test_reseed_kat() override {
1✔
639
         Test::Result result("ChaCha_RNG Reseed KAT");
1✔
640

641
         Request_Counting_RNG counting_rng;
1✔
642
         auto rng = make_rng(counting_rng, 2);
1✔
643

644
         const Botan::secure_vector<uint8_t> seed_input(32);
1✔
645

646
         result.test_eq("is_seeded", rng->is_seeded(), false);
1✔
647

648
         rng->initialize_with(seed_input.data(), seed_input.size());
1✔
649

650
         Botan::secure_vector<uint8_t> out(32);
1✔
651

652
         rng->randomize(out.data(), out.size());
1✔
653
         result.test_eq("underlying RNG calls", counting_rng.randomize_count(), size_t(0));
1✔
654
         result.test_eq("out before reseed", out, "1F0E6F13429D5073B59C057C37CBE9587740A0A894D247E2596C393CE91DDC6F");
1✔
655

656
         // reseed must happen here
657
         rng->randomize(out.data(), out.size());
1✔
658
         result.test_eq("underlying RNG calls", counting_rng.randomize_count(), size_t(1));
1✔
659
         result.test_eq("out after reseed", out, "F2CAE73F22684D5D773290B48FDCDA0E6C0661EBA0A854AFEC922832BDBB9C49");
1✔
660

661
         return result;
2✔
662
      }
3✔
663
};
664

665
BOTAN_REGISTER_TEST("rng", "chacha_rng_unit", ChaCha_RNG_Unit_Tests);
666

667
#endif
668

669
#if defined(BOTAN_HAS_AUTO_RNG)
670

671
class AutoSeeded_RNG_Tests final : public Test {
×
672
   private:
673
      static Test::Result auto_rng_tests() {
1✔
674
         Test::Result result("AutoSeeded_RNG");
1✔
675

676
         Botan::Entropy_Sources no_entropy_for_you;
1✔
677
         Botan::Null_RNG null_rng;
1✔
678

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

681
         try {
1✔
682
            Botan::AutoSeeded_RNG rng(no_entropy_for_you);
1✔
683
            result.test_failure("AutoSeeded_RNG should have rejected useless entropy source");
×
684
         } catch(Botan::PRNG_Unseeded&) { result.test_success("AutoSeeded_RNG rejected empty entropy source"); }
2✔
685

686
         try {
1✔
687
            Botan::AutoSeeded_RNG rng(null_rng);
1✔
688
         } catch(Botan::PRNG_Unseeded&) { result.test_success("AutoSeeded_RNG rejected useless RNG"); }
2✔
689

690
         try {
1✔
691
            Botan::AutoSeeded_RNG rng(null_rng, no_entropy_for_you);
1✔
692
         } catch(Botan::PRNG_Unseeded&) { result.test_success("AutoSeeded_RNG rejected useless RNG+entropy sources"); }
2✔
693

694
         Botan::AutoSeeded_RNG rng;
1✔
695

696
         result.confirm("AutoSeeded_RNG::name", rng.name().starts_with("HMAC_DRBG(HMAC(SHA-"));
4✔
697

698
         result.confirm("AutoSeeded_RNG starts seeded", rng.is_seeded());
2✔
699
         rng.random_vec(16);  // generate and discard output
1✔
700
         rng.clear();
1✔
701
         result.test_eq("AutoSeeded_RNG unseeded after calling clear", rng.is_seeded(), false);
1✔
702

703
         // AutoSeeded_RNG automatically reseeds as required:
704
         rng.random_vec(16);
1✔
705
         result.confirm("AutoSeeded_RNG can be reseeded", rng.is_seeded());
2✔
706

707
         result.confirm("AutoSeeded_RNG ", rng.is_seeded());
2✔
708
         rng.random_vec(16);  // generate and discard output
1✔
709
         rng.clear();
1✔
710
         result.test_eq("AutoSeeded_RNG unseeded after calling clear", rng.is_seeded(), false);
1✔
711

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

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

719
         for(size_t i = 0; i != 4096; ++i) {
4,097✔
720
            std::vector<uint8_t> buf(i);
4,096✔
721
            rng.randomize(buf.data(), buf.size());
4,096✔
722
            rng.add_entropy(buf.data(), buf.size());
4,096✔
723

724
            result.test_success("AutoSeeded_RNG accepted input and output length");
8,192✔
725
         }
4,096✔
726

727
         rng.clear();
1✔
728

729
         return result;
2✔
730
      }
1✔
731

732
   public:
733
      std::vector<Test::Result> run() override {
1✔
734
         std::vector<Test::Result> results;
1✔
735
         results.push_back(auto_rng_tests());
2✔
736
         return results;
1✔
737
      }
×
738
};
739

740
BOTAN_REGISTER_TEST("rng", "auto_rng_unit", AutoSeeded_RNG_Tests);
741

742
#endif
743

744
#if defined(BOTAN_HAS_SYSTEM_RNG)
745

746
class System_RNG_Tests final : public Test {
×
747
   public:
748
      std::vector<Test::Result> run() override {
1✔
749
         Test::Result result("System_RNG");
1✔
750

751
         Botan::System_RNG rng;
1✔
752

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

755
         result.confirm("System RNG always seeded", rng.is_seeded());
3✔
756
         rng.clear();  // clear is a noop for system rng
1✔
757
         result.confirm("System RNG always seeded", rng.is_seeded());
3✔
758

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

761
         for(size_t i = 0; i != 128; ++i) {
129✔
762
            std::vector<uint8_t> out_buf(i);
128✔
763
            rng.randomize(out_buf.data(), out_buf.size());
128✔
764
            rng.add_entropy(out_buf.data(), out_buf.size());
128✔
765
         }
128✔
766

767
         if(Test::run_long_tests() && Test::run_memory_intensive_tests() && (sizeof(size_t) > 4)) {
1✔
768
            // Pass buffer with a size greater than 32bit
769
            const size_t size32BitsMax = std::numeric_limits<uint32_t>::max();
1✔
770
            const size_t checkSize = 1024;
1✔
771
            std::vector<uint8_t> large_buf(size32BitsMax + checkSize);
1✔
772
            std::memset(large_buf.data() + size32BitsMax, 0xFE, checkSize);
1✔
773

774
            rng.randomize(large_buf.data(), large_buf.size());
1✔
775

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

778
            result.confirm("System RNG failed to write after 4GB boundry",
3✔
779
                           std::memcmp(large_buf.data() + size32BitsMax, check_buf.data(), checkSize) != 0);
1✔
780
         }
2✔
781

782
         return std::vector<Test::Result>{result};
2✔
783
      }
1✔
784
};
785

786
BOTAN_REGISTER_TEST("rng", "system_rng", System_RNG_Tests);
787

788
#endif
789

790
#if defined(BOTAN_HAS_PROCESSOR_RNG)
791

792
class Processor_RNG_Tests final : public Test {
×
793
   public:
794
      std::vector<Test::Result> run() override {
1✔
795
         Test::Result result("Processor_RNG");
1✔
796

797
         if(Botan::Processor_RNG::available()) {
1✔
798
            Botan::Processor_RNG rng;
1✔
799

800
            result.test_ne("Has a name", rng.name(), "");
2✔
801
            result.confirm("CPU RNG always seeded", rng.is_seeded());
2✔
802
            rng.clear();  // clear is a noop for rdrand
1✔
803
            result.confirm("CPU RNG always seeded", rng.is_seeded());
2✔
804

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

808
            /*
809
            Processor_RNG ignores add_entropy calls - confirm this by passing
810
            an invalid ptr/length field to add_entropy. If it examined its
811
            arguments, it would crash...
812
            */
813
            // NOLINTNEXTLINE(*-no-int-to-ptr)
814
            const uint8_t* invalid_ptr = reinterpret_cast<const uint8_t*>(static_cast<uintptr_t>(0xDEADC0DE));
1✔
815
            const size_t invalid_ptr_len = 64 * 1024;
1✔
816
            rng.add_entropy(invalid_ptr, invalid_ptr_len);
1✔
817

818
            for(size_t i = 0; i != 128; ++i) {
129✔
819
               std::vector<uint8_t> out_buf(i);
128✔
820
               rng.randomize(out_buf.data(), out_buf.size());
128✔
821
            }
128✔
822
         } else {
1✔
823
            result.test_throws("Processor_RNG throws if instruction not available", []() { Botan::Processor_RNG rng; });
×
824
         }
825

826
         return std::vector<Test::Result>{result};
3✔
827
      }
1✔
828
};
829

830
BOTAN_REGISTER_TEST("rng", "processor_rng", Processor_RNG_Tests);
831

832
#endif
833

834
}
835

836
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc