Botan 3.14.1
Crypto and TLS for C&
rng.h
Go to the documentation of this file.
1/*
2* Random Number Generator base classes
3* (C) 1999-2009,2015,2016 Jack Lloyd
4* 2023 René Meusel - Rohde & Schwarz Cybersecurity
5*
6* Botan is released under the Simplified BSD License (see license.txt)
7*/
8
9#ifndef BOTAN_RANDOM_NUMBER_GENERATOR_H_
10#define BOTAN_RANDOM_NUMBER_GENERATOR_H_
11
12#include <botan/concepts.h>
13#include <botan/secmem.h>
14
15#include <array>
16#include <concepts>
17#include <span>
18#include <string>
19#include <type_traits>
20
21/*
22* We only include <chrono> in downstream applications to avoid
23* breaking semver wrt RandomNumberGenerator::reseed. Within the
24* library we avoid it because it slows down compilation significantly.
25*
26* TODO(Botan4): remove this entirely
27*/
28#if !defined(BOTAN_IS_BEING_BUILT)
29 #include <chrono>
30#endif
31
32namespace Botan {
33
34class Entropy_Sources;
35
36/**
37* An interface to a cryptographic random number generator
38*/
40 public:
41 /**
42 * Userspace RNGs like HMAC_DRBG will reseed after a specified number
43 * of outputs are generated. Set to zero to disable automatic reseeding.
44 */
45 static constexpr size_t DefaultReseedInterval = 1024;
46
47 /**
48 * Number of entropy bits polled for reseeding userspace RNGs like HMAC_DRBG
49 */
50 static constexpr size_t DefaultPollBits = 256;
51
52 virtual ~RandomNumberGenerator() = default;
53
54 /**
55 * Default constructor
56 */
58
59 /*
60 * Never copy a RNG, create a new one
61 */
64
65 /**
66 * Move constructor
67 */
69
70 /**
71 * Move assignment
72 * @return reference to this
73 */
75
76 /**
77 * Randomize a byte array.
78 *
79 * May block shortly if e.g. the RNG is not yet initialized
80 * or a retry because of insufficient entropy is needed.
81 *
82 * @param output the byte array to hold the random output.
83 * @throws PRNG_Unseeded if the RNG fails because it has not enough entropy
84 * @throws Exception if the RNG fails
85 */
86 void randomize(std::span<uint8_t> output) { this->fill_bytes_with_input(output, {}); }
87
88 /**
89 * Randomize a byte array
90 * @param output the byte array to hold the random output
91 * @param length the number of bytes to generate
92 */
93 void randomize(uint8_t output[], size_t length) { this->randomize(std::span(output, length)); }
94
95 /**
96 * Returns false if it is known that this RNG object is not able to accept
97 * externally provided inputs (via add_entropy, randomize_with_input, etc).
98 * In this case, any such provided inputs are ignored.
99 *
100 * If this function returns true, then inputs may or may not be accepted.
101 */
102 virtual bool accepts_input() const = 0;
103
104 /**
105 * Provide seed material to the RNG.
106 *
107 * The caller asserts that the input is full entropy seed material. For a
108 * stateful RNG such as HMAC_DRBG, an input of at least security_level()
109 * bits marks the RNG as seeded.
110 *
111 * To mix in data of unknown quality (nonces, timestamps, values from a
112 * peer's protocol message) without affecting the seeded state, instead
113 * call randomize_with_input with an empty output buffer.
114 *
115 * A few RNG types do not accept any externally provided input,
116 * in which case this function is a no-op.
117 *
118 * @param input a byte array containing the entropy to be added
119 * @throws Exception may throw if the RNG accepts input, but adding the entropy failed.
120 */
121 void add_entropy(std::span<const uint8_t> input) { this->accept_seed_material(input); }
122
123 /**
124 * Provide seed material to the RNG, see add_entropy
125 * @param input a byte array containing the entropy to be added
126 * @param length the number of bytes in input
127 */
128 void add_entropy(const uint8_t input[], size_t length) { this->add_entropy(std::span(input, length)); }
129
130 /**
131 * Provide seed material to the RNG, see add_entropy
132 */
133 template <typename T>
134 requires std::is_standard_layout_v<T> && std::is_trivial_v<T>
135 void add_entropy_T(const T& t) {
136 this->add_entropy(reinterpret_cast<const uint8_t*>(&t), sizeof(T));
137 }
138
139 /**
140 * Incorporate additional input into the RNG state then produce output.
141 *
142 * Use this to further bind the outputs to your current
143 * process/protocol state. For instance if generating a new key
144 * for use in a session, include a session ID or other such
145 * value. See NIST SP 800-90 A, B, C series for more ideas.
146 *
147 * The input is never credited as entropy: if the output buffer is
148 * empty, the input is mixed into the state of a stateful RNG without
149 * affecting whether it is considered seeded. Use add_entropy to
150 * provide seed material.
151 *
152 * @param output buffer to hold the random output
153 * @param input entropy buffer to incorporate
154 * @throws PRNG_Unseeded if the RNG fails because it has not enough entropy
155 * @throws Exception if the RNG fails
156 * @throws Exception may throw if the RNG accepts input, but adding the entropy failed.
157 */
158 void randomize_with_input(std::span<uint8_t> output, std::span<const uint8_t> input) {
159 this->fill_bytes_with_input(output, input);
160 }
161
162 /**
163 * Randomize a byte array, first incorporating additional input
164 * @param output the byte array to hold the random output
165 * @param output_len the number of bytes to generate
166 * @param input a byte array containing the entropy to be added
167 * @param input_len the number of bytes in input
168 */
169 void randomize_with_input(uint8_t output[], size_t output_len, const uint8_t input[], size_t input_len) {
170 this->randomize_with_input(std::span(output, output_len), std::span(input, input_len));
171 }
172
173 /**
174 * This calls `randomize_with_input` using system specific values
175 *
176 * This first attempts to provide input to the underlying RNG from some system
177 * specific source. The additional input consists of an 8 byte timestamp from the
178 * local clock. The remainder of the 22 byte input is filled from the system RNG if
179 * available, otherwise the current process ID is appended.
180 *
181 * For a stateful RNG that was already correctly seeded with sufficient
182 * cryptographically secure material, using non-random but potentially unique data
183 * as the extra input can help protect against problems with fork, VM state
184 * rollback, or other cases where somehow an RNG state is duplicated. If both of
185 * the duplicated RNG states later incorporate some input, even predictable input,
186 * their outputs will diverge.
187 *
188 * @param output buffer to hold the random output
189 * @throws PRNG_Unseeded if the RNG fails because it has not enough entropy
190 * @throws Exception if the RNG fails
191 * @throws Exception may throw if the RNG accepts input, but adding the entropy failed.
192 */
193 void randomize_with_ts_input(std::span<uint8_t> output);
194
195 /**
196 * Randomize a byte array, using timestamps as additional input
197 * @param output the byte array to hold the random output
198 * @param output_len the number of bytes to generate
199 */
200 void randomize_with_ts_input(uint8_t output[], size_t output_len) {
201 this->randomize_with_ts_input(std::span(output, output_len));
202 }
203
204 /**
205 * Return the name of this RNG type
206 * @return the name of this RNG type
207 */
208 virtual std::string name() const = 0;
209
210 /**
211 * Clear all internally held values of this RNG
212 * @post is_seeded() == false if the RNG has an internal state that can be cleared.
213 */
214 virtual void clear() = 0;
215
216 /**
217 * Check whether this RNG is seeded.
218 * @return true if this RNG was already seeded, false otherwise.
219 */
220 virtual bool is_seeded() const = 0;
221
222 /**
223 * Poll provided sources for up to poll_bits bits of entropy.
224 * Returns estimate of the number of bits collected.
225 * Sets the seeded state to true if enough entropy was added.
226 *
227 * @throws Exception if RNG accepts input but reseeding failed.
228 */
230 return reseed_from_sources(srcs, poll_bits);
231 }
232
233 /**
234 * Reseed by reading specified bits from the RNG
235 *
236 * Sets the seeded state to true if enough entropy was added.
237 *
238 * @throws Exception if RNG accepts input but reseeding failed.
239 */
241 return reseed_from_rng(rng, poll_bits);
242 }
243
244 // Some utility functions built on the interface above:
245
246 /**
247 * Fill a given byte container with @p bytes random bytes
248 *
249 * @todo deprecate this overload (in favor of randomize())
250 *
251 * @param v the container to be filled with @p bytes random bytes
252 * @throws Exception if RNG fails
253 */
254 void random_vec(std::span<uint8_t> v) { this->randomize(v); }
255
256 /**
257 * Resize a given byte container to @p bytes and fill it with random bytes
258 *
259 * @tparam T the desired byte container type (e.g std::vector<uint8_t>)
260 * @param v the container to be filled with @p bytes random bytes
261 * @param bytes number of random bytes to initialize the container with
262 * @throws Exception if RNG or memory allocation fails
263 */
264 template <concepts::resizable_byte_buffer T>
265 void random_vec(T& v, size_t bytes) {
266 v.resize(bytes);
267 random_vec(v);
268 }
269
270 /**
271 * Create some byte container type and fill it with some random @p bytes.
272 *
273 * @tparam T the desired byte container type (e.g std::vector<uint8_t>)
274 * @param bytes number of random bytes to initialize the container with
275 * @return a container of type T with @p bytes random bytes
276 * @throws Exception if RNG or memory allocation fails
277 */
278 template <concepts::resizable_byte_buffer T = secure_vector<uint8_t>>
279 requires std::default_initializable<T>
280 T random_vec(size_t bytes) {
281 T result;
282 random_vec(result, bytes);
283 return result;
284 }
285
286 /**
287 * Create a std::array of @p bytes random bytes
288 */
289 template <size_t bytes>
290 std::array<uint8_t, bytes> random_array() {
291 std::array<uint8_t, bytes> result{};
292 random_vec(result);
293 return result;
294 }
295
296 /**
297 * Return a random byte
298 * @return random byte
299 * @throws PRNG_Unseeded if the RNG fails because it has not enough entropy
300 * @throws Exception if the RNG fails
301 */
302 uint8_t next_byte() {
303 uint8_t b = 0;
304 this->fill_bytes_with_input(std::span(&b, 1), {});
305 return b;
306 }
307
308 /**
309 * Generate a single random byte which is not zero
310 * @return a random byte that is greater than zero
311 * @throws PRNG_Unseeded if the RNG fails because it has not enough entropy
312 * @throws Exception if the RNG fails
313 */
315 uint8_t b = this->next_byte();
316 while(b == 0) {
317 b = this->next_byte();
318 }
319 return b;
320 }
321
322 /**
323 * Reseed by reading specified bits from the RNG
324 *
325 * Sets the seeded state to true if enough entropy was added.
326 *
327 * @throws Exception if RNG accepts input but reseeding failed.
328 */
329 virtual void reseed_from_rng(RandomNumberGenerator& rng,
330 size_t poll_bits = RandomNumberGenerator::DefaultPollBits);
331
332#if !defined(BOTAN_IS_BEING_BUILT)
333 /**
334 * Default poll timeout
335 */
336 static constexpr auto DefaultPollTimeout = std::chrono::milliseconds(50);
337
338 /**
339 * Poll provided sources for up to poll_bits bits of entropy.
340 * Returns estimate of the number of bits collected.
341 *
342 * Sets the seeded state to true if enough entropy was added.
343 *
344 * TODO(Botan4) remove this function
345 */
346 BOTAN_DEPRECATED("Use reseed_from_sources")
347 inline size_t reseed(Entropy_Sources& srcs,
348 size_t poll_bits = RandomNumberGenerator::DefaultPollBits,
349 std::chrono::milliseconds /*unused_timeout*/ = DefaultPollTimeout) {
350 return reseed_from(srcs, poll_bits);
351 }
352#endif
353
354 protected:
355 /**
356 * Poll provided sources for up to poll_bits bits of entropy.
357 * Returns estimate of the number of bits collected.
358 * Sets the seeded state to true if enough entropy was added.
359 *
360 * @throws Exception if RNG accepts input but reseeding failed.
361 */
362 virtual size_t reseed_from_sources(Entropy_Sources& srcs,
363 size_t poll_bits = RandomNumberGenerator::DefaultPollBits);
364
365 /**
366 * Consume seed material provided via add_entropy
367 *
368 * This is the only path through which application provided input may
369 * mark an RNG as seeded. The default implementation forwards the input
370 * to fill_bytes_with_input with an empty output buffer, which is
371 * appropriate for RNGs which do not track a seeded state. RNGs which do
372 * track a seeded state must override this function.
373 */
374 virtual void accept_seed_material(std::span<const uint8_t> input);
375
376 /**
377 * Generic interface to provide entropy to a concrete implementation and to
378 * fill a given buffer with random output. Both @p output and @p input may
379 * be empty and should be ignored in that case. If both buffers are
380 * non-empty implementations should typically first apply the @p input data
381 * and then generate random data into @p output.
382 *
383 * This method must be implemented by all RandomNumberGenerator sub-classes.
384 *
385 * @param output Byte buffer to write random bytes into. Implementations
386 * should not read from this buffer.
387 * @param input Byte buffer that may contain bytes to be incorporated in
388 * the RNG's internal state. Implementations may choose to
389 * ignore the bytes in this buffer.
390 */
391 virtual void fill_bytes_with_input(std::span<uint8_t> output, std::span<const uint8_t> input) = 0;
392};
393
394/**
395* Convenience typedef
396*/
398
399/**
400* Hardware_RNG exists to tag hardware RNG types (PKCS11_RNG, TPM_RNG, Processor_RNG)
401*/
403 public:
404 /**
405 * No-op clear implementation - no way to clear state of a hardware RNG
406 */
407 void clear() final {}
408};
409
410/**
411* Null/stub RNG - fails if you try to use it for anything
412* This is not generally useful except for in certain tests
413*/
415 public:
416 /**
417 * Test whether this RNG has been seeded
418 * @return true if this RNG is seeded and ready for use
419 */
420 bool is_seeded() const override { return false; }
421
422 /**
423 * Test whether this RNG accepts externally provided input
424 * @return false if this RNG is known to ignore provided inputs
425 */
426 bool accepts_input() const override { return false; }
427
428 /**
429 * Clear all internally held values of this RNG
430 */
431 void clear() override {}
432
433 /**
434 * Return the name of this RNG type
435 * @return the name of this RNG type
436 */
437 std::string name() const override { return "Null_RNG"; }
438
439 private:
440 void fill_bytes_with_input(std::span<uint8_t> output, std::span<const uint8_t> /* ignored */) override;
441};
442
443} // namespace Botan
444
445#endif
#define BOTAN_PUBLIC_API(maj, min)
Definition api.h:21
#define BOTAN_DEPRECATED(msg)
Definition api.h:73
void clear() final
Definition rng.h:407
bool accepts_input() const override
Definition rng.h:426
void clear() override
Definition rng.h:431
std::string name() const override
Definition rng.h:437
bool is_seeded() const override
Definition rng.h:420
void randomize(std::span< uint8_t > output)
Definition rng.h:86
RandomNumberGenerator & operator=(RandomNumberGenerator &&rng)=default
std::array< uint8_t, bytes > random_array()
Definition rng.h:290
virtual bool accepts_input() const =0
RandomNumberGenerator(RandomNumberGenerator &&rng)=default
virtual ~RandomNumberGenerator()=default
void add_entropy(std::span< const uint8_t > input)
Definition rng.h:121
virtual void accept_seed_material(std::span< const uint8_t > input)
Definition rng.cpp:30
virtual size_t reseed_from_sources(Entropy_Sources &srcs, size_t poll_bits=RandomNumberGenerator::DefaultPollBits)
Definition rng.cpp:85
void randomize(uint8_t output[], size_t length)
Definition rng.h:93
uint8_t next_nonzero_byte()
Definition rng.h:314
static constexpr size_t DefaultPollBits
Definition rng.h:50
void random_vec(T &v, size_t bytes)
Definition rng.h:265
RandomNumberGenerator & operator=(const RandomNumberGenerator &rng)=delete
static constexpr size_t DefaultReseedInterval
Definition rng.h:45
static constexpr auto DefaultPollTimeout
Definition rng.h:336
virtual bool is_seeded() const =0
void randomize_with_ts_input(uint8_t output[], size_t output_len)
Definition rng.h:200
void add_entropy_T(const T &t)
Definition rng.h:135
void add_entropy(const uint8_t input[], size_t length)
Definition rng.h:128
virtual std::string name() const =0
virtual void reseed_from_rng(RandomNumberGenerator &rng, size_t poll_bits=RandomNumberGenerator::DefaultPollBits)
Definition rng.cpp:99
void randomize_with_ts_input(std::span< uint8_t > output)
Definition rng.cpp:73
void random_vec(std::span< uint8_t > v)
Definition rng.h:254
T random_vec(size_t bytes)
Definition rng.h:280
size_t reseed_from(Entropy_Sources &srcs, size_t poll_bits=RandomNumberGenerator::DefaultPollBits)
Definition rng.h:229
virtual void fill_bytes_with_input(std::span< uint8_t > output, std::span< const uint8_t > input)=0
void randomize_with_input(std::span< uint8_t > output, std::span< const uint8_t > input)
Definition rng.h:158
RandomNumberGenerator(const RandomNumberGenerator &rng)=delete
void reseed_from(RandomNumberGenerator &rng, size_t poll_bits=RandomNumberGenerator::DefaultPollBits)
Definition rng.h:240
void randomize_with_input(uint8_t output[], size_t output_len, const uint8_t input[], size_t input_len)
Definition rng.h:169
size_t reseed(Entropy_Sources &srcs, size_t poll_bits=RandomNumberGenerator::DefaultPollBits, std::chrono::milliseconds=DefaultPollTimeout)
Definition rng.h:347
RandomNumberGenerator RNG
Definition rng.h:397