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