1 /* Copyright (c) 2001, Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2021, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
8 * \file crypto_rand_fast.c
10 * \brief A fast strong PRNG for use when our underlying cryptographic
11 * library's PRNG isn't fast enough.
14 /* This library is currently implemented to use the same implementation
15 * technique as libottery, using AES-CTR-256 as our underlying stream cipher.
16 * It's backtracking-resistant immediately, and prediction-resistant after
19 * Here's how it works:
21 * We generate pseudorandom bytes using AES-CTR-256. We generate BUFLEN bytes
22 * at a time. When we do this, we keep the first SEED_LEN bytes as the key
23 * and the IV for our next invocation of AES_CTR, and yield the remaining
24 * BUFLEN - SEED_LEN bytes to the user as they invoke the PRNG. As we yield
25 * bytes to the user, we clear them from the buffer.
27 * After we have refilled the buffer RESEED_AFTER times, we mix in an
28 * additional SEED_LEN bytes from our strong PRNG into the seed.
30 * If the user ever asks for a huge number of bytes at once, we pull SEED_LEN
31 * bytes from the PRNG and use them with our stream cipher to fill the user's
35 #define CRYPTO_PRIVATE
37 #include "lib/crypt_ops/crypto_rand.h"
38 #include "lib/crypt_ops/crypto_cipher.h"
39 #include "lib/crypt_ops/crypto_digest.h"
40 #include "lib/crypt_ops/crypto_util.h"
41 #include "lib/intmath/cmp.h"
42 #include "lib/cc/ctassert.h"
43 #include "lib/malloc/map_anon.h"
44 #include "lib/thread/threads.h"
46 #include "lib/log/util_bug.h"
48 #ifdef HAVE_SYS_TYPES_H
49 #include <sys/types.h>
57 #ifdef NOINHERIT_CAN_FAIL
62 #define PID_FIELD_LEN sizeof(pid_t)
64 #define PID_FIELD_LEN 0
67 /* Alias for CRYPTO_FAST_RNG_SEED_LEN to make our code shorter.
69 #define SEED_LEN (CRYPTO_FAST_RNG_SEED_LEN)
71 /* The amount of space that we mmap for a crypto_fast_rng_t.
75 /* The number of random bytes that we can yield to the user after each
76 * time we fill a crypto_fast_rng_t's buffer.
78 #define BUFLEN (MAPLEN - 2*sizeof(uint16_t) - SEED_LEN - PID_FIELD_LEN)
80 /* The number of buffer refills after which we should fetch more
81 * entropy from crypto_strongest_rand().
83 #define RESEED_AFTER 16
85 /* The length of the stream cipher key we will use for the PRNG, in bytes.
87 #define KEY_LEN (CRYPTO_FAST_RNG_SEED_LEN - CIPHER_IV_LEN)
88 /* The length of the stream cipher key we will use for the PRNG, in bits.
90 #define KEY_BITS (KEY_LEN * 8)
92 /* Make sure that we have a key length we can actually use with AES. */
93 CTASSERT(KEY_BITS
== 128 || KEY_BITS
== 192 || KEY_BITS
== 256);
95 struct crypto_fast_rng_t
{
96 /** How many more fills does this buffer have before we should mix
97 * in the output of crypto_strongest_rand()?
99 * This value may be negative if unit tests are enabled. If so, it
100 * indicates that we should never mix in extra data from
101 * crypto_strongest_rand().
103 int16_t n_till_reseed
;
104 /** How many bytes are remaining in cbuf_t.bytes? */
107 /** Which process owns this fast_rng? If this value is zero, we do not
108 * need to test the owner. */
112 /** The seed (key and IV) that we will use the next time that we refill
114 uint8_t seed
[SEED_LEN
];
116 * Bytes that we are yielding to the user. The next byte to be
117 * yielded is at bytes[BUFLEN-bytes_left]; all other bytes in this
118 * array are set to zero.
120 uint8_t bytes
[BUFLEN
];
124 /* alignof(uint8_t) should be 1, so there shouldn't be any padding in cbuf_t.
126 CTASSERT(sizeof(struct cbuf_t
) == BUFLEN
+SEED_LEN
);
127 /* We're trying to fit all of the RNG state into a nice mmapable chunk.
129 CTASSERT(sizeof(crypto_fast_rng_t
) <= MAPLEN
);
132 * Initialize and return a new fast PRNG, using a strong random seed.
134 * Note that this object is NOT thread-safe. If you need a thread-safe
135 * prng, use crypto_rand(), or wrap this in a mutex.
138 crypto_fast_rng_new(void)
140 uint8_t seed
[SEED_LEN
];
141 crypto_strongest_rand(seed
, sizeof(seed
));
142 crypto_fast_rng_t
*result
= crypto_fast_rng_new_from_seed(seed
);
143 memwipe(seed
, 0, sizeof(seed
));
148 * Initialize and return a new fast PRNG, using a seed value specified
149 * in <b>seed</b>. This value must be CRYPTO_FAST_RNG_SEED_LEN bytes
152 * Note that this object is NOT thread-safe. If you need a thread-safe
153 * prng, you should probably look at get_thread_fast_rng(). Alternatively,
154 * use crypto_rand(), wrap this in a mutex.
157 crypto_fast_rng_new_from_seed(const uint8_t *seed
)
159 unsigned inherit
= INHERIT_RES_KEEP
;
160 /* We try to allocate this object as securely as we can, to avoid
161 * having it get dumped, swapped, or shared after fork.
163 crypto_fast_rng_t
*result
= tor_mmap_anonymous(sizeof(*result
),
164 ANONMAP_PRIVATE
| ANONMAP_NOINHERIT
,
166 memcpy(result
->buf
.seed
, seed
, SEED_LEN
);
167 /* Causes an immediate refill once the user asks for data. */
168 result
->bytes_left
= 0;
169 result
->n_till_reseed
= RESEED_AFTER
;
171 if (inherit
== INHERIT_RES_KEEP
) {
172 /* This value will neither be dropped nor zeroed after fork, so we need to
173 * check our pid to make sure we are not sharing it across a fork. This
174 * can be expensive if the pid value isn't cached, sadly.
176 result
->owner
= getpid();
178 #elif defined(_WIN32)
179 /* Windows can't fork(), so there's no need to noinherit. */
181 /* We decided above that noinherit would always do _something_. Assert here
182 * that we were correct. */
183 tor_assertf(inherit
!= INHERIT_RES_KEEP
,
184 "We failed to create a non-inheritable memory region, even "
185 "though we believed such a failure to be impossible! This is "
186 "probably a bug in Tor support for your platform; please report "
188 #endif /* defined(CHECK_PID) || ... */
192 #ifdef TOR_UNIT_TESTS
194 * Unit tests only: prevent a crypto_fast_rng_t from ever mixing in more
198 crypto_fast_rng_disable_reseed(crypto_fast_rng_t
*rng
)
200 rng
->n_till_reseed
= -1;
202 #endif /* defined(TOR_UNIT_TESTS) */
205 * Helper: create a crypto_cipher_t object from SEED_LEN bytes of
206 * input. The first KEY_LEN bytes are used as the stream cipher's key,
207 * and the remaining CIPHER_IV_LEN bytes are used as its IV.
209 static inline crypto_cipher_t
*
210 cipher_from_seed(const uint8_t *seed
)
212 return crypto_cipher_new_with_iv_and_bits(seed
, seed
+KEY_LEN
, KEY_BITS
);
216 * Helper: mix additional entropy into <b>rng</b> by using our XOF to mix the
217 * old value for the seed with some additional bytes from
218 * crypto_strongest_rand().
221 crypto_fast_rng_add_entopy(crypto_fast_rng_t
*rng
)
223 crypto_xof_t
*xof
= crypto_xof_new();
224 crypto_xof_add_bytes(xof
, rng
->buf
.seed
, SEED_LEN
);
226 uint8_t seedbuf
[SEED_LEN
];
227 crypto_strongest_rand(seedbuf
, SEED_LEN
);
228 crypto_xof_add_bytes(xof
, seedbuf
, SEED_LEN
);
229 memwipe(seedbuf
, 0, SEED_LEN
);
231 crypto_xof_squeeze_bytes(xof
, rng
->buf
.seed
, SEED_LEN
);
232 crypto_xof_free(xof
);
236 * Helper: refill the seed bytes and output buffer of <b>rng</b>, using
237 * the input seed bytes as input (key and IV) for the stream cipher.
239 * If the n_till_reseed counter has reached zero, mix more random bytes into
240 * the seed before refilling the buffer.
243 crypto_fast_rng_refill(crypto_fast_rng_t
*rng
)
245 rng
->n_till_reseed
--;
246 if (rng
->n_till_reseed
== 0) {
247 /* It's time to reseed the RNG. */
248 crypto_fast_rng_add_entopy(rng
);
249 rng
->n_till_reseed
= RESEED_AFTER
;
250 } else if (rng
->n_till_reseed
< 0) {
251 #ifdef TOR_UNIT_TESTS
252 /* Reseeding is disabled for testing; never do it on this prng. */
253 rng
->n_till_reseed
= -1;
255 /* If testing is disabled, this shouldn't be able to become negative. */
256 tor_assert_unreached();
257 #endif /* defined(TOR_UNIT_TESTS) */
259 /* Now fill rng->buf with output from our stream cipher, initialized from
260 * that seed value. */
261 crypto_cipher_t
*c
= cipher_from_seed(rng
->buf
.seed
);
262 memset(&rng
->buf
, 0, sizeof(rng
->buf
));
263 crypto_cipher_crypt_inplace(c
, (char*)&rng
->buf
, sizeof(rng
->buf
));
264 crypto_cipher_free(c
);
266 rng
->bytes_left
= sizeof(rng
->buf
.bytes
);
270 * Release all storage held by <b>rng</b>.
273 crypto_fast_rng_free_(crypto_fast_rng_t
*rng
)
277 memwipe(rng
, 0, sizeof(*rng
));
278 tor_munmap_anonymous(rng
, sizeof(*rng
));
282 * Helper: extract bytes from the PRNG, refilling it as necessary. Does not
283 * optimize the case when the user has asked for a huge output.
286 crypto_fast_rng_getbytes_impl(crypto_fast_rng_t
*rng
, uint8_t *out
,
291 /* Note that we only need to do this check when we have owner set: that
292 * is, when our attempt to block inheriting failed, and the result was
295 * If the result was INHERIT_RES_DROP, then any attempt to access the rng
296 * memory after forking will crash.
298 * If the result was INHERIT_RES_ZERO, then forking will set the bytes_left
299 * and n_till_reseed fields to zero. This function will call
300 * crypto_fast_rng_refill(), which will in turn reseed the PRNG.
302 * So we only need to do this test in the case when mmap_anonymous()
303 * returned INHERIT_KEEP. We avoid doing it needlessly, since getpid() is
304 * often a system call, and that can be slow.
306 tor_assert(rng
->owner
== getpid());
308 #endif /* defined(CHECK_PID) */
310 size_t bytes_to_yield
= n
;
312 while (bytes_to_yield
) {
313 if (rng
->bytes_left
== 0)
314 crypto_fast_rng_refill(rng
);
316 const size_t to_copy
= MIN(rng
->bytes_left
, bytes_to_yield
);
318 tor_assert(sizeof(rng
->buf
.bytes
) >= rng
->bytes_left
);
319 uint8_t *copy_from
= rng
->buf
.bytes
+
320 (sizeof(rng
->buf
.bytes
) - rng
->bytes_left
);
321 memcpy(out
, copy_from
, to_copy
);
322 memset(copy_from
, 0, to_copy
);
325 bytes_to_yield
-= to_copy
;
326 rng
->bytes_left
-= to_copy
;
331 * Extract <b>n</b> bytes from <b>rng</b> into the buffer at <b>out</b>.
334 crypto_fast_rng_getbytes(crypto_fast_rng_t
*rng
, uint8_t *out
, size_t n
)
336 if (PREDICT_UNLIKELY(n
> BUFLEN
)) {
337 /* The user has asked for a lot of output; generate it from a stream
338 * cipher seeded by the PRNG rather than by pulling it out of the PRNG
341 uint8_t seed
[SEED_LEN
];
342 crypto_fast_rng_getbytes_impl(rng
, seed
, SEED_LEN
);
343 crypto_cipher_t
*c
= cipher_from_seed(seed
);
345 crypto_cipher_crypt_inplace(c
, (char*)out
, n
);
346 crypto_cipher_free(c
);
347 memwipe(seed
, 0, sizeof(seed
));
351 crypto_fast_rng_getbytes_impl(rng
, out
, n
);
354 #if defined(TOR_UNIT_TESTS)
355 /** for white-box testing: return the number of bytes that are returned from
356 * the user for each invocation of the stream cipher in this RNG. */
358 crypto_fast_rng_get_bytes_used_per_stream(void)
362 #endif /* defined(TOR_UNIT_TESTS) */
365 * Thread-local instance for our fast RNG.
367 static tor_threadlocal_t thread_rng
;
370 * Return a per-thread fast RNG, initializing it if necessary.
372 * You do not need to free this yourself.
374 * It is NOT safe to share this value across threads.
377 get_thread_fast_rng(void)
379 crypto_fast_rng_t
*rng
= tor_threadlocal_get(&thread_rng
);
381 if (PREDICT_UNLIKELY(rng
== NULL
)) {
382 rng
= crypto_fast_rng_new();
383 tor_threadlocal_set(&thread_rng
, rng
);
390 * Used when a thread is exiting: free the per-thread fast RNG if needed.
391 * Invoked from the crypto subsystem's thread-cleanup code.
394 destroy_thread_fast_rng(void)
396 crypto_fast_rng_t
*rng
= tor_threadlocal_get(&thread_rng
);
399 crypto_fast_rng_free(rng
);
400 tor_threadlocal_set(&thread_rng
, NULL
);
403 #ifdef TOR_UNIT_TESTS
405 * Replace the current thread's rng with <b>rng</b>. For use by the
406 * unit tests only. Returns the previous thread rng.
409 crypto_replace_thread_fast_rng(crypto_fast_rng_t
*rng
)
411 crypto_fast_rng_t
*old_rng
= tor_threadlocal_get(&thread_rng
);
412 tor_threadlocal_set(&thread_rng
, rng
);
415 #endif /* defined(TOR_UNIT_TESTS) */
418 * Initialize the global thread-local key that will be used to keep track
419 * of per-thread fast RNG instances. Called from the crypto subsystem's
420 * initialization code.
423 crypto_rand_fast_init(void)
425 tor_threadlocal_init(&thread_rng
);
429 * Initialize the global thread-local key that will be used to keep track
430 * of per-thread fast RNG instances. Called from the crypto subsystem's
434 crypto_rand_fast_shutdown(void)
436 destroy_thread_fast_rng();
437 tor_threadlocal_destroy(&thread_rng
);