crypto_rand_fast.c 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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-2019, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file crypto_rand_fast.c
  8. *
  9. * \brief A fast strong PRNG for use when our underlying cryptographic
  10. * library's PRNG isn't fast enough.
  11. **/
  12. /* This library is currently implemented to use the same implementation
  13. * technique as libottery, using AES-CTR-256 as our underlying stream cipher.
  14. * It's backtracking-resistant immediately, and prediction-resistant after
  15. * a while.
  16. *
  17. * Here's how it works:
  18. *
  19. * We generate pseudorandom bytes using AES-CTR-256. We generate BUFLEN bytes
  20. * at a time. When we do this, we keep the first SEED_LEN bytes as the key
  21. * and the IV for our next invocation of AES_CTR, and yield the remaining
  22. * BUFLEN - SEED_LEN bytes to the user as they invoke the PRNG. As we yield
  23. * bytes to the user, we clear them from the buffer.
  24. *
  25. * After we have refilled the buffer RESEED_AFTER times, we mix in an
  26. * additional SEED_LEN bytes from our strong PRNG into the seed.
  27. *
  28. * If the user ever asks for a huge number of bytes at once, we pull SEED_LEN
  29. * bytes from the PRNG and use them with our stream cipher to fill the user's
  30. * request.
  31. */
  32. #define CRYPTO_RAND_FAST_PRIVATE
  33. #define CRYPTO_PRIVATE
  34. #include "lib/crypt_ops/crypto_rand.h"
  35. #include "lib/crypt_ops/crypto_cipher.h"
  36. #include "lib/crypt_ops/crypto_digest.h"
  37. #include "lib/crypt_ops/crypto_util.h"
  38. #include "lib/intmath/cmp.h"
  39. #include "lib/cc/ctassert.h"
  40. #include "lib/malloc/map_anon.h"
  41. #include "lib/thread/threads.h"
  42. #include "lib/log/util_bug.h"
  43. #include <string.h>
  44. /* Alias for CRYPTO_FAST_RNG_SEED_LEN to make our code shorter.
  45. */
  46. #define SEED_LEN (CRYPTO_FAST_RNG_SEED_LEN)
  47. /* The amount of space that we mmap for a crypto_fast_rng_t.
  48. */
  49. #define MAPLEN 4096
  50. /* The number of random bytes that we can yield to the user after each
  51. * time we fill a crypto_fast_rng_t's buffer.
  52. */
  53. #define BUFLEN (MAPLEN - 2*sizeof(uint16_t) - SEED_LEN)
  54. /* The number of buffer refills after which we should fetch more
  55. * entropy from crypto_strongest_rand().
  56. */
  57. #define RESEED_AFTER 16
  58. /* The length of the stream cipher key we will use for the PRNG, in bytes.
  59. */
  60. #define KEY_LEN (CRYPTO_FAST_RNG_SEED_LEN - CIPHER_IV_LEN)
  61. /* The length of the stream cipher key we will use for the PRNG, in bits.
  62. */
  63. #define KEY_BITS (KEY_LEN * 8)
  64. /* Make sure that we have a key length we can actually use with AES. */
  65. CTASSERT(KEY_BITS == 128 || KEY_BITS == 192 || KEY_BITS == 256);
  66. struct crypto_fast_rng_t {
  67. /** How many more fills does this buffer have before we should mix
  68. * in the output of crypto_rand()? */
  69. uint16_t n_till_reseed;
  70. /** How many bytes are remaining in cbuf.bytes? */
  71. uint16_t bytes_left;
  72. struct cbuf {
  73. /** The seed (key and IV) that we will use the next time that we refill
  74. * cbuf. */
  75. uint8_t seed[SEED_LEN];
  76. /**
  77. * Bytes that we are yielding to the user. The next byte to be
  78. * yielded is at bytes[BUFLEN-bytes_left]; all other bytes in this
  79. * array are set to zero.
  80. */
  81. uint8_t bytes[BUFLEN];
  82. } buf;
  83. };
  84. /* alignof(uint8_t) should be 1, so there shouldn't be any padding in cbuf.
  85. */
  86. CTASSERT(sizeof(struct cbuf) == BUFLEN+SEED_LEN);
  87. /* We're trying to fit all of the RNG state into a nice mmapable chunk.
  88. */
  89. CTASSERT(sizeof(crypto_fast_rng_t) <= MAPLEN);
  90. /**
  91. * Initialize and return a new fast PRNG, using a strong random seed.
  92. *
  93. * Note that this object is NOT thread-safe. If you need a thread-safe
  94. * prng, use crypto_rand(), or wrap this in a mutex.
  95. **/
  96. crypto_fast_rng_t *
  97. crypto_fast_rng_new(void)
  98. {
  99. uint8_t seed[SEED_LEN];
  100. crypto_strongest_rand(seed, sizeof(seed));
  101. crypto_fast_rng_t *result = crypto_fast_rng_new_from_seed(seed);
  102. memwipe(seed, 0, sizeof(seed));
  103. return result;
  104. }
  105. /**
  106. * Initialize and return a new fast PRNG, using a seed value specified
  107. * in <b>seed</b>. This value must be CRYPTO_FAST_RNG_SEED_LEN bytes
  108. * long.
  109. *
  110. * Note that this object is NOT thread-safe. If you need a thread-safe
  111. * prng, you should probably look at get_thread_fast_rng(). Alternatively,
  112. * use crypto_rand(), wrap this in a mutex.
  113. **/
  114. crypto_fast_rng_t *
  115. crypto_fast_rng_new_from_seed(const uint8_t *seed)
  116. {
  117. /* We try to allocate this object as securely as we can, to avoid
  118. * having it get dumped, swapped, or shared after fork.
  119. */
  120. crypto_fast_rng_t *result = tor_mmap_anonymous(sizeof(*result),
  121. ANONMAP_PRIVATE | ANONMAP_NOINHERIT,
  122. NULL);
  123. memcpy(result->buf.seed, seed, SEED_LEN);
  124. /* Causes an immediate refill once the user asks for data. */
  125. result->bytes_left = 0;
  126. result->n_till_reseed = RESEED_AFTER;
  127. return result;
  128. }
  129. /**
  130. * Helper: create a crypto_cipher_t object from SEED_LEN bytes of
  131. * input. The first KEY_LEN bytes are used as the stream cipher's key,
  132. * and the remaining CIPHER_IV_LEN bytes are used as its IV.
  133. **/
  134. static inline crypto_cipher_t *
  135. cipher_from_seed(const uint8_t *seed)
  136. {
  137. return crypto_cipher_new_with_iv_and_bits(seed, seed+KEY_LEN, KEY_BITS);
  138. }
  139. /**
  140. * Helper: refill the seed bytes and output buffer of <b>rng</b>, using
  141. * the input seed bytes as input (key and IV) for the stream cipher.
  142. *
  143. * If the n_till_reseed counter has reached zero, mix more random bytes into
  144. * the seed before refilling the buffer.
  145. **/
  146. static void
  147. crypto_fast_rng_refill(crypto_fast_rng_t *rng)
  148. {
  149. if (rng->n_till_reseed-- == 0) {
  150. /* It's time to reseed the RNG. We'll do this by using our XOF to mix the
  151. * old value for the seed with some additional bytes from
  152. * crypto_strongest_rand(). */
  153. crypto_xof_t *xof = crypto_xof_new();
  154. crypto_xof_add_bytes(xof, rng->buf.seed, SEED_LEN);
  155. {
  156. uint8_t seedbuf[SEED_LEN];
  157. crypto_strongest_rand(seedbuf, SEED_LEN);
  158. crypto_xof_add_bytes(xof, seedbuf, SEED_LEN);
  159. memwipe(seedbuf, 0, SEED_LEN);
  160. }
  161. crypto_xof_squeeze_bytes(xof, rng->buf.seed, SEED_LEN);
  162. crypto_xof_free(xof);
  163. rng->n_till_reseed = RESEED_AFTER;
  164. }
  165. /* Now fill rng->buf with output from our stream cipher, initialized from
  166. * that seed value. */
  167. crypto_cipher_t *c = cipher_from_seed(rng->buf.seed);
  168. memset(&rng->buf, 0, sizeof(rng->buf));
  169. crypto_cipher_crypt_inplace(c, (char*)&rng->buf, sizeof(rng->buf));
  170. crypto_cipher_free(c);
  171. rng->bytes_left = sizeof(rng->buf.bytes);
  172. }
  173. /**
  174. * Release all storage held by <b>rng</b>.
  175. **/
  176. void
  177. crypto_fast_rng_free_(crypto_fast_rng_t *rng)
  178. {
  179. if (!rng)
  180. return;
  181. memwipe(rng, 0, sizeof(*rng));
  182. tor_munmap_anonymous(rng, sizeof(*rng));
  183. }
  184. /**
  185. * Helper: extract bytes from the PRNG, refilling it as necessary. Does not
  186. * optimize the case when the user has asked for a huge output.
  187. **/
  188. static void
  189. crypto_fast_rng_getbytes_impl(crypto_fast_rng_t *rng, uint8_t *out,
  190. const size_t n)
  191. {
  192. size_t bytes_to_yield = n;
  193. while (bytes_to_yield) {
  194. if (rng->bytes_left == 0)
  195. crypto_fast_rng_refill(rng);
  196. const size_t to_copy = MIN(rng->bytes_left, bytes_to_yield);
  197. tor_assert(sizeof(rng->buf.bytes) >= rng->bytes_left);
  198. uint8_t *copy_from = rng->buf.bytes +
  199. (sizeof(rng->buf.bytes) - rng->bytes_left);
  200. memcpy(out, copy_from, to_copy);
  201. memset(copy_from, 0, to_copy);
  202. out += to_copy;
  203. bytes_to_yield -= to_copy;
  204. rng->bytes_left -= to_copy;
  205. }
  206. }
  207. /**
  208. * Extract <b>n</b> bytes from <b>rng</b> into the buffer at <b>out</b>.
  209. **/
  210. void
  211. crypto_fast_rng_getbytes(crypto_fast_rng_t *rng, uint8_t *out, size_t n)
  212. {
  213. if (PREDICT_UNLIKELY(n > BUFLEN)) {
  214. /* The user has asked for a lot of output; generate it from a stream
  215. * cipher seeded by the PRNG rather than by pulling it out of the PRNG
  216. * directly.
  217. */
  218. uint8_t seed[SEED_LEN];
  219. crypto_fast_rng_getbytes_impl(rng, seed, SEED_LEN);
  220. crypto_cipher_t *c = cipher_from_seed(seed);
  221. memset(out, 0, n);
  222. crypto_cipher_crypt_inplace(c, (char*)out, n);
  223. crypto_cipher_free(c);
  224. memwipe(seed, 0, sizeof(seed));
  225. return;
  226. }
  227. crypto_fast_rng_getbytes_impl(rng, out, n);
  228. }
  229. #if defined(TOR_UNIT_TESTS)
  230. /** for white-box testing: return the number of bytes that are returned from
  231. * the user for each invocation of the stream cipher in this RNG. */
  232. size_t
  233. crypto_fast_rng_get_bytes_used_per_stream(void)
  234. {
  235. return BUFLEN;
  236. }
  237. #endif
  238. /**
  239. * Thread-local instance for our fast RNG.
  240. **/
  241. static tor_threadlocal_t thread_rng;
  242. /**
  243. * Return a per-thread fast RNG, initializing it if necessary.
  244. *
  245. * You do not need to free this yourself.
  246. *
  247. * It is NOT safe to share this value across threads.
  248. **/
  249. crypto_fast_rng_t *
  250. get_thread_fast_rng(void)
  251. {
  252. crypto_fast_rng_t *rng = tor_threadlocal_get(&thread_rng);
  253. if (PREDICT_UNLIKELY(rng == NULL)) {
  254. rng = crypto_fast_rng_new();
  255. tor_threadlocal_set(&thread_rng, rng);
  256. }
  257. return rng;
  258. }
  259. /**
  260. * Used when a thread is exiting: free the per-thread fast RNG if needed.
  261. * Invoked from the crypto subsystem's thread-cleanup code.
  262. **/
  263. void
  264. destroy_thread_fast_rng(void)
  265. {
  266. crypto_fast_rng_t *rng = tor_threadlocal_get(&thread_rng);
  267. if (!rng)
  268. return;
  269. crypto_fast_rng_free(rng);
  270. tor_threadlocal_set(&thread_rng, NULL);
  271. }
  272. /**
  273. * Initialize the global thread-local key that will be used to keep track
  274. * of per-thread fast RNG instances. Called from the crypto subsystem's
  275. * initialization code.
  276. **/
  277. void
  278. crypto_rand_fast_init(void)
  279. {
  280. tor_threadlocal_init(&thread_rng);
  281. }
  282. /**
  283. * Initialize the global thread-local key that will be used to keep track
  284. * of per-thread fast RNG instances. Called from the crypto subsystem's
  285. * shutdown code.
  286. **/
  287. void
  288. crypto_rand_fast_shutdown(void)
  289. {
  290. destroy_thread_fast_rng();
  291. tor_threadlocal_destroy(&thread_rng);
  292. }