xref: /openbsd-src/sys/dev/rnd.c (revision db3296cf5c1dd9058ceecc3a29fe4aaa0bd26000)
1 /*	$OpenBSD: rnd.c,v 1.62 2002/11/25 10:09:24 mickey 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 
250 #include <dev/rndvar.h>
251 #include <dev/rndioctl.h>
252 
253 #ifdef	RNDEBUG
254 int	rnd_debug = 0x0000;
255 #define	RD_INPUT	0x000f	/* input data */
256 #define	RD_OUTPUT	0x00f0	/* output data */
257 #define	RD_WAIT		0x0100	/* sleep/wakeup for good data */
258 #endif
259 
260 /*
261  * The pool is stirred with a primitive polynomial of degree 128
262  * over GF(2), namely x^128 + x^99 + x^59 + x^31 + x^9 + x^7 + 1.
263  * For a pool of size 64, try x^64+x^62+x^38+x^10+x^6+x+1.
264  */
265 #define POOLBITS (POOLWORDS*32)
266 #if POOLWORDS == 2048
267 #define	TAP1	1638
268 #define	TAP2	1231
269 #define	TAP3	819
270 #define	TAP4	411
271 #define	TAP5	1
272 #elif POOLWORDS == 1024	/* also (819, 616, 410, 207, 2) */
273 #define	TAP1	817
274 #define	TAP2	615
275 #define	TAP3	412
276 #define	TAP4	204
277 #define	TAP5	1
278 #elif POOLWORDS == 512	/* also (409,307,206,102,2), (409,309,205,103,2) */
279 #define	TAP1	411
280 #define	TAP2	308
281 #define	TAP3	208
282 #define	TAP4	104
283 #define	TAP5	1
284 #elif POOLWORDS == 256
285 #define	TAP1	205
286 #define	TAP2	155
287 #define	TAP3	101
288 #define	TAP4	52
289 #define	TAP5	1
290 #elif POOLWORDS == 128	/* also (103, 78, 51, 27, 2) */
291 #define	TAP1	103
292 #define	TAP2	76
293 #define	TAP3	51
294 #define	TAP4	25
295 #define	TAP5	1
296 #elif POOLWORDS == 64
297 #define	TAP1	52
298 #define	TAP2	39
299 #define	TAP3	26
300 #define	TAP4	14
301 #define	TAP5	1
302 #elif POOLWORDS == 32
303 #define	TAP1	26
304 #define	TAP2	20
305 #define	TAP3	14
306 #define	TAP4	7
307 #define	TAP5	1
308 #else
309 #error No primitive polynomial available for chosen POOLWORDS
310 #endif
311 
312 /*
313  * For the purposes of better mixing, we use the CRC-32 polynomial as
314  * well to make a twisted Generalized Feedback Shift Register
315  *
316  * (See M. Matsumoto & Y. Kurita, 1992.  Twisted GFSR generators.  ACM
317  * Transactions on Modeling and Computer Simulation 2(3):179-194.
318  * Also see M. Matsumoto & Y. Kurita, 1994.  Twisted GFSR generators
319  * II.  ACM Transactions on Mdeling and Computer Simulation 4:254-266)
320  *
321  * Thanks to Colin Plumb for suggesting this.
322  *
323  * We have not analyzed the resultant polynomial to prove it primitive;
324  * in fact it almost certainly isn't.  Nonetheless, the irreducible factors
325  * of a random large-degree polynomial over GF(2) are more than large enough
326  * that periodicity is not a concern.
327  *
328  * The input hash is much less sensitive than the output hash.  All
329  * we want from it is to be a good non-cryptographic hash -
330  * i.e. to not produce collisions when fed "random" data of the sort
331  * we expect to see.  As long as the pool state differs for different
332  * inputs, we have preserved the input entropy and done a good job.
333  * The fact that an intelligent attacker can construct inputs that
334  * will produce controlled alterations to the pool's state is not
335  * important because we don't consider such inputs to contribute any
336  * randomness.  The only property we need with respect to them is that
337  * the attacker can't increase his/her knowledge of the pool's state.
338  * Since all additions are reversible (knowing the final state and the
339  * input, you can reconstruct the initial state), if an attacker has
340  * any uncertainty about the initial state, he/she can only shuffle
341  * that uncertainty about, but never cause any collisions (which would
342  * decrease the uncertainty).
343  *
344  * The chosen system lets the state of the pool be (essentially) the input
345  * modulo the generator polymnomial.  Now, for random primitive polynomials,
346  * this is a universal class of hash functions, meaning that the chance
347  * of a collision is limited by the attacker's knowledge of the generator
348  * polynomial, so if it is chosen at random, an attacker can never force
349  * a collision.  Here, we use a fixed polynomial, but we *can* assume that
350  * ###--> it is unknown to the processes generating the input entropy. <-###
351  * Because of this important property, this is a good, collision-resistant
352  * hash; hash collisions will occur no more often than chance.
353  */
354 
355 /* pIII/333 reported to have some drops w/ these numbers */
356 #define QEVLEN (1024 / sizeof(struct rand_event))
357 #define QEVSLOW (QEVLEN * 3 / 4) /* yet another 0.75 for 60-minutes hour /-; */
358 #define QEVSBITS 10
359 
360 /* There is actually only one of these, globally. */
361 struct random_bucket {
362 	u_int	add_ptr;
363 	u_int	entropy_count;
364 	u_char	input_rotate;
365 	u_int32_t pool[POOLWORDS];
366 	u_int	asleep;
367 	u_int	tmo;
368 };
369 
370 /* There is one of these per entropy source */
371 struct timer_rand_state {
372 	u_int	last_time;
373 	u_int	last_delta;
374 	u_int	last_delta2;
375 	u_int	dont_count_entropy : 1;
376 	u_int	max_entropy : 1;
377 };
378 
379 struct arc4_stream {
380 	u_int8_t s[256];
381 	u_int	cnt;
382 	u_int8_t i;
383 	u_int8_t j;
384 };
385 
386 struct rand_event {
387 	struct timer_rand_state *re_state;
388 	u_int re_nbits;
389 	u_int re_time;
390 	u_int re_val;
391 };
392 
393 struct timeout rnd_timeout, arc4_timeout;
394 struct random_bucket random_state;
395 struct arc4_stream arc4random_state;
396 struct timer_rand_state rnd_states[RND_SRC_NUM];
397 struct rand_event rnd_event_space[QEVLEN];
398 struct rand_event *rnd_event_head = rnd_event_space;
399 struct rand_event *rnd_event_tail = rnd_event_space;
400 struct selinfo rnd_rsel, rnd_wsel;
401 
402 void filt_rndrdetach(struct knote *kn);
403 int filt_rndread(struct knote *kn, long hint);
404 
405 struct filterops rndread_filtops =
406 	{ 1, NULL, filt_rndrdetach, filt_rndread};
407 
408 void filt_rndwdetach(struct knote *kn);
409 int filt_rndwrite(struct knote *kn, long hint);
410 
411 struct filterops rndwrite_filtops =
412 	{ 1, NULL, filt_rndwdetach, filt_rndwrite};
413 
414 int rnd_attached;
415 int arc4random_initialized;
416 struct rndstats rndstats;
417 
418 static __inline u_int32_t roll(u_int32_t w, int i)
419 {
420 #ifdef i386
421 	__asm ("roll %%cl, %0" : "+r" (w) : "c" (i));
422 #else
423 	w = (w << i) | (w >> (32 - i));
424 #endif
425 	return w;
426 }
427 
428 /* must be called at a proper spl, returns ptr to the next event */
429 static __inline struct rand_event *
430 rnd_get(void)
431 {
432 	struct rand_event *p = rnd_event_tail;
433 
434 	if (p == rnd_event_head)
435 		return NULL;
436 
437 	if (p + 1 >= &rnd_event_space[QEVLEN])
438 		rnd_event_tail = rnd_event_space;
439 	else
440 		rnd_event_tail++;
441 
442 	return p;
443 }
444 
445 /* must be called at a proper spl, returns next available item */
446 static __inline struct rand_event *
447 rnd_put(void)
448 {
449 	struct rand_event *p = rnd_event_head + 1;
450 
451 	if (p >= &rnd_event_space[QEVLEN])
452 		p = rnd_event_space;
453 
454 	if (p == rnd_event_tail)
455 		return NULL;
456 
457 	return rnd_event_head = p;
458 }
459 
460 /* must be called at a proper spl, returns number of items in the queue */
461 static __inline int
462 rnd_qlen(void)
463 {
464 	int len = rnd_event_head - rnd_event_tail;
465 	return (len < 0)? -len : len;
466 }
467 
468 void dequeue_randomness(void *);
469 
470 static __inline void add_entropy_words(const u_int32_t *, u_int n);
471 static __inline void extract_entropy(register u_int8_t *, int);
472 
473 static __inline u_int8_t arc4_getbyte(void);
474 static __inline void arc4_stir(void);
475 void arc4_reinit(void *v);
476 void arc4maybeinit(void);
477 
478 /* Arcfour random stream generator.  This code is derived from section
479  * 17.1 of Applied Cryptography, second edition, which describes a
480  * stream cipher allegedly compatible with RSA Labs "RC4" cipher (the
481  * actual description of which is a trade secret).  The same algorithm
482  * is used as a stream cipher called "arcfour" in Tatu Ylonen's ssh
483  * package.
484  *
485  * The initialization function here has been modified to not discard
486  * the old state, and it's input always includes the time of day in
487  * microseconds.  Moreover, bytes from the stream may at any point be
488  * diverted to multiple processes or even kernel functions desiring
489  * random numbers.  This increases the strength of the random stream,
490  * but makes it impossible to use this code for encryption, since there
491  * is no way to ever reproduce the same stream of random bytes.
492  *
493  * RC4 is a registered trademark of RSA Laboratories.
494  */
495 
496 static __inline u_int8_t
497 arc4_getbyte(void)
498 {
499 	register u_int8_t si, sj, ret;
500 	int s;
501 
502 	s = splhigh();
503 	rndstats.arc4_reads++;
504 	arc4random_state.cnt++;
505 	arc4random_state.i++;
506 	si = arc4random_state.s[arc4random_state.i];
507 	arc4random_state.j += si;
508 	sj = arc4random_state.s[arc4random_state.j];
509 	arc4random_state.s[arc4random_state.i] = sj;
510 	arc4random_state.s[arc4random_state.j] = si;
511 	ret = arc4random_state.s[(si + sj) & 0xff];
512 	splx(s);
513 	return (ret);
514 }
515 
516 static __inline void
517 arc4_stir(void)
518 {
519 	u_int8_t buf[256];
520 	register u_int8_t si;
521 	register int n, s;
522 	int len;
523 
524 	microtime((struct timeval *) buf);
525 	len = random_state.entropy_count / 8; /* XXX maybe a half? */
526 	if (len > sizeof(buf) - sizeof(struct timeval))
527 		len = sizeof(buf) - sizeof(struct timeval);
528 	get_random_bytes(buf + sizeof (struct timeval), len);
529 	len += sizeof(struct timeval);
530 
531 	s = splhigh();
532 	arc4random_state.i--;
533 	for (n = 0; n < 256; n++) {
534 		arc4random_state.i++;
535 		si = arc4random_state.s[arc4random_state.i];
536 		arc4random_state.j += si + buf[n % len];
537 		arc4random_state.s[arc4random_state.i] =
538 		    arc4random_state.s[arc4random_state.j];
539 		arc4random_state.s[arc4random_state.j] = si;
540 	}
541 	arc4random_state.j = arc4random_state.i;
542 	arc4random_state.cnt = 0;
543 	rndstats.arc4_stirs += len;
544 	rndstats.arc4_nstirs++;
545 	splx(s);
546 
547 	/*
548 	 * Throw away the first N words of output, as suggested in the
549 	 * paper "Weaknesses in the Key Scheduling Algorithm of RC4"
550 	 * by Fluher, Mantin, and Shamir.  (N = 256 in our case.)
551 	 */
552 	for (n = 0; n < 256 * 4; n++)
553 		arc4_getbyte();
554 }
555 
556 void
557 arc4maybeinit(void)
558 {
559 	extern int hz;
560 
561 	if (!arc4random_initialized) {
562 		arc4random_initialized++;
563 		arc4_stir();
564 		/* 10 minutes, per dm@'s suggestion */
565 		timeout_add(&arc4_timeout, 10 * 60 * hz);
566 	}
567 }
568 
569 /*
570  * called by timeout to mark arc4 for stirring,
571  * actual stirring happens on any access attempt.
572  */
573 void
574 arc4_reinit(v)
575 	void *v;
576 {
577 	arc4random_initialized = 0;
578 }
579 
580 static int arc4random_8(void);
581 
582 static int
583 arc4random_8(void)
584 {
585 	arc4maybeinit();
586 	return arc4_getbyte();
587 }
588 
589 u_int32_t
590 arc4random(void)
591 {
592 	arc4maybeinit();
593 	return ((arc4_getbyte() << 24) | (arc4_getbyte() << 16)
594 		| (arc4_getbyte() << 8) | arc4_getbyte());
595 }
596 
597 void
598 randomattach(void)
599 {
600 	int i;
601 
602 	if (rnd_attached) {
603 #ifdef RNDEBUG
604 		printf("random: second attach\n");
605 #endif
606 		return;
607 	}
608 
609 	timeout_set(&rnd_timeout, dequeue_randomness, &random_state);
610 	timeout_set(&arc4_timeout, arc4_reinit, NULL);
611 
612 	random_state.add_ptr = 0;
613 	random_state.entropy_count = 0;
614 	rnd_states[RND_SRC_TIMER].dont_count_entropy = 1;
615 	rnd_states[RND_SRC_TRUE].dont_count_entropy = 1;
616 	rnd_states[RND_SRC_TRUE].max_entropy = 1;
617 
618 	bzero(&rndstats, sizeof(rndstats));
619 	bzero(&rnd_event_space, sizeof(rnd_event_space));
620 
621 	for (i = 0; i < 256; i++)
622 		arc4random_state.s[i] = i;
623 	arc4_reinit(NULL);
624 
625 	rnd_attached = 1;
626 }
627 
628 int
629 randomopen(dev, flag, mode, p)
630 	dev_t	dev;
631 	int	flag;
632 	int	mode;
633 	struct proc *p;
634 {
635 	return (minor (dev) < RND_NODEV) ? 0 : ENXIO;
636 }
637 
638 int
639 randomclose(dev, flag, mode, p)
640 	dev_t	dev;
641 	int	flag;
642 	int	mode;
643 	struct proc *p;
644 {
645 	return 0;
646 }
647 
648 /*
649  * This function adds a byte into the entropy pool.  It does not
650  * update the entropy estimate.  The caller must do this if appropriate.
651  *
652  * The pool is stirred with a primitive polynomial of degree 128
653  * over GF(2), namely x^128 + x^99 + x^59 + x^31 + x^9 + x^7 + 1.
654  * For a pool of size 64, try x^64+x^62+x^38+x^10+x^6+x+1.
655  *
656  * We rotate the input word by a changing number of bits, to help
657  * assure that all bits in the entropy get toggled.  Otherwise, if we
658  * consistently feed the entropy pool small numbers (like jiffies and
659  * scancodes, for example), the upper bits of the entropy pool don't
660  * get affected. --- TYT, 10/11/95
661  */
662 static __inline void
663 add_entropy_words(buf, n)
664 	const u_int32_t *buf;
665 	u_int n;
666 {
667 	static const u_int32_t twist_table[8] = {
668 		0x00000000, 0x3b6e20c8, 0x76dc4190, 0x4db26158,
669 		0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278
670 	};
671 
672 	for (; n--; buf++) {
673 		register u_int32_t w = roll(*buf, random_state.input_rotate);
674 		register u_int i = random_state.add_ptr =
675 		    (random_state.add_ptr - 1) & (POOLWORDS - 1);
676 		/*
677 		 * Normally, we add 7 bits of rotation to the pool.
678 		 * At the beginning of the pool, add an extra 7 bits
679 		 * rotation, so that successive passes spread the
680 		 * input bits across the pool evenly.
681 		 */
682 		random_state.input_rotate =
683 		    (random_state.input_rotate + (i? 7 : 14)) & 31;
684 
685 		/* XOR in the various taps */
686 		w ^= random_state.pool[(i+TAP1) & (POOLWORDS-1)] ^
687 		     random_state.pool[(i+TAP2) & (POOLWORDS-1)] ^
688 		     random_state.pool[(i+TAP3) & (POOLWORDS-1)] ^
689 		     random_state.pool[(i+TAP4) & (POOLWORDS-1)] ^
690 		     random_state.pool[(i+TAP5) & (POOLWORDS-1)] ^
691 		     random_state.pool[i];
692 		random_state.pool[i] = (w >> 3) ^ twist_table[w & 7];
693 	}
694 }
695 
696 /*
697  * This function adds entropy to the entropy pool by using timing
698  * delays.  It uses the timer_rand_state structure to make an estimate
699  * of how many bits of entropy this call has added to the pool.
700  *
701  * The number "num" is also added to the pool - it should somehow describe
702  * the type of event which just happened.  Currently the values of 0-255
703  * are for keyboard scan codes, 256 and upwards - for interrupts.
704  * On the i386, this is assumed to be at most 16 bits, and the high bits
705  * are used for a high-resolution timer.
706  *
707  */
708 void
709 enqueue_randomness(state, val)
710 	int	state, val;
711 {
712 	register struct timer_rand_state *p;
713 	register struct rand_event *rep;
714 	struct timeval	tv;
715 	u_int	time, nbits;
716 	int s;
717 
718 	/* XXX on sparc we get here before randomattach() */
719 	if (!rnd_attached)
720 		return;
721 
722 #ifdef DIAGNOSTIC
723 	if (state < 0 || state >= RND_SRC_NUM)
724 		return;
725 #endif
726 
727 	p = &rnd_states[state];
728 	val += state << 13;
729 
730 	microtime(&tv);
731 	time = tv.tv_usec ^ tv.tv_sec;
732 	nbits = 0;
733 
734 	/*
735 	 * Calculate the number of bits of randomness that we probably
736 	 * added.  We take into account the first and second order
737 	 * deltas in order to make our estimate.
738 	 */
739 	if (!p->dont_count_entropy) {
740 		register int	delta, delta2, delta3;
741 		delta  = time   - p->last_time;
742 		delta2 = delta  - p->last_delta;
743 		delta3 = delta2 - p->last_delta2;
744 
745 		if (delta < 0) delta = -delta;
746 		if (delta2 < 0) delta2 = -delta2;
747 		if (delta3 < 0) delta3 = -delta3;
748 		if (delta > delta2) delta = delta2;
749 		if (delta > delta3) delta = delta3;
750 		delta3 = delta >>= 1;
751 		/*
752 		 * delta &= 0xfff;
753 		 * we don't do it since our time sheet is different from linux
754 		 */
755 
756 		if (delta & 0xffff0000) {
757 			nbits = 16;
758 			delta >>= 16;
759 		}
760 		if (delta & 0xff00) {
761 			nbits += 8;
762 			delta >>= 8;
763 		}
764 		if (delta & 0xf0) {
765 			nbits += 4;
766 			delta >>= 4;
767 		}
768 		if (delta & 0xc) {
769 			nbits += 2;
770 			delta >>= 2;
771 		}
772 		if (delta & 2) {
773 			nbits += 1;
774 			delta >>= 1;
775 		}
776 		if (delta & 1)
777 			nbits++;
778 
779 		/*
780 		 * the logic is to drop low-entropy entries,
781 		 * in hope for dequeuing to be more randomfull
782 		 */
783 		if (rnd_qlen() > QEVSLOW && nbits < QEVSBITS) {
784 			rndstats.rnd_drople++;
785 			return;
786 		}
787 		p->last_time = time;
788 		p->last_delta  = delta3;
789 		p->last_delta2 = delta2;
790 	} else if (p->max_entropy)
791 		nbits = 8 * sizeof(val) - 1;
792 
793 	s = splhigh();
794 	if ((rep = rnd_put()) == NULL) {
795 		rndstats.rnd_drops++;
796 		splx(s);
797 		return;
798 	}
799 
800 	rep->re_state = p;
801 	rep->re_nbits = nbits;
802 	rep->re_time = time;
803 	rep->re_val = val;
804 
805 	rndstats.rnd_enqs++;
806 	rndstats.rnd_ed[nbits]++;
807 	rndstats.rnd_sc[state]++;
808 	rndstats.rnd_sb[state] += nbits;
809 
810 	if (rnd_qlen() > QEVSLOW/2 && !random_state.tmo) {
811 		random_state.tmo++;
812 		timeout_add(&rnd_timeout, 1);
813 	}
814 	splx(s);
815 }
816 
817 void
818 dequeue_randomness(v)
819 	void *v;
820 {
821 	struct random_bucket *rs = v;
822 	register struct rand_event *rep;
823 	u_int32_t buf[2];
824 	u_int nbits;
825 	int s;
826 
827 	timeout_del(&rnd_timeout);
828 	rndstats.rnd_deqs++;
829 
830 	s = splhigh();
831 	while ((rep = rnd_get())) {
832 
833 		buf[0] = rep->re_time;
834 		buf[1] = rep->re_val;
835 		nbits = rep->re_nbits;
836 		splx(s);
837 
838 		add_entropy_words(buf, 2);
839 
840 		rndstats.rnd_total += nbits;
841 		rs->entropy_count += nbits;
842 		if (rs->entropy_count > POOLBITS)
843 			rs->entropy_count = POOLBITS;
844 
845 		if (rs->asleep && rs->entropy_count > 8) {
846 #ifdef	RNDEBUG
847 			if (rnd_debug & RD_WAIT)
848 				printf("rnd: wakeup[%u]{%u}\n",
849 				    rs->asleep,
850 				    rs->entropy_count);
851 #endif
852 			rs->asleep--;
853 			wakeup((void *)&rs->asleep);
854 			selwakeup(&rnd_rsel);
855 			KNOTE(&rnd_rsel.si_note, 0);
856 		}
857 
858 		s = splhigh();
859 	}
860 
861 	rs->tmo = 0;
862 	splx(s);
863 }
864 
865 #if POOLWORDS % 16
866 #error extract_entropy() assumes that POOLWORDS is a multiple of 16 words.
867 #endif
868 
869 /*
870  * This function extracts randomness from the entropy pool, and
871  * returns it in a buffer.  This function computes how many remaining
872  * bits of entropy are left in the pool, but it does not restrict the
873  * number of bytes that are actually obtained.
874  */
875 static __inline void
876 extract_entropy(buf, nbytes)
877 	register u_int8_t *buf;
878 	int	nbytes;
879 {
880 	struct random_bucket *rs = &random_state;
881 	u_char buffer[16];
882 
883 	add_timer_randomness(nbytes);
884 
885 	while (nbytes) {
886 		MD5_CTX tmp;
887 		int i, s;
888 
889 		/* Hash the pool to get the output */
890 		MD5Init(&tmp);
891 		s = splhigh();
892 		MD5Update(&tmp, (u_int8_t*)rs->pool, sizeof(rs->pool));
893 		if (rs->entropy_count / 8 > nbytes)
894 			rs->entropy_count -= nbytes * 8;
895 		else
896 			rs->entropy_count = 0;
897 		splx(s);
898 		MD5Final(buffer, &tmp);
899 		bzero(&tmp, sizeof(tmp));
900 
901 		/*
902 		 * In case the hash function has some recognizable
903 		 * output pattern, we fold it in half.
904 		 */
905 		buffer[0] ^= buffer[15];
906 		buffer[1] ^= buffer[14];
907 		buffer[2] ^= buffer[13];
908 		buffer[3] ^= buffer[12];
909 		buffer[4] ^= buffer[11];
910 		buffer[5] ^= buffer[10];
911 		buffer[6] ^= buffer[ 9];
912 		buffer[7] ^= buffer[ 8];
913 
914 		/* Copy data to destination buffer */
915 		if (nbytes < sizeof(buffer) / 2)
916 			bcopy(buffer, buf, i = nbytes);
917 		else
918 			bcopy(buffer, buf, i = sizeof(buffer) / 2);
919 		nbytes -= i;
920 		buf += i;
921 
922 		/* Modify pool so next hash will produce different results */
923 		add_timer_randomness(nbytes);
924 		dequeue_randomness(&random_state);
925 	}
926 
927 	/* Wipe data from memory */
928 	bzero(&buffer, sizeof(buffer));
929 }
930 
931 /*
932  * This function is the exported kernel interface.  It returns some
933  * number of good random numbers, suitable for seeding TCP sequence
934  * numbers, etc.
935  */
936 void
937 get_random_bytes(buf, nbytes)
938 	void	*buf;
939 	size_t	nbytes;
940 {
941 	extract_entropy((u_int8_t *) buf, nbytes);
942 	rndstats.rnd_used += nbytes * 8;
943 }
944 
945 int
946 randomread(dev, uio, ioflag)
947 	dev_t	dev;
948 	struct uio *uio;
949 	int	ioflag;
950 {
951 	int	ret = 0;
952 	int	i;
953 
954 	if (uio->uio_resid == 0)
955 		return 0;
956 
957 	while (!ret && uio->uio_resid > 0) {
958 		u_int32_t buf[ POOLWORDS ];
959 		int	n = min(sizeof(buf), uio->uio_resid);
960 
961 		switch(minor(dev)) {
962 		case RND_RND:
963 			ret = EIO;	/* no chip -- error */
964 			break;
965 		case RND_SRND:
966 			if (random_state.entropy_count < 16 * 8) {
967 				if (ioflag & IO_NDELAY) {
968 					ret = EWOULDBLOCK;
969 					break;
970 				}
971 #ifdef	RNDEBUG
972 				if (rnd_debug & RD_WAIT)
973 					printf("rnd: sleep[%u]\n",
974 					    random_state.asleep);
975 #endif
976 				random_state.asleep++;
977 				rndstats.rnd_waits++;
978 				ret = tsleep(&random_state.asleep,
979 				    PWAIT | PCATCH, "rndrd", 0);
980 #ifdef	RNDEBUG
981 				if (rnd_debug & RD_WAIT)
982 					printf("rnd: awakened(%d)\n", ret);
983 #endif
984 				if (ret)
985 					break;
986 			}
987 			if (n > random_state.entropy_count / 8)
988 				n = random_state.entropy_count / 8;
989 			rndstats.rnd_reads++;
990 #ifdef	RNDEBUG
991 			if (rnd_debug & RD_OUTPUT)
992 				printf("rnd: %u possible output\n", n);
993 #endif
994 		case RND_URND:
995 			get_random_bytes((char *)buf, n);
996 #ifdef	RNDEBUG
997 			if (rnd_debug & RD_OUTPUT)
998 				printf("rnd: %u bytes for output\n", n);
999 #endif
1000 			break;
1001 		case RND_PRND:
1002 			i = (n + 3) / 4;
1003 			while (i--)
1004 				buf[i] = random() << 16 | (random() & 0xFFFF);
1005 			break;
1006 		case RND_ARND:
1007 		{
1008 			u_int8_t *cp = (u_int8_t *) buf;
1009 			u_int8_t *end = cp + n;
1010 			while (cp < end)
1011 				*cp++ = arc4random_8();
1012 			break;
1013 		}
1014 		default:
1015 			ret = ENXIO;
1016 		}
1017 		if (n != 0 && ret == 0)
1018 			ret = uiomove((caddr_t)buf, n, uio);
1019 	}
1020 	return ret;
1021 }
1022 
1023 int
1024 randomselect(dev, rw, p)
1025 	dev_t	dev;
1026 	int	rw;
1027 	struct proc *p;
1028 {
1029 	switch (rw) {
1030 	case FREAD:
1031 		if (random_state.entropy_count > 0)
1032 			return (1);
1033 		else
1034 			selrecord(p, &rnd_rsel);
1035 		break;
1036 	case FWRITE:
1037 		return 1;
1038 	}
1039 	return 0;
1040 }
1041 
1042 int
1043 randomkqfilter(dev_t dev, struct knote *kn)
1044 {
1045 	struct klist *klist;
1046 	int s;
1047 
1048 	switch (kn->kn_filter) {
1049 	case EVFILT_READ:
1050 		klist = &rnd_rsel.si_note;
1051 		kn->kn_fop = &rndread_filtops;
1052 		break;
1053 	case EVFILT_WRITE:
1054 		klist = &rnd_wsel.si_note;
1055 		kn->kn_fop = &rndwrite_filtops;
1056 		break;
1057 	default:
1058 		return (1);
1059 	}
1060 	kn->kn_hook = (void *)&random_state;
1061 
1062 	s = splhigh();
1063 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
1064 	splx(s);
1065 
1066 	return (0);
1067 }
1068 
1069 void
1070 filt_rndrdetach(struct knote *kn)
1071 {
1072 	int s = splhigh();
1073 
1074 	SLIST_REMOVE(&rnd_rsel.si_note, kn, knote, kn_selnext);
1075 	splx(s);
1076 }
1077 
1078 int
1079 filt_rndread(kn, hint)
1080 	struct knote *kn;
1081 	long hint;
1082 {
1083 	struct random_bucket *rs = (struct random_bucket *)kn->kn_hook;
1084 
1085 	kn->kn_data = (int)rs->entropy_count;
1086 	return rs->entropy_count > 0;
1087 }
1088 
1089 void
1090 filt_rndwdetach(struct knote *kn)
1091 {
1092 	int s = splhigh();
1093 
1094 	SLIST_REMOVE(&rnd_wsel.si_note, kn, knote, kn_selnext);
1095 	splx(s);
1096 }
1097 
1098 int
1099 filt_rndwrite(kn, hint)
1100 	struct knote *kn;
1101 	long hint;
1102 {
1103 	return (1);
1104 }
1105 
1106 int
1107 randomwrite(dev, uio, flags)
1108 	dev_t	dev;
1109 	struct uio *uio;
1110 	int	flags;
1111 {
1112 	int	ret = 0;
1113 
1114 	if (minor(dev) == RND_RND || minor(dev) == RND_PRND)
1115 		return ENXIO;
1116 
1117 	if (uio->uio_resid == 0)
1118 		return 0;
1119 
1120 	while (!ret && uio->uio_resid > 0) {
1121 		u_int32_t	buf[ POOLWORDS ];
1122 		u_short		n = min(sizeof(buf),uio->uio_resid);
1123 
1124 		ret = uiomove((caddr_t)buf, n, uio);
1125 		if (!ret) {
1126 			while (n % sizeof(u_int32_t))
1127 				((u_int8_t *) buf)[n++] = 0;
1128 			add_entropy_words(buf, n / 4);
1129 		}
1130 	}
1131 
1132 	if (minor(dev) == RND_ARND && !ret)
1133 		arc4random_initialized = 0;
1134 
1135 	return ret;
1136 }
1137 
1138 int
1139 randomioctl(dev, cmd, data, flag, p)
1140 	dev_t	dev;
1141 	u_long	cmd;
1142 	caddr_t	data;
1143 	int	flag;
1144 	struct proc *p;
1145 {
1146 	int	s, ret = 0;
1147 	u_int	cnt;
1148 
1149 	add_timer_randomness((u_long)p ^ (u_long)data ^ cmd);
1150 
1151 	switch (cmd) {
1152 	case FIOASYNC:
1153 		/* rnd has no async flag in softc so this is really a no-op. */
1154 		break;
1155 
1156 	case FIONBIO:
1157 		/* Handled in the upper FS layer. */
1158 		break;
1159 
1160 	case RNDGETENTCNT:
1161 		s = splhigh();
1162 		*(u_int *)data = random_state.entropy_count;
1163 		splx(s);
1164 		break;
1165 	case RNDADDTOENTCNT:
1166 		if (suser(p->p_ucred, &p->p_acflag) != 0)
1167 			ret = EPERM;
1168 		else {
1169 			cnt = *(u_int *)data;
1170 			s = splhigh();
1171 			random_state.entropy_count += cnt;
1172 			if (random_state.entropy_count > POOLBITS)
1173 				random_state.entropy_count = POOLBITS;
1174 			splx(s);
1175 		}
1176 		break;
1177 	case RNDZAPENTCNT:
1178 		if (suser(p->p_ucred, &p->p_acflag) != 0)
1179 			ret = EPERM;
1180 		else {
1181 			s = splhigh();
1182 			random_state.entropy_count = 0;
1183 			splx(s);
1184 		}
1185 		break;
1186 	case RNDSTIRARC4:
1187 		if (suser(p->p_ucred, &p->p_acflag) != 0)
1188 			ret = EPERM;
1189 		else if (random_state.entropy_count < 64)
1190 			ret = EAGAIN;
1191 		else {
1192 			s = splhigh();
1193 			arc4random_initialized = 0;
1194 			splx(s);
1195 		}
1196 		break;
1197 	case RNDCLRSTATS:
1198 		if (suser(p->p_ucred, &p->p_acflag) != 0)
1199 			ret = EPERM;
1200 		else {
1201 			s = splhigh();
1202 			bzero(&rndstats, sizeof(rndstats));
1203 			splx(s);
1204 		}
1205 		break;
1206 	default:
1207 		ret = ENOTTY;
1208 	}
1209 
1210 	add_timer_randomness((u_long)p ^ (u_long)data ^ cmd);
1211 	return ret;
1212 }
1213