rnd.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967
  1. /* $OpenBSD: rnd.c,v 1.175 2015/05/25 03:07:07 deraadt Exp $ */
  2. /*
  3. * Copyright (c) 2011 Theo de Raadt.
  4. * Copyright (c) 2008 Damien Miller.
  5. * Copyright (c) 1996, 1997, 2000-2002 Michael Shalayeff.
  6. * Copyright (c) 2013 Markus Friedl.
  7. * Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999.
  8. * All rights reserved.
  9. *
  10. * Redistribution and use in source and binary forms, with or without
  11. * modification, are permitted provided that the following conditions
  12. * are met:
  13. * 1. Redistributions of source code must retain the above copyright
  14. * notice, and the entire permission notice in its entirety,
  15. * including the disclaimer of warranties.
  16. * 2. Redistributions in binary form must reproduce the above copyright
  17. * notice, this list of conditions and the following disclaimer in the
  18. * documentation and/or other materials provided with the distribution.
  19. * 3. The name of the author may not be used to endorse or promote
  20. * products derived from this software without specific prior
  21. * written permission.
  22. *
  23. * ALTERNATIVELY, this product may be distributed under the terms of
  24. * the GNU Public License, in which case the provisions of the GPL are
  25. * required INSTEAD OF the above restrictions. (This clause is
  26. * necessary due to a potential bad interaction between the GPL and
  27. * the restrictions contained in a BSD-style copyright.)
  28. *
  29. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
  30. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  31. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  32. * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
  33. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  34. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  35. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  36. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  37. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  38. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  39. * OF THE POSSIBILITY OF SUCH DAMAGE.
  40. */
  41. /*
  42. * Computers are very predictable devices. Hence it is extremely hard
  43. * to produce truly random numbers on a computer --- as opposed to
  44. * pseudo-random numbers, which can be easily generated by using an
  45. * algorithm. Unfortunately, it is very easy for attackers to guess
  46. * the sequence of pseudo-random number generators, and for some
  47. * applications this is not acceptable. Instead, we must try to
  48. * gather "environmental noise" from the computer's environment, which
  49. * must be hard for outside attackers to observe and use to
  50. * generate random numbers. In a Unix environment, this is best done
  51. * from inside the kernel.
  52. *
  53. * Sources of randomness from the environment include inter-keyboard
  54. * timings, inter-interrupt timings from some interrupts, and other
  55. * events which are both (a) non-deterministic and (b) hard for an
  56. * outside observer to measure. Randomness from these sources is
  57. * added to the "rnd states" queue; this is used as much of the
  58. * source material which is mixed on occasion using a CRC-like function
  59. * into the "entropy pool". This is not cryptographically strong, but
  60. * it is adequate assuming the randomness is not chosen maliciously,
  61. * and it is very fast because the interrupt-time event is only to add
  62. * a small random token to the "rnd states" queue.
  63. *
  64. * When random bytes are desired, they are obtained by pulling from
  65. * the entropy pool and running a SHA512 hash. The SHA512 hash avoids
  66. * exposing the internal state of the entropy pool. Even if it is
  67. * possible to analyze SHA512 in some clever way, as long as the amount
  68. * of data returned from the generator is less than the inherent
  69. * entropy in the pool, the output data is totally unpredictable. For
  70. * this reason, the routine decreases its internal estimate of how many
  71. * bits of "true randomness" are contained in the entropy pool as it
  72. * outputs random numbers.
  73. *
  74. * If this estimate goes to zero, the SHA512 hash will continue to generate
  75. * output since there is no true risk because the SHA512 output is not
  76. * exported outside this subsystem. It is next used as input to seed a
  77. * ChaCha20 stream cipher, which is re-seeded from time to time. This
  78. * design provides very high amounts of output data from a potentially
  79. * small entropy base, at high enough speeds to encourage use of random
  80. * numbers in nearly any situation. Before OpenBSD 5.5, the RC4 stream
  81. * cipher (also known as ARC4) was used instead of ChaCha20.
  82. *
  83. * The output of this single ChaCha20 engine is then shared amongst many
  84. * consumers in the kernel and userland via a few interfaces:
  85. * arc4random_buf(), arc4random(), arc4random_uniform(), randomread()
  86. * for the set of /dev/random nodes, the sysctl kern.arandom, and the
  87. * system call getentropy(), which provides seeds for process-context
  88. * pseudorandom generators.
  89. *
  90. * Acknowledgements:
  91. * =================
  92. *
  93. * Ideas for constructing this random number generator were derived
  94. * from Pretty Good Privacy's random number generator, and from private
  95. * discussions with Phil Karn. Colin Plumb provided a faster random
  96. * number generator, which speeds up the mixing function of the entropy
  97. * pool, taken from PGPfone. Dale Worley has also contributed many
  98. * useful ideas and suggestions to improve this driver.
  99. *
  100. * Any flaws in the design are solely my responsibility, and should
  101. * not be attributed to the Phil, Colin, or any of the authors of PGP.
  102. *
  103. * Further background information on this topic may be obtained from
  104. * RFC 1750, "Randomness Recommendations for Security", by Donald
  105. * Eastlake, Steve Crocker, and Jeff Schiller.
  106. *
  107. * Using a RC4 stream cipher as 2nd stage after the MD5 (now SHA512) output
  108. * is the result of work by David Mazieres.
  109. */
  110. #include <sys/param.h>
  111. #include <sys/systm.h>
  112. #include <sys/disk.h>
  113. #include <sys/event.h>
  114. #include <sys/limits.h>
  115. #include <sys/time.h>
  116. #include <sys/ioctl.h>
  117. #include <sys/malloc.h>
  118. #include <sys/fcntl.h>
  119. #include <sys/timeout.h>
  120. #include <sys/mutex.h>
  121. #include <sys/task.h>
  122. #include <sys/msgbuf.h>
  123. #include <sys/mount.h>
  124. #include <sys/syscallargs.h>
  125. #include <crypto/sha2.h>
  126. #define KEYSTREAM_ONLY
  127. #include <crypto/chacha_private.h>
  128. #include <dev/rndvar.h>
  129. /*
  130. * For the purposes of better mixing, we use the CRC-32 polynomial as
  131. * well to make a twisted Generalized Feedback Shift Register
  132. *
  133. * (See M. Matsumoto & Y. Kurita, 1992. Twisted GFSR generators. ACM
  134. * Transactions on Modeling and Computer Simulation 2(3):179-194.
  135. * Also see M. Matsumoto & Y. Kurita, 1994. Twisted GFSR generators
  136. * II. ACM Transactions on Mdeling and Computer Simulation 4:254-266)
  137. *
  138. * Thanks to Colin Plumb for suggesting this.
  139. *
  140. * We have not analyzed the resultant polynomial to prove it primitive;
  141. * in fact it almost certainly isn't. Nonetheless, the irreducible factors
  142. * of a random large-degree polynomial over GF(2) are more than large enough
  143. * that periodicity is not a concern.
  144. *
  145. * The input hash is much less sensitive than the output hash. All
  146. * we want from it is to be a good non-cryptographic hash -
  147. * i.e. to not produce collisions when fed "random" data of the sort
  148. * we expect to see. As long as the pool state differs for different
  149. * inputs, we have preserved the input entropy and done a good job.
  150. * The fact that an intelligent attacker can construct inputs that
  151. * will produce controlled alterations to the pool's state is not
  152. * important because we don't consider such inputs to contribute any
  153. * randomness. The only property we need with respect to them is that
  154. * the attacker can't increase his/her knowledge of the pool's state.
  155. * Since all additions are reversible (knowing the final state and the
  156. * input, you can reconstruct the initial state), if an attacker has
  157. * any uncertainty about the initial state, he/she can only shuffle
  158. * that uncertainty about, but never cause any collisions (which would
  159. * decrease the uncertainty).
  160. *
  161. * The chosen system lets the state of the pool be (essentially) the input
  162. * modulo the generator polynomial. Now, for random primitive polynomials,
  163. * this is a universal class of hash functions, meaning that the chance
  164. * of a collision is limited by the attacker's knowledge of the generator
  165. * polynomial, so if it is chosen at random, an attacker can never force
  166. * a collision. Here, we use a fixed polynomial, but we *can* assume that
  167. * ###--> it is unknown to the processes generating the input entropy. <-###
  168. * Because of this important property, this is a good, collision-resistant
  169. * hash; hash collisions will occur no more often than chance.
  170. */
  171. /*
  172. * Stirring polynomials over GF(2) for various pool sizes. Used in
  173. * add_entropy_words() below.
  174. *
  175. * The polynomial terms are chosen to be evenly spaced (minimum RMS
  176. * distance from evenly spaced; except for the last tap, which is 1 to
  177. * get the twisting happening as fast as possible.
  178. *
  179. * The reultant polynomial is:
  180. * 2^POOLWORDS + 2^POOL_TAP1 + 2^POOL_TAP2 + 2^POOL_TAP3 + 2^POOL_TAP4 + 1
  181. */
  182. #define POOLWORDS 2048
  183. #define POOLBYTES (POOLWORDS*4)
  184. #define POOLMASK (POOLWORDS - 1)
  185. #define POOL_TAP1 1638
  186. #define POOL_TAP2 1231
  187. #define POOL_TAP3 819
  188. #define POOL_TAP4 411
  189. struct mutex entropylock = MUTEX_INITIALIZER(IPL_HIGH);
  190. /*
  191. * Raw entropy collection from device drivers; at interrupt context or not.
  192. * add_*_randomness() provide data which is put into the entropy queue.
  193. * Almost completely under the entropylock.
  194. */
  195. struct timer_rand_state { /* There is one of these per entropy source */
  196. u_int last_time;
  197. u_int last_delta;
  198. u_int last_delta2;
  199. u_int dont_count_entropy : 1;
  200. u_int max_entropy : 1;
  201. } rnd_states[RND_SRC_NUM];
  202. #define QEVLEN (1024 / sizeof(struct rand_event))
  203. #define QEVSLOW (QEVLEN * 3 / 4) /* yet another 0.75 for 60-minutes hour /-; */
  204. #define QEVSBITS 10
  205. #define KEYSZ 32
  206. #define IVSZ 8
  207. #define BLOCKSZ 64
  208. #define RSBUFSZ (16*BLOCKSZ)
  209. #define EBUFSIZE KEYSZ + IVSZ
  210. struct rand_event {
  211. struct timer_rand_state *re_state;
  212. u_int re_nbits;
  213. u_int re_time;
  214. u_int re_val;
  215. } rnd_event_space[QEVLEN];
  216. /* index of next free slot */
  217. int rnd_event_idx;
  218. struct timeout rnd_timeout;
  219. struct rndstats rndstats;
  220. u_int32_t entropy_pool[POOLWORDS] __attribute__((section(".openbsd.randomdata")));
  221. u_int entropy_add_ptr;
  222. u_char entropy_input_rotate;
  223. void dequeue_randomness(void *);
  224. void add_entropy_words(const u_int32_t *, u_int);
  225. void extract_entropy(u_int8_t *)
  226. __attribute__((__bounded__(__minbytes__,1,EBUFSIZE)));
  227. int filt_randomread(struct knote *, long);
  228. void filt_randomdetach(struct knote *);
  229. int filt_randomwrite(struct knote *, long);
  230. static void _rs_seed(u_char *, size_t);
  231. struct filterops randomread_filtops =
  232. { 1, NULL, filt_randomdetach, filt_randomread };
  233. struct filterops randomwrite_filtops =
  234. { 1, NULL, filt_randomdetach, filt_randomwrite };
  235. static __inline struct rand_event *
  236. rnd_get(void)
  237. {
  238. if (rnd_event_idx == 0)
  239. return NULL;
  240. return &rnd_event_space[--rnd_event_idx];
  241. }
  242. static __inline struct rand_event *
  243. rnd_put(void)
  244. {
  245. if (rnd_event_idx == QEVLEN)
  246. return NULL;
  247. return &rnd_event_space[rnd_event_idx++];
  248. }
  249. static __inline int
  250. rnd_qlen(void)
  251. {
  252. return rnd_event_idx;
  253. }
  254. /*
  255. * This function adds entropy to the entropy pool by using timing
  256. * delays. It uses the timer_rand_state structure to make an estimate
  257. * of how many bits of entropy this call has added to the pool.
  258. *
  259. * The number "val" is also added to the pool - it should somehow describe
  260. * the type of event which just happened. Currently the values of 0-255
  261. * are for keyboard scan codes, 256 and upwards - for interrupts.
  262. * On the i386, this is assumed to be at most 16 bits, and the high bits
  263. * are used for a high-resolution timer.
  264. */
  265. void
  266. enqueue_randomness(int state, int val)
  267. {
  268. int delta, delta2, delta3;
  269. struct timer_rand_state *p;
  270. struct rand_event *rep;
  271. struct timespec ts;
  272. u_int time, nbits;
  273. #ifdef DIAGNOSTIC
  274. if (state < 0 || state >= RND_SRC_NUM)
  275. return;
  276. #endif
  277. if (timeout_initialized(&rnd_timeout))
  278. nanotime(&ts);
  279. p = &rnd_states[state];
  280. val += state << 13;
  281. time = (ts.tv_nsec >> 10) + (ts.tv_sec << 20);
  282. nbits = 0;
  283. /*
  284. * Calculate the number of bits of randomness that we probably
  285. * added. We take into account the first and second order
  286. * deltas in order to make our estimate.
  287. */
  288. if (!p->dont_count_entropy) {
  289. delta = time - p->last_time;
  290. delta2 = delta - p->last_delta;
  291. delta3 = delta2 - p->last_delta2;
  292. if (delta < 0) delta = -delta;
  293. if (delta2 < 0) delta2 = -delta2;
  294. if (delta3 < 0) delta3 = -delta3;
  295. if (delta > delta2) delta = delta2;
  296. if (delta > delta3) delta = delta3;
  297. delta3 = delta >>= 1;
  298. /*
  299. * delta &= 0xfff;
  300. * we don't do it since our time sheet is different from linux
  301. */
  302. if (delta & 0xffff0000) {
  303. nbits = 16;
  304. delta >>= 16;
  305. }
  306. if (delta & 0xff00) {
  307. nbits += 8;
  308. delta >>= 8;
  309. }
  310. if (delta & 0xf0) {
  311. nbits += 4;
  312. delta >>= 4;
  313. }
  314. if (delta & 0xc) {
  315. nbits += 2;
  316. delta >>= 2;
  317. }
  318. if (delta & 2) {
  319. nbits += 1;
  320. delta >>= 1;
  321. }
  322. if (delta & 1)
  323. nbits++;
  324. } else if (p->max_entropy)
  325. nbits = 8 * sizeof(val) - 1;
  326. /* given the multi-order delta logic above, this should never happen */
  327. if (nbits >= 32)
  328. return;
  329. mtx_enter(&entropylock);
  330. if (!p->dont_count_entropy) {
  331. /*
  332. * the logic is to drop low-entropy entries,
  333. * in hope for dequeuing to be more randomfull
  334. */
  335. if (rnd_qlen() > QEVSLOW && nbits < QEVSBITS) {
  336. rndstats.rnd_drople++;
  337. goto done;
  338. }
  339. p->last_time = time;
  340. p->last_delta = delta3;
  341. p->last_delta2 = delta2;
  342. }
  343. if ((rep = rnd_put()) == NULL) {
  344. rndstats.rnd_drops++;
  345. goto done;
  346. }
  347. rep->re_state = p;
  348. rep->re_nbits = nbits;
  349. rep->re_time = ts.tv_nsec ^ (ts.tv_sec << 20);
  350. rep->re_val = val;
  351. rndstats.rnd_enqs++;
  352. rndstats.rnd_ed[nbits]++;
  353. rndstats.rnd_sc[state]++;
  354. rndstats.rnd_sb[state] += nbits;
  355. if (rnd_qlen() > QEVSLOW/2 && timeout_initialized(&rnd_timeout) &&
  356. !timeout_pending(&rnd_timeout))
  357. timeout_add(&rnd_timeout, 1);
  358. done:
  359. mtx_leave(&entropylock);
  360. }
  361. /*
  362. * This function adds a byte into the entropy pool. It does not
  363. * update the entropy estimate. The caller must do this if appropriate.
  364. *
  365. * The pool is stirred with a polynomial of degree POOLWORDS over GF(2);
  366. * see POOL_TAP[1-4] above
  367. *
  368. * Rotate the input word by a changing number of bits, to help assure
  369. * that all bits in the entropy get toggled. Otherwise, if the pool
  370. * is consistently fed small numbers (such as keyboard scan codes)
  371. * then the upper bits of the entropy pool will frequently remain
  372. * untouched.
  373. */
  374. void
  375. add_entropy_words(const u_int32_t *buf, u_int n)
  376. {
  377. /* derived from IEEE 802.3 CRC-32 */
  378. static const u_int32_t twist_table[8] = {
  379. 0x00000000, 0x3b6e20c8, 0x76dc4190, 0x4db26158,
  380. 0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278
  381. };
  382. for (; n--; buf++) {
  383. u_int32_t w = (*buf << entropy_input_rotate) |
  384. (*buf >> (32 - entropy_input_rotate));
  385. u_int i = entropy_add_ptr =
  386. (entropy_add_ptr - 1) & POOLMASK;
  387. /*
  388. * Normally, we add 7 bits of rotation to the pool.
  389. * At the beginning of the pool, add an extra 7 bits
  390. * rotation, so that successive passes spread the
  391. * input bits across the pool evenly.
  392. */
  393. entropy_input_rotate =
  394. (entropy_input_rotate + (i ? 7 : 14)) & 31;
  395. /* XOR pool contents corresponding to polynomial terms */
  396. w ^= entropy_pool[(i + POOL_TAP1) & POOLMASK] ^
  397. entropy_pool[(i + POOL_TAP2) & POOLMASK] ^
  398. entropy_pool[(i + POOL_TAP3) & POOLMASK] ^
  399. entropy_pool[(i + POOL_TAP4) & POOLMASK] ^
  400. entropy_pool[(i + 1) & POOLMASK] ^
  401. entropy_pool[i]; /* + 2^POOLWORDS */
  402. entropy_pool[i] = (w >> 3) ^ twist_table[w & 7];
  403. }
  404. }
  405. /*
  406. * Pulls entropy out of the queue and throws merges it into the pool
  407. * with the CRC.
  408. */
  409. /* ARGSUSED */
  410. void
  411. dequeue_randomness(void *v)
  412. {
  413. struct rand_event *rep;
  414. u_int32_t buf[2];
  415. u_int nbits;
  416. mtx_enter(&entropylock);
  417. if (timeout_initialized(&rnd_timeout))
  418. timeout_del(&rnd_timeout);
  419. rndstats.rnd_deqs++;
  420. while ((rep = rnd_get())) {
  421. buf[0] = rep->re_time;
  422. buf[1] = rep->re_val;
  423. nbits = rep->re_nbits;
  424. mtx_leave(&entropylock);
  425. add_entropy_words(buf, 2);
  426. mtx_enter(&entropylock);
  427. rndstats.rnd_total += nbits;
  428. }
  429. mtx_leave(&entropylock);
  430. }
  431. /*
  432. * Grabs a chunk from the entropy_pool[] and slams it through SHA512 when
  433. * requested.
  434. */
  435. void
  436. extract_entropy(u_int8_t *buf)
  437. {
  438. static u_int32_t extract_pool[POOLWORDS];
  439. u_char digest[SHA512_DIGEST_LENGTH];
  440. SHA2_CTX shactx;
  441. #if SHA512_DIGEST_LENGTH < EBUFSIZE
  442. #error "need more bigger hash output"
  443. #endif
  444. /*
  445. * INTENTIONALLY not protected by entropylock. Races during
  446. * memcpy() result in acceptable input data; races during
  447. * SHA512Update() would create nasty data dependencies. We
  448. * do not rely on this as a benefit, but if it happens, cool.
  449. */
  450. memcpy(extract_pool, entropy_pool, sizeof(extract_pool));
  451. /* Hash the pool to get the output */
  452. SHA512Init(&shactx);
  453. SHA512Update(&shactx, (u_int8_t *)extract_pool, sizeof(extract_pool));
  454. SHA512Final(digest, &shactx);
  455. /* Copy data to destination buffer */
  456. memcpy(buf, digest, EBUFSIZE);
  457. /* Modify pool so next hash will produce different results */
  458. add_timer_randomness(EBUFSIZE);
  459. dequeue_randomness(NULL);
  460. /* Wipe data from memory */
  461. explicit_bzero(extract_pool, sizeof(extract_pool));
  462. explicit_bzero(digest, sizeof(digest));
  463. }
  464. /* random keystream by ChaCha */
  465. void arc4_reinit(void *v); /* timeout to start reinit */
  466. void arc4_init(void *); /* actually do the reinit */
  467. struct mutex rndlock = MUTEX_INITIALIZER(IPL_HIGH);
  468. struct timeout arc4_timeout;
  469. struct task arc4_task = TASK_INITIALIZER(arc4_init, NULL);
  470. static int rs_initialized;
  471. static chacha_ctx rs; /* chacha context for random keystream */
  472. /* keystream blocks (also chacha seed from boot) */
  473. static u_char rs_buf[RSBUFSZ] __attribute__((section(".openbsd.randomdata")));
  474. static size_t rs_have; /* valid bytes at end of rs_buf */
  475. static size_t rs_count; /* bytes till reseed */
  476. void
  477. suspend_randomness(void)
  478. {
  479. struct timespec ts;
  480. getnanotime(&ts);
  481. add_true_randomness(ts.tv_sec);
  482. add_true_randomness(ts.tv_nsec);
  483. dequeue_randomness(NULL);
  484. rs_count = 0;
  485. arc4random_buf(entropy_pool, sizeof(entropy_pool));
  486. }
  487. void
  488. resume_randomness(char *buf, size_t buflen)
  489. {
  490. struct timespec ts;
  491. if (buf && buflen)
  492. _rs_seed(buf, buflen);
  493. getnanotime(&ts);
  494. add_true_randomness(ts.tv_sec);
  495. add_true_randomness(ts.tv_nsec);
  496. dequeue_randomness(NULL);
  497. rs_count = 0;
  498. }
  499. static inline void _rs_rekey(u_char *dat, size_t datlen);
  500. static inline void
  501. _rs_init(u_char *buf, size_t n)
  502. {
  503. KASSERT(n >= KEYSZ + IVSZ);
  504. chacha_keysetup(&rs, buf, KEYSZ * 8, 0);
  505. chacha_ivsetup(&rs, buf + KEYSZ);
  506. }
  507. static void
  508. _rs_seed(u_char *buf, size_t n)
  509. {
  510. _rs_rekey(buf, n);
  511. /* invalidate rs_buf */
  512. rs_have = 0;
  513. memset(rs_buf, 0, RSBUFSZ);
  514. rs_count = 1600000;
  515. }
  516. static void
  517. _rs_stir(int do_lock)
  518. {
  519. struct timespec ts;
  520. u_int8_t buf[EBUFSIZE], *p;
  521. int i;
  522. /*
  523. * Use SHA512 PRNG data and a system timespec; early in the boot
  524. * process this is the best we can do -- some architectures do
  525. * not collect entropy very well during this time, but may have
  526. * clock information which is better than nothing.
  527. */
  528. extract_entropy(buf);
  529. nanotime(&ts);
  530. for (p = (u_int8_t *)&ts, i = 0; i < sizeof(ts); i++)
  531. buf[i] ^= p[i];
  532. if (do_lock)
  533. mtx_enter(&rndlock);
  534. _rs_seed(buf, sizeof(buf));
  535. rndstats.arc4_nstirs++;
  536. if (do_lock)
  537. mtx_leave(&rndlock);
  538. explicit_bzero(buf, sizeof(buf));
  539. }
  540. static inline void
  541. _rs_stir_if_needed(size_t len)
  542. {
  543. if (!rs_initialized) {
  544. _rs_init(rs_buf, KEYSZ + IVSZ);
  545. rs_count = 1024 * 1024 * 1024; /* until main() runs */
  546. rs_initialized = 1;
  547. } else if (rs_count <= len)
  548. _rs_stir(0);
  549. else
  550. rs_count -= len;
  551. }
  552. static inline void
  553. _rs_rekey(u_char *dat, size_t datlen)
  554. {
  555. #ifndef KEYSTREAM_ONLY
  556. memset(rs_buf, 0, RSBUFSZ);
  557. #endif
  558. /* fill rs_buf with the keystream */
  559. chacha_encrypt_bytes(&rs, rs_buf, rs_buf, RSBUFSZ);
  560. /* mix in optional user provided data */
  561. if (dat) {
  562. size_t i, m;
  563. m = MIN(datlen, KEYSZ + IVSZ);
  564. for (i = 0; i < m; i++)
  565. rs_buf[i] ^= dat[i];
  566. }
  567. /* immediately reinit for backtracking resistance */
  568. _rs_init(rs_buf, KEYSZ + IVSZ);
  569. memset(rs_buf, 0, KEYSZ + IVSZ);
  570. rs_have = RSBUFSZ - KEYSZ - IVSZ;
  571. }
  572. static inline void
  573. _rs_random_buf(void *_buf, size_t n)
  574. {
  575. u_char *buf = (u_char *)_buf;
  576. size_t m;
  577. _rs_stir_if_needed(n);
  578. while (n > 0) {
  579. if (rs_have > 0) {
  580. m = MIN(n, rs_have);
  581. memcpy(buf, rs_buf + RSBUFSZ - rs_have, m);
  582. memset(rs_buf + RSBUFSZ - rs_have, 0, m);
  583. buf += m;
  584. n -= m;
  585. rs_have -= m;
  586. }
  587. if (rs_have == 0)
  588. _rs_rekey(NULL, 0);
  589. }
  590. }
  591. static inline void
  592. _rs_random_u32(u_int32_t *val)
  593. {
  594. _rs_stir_if_needed(sizeof(*val));
  595. if (rs_have < sizeof(*val))
  596. _rs_rekey(NULL, 0);
  597. memcpy(val, rs_buf + RSBUFSZ - rs_have, sizeof(*val));
  598. memset(rs_buf + RSBUFSZ - rs_have, 0, sizeof(*val));
  599. rs_have -= sizeof(*val);
  600. return;
  601. }
  602. /* Return one word of randomness from a ChaCha20 generator */
  603. u_int32_t
  604. arc4random(void)
  605. {
  606. u_int32_t ret;
  607. mtx_enter(&rndlock);
  608. _rs_random_u32(&ret);
  609. rndstats.arc4_reads += sizeof(ret);
  610. mtx_leave(&rndlock);
  611. return ret;
  612. }
  613. /*
  614. * Fill a buffer of arbitrary length with ChaCha20-derived randomness.
  615. */
  616. void
  617. arc4random_buf(void *buf, size_t n)
  618. {
  619. mtx_enter(&rndlock);
  620. _rs_random_buf(buf, n);
  621. rndstats.arc4_reads += n;
  622. mtx_leave(&rndlock);
  623. }
  624. /*
  625. * Calculate a uniformly distributed random number less than upper_bound
  626. * avoiding "modulo bias".
  627. *
  628. * Uniformity is achieved by generating new random numbers until the one
  629. * returned is outside the range [0, 2**32 % upper_bound). This
  630. * guarantees the selected random number will be inside
  631. * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
  632. * after reduction modulo upper_bound.
  633. */
  634. u_int32_t
  635. arc4random_uniform(u_int32_t upper_bound)
  636. {
  637. u_int32_t r, min;
  638. if (upper_bound < 2)
  639. return 0;
  640. /* 2**32 % x == (2**32 - x) % x */
  641. min = -upper_bound % upper_bound;
  642. /*
  643. * This could theoretically loop forever but each retry has
  644. * p > 0.5 (worst case, usually far better) of selecting a
  645. * number inside the range we need, so it should rarely need
  646. * to re-roll.
  647. */
  648. for (;;) {
  649. r = arc4random();
  650. if (r >= min)
  651. break;
  652. }
  653. return r % upper_bound;
  654. }
  655. /* ARGSUSED */
  656. void
  657. arc4_init(void *null)
  658. {
  659. _rs_stir(1);
  660. }
  661. /*
  662. * Called by timeout to mark arc4 for stirring,
  663. */
  664. void
  665. arc4_reinit(void *v)
  666. {
  667. task_add(systq, &arc4_task);
  668. /* 10 minutes, per dm@'s suggestion */
  669. timeout_add_sec(&arc4_timeout, 10 * 60);
  670. }
  671. /*
  672. * Start periodic services inside the random subsystem, which pull
  673. * entropy forward, hash it, and re-seed the random stream as needed.
  674. */
  675. void
  676. random_start(void)
  677. {
  678. #if !defined(NO_PROPOLICE)
  679. extern long __guard_local;
  680. if (__guard_local == 0)
  681. printf("warning: no entropy supplied by boot loader\n");
  682. #endif
  683. rnd_states[RND_SRC_TIMER].dont_count_entropy = 1;
  684. rnd_states[RND_SRC_TRUE].dont_count_entropy = 1;
  685. rnd_states[RND_SRC_TRUE].max_entropy = 1;
  686. /* Provide some data from this kernel */
  687. add_entropy_words((u_int32_t *)version,
  688. strlen(version) / sizeof(u_int32_t));
  689. /* Provide some data from this kernel */
  690. add_entropy_words((u_int32_t *)cfdata,
  691. 8192 / sizeof(u_int32_t));
  692. /* Message buffer may contain data from previous boot */
  693. if (msgbufp->msg_magic == MSG_MAGIC)
  694. add_entropy_words((u_int32_t *)msgbufp->msg_bufc,
  695. msgbufp->msg_bufs / sizeof(u_int32_t));
  696. rs_initialized = 1;
  697. dequeue_randomness(NULL);
  698. arc4_init(NULL);
  699. timeout_set(&arc4_timeout, arc4_reinit, NULL);
  700. arc4_reinit(NULL);
  701. timeout_set(&rnd_timeout, dequeue_randomness, NULL);
  702. }
  703. int
  704. randomopen(dev_t dev, int flag, int mode, struct proc *p)
  705. {
  706. return 0;
  707. }
  708. int
  709. randomclose(dev_t dev, int flag, int mode, struct proc *p)
  710. {
  711. return 0;
  712. }
  713. /*
  714. * Maximum number of bytes to serve directly from the main ChaCha
  715. * pool. Larger requests are served from a discrete ChaCha instance keyed
  716. * from the main pool.
  717. */
  718. #define ARC4_MAIN_MAX_BYTES 2048
  719. int
  720. randomread(dev_t dev, struct uio *uio, int ioflag)
  721. {
  722. u_char lbuf[KEYSZ+IVSZ];
  723. chacha_ctx lctx;
  724. size_t total = uio->uio_resid;
  725. u_char *buf;
  726. int myctx = 0, ret = 0;
  727. if (uio->uio_resid == 0)
  728. return 0;
  729. buf = malloc(POOLBYTES, M_TEMP, M_WAITOK);
  730. if (total > ARC4_MAIN_MAX_BYTES) {
  731. arc4random_buf(lbuf, sizeof(lbuf));
  732. chacha_keysetup(&lctx, lbuf, KEYSZ * 8, 0);
  733. chacha_ivsetup(&lctx, lbuf + KEYSZ);
  734. explicit_bzero(lbuf, sizeof(lbuf));
  735. myctx = 1;
  736. }
  737. while (ret == 0 && uio->uio_resid > 0) {
  738. int n = min(POOLBYTES, uio->uio_resid);
  739. if (myctx) {
  740. #ifndef KEYSTREAM_ONLY
  741. memset(buf, 0, n);
  742. #endif
  743. chacha_encrypt_bytes(&lctx, buf, buf, n);
  744. } else
  745. arc4random_buf(buf, n);
  746. ret = uiomovei(buf, n, uio);
  747. if (ret == 0 && uio->uio_resid > 0)
  748. yield();
  749. }
  750. if (myctx)
  751. explicit_bzero(&lctx, sizeof(lctx));
  752. explicit_bzero(buf, POOLBYTES);
  753. free(buf, M_TEMP, POOLBYTES);
  754. return ret;
  755. }
  756. int
  757. randomwrite(dev_t dev, struct uio *uio, int flags)
  758. {
  759. int ret = 0, newdata = 0;
  760. u_int32_t *buf;
  761. if (uio->uio_resid == 0)
  762. return 0;
  763. buf = malloc(POOLBYTES, M_TEMP, M_WAITOK);
  764. while (ret == 0 && uio->uio_resid > 0) {
  765. int n = min(POOLBYTES, uio->uio_resid);
  766. ret = uiomovei(buf, n, uio);
  767. if (ret != 0)
  768. break;
  769. while (n % sizeof(u_int32_t))
  770. ((u_int8_t *)buf)[n++] = 0;
  771. add_entropy_words(buf, n / 4);
  772. if (uio->uio_resid > 0)
  773. yield();
  774. newdata = 1;
  775. }
  776. if (newdata)
  777. arc4_init(NULL);
  778. explicit_bzero(buf, POOLBYTES);
  779. free(buf, M_TEMP, POOLBYTES);
  780. return ret;
  781. }
  782. int
  783. randomkqfilter(dev_t dev, struct knote *kn)
  784. {
  785. switch (kn->kn_filter) {
  786. case EVFILT_READ:
  787. kn->kn_fop = &randomread_filtops;
  788. break;
  789. case EVFILT_WRITE:
  790. kn->kn_fop = &randomwrite_filtops;
  791. break;
  792. default:
  793. return (EINVAL);
  794. }
  795. return (0);
  796. }
  797. void
  798. filt_randomdetach(struct knote *kn)
  799. {
  800. }
  801. int
  802. filt_randomread(struct knote *kn, long hint)
  803. {
  804. kn->kn_data = ARC4_MAIN_MAX_BYTES;
  805. return (1);
  806. }
  807. int
  808. filt_randomwrite(struct knote *kn, long hint)
  809. {
  810. kn->kn_data = POOLBYTES;
  811. return (1);
  812. }
  813. int
  814. randomioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct proc *p)
  815. {
  816. switch (cmd) {
  817. case FIOASYNC:
  818. /* No async flag in softc so this is a no-op. */
  819. break;
  820. case FIONBIO:
  821. /* Handled in the upper FS layer. */
  822. break;
  823. default:
  824. return ENOTTY;
  825. }
  826. return 0;
  827. }
  828. int
  829. sys_getentropy(struct proc *p, void *v, register_t *retval)
  830. {
  831. struct sys_getentropy_args /* {
  832. syscallarg(void *) buf;
  833. syscallarg(size_t) nbyte;
  834. } */ *uap = v;
  835. char buf[256];
  836. int error;
  837. if (SCARG(uap, nbyte) > sizeof(buf))
  838. return (EIO);
  839. arc4random_buf(buf, SCARG(uap, nbyte));
  840. if ((error = copyout(buf, SCARG(uap, buf), SCARG(uap, nbyte))) != 0)
  841. return (error);
  842. explicit_bzero(buf, sizeof(buf));
  843. retval[0] = 0;
  844. return (0);
  845. }