Import 2.3.16
[davej-history.git] / drivers / char / random.c
blobb0e3c2357fce0cedda1c38a0d917a80e482b5e62
1 /*
2 * random.c -- A strong random number generator
4 * Version 1.88, last modified 30-Aug-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 to
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/kernel.h>
239 #include <linux/major.h>
240 #include <linux/string.h>
241 #include <linux/fcntl.h>
242 #include <linux/malloc.h>
243 #include <linux/random.h>
244 #include <linux/poll.h>
245 #include <linux/init.h>
247 #include <asm/processor.h>
248 #include <asm/uaccess.h>
249 #include <asm/irq.h>
250 #include <asm/io.h>
253 * Configuration information
255 #define DEFAULT_POOL_SIZE 512
256 #define SECONDARY_POOL_SIZE 128
257 #define BATCH_ENTROPY_SIZE 256
258 #define USE_SHA
261 * The minimum number of bits of entropy before we wake up a read on
262 * /dev/random. Should always be at least 8, or at least 1 byte.
264 static int random_read_wakeup_thresh = 8;
267 * If the entropy count falls under this number of bits, then we
268 * should wake up processes which are selecting or polling on write
269 * access to /dev/random.
271 static int random_write_wakeup_thresh = 128;
274 * A pool of size POOLWORDS is stirred with a primitive polynomial
275 * of degree POOLWORDS over GF(2). The taps for various sizes are
276 * defined below. They are chosen to be evenly spaced (minimum RMS
277 * distance from evenly spaced; the numbers in the comments are a
278 * scaled squared error sum) except for the last tap, which is 1 to
279 * get the twisting happening as fast as possible.
281 static struct poolinfo {
282 int poolwords;
283 int tap1, tap2, tap3, tap4, tap5;
284 } poolinfo_table[] = {
285 /* x^2048 + x^1638 + x^1231 + x^819 + x^411 + x + 1 -- 115 */
286 { 2048, 1638, 1231, 819, 411, 1 },
288 /* x^1024 + x^817 + x^615 + x^412 + x^204 + x + 1 -- 290 */
289 { 1024, 817, 615, 412, 204, 1 },
291 #if 0 /* Alternate polynomial */
292 /* x^1024 + x^819 + x^616 + x^410 + x^207 + x^2 + 1 -- 115 */
293 { 1024, 819, 616, 410, 207, 2 },
294 #endif
296 /* x^512 + x^411 + x^308 + x^208 + x^104 + x + 1 -- 225 */
297 { 512, 411, 308, 208, 104, 1 },
299 #if 0 /* Alternates */
300 /* x^512 + x^409 + x^307 + x^206 + x^102 + x^2 + 1 -- 95 */
301 { 512, 409, 307, 206, 102, 2 },
302 /* x^512 + x^409 + x^309 + x^205 + x^103 + x^2 + 1 -- 95 */
303 { 512, 409, 309, 205, 103, 2 },
304 #endif
306 /* x^256 + x^205 + x^155 + x^101 + x^52 + x + 1 -- 125 */
307 { 256, 205, 155, 101, 52, 1 },
309 /* x^128 + x^103 + x^76 + x^51 +x^25 + x + 1 -- 105 */
310 { 128, 103, 76, 51, 25, 1 },
312 #if 0 /* Alternate polynomial */
313 /* x^128 + x^103 + x^78 + x^51 + x^27 + x^2 + 1 -- 70 */
314 { 128, 103, 78, 51, 27, 2 },
315 #endif
317 /* x^64 + x^52 + x^39 + x^26 + x^14 + x + 1 -- 15 */
318 { 64, 52, 39, 26, 14, 1 },
320 /* x^32 + x^26 + x^20 + x^14 + x^7 + x + 1 -- 15 */
321 { 32, 26, 20, 14, 7, 1 },
323 { 0, 0, 0, 0, 0, 0 },
327 * For the purposes of better mixing, we use the CRC-32 polynomial as
328 * well to make a twisted Generalized Feedback Shift Reigster
330 * (See M. Matsumoto & Y. Kurita, 1992. Twisted GFSR generators. ACM
331 * Transactions on Modeling and Computer Simulation 2(3):179-194.
332 * Also see M. Matsumoto & Y. Kurita, 1994. Twisted GFSR generators
333 * II. ACM Transactions on Mdeling and Computer Simulation 4:254-266)
335 * Thanks to Colin Plumb for suggesting this.
337 * We have not analyzed the resultant polynomial to prove it primitive;
338 * in fact it almost certainly isn't. Nonetheless, the irreducible factors
339 * of a random large-degree polynomial over GF(2) are more than large enough
340 * that periodicity is not a concern.
342 * The input hash is much less sensitive than the output hash. All
343 * that we want of it is that it be a good non-cryptographic hash;
344 * i.e. it not produce collisions when fed "random" data of the sort
345 * we expect to see. As long as the pool state differs for different
346 * inputs, we have preserved the input entropy and done a good job.
347 * The fact that an intelligent attacker can construct inputs that
348 * will produce controlled alterations to the pool's state is not
349 * important because we don't consider such inputs to contribute any
350 * randomness. The only property we need with respect to them is that
351 * the attacker can't increase his/her knowledge of the pool's state.
352 * Since all additions are reversible (knowing the final state and the
353 * input, you can reconstruct the initial state), if an attacker has
354 * any uncertainty about the initial state, he/she can only shuffle
355 * that uncertainty about, but never cause any collisions (which would
356 * decrease the uncertainty).
358 * The chosen system lets the state of the pool be (essentially) the input
359 * modulo the generator polymnomial. Now, for random primitive polynomials,
360 * this is a universal class of hash functions, meaning that the chance
361 * of a collision is limited by the attacker's knowledge of the generator
362 * polynomail, so if it is chosen at random, an attacker can never force
363 * a collision. Here, we use a fixed polynomial, but we *can* assume that
364 * ###--> it is unknown to the processes generating the input entropy. <-###
365 * Because of this important property, this is a good, collision-resistant
366 * hash; hash collisions will occur no more often than chance.
370 * Linux 2.2 compatibility
372 #ifndef DECLARE_WAITQUEUE
373 #define DECLARE_WAITQUEUE(WAIT, PTR) struct wait_queue WAIT = { PTR, NULL }
374 #endif
375 #ifndef DECLARE_WAIT_QUEUE_HEAD
376 #define DECLARE_WAIT_QUEUE_HEAD(WAIT) struct wait_queue *WAIT
377 #endif
380 * Static global variables
382 static struct entropy_store *random_state; /* The default global store */
383 static struct entropy_store *sec_random_state; /* secondary store */
384 static DECLARE_WAIT_QUEUE_HEAD(random_read_wait);
385 static DECLARE_WAIT_QUEUE_HEAD(random_write_wait);
388 * Forward procedure declarations
390 #ifdef CONFIG_SYSCTL
391 static void sysctl_init_random(struct entropy_store *random_state);
392 #endif
394 /*****************************************************************
396 * Utility functions, with some ASM defined functions for speed
397 * purposes
399 *****************************************************************/
401 #ifndef MIN
402 #define MIN(a,b) (((a) < (b)) ? (a) : (b))
403 #endif
406 * Unfortunately, while the GCC optimizer for the i386 understands how
407 * to optimize a static rotate left of x bits, it doesn't know how to
408 * deal with a variable rotate of x bits. So we use a bit of asm magic.
410 #if (!defined (__i386__))
411 extern inline __u32 rotate_left(int i, __u32 word)
413 return (word << i) | (word >> (32 - i));
416 #else
417 extern inline __u32 rotate_left(int i, __u32 word)
419 __asm__("roll %%cl,%0"
420 :"=r" (word)
421 :"0" (word),"c" (i));
422 return word;
424 #endif
427 * More asm magic....
429 * For entropy estimation, we need to do an integral base 2
430 * logarithm.
432 * Note the "12bits" suffix - this is used for numbers between
433 * 0 and 4095 only. This allows a few shortcuts.
435 #if 0 /* Slow but clear version */
436 static inline __u32 int_ln_12bits(__u32 word)
438 __u32 nbits = 0;
440 while (word >>= 1)
441 nbits++;
442 return nbits;
444 #else /* Faster (more clever) version, courtesy Colin Plumb */
445 static inline __u32 int_ln_12bits(__u32 word)
447 /* Smear msbit right to make an n-bit mask */
448 word |= word >> 8;
449 word |= word >> 4;
450 word |= word >> 2;
451 word |= word >> 1;
452 /* Remove one bit to make this a logarithm */
453 word >>= 1;
454 /* Count the bits set in the word */
455 word -= (word >> 1) & 0x555;
456 word = (word & 0x333) + ((word >> 2) & 0x333);
457 word += (word >> 4);
458 word += (word >> 8);
459 return word & 15;
461 #endif
463 /**********************************************************************
465 * OS independent entropy store. Here are the functions which handle
466 * storing entropy in an entropy pool.
468 **********************************************************************/
470 struct entropy_store {
471 unsigned add_ptr;
472 int entropy_count;
473 int input_rotate;
474 int extract_count;
475 struct poolinfo poolinfo;
476 __u32 *pool;
480 * Initialize the entropy store. The input argument is the size of
481 * the random pool.
483 * Returns an negative error if there is a problem.
485 static int create_entropy_store(int size, struct entropy_store **ret_bucket)
487 struct entropy_store *r;
488 struct poolinfo *p;
489 int poolwords;
491 poolwords = (size + 3) / 4; /* Convert bytes->words */
492 /* The pool size must be a multiple of 16 32-bit words */
493 poolwords = ((poolwords + 15) / 16) * 16;
495 for (p = poolinfo_table; p->poolwords; p++) {
496 if (poolwords == p->poolwords)
497 break;
499 if (p->poolwords == 0)
500 return -EINVAL;
502 r = kmalloc(sizeof(struct entropy_store), GFP_KERNEL);
503 if (!r)
504 return -ENOMEM;
506 memset (r, 0, sizeof(struct entropy_store));
507 r->poolinfo = *p;
509 r->pool = kmalloc(poolwords*4, GFP_KERNEL);
510 if (!r->pool) {
511 kfree_s(r, sizeof(struct entropy_store));
512 return -ENOMEM;
514 memset(r->pool, 0, poolwords*4);
515 *ret_bucket = r;
516 return 0;
519 /* Clear the entropy pool and associated counters. */
520 static void clear_entropy_store(struct entropy_store *r)
522 r->add_ptr = 0;
523 r->entropy_count = 0;
524 r->input_rotate = 0;
525 r->extract_count = 0;
526 memset(r->pool, 0, r->poolinfo.poolwords*4);
529 static void free_entropy_store(struct entropy_store *r)
531 if (r->pool)
532 kfree(r->pool);
533 kfree_s(r, sizeof(struct entropy_store));
537 * This function adds a byte into the entropy "pool". It does not
538 * update the entropy estimate. The caller should call
539 * credit_entropy_store if this is appropriate.
541 * The pool is stirred with a primitive polynomial of the appropriate
542 * degree, and then twisted. We twist by three bits at a time because
543 * it's cheap to do so and helps slightly in the expected case where
544 * the entropy is concentrated in the low-order bits.
546 static void add_entropy_words(struct entropy_store *r, const __u32 *in,
547 int num)
549 static __u32 const twist_table[8] = {
550 0, 0x3b6e20c8, 0x76dc4190, 0x4db26158,
551 0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278 };
552 unsigned i;
553 int new_rotate;
554 __u32 w;
556 while (num--) {
557 w = rotate_left(r->input_rotate, *in);
558 i = r->add_ptr = (r->add_ptr - 1) & (r->poolinfo.poolwords-1);
560 * Normally, we add 7 bits of rotation to the pool.
561 * At the beginning of the pool, add an extra 7 bits
562 * rotation, so that successive passes spread the
563 * input bits across the pool evenly.
565 new_rotate = r->input_rotate + 14;
566 if (i)
567 new_rotate = r->input_rotate + 7;
568 r->input_rotate = new_rotate & 31;
570 /* XOR in the various taps */
571 w ^= r->pool[(i+r->poolinfo.tap1)&(r->poolinfo.poolwords-1)];
572 w ^= r->pool[(i+r->poolinfo.tap2)&(r->poolinfo.poolwords-1)];
573 w ^= r->pool[(i+r->poolinfo.tap3)&(r->poolinfo.poolwords-1)];
574 w ^= r->pool[(i+r->poolinfo.tap4)&(r->poolinfo.poolwords-1)];
575 w ^= r->pool[(i+r->poolinfo.tap5)&(r->poolinfo.poolwords-1)];
576 w ^= r->pool[i];
577 r->pool[i] = (w >> 3) ^ twist_table[w & 7];
582 * Credit (or debit) the entropy store with n bits of entropy
584 static void credit_entropy_store(struct entropy_store *r, int num)
586 int max_entropy = r->poolinfo.poolwords*32;
588 if (r->entropy_count + num < 0)
589 r->entropy_count = 0;
590 else if (r->entropy_count + num > max_entropy)
591 r->entropy_count = max_entropy;
592 else
593 r->entropy_count = r->entropy_count + num;
596 /**********************************************************************
598 * Entropy batch input management
600 * We batch entropy to be added to avoid increasing interrupt latency
602 **********************************************************************/
604 static __u32 *batch_entropy_pool;
605 static int *batch_entropy_credit;
606 static int batch_max;
607 static int batch_head, batch_tail;
608 static struct tq_struct batch_tqueue;
609 static void batch_entropy_process(void *private_);
611 /* note: the size must be a power of 2 */
612 static int batch_entropy_init(int size, struct entropy_store *r)
614 batch_entropy_pool = kmalloc(2*size*sizeof(__u32), GFP_KERNEL);
615 if (!batch_entropy_pool)
616 return -1;
617 batch_entropy_credit =kmalloc(size*sizeof(int), GFP_KERNEL);
618 if (!batch_entropy_credit) {
619 kfree(batch_entropy_pool);
620 return -1;
622 batch_head = batch_tail = 0;
623 batch_max = size;
624 batch_tqueue.routine = batch_entropy_process;
625 batch_tqueue.data = r;
626 return 0;
629 static void batch_entropy_store(__u32 a, __u32 b, int num)
631 int new;
633 if (!batch_max)
634 return;
636 batch_entropy_pool[2*batch_head] = a;
637 batch_entropy_pool[(2*batch_head) + 1] = b;
638 batch_entropy_credit[batch_head] = num;
640 new = (batch_head+1) & (batch_max-1);
641 if (new != batch_tail) {
642 queue_task(&batch_tqueue, &tq_timer);
643 batch_head = new;
644 } else {
645 #if 0
646 printk(KERN_NOTICE "random: batch entropy buffer full\n");
647 #endif
651 static void batch_entropy_process(void *private_)
653 int num = 0;
654 int max_entropy;
655 struct entropy_store *r = (struct entropy_store *) private_, *p;
657 if (!batch_max)
658 return;
660 max_entropy = r->poolinfo.poolwords*32;
661 while (batch_head != batch_tail) {
662 add_entropy_words(r, batch_entropy_pool + 2*batch_tail, 2);
663 p = r;
664 if (r->entropy_count > max_entropy && (num & 1))
665 r = sec_random_state;
666 credit_entropy_store(r, batch_entropy_credit[batch_tail]);
667 batch_tail = (batch_tail+1) & (batch_max-1);
668 num++;
670 if (r->entropy_count >= random_read_wakeup_thresh)
671 wake_up_interruptible(&random_read_wait);
674 /*********************************************************************
676 * Entropy input management
678 *********************************************************************/
680 /* There is one of these per entropy source */
681 struct timer_rand_state {
682 __u32 last_time;
683 __s32 last_delta,last_delta2;
684 int dont_count_entropy:1;
687 static struct timer_rand_state keyboard_timer_state;
688 static struct timer_rand_state mouse_timer_state;
689 static struct timer_rand_state extract_timer_state;
690 static struct timer_rand_state *irq_timer_state[NR_IRQS];
691 static struct timer_rand_state *blkdev_timer_state[MAX_BLKDEV];
694 * This function adds entropy to the entropy "pool" by using timing
695 * delays. It uses the timer_rand_state structure to make an estimate
696 * of how many bits of entropy this call has added to the pool.
698 * The number "num" is also added to the pool - it should somehow describe
699 * the type of event which just happened. This is currently 0-255 for
700 * keyboard scan codes, and 256 upwards for interrupts.
701 * On the i386, this is assumed to be at most 16 bits, and the high bits
702 * are used for a high-resolution timer.
705 static void add_timer_randomness(struct timer_rand_state *state, unsigned num)
707 __u32 time;
708 __s32 delta, delta2, delta3;
709 int entropy = 0;
711 #if defined (__i386__)
712 if (boot_cpu_data.x86_capability & X86_FEATURE_TSC) {
713 __u32 high;
714 __asm__(".byte 0x0f,0x31"
715 :"=a" (time), "=d" (high));
716 num ^= high;
717 } else {
718 time = jiffies;
720 #else
721 time = jiffies;
722 #endif
725 * Calculate number of bits of randomness we probably added.
726 * We take into account the first, second and third-order deltas
727 * in order to make our estimate.
729 if (!state->dont_count_entropy) {
730 delta = time - state->last_time;
731 state->last_time = time;
733 delta2 = delta - state->last_delta;
734 state->last_delta = delta;
736 delta3 = delta2 - state->last_delta2;
737 state->last_delta2 = delta2;
739 if (delta < 0)
740 delta = -delta;
741 if (delta2 < 0)
742 delta2 = -delta2;
743 if (delta3 < 0)
744 delta3 = -delta3;
745 if (delta > delta2)
746 delta = delta2;
747 if (delta > delta3)
748 delta = delta3;
751 * delta is now minimum absolute delta.
752 * Round down by 1 bit on general principles,
753 * and limit entropy entimate to 12 bits.
755 delta >>= 1;
756 delta &= (1 << 12) - 1;
758 entropy = int_ln_12bits(delta);
760 batch_entropy_store(num, time, entropy);
763 void add_keyboard_randomness(unsigned char scancode)
765 add_timer_randomness(&keyboard_timer_state, scancode);
768 void add_mouse_randomness(__u32 mouse_data)
770 add_timer_randomness(&mouse_timer_state, mouse_data);
773 void add_interrupt_randomness(int irq)
775 if (irq >= NR_IRQS || irq_timer_state[irq] == 0)
776 return;
778 add_timer_randomness(irq_timer_state[irq], 0x100+irq);
781 void add_blkdev_randomness(int major)
783 if (major >= MAX_BLKDEV)
784 return;
786 if (blkdev_timer_state[major] == 0) {
787 rand_initialize_blkdev(major, GFP_ATOMIC);
788 if (blkdev_timer_state[major] == 0)
789 return;
792 add_timer_randomness(blkdev_timer_state[major], 0x200+major);
795 /******************************************************************
797 * Hash function definition
799 *******************************************************************/
802 * This chunk of code defines a function
803 * void HASH_TRANSFORM(__u32 digest[HASH_BUFFER_SIZE + HASH_EXTRA_SIZE],
804 * __u32 const data[16])
806 * The function hashes the input data to produce a digest in the first
807 * HASH_BUFFER_SIZE words of the digest[] array, and uses HASH_EXTRA_SIZE
808 * more words for internal purposes. (This buffer is exported so the
809 * caller can wipe it once rather than this code doing it each call,
810 * and tacking it onto the end of the digest[] array is the quick and
811 * dirty way of doing it.)
813 * It so happens that MD5 and SHA share most of the initial vector
814 * used to initialize the digest[] array before the first call:
815 * 1) 0x67452301
816 * 2) 0xefcdab89
817 * 3) 0x98badcfe
818 * 4) 0x10325476
819 * 5) 0xc3d2e1f0 (SHA only)
821 * For /dev/random purposes, the length of the data being hashed is
822 * fixed in length, so appending a bit count in the usual way is not
823 * cryptographically necessary.
826 #ifdef USE_SHA
828 #define HASH_BUFFER_SIZE 5
829 #define HASH_EXTRA_SIZE 80
830 #define HASH_TRANSFORM SHATransform
832 /* Various size/speed tradeoffs are available. Choose 0..3. */
833 #define SHA_CODE_SIZE 0
836 * SHA transform algorithm, taken from code written by Peter Gutmann,
837 * and placed in the public domain.
840 /* The SHA f()-functions. */
842 #define f1(x,y,z) ( z ^ (x & (y^z)) ) /* Rounds 0-19: x ? y : z */
843 #define f2(x,y,z) (x ^ y ^ z) /* Rounds 20-39: XOR */
844 #define f3(x,y,z) ( (x & y) + (z & (x ^ y)) ) /* Rounds 40-59: majority */
845 #define f4(x,y,z) (x ^ y ^ z) /* Rounds 60-79: XOR */
847 /* The SHA Mysterious Constants */
849 #define K1 0x5A827999L /* Rounds 0-19: sqrt(2) * 2^30 */
850 #define K2 0x6ED9EBA1L /* Rounds 20-39: sqrt(3) * 2^30 */
851 #define K3 0x8F1BBCDCL /* Rounds 40-59: sqrt(5) * 2^30 */
852 #define K4 0xCA62C1D6L /* Rounds 60-79: sqrt(10) * 2^30 */
854 #define ROTL(n,X) ( ( ( X ) << n ) | ( ( X ) >> ( 32 - n ) ) )
856 #define subRound(a, b, c, d, e, f, k, data) \
857 ( e += ROTL( 5, a ) + f( b, c, d ) + k + data, b = ROTL( 30, b ) )
860 static void SHATransform(__u32 digest[85], __u32 const data[16])
862 __u32 A, B, C, D, E; /* Local vars */
863 __u32 TEMP;
864 int i;
865 #define W (digest + HASH_BUFFER_SIZE) /* Expanded data array */
868 * Do the preliminary expansion of 16 to 80 words. Doing it
869 * out-of-line line this is faster than doing it in-line on
870 * register-starved machines like the x86, and not really any
871 * slower on real processors.
873 memcpy(W, data, 16*sizeof(__u32));
874 for (i = 0; i < 64; i++) {
875 TEMP = W[i] ^ W[i+2] ^ W[i+8] ^ W[i+13];
876 W[i+16] = ROTL(1, TEMP);
879 /* Set up first buffer and local data buffer */
880 A = digest[ 0 ];
881 B = digest[ 1 ];
882 C = digest[ 2 ];
883 D = digest[ 3 ];
884 E = digest[ 4 ];
886 /* Heavy mangling, in 4 sub-rounds of 20 iterations each. */
887 #if SHA_CODE_SIZE == 0
889 * Approximately 50% of the speed of the largest version, but
890 * takes up 1/16 the space. Saves about 6k on an i386 kernel.
892 for (i = 0; i < 80; i++) {
893 if (i < 40) {
894 if (i < 20)
895 TEMP = f1(B, C, D) + K1;
896 else
897 TEMP = f2(B, C, D) + K2;
898 } else {
899 if (i < 60)
900 TEMP = f3(B, C, D) + K3;
901 else
902 TEMP = f4(B, C, D) + K4;
904 TEMP += ROTL(5, A) + E + W[i];
905 E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
907 #elif SHA_CODE_SIZE == 1
908 for (i = 0; i < 20; i++) {
909 TEMP = f1(B, C, D) + K1 + ROTL(5, A) + E + W[i];
910 E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
912 for (; i < 40; i++) {
913 TEMP = f2(B, C, D) + K2 + ROTL(5, A) + E + W[i];
914 E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
916 for (; i < 60; i++) {
917 TEMP = f3(B, C, D) + K3 + ROTL(5, A) + E + W[i];
918 E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
920 for (; i < 80; i++) {
921 TEMP = f4(B, C, D) + K4 + ROTL(5, A) + E + W[i];
922 E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
924 #elif SHA_CODE_SIZE == 2
925 for (i = 0; i < 20; i += 5) {
926 subRound( A, B, C, D, E, f1, K1, W[ i ] );
927 subRound( E, A, B, C, D, f1, K1, W[ i+1 ] );
928 subRound( D, E, A, B, C, f1, K1, W[ i+2 ] );
929 subRound( C, D, E, A, B, f1, K1, W[ i+3 ] );
930 subRound( B, C, D, E, A, f1, K1, W[ i+4 ] );
932 for (; i < 40; i += 5) {
933 subRound( A, B, C, D, E, f2, K2, W[ i ] );
934 subRound( E, A, B, C, D, f2, K2, W[ i+1 ] );
935 subRound( D, E, A, B, C, f2, K2, W[ i+2 ] );
936 subRound( C, D, E, A, B, f2, K2, W[ i+3 ] );
937 subRound( B, C, D, E, A, f2, K2, W[ i+4 ] );
939 for (; i < 60; i += 5) {
940 subRound( A, B, C, D, E, f3, K3, W[ i ] );
941 subRound( E, A, B, C, D, f3, K3, W[ i+1 ] );
942 subRound( D, E, A, B, C, f3, K3, W[ i+2 ] );
943 subRound( C, D, E, A, B, f3, K3, W[ i+3 ] );
944 subRound( B, C, D, E, A, f3, K3, W[ i+4 ] );
946 for (; i < 80; i += 5) {
947 subRound( A, B, C, D, E, f4, K4, W[ i ] );
948 subRound( E, A, B, C, D, f4, K4, W[ i+1 ] );
949 subRound( D, E, A, B, C, f4, K4, W[ i+2 ] );
950 subRound( C, D, E, A, B, f4, K4, W[ i+3 ] );
951 subRound( B, C, D, E, A, f4, K4, W[ i+4 ] );
953 #elif SHA_CODE_SIZE == 3 /* Really large version */
954 subRound( A, B, C, D, E, f1, K1, W[ 0 ] );
955 subRound( E, A, B, C, D, f1, K1, W[ 1 ] );
956 subRound( D, E, A, B, C, f1, K1, W[ 2 ] );
957 subRound( C, D, E, A, B, f1, K1, W[ 3 ] );
958 subRound( B, C, D, E, A, f1, K1, W[ 4 ] );
959 subRound( A, B, C, D, E, f1, K1, W[ 5 ] );
960 subRound( E, A, B, C, D, f1, K1, W[ 6 ] );
961 subRound( D, E, A, B, C, f1, K1, W[ 7 ] );
962 subRound( C, D, E, A, B, f1, K1, W[ 8 ] );
963 subRound( B, C, D, E, A, f1, K1, W[ 9 ] );
964 subRound( A, B, C, D, E, f1, K1, W[ 10 ] );
965 subRound( E, A, B, C, D, f1, K1, W[ 11 ] );
966 subRound( D, E, A, B, C, f1, K1, W[ 12 ] );
967 subRound( C, D, E, A, B, f1, K1, W[ 13 ] );
968 subRound( B, C, D, E, A, f1, K1, W[ 14 ] );
969 subRound( A, B, C, D, E, f1, K1, W[ 15 ] );
970 subRound( E, A, B, C, D, f1, K1, W[ 16 ] );
971 subRound( D, E, A, B, C, f1, K1, W[ 17 ] );
972 subRound( C, D, E, A, B, f1, K1, W[ 18 ] );
973 subRound( B, C, D, E, A, f1, K1, W[ 19 ] );
975 subRound( A, B, C, D, E, f2, K2, W[ 20 ] );
976 subRound( E, A, B, C, D, f2, K2, W[ 21 ] );
977 subRound( D, E, A, B, C, f2, K2, W[ 22 ] );
978 subRound( C, D, E, A, B, f2, K2, W[ 23 ] );
979 subRound( B, C, D, E, A, f2, K2, W[ 24 ] );
980 subRound( A, B, C, D, E, f2, K2, W[ 25 ] );
981 subRound( E, A, B, C, D, f2, K2, W[ 26 ] );
982 subRound( D, E, A, B, C, f2, K2, W[ 27 ] );
983 subRound( C, D, E, A, B, f2, K2, W[ 28 ] );
984 subRound( B, C, D, E, A, f2, K2, W[ 29 ] );
985 subRound( A, B, C, D, E, f2, K2, W[ 30 ] );
986 subRound( E, A, B, C, D, f2, K2, W[ 31 ] );
987 subRound( D, E, A, B, C, f2, K2, W[ 32 ] );
988 subRound( C, D, E, A, B, f2, K2, W[ 33 ] );
989 subRound( B, C, D, E, A, f2, K2, W[ 34 ] );
990 subRound( A, B, C, D, E, f2, K2, W[ 35 ] );
991 subRound( E, A, B, C, D, f2, K2, W[ 36 ] );
992 subRound( D, E, A, B, C, f2, K2, W[ 37 ] );
993 subRound( C, D, E, A, B, f2, K2, W[ 38 ] );
994 subRound( B, C, D, E, A, f2, K2, W[ 39 ] );
996 subRound( A, B, C, D, E, f3, K3, W[ 40 ] );
997 subRound( E, A, B, C, D, f3, K3, W[ 41 ] );
998 subRound( D, E, A, B, C, f3, K3, W[ 42 ] );
999 subRound( C, D, E, A, B, f3, K3, W[ 43 ] );
1000 subRound( B, C, D, E, A, f3, K3, W[ 44 ] );
1001 subRound( A, B, C, D, E, f3, K3, W[ 45 ] );
1002 subRound( E, A, B, C, D, f3, K3, W[ 46 ] );
1003 subRound( D, E, A, B, C, f3, K3, W[ 47 ] );
1004 subRound( C, D, E, A, B, f3, K3, W[ 48 ] );
1005 subRound( B, C, D, E, A, f3, K3, W[ 49 ] );
1006 subRound( A, B, C, D, E, f3, K3, W[ 50 ] );
1007 subRound( E, A, B, C, D, f3, K3, W[ 51 ] );
1008 subRound( D, E, A, B, C, f3, K3, W[ 52 ] );
1009 subRound( C, D, E, A, B, f3, K3, W[ 53 ] );
1010 subRound( B, C, D, E, A, f3, K3, W[ 54 ] );
1011 subRound( A, B, C, D, E, f3, K3, W[ 55 ] );
1012 subRound( E, A, B, C, D, f3, K3, W[ 56 ] );
1013 subRound( D, E, A, B, C, f3, K3, W[ 57 ] );
1014 subRound( C, D, E, A, B, f3, K3, W[ 58 ] );
1015 subRound( B, C, D, E, A, f3, K3, W[ 59 ] );
1017 subRound( A, B, C, D, E, f4, K4, W[ 60 ] );
1018 subRound( E, A, B, C, D, f4, K4, W[ 61 ] );
1019 subRound( D, E, A, B, C, f4, K4, W[ 62 ] );
1020 subRound( C, D, E, A, B, f4, K4, W[ 63 ] );
1021 subRound( B, C, D, E, A, f4, K4, W[ 64 ] );
1022 subRound( A, B, C, D, E, f4, K4, W[ 65 ] );
1023 subRound( E, A, B, C, D, f4, K4, W[ 66 ] );
1024 subRound( D, E, A, B, C, f4, K4, W[ 67 ] );
1025 subRound( C, D, E, A, B, f4, K4, W[ 68 ] );
1026 subRound( B, C, D, E, A, f4, K4, W[ 69 ] );
1027 subRound( A, B, C, D, E, f4, K4, W[ 70 ] );
1028 subRound( E, A, B, C, D, f4, K4, W[ 71 ] );
1029 subRound( D, E, A, B, C, f4, K4, W[ 72 ] );
1030 subRound( C, D, E, A, B, f4, K4, W[ 73 ] );
1031 subRound( B, C, D, E, A, f4, K4, W[ 74 ] );
1032 subRound( A, B, C, D, E, f4, K4, W[ 75 ] );
1033 subRound( E, A, B, C, D, f4, K4, W[ 76 ] );
1034 subRound( D, E, A, B, C, f4, K4, W[ 77 ] );
1035 subRound( C, D, E, A, B, f4, K4, W[ 78 ] );
1036 subRound( B, C, D, E, A, f4, K4, W[ 79 ] );
1037 #else
1038 #error Illegal SHA_CODE_SIZE
1039 #endif
1041 /* Build message digest */
1042 digest[ 0 ] += A;
1043 digest[ 1 ] += B;
1044 digest[ 2 ] += C;
1045 digest[ 3 ] += D;
1046 digest[ 4 ] += E;
1048 /* W is wiped by the caller */
1049 #undef W
1052 #undef ROTL
1053 #undef f1
1054 #undef f2
1055 #undef f3
1056 #undef f4
1057 #undef K1
1058 #undef K2
1059 #undef K3
1060 #undef K4
1061 #undef subRound
1063 #else /* !USE_SHA - Use MD5 */
1065 #define HASH_BUFFER_SIZE 4
1066 #define HASH_EXTRA_SIZE 0
1067 #define HASH_TRANSFORM MD5Transform
1070 * MD5 transform algorithm, taken from code written by Colin Plumb,
1071 * and put into the public domain
1074 /* The four core functions - F1 is optimized somewhat */
1076 /* #define F1(x, y, z) (x & y | ~x & z) */
1077 #define F1(x, y, z) (z ^ (x & (y ^ z)))
1078 #define F2(x, y, z) F1(z, x, y)
1079 #define F3(x, y, z) (x ^ y ^ z)
1080 #define F4(x, y, z) (y ^ (x | ~z))
1082 /* This is the central step in the MD5 algorithm. */
1083 #define MD5STEP(f, w, x, y, z, data, s) \
1084 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
1087 * The core of the MD5 algorithm, this alters an existing MD5 hash to
1088 * reflect the addition of 16 longwords of new data. MD5Update blocks
1089 * the data and converts bytes into longwords for this routine.
1091 static void MD5Transform(__u32 buf[HASH_BUFFER_SIZE], __u32 const in[16])
1093 __u32 a, b, c, d;
1095 a = buf[0];
1096 b = buf[1];
1097 c = buf[2];
1098 d = buf[3];
1100 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);
1101 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
1102 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
1103 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
1104 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);
1105 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
1106 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
1107 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
1108 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);
1109 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
1110 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
1111 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
1112 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);
1113 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
1114 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
1115 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
1117 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);
1118 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);
1119 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
1120 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
1121 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);
1122 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);
1123 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
1124 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
1125 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);
1126 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);
1127 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
1128 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
1129 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);
1130 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);
1131 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
1132 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
1134 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);
1135 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
1136 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
1137 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
1138 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);
1139 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
1140 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
1141 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
1142 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);
1143 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
1144 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
1145 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
1146 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);
1147 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
1148 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
1149 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
1151 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);
1152 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
1153 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
1154 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
1155 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);
1156 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
1157 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
1158 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
1159 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);
1160 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
1161 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
1162 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
1163 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);
1164 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
1165 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
1166 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
1168 buf[0] += a;
1169 buf[1] += b;
1170 buf[2] += c;
1171 buf[3] += d;
1174 #undef F1
1175 #undef F2
1176 #undef F3
1177 #undef F4
1178 #undef MD5STEP
1180 #endif /* !USE_SHA */
1182 /*********************************************************************
1184 * Entropy extraction routines
1186 *********************************************************************/
1188 #define EXTRACT_ENTROPY_USER 1
1189 #define EXTRACT_ENTROPY_SECONDARY 2
1190 #define TMP_BUF_SIZE (HASH_BUFFER_SIZE + HASH_EXTRA_SIZE)
1191 #define SEC_XFER_SIZE (TMP_BUF_SIZE*4)
1193 static ssize_t extract_entropy(struct entropy_store *r, void * buf,
1194 size_t nbytes, int flags);
1197 * This utility inline function is responsible for transfering entropy
1198 * from the primary pool to the secondary extraction pool. We pull
1199 * randomness under two conditions; one is if there isn't enough entropy
1200 * in the secondary pool. The other is after we have extract 1024 bytes,
1201 * at which point we do a "catastrophic reseeding".
1203 static inline void xfer_secondary_pool(struct entropy_store *r,
1204 size_t nbytes)
1206 __u32 tmp[TMP_BUF_SIZE];
1208 if (r->entropy_count < nbytes*8) {
1209 extract_entropy(random_state, tmp, sizeof(tmp), 0);
1210 add_entropy_words(r, tmp, TMP_BUF_SIZE);
1211 credit_entropy_store(r, TMP_BUF_SIZE*8);
1213 if (r->extract_count > 1024) {
1214 extract_entropy(random_state, tmp, sizeof(tmp), 0);
1215 add_entropy_words(r, tmp, TMP_BUF_SIZE);
1216 r->extract_count = 0;
1221 * This function extracts randomness from the "entropy pool", and
1222 * returns it in a buffer. This function computes how many remaining
1223 * bits of entropy are left in the pool, but it does not restrict the
1224 * number of bytes that are actually obtained. If the EXTRACT_ENTROPY_USER
1225 * flag is given, then the buf pointer is assumed to be in user space.
1226 * If the EXTRACT_ENTROPY_SECONDARY flag is given, then this function will
1228 * Note: extract_entropy() assumes that POOLWORDS is a multiple of 16 words.
1230 static ssize_t extract_entropy(struct entropy_store *r, void * buf,
1231 size_t nbytes, int flags)
1233 ssize_t ret, i;
1234 __u32 tmp[TMP_BUF_SIZE];
1235 __u32 x;
1237 add_timer_randomness(&extract_timer_state, nbytes);
1239 /* Redundant, but just in case... */
1240 if (r->entropy_count > r->poolinfo.poolwords)
1241 r->entropy_count = r->poolinfo.poolwords;
1243 if (flags & EXTRACT_ENTROPY_SECONDARY)
1244 xfer_secondary_pool(r, nbytes);
1246 if (r->entropy_count / 8 >= nbytes)
1247 r->entropy_count -= nbytes*8;
1248 else
1249 r->entropy_count = 0;
1251 if (r->entropy_count < random_write_wakeup_thresh)
1252 wake_up_interruptible(&random_write_wait);
1254 r->extract_count += nbytes;
1256 ret = 0;
1257 while (nbytes) {
1259 * Check if we need to break out or reschedule....
1261 if ((flags & EXTRACT_ENTROPY_USER) && current->need_resched) {
1262 if (signal_pending(current)) {
1263 if (ret == 0)
1264 ret = -ERESTARTSYS;
1265 break;
1267 schedule();
1270 /* Hash the pool to get the output */
1271 tmp[0] = 0x67452301;
1272 tmp[1] = 0xefcdab89;
1273 tmp[2] = 0x98badcfe;
1274 tmp[3] = 0x10325476;
1275 #ifdef USE_SHA
1276 tmp[4] = 0xc3d2e1f0;
1277 #endif
1279 * As we hash the pool, we mix intermediate values of
1280 * the hash back into the pool. This eliminates
1281 * backtracking attacks (where the attacker knows
1282 * the state of the pool plus the current outputs, and
1283 * attempts to find previous ouputs), unless the hash
1284 * function can be inverted.
1286 for (i = 0, x = 0; i < r->poolinfo.poolwords; i += 16, x+=2) {
1287 HASH_TRANSFORM(tmp, r->pool+i);
1288 add_entropy_words(r, &tmp[x%HASH_BUFFER_SIZE], 1);
1292 * In case the hash function has some recognizable
1293 * output pattern, we fold it in half.
1295 for (i = 0; i < HASH_BUFFER_SIZE/2; i++)
1296 tmp[i] ^= tmp[i + (HASH_BUFFER_SIZE+1)/2];
1297 #if HASH_BUFFER_SIZE & 1 /* There's a middle word to deal with */
1298 x = tmp[HASH_BUFFER_SIZE/2];
1299 x ^= (x >> 16); /* Fold it in half */
1300 ((__u16 *)tmp)[HASH_BUFFER_SIZE-1] = (__u16)x;
1301 #endif
1303 /* Copy data to destination buffer */
1304 i = MIN(nbytes, HASH_BUFFER_SIZE*sizeof(__u32)/2);
1305 if (flags & EXTRACT_ENTROPY_USER) {
1306 i -= copy_to_user(buf, (__u8 const *)tmp, i);
1307 if (!i) {
1308 ret = -EFAULT;
1309 break;
1311 } else
1312 memcpy(buf, (__u8 const *)tmp, i);
1313 nbytes -= i;
1314 buf += i;
1315 ret += i;
1316 add_timer_randomness(&extract_timer_state, nbytes);
1319 /* Wipe data just returned from memory */
1320 memset(tmp, 0, sizeof(tmp));
1322 return ret;
1326 * This function is the exported kernel interface. It returns some
1327 * number of good random numbers, suitable for seeding TCP sequence
1328 * numbers, etc.
1330 void get_random_bytes(void *buf, int nbytes)
1332 extract_entropy(sec_random_state, (char *) buf, nbytes,
1333 EXTRACT_ENTROPY_SECONDARY);
1336 /*********************************************************************
1338 * Functions to interface with Linux
1340 *********************************************************************/
1343 * Initialize the random pool with standard stuff.
1345 * NOTE: This is an OS-dependent function.
1347 static void init_std_data(struct entropy_store *r)
1349 struct timeval tv;
1350 __u32 words[2];
1351 char *p;
1352 int i;
1354 do_gettimeofday(&tv);
1355 words[0] = tv.tv_sec;
1356 words[1] = tv.tv_usec;
1357 add_entropy_words(r, words, 2);
1360 * This doesn't lock system.utsname. However, we are generating
1361 * entropy so a race with a name set here is fine.
1363 p = (char *) &system_utsname;
1364 for (i = sizeof(system_utsname) / sizeof(words); i; i--) {
1365 memcpy(words, p, sizeof(words));
1366 add_entropy_words(r, words, sizeof(words)/4);
1367 p += sizeof(words);
1371 void __init rand_initialize(void)
1373 int i;
1375 if (create_entropy_store(DEFAULT_POOL_SIZE, &random_state))
1376 return; /* Error, return */
1377 if (batch_entropy_init(BATCH_ENTROPY_SIZE, random_state))
1378 return; /* Error, return */
1379 if (create_entropy_store(SECONDARY_POOL_SIZE, &sec_random_state))
1380 return; /* Error, return */
1381 clear_entropy_store(random_state);
1382 clear_entropy_store(sec_random_state);
1383 init_std_data(random_state);
1384 #ifdef CONFIG_SYSCTL
1385 sysctl_init_random(random_state);
1386 #endif
1387 for (i = 0; i < NR_IRQS; i++)
1388 irq_timer_state[i] = NULL;
1389 for (i = 0; i < MAX_BLKDEV; i++)
1390 blkdev_timer_state[i] = NULL;
1391 memset(&keyboard_timer_state, 0, sizeof(struct timer_rand_state));
1392 memset(&mouse_timer_state, 0, sizeof(struct timer_rand_state));
1393 memset(&extract_timer_state, 0, sizeof(struct timer_rand_state));
1394 extract_timer_state.dont_count_entropy = 1;
1397 void rand_initialize_irq(int irq)
1399 struct timer_rand_state *state;
1401 if (irq >= NR_IRQS || irq_timer_state[irq])
1402 return;
1405 * If kmalloc returns null, we just won't use that entropy
1406 * source.
1408 state = kmalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
1409 if (state) {
1410 memset(state, 0, sizeof(struct timer_rand_state));
1411 irq_timer_state[irq] = state;
1415 void rand_initialize_blkdev(int major, int mode)
1417 struct timer_rand_state *state;
1419 if (major >= MAX_BLKDEV || blkdev_timer_state[major])
1420 return;
1423 * If kmalloc returns null, we just won't use that entropy
1424 * source.
1426 state = kmalloc(sizeof(struct timer_rand_state), mode);
1427 if (state) {
1428 memset(state, 0, sizeof(struct timer_rand_state));
1429 blkdev_timer_state[major] = state;
1434 static ssize_t
1435 random_read(struct file * file, char * buf, size_t nbytes, loff_t *ppos)
1437 DECLARE_WAITQUEUE(wait, current);
1438 ssize_t n, retval = 0, count = 0;
1440 if (nbytes == 0)
1441 return 0;
1443 add_wait_queue(&random_read_wait, &wait);
1444 while (nbytes > 0) {
1445 set_current_state(TASK_INTERRUPTIBLE);
1447 n = nbytes;
1448 if (n > SEC_XFER_SIZE)
1449 n = SEC_XFER_SIZE;
1450 if (n > random_state->entropy_count / 8)
1451 n = random_state->entropy_count / 8;
1452 if (n == 0) {
1453 if (file->f_flags & O_NONBLOCK) {
1454 retval = -EAGAIN;
1455 break;
1457 if (signal_pending(current)) {
1458 retval = -ERESTARTSYS;
1459 break;
1461 schedule();
1462 continue;
1464 n = extract_entropy(sec_random_state, buf, n,
1465 EXTRACT_ENTROPY_USER |
1466 EXTRACT_ENTROPY_SECONDARY);
1467 if (n < 0) {
1468 retval = n;
1469 break;
1471 count += n;
1472 buf += n;
1473 nbytes -= n;
1474 break; /* This break makes the device work */
1475 /* like a named pipe */
1477 current->state = TASK_RUNNING;
1478 remove_wait_queue(&random_read_wait, &wait);
1481 * If we gave the user some bytes, update the access time.
1483 if (count != 0) {
1484 UPDATE_ATIME(file->f_dentry->d_inode);
1487 return (count ? count : retval);
1490 static ssize_t
1491 urandom_read(struct file * file, char * buf,
1492 size_t nbytes, loff_t *ppos)
1494 return extract_entropy(sec_random_state, buf, nbytes,
1495 EXTRACT_ENTROPY_USER |
1496 EXTRACT_ENTROPY_SECONDARY);
1499 static unsigned int
1500 random_poll(struct file *file, poll_table * wait)
1502 unsigned int mask;
1504 poll_wait(file, &random_read_wait, wait);
1505 poll_wait(file, &random_write_wait, wait);
1506 mask = 0;
1507 if (random_state->entropy_count >= random_read_wakeup_thresh)
1508 mask |= POLLIN | POLLRDNORM;
1509 if (random_state->entropy_count < random_write_wakeup_thresh)
1510 mask |= POLLOUT | POLLWRNORM;
1511 return mask;
1514 static ssize_t
1515 random_write(struct file * file, const char * buffer,
1516 size_t count, loff_t *ppos)
1518 int ret = 0;
1519 size_t bytes;
1520 __u32 buf[16];
1521 const char *p = buffer;
1522 size_t c = count;
1524 while (c > 0) {
1525 bytes = MIN(c, sizeof(buf));
1527 bytes -= copy_from_user(&buf, p, bytes);
1528 if (!bytes) {
1529 ret = -EFAULT;
1530 break;
1532 c -= bytes;
1533 p += bytes;
1535 /* Convert bytes to words */
1536 bytes = (bytes + 3) / sizeof(__u32);
1537 add_entropy_words(random_state, buf, bytes);
1539 if (p == buffer) {
1540 return (ssize_t)ret;
1541 } else {
1542 file->f_dentry->d_inode->i_mtime = CURRENT_TIME;
1543 mark_inode_dirty(file->f_dentry->d_inode);
1544 return (ssize_t)(p - buffer);
1548 static int
1549 random_ioctl(struct inode * inode, struct file * file,
1550 unsigned int cmd, unsigned long arg)
1552 int *p, size, ent_count;
1553 int retval;
1555 switch (cmd) {
1556 case RNDGETENTCNT:
1557 ent_count = random_state->entropy_count;
1558 if (put_user(ent_count, (int *) arg))
1559 return -EFAULT;
1560 return 0;
1561 case RNDADDTOENTCNT:
1562 if (!capable(CAP_SYS_ADMIN))
1563 return -EPERM;
1564 if (get_user(ent_count, (int *) arg))
1565 return -EFAULT;
1566 credit_entropy_store(random_state, ent_count);
1568 * Wake up waiting processes if we have enough
1569 * entropy.
1571 if (random_state->entropy_count >= random_read_wakeup_thresh)
1572 wake_up_interruptible(&random_read_wait);
1573 return 0;
1574 case RNDGETPOOL:
1575 if (!capable(CAP_SYS_ADMIN))
1576 return -EPERM;
1577 p = (int *) arg;
1578 ent_count = random_state->entropy_count;
1579 if (put_user(ent_count, p++))
1580 return -EFAULT;
1582 if (get_user(size, p))
1583 return -EFAULT;
1584 if (put_user(random_state->poolinfo.poolwords, p++))
1585 return -EFAULT;
1586 if (size < 0)
1587 return -EINVAL;
1588 if (size > random_state->poolinfo.poolwords)
1589 size = random_state->poolinfo.poolwords;
1590 if (copy_to_user(p, random_state->pool, size*sizeof(__u32)))
1591 return -EFAULT;
1592 return 0;
1593 case RNDADDENTROPY:
1594 if (!capable(CAP_SYS_ADMIN))
1595 return -EPERM;
1596 p = (int *) arg;
1597 if (get_user(ent_count, p++))
1598 return -EFAULT;
1599 if (ent_count < 0)
1600 return -EINVAL;
1601 if (get_user(size, p++))
1602 return -EFAULT;
1603 retval = random_write(file, (const char *) p,
1604 size, &file->f_pos);
1605 if (retval < 0)
1606 return retval;
1607 credit_entropy_store(random_state, ent_count);
1609 * Wake up waiting processes if we have enough
1610 * entropy.
1612 if (random_state->entropy_count >= random_read_wakeup_thresh)
1613 wake_up_interruptible(&random_read_wait);
1614 return 0;
1615 case RNDZAPENTCNT:
1616 if (!capable(CAP_SYS_ADMIN))
1617 return -EPERM;
1618 random_state->entropy_count = 0;
1619 return 0;
1620 case RNDCLEARPOOL:
1621 /* Clear the entropy pool and associated counters. */
1622 if (!capable(CAP_SYS_ADMIN))
1623 return -EPERM;
1624 clear_entropy_store(random_state);
1625 init_std_data(random_state);
1626 return 0;
1627 default:
1628 return -EINVAL;
1632 struct file_operations random_fops = {
1633 NULL, /* random_lseek */
1634 random_read,
1635 random_write,
1636 NULL, /* random_readdir */
1637 random_poll, /* random_poll */
1638 random_ioctl,
1639 NULL, /* random_mmap */
1640 NULL, /* no special open code */
1641 NULL, /* flush */
1642 NULL /* no special release code */
1645 struct file_operations urandom_fops = {
1646 NULL, /* unrandom_lseek */
1647 urandom_read,
1648 random_write,
1649 NULL, /* urandom_readdir */
1650 NULL, /* urandom_poll */
1651 random_ioctl,
1652 NULL, /* urandom_mmap */
1653 NULL, /* no special open code */
1654 NULL, /* flush */
1655 NULL /* no special release code */
1658 /***************************************************************
1659 * Random UUID interface
1661 * Used here for a Boot ID, but can be useful for other kernel
1662 * drivers.
1663 ***************************************************************/
1666 * Generate random UUID
1668 void generate_random_uuid(unsigned char uuid_out[16])
1670 get_random_bytes(uuid_out, 16);
1671 /* Set UUID version to 4 --- truely random generation */
1672 uuid_out[6] = (uuid_out[6] & 0x0F) | 0x40;
1673 /* Set the UUID variant to DCE */
1674 uuid_out[8] = (uuid_out[8] & 0x3F) | 0x80;
1677 /********************************************************************
1679 * Sysctl interface
1681 ********************************************************************/
1683 #ifdef CONFIG_SYSCTL
1685 #include <linux/sysctl.h>
1687 static int sysctl_poolsize;
1688 static int min_read_thresh, max_read_thresh;
1689 static int min_write_thresh, max_write_thresh;
1690 static char sysctl_bootid[16];
1693 * This function handles a request from the user to change the pool size
1694 * of the primary entropy store.
1696 static int change_poolsize(int poolsize)
1698 struct entropy_store *new_store, *old_store;
1699 int ret;
1701 if ((ret = create_entropy_store(poolsize, &new_store)))
1702 return ret;
1704 add_entropy_words(new_store, random_state->pool,
1705 random_state->poolinfo.poolwords);
1706 credit_entropy_store(new_store, random_state->entropy_count);
1708 sysctl_init_random(new_store);
1709 old_store = random_state;
1710 random_state = batch_tqueue.data = new_store;
1711 free_entropy_store(old_store);
1712 return 0;
1715 static int proc_do_poolsize(ctl_table *table, int write, struct file *filp,
1716 void *buffer, size_t *lenp)
1718 int ret;
1720 sysctl_poolsize = random_state->poolinfo.poolwords * 4;
1722 ret = proc_dointvec(table, write, filp, buffer, lenp);
1723 if (ret || !write ||
1724 (sysctl_poolsize == random_state->poolinfo.poolwords * 4))
1725 return ret;
1727 return change_poolsize(sysctl_poolsize);
1730 static int poolsize_strategy(ctl_table *table, int *name, int nlen,
1731 void *oldval, size_t *oldlenp,
1732 void *newval, size_t newlen, void **context)
1734 int len;
1736 sysctl_poolsize = random_state->poolinfo.poolwords * 4;
1739 * We only handle the write case, since the read case gets
1740 * handled by the default handler (and we don't care if the
1741 * write case happens twice; it's harmless).
1743 if (newval && newlen) {
1744 len = newlen;
1745 if (len > table->maxlen)
1746 len = table->maxlen;
1747 if (copy_from_user(table->data, newval, len))
1748 return -EFAULT;
1751 if (sysctl_poolsize != random_state->poolinfo.poolwords * 4)
1752 return change_poolsize(sysctl_poolsize);
1754 return 0;
1758 * These functions is used to return both the bootid UUID, and random
1759 * UUID. The difference is in whether table->data is NULL; if it is,
1760 * then a new UUID is generated and returned to the user.
1762 * If the user accesses this via the proc interface, it will be returned
1763 * as an ASCII string in the standard UUID format. If accesses via the
1764 * sysctl system call, it is returned as 16 bytes of binary data.
1766 static int proc_do_uuid(ctl_table *table, int write, struct file *filp,
1767 void *buffer, size_t *lenp)
1769 ctl_table fake_table;
1770 unsigned char buf[64], tmp_uuid[16], *uuid;
1772 uuid = table->data;
1773 if (!uuid) {
1774 uuid = tmp_uuid;
1775 uuid[8] = 0;
1777 if (uuid[8] == 0)
1778 generate_random_uuid(uuid);
1780 sprintf(buf, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
1781 "%02x%02x%02x%02x%02x%02x",
1782 uuid[0], uuid[1], uuid[2], uuid[3],
1783 uuid[4], uuid[5], uuid[6], uuid[7],
1784 uuid[8], uuid[9], uuid[10], uuid[11],
1785 uuid[12], uuid[13], uuid[14], uuid[15]);
1786 fake_table.data = buf;
1787 fake_table.maxlen = sizeof(buf);
1789 return proc_dostring(&fake_table, write, filp, buffer, lenp);
1792 static int uuid_strategy(ctl_table *table, int *name, int nlen,
1793 void *oldval, size_t *oldlenp,
1794 void *newval, size_t newlen, void **context)
1796 unsigned char tmp_uuid[16], *uuid;
1797 int len;
1799 if (!oldval || !oldlenp)
1800 return 1;
1802 uuid = table->data;
1803 if (!uuid) {
1804 uuid = tmp_uuid;
1805 uuid[8] = 0;
1807 if (uuid[8] == 0)
1808 generate_random_uuid(uuid);
1810 get_user(len, oldlenp);
1811 if (len) {
1812 if (len > 16)
1813 len = 16;
1814 if (copy_to_user(oldval, table->data, len))
1815 return -EFAULT;
1816 if (put_user(len, oldlenp))
1817 return -EFAULT;
1819 return 1;
1822 ctl_table random_table[] = {
1823 {RANDOM_POOLSIZE, "poolsize",
1824 &sysctl_poolsize, sizeof(int), 0644, NULL,
1825 &proc_do_poolsize, &poolsize_strategy},
1826 {RANDOM_ENTROPY_COUNT, "entropy_avail",
1827 NULL, sizeof(int), 0444, NULL,
1828 &proc_dointvec},
1829 {RANDOM_READ_THRESH, "read_wakeup_threshold",
1830 &random_read_wakeup_thresh, sizeof(int), 0644, NULL,
1831 &proc_dointvec_minmax, &sysctl_intvec, 0,
1832 &min_read_thresh, &max_read_thresh},
1833 {RANDOM_WRITE_THRESH, "write_wakeup_threshold",
1834 &random_write_wakeup_thresh, sizeof(int), 0644, NULL,
1835 &proc_dointvec_minmax, &sysctl_intvec, 0,
1836 &min_write_thresh, &max_write_thresh},
1837 {RANDOM_BOOT_ID, "boot_id",
1838 &sysctl_bootid, 16, 0444, NULL,
1839 &proc_do_uuid, &uuid_strategy},
1840 {RANDOM_UUID, "uuid",
1841 NULL, 16, 0444, NULL,
1842 &proc_do_uuid, &uuid_strategy},
1846 static void sysctl_init_random(struct entropy_store *random_state)
1848 min_read_thresh = 8;
1849 min_write_thresh = 0;
1850 max_read_thresh = max_write_thresh =
1851 random_state->poolinfo.poolwords * 32;
1852 random_table[1].data = &random_state->entropy_count;
1854 #endif /* CONFIG_SYSCTL */
1856 /********************************************************************
1858 * Random funtions for networking
1860 ********************************************************************/
1863 * TCP initial sequence number picking. This uses the random number
1864 * generator to pick an initial secret value. This value is hashed
1865 * along with the TCP endpoint information to provide a unique
1866 * starting point for each pair of TCP endpoints. This defeats
1867 * attacks which rely on guessing the initial TCP sequence number.
1868 * This algorithm was suggested by Steve Bellovin.
1870 * Using a very strong hash was taking an appreciable amount of the total
1871 * TCP connection establishment time, so this is a weaker hash,
1872 * compensated for by changing the secret periodically.
1875 /* F, G and H are basic MD4 functions: selection, majority, parity */
1876 #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
1877 #define G(x, y, z) (((x) & (y)) + (((x) ^ (y)) & (z)))
1878 #define H(x, y, z) ((x) ^ (y) ^ (z))
1881 * The generic round function. The application is so specific that
1882 * we don't bother protecting all the arguments with parens, as is generally
1883 * good macro practice, in favor of extra legibility.
1884 * Rotation is separate from addition to prevent recomputation
1886 #define ROUND(f, a, b, c, d, x, s) \
1887 (a += f(b, c, d) + x, a = (a << s) | (a >> (32-s)))
1888 #define K1 0
1889 #define K2 013240474631UL
1890 #define K3 015666365641UL
1893 * Basic cut-down MD4 transform. Returns only 32 bits of result.
1895 static __u32 halfMD4Transform (__u32 const buf[4], __u32 const in[8])
1897 __u32 a = buf[0], b = buf[1], c = buf[2], d = buf[3];
1899 /* Round 1 */
1900 ROUND(F, a, b, c, d, in[0] + K1, 3);
1901 ROUND(F, d, a, b, c, in[1] + K1, 7);
1902 ROUND(F, c, d, a, b, in[2] + K1, 11);
1903 ROUND(F, b, c, d, a, in[3] + K1, 19);
1904 ROUND(F, a, b, c, d, in[4] + K1, 3);
1905 ROUND(F, d, a, b, c, in[5] + K1, 7);
1906 ROUND(F, c, d, a, b, in[6] + K1, 11);
1907 ROUND(F, b, c, d, a, in[7] + K1, 19);
1909 /* Round 2 */
1910 ROUND(G, a, b, c, d, in[1] + K2, 3);
1911 ROUND(G, d, a, b, c, in[3] + K2, 5);
1912 ROUND(G, c, d, a, b, in[5] + K2, 9);
1913 ROUND(G, b, c, d, a, in[7] + K2, 13);
1914 ROUND(G, a, b, c, d, in[0] + K2, 3);
1915 ROUND(G, d, a, b, c, in[2] + K2, 5);
1916 ROUND(G, c, d, a, b, in[4] + K2, 9);
1917 ROUND(G, b, c, d, a, in[6] + K2, 13);
1919 /* Round 3 */
1920 ROUND(H, a, b, c, d, in[3] + K3, 3);
1921 ROUND(H, d, a, b, c, in[7] + K3, 9);
1922 ROUND(H, c, d, a, b, in[2] + K3, 11);
1923 ROUND(H, b, c, d, a, in[6] + K3, 15);
1924 ROUND(H, a, b, c, d, in[1] + K3, 3);
1925 ROUND(H, d, a, b, c, in[5] + K3, 9);
1926 ROUND(H, c, d, a, b, in[0] + K3, 11);
1927 ROUND(H, b, c, d, a, in[4] + K3, 15);
1929 return buf[1] + b; /* "most hashed" word */
1930 /* Alternative: return sum of all words? */
1933 #if 0 /* May be needed for IPv6 */
1935 static __u32 twothirdsMD4Transform (__u32 const buf[4], __u32 const in[12])
1937 __u32 a = buf[0], b = buf[1], c = buf[2], d = buf[3];
1939 /* Round 1 */
1940 ROUND(F, a, b, c, d, in[ 0] + K1, 3);
1941 ROUND(F, d, a, b, c, in[ 1] + K1, 7);
1942 ROUND(F, c, d, a, b, in[ 2] + K1, 11);
1943 ROUND(F, b, c, d, a, in[ 3] + K1, 19);
1944 ROUND(F, a, b, c, d, in[ 4] + K1, 3);
1945 ROUND(F, d, a, b, c, in[ 5] + K1, 7);
1946 ROUND(F, c, d, a, b, in[ 6] + K1, 11);
1947 ROUND(F, b, c, d, a, in[ 7] + K1, 19);
1948 ROUND(F, a, b, c, d, in[ 8] + K1, 3);
1949 ROUND(F, d, a, b, c, in[ 9] + K1, 7);
1950 ROUND(F, c, d, a, b, in[10] + K1, 11);
1951 ROUND(F, b, c, d, a, in[11] + K1, 19);
1953 /* Round 2 */
1954 ROUND(G, a, b, c, d, in[ 1] + K2, 3);
1955 ROUND(G, d, a, b, c, in[ 3] + K2, 5);
1956 ROUND(G, c, d, a, b, in[ 5] + K2, 9);
1957 ROUND(G, b, c, d, a, in[ 7] + K2, 13);
1958 ROUND(G, a, b, c, d, in[ 9] + K2, 3);
1959 ROUND(G, d, a, b, c, in[11] + K2, 5);
1960 ROUND(G, c, d, a, b, in[ 0] + K2, 9);
1961 ROUND(G, b, c, d, a, in[ 2] + K2, 13);
1962 ROUND(G, a, b, c, d, in[ 4] + K2, 3);
1963 ROUND(G, d, a, b, c, in[ 6] + K2, 5);
1964 ROUND(G, c, d, a, b, in[ 8] + K2, 9);
1965 ROUND(G, b, c, d, a, in[10] + K2, 13);
1967 /* Round 3 */
1968 ROUND(H, a, b, c, d, in[ 3] + K3, 3);
1969 ROUND(H, d, a, b, c, in[ 7] + K3, 9);
1970 ROUND(H, c, d, a, b, in[11] + K3, 11);
1971 ROUND(H, b, c, d, a, in[ 2] + K3, 15);
1972 ROUND(H, a, b, c, d, in[ 6] + K3, 3);
1973 ROUND(H, d, a, b, c, in[10] + K3, 9);
1974 ROUND(H, c, d, a, b, in[ 1] + K3, 11);
1975 ROUND(H, b, c, d, a, in[ 5] + K3, 15);
1976 ROUND(H, a, b, c, d, in[ 9] + K3, 3);
1977 ROUND(H, d, a, b, c, in[ 0] + K3, 9);
1978 ROUND(H, c, d, a, b, in[ 4] + K3, 11);
1979 ROUND(H, b, c, d, a, in[ 8] + K3, 15);
1981 return buf[1] + b; /* "most hashed" word */
1982 /* Alternative: return sum of all words? */
1984 #endif
1986 #undef ROUND
1987 #undef F
1988 #undef G
1989 #undef H
1990 #undef K1
1991 #undef K2
1992 #undef K3
1994 /* This should not be decreased so low that ISNs wrap too fast. */
1995 #define REKEY_INTERVAL 300
1996 #define HASH_BITS 24
1998 __u32 secure_tcp_sequence_number(__u32 saddr, __u32 daddr,
1999 __u16 sport, __u16 dport)
2001 static __u32 rekey_time = 0;
2002 static __u32 count = 0;
2003 static __u32 secret[12];
2004 struct timeval tv;
2005 __u32 seq;
2008 * Pick a random secret every REKEY_INTERVAL seconds.
2010 do_gettimeofday(&tv); /* We need the usecs below... */
2012 if (!rekey_time || (tv.tv_sec - rekey_time) > REKEY_INTERVAL) {
2013 rekey_time = tv.tv_sec;
2014 /* First three words are overwritten below. */
2015 get_random_bytes(&secret+3, sizeof(secret)-12);
2016 count = (tv.tv_sec/REKEY_INTERVAL) << HASH_BITS;
2020 * Pick a unique starting offset for each TCP connection endpoints
2021 * (saddr, daddr, sport, dport).
2022 * Note that the words are placed into the first words to be
2023 * mixed in with the halfMD4. This is because the starting
2024 * vector is also a random secret (at secret+8), and further
2025 * hashing fixed data into it isn't going to improve anything,
2026 * so we should get started with the variable data.
2028 secret[0]=saddr;
2029 secret[1]=daddr;
2030 secret[2]=(sport << 16) + dport;
2032 seq = (halfMD4Transform(secret+8, secret) &
2033 ((1<<HASH_BITS)-1)) + count;
2036 * As close as possible to RFC 793, which
2037 * suggests using a 250 kHz clock.
2038 * Further reading shows this assumes 2 Mb/s networks.
2039 * For 10 Mb/s Ethernet, a 1 MHz clock is appropriate.
2040 * That's funny, Linux has one built in! Use it!
2041 * (Networks are faster now - should this be increased?)
2043 seq += tv.tv_usec + tv.tv_sec*1000000;
2044 #if 0
2045 printk("init_seq(%lx, %lx, %d, %d) = %d\n",
2046 saddr, daddr, sport, dport, seq);
2047 #endif
2048 return seq;
2051 #ifdef CONFIG_SYN_COOKIES
2053 * Secure SYN cookie computation. This is the algorithm worked out by
2054 * Dan Bernstein and Eric Schenk.
2056 * For linux I implement the 1 minute counter by looking at the jiffies clock.
2057 * The count is passed in as a parameter, so this code doesn't much care.
2060 #define COOKIEBITS 24 /* Upper bits store count */
2061 #define COOKIEMASK (((__u32)1 << COOKIEBITS) - 1)
2063 static int syncookie_init = 0;
2064 static __u32 syncookie_secret[2][16-3+HASH_BUFFER_SIZE];
2066 __u32 secure_tcp_syn_cookie(__u32 saddr, __u32 daddr, __u16 sport,
2067 __u16 dport, __u32 sseq, __u32 count, __u32 data)
2069 __u32 tmp[16 + HASH_BUFFER_SIZE + HASH_EXTRA_SIZE];
2070 __u32 seq;
2073 * Pick two random secrets the first time we need a cookie.
2075 if (syncookie_init == 0) {
2076 get_random_bytes(syncookie_secret, sizeof(syncookie_secret));
2077 syncookie_init = 1;
2081 * Compute the secure sequence number.
2082 * The output should be:
2083 * HASH(sec1,saddr,sport,daddr,dport,sec1) + sseq + (count * 2^24)
2084 * + (HASH(sec2,saddr,sport,daddr,dport,count,sec2) % 2^24).
2085 * Where sseq is their sequence number and count increases every
2086 * minute by 1.
2087 * As an extra hack, we add a small "data" value that encodes the
2088 * MSS into the second hash value.
2091 memcpy(tmp+3, syncookie_secret[0], sizeof(syncookie_secret[0]));
2092 tmp[0]=saddr;
2093 tmp[1]=daddr;
2094 tmp[2]=(sport << 16) + dport;
2095 HASH_TRANSFORM(tmp+16, tmp);
2096 seq = tmp[17] + sseq + (count << COOKIEBITS);
2098 memcpy(tmp+3, syncookie_secret[1], sizeof(syncookie_secret[1]));
2099 tmp[0]=saddr;
2100 tmp[1]=daddr;
2101 tmp[2]=(sport << 16) + dport;
2102 tmp[3] = count; /* minute counter */
2103 HASH_TRANSFORM(tmp+16, tmp);
2105 /* Add in the second hash and the data */
2106 return seq + ((tmp[17] + data) & COOKIEMASK);
2110 * This retrieves the small "data" value from the syncookie.
2111 * If the syncookie is bad, the data returned will be out of
2112 * range. This must be checked by the caller.
2114 * The count value used to generate the cookie must be within
2115 * "maxdiff" if the current (passed-in) "count". The return value
2116 * is (__u32)-1 if this test fails.
2118 __u32 check_tcp_syn_cookie(__u32 cookie, __u32 saddr, __u32 daddr, __u16 sport,
2119 __u16 dport, __u32 sseq, __u32 count, __u32 maxdiff)
2121 __u32 tmp[16 + HASH_BUFFER_SIZE + HASH_EXTRA_SIZE];
2122 __u32 diff;
2124 if (syncookie_init == 0)
2125 return (__u32)-1; /* Well, duh! */
2127 /* Strip away the layers from the cookie */
2128 memcpy(tmp+3, syncookie_secret[0], sizeof(syncookie_secret[0]));
2129 tmp[0]=saddr;
2130 tmp[1]=daddr;
2131 tmp[2]=(sport << 16) + dport;
2132 HASH_TRANSFORM(tmp+16, tmp);
2133 cookie -= tmp[17] + sseq;
2134 /* Cookie is now reduced to (count * 2^24) ^ (hash % 2^24) */
2136 diff = (count - (cookie >> COOKIEBITS)) & ((__u32)-1 >> COOKIEBITS);
2137 if (diff >= maxdiff)
2138 return (__u32)-1;
2140 memcpy(tmp+3, syncookie_secret[1], sizeof(syncookie_secret[1]));
2141 tmp[0] = saddr;
2142 tmp[1] = daddr;
2143 tmp[2] = (sport << 16) + dport;
2144 tmp[3] = count - diff; /* minute counter */
2145 HASH_TRANSFORM(tmp+16, tmp);
2147 return (cookie - tmp[17]) & COOKIEMASK; /* Leaving the data behind */
2149 #endif