xref: /openbsd-src/sys/dev/rnd.c (revision 8500990981f885cbe5e6a4958549cacc238b5ae6)
1 /*	$OpenBSD: rnd.c,v 1.66 2003/11/03 18:24:28 tedu Exp $	*/
2 
3 /*
4  * rnd.c -- A strong random number generator
5  *
6  * Copyright (c) 1996, 1997, 2000-2002 Michael Shalayeff.
7  *
8  * Version 1.89, last modified 19-Sep-99
9  *
10  * Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999.
11  * All rights reserved.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, and the entire permission notice in its entirety,
18  *    including the disclaimer of warranties.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. The name of the author may not be used to endorse or promote
23  *    products derived from this software without specific prior
24  *    written permission.
25  *
26  * ALTERNATIVELY, this product may be distributed under the terms of
27  * the GNU Public License, in which case the provisions of the GPL are
28  * required INSTEAD OF the above restrictions.  (This clause is
29  * necessary due to a potential bad interaction between the GPL and
30  * the restrictions contained in a BSD-style copyright.)
31  *
32  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
33  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
35  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
36  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
37  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
38  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
40  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
41  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
42  * OF THE POSSIBILITY OF SUCH DAMAGE.
43  */
44 /*
45  * (now, with legal B.S. out of the way.....)
46  *
47  * This routine gathers environmental noise from device drivers, etc.,
48  * and returns good random numbers, suitable for cryptographic use.
49  * Besides the obvious cryptographic uses, these numbers are also good
50  * for seeding TCP sequence numbers, and other places where it is
51  * desirable to have numbers which are not only random, but hard to
52  * predict by an attacker.
53  *
54  * Theory of operation
55  * ===================
56  *
57  * Computers are very predictable devices.  Hence it is extremely hard
58  * to produce truly random numbers on a computer --- as opposed to
59  * pseudo-random numbers, which can be easily generated by using an
60  * algorithm.  Unfortunately, it is very easy for attackers to guess
61  * the sequence of pseudo-random number generators, and for some
62  * applications this is not acceptable.  Instead, we must try to
63  * gather "environmental noise" from the computer's environment, which
64  * must be hard for outside attackers to observe and use to
65  * generate random numbers.  In a Unix environment, this is best done
66  * from inside the kernel.
67  *
68  * Sources of randomness from the environment include inter-keyboard
69  * timings, inter-interrupt timings from some interrupts, and other
70  * events which are both (a) non-deterministic and (b) hard for an
71  * outside observer to measure.  Randomness from these sources is
72  * added to the "entropy pool", which is mixed using a CRC-like function.
73  * This is not cryptographically strong, but it is adequate assuming
74  * the randomness is not chosen maliciously, and it is fast enough that
75  * the overhead of doing it on every interrupt is very reasonable.
76  * As random bytes are mixed into the entropy pool, the routines keep
77  * an *estimate* of how many bits of randomness have been stored into
78  * the random number generator's internal state.
79  *
80  * When random bytes are desired, they are obtained by taking the MD5
81  * hash of the content of the entropy pool.  The MD5 hash avoids
82  * exposing the internal state of the entropy pool.  It is believed to
83  * be computationally infeasible to derive any useful information
84  * about the input of MD5 from its output.  Even if it is possible to
85  * analyze MD5 in some clever way, as long as the amount of data
86  * returned from the generator is less than the inherent entropy in
87  * the pool, the output data is totally unpredictable.  For this
88  * reason, the routine decreases its internal estimate of how many
89  * bits of "true randomness" are contained in the entropy pool as it
90  * outputs random numbers.
91  *
92  * If this estimate goes to zero, the routine can still generate
93  * random numbers; however, an attacker may (at least in theory) be
94  * able to infer the future output of the generator from prior
95  * outputs.  This requires successful cryptanalysis of MD5, which is
96  * believed to be not feasible, but there is a remote possibility.
97  * Nonetheless, these numbers should be useful for the vast majority
98  * of purposes.
99  *
100  * Exported interfaces ---- output
101  * ===============================
102  *
103  * There are three exported interfaces.
104  * The first one is designed to be used from within the kernel:
105  *
106  *	void get_random_bytes(void *buf, int nbytes);
107  *
108  * This interface will return the requested number of random bytes,
109  * and place it in the requested buffer.
110  *
111  * Two other interfaces are two character devices /dev/random and
112  * /dev/urandom.  /dev/random is suitable for use when very high
113  * quality randomness is desired (for example, for key generation or
114  * one-time pads), as it will only return a maximum of the number of
115  * bits of randomness (as estimated by the random number generator)
116  * contained in the entropy pool.
117  *
118  * The /dev/urandom device does not have this limit, and will return
119  * as many bytes as were requested.  As more and more random bytes
120  * requested without giving time for the entropy pool to recharge,
121  * this will result in random numbers that are merely cryptographically
122  * strong.  For many applications, however, this is acceptable.
123  *
124  * Exported interfaces ---- input
125  * ==============================
126  *
127  * The current exported interfaces for gathering environmental noise
128  * from the devices are:
129  *
130  *	void add_true_randomness(int data);
131  *	void add_timer_randomness(int data);
132  *	void add_mouse_randomness(int mouse_data);
133  *	void add_net_randomness(int isr);
134  *	void add_tty_randomness(int c);
135  *	void add_disk_randomness(int n);
136  *	void add_audio_randomness(int n);
137  *
138  * add_true_randomness() uses true random number generators present
139  * on some cryptographic and system chipsets.  Entropy accounting
140  * is not quitable, no timing is done, supplied 32 bits of pure entropy
141  * are hashed into the pool plain and blindly, increasing the counter.
142  *
143  * add_timer_randomness() uses the random driver itselves timing,
144  * measuring extract_entropy() and rndioctl() execution times.
145  *
146  * add_mouse_randomness() uses the mouse interrupt timing, as well as
147  * the reported position of the mouse from the hardware.
148  *
149  * add_net_randomness() times the finishing time of net input.
150  *
151  * add_tty_randomness() uses the inter-keypress timing, as well as the
152  * character as random inputs into the entropy pool.
153  *
154  * add_disk_randomness() times the finishing time of disk requests as well
155  * as feeding both xfer size & time into the entropy pool.
156  *
157  * add_audio_randomness() times the finishing of audio codec dma
158  * requests for both recording and playback, apparently supplies quite
159  * a lot of entropy. I'd blame it on low resolution audio clock generators.
160  *
161  * All of these routines (except for add_true_randomness() of course)
162  * try to estimate how many bits of randomness are in a particular
163  * randomness source.  They do this by keeping track of the first and
164  * second order deltas of the event timings.
165  *
166  * Ensuring unpredictability at system startup
167  * ============================================
168  *
169  * When any operating system starts up, it will go through a sequence
170  * of actions that are fairly predictable by an adversary, especially
171  * if the start-up does not involve interaction with a human operator.
172  * This reduces the actual number of bits of unpredictability in the
173  * entropy pool below the value in entropy_count.  In order to
174  * counteract this effect, it helps to carry information in the
175  * entropy pool across shut-downs and start-ups.  To do this, put the
176  * following lines in appropriate script which is run during the boot
177  * sequence:
178  *
179  *	echo "Initializing random number generator..."
180  *	# Carry a random seed from start-up to start-up
181  *	# Load and then save 512 bytes, which is the size of the entropy pool
182  *	if [ -f /etc/random-seed ]; then
183  *		cat /etc/random-seed >/dev/urandom
184  *	fi
185  *	dd if=/dev/urandom of=/etc/random-seed count=1
186  *
187  * and the following lines in appropriate script which is run when
188  * the system is shutting down:
189  *
190  *	# Carry a random seed from shut-down to start-up
191  *	# Save 512 bytes, which is the size of the entropy pool
192  *	echo "Saving random seed..."
193  *	dd if=/dev/urandom of=/etc/random-seed count=1
194  *
195  * For example, on many Linux systems, the appropriate scripts are
196  * usually /etc/rc.d/rc.local and /etc/rc.d/rc.0, respectively.
197  *
198  * Effectively, these commands cause the contents of the entropy pool
199  * to be saved at shutdown time and reloaded into the entropy pool at
200  * start-up.  (The 'dd' in the addition to the bootup script is to
201  * make sure that /etc/random-seed is different for every start-up,
202  * even if the system crashes without executing rc.0.)  Even with
203  * complete knowledge of the start-up activities, predicting the state
204  * of the entropy pool requires knowledge of the previous history of
205  * the system.
206  *
207  * Configuring the /dev/random driver under Linux
208  * ==============================================
209  *
210  * The /dev/random driver under Linux uses minor numbers 8 and 9 of
211  * the /dev/mem major number (#1).  So if your system does not have
212  * /dev/random and /dev/urandom created already, they can be created
213  * by using the commands:
214  *
215  *	mknod /dev/random c 1 8
216  *	mknod /dev/urandom c 1 9
217  *
218  * Acknowledgements:
219  * =================
220  *
221  * Ideas for constructing this random number generator were derived
222  * from Pretty Good Privacy's random number generator, and from private
223  * discussions with Phil Karn.  Colin Plumb provided a faster random
224  * number generator, which speeds up the mixing function of the entropy
225  * pool, taken from PGPfone.  Dale Worley has also contributed many
226  * useful ideas and suggestions to improve this driver.
227  *
228  * Any flaws in the design are solely my responsibility, and should
229  * not be attributed to the Phil, Colin, or any of the authors of PGP.
230  *
231  * Further background information on this topic may be obtained from
232  * RFC 1750, "Randomness Recommendations for Security", by Donald
233  * Eastlake, Steve Crocker, and Jeff Schiller.
234  */
235 
236 #undef RNDEBUG
237 
238 #include <sys/param.h>
239 #include <sys/systm.h>
240 #include <sys/conf.h>
241 #include <sys/disk.h>
242 #include <sys/ioctl.h>
243 #include <sys/malloc.h>
244 #include <sys/fcntl.h>
245 #include <sys/vnode.h>
246 #include <sys/md5k.h>
247 #include <sys/sysctl.h>
248 #include <sys/timeout.h>
249 #include <sys/poll.h>
250 
251 #include <dev/rndvar.h>
252 #include <dev/rndioctl.h>
253 
254 #ifdef	RNDEBUG
255 int	rnd_debug = 0x0000;
256 #define	RD_INPUT	0x000f	/* input data */
257 #define	RD_OUTPUT	0x00f0	/* output data */
258 #define	RD_WAIT		0x0100	/* sleep/wakeup for good data */
259 #endif
260 
261 /*
262  * The pool is stirred with a primitive polynomial of degree 128
263  * over GF(2), namely x^128 + x^99 + x^59 + x^31 + x^9 + x^7 + 1.
264  * For a pool of size 64, try x^64+x^62+x^38+x^10+x^6+x+1.
265  */
266 #define POOLBITS (POOLWORDS*32)
267 #if POOLWORDS == 2048
268 #define	TAP1	1638
269 #define	TAP2	1231
270 #define	TAP3	819
271 #define	TAP4	411
272 #define	TAP5	1
273 #elif POOLWORDS == 1024	/* also (819, 616, 410, 207, 2) */
274 #define	TAP1	817
275 #define	TAP2	615
276 #define	TAP3	412
277 #define	TAP4	204
278 #define	TAP5	1
279 #elif POOLWORDS == 512	/* also (409,307,206,102,2), (409,309,205,103,2) */
280 #define	TAP1	411
281 #define	TAP2	308
282 #define	TAP3	208
283 #define	TAP4	104
284 #define	TAP5	1
285 #elif POOLWORDS == 256
286 #define	TAP1	205
287 #define	TAP2	155
288 #define	TAP3	101
289 #define	TAP4	52
290 #define	TAP5	1
291 #elif POOLWORDS == 128	/* also (103, 78, 51, 27, 2) */
292 #define	TAP1	103
293 #define	TAP2	76
294 #define	TAP3	51
295 #define	TAP4	25
296 #define	TAP5	1
297 #elif POOLWORDS == 64
298 #define	TAP1	52
299 #define	TAP2	39
300 #define	TAP3	26
301 #define	TAP4	14
302 #define	TAP5	1
303 #elif POOLWORDS == 32
304 #define	TAP1	26
305 #define	TAP2	20
306 #define	TAP3	14
307 #define	TAP4	7
308 #define	TAP5	1
309 #else
310 #error No primitive polynomial available for chosen POOLWORDS
311 #endif
312 
313 /*
314  * For the purposes of better mixing, we use the CRC-32 polynomial as
315  * well to make a twisted Generalized Feedback Shift Register
316  *
317  * (See M. Matsumoto & Y. Kurita, 1992.  Twisted GFSR generators.  ACM
318  * Transactions on Modeling and Computer Simulation 2(3):179-194.
319  * Also see M. Matsumoto & Y. Kurita, 1994.  Twisted GFSR generators
320  * II.  ACM Transactions on Mdeling and Computer Simulation 4:254-266)
321  *
322  * Thanks to Colin Plumb for suggesting this.
323  *
324  * We have not analyzed the resultant polynomial to prove it primitive;
325  * in fact it almost certainly isn't.  Nonetheless, the irreducible factors
326  * of a random large-degree polynomial over GF(2) are more than large enough
327  * that periodicity is not a concern.
328  *
329  * The input hash is much less sensitive than the output hash.  All
330  * we want from it is to be a good non-cryptographic hash -
331  * i.e. to not produce collisions when fed "random" data of the sort
332  * we expect to see.  As long as the pool state differs for different
333  * inputs, we have preserved the input entropy and done a good job.
334  * The fact that an intelligent attacker can construct inputs that
335  * will produce controlled alterations to the pool's state is not
336  * important because we don't consider such inputs to contribute any
337  * randomness.  The only property we need with respect to them is that
338  * the attacker can't increase his/her knowledge of the pool's state.
339  * Since all additions are reversible (knowing the final state and the
340  * input, you can reconstruct the initial state), if an attacker has
341  * any uncertainty about the initial state, he/she can only shuffle
342  * that uncertainty about, but never cause any collisions (which would
343  * decrease the uncertainty).
344  *
345  * The chosen system lets the state of the pool be (essentially) the input
346  * modulo the generator polynomial.  Now, for random primitive polynomials,
347  * this is a universal class of hash functions, meaning that the chance
348  * of a collision is limited by the attacker's knowledge of the generator
349  * polynomial, so if it is chosen at random, an attacker can never force
350  * a collision.  Here, we use a fixed polynomial, but we *can* assume that
351  * ###--> it is unknown to the processes generating the input entropy. <-###
352  * Because of this important property, this is a good, collision-resistant
353  * hash; hash collisions will occur no more often than chance.
354  */
355 
356 /* pIII/333 reported to have some drops w/ these numbers */
357 #define QEVLEN (1024 / sizeof(struct rand_event))
358 #define QEVSLOW (QEVLEN * 3 / 4) /* yet another 0.75 for 60-minutes hour /-; */
359 #define QEVSBITS 10
360 
361 /* There is actually only one of these, globally. */
362 struct random_bucket {
363 	u_int	add_ptr;
364 	u_int	entropy_count;
365 	u_char	input_rotate;
366 	u_int32_t pool[POOLWORDS];
367 	u_int	asleep;
368 	u_int	tmo;
369 };
370 
371 /* There is one of these per entropy source */
372 struct timer_rand_state {
373 	u_int	last_time;
374 	u_int	last_delta;
375 	u_int	last_delta2;
376 	u_int	dont_count_entropy : 1;
377 	u_int	max_entropy : 1;
378 };
379 
380 struct arc4_stream {
381 	u_int8_t s[256];
382 	u_int	cnt;
383 	u_int8_t i;
384 	u_int8_t j;
385 };
386 
387 struct rand_event {
388 	struct timer_rand_state *re_state;
389 	u_int re_nbits;
390 	u_int re_time;
391 	u_int re_val;
392 };
393 
394 struct timeout rnd_timeout, arc4_timeout;
395 struct random_bucket random_state;
396 struct arc4_stream arc4random_state;
397 struct timer_rand_state rnd_states[RND_SRC_NUM];
398 struct rand_event rnd_event_space[QEVLEN];
399 struct rand_event *rnd_event_head = rnd_event_space;
400 struct rand_event *rnd_event_tail = rnd_event_space;
401 struct selinfo rnd_rsel, rnd_wsel;
402 
403 void filt_rndrdetach(struct knote *kn);
404 int filt_rndread(struct knote *kn, long hint);
405 
406 struct filterops rndread_filtops =
407 	{ 1, NULL, filt_rndrdetach, filt_rndread};
408 
409 void filt_rndwdetach(struct knote *kn);
410 int filt_rndwrite(struct knote *kn, long hint);
411 
412 struct filterops rndwrite_filtops =
413 	{ 1, NULL, filt_rndwdetach, filt_rndwrite};
414 
415 int rnd_attached;
416 int arc4random_initialized;
417 struct rndstats rndstats;
418 
419 static __inline u_int32_t roll(u_int32_t w, int i)
420 {
421 #ifdef i386
422 	__asm ("roll %%cl, %0" : "+r" (w) : "c" (i));
423 #else
424 	w = (w << i) | (w >> (32 - i));
425 #endif
426 	return w;
427 }
428 
429 /* must be called at a proper spl, returns ptr to the next event */
430 static __inline struct rand_event *
431 rnd_get(void)
432 {
433 	struct rand_event *p = rnd_event_tail;
434 
435 	if (p == rnd_event_head)
436 		return NULL;
437 
438 	if (p + 1 >= &rnd_event_space[QEVLEN])
439 		rnd_event_tail = rnd_event_space;
440 	else
441 		rnd_event_tail++;
442 
443 	return p;
444 }
445 
446 /* must be called at a proper spl, returns next available item */
447 static __inline struct rand_event *
448 rnd_put(void)
449 {
450 	struct rand_event *p = rnd_event_head + 1;
451 
452 	if (p >= &rnd_event_space[QEVLEN])
453 		p = rnd_event_space;
454 
455 	if (p == rnd_event_tail)
456 		return NULL;
457 
458 	return rnd_event_head = p;
459 }
460 
461 /* must be called at a proper spl, returns number of items in the queue */
462 static __inline int
463 rnd_qlen(void)
464 {
465 	int len = rnd_event_head - rnd_event_tail;
466 	return (len < 0)? -len : len;
467 }
468 
469 void dequeue_randomness(void *);
470 
471 static __inline void add_entropy_words(const u_int32_t *, u_int n);
472 static __inline void extract_entropy(register u_int8_t *, int);
473 
474 static __inline u_int8_t arc4_getbyte(void);
475 static __inline void arc4_stir(void);
476 void arc4_reinit(void *v);
477 void arc4maybeinit(void);
478 
479 /* Arcfour random stream generator.  This code is derived from section
480  * 17.1 of Applied Cryptography, second edition, which describes a
481  * stream cipher allegedly compatible with RSA Labs "RC4" cipher (the
482  * actual description of which is a trade secret).  The same algorithm
483  * is used as a stream cipher called "arcfour" in Tatu Ylonen's ssh
484  * package.
485  *
486  * The initialization function here has been modified to not discard
487  * the old state, and it's input always includes the time of day in
488  * microseconds.  Moreover, bytes from the stream may at any point be
489  * diverted to multiple processes or even kernel functions desiring
490  * random numbers.  This increases the strength of the random stream,
491  * but makes it impossible to use this code for encryption, since there
492  * is no way to ever reproduce the same stream of random bytes.
493  *
494  * RC4 is a registered trademark of RSA Laboratories.
495  */
496 
497 static __inline u_int8_t
498 arc4_getbyte(void)
499 {
500 	register u_int8_t si, sj, ret;
501 	int s;
502 
503 	s = splhigh();
504 	rndstats.arc4_reads++;
505 	arc4random_state.cnt++;
506 	arc4random_state.i++;
507 	si = arc4random_state.s[arc4random_state.i];
508 	arc4random_state.j += si;
509 	sj = arc4random_state.s[arc4random_state.j];
510 	arc4random_state.s[arc4random_state.i] = sj;
511 	arc4random_state.s[arc4random_state.j] = si;
512 	ret = arc4random_state.s[(si + sj) & 0xff];
513 	splx(s);
514 	return (ret);
515 }
516 
517 static __inline void
518 arc4_stir(void)
519 {
520 	u_int8_t buf[256];
521 	register u_int8_t si;
522 	register int n, s;
523 	int len;
524 
525 	microtime((struct timeval *) buf);
526 	len = random_state.entropy_count / 8; /* XXX maybe a half? */
527 	if (len > sizeof(buf) - sizeof(struct timeval))
528 		len = sizeof(buf) - sizeof(struct timeval);
529 	get_random_bytes(buf + sizeof (struct timeval), len);
530 	len += sizeof(struct timeval);
531 
532 	s = splhigh();
533 	arc4random_state.i--;
534 	for (n = 0; n < 256; n++) {
535 		arc4random_state.i++;
536 		si = arc4random_state.s[arc4random_state.i];
537 		arc4random_state.j += si + buf[n % len];
538 		arc4random_state.s[arc4random_state.i] =
539 		    arc4random_state.s[arc4random_state.j];
540 		arc4random_state.s[arc4random_state.j] = si;
541 	}
542 	arc4random_state.j = arc4random_state.i;
543 	arc4random_state.cnt = 0;
544 	rndstats.arc4_stirs += len;
545 	rndstats.arc4_nstirs++;
546 	splx(s);
547 
548 	/*
549 	 * Throw away the first N words of output, as suggested in the
550 	 * paper "Weaknesses in the Key Scheduling Algorithm of RC4"
551 	 * by Fluher, Mantin, and Shamir.  (N = 256 in our case.)
552 	 */
553 	for (n = 0; n < 256 * 4; n++)
554 		arc4_getbyte();
555 }
556 
557 void
558 arc4maybeinit(void)
559 {
560 	extern int hz;
561 
562 	if (!arc4random_initialized) {
563 		arc4random_initialized++;
564 		arc4_stir();
565 		/* 10 minutes, per dm@'s suggestion */
566 		timeout_add(&arc4_timeout, 10 * 60 * hz);
567 	}
568 }
569 
570 /*
571  * called by timeout to mark arc4 for stirring,
572  * actual stirring happens on any access attempt.
573  */
574 void
575 arc4_reinit(v)
576 	void *v;
577 {
578 	arc4random_initialized = 0;
579 }
580 
581 static int arc4random_8(void);
582 
583 static int
584 arc4random_8(void)
585 {
586 	arc4maybeinit();
587 	return arc4_getbyte();
588 }
589 
590 u_int32_t
591 arc4random(void)
592 {
593 	arc4maybeinit();
594 	return ((arc4_getbyte() << 24) | (arc4_getbyte() << 16)
595 		| (arc4_getbyte() << 8) | arc4_getbyte());
596 }
597 
598 void
599 arc4random_bytes(void *buf, size_t n)
600 {
601 	u_int8_t *cp = buf;
602 	u_int8_t *end = cp + n;
603 
604 	arc4maybeinit();
605 	while (cp < end)
606 		*cp++ = arc4_getbyte();
607 }
608 
609 void
610 randomattach(void)
611 {
612 	int i;
613 
614 	if (rnd_attached) {
615 #ifdef RNDEBUG
616 		printf("random: second attach\n");
617 #endif
618 		return;
619 	}
620 
621 	timeout_set(&rnd_timeout, dequeue_randomness, &random_state);
622 	timeout_set(&arc4_timeout, arc4_reinit, NULL);
623 
624 	random_state.add_ptr = 0;
625 	random_state.entropy_count = 0;
626 	rnd_states[RND_SRC_TIMER].dont_count_entropy = 1;
627 	rnd_states[RND_SRC_TRUE].dont_count_entropy = 1;
628 	rnd_states[RND_SRC_TRUE].max_entropy = 1;
629 
630 	bzero(&rndstats, sizeof(rndstats));
631 	bzero(&rnd_event_space, sizeof(rnd_event_space));
632 
633 	for (i = 0; i < 256; i++)
634 		arc4random_state.s[i] = i;
635 	arc4_reinit(NULL);
636 
637 	rnd_attached = 1;
638 }
639 
640 int
641 randomopen(dev, flag, mode, p)
642 	dev_t	dev;
643 	int	flag;
644 	int	mode;
645 	struct proc *p;
646 {
647 	return (minor (dev) < RND_NODEV) ? 0 : ENXIO;
648 }
649 
650 int
651 randomclose(dev, flag, mode, p)
652 	dev_t	dev;
653 	int	flag;
654 	int	mode;
655 	struct proc *p;
656 {
657 	return 0;
658 }
659 
660 /*
661  * This function adds a byte into the entropy pool.  It does not
662  * update the entropy estimate.  The caller must do this if appropriate.
663  *
664  * The pool is stirred with a primitive polynomial of degree 128
665  * over GF(2), namely x^128 + x^99 + x^59 + x^31 + x^9 + x^7 + 1.
666  * For a pool of size 64, try x^64+x^62+x^38+x^10+x^6+x+1.
667  *
668  * We rotate the input word by a changing number of bits, to help
669  * assure that all bits in the entropy get toggled.  Otherwise, if we
670  * consistently feed the entropy pool small numbers (like jiffies and
671  * scancodes, for example), the upper bits of the entropy pool don't
672  * get affected. --- TYT, 10/11/95
673  */
674 static __inline void
675 add_entropy_words(buf, n)
676 	const u_int32_t *buf;
677 	u_int n;
678 {
679 	static const u_int32_t twist_table[8] = {
680 		0x00000000, 0x3b6e20c8, 0x76dc4190, 0x4db26158,
681 		0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278
682 	};
683 
684 	for (; n--; buf++) {
685 		register u_int32_t w = roll(*buf, random_state.input_rotate);
686 		register u_int i = random_state.add_ptr =
687 		    (random_state.add_ptr - 1) & (POOLWORDS - 1);
688 		/*
689 		 * Normally, we add 7 bits of rotation to the pool.
690 		 * At the beginning of the pool, add an extra 7 bits
691 		 * rotation, so that successive passes spread the
692 		 * input bits across the pool evenly.
693 		 */
694 		random_state.input_rotate =
695 		    (random_state.input_rotate + (i? 7 : 14)) & 31;
696 
697 		/* XOR in the various taps */
698 		w ^= random_state.pool[(i+TAP1) & (POOLWORDS-1)] ^
699 		     random_state.pool[(i+TAP2) & (POOLWORDS-1)] ^
700 		     random_state.pool[(i+TAP3) & (POOLWORDS-1)] ^
701 		     random_state.pool[(i+TAP4) & (POOLWORDS-1)] ^
702 		     random_state.pool[(i+TAP5) & (POOLWORDS-1)] ^
703 		     random_state.pool[i];
704 		random_state.pool[i] = (w >> 3) ^ twist_table[w & 7];
705 	}
706 }
707 
708 /*
709  * This function adds entropy to the entropy pool by using timing
710  * delays.  It uses the timer_rand_state structure to make an estimate
711  * of how many bits of entropy this call has added to the pool.
712  *
713  * The number "num" is also added to the pool - it should somehow describe
714  * the type of event which just happened.  Currently the values of 0-255
715  * are for keyboard scan codes, 256 and upwards - for interrupts.
716  * On the i386, this is assumed to be at most 16 bits, and the high bits
717  * are used for a high-resolution timer.
718  *
719  */
720 void
721 enqueue_randomness(state, val)
722 	int	state, val;
723 {
724 	register struct timer_rand_state *p;
725 	register struct rand_event *rep;
726 	struct timeval	tv;
727 	u_int	time, nbits;
728 	int s;
729 
730 	/* XXX on sparc we get here before randomattach() */
731 	if (!rnd_attached)
732 		return;
733 
734 #ifdef DIAGNOSTIC
735 	if (state < 0 || state >= RND_SRC_NUM)
736 		return;
737 #endif
738 
739 	p = &rnd_states[state];
740 	val += state << 13;
741 
742 	microtime(&tv);
743 	time = tv.tv_usec ^ tv.tv_sec;
744 	nbits = 0;
745 
746 	/*
747 	 * Calculate the number of bits of randomness that we probably
748 	 * added.  We take into account the first and second order
749 	 * deltas in order to make our estimate.
750 	 */
751 	if (!p->dont_count_entropy) {
752 		register int	delta, delta2, delta3;
753 		delta  = time   - p->last_time;
754 		delta2 = delta  - p->last_delta;
755 		delta3 = delta2 - p->last_delta2;
756 
757 		if (delta < 0) delta = -delta;
758 		if (delta2 < 0) delta2 = -delta2;
759 		if (delta3 < 0) delta3 = -delta3;
760 		if (delta > delta2) delta = delta2;
761 		if (delta > delta3) delta = delta3;
762 		delta3 = delta >>= 1;
763 		/*
764 		 * delta &= 0xfff;
765 		 * we don't do it since our time sheet is different from linux
766 		 */
767 
768 		if (delta & 0xffff0000) {
769 			nbits = 16;
770 			delta >>= 16;
771 		}
772 		if (delta & 0xff00) {
773 			nbits += 8;
774 			delta >>= 8;
775 		}
776 		if (delta & 0xf0) {
777 			nbits += 4;
778 			delta >>= 4;
779 		}
780 		if (delta & 0xc) {
781 			nbits += 2;
782 			delta >>= 2;
783 		}
784 		if (delta & 2) {
785 			nbits += 1;
786 			delta >>= 1;
787 		}
788 		if (delta & 1)
789 			nbits++;
790 
791 		/*
792 		 * the logic is to drop low-entropy entries,
793 		 * in hope for dequeuing to be more randomfull
794 		 */
795 		if (rnd_qlen() > QEVSLOW && nbits < QEVSBITS) {
796 			rndstats.rnd_drople++;
797 			return;
798 		}
799 		p->last_time = time;
800 		p->last_delta  = delta3;
801 		p->last_delta2 = delta2;
802 	} else if (p->max_entropy)
803 		nbits = 8 * sizeof(val) - 1;
804 
805 	s = splhigh();
806 	if ((rep = rnd_put()) == NULL) {
807 		rndstats.rnd_drops++;
808 		splx(s);
809 		return;
810 	}
811 
812 	rep->re_state = p;
813 	rep->re_nbits = nbits;
814 	rep->re_time = time;
815 	rep->re_val = val;
816 
817 	rndstats.rnd_enqs++;
818 	rndstats.rnd_ed[nbits]++;
819 	rndstats.rnd_sc[state]++;
820 	rndstats.rnd_sb[state] += nbits;
821 
822 	if (rnd_qlen() > QEVSLOW/2 && !random_state.tmo) {
823 		random_state.tmo++;
824 		timeout_add(&rnd_timeout, 1);
825 	}
826 	splx(s);
827 }
828 
829 void
830 dequeue_randomness(v)
831 	void *v;
832 {
833 	struct random_bucket *rs = v;
834 	register struct rand_event *rep;
835 	u_int32_t buf[2];
836 	u_int nbits;
837 	int s;
838 
839 	timeout_del(&rnd_timeout);
840 	rndstats.rnd_deqs++;
841 
842 	s = splhigh();
843 	while ((rep = rnd_get())) {
844 
845 		buf[0] = rep->re_time;
846 		buf[1] = rep->re_val;
847 		nbits = rep->re_nbits;
848 		splx(s);
849 
850 		add_entropy_words(buf, 2);
851 
852 		rndstats.rnd_total += nbits;
853 		rs->entropy_count += nbits;
854 		if (rs->entropy_count > POOLBITS)
855 			rs->entropy_count = POOLBITS;
856 
857 		if (rs->asleep && rs->entropy_count > 8) {
858 #ifdef	RNDEBUG
859 			if (rnd_debug & RD_WAIT)
860 				printf("rnd: wakeup[%u]{%u}\n",
861 				    rs->asleep,
862 				    rs->entropy_count);
863 #endif
864 			rs->asleep--;
865 			wakeup((void *)&rs->asleep);
866 			selwakeup(&rnd_rsel);
867 			KNOTE(&rnd_rsel.si_note, 0);
868 		}
869 
870 		s = splhigh();
871 	}
872 
873 	rs->tmo = 0;
874 	splx(s);
875 }
876 
877 #if POOLWORDS % 16
878 #error extract_entropy() assumes that POOLWORDS is a multiple of 16 words.
879 #endif
880 
881 /*
882  * This function extracts randomness from the entropy pool, and
883  * returns it in a buffer.  This function computes how many remaining
884  * bits of entropy are left in the pool, but it does not restrict the
885  * number of bytes that are actually obtained.
886  */
887 static __inline void
888 extract_entropy(buf, nbytes)
889 	register u_int8_t *buf;
890 	int	nbytes;
891 {
892 	struct random_bucket *rs = &random_state;
893 	u_char buffer[16];
894 
895 	add_timer_randomness(nbytes);
896 
897 	while (nbytes) {
898 		MD5_CTX tmp;
899 		int i, s;
900 
901 		/* Hash the pool to get the output */
902 		MD5Init(&tmp);
903 		s = splhigh();
904 		MD5Update(&tmp, (u_int8_t*)rs->pool, sizeof(rs->pool));
905 		if (rs->entropy_count / 8 > nbytes)
906 			rs->entropy_count -= nbytes * 8;
907 		else
908 			rs->entropy_count = 0;
909 		splx(s);
910 		MD5Final(buffer, &tmp);
911 		bzero(&tmp, sizeof(tmp));
912 
913 		/*
914 		 * In case the hash function has some recognizable
915 		 * output pattern, we fold it in half.
916 		 */
917 		buffer[0] ^= buffer[15];
918 		buffer[1] ^= buffer[14];
919 		buffer[2] ^= buffer[13];
920 		buffer[3] ^= buffer[12];
921 		buffer[4] ^= buffer[11];
922 		buffer[5] ^= buffer[10];
923 		buffer[6] ^= buffer[ 9];
924 		buffer[7] ^= buffer[ 8];
925 
926 		/* Copy data to destination buffer */
927 		if (nbytes < sizeof(buffer) / 2)
928 			bcopy(buffer, buf, i = nbytes);
929 		else
930 			bcopy(buffer, buf, i = sizeof(buffer) / 2);
931 		nbytes -= i;
932 		buf += i;
933 
934 		/* Modify pool so next hash will produce different results */
935 		add_timer_randomness(nbytes);
936 		dequeue_randomness(&random_state);
937 	}
938 
939 	/* Wipe data from memory */
940 	bzero(&buffer, sizeof(buffer));
941 }
942 
943 /*
944  * This function is the exported kernel interface.  It returns some
945  * number of good random numbers, suitable for seeding TCP sequence
946  * numbers, etc.
947  */
948 void
949 get_random_bytes(buf, nbytes)
950 	void	*buf;
951 	size_t	nbytes;
952 {
953 	extract_entropy((u_int8_t *) buf, nbytes);
954 	rndstats.rnd_used += nbytes * 8;
955 }
956 
957 int
958 randomread(dev, uio, ioflag)
959 	dev_t	dev;
960 	struct uio *uio;
961 	int	ioflag;
962 {
963 	int	ret = 0;
964 	int	i;
965 
966 	if (uio->uio_resid == 0)
967 		return 0;
968 
969 	while (!ret && uio->uio_resid > 0) {
970 		u_int32_t buf[ POOLWORDS ];
971 		int	n = min(sizeof(buf), uio->uio_resid);
972 
973 		switch(minor(dev)) {
974 		case RND_RND:
975 			ret = EIO;	/* no chip -- error */
976 			break;
977 		case RND_SRND:
978 			if (random_state.entropy_count < 16 * 8) {
979 				if (ioflag & IO_NDELAY) {
980 					ret = EWOULDBLOCK;
981 					break;
982 				}
983 #ifdef	RNDEBUG
984 				if (rnd_debug & RD_WAIT)
985 					printf("rnd: sleep[%u]\n",
986 					    random_state.asleep);
987 #endif
988 				random_state.asleep++;
989 				rndstats.rnd_waits++;
990 				ret = tsleep(&random_state.asleep,
991 				    PWAIT | PCATCH, "rndrd", 0);
992 #ifdef	RNDEBUG
993 				if (rnd_debug & RD_WAIT)
994 					printf("rnd: awakened(%d)\n", ret);
995 #endif
996 				if (ret)
997 					break;
998 			}
999 			if (n > random_state.entropy_count / 8)
1000 				n = random_state.entropy_count / 8;
1001 			rndstats.rnd_reads++;
1002 #ifdef	RNDEBUG
1003 			if (rnd_debug & RD_OUTPUT)
1004 				printf("rnd: %u possible output\n", n);
1005 #endif
1006 		case RND_URND:
1007 			get_random_bytes((char *)buf, n);
1008 #ifdef	RNDEBUG
1009 			if (rnd_debug & RD_OUTPUT)
1010 				printf("rnd: %u bytes for output\n", n);
1011 #endif
1012 			break;
1013 		case RND_PRND:
1014 			i = (n + 3) / 4;
1015 			while (i--)
1016 				buf[i] = random() << 16 | (random() & 0xFFFF);
1017 			break;
1018 		case RND_ARND:
1019 		{
1020 			u_int8_t *cp = (u_int8_t *) buf;
1021 			u_int8_t *end = cp + n;
1022 			while (cp < end)
1023 				*cp++ = arc4random_8();
1024 			break;
1025 		}
1026 		default:
1027 			ret = ENXIO;
1028 		}
1029 		if (n != 0 && ret == 0)
1030 			ret = uiomove((caddr_t)buf, n, uio);
1031 	}
1032 	return ret;
1033 }
1034 
1035 int
1036 randompoll(dev, events, p)
1037 	dev_t	dev;
1038 	int	events;
1039 	struct proc *p;
1040 {
1041 	int revents = 0;
1042 
1043 	if (events & (POLLIN | POLLRDNORM)) {
1044 		if (random_state.entropy_count > 0)
1045 			revents |= events & (POLLIN | POLLRDNORM);
1046 		else
1047 			selrecord(p, &rnd_rsel);
1048 	}
1049 	if (events & (POLLOUT | POLLWRNORM))
1050 		revents = events & (POLLOUT | POLLWRNORM); /* always writable */
1051 
1052 	return (revents);
1053 }
1054 
1055 int
1056 randomkqfilter(dev_t dev, struct knote *kn)
1057 {
1058 	struct klist *klist;
1059 	int s;
1060 
1061 	switch (kn->kn_filter) {
1062 	case EVFILT_READ:
1063 		klist = &rnd_rsel.si_note;
1064 		kn->kn_fop = &rndread_filtops;
1065 		break;
1066 	case EVFILT_WRITE:
1067 		klist = &rnd_wsel.si_note;
1068 		kn->kn_fop = &rndwrite_filtops;
1069 		break;
1070 	default:
1071 		return (1);
1072 	}
1073 	kn->kn_hook = (void *)&random_state;
1074 
1075 	s = splhigh();
1076 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
1077 	splx(s);
1078 
1079 	return (0);
1080 }
1081 
1082 void
1083 filt_rndrdetach(struct knote *kn)
1084 {
1085 	int s = splhigh();
1086 
1087 	SLIST_REMOVE(&rnd_rsel.si_note, kn, knote, kn_selnext);
1088 	splx(s);
1089 }
1090 
1091 int
1092 filt_rndread(kn, hint)
1093 	struct knote *kn;
1094 	long hint;
1095 {
1096 	struct random_bucket *rs = (struct random_bucket *)kn->kn_hook;
1097 
1098 	kn->kn_data = (int)rs->entropy_count;
1099 	return rs->entropy_count > 0;
1100 }
1101 
1102 void
1103 filt_rndwdetach(struct knote *kn)
1104 {
1105 	int s = splhigh();
1106 
1107 	SLIST_REMOVE(&rnd_wsel.si_note, kn, knote, kn_selnext);
1108 	splx(s);
1109 }
1110 
1111 int
1112 filt_rndwrite(kn, hint)
1113 	struct knote *kn;
1114 	long hint;
1115 {
1116 	return (1);
1117 }
1118 
1119 int
1120 randomwrite(dev, uio, flags)
1121 	dev_t	dev;
1122 	struct uio *uio;
1123 	int	flags;
1124 {
1125 	int	ret = 0;
1126 
1127 	if (minor(dev) == RND_RND || minor(dev) == RND_PRND)
1128 		return ENXIO;
1129 
1130 	if (uio->uio_resid == 0)
1131 		return 0;
1132 
1133 	while (!ret && uio->uio_resid > 0) {
1134 		u_int32_t	buf[ POOLWORDS ];
1135 		u_short		n = min(sizeof(buf),uio->uio_resid);
1136 
1137 		ret = uiomove((caddr_t)buf, n, uio);
1138 		if (!ret) {
1139 			while (n % sizeof(u_int32_t))
1140 				((u_int8_t *) buf)[n++] = 0;
1141 			add_entropy_words(buf, n / 4);
1142 		}
1143 	}
1144 
1145 	if (minor(dev) == RND_ARND && !ret)
1146 		arc4random_initialized = 0;
1147 
1148 	return ret;
1149 }
1150 
1151 int
1152 randomioctl(dev, cmd, data, flag, p)
1153 	dev_t	dev;
1154 	u_long	cmd;
1155 	caddr_t	data;
1156 	int	flag;
1157 	struct proc *p;
1158 {
1159 	int	s, ret = 0;
1160 	u_int	cnt;
1161 
1162 	add_timer_randomness((u_long)p ^ (u_long)data ^ cmd);
1163 
1164 	switch (cmd) {
1165 	case FIOASYNC:
1166 		/* rnd has no async flag in softc so this is really a no-op. */
1167 		break;
1168 
1169 	case FIONBIO:
1170 		/* Handled in the upper FS layer. */
1171 		break;
1172 
1173 	case RNDGETENTCNT:
1174 		s = splhigh();
1175 		*(u_int *)data = random_state.entropy_count;
1176 		splx(s);
1177 		break;
1178 	case RNDADDTOENTCNT:
1179 		if (suser(p, 0) != 0)
1180 			ret = EPERM;
1181 		else {
1182 			cnt = *(u_int *)data;
1183 			s = splhigh();
1184 			random_state.entropy_count += cnt;
1185 			if (random_state.entropy_count > POOLBITS)
1186 				random_state.entropy_count = POOLBITS;
1187 			splx(s);
1188 		}
1189 		break;
1190 	case RNDZAPENTCNT:
1191 		if (suser(p, 0) != 0)
1192 			ret = EPERM;
1193 		else {
1194 			s = splhigh();
1195 			random_state.entropy_count = 0;
1196 			splx(s);
1197 		}
1198 		break;
1199 	case RNDSTIRARC4:
1200 		if (suser(p, 0) != 0)
1201 			ret = EPERM;
1202 		else if (random_state.entropy_count < 64)
1203 			ret = EAGAIN;
1204 		else {
1205 			s = splhigh();
1206 			arc4random_initialized = 0;
1207 			splx(s);
1208 		}
1209 		break;
1210 	case RNDCLRSTATS:
1211 		if (suser(p, 0) != 0)
1212 			ret = EPERM;
1213 		else {
1214 			s = splhigh();
1215 			bzero(&rndstats, sizeof(rndstats));
1216 			splx(s);
1217 		}
1218 		break;
1219 	default:
1220 		ret = ENOTTY;
1221 	}
1222 
1223 	add_timer_randomness((u_long)p ^ (u_long)data ^ cmd);
1224 	return ret;
1225 }
1226