Coarsly sort out 32-bit-only, 64-bit-only and ``portable'' MIPS lib/
[linux-2.6/linux-mips.git] / drivers / char / random.c
blob2278abad5f94c5a6bd36275c06e73c8410ac1dda
1 /*
2 * random.c -- A strong random number generator
4 * Version 1.89, last modified 19-Sep-99
5 *
6 * Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999. All
7 * rights reserved.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, and the entire permission notice in its entirety,
14 * including the disclaimer of warranties.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. The name of the author may not be used to endorse or promote
19 * products derived from this software without specific prior
20 * written permission.
22 * ALTERNATIVELY, this product may be distributed under the terms of
23 * the GNU General Public License, in which case the provisions of the GPL are
24 * required INSTEAD OF the above restrictions. (This clause is
25 * necessary due to a potential bad interaction between the GPL and
26 * the restrictions contained in a BSD-style copyright.)
28 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
29 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
31 * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
32 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
34 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
35 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
36 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
38 * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
39 * DAMAGE.
43 * (now, with legal B.S. out of the way.....)
45 * This routine gathers environmental noise from device drivers, etc.,
46 * and returns good random numbers, suitable for cryptographic use.
47 * Besides the obvious cryptographic uses, these numbers are also good
48 * for seeding TCP sequence numbers, and other places where it is
49 * desirable to have numbers which are not only random, but hard to
50 * predict by an attacker.
52 * Theory of operation
53 * ===================
55 * Computers are very predictable devices. Hence it is extremely hard
56 * to produce truly random numbers on a computer --- as opposed to
57 * pseudo-random numbers, which can easily generated by using a
58 * algorithm. Unfortunately, it is very easy for attackers to guess
59 * the sequence of pseudo-random number generators, and for some
60 * applications this is not acceptable. So instead, we must try to
61 * gather "environmental noise" from the computer's environment, which
62 * must be hard for outside attackers to observe, and use that to
63 * generate random numbers. In a Unix environment, this is best done
64 * from inside the kernel.
66 * Sources of randomness from the environment include inter-keyboard
67 * timings, inter-interrupt timings from some interrupts, and other
68 * events which are both (a) non-deterministic and (b) hard for an
69 * outside observer to measure. Randomness from these sources are
70 * added to an "entropy pool", which is mixed using a CRC-like function.
71 * This is not cryptographically strong, but it is adequate assuming
72 * the randomness is not chosen maliciously, and it is fast enough that
73 * the overhead of doing it on every interrupt is very reasonable.
74 * As random bytes are mixed into the entropy pool, the routines keep
75 * an *estimate* of how many bits of randomness have been stored into
76 * the random number generator's internal state.
78 * When random bytes are desired, they are obtained by taking the SHA
79 * hash of the contents of the "entropy pool". The SHA hash avoids
80 * exposing the internal state of the entropy pool. It is believed to
81 * be computationally infeasible to derive any useful information
82 * about the input of SHA from its output. Even if it is possible to
83 * analyze SHA in some clever way, as long as the amount of data
84 * returned from the generator is less than the inherent entropy in
85 * the pool, the output data is totally unpredictable. For this
86 * reason, the routine decreases its internal estimate of how many
87 * bits of "true randomness" are contained in the entropy pool as it
88 * outputs random numbers.
90 * If this estimate goes to zero, the routine can still generate
91 * random numbers; however, an attacker may (at least in theory) be
92 * able to infer the future output of the generator from prior
93 * outputs. This requires successful cryptanalysis of SHA, which is
94 * not believed to be feasible, but there is a remote possibility.
95 * Nonetheless, these numbers should be useful for the vast majority
96 * of purposes.
98 * Exported interfaces ---- output
99 * ===============================
101 * There are three exported interfaces; the first is one designed to
102 * be used from within the kernel:
104 * void get_random_bytes(void *buf, int nbytes);
106 * This interface will return the requested number of random bytes,
107 * and place it in the requested buffer.
109 * The two other interfaces are two character devices /dev/random and
110 * /dev/urandom. /dev/random is suitable for use when very high
111 * quality randomness is desired (for example, for key generation or
112 * one-time pads), as it will only return a maximum of the number of
113 * bits of randomness (as estimated by the random number generator)
114 * contained in the entropy pool.
116 * The /dev/urandom device does not have this limit, and will return
117 * as many bytes as are requested. As more and more random bytes are
118 * requested without giving time for the entropy pool to recharge,
119 * this will result in random numbers that are merely cryptographically
120 * strong. For many applications, however, this is acceptable.
122 * Exported interfaces ---- input
123 * ==============================
125 * The current exported interfaces for gathering environmental noise
126 * from the devices are:
128 * void add_keyboard_randomness(unsigned char scancode);
129 * void add_mouse_randomness(__u32 mouse_data);
130 * void add_interrupt_randomness(int irq);
132 * add_keyboard_randomness() uses the inter-keypress timing, as well as the
133 * scancode as random inputs into the "entropy pool".
135 * add_mouse_randomness() uses the mouse interrupt timing, as well as
136 * the reported position of the mouse from the hardware.
138 * add_interrupt_randomness() uses the inter-interrupt timing as random
139 * inputs to the entropy pool. Note that not all interrupts are good
140 * sources of randomness! For example, the timer interrupts is not a
141 * good choice, because the periodicity of the interrupts is too
142 * regular, and hence predictable to an attacker. Disk interrupts are
143 * a better measure, since the timing of the disk interrupts are more
144 * unpredictable.
146 * All of these routines try to estimate how many bits of randomness a
147 * particular randomness source. They do this by keeping track of the
148 * first and second order deltas of the event timings.
150 * Ensuring unpredictability at system startup
151 * ============================================
153 * When any operating system starts up, it will go through a sequence
154 * of actions that are fairly predictable by an adversary, especially
155 * if the start-up does not involve interaction with a human operator.
156 * This reduces the actual number of bits of unpredictability in the
157 * entropy pool below the value in entropy_count. In order to
158 * counteract this effect, it helps to carry information in the
159 * entropy pool across shut-downs and start-ups. To do this, put the
160 * following lines an appropriate script which is run during the boot
161 * sequence:
163 * echo "Initializing random number generator..."
164 * random_seed=/var/run/random-seed
165 * # Carry a random seed from start-up to start-up
166 * # Load and then save the whole entropy pool
167 * if [ -f $random_seed ]; then
168 * cat $random_seed >/dev/urandom
169 * else
170 * touch $random_seed
171 * fi
172 * chmod 600 $random_seed
173 * poolfile=/proc/sys/kernel/random/poolsize
174 * [ -r $poolfile ] && bytes=`cat $poolfile` || bytes=512
175 * dd if=/dev/urandom of=$random_seed count=1 bs=$bytes
177 * and the following lines in an appropriate script which is run as
178 * the system is shutdown:
180 * # Carry a random seed from shut-down to start-up
181 * # Save the whole entropy pool
182 * echo "Saving random seed..."
183 * random_seed=/var/run/random-seed
184 * touch $random_seed
185 * chmod 600 $random_seed
186 * poolfile=/proc/sys/kernel/random/poolsize
187 * [ -r $poolfile ] && bytes=`cat $poolfile` || bytes=512
188 * dd if=/dev/urandom of=$random_seed count=1 bs=$bytes
190 * For example, on most modern systems using the System V init
191 * scripts, such code fragments would be found in
192 * /etc/rc.d/init.d/random. On older Linux systems, the correct script
193 * location might be in /etc/rcb.d/rc.local or /etc/rc.d/rc.0.
195 * Effectively, these commands cause the contents of the entropy pool
196 * to be saved at shut-down time and reloaded into the entropy pool at
197 * start-up. (The 'dd' in the addition to the bootup script is to
198 * make sure that /etc/random-seed is different for every start-up,
199 * even if the system crashes without executing rc.0.) Even with
200 * complete knowledge of the start-up activities, predicting the state
201 * of the entropy pool requires knowledge of the previous history of
202 * the system.
204 * Configuring the /dev/random driver under Linux
205 * ==============================================
207 * The /dev/random driver under Linux uses minor numbers 8 and 9 of
208 * the /dev/mem major number (#1). So if your system does not have
209 * /dev/random and /dev/urandom created already, they can be created
210 * by using the commands:
212 * mknod /dev/random c 1 8
213 * mknod /dev/urandom c 1 9
215 * Acknowledgements:
216 * =================
218 * Ideas for constructing this random number generator were derived
219 * from Pretty Good Privacy's random number generator, and from private
220 * discussions with Phil Karn. Colin Plumb provided a faster random
221 * number generator, which speed up the mixing function of the entropy
222 * pool, taken from PGPfone. Dale Worley has also contributed many
223 * useful ideas and suggestions to improve this driver.
225 * Any flaws in the design are solely my responsibility, and should
226 * not be attributed to the Phil, Colin, or any of authors of PGP.
228 * The code for SHA transform was taken from Peter Gutmann's
229 * implementation, which has been placed in the public domain.
230 * The code for MD5 transform was taken from Colin Plumb's
231 * implementation, which has been placed in the public domain.
232 * The MD5 cryptographic checksum was devised by Ronald Rivest, and is
233 * documented in RFC 1321, "The MD5 Message Digest Algorithm".
235 * Further background information on this topic may be obtained from
236 * RFC 1750, "Randomness Recommendations for Security", by Donald
237 * Eastlake, Steve Crocker, and Jeff Schiller.
240 #include <linux/utsname.h>
241 #include <linux/config.h>
242 #include <linux/module.h>
243 #include <linux/kernel.h>
244 #include <linux/major.h>
245 #include <linux/string.h>
246 #include <linux/fcntl.h>
247 #include <linux/slab.h>
248 #include <linux/random.h>
249 #include <linux/poll.h>
250 #include <linux/init.h>
251 #include <linux/fs.h>
252 #include <linux/workqueue.h>
253 #include <linux/genhd.h>
255 #include <asm/processor.h>
256 #include <asm/uaccess.h>
257 #include <asm/irq.h>
258 #include <asm/io.h>
261 * Configuration information
263 #define DEFAULT_POOL_SIZE 512
264 #define SECONDARY_POOL_SIZE 128
265 #define BATCH_ENTROPY_SIZE 256
266 #define USE_SHA
269 * The minimum number of bits of entropy before we wake up a read on
270 * /dev/random. Should always be at least 8, or at least 1 byte.
272 static int random_read_wakeup_thresh = 8;
275 * If the entropy count falls under this number of bits, then we
276 * should wake up processes which are selecting or polling on write
277 * access to /dev/random.
279 static int random_write_wakeup_thresh = 128;
282 * A pool of size .poolwords is stirred with a primitive polynomial
283 * of degree .poolwords over GF(2). The taps for various sizes are
284 * defined below. They are chosen to be evenly spaced (minimum RMS
285 * distance from evenly spaced; the numbers in the comments are a
286 * scaled squared error sum) except for the last tap, which is 1 to
287 * get the twisting happening as fast as possible.
289 static struct poolinfo {
290 int poolwords;
291 int tap1, tap2, tap3, tap4, tap5;
292 } poolinfo_table[] = {
293 /* x^2048 + x^1638 + x^1231 + x^819 + x^411 + x + 1 -- 115 */
294 { 2048, 1638, 1231, 819, 411, 1 },
296 /* x^1024 + x^817 + x^615 + x^412 + x^204 + x + 1 -- 290 */
297 { 1024, 817, 615, 412, 204, 1 },
298 #if 0 /* Alternate polynomial */
299 /* x^1024 + x^819 + x^616 + x^410 + x^207 + x^2 + 1 -- 115 */
300 { 1024, 819, 616, 410, 207, 2 },
301 #endif
303 /* x^512 + x^411 + x^308 + x^208 + x^104 + x + 1 -- 225 */
304 { 512, 411, 308, 208, 104, 1 },
305 #if 0 /* Alternates */
306 /* x^512 + x^409 + x^307 + x^206 + x^102 + x^2 + 1 -- 95 */
307 { 512, 409, 307, 206, 102, 2 },
308 /* x^512 + x^409 + x^309 + x^205 + x^103 + x^2 + 1 -- 95 */
309 { 512, 409, 309, 205, 103, 2 },
310 #endif
312 /* x^256 + x^205 + x^155 + x^101 + x^52 + x + 1 -- 125 */
313 { 256, 205, 155, 101, 52, 1 },
315 /* x^128 + x^103 + x^76 + x^51 +x^25 + x + 1 -- 105 */
316 { 128, 103, 76, 51, 25, 1 },
317 #if 0 /* Alternate polynomial */
318 /* x^128 + x^103 + x^78 + x^51 + x^27 + x^2 + 1 -- 70 */
319 { 128, 103, 78, 51, 27, 2 },
320 #endif
322 /* x^64 + x^52 + x^39 + x^26 + x^14 + x + 1 -- 15 */
323 { 64, 52, 39, 26, 14, 1 },
325 /* x^32 + x^26 + x^20 + x^14 + x^7 + x + 1 -- 15 */
326 { 32, 26, 20, 14, 7, 1 },
328 { 0, 0, 0, 0, 0, 0 },
331 #define POOLBITS poolwords*32
332 #define POOLBYTES poolwords*4
335 * For the purposes of better mixing, we use the CRC-32 polynomial as
336 * well to make a twisted Generalized Feedback Shift Reigster
338 * (See M. Matsumoto & Y. Kurita, 1992. Twisted GFSR generators. ACM
339 * Transactions on Modeling and Computer Simulation 2(3):179-194.
340 * Also see M. Matsumoto & Y. Kurita, 1994. Twisted GFSR generators
341 * II. ACM Transactions on Mdeling and Computer Simulation 4:254-266)
343 * Thanks to Colin Plumb for suggesting this.
345 * We have not analyzed the resultant polynomial to prove it primitive;
346 * in fact it almost certainly isn't. Nonetheless, the irreducible factors
347 * of a random large-degree polynomial over GF(2) are more than large enough
348 * that periodicity is not a concern.
350 * The input hash is much less sensitive than the output hash. All
351 * that we want of it is that it be a good non-cryptographic hash;
352 * i.e. it not produce collisions when fed "random" data of the sort
353 * we expect to see. As long as the pool state differs for different
354 * inputs, we have preserved the input entropy and done a good job.
355 * The fact that an intelligent attacker can construct inputs that
356 * will produce controlled alterations to the pool's state is not
357 * important because we don't consider such inputs to contribute any
358 * randomness. The only property we need with respect to them is that
359 * the attacker can't increase his/her knowledge of the pool's state.
360 * Since all additions are reversible (knowing the final state and the
361 * input, you can reconstruct the initial state), if an attacker has
362 * any uncertainty about the initial state, he/she can only shuffle
363 * that uncertainty about, but never cause any collisions (which would
364 * decrease the uncertainty).
366 * The chosen system lets the state of the pool be (essentially) the input
367 * modulo the generator polymnomial. Now, for random primitive polynomials,
368 * this is a universal class of hash functions, meaning that the chance
369 * of a collision is limited by the attacker's knowledge of the generator
370 * polynomail, so if it is chosen at random, an attacker can never force
371 * a collision. Here, we use a fixed polynomial, but we *can* assume that
372 * ###--> it is unknown to the processes generating the input entropy. <-###
373 * Because of this important property, this is a good, collision-resistant
374 * hash; hash collisions will occur no more often than chance.
378 * Linux 2.2 compatibility
380 #ifndef DECLARE_WAITQUEUE
381 #define DECLARE_WAITQUEUE(WAIT, PTR) struct wait_queue WAIT = { PTR, NULL }
382 #endif
383 #ifndef DECLARE_WAIT_QUEUE_HEAD
384 #define DECLARE_WAIT_QUEUE_HEAD(WAIT) struct wait_queue *WAIT
385 #endif
388 * Static global variables
390 static struct entropy_store *random_state; /* The default global store */
391 static struct entropy_store *sec_random_state; /* secondary store */
392 static DECLARE_WAIT_QUEUE_HEAD(random_read_wait);
393 static DECLARE_WAIT_QUEUE_HEAD(random_write_wait);
396 * Forward procedure declarations
398 #ifdef CONFIG_SYSCTL
399 static void sysctl_init_random(struct entropy_store *random_state);
400 #endif
402 /*****************************************************************
404 * Utility functions, with some ASM defined functions for speed
405 * purposes
407 *****************************************************************/
410 * Unfortunately, while the GCC optimizer for the i386 understands how
411 * to optimize a static rotate left of x bits, it doesn't know how to
412 * deal with a variable rotate of x bits. So we use a bit of asm magic.
414 #if (!defined (__i386__))
415 static inline __u32 rotate_left(int i, __u32 word)
417 return (word << i) | (word >> (32 - i));
420 #else
421 static inline __u32 rotate_left(int i, __u32 word)
423 __asm__("roll %%cl,%0"
424 :"=r" (word)
425 :"0" (word),"c" (i));
426 return word;
428 #endif
431 * More asm magic....
433 * For entropy estimation, we need to do an integral base 2
434 * logarithm.
436 * Note the "12bits" suffix - this is used for numbers between
437 * 0 and 4095 only. This allows a few shortcuts.
439 #if 0 /* Slow but clear version */
440 static inline __u32 int_ln_12bits(__u32 word)
442 __u32 nbits = 0;
444 while (word >>= 1)
445 nbits++;
446 return nbits;
448 #else /* Faster (more clever) version, courtesy Colin Plumb */
449 static inline __u32 int_ln_12bits(__u32 word)
451 /* Smear msbit right to make an n-bit mask */
452 word |= word >> 8;
453 word |= word >> 4;
454 word |= word >> 2;
455 word |= word >> 1;
456 /* Remove one bit to make this a logarithm */
457 word >>= 1;
458 /* Count the bits set in the word */
459 word -= (word >> 1) & 0x555;
460 word = (word & 0x333) + ((word >> 2) & 0x333);
461 word += (word >> 4);
462 word += (word >> 8);
463 return word & 15;
465 #endif
467 #if 0
468 #define DEBUG_ENT(fmt, arg...) printk(KERN_DEBUG "random: " fmt, ## arg)
469 #else
470 #define DEBUG_ENT(fmt, arg...) do {} while (0)
471 #endif
473 /**********************************************************************
475 * OS independent entropy store. Here are the functions which handle
476 * storing entropy in an entropy pool.
478 **********************************************************************/
480 struct entropy_store {
481 unsigned add_ptr;
482 int entropy_count;
483 int input_rotate;
484 int extract_count;
485 struct poolinfo poolinfo;
486 __u32 *pool;
490 * Initialize the entropy store. The input argument is the size of
491 * the random pool.
493 * Returns an negative error if there is a problem.
495 static int create_entropy_store(int size, struct entropy_store **ret_bucket)
497 struct entropy_store *r;
498 struct poolinfo *p;
499 int poolwords;
501 poolwords = (size + 3) / 4; /* Convert bytes->words */
502 /* The pool size must be a multiple of 16 32-bit words */
503 poolwords = ((poolwords + 15) / 16) * 16;
505 for (p = poolinfo_table; p->poolwords; p++) {
506 if (poolwords == p->poolwords)
507 break;
509 if (p->poolwords == 0)
510 return -EINVAL;
512 r = kmalloc(sizeof(struct entropy_store), GFP_KERNEL);
513 if (!r)
514 return -ENOMEM;
516 memset (r, 0, sizeof(struct entropy_store));
517 r->poolinfo = *p;
519 r->pool = kmalloc(POOLBYTES, GFP_KERNEL);
520 if (!r->pool) {
521 kfree(r);
522 return -ENOMEM;
524 memset(r->pool, 0, POOLBYTES);
525 *ret_bucket = r;
526 return 0;
529 /* Clear the entropy pool and associated counters. */
530 static void clear_entropy_store(struct entropy_store *r)
532 r->add_ptr = 0;
533 r->entropy_count = 0;
534 r->input_rotate = 0;
535 r->extract_count = 0;
536 memset(r->pool, 0, r->poolinfo.POOLBYTES);
538 #ifdef CONFIG_SYSCTL
539 static void free_entropy_store(struct entropy_store *r)
541 if (r->pool)
542 kfree(r->pool);
543 kfree(r);
545 #endif
547 * This function adds a byte into the entropy "pool". It does not
548 * update the entropy estimate. The caller should call
549 * credit_entropy_store if this is appropriate.
551 * The pool is stirred with a primitive polynomial of the appropriate
552 * degree, and then twisted. We twist by three bits at a time because
553 * it's cheap to do so and helps slightly in the expected case where
554 * the entropy is concentrated in the low-order bits.
556 static void add_entropy_words(struct entropy_store *r, const __u32 *in,
557 int nwords)
559 static __u32 const twist_table[8] = {
560 0, 0x3b6e20c8, 0x76dc4190, 0x4db26158,
561 0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278 };
562 unsigned i;
563 int new_rotate;
564 int wordmask = r->poolinfo.poolwords - 1;
565 __u32 w;
567 while (nwords--) {
568 w = rotate_left(r->input_rotate, *in++);
569 i = r->add_ptr = (r->add_ptr - 1) & wordmask;
571 * Normally, we add 7 bits of rotation to the pool.
572 * At the beginning of the pool, add an extra 7 bits
573 * rotation, so that successive passes spread the
574 * input bits across the pool evenly.
576 new_rotate = r->input_rotate + 14;
577 if (i)
578 new_rotate = r->input_rotate + 7;
579 r->input_rotate = new_rotate & 31;
581 /* XOR in the various taps */
582 w ^= r->pool[(i + r->poolinfo.tap1) & wordmask];
583 w ^= r->pool[(i + r->poolinfo.tap2) & wordmask];
584 w ^= r->pool[(i + r->poolinfo.tap3) & wordmask];
585 w ^= r->pool[(i + r->poolinfo.tap4) & wordmask];
586 w ^= r->pool[(i + r->poolinfo.tap5) & wordmask];
587 w ^= r->pool[i];
588 r->pool[i] = (w >> 3) ^ twist_table[w & 7];
593 * Credit (or debit) the entropy store with n bits of entropy
595 static void credit_entropy_store(struct entropy_store *r, int nbits)
597 if (r->entropy_count + nbits < 0) {
598 DEBUG_ENT("negative entropy/overflow (%d+%d)\n",
599 r->entropy_count, nbits);
600 r->entropy_count = 0;
601 } else if (r->entropy_count + nbits > r->poolinfo.POOLBITS) {
602 r->entropy_count = r->poolinfo.POOLBITS;
603 } else {
604 r->entropy_count += nbits;
605 if (nbits)
606 DEBUG_ENT("%s added %d bits, now %d\n",
607 r == sec_random_state ? "secondary" :
608 r == random_state ? "primary" : "unknown",
609 nbits, r->entropy_count);
613 /**********************************************************************
615 * Entropy batch input management
617 * We batch entropy to be added to avoid increasing interrupt latency
619 **********************************************************************/
621 static __u32 *batch_entropy_pool;
622 static int *batch_entropy_credit;
623 static int batch_max;
624 static int batch_head, batch_tail;
625 static void batch_entropy_process(void *private_);
626 static DECLARE_WORK(batch_work, batch_entropy_process, NULL);
628 /* note: the size must be a power of 2 */
629 static int __init batch_entropy_init(int size, struct entropy_store *r)
631 batch_entropy_pool = kmalloc(2*size*sizeof(__u32), GFP_KERNEL);
632 if (!batch_entropy_pool)
633 return -1;
634 batch_entropy_credit =kmalloc(size*sizeof(int), GFP_KERNEL);
635 if (!batch_entropy_credit) {
636 kfree(batch_entropy_pool);
637 return -1;
639 batch_head = batch_tail = 0;
640 batch_max = size;
641 batch_work.data = r;
642 return 0;
646 * Changes to the entropy data is put into a queue rather than being added to
647 * the entropy counts directly. This is presumably to avoid doing heavy
648 * hashing calculations during an interrupt in add_timer_randomness().
649 * Instead, the entropy is only added to the pool by keventd.
651 void batch_entropy_store(u32 a, u32 b, int num)
653 int new;
655 if (!batch_max)
656 return;
658 batch_entropy_pool[2*batch_head] = a;
659 batch_entropy_pool[(2*batch_head) + 1] = b;
660 batch_entropy_credit[batch_head] = num;
662 new = (batch_head+1) & (batch_max-1);
663 if ((unsigned)(new - batch_tail) >= (unsigned)(batch_max / 2)) {
665 * Schedule it for the next timer tick:
667 schedule_delayed_work(&batch_work, 1);
668 batch_head = new;
669 } else if (new == batch_tail) {
670 DEBUG_ENT("batch entropy buffer full\n");
671 } else {
672 batch_head = new;
677 * Flush out the accumulated entropy operations, adding entropy to the passed
678 * store (normally random_state). If that store has enough entropy, alternate
679 * between randomizing the data of the primary and secondary stores.
681 static void batch_entropy_process(void *private_)
683 struct entropy_store *r = (struct entropy_store *) private_, *p;
684 int max_entropy = r->poolinfo.POOLBITS;
686 if (!batch_max)
687 return;
689 p = r;
690 while (batch_head != batch_tail) {
691 if (r->entropy_count >= max_entropy) {
692 r = (r == sec_random_state) ? random_state :
693 sec_random_state;
694 max_entropy = r->poolinfo.POOLBITS;
696 add_entropy_words(r, batch_entropy_pool + 2*batch_tail, 2);
697 credit_entropy_store(r, batch_entropy_credit[batch_tail]);
698 batch_tail = (batch_tail+1) & (batch_max-1);
700 if (p->entropy_count >= random_read_wakeup_thresh)
701 wake_up_interruptible(&random_read_wait);
704 /*********************************************************************
706 * Entropy input management
708 *********************************************************************/
710 /* There is one of these per entropy source */
711 struct timer_rand_state {
712 __u32 last_time;
713 __s32 last_delta,last_delta2;
714 int dont_count_entropy:1;
717 static struct timer_rand_state keyboard_timer_state;
718 static struct timer_rand_state mouse_timer_state;
719 static struct timer_rand_state extract_timer_state;
720 static struct timer_rand_state *irq_timer_state[NR_IRQS];
723 * This function adds entropy to the entropy "pool" by using timing
724 * delays. It uses the timer_rand_state structure to make an estimate
725 * of how many bits of entropy this call has added to the pool.
727 * The number "num" is also added to the pool - it should somehow describe
728 * the type of event which just happened. This is currently 0-255 for
729 * keyboard scan codes, and 256 upwards for interrupts.
730 * On the i386, this is assumed to be at most 16 bits, and the high bits
731 * are used for a high-resolution timer.
734 static void add_timer_randomness(struct timer_rand_state *state, unsigned num)
736 __u32 time;
737 __s32 delta, delta2, delta3;
738 int entropy = 0;
740 #if defined (__i386__) || defined (__x86_64__)
741 if (cpu_has_tsc) {
742 __u32 high;
743 rdtsc(time, high);
744 num ^= high;
745 } else {
746 time = jiffies;
748 #else
749 time = jiffies;
750 #endif
753 * Calculate number of bits of randomness we probably added.
754 * We take into account the first, second and third-order deltas
755 * in order to make our estimate.
757 if (!state->dont_count_entropy) {
758 delta = time - state->last_time;
759 state->last_time = time;
761 delta2 = delta - state->last_delta;
762 state->last_delta = delta;
764 delta3 = delta2 - state->last_delta2;
765 state->last_delta2 = delta2;
767 if (delta < 0)
768 delta = -delta;
769 if (delta2 < 0)
770 delta2 = -delta2;
771 if (delta3 < 0)
772 delta3 = -delta3;
773 if (delta > delta2)
774 delta = delta2;
775 if (delta > delta3)
776 delta = delta3;
779 * delta is now minimum absolute delta.
780 * Round down by 1 bit on general principles,
781 * and limit entropy entimate to 12 bits.
783 delta >>= 1;
784 delta &= (1 << 12) - 1;
786 entropy = int_ln_12bits(delta);
788 batch_entropy_store(num, time, entropy);
791 void add_keyboard_randomness(unsigned char scancode)
793 static unsigned char last_scancode;
794 /* ignore autorepeat (multiple key down w/o key up) */
795 if (scancode != last_scancode) {
796 last_scancode = scancode;
797 add_timer_randomness(&keyboard_timer_state, scancode);
801 void add_mouse_randomness(__u32 mouse_data)
803 add_timer_randomness(&mouse_timer_state, mouse_data);
806 void add_interrupt_randomness(int irq)
808 if (irq >= NR_IRQS || irq_timer_state[irq] == 0)
809 return;
811 add_timer_randomness(irq_timer_state[irq], 0x100+irq);
814 void add_disk_randomness(struct gendisk *disk)
816 if (!disk || !disk->random)
817 return;
818 /* first major is 1, so we get >= 0x200 here */
819 add_timer_randomness(disk->random, 0x100+MKDEV(disk->major, disk->first_minor));
822 /******************************************************************
824 * Hash function definition
826 *******************************************************************/
829 * This chunk of code defines a function
830 * void HASH_TRANSFORM(__u32 digest[HASH_BUFFER_SIZE + HASH_EXTRA_SIZE],
831 * __u32 const data[16])
833 * The function hashes the input data to produce a digest in the first
834 * HASH_BUFFER_SIZE words of the digest[] array, and uses HASH_EXTRA_SIZE
835 * more words for internal purposes. (This buffer is exported so the
836 * caller can wipe it once rather than this code doing it each call,
837 * and tacking it onto the end of the digest[] array is the quick and
838 * dirty way of doing it.)
840 * It so happens that MD5 and SHA share most of the initial vector
841 * used to initialize the digest[] array before the first call:
842 * 1) 0x67452301
843 * 2) 0xefcdab89
844 * 3) 0x98badcfe
845 * 4) 0x10325476
846 * 5) 0xc3d2e1f0 (SHA only)
848 * For /dev/random purposes, the length of the data being hashed is
849 * fixed in length, so appending a bit count in the usual way is not
850 * cryptographically necessary.
853 #ifdef USE_SHA
855 #define HASH_BUFFER_SIZE 5
856 #define HASH_EXTRA_SIZE 80
857 #define HASH_TRANSFORM SHATransform
859 /* Various size/speed tradeoffs are available. Choose 0..3. */
860 #define SHA_CODE_SIZE 0
863 * SHA transform algorithm, taken from code written by Peter Gutmann,
864 * and placed in the public domain.
867 /* The SHA f()-functions. */
869 #define f1(x,y,z) ( z ^ (x & (y^z)) ) /* Rounds 0-19: x ? y : z */
870 #define f2(x,y,z) (x ^ y ^ z) /* Rounds 20-39: XOR */
871 #define f3(x,y,z) ( (x & y) + (z & (x ^ y)) ) /* Rounds 40-59: majority */
872 #define f4(x,y,z) (x ^ y ^ z) /* Rounds 60-79: XOR */
874 /* The SHA Mysterious Constants */
876 #define K1 0x5A827999L /* Rounds 0-19: sqrt(2) * 2^30 */
877 #define K2 0x6ED9EBA1L /* Rounds 20-39: sqrt(3) * 2^30 */
878 #define K3 0x8F1BBCDCL /* Rounds 40-59: sqrt(5) * 2^30 */
879 #define K4 0xCA62C1D6L /* Rounds 60-79: sqrt(10) * 2^30 */
881 #define ROTL(n,X) ( ( ( X ) << n ) | ( ( X ) >> ( 32 - n ) ) )
883 #define subRound(a, b, c, d, e, f, k, data) \
884 ( e += ROTL( 5, a ) + f( b, c, d ) + k + data, b = ROTL( 30, b ) )
887 static void SHATransform(__u32 digest[85], __u32 const data[16])
889 __u32 A, B, C, D, E; /* Local vars */
890 __u32 TEMP;
891 int i;
892 #define W (digest + HASH_BUFFER_SIZE) /* Expanded data array */
895 * Do the preliminary expansion of 16 to 80 words. Doing it
896 * out-of-line line this is faster than doing it in-line on
897 * register-starved machines like the x86, and not really any
898 * slower on real processors.
900 memcpy(W, data, 16*sizeof(__u32));
901 for (i = 0; i < 64; i++) {
902 TEMP = W[i] ^ W[i+2] ^ W[i+8] ^ W[i+13];
903 W[i+16] = ROTL(1, TEMP);
906 /* Set up first buffer and local data buffer */
907 A = digest[ 0 ];
908 B = digest[ 1 ];
909 C = digest[ 2 ];
910 D = digest[ 3 ];
911 E = digest[ 4 ];
913 /* Heavy mangling, in 4 sub-rounds of 20 iterations each. */
914 #if SHA_CODE_SIZE == 0
916 * Approximately 50% of the speed of the largest version, but
917 * takes up 1/16 the space. Saves about 6k on an i386 kernel.
919 for (i = 0; i < 80; i++) {
920 if (i < 40) {
921 if (i < 20)
922 TEMP = f1(B, C, D) + K1;
923 else
924 TEMP = f2(B, C, D) + K2;
925 } else {
926 if (i < 60)
927 TEMP = f3(B, C, D) + K3;
928 else
929 TEMP = f4(B, C, D) + K4;
931 TEMP += ROTL(5, A) + E + W[i];
932 E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
934 #elif SHA_CODE_SIZE == 1
935 for (i = 0; i < 20; i++) {
936 TEMP = f1(B, C, D) + K1 + ROTL(5, A) + E + W[i];
937 E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
939 for (; i < 40; i++) {
940 TEMP = f2(B, C, D) + K2 + ROTL(5, A) + E + W[i];
941 E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
943 for (; i < 60; i++) {
944 TEMP = f3(B, C, D) + K3 + ROTL(5, A) + E + W[i];
945 E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
947 for (; i < 80; i++) {
948 TEMP = f4(B, C, D) + K4 + ROTL(5, A) + E + W[i];
949 E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
951 #elif SHA_CODE_SIZE == 2
952 for (i = 0; i < 20; i += 5) {
953 subRound( A, B, C, D, E, f1, K1, W[ i ] );
954 subRound( E, A, B, C, D, f1, K1, W[ i+1 ] );
955 subRound( D, E, A, B, C, f1, K1, W[ i+2 ] );
956 subRound( C, D, E, A, B, f1, K1, W[ i+3 ] );
957 subRound( B, C, D, E, A, f1, K1, W[ i+4 ] );
959 for (; i < 40; i += 5) {
960 subRound( A, B, C, D, E, f2, K2, W[ i ] );
961 subRound( E, A, B, C, D, f2, K2, W[ i+1 ] );
962 subRound( D, E, A, B, C, f2, K2, W[ i+2 ] );
963 subRound( C, D, E, A, B, f2, K2, W[ i+3 ] );
964 subRound( B, C, D, E, A, f2, K2, W[ i+4 ] );
966 for (; i < 60; i += 5) {
967 subRound( A, B, C, D, E, f3, K3, W[ i ] );
968 subRound( E, A, B, C, D, f3, K3, W[ i+1 ] );
969 subRound( D, E, A, B, C, f3, K3, W[ i+2 ] );
970 subRound( C, D, E, A, B, f3, K3, W[ i+3 ] );
971 subRound( B, C, D, E, A, f3, K3, W[ i+4 ] );
973 for (; i < 80; i += 5) {
974 subRound( A, B, C, D, E, f4, K4, W[ i ] );
975 subRound( E, A, B, C, D, f4, K4, W[ i+1 ] );
976 subRound( D, E, A, B, C, f4, K4, W[ i+2 ] );
977 subRound( C, D, E, A, B, f4, K4, W[ i+3 ] );
978 subRound( B, C, D, E, A, f4, K4, W[ i+4 ] );
980 #elif SHA_CODE_SIZE == 3 /* Really large version */
981 subRound( A, B, C, D, E, f1, K1, W[ 0 ] );
982 subRound( E, A, B, C, D, f1, K1, W[ 1 ] );
983 subRound( D, E, A, B, C, f1, K1, W[ 2 ] );
984 subRound( C, D, E, A, B, f1, K1, W[ 3 ] );
985 subRound( B, C, D, E, A, f1, K1, W[ 4 ] );
986 subRound( A, B, C, D, E, f1, K1, W[ 5 ] );
987 subRound( E, A, B, C, D, f1, K1, W[ 6 ] );
988 subRound( D, E, A, B, C, f1, K1, W[ 7 ] );
989 subRound( C, D, E, A, B, f1, K1, W[ 8 ] );
990 subRound( B, C, D, E, A, f1, K1, W[ 9 ] );
991 subRound( A, B, C, D, E, f1, K1, W[ 10 ] );
992 subRound( E, A, B, C, D, f1, K1, W[ 11 ] );
993 subRound( D, E, A, B, C, f1, K1, W[ 12 ] );
994 subRound( C, D, E, A, B, f1, K1, W[ 13 ] );
995 subRound( B, C, D, E, A, f1, K1, W[ 14 ] );
996 subRound( A, B, C, D, E, f1, K1, W[ 15 ] );
997 subRound( E, A, B, C, D, f1, K1, W[ 16 ] );
998 subRound( D, E, A, B, C, f1, K1, W[ 17 ] );
999 subRound( C, D, E, A, B, f1, K1, W[ 18 ] );
1000 subRound( B, C, D, E, A, f1, K1, W[ 19 ] );
1002 subRound( A, B, C, D, E, f2, K2, W[ 20 ] );
1003 subRound( E, A, B, C, D, f2, K2, W[ 21 ] );
1004 subRound( D, E, A, B, C, f2, K2, W[ 22 ] );
1005 subRound( C, D, E, A, B, f2, K2, W[ 23 ] );
1006 subRound( B, C, D, E, A, f2, K2, W[ 24 ] );
1007 subRound( A, B, C, D, E, f2, K2, W[ 25 ] );
1008 subRound( E, A, B, C, D, f2, K2, W[ 26 ] );
1009 subRound( D, E, A, B, C, f2, K2, W[ 27 ] );
1010 subRound( C, D, E, A, B, f2, K2, W[ 28 ] );
1011 subRound( B, C, D, E, A, f2, K2, W[ 29 ] );
1012 subRound( A, B, C, D, E, f2, K2, W[ 30 ] );
1013 subRound( E, A, B, C, D, f2, K2, W[ 31 ] );
1014 subRound( D, E, A, B, C, f2, K2, W[ 32 ] );
1015 subRound( C, D, E, A, B, f2, K2, W[ 33 ] );
1016 subRound( B, C, D, E, A, f2, K2, W[ 34 ] );
1017 subRound( A, B, C, D, E, f2, K2, W[ 35 ] );
1018 subRound( E, A, B, C, D, f2, K2, W[ 36 ] );
1019 subRound( D, E, A, B, C, f2, K2, W[ 37 ] );
1020 subRound( C, D, E, A, B, f2, K2, W[ 38 ] );
1021 subRound( B, C, D, E, A, f2, K2, W[ 39 ] );
1023 subRound( A, B, C, D, E, f3, K3, W[ 40 ] );
1024 subRound( E, A, B, C, D, f3, K3, W[ 41 ] );
1025 subRound( D, E, A, B, C, f3, K3, W[ 42 ] );
1026 subRound( C, D, E, A, B, f3, K3, W[ 43 ] );
1027 subRound( B, C, D, E, A, f3, K3, W[ 44 ] );
1028 subRound( A, B, C, D, E, f3, K3, W[ 45 ] );
1029 subRound( E, A, B, C, D, f3, K3, W[ 46 ] );
1030 subRound( D, E, A, B, C, f3, K3, W[ 47 ] );
1031 subRound( C, D, E, A, B, f3, K3, W[ 48 ] );
1032 subRound( B, C, D, E, A, f3, K3, W[ 49 ] );
1033 subRound( A, B, C, D, E, f3, K3, W[ 50 ] );
1034 subRound( E, A, B, C, D, f3, K3, W[ 51 ] );
1035 subRound( D, E, A, B, C, f3, K3, W[ 52 ] );
1036 subRound( C, D, E, A, B, f3, K3, W[ 53 ] );
1037 subRound( B, C, D, E, A, f3, K3, W[ 54 ] );
1038 subRound( A, B, C, D, E, f3, K3, W[ 55 ] );
1039 subRound( E, A, B, C, D, f3, K3, W[ 56 ] );
1040 subRound( D, E, A, B, C, f3, K3, W[ 57 ] );
1041 subRound( C, D, E, A, B, f3, K3, W[ 58 ] );
1042 subRound( B, C, D, E, A, f3, K3, W[ 59 ] );
1044 subRound( A, B, C, D, E, f4, K4, W[ 60 ] );
1045 subRound( E, A, B, C, D, f4, K4, W[ 61 ] );
1046 subRound( D, E, A, B, C, f4, K4, W[ 62 ] );
1047 subRound( C, D, E, A, B, f4, K4, W[ 63 ] );
1048 subRound( B, C, D, E, A, f4, K4, W[ 64 ] );
1049 subRound( A, B, C, D, E, f4, K4, W[ 65 ] );
1050 subRound( E, A, B, C, D, f4, K4, W[ 66 ] );
1051 subRound( D, E, A, B, C, f4, K4, W[ 67 ] );
1052 subRound( C, D, E, A, B, f4, K4, W[ 68 ] );
1053 subRound( B, C, D, E, A, f4, K4, W[ 69 ] );
1054 subRound( A, B, C, D, E, f4, K4, W[ 70 ] );
1055 subRound( E, A, B, C, D, f4, K4, W[ 71 ] );
1056 subRound( D, E, A, B, C, f4, K4, W[ 72 ] );
1057 subRound( C, D, E, A, B, f4, K4, W[ 73 ] );
1058 subRound( B, C, D, E, A, f4, K4, W[ 74 ] );
1059 subRound( A, B, C, D, E, f4, K4, W[ 75 ] );
1060 subRound( E, A, B, C, D, f4, K4, W[ 76 ] );
1061 subRound( D, E, A, B, C, f4, K4, W[ 77 ] );
1062 subRound( C, D, E, A, B, f4, K4, W[ 78 ] );
1063 subRound( B, C, D, E, A, f4, K4, W[ 79 ] );
1064 #else
1065 #error Illegal SHA_CODE_SIZE
1066 #endif
1068 /* Build message digest */
1069 digest[ 0 ] += A;
1070 digest[ 1 ] += B;
1071 digest[ 2 ] += C;
1072 digest[ 3 ] += D;
1073 digest[ 4 ] += E;
1075 /* W is wiped by the caller */
1076 #undef W
1079 #undef ROTL
1080 #undef f1
1081 #undef f2
1082 #undef f3
1083 #undef f4
1084 #undef K1
1085 #undef K2
1086 #undef K3
1087 #undef K4
1088 #undef subRound
1090 #else /* !USE_SHA - Use MD5 */
1092 #define HASH_BUFFER_SIZE 4
1093 #define HASH_EXTRA_SIZE 0
1094 #define HASH_TRANSFORM MD5Transform
1097 * MD5 transform algorithm, taken from code written by Colin Plumb,
1098 * and put into the public domain
1101 /* The four core functions - F1 is optimized somewhat */
1103 /* #define F1(x, y, z) (x & y | ~x & z) */
1104 #define F1(x, y, z) (z ^ (x & (y ^ z)))
1105 #define F2(x, y, z) F1(z, x, y)
1106 #define F3(x, y, z) (x ^ y ^ z)
1107 #define F4(x, y, z) (y ^ (x | ~z))
1109 /* This is the central step in the MD5 algorithm. */
1110 #define MD5STEP(f, w, x, y, z, data, s) \
1111 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
1114 * The core of the MD5 algorithm, this alters an existing MD5 hash to
1115 * reflect the addition of 16 longwords of new data. MD5Update blocks
1116 * the data and converts bytes into longwords for this routine.
1118 static void MD5Transform(__u32 buf[HASH_BUFFER_SIZE], __u32 const in[16])
1120 __u32 a, b, c, d;
1122 a = buf[0];
1123 b = buf[1];
1124 c = buf[2];
1125 d = buf[3];
1127 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
1128 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
1129 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
1130 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
1131 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
1132 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
1133 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
1134 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
1135 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
1136 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
1137 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
1138 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
1139 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
1140 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
1141 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
1142 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
1144 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
1145 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
1146 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
1147 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
1148 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
1149 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
1150 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
1151 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
1152 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
1153 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
1154 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
1155 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
1156 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
1157 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
1158 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
1159 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
1161 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
1162 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
1163 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
1164 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
1165 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
1166 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
1167 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
1168 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
1169 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
1170 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
1171 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
1172 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
1173 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
1174 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
1175 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
1176 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
1178 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
1179 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
1180 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
1181 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
1182 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
1183 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
1184 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
1185 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
1186 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
1187 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
1188 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
1189 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
1190 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
1191 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
1192 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
1193 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
1195 buf[0] += a;
1196 buf[1] += b;
1197 buf[2] += c;
1198 buf[3] += d;
1201 #undef F1
1202 #undef F2
1203 #undef F3
1204 #undef F4
1205 #undef MD5STEP
1207 #endif /* !USE_SHA */
1209 /*********************************************************************
1211 * Entropy extraction routines
1213 *********************************************************************/
1215 #define EXTRACT_ENTROPY_USER 1
1216 #define EXTRACT_ENTROPY_SECONDARY 2
1217 #define TMP_BUF_SIZE (HASH_BUFFER_SIZE + HASH_EXTRA_SIZE)
1218 #define SEC_XFER_SIZE (TMP_BUF_SIZE*4)
1220 static ssize_t extract_entropy(struct entropy_store *r, void * buf,
1221 size_t nbytes, int flags);
1224 * This utility inline function is responsible for transfering entropy
1225 * from the primary pool to the secondary extraction pool. We pull
1226 * randomness under two conditions; one is if there isn't enough entropy
1227 * in the secondary pool. The other is after we have extracted 1024 bytes,
1228 * at which point we do a "catastrophic reseeding".
1230 static inline void xfer_secondary_pool(struct entropy_store *r,
1231 size_t nbytes, __u32 *tmp)
1233 if (r->entropy_count < nbytes * 8 &&
1234 r->entropy_count < r->poolinfo.POOLBITS) {
1235 int nwords = min_t(int,
1236 r->poolinfo.poolwords - r->entropy_count/32,
1237 sizeof(tmp) / 4);
1239 DEBUG_ENT("xfer %d from primary to %s (have %d, need %d)\n",
1240 nwords * 32,
1241 r == sec_random_state ? "secondary" : "unknown",
1242 r->entropy_count, nbytes * 8);
1244 extract_entropy(random_state, tmp, nwords * 4, 0);
1245 add_entropy_words(r, tmp, nwords);
1246 credit_entropy_store(r, nwords * 32);
1248 if (r->extract_count > 1024) {
1249 DEBUG_ENT("reseeding %s with %d from primary\n",
1250 r == sec_random_state ? "secondary" : "unknown",
1251 sizeof(tmp) * 8);
1252 extract_entropy(random_state, tmp, sizeof(tmp), 0);
1253 add_entropy_words(r, tmp, sizeof(tmp) / 4);
1254 r->extract_count = 0;
1259 * This function extracts randomness from the "entropy pool", and
1260 * returns it in a buffer. This function computes how many remaining
1261 * bits of entropy are left in the pool, but it does not restrict the
1262 * number of bytes that are actually obtained. If the EXTRACT_ENTROPY_USER
1263 * flag is given, then the buf pointer is assumed to be in user space.
1265 * If the EXTRACT_ENTROPY_SECONDARY flag is given, then we are actually
1266 * extracting entropy from the secondary pool, and can refill from the
1267 * primary pool if needed.
1269 * Note: extract_entropy() assumes that .poolwords is a multiple of 16 words.
1271 static ssize_t extract_entropy(struct entropy_store *r, void * buf,
1272 size_t nbytes, int flags)
1274 ssize_t ret, i;
1275 __u32 tmp[TMP_BUF_SIZE];
1276 __u32 x;
1278 add_timer_randomness(&extract_timer_state, nbytes);
1280 /* Redundant, but just in case... */
1281 if (r->entropy_count > r->poolinfo.POOLBITS)
1282 r->entropy_count = r->poolinfo.POOLBITS;
1284 if (flags & EXTRACT_ENTROPY_SECONDARY)
1285 xfer_secondary_pool(r, nbytes, tmp);
1287 DEBUG_ENT("%s has %d bits, want %d bits\n",
1288 r == sec_random_state ? "secondary" :
1289 r == random_state ? "primary" : "unknown",
1290 r->entropy_count, nbytes * 8);
1292 if (r->entropy_count / 8 >= nbytes)
1293 r->entropy_count -= nbytes*8;
1294 else
1295 r->entropy_count = 0;
1297 if (r->entropy_count < random_write_wakeup_thresh)
1298 wake_up_interruptible(&random_write_wait);
1300 r->extract_count += nbytes;
1302 ret = 0;
1303 while (nbytes) {
1305 * Check if we need to break out or reschedule....
1307 if ((flags & EXTRACT_ENTROPY_USER) && need_resched()) {
1308 if (signal_pending(current)) {
1309 if (ret == 0)
1310 ret = -ERESTARTSYS;
1311 break;
1313 schedule();
1316 /* Hash the pool to get the output */
1317 tmp[0] = 0x67452301;
1318 tmp[1] = 0xefcdab89;
1319 tmp[2] = 0x98badcfe;
1320 tmp[3] = 0x10325476;
1321 #ifdef USE_SHA
1322 tmp[4] = 0xc3d2e1f0;
1323 #endif
1325 * As we hash the pool, we mix intermediate values of
1326 * the hash back into the pool. This eliminates
1327 * backtracking attacks (where the attacker knows
1328 * the state of the pool plus the current outputs, and
1329 * attempts to find previous ouputs), unless the hash
1330 * function can be inverted.
1332 for (i = 0, x = 0; i < r->poolinfo.poolwords; i += 16, x+=2) {
1333 HASH_TRANSFORM(tmp, r->pool+i);
1334 add_entropy_words(r, &tmp[x%HASH_BUFFER_SIZE], 1);
1338 * In case the hash function has some recognizable
1339 * output pattern, we fold it in half.
1341 for (i = 0; i < HASH_BUFFER_SIZE/2; i++)
1342 tmp[i] ^= tmp[i + (HASH_BUFFER_SIZE+1)/2];
1343 #if HASH_BUFFER_SIZE & 1 /* There's a middle word to deal with */
1344 x = tmp[HASH_BUFFER_SIZE/2];
1345 x ^= (x >> 16); /* Fold it in half */
1346 ((__u16 *)tmp)[HASH_BUFFER_SIZE-1] = (__u16)x;
1347 #endif
1349 /* Copy data to destination buffer */
1350 i = min(nbytes, HASH_BUFFER_SIZE*sizeof(__u32)/2);
1351 if (flags & EXTRACT_ENTROPY_USER) {
1352 i -= copy_to_user(buf, (__u8 const *)tmp, i);
1353 if (!i) {
1354 ret = -EFAULT;
1355 break;
1357 } else
1358 memcpy(buf, (__u8 const *)tmp, i);
1359 nbytes -= i;
1360 buf += i;
1361 ret += i;
1362 add_timer_randomness(&extract_timer_state, nbytes);
1365 /* Wipe data just returned from memory */
1366 memset(tmp, 0, sizeof(tmp));
1368 return ret;
1372 * This function is the exported kernel interface. It returns some
1373 * number of good random numbers, suitable for seeding TCP sequence
1374 * numbers, etc.
1376 void get_random_bytes(void *buf, int nbytes)
1378 if (sec_random_state)
1379 extract_entropy(sec_random_state, (char *) buf, nbytes,
1380 EXTRACT_ENTROPY_SECONDARY);
1381 else if (random_state)
1382 extract_entropy(random_state, (char *) buf, nbytes, 0);
1383 else
1384 printk(KERN_NOTICE "get_random_bytes called before "
1385 "random driver initialization\n");
1388 /*********************************************************************
1390 * Functions to interface with Linux
1392 *********************************************************************/
1395 * Initialize the random pool with standard stuff.
1397 * NOTE: This is an OS-dependent function.
1399 static void init_std_data(struct entropy_store *r)
1401 struct timeval tv;
1402 __u32 words[2];
1403 char *p;
1404 int i;
1406 do_gettimeofday(&tv);
1407 words[0] = tv.tv_sec;
1408 words[1] = tv.tv_usec;
1409 add_entropy_words(r, words, 2);
1412 * This doesn't lock system.utsname. However, we are generating
1413 * entropy so a race with a name set here is fine.
1415 p = (char *) &system_utsname;
1416 for (i = sizeof(system_utsname) / sizeof(words); i; i--) {
1417 memcpy(words, p, sizeof(words));
1418 add_entropy_words(r, words, sizeof(words)/4);
1419 p += sizeof(words);
1423 void __init rand_initialize(void)
1425 int i;
1427 if (create_entropy_store(DEFAULT_POOL_SIZE, &random_state))
1428 return; /* Error, return */
1429 if (batch_entropy_init(BATCH_ENTROPY_SIZE, random_state))
1430 return; /* Error, return */
1431 if (create_entropy_store(SECONDARY_POOL_SIZE, &sec_random_state))
1432 return; /* Error, return */
1433 clear_entropy_store(random_state);
1434 clear_entropy_store(sec_random_state);
1435 init_std_data(random_state);
1436 #ifdef CONFIG_SYSCTL
1437 sysctl_init_random(random_state);
1438 #endif
1439 for (i = 0; i < NR_IRQS; i++)
1440 irq_timer_state[i] = NULL;
1441 memset(&keyboard_timer_state, 0, sizeof(struct timer_rand_state));
1442 memset(&mouse_timer_state, 0, sizeof(struct timer_rand_state));
1443 memset(&extract_timer_state, 0, sizeof(struct timer_rand_state));
1444 extract_timer_state.dont_count_entropy = 1;
1447 void rand_initialize_irq(int irq)
1449 struct timer_rand_state *state;
1451 if (irq >= NR_IRQS || irq_timer_state[irq])
1452 return;
1455 * If kmalloc returns null, we just won't use that entropy
1456 * source.
1458 state = kmalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
1459 if (state) {
1460 memset(state, 0, sizeof(struct timer_rand_state));
1461 irq_timer_state[irq] = state;
1465 void rand_initialize_disk(struct gendisk *disk)
1467 struct timer_rand_state *state;
1470 * If kmalloc returns null, we just won't use that entropy
1471 * source.
1473 state = kmalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
1474 if (state) {
1475 memset(state, 0, sizeof(struct timer_rand_state));
1476 disk->random = state;
1480 static ssize_t
1481 random_read(struct file * file, char * buf, size_t nbytes, loff_t *ppos)
1483 DECLARE_WAITQUEUE(wait, current);
1484 ssize_t n, retval = 0, count = 0;
1486 if (nbytes == 0)
1487 return 0;
1489 add_wait_queue(&random_read_wait, &wait);
1490 while (nbytes > 0) {
1491 set_current_state(TASK_INTERRUPTIBLE);
1493 n = nbytes;
1494 if (n > SEC_XFER_SIZE)
1495 n = SEC_XFER_SIZE;
1496 if (n > random_state->entropy_count / 8)
1497 n = random_state->entropy_count / 8;
1498 if (n == 0) {
1499 if (file->f_flags & O_NONBLOCK) {
1500 retval = -EAGAIN;
1501 break;
1503 if (signal_pending(current)) {
1504 retval = -ERESTARTSYS;
1505 break;
1507 schedule();
1508 continue;
1510 n = extract_entropy(sec_random_state, buf, n,
1511 EXTRACT_ENTROPY_USER |
1512 EXTRACT_ENTROPY_SECONDARY);
1513 if (n < 0) {
1514 retval = n;
1515 break;
1517 count += n;
1518 buf += n;
1519 nbytes -= n;
1520 break; /* This break makes the device work */
1521 /* like a named pipe */
1523 current->state = TASK_RUNNING;
1524 remove_wait_queue(&random_read_wait, &wait);
1527 * If we gave the user some bytes, update the access time.
1529 if (count != 0) {
1530 update_atime(file->f_dentry->d_inode);
1533 return (count ? count : retval);
1536 static ssize_t
1537 urandom_read(struct file * file, char * buf,
1538 size_t nbytes, loff_t *ppos)
1540 return extract_entropy(sec_random_state, buf, nbytes,
1541 EXTRACT_ENTROPY_USER |
1542 EXTRACT_ENTROPY_SECONDARY);
1545 static unsigned int
1546 random_poll(struct file *file, poll_table * wait)
1548 unsigned int mask;
1550 poll_wait(file, &random_read_wait, wait);
1551 poll_wait(file, &random_write_wait, wait);
1552 mask = 0;
1553 if (random_state->entropy_count >= random_read_wakeup_thresh)
1554 mask |= POLLIN | POLLRDNORM;
1555 if (random_state->entropy_count < random_write_wakeup_thresh)
1556 mask |= POLLOUT | POLLWRNORM;
1557 return mask;
1560 static ssize_t
1561 random_write(struct file * file, const char * buffer,
1562 size_t count, loff_t *ppos)
1564 int ret = 0;
1565 size_t bytes;
1566 __u32 buf[16];
1567 const char *p = buffer;
1568 size_t c = count;
1570 while (c > 0) {
1571 bytes = min(c, sizeof(buf));
1573 bytes -= copy_from_user(&buf, p, bytes);
1574 if (!bytes) {
1575 ret = -EFAULT;
1576 break;
1578 c -= bytes;
1579 p += bytes;
1581 add_entropy_words(random_state, buf, (bytes + 3) / 4);
1583 if (p == buffer) {
1584 return (ssize_t)ret;
1585 } else {
1586 file->f_dentry->d_inode->i_mtime = CURRENT_TIME;
1587 mark_inode_dirty(file->f_dentry->d_inode);
1588 return (ssize_t)(p - buffer);
1592 static int
1593 random_ioctl(struct inode * inode, struct file * file,
1594 unsigned int cmd, unsigned long arg)
1596 int *p, size, ent_count;
1597 int retval;
1599 switch (cmd) {
1600 case RNDGETENTCNT:
1601 ent_count = random_state->entropy_count;
1602 if (put_user(ent_count, (int *) arg))
1603 return -EFAULT;
1604 return 0;
1605 case RNDADDTOENTCNT:
1606 if (!capable(CAP_SYS_ADMIN))
1607 return -EPERM;
1608 if (get_user(ent_count, (int *) arg))
1609 return -EFAULT;
1610 credit_entropy_store(random_state, ent_count);
1612 * Wake up waiting processes if we have enough
1613 * entropy.
1615 if (random_state->entropy_count >= random_read_wakeup_thresh)
1616 wake_up_interruptible(&random_read_wait);
1617 return 0;
1618 case RNDGETPOOL:
1619 if (!capable(CAP_SYS_ADMIN))
1620 return -EPERM;
1621 p = (int *) arg;
1622 ent_count = random_state->entropy_count;
1623 if (put_user(ent_count, p++) ||
1624 get_user(size, p) ||
1625 put_user(random_state->poolinfo.poolwords, p++))
1626 return -EFAULT;
1627 if (size < 0)
1628 return -EINVAL;
1629 if (size > random_state->poolinfo.poolwords)
1630 size = random_state->poolinfo.poolwords;
1631 if (copy_to_user(p, random_state->pool, size * sizeof(__u32)))
1632 return -EFAULT;
1633 return 0;
1634 case RNDADDENTROPY:
1635 if (!capable(CAP_SYS_ADMIN))
1636 return -EPERM;
1637 p = (int *) arg;
1638 if (get_user(ent_count, p++))
1639 return -EFAULT;
1640 if (ent_count < 0)
1641 return -EINVAL;
1642 if (get_user(size, p++))
1643 return -EFAULT;
1644 retval = random_write(file, (const char *) p,
1645 size, &file->f_pos);
1646 if (retval < 0)
1647 return retval;
1648 credit_entropy_store(random_state, ent_count);
1650 * Wake up waiting processes if we have enough
1651 * entropy.
1653 if (random_state->entropy_count >= random_read_wakeup_thresh)
1654 wake_up_interruptible(&random_read_wait);
1655 return 0;
1656 case RNDZAPENTCNT:
1657 if (!capable(CAP_SYS_ADMIN))
1658 return -EPERM;
1659 random_state->entropy_count = 0;
1660 return 0;
1661 case RNDCLEARPOOL:
1662 /* Clear the entropy pool and associated counters. */
1663 if (!capable(CAP_SYS_ADMIN))
1664 return -EPERM;
1665 clear_entropy_store(random_state);
1666 init_std_data(random_state);
1667 return 0;
1668 default:
1669 return -EINVAL;
1673 struct file_operations random_fops = {
1674 .read = random_read,
1675 .write = random_write,
1676 .poll = random_poll,
1677 .ioctl = random_ioctl,
1680 struct file_operations urandom_fops = {
1681 .read = urandom_read,
1682 .write = random_write,
1683 .ioctl = random_ioctl,
1686 /***************************************************************
1687 * Random UUID interface
1689 * Used here for a Boot ID, but can be useful for other kernel
1690 * drivers.
1691 ***************************************************************/
1694 * Generate random UUID
1696 void generate_random_uuid(unsigned char uuid_out[16])
1698 get_random_bytes(uuid_out, 16);
1699 /* Set UUID version to 4 --- truely random generation */
1700 uuid_out[6] = (uuid_out[6] & 0x0F) | 0x40;
1701 /* Set the UUID variant to DCE */
1702 uuid_out[8] = (uuid_out[8] & 0x3F) | 0x80;
1705 /********************************************************************
1707 * Sysctl interface
1709 ********************************************************************/
1711 #ifdef CONFIG_SYSCTL
1713 #include <linux/sysctl.h>
1715 static int sysctl_poolsize;
1716 static int min_read_thresh, max_read_thresh;
1717 static int min_write_thresh, max_write_thresh;
1718 static char sysctl_bootid[16];
1721 * This function handles a request from the user to change the pool size
1722 * of the primary entropy store.
1724 static int change_poolsize(int poolsize)
1726 struct entropy_store *new_store, *old_store;
1727 int ret;
1729 if ((ret = create_entropy_store(poolsize, &new_store)))
1730 return ret;
1732 add_entropy_words(new_store, random_state->pool,
1733 random_state->poolinfo.poolwords);
1734 credit_entropy_store(new_store, random_state->entropy_count);
1736 sysctl_init_random(new_store);
1737 old_store = random_state;
1738 random_state = batch_work.data = new_store;
1739 free_entropy_store(old_store);
1740 return 0;
1743 static int proc_do_poolsize(ctl_table *table, int write, struct file *filp,
1744 void *buffer, size_t *lenp)
1746 int ret;
1748 sysctl_poolsize = random_state->poolinfo.POOLBYTES;
1750 ret = proc_dointvec(table, write, filp, buffer, lenp);
1751 if (ret || !write ||
1752 (sysctl_poolsize == random_state->poolinfo.POOLBYTES))
1753 return ret;
1755 return change_poolsize(sysctl_poolsize);
1758 static int poolsize_strategy(ctl_table *table, int *name, int nlen,
1759 void *oldval, size_t *oldlenp,
1760 void *newval, size_t newlen, void **context)
1762 int len;
1764 sysctl_poolsize = random_state->poolinfo.POOLBYTES;
1767 * We only handle the write case, since the read case gets
1768 * handled by the default handler (and we don't care if the
1769 * write case happens twice; it's harmless).
1771 if (newval && newlen) {
1772 len = newlen;
1773 if (len > table->maxlen)
1774 len = table->maxlen;
1775 if (copy_from_user(table->data, newval, len))
1776 return -EFAULT;
1779 if (sysctl_poolsize != random_state->poolinfo.POOLBYTES)
1780 return change_poolsize(sysctl_poolsize);
1782 return 0;
1786 * These functions is used to return both the bootid UUID, and random
1787 * UUID. The difference is in whether table->data is NULL; if it is,
1788 * then a new UUID is generated and returned to the user.
1790 * If the user accesses this via the proc interface, it will be returned
1791 * as an ASCII string in the standard UUID format. If accesses via the
1792 * sysctl system call, it is returned as 16 bytes of binary data.
1794 static int proc_do_uuid(ctl_table *table, int write, struct file *filp,
1795 void *buffer, size_t *lenp)
1797 ctl_table fake_table;
1798 unsigned char buf[64], tmp_uuid[16], *uuid;
1800 uuid = table->data;
1801 if (!uuid) {
1802 uuid = tmp_uuid;
1803 uuid[8] = 0;
1805 if (uuid[8] == 0)
1806 generate_random_uuid(uuid);
1808 sprintf(buf, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
1809 "%02x%02x%02x%02x%02x%02x",
1810 uuid[0], uuid[1], uuid[2], uuid[3],
1811 uuid[4], uuid[5], uuid[6], uuid[7],
1812 uuid[8], uuid[9], uuid[10], uuid[11],
1813 uuid[12], uuid[13], uuid[14], uuid[15]);
1814 fake_table.data = buf;
1815 fake_table.maxlen = sizeof(buf);
1817 return proc_dostring(&fake_table, write, filp, buffer, lenp);
1820 static int uuid_strategy(ctl_table *table, int *name, int nlen,
1821 void *oldval, size_t *oldlenp,
1822 void *newval, size_t newlen, void **context)
1824 unsigned char tmp_uuid[16], *uuid;
1825 unsigned int len;
1827 if (!oldval || !oldlenp)
1828 return 1;
1830 uuid = table->data;
1831 if (!uuid) {
1832 uuid = tmp_uuid;
1833 uuid[8] = 0;
1835 if (uuid[8] == 0)
1836 generate_random_uuid(uuid);
1838 if (get_user(len, oldlenp))
1839 return -EFAULT;
1840 if (len) {
1841 if (len > 16)
1842 len = 16;
1843 if (copy_to_user(oldval, uuid, len) ||
1844 put_user(len, oldlenp))
1845 return -EFAULT;
1847 return 1;
1850 ctl_table random_table[] = {
1851 {RANDOM_POOLSIZE, "poolsize",
1852 &sysctl_poolsize, sizeof(int), 0644, NULL,
1853 &proc_do_poolsize, &poolsize_strategy},
1854 {RANDOM_ENTROPY_COUNT, "entropy_avail",
1855 NULL, sizeof(int), 0444, NULL,
1856 &proc_dointvec},
1857 {RANDOM_READ_THRESH, "read_wakeup_threshold",
1858 &random_read_wakeup_thresh, sizeof(int), 0644, NULL,
1859 &proc_dointvec_minmax, &sysctl_intvec, 0,
1860 &min_read_thresh, &max_read_thresh},
1861 {RANDOM_WRITE_THRESH, "write_wakeup_threshold",
1862 &random_write_wakeup_thresh, sizeof(int), 0644, NULL,
1863 &proc_dointvec_minmax, &sysctl_intvec, 0,
1864 &min_write_thresh, &max_write_thresh},
1865 {RANDOM_BOOT_ID, "boot_id",
1866 &sysctl_bootid, 16, 0444, NULL,
1867 &proc_do_uuid, &uuid_strategy},
1868 {RANDOM_UUID, "uuid",
1869 NULL, 16, 0444, NULL,
1870 &proc_do_uuid, &uuid_strategy},
1874 static void sysctl_init_random(struct entropy_store *random_state)
1876 min_read_thresh = 8;
1877 min_write_thresh = 0;
1878 max_read_thresh = max_write_thresh = random_state->poolinfo.POOLBITS;
1879 random_table[1].data = &random_state->entropy_count;
1881 #endif /* CONFIG_SYSCTL */
1883 /********************************************************************
1885 * Random funtions for networking
1887 ********************************************************************/
1890 * TCP initial sequence number picking. This uses the random number
1891 * generator to pick an initial secret value. This value is hashed
1892 * along with the TCP endpoint information to provide a unique
1893 * starting point for each pair of TCP endpoints. This defeats
1894 * attacks which rely on guessing the initial TCP sequence number.
1895 * This algorithm was suggested by Steve Bellovin.
1897 * Using a very strong hash was taking an appreciable amount of the total
1898 * TCP connection establishment time, so this is a weaker hash,
1899 * compensated for by changing the secret periodically.
1902 /* F, G and H are basic MD4 functions: selection, majority, parity */
1903 #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
1904 #define G(x, y, z) (((x) & (y)) + (((x) ^ (y)) & (z)))
1905 #define H(x, y, z) ((x) ^ (y) ^ (z))
1908 * The generic round function. The application is so specific that
1909 * we don't bother protecting all the arguments with parens, as is generally
1910 * good macro practice, in favor of extra legibility.
1911 * Rotation is separate from addition to prevent recomputation
1913 #define ROUND(f, a, b, c, d, x, s) \
1914 (a += f(b, c, d) + x, a = (a << s) | (a >> (32-s)))
1915 #define K1 0
1916 #define K2 013240474631UL
1917 #define K3 015666365641UL
1920 * Basic cut-down MD4 transform. Returns only 32 bits of result.
1922 static __u32 halfMD4Transform (__u32 const buf[4], __u32 const in[8])
1924 __u32 a = buf[0], b = buf[1], c = buf[2], d = buf[3];
1926 /* Round 1 */
1927 ROUND(F, a, b, c, d, in[0] + K1, 3);
1928 ROUND(F, d, a, b, c, in[1] + K1, 7);
1929 ROUND(F, c, d, a, b, in[2] + K1, 11);
1930 ROUND(F, b, c, d, a, in[3] + K1, 19);
1931 ROUND(F, a, b, c, d, in[4] + K1, 3);
1932 ROUND(F, d, a, b, c, in[5] + K1, 7);
1933 ROUND(F, c, d, a, b, in[6] + K1, 11);
1934 ROUND(F, b, c, d, a, in[7] + K1, 19);
1936 /* Round 2 */
1937 ROUND(G, a, b, c, d, in[1] + K2, 3);
1938 ROUND(G, d, a, b, c, in[3] + K2, 5);
1939 ROUND(G, c, d, a, b, in[5] + K2, 9);
1940 ROUND(G, b, c, d, a, in[7] + K2, 13);
1941 ROUND(G, a, b, c, d, in[0] + K2, 3);
1942 ROUND(G, d, a, b, c, in[2] + K2, 5);
1943 ROUND(G, c, d, a, b, in[4] + K2, 9);
1944 ROUND(G, b, c, d, a, in[6] + K2, 13);
1946 /* Round 3 */
1947 ROUND(H, a, b, c, d, in[3] + K3, 3);
1948 ROUND(H, d, a, b, c, in[7] + K3, 9);
1949 ROUND(H, c, d, a, b, in[2] + K3, 11);
1950 ROUND(H, b, c, d, a, in[6] + K3, 15);
1951 ROUND(H, a, b, c, d, in[1] + K3, 3);
1952 ROUND(H, d, a, b, c, in[5] + K3, 9);
1953 ROUND(H, c, d, a, b, in[0] + K3, 11);
1954 ROUND(H, b, c, d, a, in[4] + K3, 15);
1956 return buf[1] + b; /* "most hashed" word */
1957 /* Alternative: return sum of all words? */
1960 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
1962 static __u32 twothirdsMD4Transform (__u32 const buf[4], __u32 const in[12])
1964 __u32 a = buf[0], b = buf[1], c = buf[2], d = buf[3];
1966 /* Round 1 */
1967 ROUND(F, a, b, c, d, in[ 0] + K1, 3);
1968 ROUND(F, d, a, b, c, in[ 1] + K1, 7);
1969 ROUND(F, c, d, a, b, in[ 2] + K1, 11);
1970 ROUND(F, b, c, d, a, in[ 3] + K1, 19);
1971 ROUND(F, a, b, c, d, in[ 4] + K1, 3);
1972 ROUND(F, d, a, b, c, in[ 5] + K1, 7);
1973 ROUND(F, c, d, a, b, in[ 6] + K1, 11);
1974 ROUND(F, b, c, d, a, in[ 7] + K1, 19);
1975 ROUND(F, a, b, c, d, in[ 8] + K1, 3);
1976 ROUND(F, d, a, b, c, in[ 9] + K1, 7);
1977 ROUND(F, c, d, a, b, in[10] + K1, 11);
1978 ROUND(F, b, c, d, a, in[11] + K1, 19);
1980 /* Round 2 */
1981 ROUND(G, a, b, c, d, in[ 1] + K2, 3);
1982 ROUND(G, d, a, b, c, in[ 3] + K2, 5);
1983 ROUND(G, c, d, a, b, in[ 5] + K2, 9);
1984 ROUND(G, b, c, d, a, in[ 7] + K2, 13);
1985 ROUND(G, a, b, c, d, in[ 9] + K2, 3);
1986 ROUND(G, d, a, b, c, in[11] + K2, 5);
1987 ROUND(G, c, d, a, b, in[ 0] + K2, 9);
1988 ROUND(G, b, c, d, a, in[ 2] + K2, 13);
1989 ROUND(G, a, b, c, d, in[ 4] + K2, 3);
1990 ROUND(G, d, a, b, c, in[ 6] + K2, 5);
1991 ROUND(G, c, d, a, b, in[ 8] + K2, 9);
1992 ROUND(G, b, c, d, a, in[10] + K2, 13);
1994 /* Round 3 */
1995 ROUND(H, a, b, c, d, in[ 3] + K3, 3);
1996 ROUND(H, d, a, b, c, in[ 7] + K3, 9);
1997 ROUND(H, c, d, a, b, in[11] + K3, 11);
1998 ROUND(H, b, c, d, a, in[ 2] + K3, 15);
1999 ROUND(H, a, b, c, d, in[ 6] + K3, 3);
2000 ROUND(H, d, a, b, c, in[10] + K3, 9);
2001 ROUND(H, c, d, a, b, in[ 1] + K3, 11);
2002 ROUND(H, b, c, d, a, in[ 5] + K3, 15);
2003 ROUND(H, a, b, c, d, in[ 9] + K3, 3);
2004 ROUND(H, d, a, b, c, in[ 0] + K3, 9);
2005 ROUND(H, c, d, a, b, in[ 4] + K3, 11);
2006 ROUND(H, b, c, d, a, in[ 8] + K3, 15);
2008 return buf[1] + b; /* "most hashed" word */
2009 /* Alternative: return sum of all words? */
2011 #endif
2013 #undef ROUND
2014 #undef F
2015 #undef G
2016 #undef H
2017 #undef K1
2018 #undef K2
2019 #undef K3
2021 /* This should not be decreased so low that ISNs wrap too fast. */
2022 #define REKEY_INTERVAL 300
2024 * Bit layout of the tcp sequence numbers (before adding current time):
2025 * bit 24-31: increased after every key exchange
2026 * bit 0-23: hash(source,dest)
2028 * The implementation is similar to the algorithm described
2029 * in the Appendix of RFC 1185, except that
2030 * - it uses a 1 MHz clock instead of a 250 kHz clock
2031 * - it performs a rekey every 5 minutes, which is equivalent
2032 * to a (source,dest) tulple dependent forward jump of the
2033 * clock by 0..2^(HASH_BITS+1)
2035 * Thus the average ISN wraparound time is 68 minutes instead of
2036 * 4.55 hours.
2038 * SMP cleanup and lock avoidance with poor man's RCU.
2039 * Manfred Spraul <manfred@colorfullife.com>
2042 #define COUNT_BITS 8
2043 #define COUNT_MASK ( (1<<COUNT_BITS)-1)
2044 #define HASH_BITS 24
2045 #define HASH_MASK ( (1<<HASH_BITS)-1 )
2047 static struct keydata {
2048 time_t rekey_time;
2049 __u32 count; // already shifted to the final position
2050 __u32 secret[12];
2051 } ____cacheline_aligned ip_keydata[2];
2053 static spinlock_t ip_lock = SPIN_LOCK_UNLOCKED;
2054 static unsigned int ip_cnt;
2056 static struct keydata *__check_and_rekey(time_t time)
2058 struct keydata *keyptr;
2059 spin_lock(&ip_lock);
2060 keyptr = &ip_keydata[ip_cnt&1];
2061 if (!keyptr->rekey_time || (time - keyptr->rekey_time) > REKEY_INTERVAL) {
2062 keyptr = &ip_keydata[1^(ip_cnt&1)];
2063 keyptr->rekey_time = time;
2064 get_random_bytes(keyptr->secret, sizeof(keyptr->secret));
2065 keyptr->count = (ip_cnt&COUNT_MASK)<<HASH_BITS;
2066 mb();
2067 ip_cnt++;
2069 spin_unlock(&ip_lock);
2070 return keyptr;
2073 static inline struct keydata *check_and_rekey(time_t time)
2075 struct keydata *keyptr = &ip_keydata[ip_cnt&1];
2077 rmb();
2078 if (!keyptr->rekey_time || (time - keyptr->rekey_time) > REKEY_INTERVAL) {
2079 keyptr = __check_and_rekey(time);
2082 return keyptr;
2085 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
2086 __u32 secure_tcpv6_sequence_number(__u32 *saddr, __u32 *daddr,
2087 __u16 sport, __u16 dport)
2089 struct timeval tv;
2090 __u32 seq;
2091 __u32 hash[12];
2092 struct keydata *keyptr;
2094 /* The procedure is the same as for IPv4, but addresses are longer.
2095 * Thus we must use twothirdsMD4Transform.
2098 do_gettimeofday(&tv); /* We need the usecs below... */
2099 keyptr = check_and_rekey(tv.tv_sec);
2101 memcpy(hash, saddr, 16);
2102 hash[4]=(sport << 16) + dport;
2103 memcpy(&hash[5],keyptr->secret,sizeof(__u32)*7);
2105 seq = twothirdsMD4Transform(daddr, hash) & HASH_MASK;
2106 seq += keyptr->count;
2107 seq += tv.tv_usec + tv.tv_sec*1000000;
2109 return seq;
2111 EXPORT_SYMBOL(secure_tcpv6_sequence_number);
2113 __u32 secure_ipv6_id(__u32 *daddr)
2115 struct keydata *keyptr;
2117 keyptr = check_and_rekey(get_seconds());
2119 return halfMD4Transform(daddr, keyptr->secret);
2122 EXPORT_SYMBOL(secure_ipv6_id);
2123 #endif
2126 __u32 secure_tcp_sequence_number(__u32 saddr, __u32 daddr,
2127 __u16 sport, __u16 dport)
2129 struct timeval tv;
2130 __u32 seq;
2131 __u32 hash[4];
2132 struct keydata *keyptr;
2135 * Pick a random secret every REKEY_INTERVAL seconds.
2137 do_gettimeofday(&tv); /* We need the usecs below... */
2138 keyptr = check_and_rekey(tv.tv_sec);
2141 * Pick a unique starting offset for each TCP connection endpoints
2142 * (saddr, daddr, sport, dport).
2143 * Note that the words are placed into the starting vector, which is
2144 * then mixed with a partial MD4 over random data.
2146 hash[0]=saddr;
2147 hash[1]=daddr;
2148 hash[2]=(sport << 16) + dport;
2149 hash[3]=keyptr->secret[11];
2151 seq = halfMD4Transform(hash, keyptr->secret) & HASH_MASK;
2152 seq += keyptr->count;
2154 * As close as possible to RFC 793, which
2155 * suggests using a 250 kHz clock.
2156 * Further reading shows this assumes 2 Mb/s networks.
2157 * For 10 Mb/s Ethernet, a 1 MHz clock is appropriate.
2158 * That's funny, Linux has one built in! Use it!
2159 * (Networks are faster now - should this be increased?)
2161 seq += tv.tv_usec + tv.tv_sec*1000000;
2162 #if 0
2163 printk("init_seq(%lx, %lx, %d, %d) = %d\n",
2164 saddr, daddr, sport, dport, seq);
2165 #endif
2166 return seq;
2169 /* The code below is shamelessly stolen from secure_tcp_sequence_number().
2170 * All blames to Andrey V. Savochkin <saw@msu.ru>.
2172 __u32 secure_ip_id(__u32 daddr)
2174 struct keydata *keyptr;
2175 __u32 hash[4];
2177 keyptr = check_and_rekey(get_seconds());
2180 * Pick a unique starting offset for each IP destination.
2181 * The dest ip address is placed in the starting vector,
2182 * which is then hashed with random data.
2184 hash[0] = daddr;
2185 hash[1] = keyptr->secret[9];
2186 hash[2] = keyptr->secret[10];
2187 hash[3] = keyptr->secret[11];
2189 return halfMD4Transform(hash, keyptr->secret);
2192 #ifdef CONFIG_SYN_COOKIES
2194 * Secure SYN cookie computation. This is the algorithm worked out by
2195 * Dan Bernstein and Eric Schenk.
2197 * For linux I implement the 1 minute counter by looking at the jiffies clock.
2198 * The count is passed in as a parameter, so this code doesn't much care.
2201 #define COOKIEBITS 24 /* Upper bits store count */
2202 #define COOKIEMASK (((__u32)1 << COOKIEBITS) - 1)
2204 static int syncookie_init;
2205 static __u32 syncookie_secret[2][16-3+HASH_BUFFER_SIZE];
2207 __u32 secure_tcp_syn_cookie(__u32 saddr, __u32 daddr, __u16 sport,
2208 __u16 dport, __u32 sseq, __u32 count, __u32 data)
2210 __u32 tmp[16 + HASH_BUFFER_SIZE + HASH_EXTRA_SIZE];
2211 __u32 seq;
2214 * Pick two random secrets the first time we need a cookie.
2216 if (syncookie_init == 0) {
2217 get_random_bytes(syncookie_secret, sizeof(syncookie_secret));
2218 syncookie_init = 1;
2222 * Compute the secure sequence number.
2223 * The output should be:
2224 * HASH(sec1,saddr,sport,daddr,dport,sec1) + sseq + (count * 2^24)
2225 * + (HASH(sec2,saddr,sport,daddr,dport,count,sec2) % 2^24).
2226 * Where sseq is their sequence number and count increases every
2227 * minute by 1.
2228 * As an extra hack, we add a small "data" value that encodes the
2229 * MSS into the second hash value.
2232 memcpy(tmp+3, syncookie_secret[0], sizeof(syncookie_secret[0]));
2233 tmp[0]=saddr;
2234 tmp[1]=daddr;
2235 tmp[2]=(sport << 16) + dport;
2236 HASH_TRANSFORM(tmp+16, tmp);
2237 seq = tmp[17] + sseq + (count << COOKIEBITS);
2239 memcpy(tmp+3, syncookie_secret[1], sizeof(syncookie_secret[1]));
2240 tmp[0]=saddr;
2241 tmp[1]=daddr;
2242 tmp[2]=(sport << 16) + dport;
2243 tmp[3] = count; /* minute counter */
2244 HASH_TRANSFORM(tmp+16, tmp);
2246 /* Add in the second hash and the data */
2247 return seq + ((tmp[17] + data) & COOKIEMASK);
2251 * This retrieves the small "data" value from the syncookie.
2252 * If the syncookie is bad, the data returned will be out of
2253 * range. This must be checked by the caller.
2255 * The count value used to generate the cookie must be within
2256 * "maxdiff" if the current (passed-in) "count". The return value
2257 * is (__u32)-1 if this test fails.
2259 __u32 check_tcp_syn_cookie(__u32 cookie, __u32 saddr, __u32 daddr, __u16 sport,
2260 __u16 dport, __u32 sseq, __u32 count, __u32 maxdiff)
2262 __u32 tmp[16 + HASH_BUFFER_SIZE + HASH_EXTRA_SIZE];
2263 __u32 diff;
2265 if (syncookie_init == 0)
2266 return (__u32)-1; /* Well, duh! */
2268 /* Strip away the layers from the cookie */
2269 memcpy(tmp+3, syncookie_secret[0], sizeof(syncookie_secret[0]));
2270 tmp[0]=saddr;
2271 tmp[1]=daddr;
2272 tmp[2]=(sport << 16) + dport;
2273 HASH_TRANSFORM(tmp+16, tmp);
2274 cookie -= tmp[17] + sseq;
2275 /* Cookie is now reduced to (count * 2^24) ^ (hash % 2^24) */
2277 diff = (count - (cookie >> COOKIEBITS)) & ((__u32)-1 >> COOKIEBITS);
2278 if (diff >= maxdiff)
2279 return (__u32)-1;
2281 memcpy(tmp+3, syncookie_secret[1], sizeof(syncookie_secret[1]));
2282 tmp[0] = saddr;
2283 tmp[1] = daddr;
2284 tmp[2] = (sport << 16) + dport;
2285 tmp[3] = count - diff; /* minute counter */
2286 HASH_TRANSFORM(tmp+16, tmp);
2288 return (cookie - tmp[17]) & COOKIEMASK; /* Leaving the data behind */
2290 #endif
2294 EXPORT_SYMBOL(add_keyboard_randomness);
2295 EXPORT_SYMBOL(add_mouse_randomness);
2296 EXPORT_SYMBOL(add_interrupt_randomness);
2297 EXPORT_SYMBOL(add_disk_randomness);
2298 EXPORT_SYMBOL(batch_entropy_store);
2299 EXPORT_SYMBOL(generate_random_uuid);