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