Ok. I didn't make 2.4.0 in 2000. Tough. I tried, but we had some
[davej-history.git] / drivers / char / random.c
blobbbd5aff21e3a92fe987320ab31fa86c10d0670ac
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 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);
131 * void add_blkdev_randomness(int irq);
133 * add_keyboard_randomness() uses the inter-keypress timing, as well as the
134 * scancode as random inputs into the "entropy pool".
136 * add_mouse_randomness() uses the mouse interrupt timing, as well as
137 * the reported position of the mouse from the hardware.
139 * add_interrupt_randomness() uses the inter-interrupt timing as random
140 * inputs to the entropy pool. Note that not all interrupts are good
141 * sources of randomness! For example, the timer interrupts is not a
142 * good choice, because the periodicity of the interrupts is too
143 * regular, and hence predictable to an attacker. Disk interrupts are
144 * a better measure, since the timing of the disk interrupts are more
145 * unpredictable.
147 * add_blkdev_randomness() times the finishing time of block requests.
149 * All of these routines try to estimate how many bits of randomness a
150 * particular randomness source. They do this by keeping track of the
151 * first and second order deltas of the event timings.
153 * Ensuring unpredictability at system startup
154 * ============================================
156 * When any operating system starts up, it will go through a sequence
157 * of actions that are fairly predictable by an adversary, especially
158 * if the start-up does not involve interaction with a human operator.
159 * This reduces the actual number of bits of unpredictability in the
160 * entropy pool below the value in entropy_count. In order to
161 * counteract this effect, it helps to carry information in the
162 * entropy pool across shut-downs and start-ups. To do this, put the
163 * following lines an appropriate script which is run during the boot
164 * sequence:
166 * echo "Initializing random number generator..."
167 * random_seed=/var/run/random-seed
168 * # Carry a random seed from start-up to start-up
169 * # Load and then save 512 bytes, which is the size of the entropy pool
170 * if [ -f $random_seed ]; then
171 * cat $random_seed >/dev/urandom
172 * fi
173 * dd if=/dev/urandom of=$random_seed count=1
174 * chmod 600 $random_seed
176 * and the following lines in an appropriate script which is run as
177 * the system is shutdown:
179 * # Carry a random seed from shut-down to start-up
180 * # Save 512 bytes, which is the size of the entropy pool
181 * echo "Saving random seed..."
182 * random_seed=/var/run/random-seed
183 * dd if=/dev/urandom of=$random_seed count=1
184 * chmod 600 $random_seed
186 * For example, on most modern systems using the System V init
187 * scripts, such code fragments would be found in
188 * /etc/rc.d/init.d/random. On older Linux systems, the correct script
189 * location might be in /etc/rcb.d/rc.local or /etc/rc.d/rc.0.
191 * Effectively, these commands cause the contents of the entropy pool
192 * to be saved at shut-down time and reloaded into the entropy pool at
193 * start-up. (The 'dd' in the addition to the bootup script is to
194 * make sure that /etc/random-seed is different for every start-up,
195 * even if the system crashes without executing rc.0.) Even with
196 * complete knowledge of the start-up activities, predicting the state
197 * of the entropy pool requires knowledge of the previous history of
198 * the system.
200 * Configuring the /dev/random driver under Linux
201 * ==============================================
203 * The /dev/random driver under Linux uses minor numbers 8 and 9 of
204 * the /dev/mem major number (#1). So if your system does not have
205 * /dev/random and /dev/urandom created already, they can be created
206 * by using the commands:
208 * mknod /dev/random c 1 8
209 * mknod /dev/urandom c 1 9
211 * Acknowledgements:
212 * =================
214 * Ideas for constructing this random number generator were derived
215 * from Pretty Good Privacy's random number generator, and from private
216 * discussions with Phil Karn. Colin Plumb provided a faster random
217 * number generator, which speed up the mixing function of the entropy
218 * pool, taken from PGPfone. Dale Worley has also contributed many
219 * useful ideas and suggestions to improve this driver.
221 * Any flaws in the design are solely my responsibility, and should
222 * not be attributed to the Phil, Colin, or any of authors of PGP.
224 * The code for SHA transform was taken from Peter Gutmann's
225 * implementation, which has been placed in the public domain.
226 * The code for MD5 transform was taken from Colin Plumb's
227 * implementation, which has been placed in the public domain.
228 * The MD5 cryptographic checksum was devised by Ronald Rivest, and is
229 * documented in RFC 1321, "The MD5 Message Digest Algorithm".
231 * Further background information on this topic may be obtained from
232 * RFC 1750, "Randomness Recommendations for Security", by Donald
233 * Eastlake, Steve Crocker, and Jeff Schiller.
236 #include <linux/utsname.h>
237 #include <linux/config.h>
238 #include <linux/module.h>
239 #include <linux/kernel.h>
240 #include <linux/major.h>
241 #include <linux/string.h>
242 #include <linux/fcntl.h>
243 #include <linux/malloc.h>
244 #include <linux/random.h>
245 #include <linux/poll.h>
246 #include <linux/init.h>
248 #include <asm/processor.h>
249 #include <asm/uaccess.h>
250 #include <asm/irq.h>
251 #include <asm/io.h>
254 * Configuration information
256 #define DEFAULT_POOL_SIZE 512
257 #define SECONDARY_POOL_SIZE 128
258 #define BATCH_ENTROPY_SIZE 256
259 #define USE_SHA
262 * The minimum number of bits of entropy before we wake up a read on
263 * /dev/random. Should always be at least 8, or at least 1 byte.
265 static int random_read_wakeup_thresh = 8;
268 * If the entropy count falls under this number of bits, then we
269 * should wake up processes which are selecting or polling on write
270 * access to /dev/random.
272 static int random_write_wakeup_thresh = 128;
275 * A pool of size POOLWORDS is stirred with a primitive polynomial
276 * of degree POOLWORDS over GF(2). The taps for various sizes are
277 * defined below. They are chosen to be evenly spaced (minimum RMS
278 * distance from evenly spaced; the numbers in the comments are a
279 * scaled squared error sum) except for the last tap, which is 1 to
280 * get the twisting happening as fast as possible.
282 static struct poolinfo {
283 int poolwords;
284 int tap1, tap2, tap3, tap4, tap5;
285 } poolinfo_table[] = {
286 /* x^2048 + x^1638 + x^1231 + x^819 + x^411 + x + 1 -- 115 */
287 { 2048, 1638, 1231, 819, 411, 1 },
289 /* x^1024 + x^817 + x^615 + x^412 + x^204 + x + 1 -- 290 */
290 { 1024, 817, 615, 412, 204, 1 },
292 #if 0 /* Alternate polynomial */
293 /* x^1024 + x^819 + x^616 + x^410 + x^207 + x^2 + 1 -- 115 */
294 { 1024, 819, 616, 410, 207, 2 },
295 #endif
297 /* x^512 + x^411 + x^308 + x^208 + x^104 + x + 1 -- 225 */
298 { 512, 411, 308, 208, 104, 1 },
300 #if 0 /* Alternates */
301 /* x^512 + x^409 + x^307 + x^206 + x^102 + x^2 + 1 -- 95 */
302 { 512, 409, 307, 206, 102, 2 },
303 /* x^512 + x^409 + x^309 + x^205 + x^103 + x^2 + 1 -- 95 */
304 { 512, 409, 309, 205, 103, 2 },
305 #endif
307 /* x^256 + x^205 + x^155 + x^101 + x^52 + x + 1 -- 125 */
308 { 256, 205, 155, 101, 52, 1 },
310 /* x^128 + x^103 + x^76 + x^51 +x^25 + x + 1 -- 105 */
311 { 128, 103, 76, 51, 25, 1 },
313 #if 0 /* Alternate polynomial */
314 /* x^128 + x^103 + x^78 + x^51 + x^27 + x^2 + 1 -- 70 */
315 { 128, 103, 78, 51, 27, 2 },
316 #endif
318 /* x^64 + x^52 + x^39 + x^26 + x^14 + x + 1 -- 15 */
319 { 64, 52, 39, 26, 14, 1 },
321 /* x^32 + x^26 + x^20 + x^14 + x^7 + x + 1 -- 15 */
322 { 32, 26, 20, 14, 7, 1 },
324 { 0, 0, 0, 0, 0, 0 },
328 * For the purposes of better mixing, we use the CRC-32 polynomial as
329 * well to make a twisted Generalized Feedback Shift Reigster
331 * (See M. Matsumoto & Y. Kurita, 1992. Twisted GFSR generators. ACM
332 * Transactions on Modeling and Computer Simulation 2(3):179-194.
333 * Also see M. Matsumoto & Y. Kurita, 1994. Twisted GFSR generators
334 * II. ACM Transactions on Mdeling and Computer Simulation 4:254-266)
336 * Thanks to Colin Plumb for suggesting this.
338 * We have not analyzed the resultant polynomial to prove it primitive;
339 * in fact it almost certainly isn't. Nonetheless, the irreducible factors
340 * of a random large-degree polynomial over GF(2) are more than large enough
341 * that periodicity is not a concern.
343 * The input hash is much less sensitive than the output hash. All
344 * that we want of it is that it be a good non-cryptographic hash;
345 * i.e. it not produce collisions when fed "random" data of the sort
346 * we expect to see. As long as the pool state differs for different
347 * inputs, we have preserved the input entropy and done a good job.
348 * The fact that an intelligent attacker can construct inputs that
349 * will produce controlled alterations to the pool's state is not
350 * important because we don't consider such inputs to contribute any
351 * randomness. The only property we need with respect to them is that
352 * the attacker can't increase his/her knowledge of the pool's state.
353 * Since all additions are reversible (knowing the final state and the
354 * input, you can reconstruct the initial state), if an attacker has
355 * any uncertainty about the initial state, he/she can only shuffle
356 * that uncertainty about, but never cause any collisions (which would
357 * decrease the uncertainty).
359 * The chosen system lets the state of the pool be (essentially) the input
360 * modulo the generator polymnomial. Now, for random primitive polynomials,
361 * this is a universal class of hash functions, meaning that the chance
362 * of a collision is limited by the attacker's knowledge of the generator
363 * polynomail, so if it is chosen at random, an attacker can never force
364 * a collision. Here, we use a fixed polynomial, but we *can* assume that
365 * ###--> it is unknown to the processes generating the input entropy. <-###
366 * Because of this important property, this is a good, collision-resistant
367 * hash; hash collisions will occur no more often than chance.
371 * Linux 2.2 compatibility
373 #ifndef DECLARE_WAITQUEUE
374 #define DECLARE_WAITQUEUE(WAIT, PTR) struct wait_queue WAIT = { PTR, NULL }
375 #endif
376 #ifndef DECLARE_WAIT_QUEUE_HEAD
377 #define DECLARE_WAIT_QUEUE_HEAD(WAIT) struct wait_queue *WAIT
378 #endif
381 * Static global variables
383 static struct entropy_store *random_state; /* The default global store */
384 static struct entropy_store *sec_random_state; /* secondary store */
385 static DECLARE_WAIT_QUEUE_HEAD(random_read_wait);
386 static DECLARE_WAIT_QUEUE_HEAD(random_write_wait);
389 * Forward procedure declarations
391 #ifdef CONFIG_SYSCTL
392 static void sysctl_init_random(struct entropy_store *random_state);
393 #endif
395 /*****************************************************************
397 * Utility functions, with some ASM defined functions for speed
398 * purposes
400 *****************************************************************/
402 #ifndef MIN
403 #define MIN(a,b) (((a) < (b)) ? (a) : (b))
404 #endif
407 * Unfortunately, while the GCC optimizer for the i386 understands how
408 * to optimize a static rotate left of x bits, it doesn't know how to
409 * deal with a variable rotate of x bits. So we use a bit of asm magic.
411 #if (!defined (__i386__))
412 extern inline __u32 rotate_left(int i, __u32 word)
414 return (word << i) | (word >> (32 - i));
417 #else
418 extern inline __u32 rotate_left(int i, __u32 word)
420 __asm__("roll %%cl,%0"
421 :"=r" (word)
422 :"0" (word),"c" (i));
423 return word;
425 #endif
428 * More asm magic....
430 * For entropy estimation, we need to do an integral base 2
431 * logarithm.
433 * Note the "12bits" suffix - this is used for numbers between
434 * 0 and 4095 only. This allows a few shortcuts.
436 #if 0 /* Slow but clear version */
437 static inline __u32 int_ln_12bits(__u32 word)
439 __u32 nbits = 0;
441 while (word >>= 1)
442 nbits++;
443 return nbits;
445 #else /* Faster (more clever) version, courtesy Colin Plumb */
446 static inline __u32 int_ln_12bits(__u32 word)
448 /* Smear msbit right to make an n-bit mask */
449 word |= word >> 8;
450 word |= word >> 4;
451 word |= word >> 2;
452 word |= word >> 1;
453 /* Remove one bit to make this a logarithm */
454 word >>= 1;
455 /* Count the bits set in the word */
456 word -= (word >> 1) & 0x555;
457 word = (word & 0x333) + ((word >> 2) & 0x333);
458 word += (word >> 4);
459 word += (word >> 8);
460 return word & 15;
462 #endif
464 /**********************************************************************
466 * OS independent entropy store. Here are the functions which handle
467 * storing entropy in an entropy pool.
469 **********************************************************************/
471 struct entropy_store {
472 unsigned add_ptr;
473 int entropy_count;
474 int input_rotate;
475 int extract_count;
476 struct poolinfo poolinfo;
477 __u32 *pool;
481 * Initialize the entropy store. The input argument is the size of
482 * the random pool.
484 * Returns an negative error if there is a problem.
486 static int create_entropy_store(int size, struct entropy_store **ret_bucket)
488 struct entropy_store *r;
489 struct poolinfo *p;
490 int poolwords;
492 poolwords = (size + 3) / 4; /* Convert bytes->words */
493 /* The pool size must be a multiple of 16 32-bit words */
494 poolwords = ((poolwords + 15) / 16) * 16;
496 for (p = poolinfo_table; p->poolwords; p++) {
497 if (poolwords == p->poolwords)
498 break;
500 if (p->poolwords == 0)
501 return -EINVAL;
503 r = kmalloc(sizeof(struct entropy_store), GFP_KERNEL);
504 if (!r)
505 return -ENOMEM;
507 memset (r, 0, sizeof(struct entropy_store));
508 r->poolinfo = *p;
510 r->pool = kmalloc(poolwords*4, GFP_KERNEL);
511 if (!r->pool) {
512 kfree(r);
513 return -ENOMEM;
515 memset(r->pool, 0, poolwords*4);
516 *ret_bucket = r;
517 return 0;
520 /* Clear the entropy pool and associated counters. */
521 static void clear_entropy_store(struct entropy_store *r)
523 r->add_ptr = 0;
524 r->entropy_count = 0;
525 r->input_rotate = 0;
526 r->extract_count = 0;
527 memset(r->pool, 0, r->poolinfo.poolwords*4);
530 static void free_entropy_store(struct entropy_store *r)
532 if (r->pool)
533 kfree(r->pool);
534 kfree(r);
538 * This function adds a byte into the entropy "pool". It does not
539 * update the entropy estimate. The caller should call
540 * credit_entropy_store if this is appropriate.
542 * The pool is stirred with a primitive polynomial of the appropriate
543 * degree, and then twisted. We twist by three bits at a time because
544 * it's cheap to do so and helps slightly in the expected case where
545 * the entropy is concentrated in the low-order bits.
547 static void add_entropy_words(struct entropy_store *r, const __u32 *in,
548 int num)
550 static __u32 const twist_table[8] = {
551 0, 0x3b6e20c8, 0x76dc4190, 0x4db26158,
552 0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278 };
553 unsigned i;
554 int new_rotate;
555 __u32 w;
557 while (num--) {
558 w = rotate_left(r->input_rotate, *in);
559 i = r->add_ptr = (r->add_ptr - 1) & (r->poolinfo.poolwords-1);
561 * Normally, we add 7 bits of rotation to the pool.
562 * At the beginning of the pool, add an extra 7 bits
563 * rotation, so that successive passes spread the
564 * input bits across the pool evenly.
566 new_rotate = r->input_rotate + 14;
567 if (i)
568 new_rotate = r->input_rotate + 7;
569 r->input_rotate = new_rotate & 31;
571 /* XOR in the various taps */
572 w ^= r->pool[(i+r->poolinfo.tap1)&(r->poolinfo.poolwords-1)];
573 w ^= r->pool[(i+r->poolinfo.tap2)&(r->poolinfo.poolwords-1)];
574 w ^= r->pool[(i+r->poolinfo.tap3)&(r->poolinfo.poolwords-1)];
575 w ^= r->pool[(i+r->poolinfo.tap4)&(r->poolinfo.poolwords-1)];
576 w ^= r->pool[(i+r->poolinfo.tap5)&(r->poolinfo.poolwords-1)];
577 w ^= r->pool[i];
578 r->pool[i] = (w >> 3) ^ twist_table[w & 7];
583 * Credit (or debit) the entropy store with n bits of entropy
585 static void credit_entropy_store(struct entropy_store *r, int num)
587 int max_entropy = r->poolinfo.poolwords*32;
589 if (r->entropy_count + num < 0)
590 r->entropy_count = 0;
591 else if (r->entropy_count + num > max_entropy)
592 r->entropy_count = max_entropy;
593 else
594 r->entropy_count = r->entropy_count + num;
597 /**********************************************************************
599 * Entropy batch input management
601 * We batch entropy to be added to avoid increasing interrupt latency
603 **********************************************************************/
605 static __u32 *batch_entropy_pool;
606 static int *batch_entropy_credit;
607 static int batch_max;
608 static int batch_head, batch_tail;
609 static struct tq_struct batch_tqueue;
610 static void batch_entropy_process(void *private_);
612 /* note: the size must be a power of 2 */
613 static int batch_entropy_init(int size, struct entropy_store *r)
615 batch_entropy_pool = kmalloc(2*size*sizeof(__u32), GFP_KERNEL);
616 if (!batch_entropy_pool)
617 return -1;
618 batch_entropy_credit =kmalloc(size*sizeof(int), GFP_KERNEL);
619 if (!batch_entropy_credit) {
620 kfree(batch_entropy_pool);
621 return -1;
623 batch_head = batch_tail = 0;
624 batch_max = size;
625 batch_tqueue.routine = batch_entropy_process;
626 batch_tqueue.data = r;
627 return 0;
630 void batch_entropy_store(u32 a, u32 b, int num)
632 int new;
634 if (!batch_max)
635 return;
637 batch_entropy_pool[2*batch_head] = a;
638 batch_entropy_pool[(2*batch_head) + 1] = b;
639 batch_entropy_credit[batch_head] = num;
641 new = (batch_head+1) & (batch_max-1);
642 if (new != batch_tail) {
643 queue_task(&batch_tqueue, &tq_timer);
644 batch_head = new;
645 } else {
646 #if 0
647 printk(KERN_NOTICE "random: batch entropy buffer full\n");
648 #endif
652 static void batch_entropy_process(void *private_)
654 int num = 0;
655 int max_entropy;
656 struct entropy_store *r = (struct entropy_store *) private_, *p;
658 if (!batch_max)
659 return;
661 max_entropy = r->poolinfo.poolwords*32;
662 while (batch_head != batch_tail) {
663 add_entropy_words(r, batch_entropy_pool + 2*batch_tail, 2);
664 p = r;
665 if (r->entropy_count > max_entropy && (num & 1))
666 r = sec_random_state;
667 credit_entropy_store(r, batch_entropy_credit[batch_tail]);
668 batch_tail = (batch_tail+1) & (batch_max-1);
669 num++;
671 if (r->entropy_count >= random_read_wakeup_thresh)
672 wake_up_interruptible(&random_read_wait);
675 /*********************************************************************
677 * Entropy input management
679 *********************************************************************/
681 /* There is one of these per entropy source */
682 struct timer_rand_state {
683 __u32 last_time;
684 __s32 last_delta,last_delta2;
685 int dont_count_entropy:1;
688 static struct timer_rand_state keyboard_timer_state;
689 static struct timer_rand_state mouse_timer_state;
690 static struct timer_rand_state extract_timer_state;
691 static struct timer_rand_state *irq_timer_state[NR_IRQS];
692 static struct timer_rand_state *blkdev_timer_state[MAX_BLKDEV];
695 * This function adds entropy to the entropy "pool" by using timing
696 * delays. It uses the timer_rand_state structure to make an estimate
697 * of how many bits of entropy this call has added to the pool.
699 * The number "num" is also added to the pool - it should somehow describe
700 * the type of event which just happened. This is currently 0-255 for
701 * keyboard scan codes, and 256 upwards for interrupts.
702 * On the i386, this is assumed to be at most 16 bits, and the high bits
703 * are used for a high-resolution timer.
706 static void add_timer_randomness(struct timer_rand_state *state, unsigned num)
708 __u32 time;
709 __s32 delta, delta2, delta3;
710 int entropy = 0;
712 #if defined (__i386__)
713 if ( test_bit(X86_FEATURE_TSC, &boot_cpu_data.x86_capability) ) {
714 __u32 high;
715 __asm__(".byte 0x0f,0x31"
716 :"=a" (time), "=d" (high));
717 num ^= high;
718 } else {
719 time = jiffies;
721 #else
722 time = jiffies;
723 #endif
726 * Calculate number of bits of randomness we probably added.
727 * We take into account the first, second and third-order deltas
728 * in order to make our estimate.
730 if (!state->dont_count_entropy) {
731 delta = time - state->last_time;
732 state->last_time = time;
734 delta2 = delta - state->last_delta;
735 state->last_delta = delta;
737 delta3 = delta2 - state->last_delta2;
738 state->last_delta2 = delta2;
740 if (delta < 0)
741 delta = -delta;
742 if (delta2 < 0)
743 delta2 = -delta2;
744 if (delta3 < 0)
745 delta3 = -delta3;
746 if (delta > delta2)
747 delta = delta2;
748 if (delta > delta3)
749 delta = delta3;
752 * delta is now minimum absolute delta.
753 * Round down by 1 bit on general principles,
754 * and limit entropy entimate to 12 bits.
756 delta >>= 1;
757 delta &= (1 << 12) - 1;
759 entropy = int_ln_12bits(delta);
761 batch_entropy_store(num, time, entropy);
764 void add_keyboard_randomness(unsigned char scancode)
766 static unsigned char last_scancode;
767 /* ignore autorepeat (multiple key down w/o key up) */
768 if (scancode != last_scancode) {
769 last_scancode = scancode;
770 add_timer_randomness(&keyboard_timer_state, scancode);
774 void add_mouse_randomness(__u32 mouse_data)
776 add_timer_randomness(&mouse_timer_state, mouse_data);
779 void add_interrupt_randomness(int irq)
781 if (irq >= NR_IRQS || irq_timer_state[irq] == 0)
782 return;
784 add_timer_randomness(irq_timer_state[irq], 0x100+irq);
787 void add_blkdev_randomness(int major)
789 if (major >= MAX_BLKDEV)
790 return;
792 if (blkdev_timer_state[major] == 0) {
793 rand_initialize_blkdev(major, GFP_ATOMIC);
794 if (blkdev_timer_state[major] == 0)
795 return;
798 add_timer_randomness(blkdev_timer_state[major], 0x200+major);
801 /******************************************************************
803 * Hash function definition
805 *******************************************************************/
808 * This chunk of code defines a function
809 * void HASH_TRANSFORM(__u32 digest[HASH_BUFFER_SIZE + HASH_EXTRA_SIZE],
810 * __u32 const data[16])
812 * The function hashes the input data to produce a digest in the first
813 * HASH_BUFFER_SIZE words of the digest[] array, and uses HASH_EXTRA_SIZE
814 * more words for internal purposes. (This buffer is exported so the
815 * caller can wipe it once rather than this code doing it each call,
816 * and tacking it onto the end of the digest[] array is the quick and
817 * dirty way of doing it.)
819 * It so happens that MD5 and SHA share most of the initial vector
820 * used to initialize the digest[] array before the first call:
821 * 1) 0x67452301
822 * 2) 0xefcdab89
823 * 3) 0x98badcfe
824 * 4) 0x10325476
825 * 5) 0xc3d2e1f0 (SHA only)
827 * For /dev/random purposes, the length of the data being hashed is
828 * fixed in length, so appending a bit count in the usual way is not
829 * cryptographically necessary.
832 #ifdef USE_SHA
834 #define HASH_BUFFER_SIZE 5
835 #define HASH_EXTRA_SIZE 80
836 #define HASH_TRANSFORM SHATransform
838 /* Various size/speed tradeoffs are available. Choose 0..3. */
839 #define SHA_CODE_SIZE 0
842 * SHA transform algorithm, taken from code written by Peter Gutmann,
843 * and placed in the public domain.
846 /* The SHA f()-functions. */
848 #define f1(x,y,z) ( z ^ (x & (y^z)) ) /* Rounds 0-19: x ? y : z */
849 #define f2(x,y,z) (x ^ y ^ z) /* Rounds 20-39: XOR */
850 #define f3(x,y,z) ( (x & y) + (z & (x ^ y)) ) /* Rounds 40-59: majority */
851 #define f4(x,y,z) (x ^ y ^ z) /* Rounds 60-79: XOR */
853 /* The SHA Mysterious Constants */
855 #define K1 0x5A827999L /* Rounds 0-19: sqrt(2) * 2^30 */
856 #define K2 0x6ED9EBA1L /* Rounds 20-39: sqrt(3) * 2^30 */
857 #define K3 0x8F1BBCDCL /* Rounds 40-59: sqrt(5) * 2^30 */
858 #define K4 0xCA62C1D6L /* Rounds 60-79: sqrt(10) * 2^30 */
860 #define ROTL(n,X) ( ( ( X ) << n ) | ( ( X ) >> ( 32 - n ) ) )
862 #define subRound(a, b, c, d, e, f, k, data) \
863 ( e += ROTL( 5, a ) + f( b, c, d ) + k + data, b = ROTL( 30, b ) )
866 static void SHATransform(__u32 digest[85], __u32 const data[16])
868 __u32 A, B, C, D, E; /* Local vars */
869 __u32 TEMP;
870 int i;
871 #define W (digest + HASH_BUFFER_SIZE) /* Expanded data array */
874 * Do the preliminary expansion of 16 to 80 words. Doing it
875 * out-of-line line this is faster than doing it in-line on
876 * register-starved machines like the x86, and not really any
877 * slower on real processors.
879 memcpy(W, data, 16*sizeof(__u32));
880 for (i = 0; i < 64; i++) {
881 TEMP = W[i] ^ W[i+2] ^ W[i+8] ^ W[i+13];
882 W[i+16] = ROTL(1, TEMP);
885 /* Set up first buffer and local data buffer */
886 A = digest[ 0 ];
887 B = digest[ 1 ];
888 C = digest[ 2 ];
889 D = digest[ 3 ];
890 E = digest[ 4 ];
892 /* Heavy mangling, in 4 sub-rounds of 20 iterations each. */
893 #if SHA_CODE_SIZE == 0
895 * Approximately 50% of the speed of the largest version, but
896 * takes up 1/16 the space. Saves about 6k on an i386 kernel.
898 for (i = 0; i < 80; i++) {
899 if (i < 40) {
900 if (i < 20)
901 TEMP = f1(B, C, D) + K1;
902 else
903 TEMP = f2(B, C, D) + K2;
904 } else {
905 if (i < 60)
906 TEMP = f3(B, C, D) + K3;
907 else
908 TEMP = f4(B, C, D) + K4;
910 TEMP += ROTL(5, A) + E + W[i];
911 E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
913 #elif SHA_CODE_SIZE == 1
914 for (i = 0; i < 20; i++) {
915 TEMP = f1(B, C, D) + K1 + ROTL(5, A) + E + W[i];
916 E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
918 for (; i < 40; i++) {
919 TEMP = f2(B, C, D) + K2 + ROTL(5, A) + E + W[i];
920 E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
922 for (; i < 60; i++) {
923 TEMP = f3(B, C, D) + K3 + ROTL(5, A) + E + W[i];
924 E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
926 for (; i < 80; i++) {
927 TEMP = f4(B, C, D) + K4 + ROTL(5, A) + E + W[i];
928 E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
930 #elif SHA_CODE_SIZE == 2
931 for (i = 0; i < 20; i += 5) {
932 subRound( A, B, C, D, E, f1, K1, W[ i ] );
933 subRound( E, A, B, C, D, f1, K1, W[ i+1 ] );
934 subRound( D, E, A, B, C, f1, K1, W[ i+2 ] );
935 subRound( C, D, E, A, B, f1, K1, W[ i+3 ] );
936 subRound( B, C, D, E, A, f1, K1, W[ i+4 ] );
938 for (; i < 40; i += 5) {
939 subRound( A, B, C, D, E, f2, K2, W[ i ] );
940 subRound( E, A, B, C, D, f2, K2, W[ i+1 ] );
941 subRound( D, E, A, B, C, f2, K2, W[ i+2 ] );
942 subRound( C, D, E, A, B, f2, K2, W[ i+3 ] );
943 subRound( B, C, D, E, A, f2, K2, W[ i+4 ] );
945 for (; i < 60; i += 5) {
946 subRound( A, B, C, D, E, f3, K3, W[ i ] );
947 subRound( E, A, B, C, D, f3, K3, W[ i+1 ] );
948 subRound( D, E, A, B, C, f3, K3, W[ i+2 ] );
949 subRound( C, D, E, A, B, f3, K3, W[ i+3 ] );
950 subRound( B, C, D, E, A, f3, K3, W[ i+4 ] );
952 for (; i < 80; i += 5) {
953 subRound( A, B, C, D, E, f4, K4, W[ i ] );
954 subRound( E, A, B, C, D, f4, K4, W[ i+1 ] );
955 subRound( D, E, A, B, C, f4, K4, W[ i+2 ] );
956 subRound( C, D, E, A, B, f4, K4, W[ i+3 ] );
957 subRound( B, C, D, E, A, f4, K4, W[ i+4 ] );
959 #elif SHA_CODE_SIZE == 3 /* Really large version */
960 subRound( A, B, C, D, E, f1, K1, W[ 0 ] );
961 subRound( E, A, B, C, D, f1, K1, W[ 1 ] );
962 subRound( D, E, A, B, C, f1, K1, W[ 2 ] );
963 subRound( C, D, E, A, B, f1, K1, W[ 3 ] );
964 subRound( B, C, D, E, A, f1, K1, W[ 4 ] );
965 subRound( A, B, C, D, E, f1, K1, W[ 5 ] );
966 subRound( E, A, B, C, D, f1, K1, W[ 6 ] );
967 subRound( D, E, A, B, C, f1, K1, W[ 7 ] );
968 subRound( C, D, E, A, B, f1, K1, W[ 8 ] );
969 subRound( B, C, D, E, A, f1, K1, W[ 9 ] );
970 subRound( A, B, C, D, E, f1, K1, W[ 10 ] );
971 subRound( E, A, B, C, D, f1, K1, W[ 11 ] );
972 subRound( D, E, A, B, C, f1, K1, W[ 12 ] );
973 subRound( C, D, E, A, B, f1, K1, W[ 13 ] );
974 subRound( B, C, D, E, A, f1, K1, W[ 14 ] );
975 subRound( A, B, C, D, E, f1, K1, W[ 15 ] );
976 subRound( E, A, B, C, D, f1, K1, W[ 16 ] );
977 subRound( D, E, A, B, C, f1, K1, W[ 17 ] );
978 subRound( C, D, E, A, B, f1, K1, W[ 18 ] );
979 subRound( B, C, D, E, A, f1, K1, W[ 19 ] );
981 subRound( A, B, C, D, E, f2, K2, W[ 20 ] );
982 subRound( E, A, B, C, D, f2, K2, W[ 21 ] );
983 subRound( D, E, A, B, C, f2, K2, W[ 22 ] );
984 subRound( C, D, E, A, B, f2, K2, W[ 23 ] );
985 subRound( B, C, D, E, A, f2, K2, W[ 24 ] );
986 subRound( A, B, C, D, E, f2, K2, W[ 25 ] );
987 subRound( E, A, B, C, D, f2, K2, W[ 26 ] );
988 subRound( D, E, A, B, C, f2, K2, W[ 27 ] );
989 subRound( C, D, E, A, B, f2, K2, W[ 28 ] );
990 subRound( B, C, D, E, A, f2, K2, W[ 29 ] );
991 subRound( A, B, C, D, E, f2, K2, W[ 30 ] );
992 subRound( E, A, B, C, D, f2, K2, W[ 31 ] );
993 subRound( D, E, A, B, C, f2, K2, W[ 32 ] );
994 subRound( C, D, E, A, B, f2, K2, W[ 33 ] );
995 subRound( B, C, D, E, A, f2, K2, W[ 34 ] );
996 subRound( A, B, C, D, E, f2, K2, W[ 35 ] );
997 subRound( E, A, B, C, D, f2, K2, W[ 36 ] );
998 subRound( D, E, A, B, C, f2, K2, W[ 37 ] );
999 subRound( C, D, E, A, B, f2, K2, W[ 38 ] );
1000 subRound( B, C, D, E, A, f2, K2, W[ 39 ] );
1002 subRound( A, B, C, D, E, f3, K3, W[ 40 ] );
1003 subRound( E, A, B, C, D, f3, K3, W[ 41 ] );
1004 subRound( D, E, A, B, C, f3, K3, W[ 42 ] );
1005 subRound( C, D, E, A, B, f3, K3, W[ 43 ] );
1006 subRound( B, C, D, E, A, f3, K3, W[ 44 ] );
1007 subRound( A, B, C, D, E, f3, K3, W[ 45 ] );
1008 subRound( E, A, B, C, D, f3, K3, W[ 46 ] );
1009 subRound( D, E, A, B, C, f3, K3, W[ 47 ] );
1010 subRound( C, D, E, A, B, f3, K3, W[ 48 ] );
1011 subRound( B, C, D, E, A, f3, K3, W[ 49 ] );
1012 subRound( A, B, C, D, E, f3, K3, W[ 50 ] );
1013 subRound( E, A, B, C, D, f3, K3, W[ 51 ] );
1014 subRound( D, E, A, B, C, f3, K3, W[ 52 ] );
1015 subRound( C, D, E, A, B, f3, K3, W[ 53 ] );
1016 subRound( B, C, D, E, A, f3, K3, W[ 54 ] );
1017 subRound( A, B, C, D, E, f3, K3, W[ 55 ] );
1018 subRound( E, A, B, C, D, f3, K3, W[ 56 ] );
1019 subRound( D, E, A, B, C, f3, K3, W[ 57 ] );
1020 subRound( C, D, E, A, B, f3, K3, W[ 58 ] );
1021 subRound( B, C, D, E, A, f3, K3, W[ 59 ] );
1023 subRound( A, B, C, D, E, f4, K4, W[ 60 ] );
1024 subRound( E, A, B, C, D, f4, K4, W[ 61 ] );
1025 subRound( D, E, A, B, C, f4, K4, W[ 62 ] );
1026 subRound( C, D, E, A, B, f4, K4, W[ 63 ] );
1027 subRound( B, C, D, E, A, f4, K4, W[ 64 ] );
1028 subRound( A, B, C, D, E, f4, K4, W[ 65 ] );
1029 subRound( E, A, B, C, D, f4, K4, W[ 66 ] );
1030 subRound( D, E, A, B, C, f4, K4, W[ 67 ] );
1031 subRound( C, D, E, A, B, f4, K4, W[ 68 ] );
1032 subRound( B, C, D, E, A, f4, K4, W[ 69 ] );
1033 subRound( A, B, C, D, E, f4, K4, W[ 70 ] );
1034 subRound( E, A, B, C, D, f4, K4, W[ 71 ] );
1035 subRound( D, E, A, B, C, f4, K4, W[ 72 ] );
1036 subRound( C, D, E, A, B, f4, K4, W[ 73 ] );
1037 subRound( B, C, D, E, A, f4, K4, W[ 74 ] );
1038 subRound( A, B, C, D, E, f4, K4, W[ 75 ] );
1039 subRound( E, A, B, C, D, f4, K4, W[ 76 ] );
1040 subRound( D, E, A, B, C, f4, K4, W[ 77 ] );
1041 subRound( C, D, E, A, B, f4, K4, W[ 78 ] );
1042 subRound( B, C, D, E, A, f4, K4, W[ 79 ] );
1043 #else
1044 #error Illegal SHA_CODE_SIZE
1045 #endif
1047 /* Build message digest */
1048 digest[ 0 ] += A;
1049 digest[ 1 ] += B;
1050 digest[ 2 ] += C;
1051 digest[ 3 ] += D;
1052 digest[ 4 ] += E;
1054 /* W is wiped by the caller */
1055 #undef W
1058 #undef ROTL
1059 #undef f1
1060 #undef f2
1061 #undef f3
1062 #undef f4
1063 #undef K1
1064 #undef K2
1065 #undef K3
1066 #undef K4
1067 #undef subRound
1069 #else /* !USE_SHA - Use MD5 */
1071 #define HASH_BUFFER_SIZE 4
1072 #define HASH_EXTRA_SIZE 0
1073 #define HASH_TRANSFORM MD5Transform
1076 * MD5 transform algorithm, taken from code written by Colin Plumb,
1077 * and put into the public domain
1080 /* The four core functions - F1 is optimized somewhat */
1082 /* #define F1(x, y, z) (x & y | ~x & z) */
1083 #define F1(x, y, z) (z ^ (x & (y ^ z)))
1084 #define F2(x, y, z) F1(z, x, y)
1085 #define F3(x, y, z) (x ^ y ^ z)
1086 #define F4(x, y, z) (y ^ (x | ~z))
1088 /* This is the central step in the MD5 algorithm. */
1089 #define MD5STEP(f, w, x, y, z, data, s) \
1090 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
1093 * The core of the MD5 algorithm, this alters an existing MD5 hash to
1094 * reflect the addition of 16 longwords of new data. MD5Update blocks
1095 * the data and converts bytes into longwords for this routine.
1097 static void MD5Transform(__u32 buf[HASH_BUFFER_SIZE], __u32 const in[16])
1099 __u32 a, b, c, d;
1101 a = buf[0];
1102 b = buf[1];
1103 c = buf[2];
1104 d = buf[3];
1106 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
1107 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
1108 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
1109 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
1110 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
1111 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
1112 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
1113 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
1114 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
1115 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
1116 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
1117 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
1118 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
1119 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
1120 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
1121 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
1123 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
1124 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
1125 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
1126 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
1127 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
1128 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
1129 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
1130 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
1131 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
1132 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
1133 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
1134 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
1135 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
1136 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
1137 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
1138 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
1140 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
1141 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
1142 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
1143 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
1144 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
1145 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
1146 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
1147 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
1148 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
1149 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
1150 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
1151 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
1152 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
1153 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
1154 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
1155 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
1157 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
1158 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
1159 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
1160 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
1161 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
1162 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
1163 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
1164 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
1165 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
1166 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
1167 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
1168 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
1169 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
1170 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
1171 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
1172 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
1174 buf[0] += a;
1175 buf[1] += b;
1176 buf[2] += c;
1177 buf[3] += d;
1180 #undef F1
1181 #undef F2
1182 #undef F3
1183 #undef F4
1184 #undef MD5STEP
1186 #endif /* !USE_SHA */
1188 /*********************************************************************
1190 * Entropy extraction routines
1192 *********************************************************************/
1194 #define EXTRACT_ENTROPY_USER 1
1195 #define EXTRACT_ENTROPY_SECONDARY 2
1196 #define TMP_BUF_SIZE (HASH_BUFFER_SIZE + HASH_EXTRA_SIZE)
1197 #define SEC_XFER_SIZE (TMP_BUF_SIZE*4)
1199 static ssize_t extract_entropy(struct entropy_store *r, void * buf,
1200 size_t nbytes, int flags);
1203 * This utility inline function is responsible for transfering entropy
1204 * from the primary pool to the secondary extraction pool. We pull
1205 * randomness under two conditions; one is if there isn't enough entropy
1206 * in the secondary pool. The other is after we have extract 1024 bytes,
1207 * at which point we do a "catastrophic reseeding".
1209 static inline void xfer_secondary_pool(struct entropy_store *r,
1210 size_t nbytes)
1212 __u32 tmp[TMP_BUF_SIZE];
1214 if (r->entropy_count < nbytes*8) {
1215 extract_entropy(random_state, tmp, sizeof(tmp), 0);
1216 add_entropy_words(r, tmp, TMP_BUF_SIZE);
1217 credit_entropy_store(r, TMP_BUF_SIZE*8);
1219 if (r->extract_count > 1024) {
1220 extract_entropy(random_state, tmp, sizeof(tmp), 0);
1221 add_entropy_words(r, tmp, TMP_BUF_SIZE);
1222 r->extract_count = 0;
1227 * This function extracts randomness from the "entropy pool", and
1228 * returns it in a buffer. This function computes how many remaining
1229 * bits of entropy are left in the pool, but it does not restrict the
1230 * number of bytes that are actually obtained. If the EXTRACT_ENTROPY_USER
1231 * flag is given, then the buf pointer is assumed to be in user space.
1232 * If the EXTRACT_ENTROPY_SECONDARY flag is given, then this function will
1234 * Note: extract_entropy() assumes that POOLWORDS is a multiple of 16 words.
1236 static ssize_t extract_entropy(struct entropy_store *r, void * buf,
1237 size_t nbytes, int flags)
1239 ssize_t ret, i;
1240 __u32 tmp[TMP_BUF_SIZE];
1241 __u32 x;
1243 add_timer_randomness(&extract_timer_state, nbytes);
1245 /* Redundant, but just in case... */
1246 if (r->entropy_count > r->poolinfo.poolwords)
1247 r->entropy_count = r->poolinfo.poolwords;
1249 if (flags & EXTRACT_ENTROPY_SECONDARY)
1250 xfer_secondary_pool(r, nbytes);
1252 if (r->entropy_count / 8 >= nbytes)
1253 r->entropy_count -= nbytes*8;
1254 else
1255 r->entropy_count = 0;
1257 if (r->entropy_count < random_write_wakeup_thresh)
1258 wake_up_interruptible(&random_write_wait);
1260 r->extract_count += nbytes;
1262 ret = 0;
1263 while (nbytes) {
1265 * Check if we need to break out or reschedule....
1267 if ((flags & EXTRACT_ENTROPY_USER) && current->need_resched) {
1268 if (signal_pending(current)) {
1269 if (ret == 0)
1270 ret = -ERESTARTSYS;
1271 break;
1273 schedule();
1276 /* Hash the pool to get the output */
1277 tmp[0] = 0x67452301;
1278 tmp[1] = 0xefcdab89;
1279 tmp[2] = 0x98badcfe;
1280 tmp[3] = 0x10325476;
1281 #ifdef USE_SHA
1282 tmp[4] = 0xc3d2e1f0;
1283 #endif
1285 * As we hash the pool, we mix intermediate values of
1286 * the hash back into the pool. This eliminates
1287 * backtracking attacks (where the attacker knows
1288 * the state of the pool plus the current outputs, and
1289 * attempts to find previous ouputs), unless the hash
1290 * function can be inverted.
1292 for (i = 0, x = 0; i < r->poolinfo.poolwords; i += 16, x+=2) {
1293 HASH_TRANSFORM(tmp, r->pool+i);
1294 add_entropy_words(r, &tmp[x%HASH_BUFFER_SIZE], 1);
1298 * In case the hash function has some recognizable
1299 * output pattern, we fold it in half.
1301 for (i = 0; i < HASH_BUFFER_SIZE/2; i++)
1302 tmp[i] ^= tmp[i + (HASH_BUFFER_SIZE+1)/2];
1303 #if HASH_BUFFER_SIZE & 1 /* There's a middle word to deal with */
1304 x = tmp[HASH_BUFFER_SIZE/2];
1305 x ^= (x >> 16); /* Fold it in half */
1306 ((__u16 *)tmp)[HASH_BUFFER_SIZE-1] = (__u16)x;
1307 #endif
1309 /* Copy data to destination buffer */
1310 i = MIN(nbytes, HASH_BUFFER_SIZE*sizeof(__u32)/2);
1311 if (flags & EXTRACT_ENTROPY_USER) {
1312 i -= copy_to_user(buf, (__u8 const *)tmp, i);
1313 if (!i) {
1314 ret = -EFAULT;
1315 break;
1317 } else
1318 memcpy(buf, (__u8 const *)tmp, i);
1319 nbytes -= i;
1320 buf += i;
1321 ret += i;
1322 add_timer_randomness(&extract_timer_state, nbytes);
1325 /* Wipe data just returned from memory */
1326 memset(tmp, 0, sizeof(tmp));
1328 return ret;
1332 * This function is the exported kernel interface. It returns some
1333 * number of good random numbers, suitable for seeding TCP sequence
1334 * numbers, etc.
1336 void get_random_bytes(void *buf, int nbytes)
1338 if (sec_random_state)
1339 extract_entropy(sec_random_state, (char *) buf, nbytes,
1340 EXTRACT_ENTROPY_SECONDARY);
1341 else if (random_state)
1342 extract_entropy(random_state, (char *) buf, nbytes, 0);
1343 else
1344 printk(KERN_NOTICE "get_random_bytes called before "
1345 "random driver initialization\n");
1348 /*********************************************************************
1350 * Functions to interface with Linux
1352 *********************************************************************/
1355 * Initialize the random pool with standard stuff.
1357 * NOTE: This is an OS-dependent function.
1359 static void init_std_data(struct entropy_store *r)
1361 struct timeval tv;
1362 __u32 words[2];
1363 char *p;
1364 int i;
1366 do_gettimeofday(&tv);
1367 words[0] = tv.tv_sec;
1368 words[1] = tv.tv_usec;
1369 add_entropy_words(r, words, 2);
1372 * This doesn't lock system.utsname. However, we are generating
1373 * entropy so a race with a name set here is fine.
1375 p = (char *) &system_utsname;
1376 for (i = sizeof(system_utsname) / sizeof(words); i; i--) {
1377 memcpy(words, p, sizeof(words));
1378 add_entropy_words(r, words, sizeof(words)/4);
1379 p += sizeof(words);
1383 void __init rand_initialize(void)
1385 int i;
1387 if (create_entropy_store(DEFAULT_POOL_SIZE, &random_state))
1388 return; /* Error, return */
1389 if (batch_entropy_init(BATCH_ENTROPY_SIZE, random_state))
1390 return; /* Error, return */
1391 if (create_entropy_store(SECONDARY_POOL_SIZE, &sec_random_state))
1392 return; /* Error, return */
1393 clear_entropy_store(random_state);
1394 clear_entropy_store(sec_random_state);
1395 init_std_data(random_state);
1396 #ifdef CONFIG_SYSCTL
1397 sysctl_init_random(random_state);
1398 #endif
1399 for (i = 0; i < NR_IRQS; i++)
1400 irq_timer_state[i] = NULL;
1401 for (i = 0; i < MAX_BLKDEV; i++)
1402 blkdev_timer_state[i] = NULL;
1403 memset(&keyboard_timer_state, 0, sizeof(struct timer_rand_state));
1404 memset(&mouse_timer_state, 0, sizeof(struct timer_rand_state));
1405 memset(&extract_timer_state, 0, sizeof(struct timer_rand_state));
1406 extract_timer_state.dont_count_entropy = 1;
1409 void rand_initialize_irq(int irq)
1411 struct timer_rand_state *state;
1413 if (irq >= NR_IRQS || irq_timer_state[irq])
1414 return;
1417 * If kmalloc returns null, we just won't use that entropy
1418 * source.
1420 state = kmalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
1421 if (state) {
1422 memset(state, 0, sizeof(struct timer_rand_state));
1423 irq_timer_state[irq] = state;
1427 void rand_initialize_blkdev(int major, int mode)
1429 struct timer_rand_state *state;
1431 if (major >= MAX_BLKDEV || blkdev_timer_state[major])
1432 return;
1435 * If kmalloc returns null, we just won't use that entropy
1436 * source.
1438 state = kmalloc(sizeof(struct timer_rand_state), mode);
1439 if (state) {
1440 memset(state, 0, sizeof(struct timer_rand_state));
1441 blkdev_timer_state[major] = state;
1446 static ssize_t
1447 random_read(struct file * file, char * buf, size_t nbytes, loff_t *ppos)
1449 DECLARE_WAITQUEUE(wait, current);
1450 ssize_t n, retval = 0, count = 0;
1452 if (nbytes == 0)
1453 return 0;
1455 add_wait_queue(&random_read_wait, &wait);
1456 while (nbytes > 0) {
1457 set_current_state(TASK_INTERRUPTIBLE);
1459 n = nbytes;
1460 if (n > SEC_XFER_SIZE)
1461 n = SEC_XFER_SIZE;
1462 if (n > random_state->entropy_count / 8)
1463 n = random_state->entropy_count / 8;
1464 if (n == 0) {
1465 if (file->f_flags & O_NONBLOCK) {
1466 retval = -EAGAIN;
1467 break;
1469 if (signal_pending(current)) {
1470 retval = -ERESTARTSYS;
1471 break;
1473 schedule();
1474 continue;
1476 n = extract_entropy(sec_random_state, buf, n,
1477 EXTRACT_ENTROPY_USER |
1478 EXTRACT_ENTROPY_SECONDARY);
1479 if (n < 0) {
1480 retval = n;
1481 break;
1483 count += n;
1484 buf += n;
1485 nbytes -= n;
1486 break; /* This break makes the device work */
1487 /* like a named pipe */
1489 current->state = TASK_RUNNING;
1490 remove_wait_queue(&random_read_wait, &wait);
1493 * If we gave the user some bytes, update the access time.
1495 if (count != 0) {
1496 UPDATE_ATIME(file->f_dentry->d_inode);
1499 return (count ? count : retval);
1502 static ssize_t
1503 urandom_read(struct file * file, char * buf,
1504 size_t nbytes, loff_t *ppos)
1506 return extract_entropy(sec_random_state, buf, nbytes,
1507 EXTRACT_ENTROPY_USER |
1508 EXTRACT_ENTROPY_SECONDARY);
1511 static unsigned int
1512 random_poll(struct file *file, poll_table * wait)
1514 unsigned int mask;
1516 poll_wait(file, &random_read_wait, wait);
1517 poll_wait(file, &random_write_wait, wait);
1518 mask = 0;
1519 if (random_state->entropy_count >= random_read_wakeup_thresh)
1520 mask |= POLLIN | POLLRDNORM;
1521 if (random_state->entropy_count < random_write_wakeup_thresh)
1522 mask |= POLLOUT | POLLWRNORM;
1523 return mask;
1526 static ssize_t
1527 random_write(struct file * file, const char * buffer,
1528 size_t count, loff_t *ppos)
1530 int ret = 0;
1531 size_t bytes;
1532 __u32 buf[16];
1533 const char *p = buffer;
1534 size_t c = count;
1536 while (c > 0) {
1537 bytes = MIN(c, sizeof(buf));
1539 bytes -= copy_from_user(&buf, p, bytes);
1540 if (!bytes) {
1541 ret = -EFAULT;
1542 break;
1544 c -= bytes;
1545 p += bytes;
1547 /* Convert bytes to words */
1548 bytes = (bytes + 3) / sizeof(__u32);
1549 add_entropy_words(random_state, buf, bytes);
1551 if (p == buffer) {
1552 return (ssize_t)ret;
1553 } else {
1554 file->f_dentry->d_inode->i_mtime = CURRENT_TIME;
1555 mark_inode_dirty(file->f_dentry->d_inode);
1556 return (ssize_t)(p - buffer);
1560 static int
1561 random_ioctl(struct inode * inode, struct file * file,
1562 unsigned int cmd, unsigned long arg)
1564 int *p, size, ent_count;
1565 int retval;
1567 switch (cmd) {
1568 case RNDGETENTCNT:
1569 ent_count = random_state->entropy_count;
1570 if (put_user(ent_count, (int *) arg))
1571 return -EFAULT;
1572 return 0;
1573 case RNDADDTOENTCNT:
1574 if (!capable(CAP_SYS_ADMIN))
1575 return -EPERM;
1576 if (get_user(ent_count, (int *) arg))
1577 return -EFAULT;
1578 credit_entropy_store(random_state, ent_count);
1580 * Wake up waiting processes if we have enough
1581 * entropy.
1583 if (random_state->entropy_count >= random_read_wakeup_thresh)
1584 wake_up_interruptible(&random_read_wait);
1585 return 0;
1586 case RNDGETPOOL:
1587 if (!capable(CAP_SYS_ADMIN))
1588 return -EPERM;
1589 p = (int *) arg;
1590 ent_count = random_state->entropy_count;
1591 if (put_user(ent_count, p++))
1592 return -EFAULT;
1594 if (get_user(size, p))
1595 return -EFAULT;
1596 if (put_user(random_state->poolinfo.poolwords, p++))
1597 return -EFAULT;
1598 if (size < 0)
1599 return -EINVAL;
1600 if (size > random_state->poolinfo.poolwords)
1601 size = random_state->poolinfo.poolwords;
1602 if (copy_to_user(p, random_state->pool, size*sizeof(__u32)))
1603 return -EFAULT;
1604 return 0;
1605 case RNDADDENTROPY:
1606 if (!capable(CAP_SYS_ADMIN))
1607 return -EPERM;
1608 p = (int *) arg;
1609 if (get_user(ent_count, p++))
1610 return -EFAULT;
1611 if (ent_count < 0)
1612 return -EINVAL;
1613 if (get_user(size, p++))
1614 return -EFAULT;
1615 retval = random_write(file, (const char *) p,
1616 size, &file->f_pos);
1617 if (retval < 0)
1618 return retval;
1619 credit_entropy_store(random_state, ent_count);
1621 * Wake up waiting processes if we have enough
1622 * entropy.
1624 if (random_state->entropy_count >= random_read_wakeup_thresh)
1625 wake_up_interruptible(&random_read_wait);
1626 return 0;
1627 case RNDZAPENTCNT:
1628 if (!capable(CAP_SYS_ADMIN))
1629 return -EPERM;
1630 random_state->entropy_count = 0;
1631 return 0;
1632 case RNDCLEARPOOL:
1633 /* Clear the entropy pool and associated counters. */
1634 if (!capable(CAP_SYS_ADMIN))
1635 return -EPERM;
1636 clear_entropy_store(random_state);
1637 init_std_data(random_state);
1638 return 0;
1639 default:
1640 return -EINVAL;
1644 struct file_operations random_fops = {
1645 read: random_read,
1646 write: random_write,
1647 poll: random_poll,
1648 ioctl: random_ioctl,
1651 struct file_operations urandom_fops = {
1652 read: urandom_read,
1653 write: random_write,
1654 ioctl: random_ioctl,
1657 /***************************************************************
1658 * Random UUID interface
1660 * Used here for a Boot ID, but can be useful for other kernel
1661 * drivers.
1662 ***************************************************************/
1665 * Generate random UUID
1667 void generate_random_uuid(unsigned char uuid_out[16])
1669 get_random_bytes(uuid_out, 16);
1670 /* Set UUID version to 4 --- truely random generation */
1671 uuid_out[6] = (uuid_out[6] & 0x0F) | 0x40;
1672 /* Set the UUID variant to DCE */
1673 uuid_out[8] = (uuid_out[8] & 0x3F) | 0x80;
1676 /********************************************************************
1678 * Sysctl interface
1680 ********************************************************************/
1682 #ifdef CONFIG_SYSCTL
1684 #include <linux/sysctl.h>
1686 static int sysctl_poolsize;
1687 static int min_read_thresh, max_read_thresh;
1688 static int min_write_thresh, max_write_thresh;
1689 static char sysctl_bootid[16];
1692 * This function handles a request from the user to change the pool size
1693 * of the primary entropy store.
1695 static int change_poolsize(int poolsize)
1697 struct entropy_store *new_store, *old_store;
1698 int ret;
1700 if ((ret = create_entropy_store(poolsize, &new_store)))
1701 return ret;
1703 add_entropy_words(new_store, random_state->pool,
1704 random_state->poolinfo.poolwords);
1705 credit_entropy_store(new_store, random_state->entropy_count);
1707 sysctl_init_random(new_store);
1708 old_store = random_state;
1709 random_state = batch_tqueue.data = new_store;
1710 free_entropy_store(old_store);
1711 return 0;
1714 static int proc_do_poolsize(ctl_table *table, int write, struct file *filp,
1715 void *buffer, size_t *lenp)
1717 int ret;
1719 sysctl_poolsize = random_state->poolinfo.poolwords * 4;
1721 ret = proc_dointvec(table, write, filp, buffer, lenp);
1722 if (ret || !write ||
1723 (sysctl_poolsize == random_state->poolinfo.poolwords * 4))
1724 return ret;
1726 return change_poolsize(sysctl_poolsize);
1729 static int poolsize_strategy(ctl_table *table, int *name, int nlen,
1730 void *oldval, size_t *oldlenp,
1731 void *newval, size_t newlen, void **context)
1733 int len;
1735 sysctl_poolsize = random_state->poolinfo.poolwords * 4;
1738 * We only handle the write case, since the read case gets
1739 * handled by the default handler (and we don't care if the
1740 * write case happens twice; it's harmless).
1742 if (newval && newlen) {
1743 len = newlen;
1744 if (len > table->maxlen)
1745 len = table->maxlen;
1746 if (copy_from_user(table->data, newval, len))
1747 return -EFAULT;
1750 if (sysctl_poolsize != random_state->poolinfo.poolwords * 4)
1751 return change_poolsize(sysctl_poolsize);
1753 return 0;
1757 * These functions is used to return both the bootid UUID, and random
1758 * UUID. The difference is in whether table->data is NULL; if it is,
1759 * then a new UUID is generated and returned to the user.
1761 * If the user accesses this via the proc interface, it will be returned
1762 * as an ASCII string in the standard UUID format. If accesses via the
1763 * sysctl system call, it is returned as 16 bytes of binary data.
1765 static int proc_do_uuid(ctl_table *table, int write, struct file *filp,
1766 void *buffer, size_t *lenp)
1768 ctl_table fake_table;
1769 unsigned char buf[64], tmp_uuid[16], *uuid;
1771 uuid = table->data;
1772 if (!uuid) {
1773 uuid = tmp_uuid;
1774 uuid[8] = 0;
1776 if (uuid[8] == 0)
1777 generate_random_uuid(uuid);
1779 sprintf(buf, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
1780 "%02x%02x%02x%02x%02x%02x",
1781 uuid[0], uuid[1], uuid[2], uuid[3],
1782 uuid[4], uuid[5], uuid[6], uuid[7],
1783 uuid[8], uuid[9], uuid[10], uuid[11],
1784 uuid[12], uuid[13], uuid[14], uuid[15]);
1785 fake_table.data = buf;
1786 fake_table.maxlen = sizeof(buf);
1788 return proc_dostring(&fake_table, write, filp, buffer, lenp);
1791 static int uuid_strategy(ctl_table *table, int *name, int nlen,
1792 void *oldval, size_t *oldlenp,
1793 void *newval, size_t newlen, void **context)
1795 unsigned char tmp_uuid[16], *uuid;
1796 int len;
1798 if (!oldval || !oldlenp)
1799 return 1;
1801 uuid = table->data;
1802 if (!uuid) {
1803 uuid = tmp_uuid;
1804 uuid[8] = 0;
1806 if (uuid[8] == 0)
1807 generate_random_uuid(uuid);
1809 get_user(len, oldlenp);
1810 if (len) {
1811 if (len > 16)
1812 len = 16;
1813 if (copy_to_user(oldval, table->data, len))
1814 return -EFAULT;
1815 if (put_user(len, oldlenp))
1816 return -EFAULT;
1818 return 1;
1821 ctl_table random_table[] = {
1822 {RANDOM_POOLSIZE, "poolsize",
1823 &sysctl_poolsize, sizeof(int), 0644, NULL,
1824 &proc_do_poolsize, &poolsize_strategy},
1825 {RANDOM_ENTROPY_COUNT, "entropy_avail",
1826 NULL, sizeof(int), 0444, NULL,
1827 &proc_dointvec},
1828 {RANDOM_READ_THRESH, "read_wakeup_threshold",
1829 &random_read_wakeup_thresh, sizeof(int), 0644, NULL,
1830 &proc_dointvec_minmax, &sysctl_intvec, 0,
1831 &min_read_thresh, &max_read_thresh},
1832 {RANDOM_WRITE_THRESH, "write_wakeup_threshold",
1833 &random_write_wakeup_thresh, sizeof(int), 0644, NULL,
1834 &proc_dointvec_minmax, &sysctl_intvec, 0,
1835 &min_write_thresh, &max_write_thresh},
1836 {RANDOM_BOOT_ID, "boot_id",
1837 &sysctl_bootid, 16, 0444, NULL,
1838 &proc_do_uuid, &uuid_strategy},
1839 {RANDOM_UUID, "uuid",
1840 NULL, 16, 0444, NULL,
1841 &proc_do_uuid, &uuid_strategy},
1845 static void sysctl_init_random(struct entropy_store *random_state)
1847 min_read_thresh = 8;
1848 min_write_thresh = 0;
1849 max_read_thresh = max_write_thresh =
1850 random_state->poolinfo.poolwords * 32;
1851 random_table[1].data = &random_state->entropy_count;
1853 #endif /* CONFIG_SYSCTL */
1855 /********************************************************************
1857 * Random funtions for networking
1859 ********************************************************************/
1862 * TCP initial sequence number picking. This uses the random number
1863 * generator to pick an initial secret value. This value is hashed
1864 * along with the TCP endpoint information to provide a unique
1865 * starting point for each pair of TCP endpoints. This defeats
1866 * attacks which rely on guessing the initial TCP sequence number.
1867 * This algorithm was suggested by Steve Bellovin.
1869 * Using a very strong hash was taking an appreciable amount of the total
1870 * TCP connection establishment time, so this is a weaker hash,
1871 * compensated for by changing the secret periodically.
1874 /* F, G and H are basic MD4 functions: selection, majority, parity */
1875 #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
1876 #define G(x, y, z) (((x) & (y)) + (((x) ^ (y)) & (z)))
1877 #define H(x, y, z) ((x) ^ (y) ^ (z))
1880 * The generic round function. The application is so specific that
1881 * we don't bother protecting all the arguments with parens, as is generally
1882 * good macro practice, in favor of extra legibility.
1883 * Rotation is separate from addition to prevent recomputation
1885 #define ROUND(f, a, b, c, d, x, s) \
1886 (a += f(b, c, d) + x, a = (a << s) | (a >> (32-s)))
1887 #define K1 0
1888 #define K2 013240474631UL
1889 #define K3 015666365641UL
1892 * Basic cut-down MD4 transform. Returns only 32 bits of result.
1894 static __u32 halfMD4Transform (__u32 const buf[4], __u32 const in[8])
1896 __u32 a = buf[0], b = buf[1], c = buf[2], d = buf[3];
1898 /* Round 1 */
1899 ROUND(F, a, b, c, d, in[0] + K1, 3);
1900 ROUND(F, d, a, b, c, in[1] + K1, 7);
1901 ROUND(F, c, d, a, b, in[2] + K1, 11);
1902 ROUND(F, b, c, d, a, in[3] + K1, 19);
1903 ROUND(F, a, b, c, d, in[4] + K1, 3);
1904 ROUND(F, d, a, b, c, in[5] + K1, 7);
1905 ROUND(F, c, d, a, b, in[6] + K1, 11);
1906 ROUND(F, b, c, d, a, in[7] + K1, 19);
1908 /* Round 2 */
1909 ROUND(G, a, b, c, d, in[1] + K2, 3);
1910 ROUND(G, d, a, b, c, in[3] + K2, 5);
1911 ROUND(G, c, d, a, b, in[5] + K2, 9);
1912 ROUND(G, b, c, d, a, in[7] + K2, 13);
1913 ROUND(G, a, b, c, d, in[0] + K2, 3);
1914 ROUND(G, d, a, b, c, in[2] + K2, 5);
1915 ROUND(G, c, d, a, b, in[4] + K2, 9);
1916 ROUND(G, b, c, d, a, in[6] + K2, 13);
1918 /* Round 3 */
1919 ROUND(H, a, b, c, d, in[3] + K3, 3);
1920 ROUND(H, d, a, b, c, in[7] + K3, 9);
1921 ROUND(H, c, d, a, b, in[2] + K3, 11);
1922 ROUND(H, b, c, d, a, in[6] + K3, 15);
1923 ROUND(H, a, b, c, d, in[1] + K3, 3);
1924 ROUND(H, d, a, b, c, in[5] + K3, 9);
1925 ROUND(H, c, d, a, b, in[0] + K3, 11);
1926 ROUND(H, b, c, d, a, in[4] + K3, 15);
1928 return buf[1] + b; /* "most hashed" word */
1929 /* Alternative: return sum of all words? */
1932 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
1934 static __u32 twothirdsMD4Transform (__u32 const buf[4], __u32 const in[12])
1936 __u32 a = buf[0], b = buf[1], c = buf[2], d = buf[3];
1938 /* Round 1 */
1939 ROUND(F, a, b, c, d, in[ 0] + K1, 3);
1940 ROUND(F, d, a, b, c, in[ 1] + K1, 7);
1941 ROUND(F, c, d, a, b, in[ 2] + K1, 11);
1942 ROUND(F, b, c, d, a, in[ 3] + K1, 19);
1943 ROUND(F, a, b, c, d, in[ 4] + K1, 3);
1944 ROUND(F, d, a, b, c, in[ 5] + K1, 7);
1945 ROUND(F, c, d, a, b, in[ 6] + K1, 11);
1946 ROUND(F, b, c, d, a, in[ 7] + K1, 19);
1947 ROUND(F, a, b, c, d, in[ 8] + K1, 3);
1948 ROUND(F, d, a, b, c, in[ 9] + K1, 7);
1949 ROUND(F, c, d, a, b, in[10] + K1, 11);
1950 ROUND(F, b, c, d, a, in[11] + K1, 19);
1952 /* Round 2 */
1953 ROUND(G, a, b, c, d, in[ 1] + K2, 3);
1954 ROUND(G, d, a, b, c, in[ 3] + K2, 5);
1955 ROUND(G, c, d, a, b, in[ 5] + K2, 9);
1956 ROUND(G, b, c, d, a, in[ 7] + K2, 13);
1957 ROUND(G, a, b, c, d, in[ 9] + K2, 3);
1958 ROUND(G, d, a, b, c, in[11] + K2, 5);
1959 ROUND(G, c, d, a, b, in[ 0] + K2, 9);
1960 ROUND(G, b, c, d, a, in[ 2] + K2, 13);
1961 ROUND(G, a, b, c, d, in[ 4] + K2, 3);
1962 ROUND(G, d, a, b, c, in[ 6] + K2, 5);
1963 ROUND(G, c, d, a, b, in[ 8] + K2, 9);
1964 ROUND(G, b, c, d, a, in[10] + K2, 13);
1966 /* Round 3 */
1967 ROUND(H, a, b, c, d, in[ 3] + K3, 3);
1968 ROUND(H, d, a, b, c, in[ 7] + K3, 9);
1969 ROUND(H, c, d, a, b, in[11] + K3, 11);
1970 ROUND(H, b, c, d, a, in[ 2] + K3, 15);
1971 ROUND(H, a, b, c, d, in[ 6] + K3, 3);
1972 ROUND(H, d, a, b, c, in[10] + K3, 9);
1973 ROUND(H, c, d, a, b, in[ 1] + K3, 11);
1974 ROUND(H, b, c, d, a, in[ 5] + K3, 15);
1975 ROUND(H, a, b, c, d, in[ 9] + K3, 3);
1976 ROUND(H, d, a, b, c, in[ 0] + K3, 9);
1977 ROUND(H, c, d, a, b, in[ 4] + K3, 11);
1978 ROUND(H, b, c, d, a, in[ 8] + K3, 15);
1980 return buf[1] + b; /* "most hashed" word */
1981 /* Alternative: return sum of all words? */
1983 #endif
1985 #undef ROUND
1986 #undef F
1987 #undef G
1988 #undef H
1989 #undef K1
1990 #undef K2
1991 #undef K3
1993 /* This should not be decreased so low that ISNs wrap too fast. */
1994 #define REKEY_INTERVAL 300
1995 #define HASH_BITS 24
1997 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
1998 __u32 secure_tcpv6_sequence_number(__u32 *saddr, __u32 *daddr,
1999 __u16 sport, __u16 dport)
2001 static __u32 rekey_time;
2002 static __u32 count;
2003 static __u32 secret[12];
2004 struct timeval tv;
2005 __u32 seq;
2007 /* The procedure is the same as for IPv4, but addresses are longer. */
2009 do_gettimeofday(&tv); /* We need the usecs below... */
2011 if (!rekey_time || (tv.tv_sec - rekey_time) > REKEY_INTERVAL) {
2012 rekey_time = tv.tv_sec;
2013 /* First five words are overwritten below. */
2014 get_random_bytes(&secret[5], sizeof(secret)-5*4);
2015 count = (tv.tv_sec/REKEY_INTERVAL) << HASH_BITS;
2018 memcpy(secret, saddr, 16);
2019 secret[4]=(sport << 16) + dport;
2021 seq = (twothirdsMD4Transform(daddr, secret) &
2022 ((1<<HASH_BITS)-1)) + count;
2024 seq += tv.tv_usec + tv.tv_sec*1000000;
2025 return seq;
2028 __u32 secure_ipv6_id(__u32 *daddr)
2030 static time_t rekey_time;
2031 static __u32 secret[12];
2032 time_t t;
2035 * Pick a random secret every REKEY_INTERVAL seconds.
2037 t = CURRENT_TIME;
2038 if (!rekey_time || (t - rekey_time) > REKEY_INTERVAL) {
2039 rekey_time = t;
2040 /* First word is overwritten below. */
2041 get_random_bytes(secret, sizeof(secret));
2044 return twothirdsMD4Transform(daddr, secret);
2047 #endif
2050 __u32 secure_tcp_sequence_number(__u32 saddr, __u32 daddr,
2051 __u16 sport, __u16 dport)
2053 static __u32 rekey_time;
2054 static __u32 count;
2055 static __u32 secret[12];
2056 struct timeval tv;
2057 __u32 seq;
2060 * Pick a random secret every REKEY_INTERVAL seconds.
2062 do_gettimeofday(&tv); /* We need the usecs below... */
2064 if (!rekey_time || (tv.tv_sec - rekey_time) > REKEY_INTERVAL) {
2065 rekey_time = tv.tv_sec;
2066 /* First three words are overwritten below. */
2067 get_random_bytes(&secret[3], sizeof(secret)-12);
2068 count = (tv.tv_sec/REKEY_INTERVAL) << HASH_BITS;
2072 * Pick a unique starting offset for each TCP connection endpoints
2073 * (saddr, daddr, sport, dport).
2074 * Note that the words are placed into the first words to be
2075 * mixed in with the halfMD4. This is because the starting
2076 * vector is also a random secret (at secret+8), and further
2077 * hashing fixed data into it isn't going to improve anything,
2078 * so we should get started with the variable data.
2080 secret[0]=saddr;
2081 secret[1]=daddr;
2082 secret[2]=(sport << 16) + dport;
2084 seq = (halfMD4Transform(secret+8, secret) &
2085 ((1<<HASH_BITS)-1)) + count;
2088 * As close as possible to RFC 793, which
2089 * suggests using a 250 kHz clock.
2090 * Further reading shows this assumes 2 Mb/s networks.
2091 * For 10 Mb/s Ethernet, a 1 MHz clock is appropriate.
2092 * That's funny, Linux has one built in! Use it!
2093 * (Networks are faster now - should this be increased?)
2095 seq += tv.tv_usec + tv.tv_sec*1000000;
2096 #if 0
2097 printk("init_seq(%lx, %lx, %d, %d) = %d\n",
2098 saddr, daddr, sport, dport, seq);
2099 #endif
2100 return seq;
2103 /* The code below is shamelessly stolen from secure_tcp_sequence_number().
2104 * All blames to Andrey V. Savochkin <saw@msu.ru>.
2106 __u32 secure_ip_id(__u32 daddr)
2108 static time_t rekey_time;
2109 static __u32 secret[12];
2110 time_t t;
2113 * Pick a random secret every REKEY_INTERVAL seconds.
2115 t = CURRENT_TIME;
2116 if (!rekey_time || (t - rekey_time) > REKEY_INTERVAL) {
2117 rekey_time = t;
2118 /* First word is overwritten below. */
2119 get_random_bytes(secret+1, sizeof(secret)-4);
2123 * Pick a unique starting offset for each IP destination.
2124 * Note that the words are placed into the first words to be
2125 * mixed in with the halfMD4. This is because the starting
2126 * vector is also a random secret (at secret+8), and further
2127 * hashing fixed data into it isn't going to improve anything,
2128 * so we should get started with the variable data.
2130 secret[0]=daddr;
2132 return halfMD4Transform(secret+8, secret);
2135 #ifdef CONFIG_SYN_COOKIES
2137 * Secure SYN cookie computation. This is the algorithm worked out by
2138 * Dan Bernstein and Eric Schenk.
2140 * For linux I implement the 1 minute counter by looking at the jiffies clock.
2141 * The count is passed in as a parameter, so this code doesn't much care.
2144 #define COOKIEBITS 24 /* Upper bits store count */
2145 #define COOKIEMASK (((__u32)1 << COOKIEBITS) - 1)
2147 static int syncookie_init;
2148 static __u32 syncookie_secret[2][16-3+HASH_BUFFER_SIZE];
2150 __u32 secure_tcp_syn_cookie(__u32 saddr, __u32 daddr, __u16 sport,
2151 __u16 dport, __u32 sseq, __u32 count, __u32 data)
2153 __u32 tmp[16 + HASH_BUFFER_SIZE + HASH_EXTRA_SIZE];
2154 __u32 seq;
2157 * Pick two random secrets the first time we need a cookie.
2159 if (syncookie_init == 0) {
2160 get_random_bytes(syncookie_secret, sizeof(syncookie_secret));
2161 syncookie_init = 1;
2165 * Compute the secure sequence number.
2166 * The output should be:
2167 * HASH(sec1,saddr,sport,daddr,dport,sec1) + sseq + (count * 2^24)
2168 * + (HASH(sec2,saddr,sport,daddr,dport,count,sec2) % 2^24).
2169 * Where sseq is their sequence number and count increases every
2170 * minute by 1.
2171 * As an extra hack, we add a small "data" value that encodes the
2172 * MSS into the second hash value.
2175 memcpy(tmp+3, syncookie_secret[0], sizeof(syncookie_secret[0]));
2176 tmp[0]=saddr;
2177 tmp[1]=daddr;
2178 tmp[2]=(sport << 16) + dport;
2179 HASH_TRANSFORM(tmp+16, tmp);
2180 seq = tmp[17] + sseq + (count << COOKIEBITS);
2182 memcpy(tmp+3, syncookie_secret[1], sizeof(syncookie_secret[1]));
2183 tmp[0]=saddr;
2184 tmp[1]=daddr;
2185 tmp[2]=(sport << 16) + dport;
2186 tmp[3] = count; /* minute counter */
2187 HASH_TRANSFORM(tmp+16, tmp);
2189 /* Add in the second hash and the data */
2190 return seq + ((tmp[17] + data) & COOKIEMASK);
2194 * This retrieves the small "data" value from the syncookie.
2195 * If the syncookie is bad, the data returned will be out of
2196 * range. This must be checked by the caller.
2198 * The count value used to generate the cookie must be within
2199 * "maxdiff" if the current (passed-in) "count". The return value
2200 * is (__u32)-1 if this test fails.
2202 __u32 check_tcp_syn_cookie(__u32 cookie, __u32 saddr, __u32 daddr, __u16 sport,
2203 __u16 dport, __u32 sseq, __u32 count, __u32 maxdiff)
2205 __u32 tmp[16 + HASH_BUFFER_SIZE + HASH_EXTRA_SIZE];
2206 __u32 diff;
2208 if (syncookie_init == 0)
2209 return (__u32)-1; /* Well, duh! */
2211 /* Strip away the layers from the cookie */
2212 memcpy(tmp+3, syncookie_secret[0], sizeof(syncookie_secret[0]));
2213 tmp[0]=saddr;
2214 tmp[1]=daddr;
2215 tmp[2]=(sport << 16) + dport;
2216 HASH_TRANSFORM(tmp+16, tmp);
2217 cookie -= tmp[17] + sseq;
2218 /* Cookie is now reduced to (count * 2^24) ^ (hash % 2^24) */
2220 diff = (count - (cookie >> COOKIEBITS)) & ((__u32)-1 >> COOKIEBITS);
2221 if (diff >= maxdiff)
2222 return (__u32)-1;
2224 memcpy(tmp+3, syncookie_secret[1], sizeof(syncookie_secret[1]));
2225 tmp[0] = saddr;
2226 tmp[1] = daddr;
2227 tmp[2] = (sport << 16) + dport;
2228 tmp[3] = count - diff; /* minute counter */
2229 HASH_TRANSFORM(tmp+16, tmp);
2231 return (cookie - tmp[17]) & COOKIEMASK; /* Leaving the data behind */
2233 #endif
2237 EXPORT_SYMBOL(add_keyboard_randomness);
2238 EXPORT_SYMBOL(add_mouse_randomness);
2239 EXPORT_SYMBOL(add_interrupt_randomness);
2240 EXPORT_SYMBOL(add_blkdev_randomness);
2241 EXPORT_SYMBOL(batch_entropy_store);