2 * random.c -- A strong random number generator
4 * Version 1.89, last modified 19-Sep-99
6 * Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999. All
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
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
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
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.
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
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
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
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
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
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
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>
253 * Configuration information
255 #define DEFAULT_POOL_SIZE 512
256 #define SECONDARY_POOL_SIZE 128
257 #define BATCH_ENTROPY_SIZE 256
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
{
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 },
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 },
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 },
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 }
375 #ifndef DECLARE_WAIT_QUEUE_HEAD
376 #define DECLARE_WAIT_QUEUE_HEAD(WAIT) struct wait_queue *WAIT
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
391 static void sysctl_init_random(struct entropy_store
*random_state
);
394 /*****************************************************************
396 * Utility functions, with some ASM defined functions for speed
399 *****************************************************************/
402 #define MIN(a,b) (((a) < (b)) ? (a) : (b))
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
));
417 extern inline __u32
rotate_left(int i
, __u32 word
)
419 __asm__("roll %%cl,%0"
421 :"0" (word
),"c" (i
));
429 * For entropy estimation, we need to do an integral base 2
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
)
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 */
452 /* Remove one bit to make this a logarithm */
454 /* Count the bits set in the word */
455 word
-= (word
>> 1) & 0x555;
456 word
= (word
& 0x333) + ((word
>> 2) & 0x333);
463 /**********************************************************************
465 * OS independent entropy store. Here are the functions which handle
466 * storing entropy in an entropy pool.
468 **********************************************************************/
470 struct entropy_store
{
475 struct poolinfo poolinfo
;
480 * Initialize the entropy store. The input argument is the size of
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
;
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
)
499 if (p
->poolwords
== 0)
502 r
= kmalloc(sizeof(struct entropy_store
), GFP_KERNEL
);
506 memset (r
, 0, sizeof(struct entropy_store
));
509 r
->pool
= kmalloc(poolwords
*4, GFP_KERNEL
);
511 kfree_s(r
, sizeof(struct entropy_store
));
514 memset(r
->pool
, 0, poolwords
*4);
519 /* Clear the entropy pool and associated counters. */
520 static void clear_entropy_store(struct entropy_store
*r
)
523 r
->entropy_count
= 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
)
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
,
549 static __u32
const twist_table
[8] = {
550 0, 0x3b6e20c8, 0x76dc4190, 0x4db26158,
551 0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278 };
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;
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)];
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
;
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
)
617 batch_entropy_credit
=kmalloc(size
*sizeof(int), GFP_KERNEL
);
618 if (!batch_entropy_credit
) {
619 kfree(batch_entropy_pool
);
622 batch_head
= batch_tail
= 0;
624 batch_tqueue
.routine
= batch_entropy_process
;
625 batch_tqueue
.data
= r
;
629 static void batch_entropy_store(__u32 a
, __u32 b
, int num
)
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
);
646 printk(KERN_NOTICE
"random: batch entropy buffer full\n");
651 static void batch_entropy_process(void *private_
)
655 struct entropy_store
*r
= (struct entropy_store
*) private_
, *p
;
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);
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);
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
{
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
)
708 __s32 delta
, delta2
, delta3
;
711 #if defined (__i386__)
712 if (boot_cpu_data
.x86_capability
& X86_FEATURE_TSC
) {
714 __asm__(".byte 0x0f,0x31"
715 :"=a" (time
), "=d" (high
));
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
;
751 * delta is now minimum absolute delta.
752 * Round down by 1 bit on general principles,
753 * and limit entropy entimate to 12 bits.
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)
778 add_timer_randomness(irq_timer_state
[irq
], 0x100+irq
);
781 void add_blkdev_randomness(int major
)
783 if (major
>= MAX_BLKDEV
)
786 if (blkdev_timer_state
[major
] == 0) {
787 rand_initialize_blkdev(major
, GFP_ATOMIC
);
788 if (blkdev_timer_state
[major
] == 0)
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:
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.
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 */
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 */
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
++) {
895 TEMP
= f1(B
, C
, D
) + K1
;
897 TEMP
= f2(B
, C
, D
) + K2
;
900 TEMP
= f3(B
, C
, D
) + K3
;
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 ] );
1038 #error Illegal SHA_CODE_SIZE
1041 /* Build message digest */
1048 /* W is wiped by the caller */
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])
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);
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
,
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
)
1234 __u32 tmp
[TMP_BUF_SIZE
];
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;
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
;
1259 * Check if we need to break out or reschedule....
1261 if ((flags
& EXTRACT_ENTROPY_USER
) && current
->need_resched
) {
1262 if (signal_pending(current
)) {
1270 /* Hash the pool to get the output */
1271 tmp
[0] = 0x67452301;
1272 tmp
[1] = 0xefcdab89;
1273 tmp
[2] = 0x98badcfe;
1274 tmp
[3] = 0x10325476;
1276 tmp
[4] = 0xc3d2e1f0;
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
;
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
);
1312 memcpy(buf
, (__u8
const *)tmp
, i
);
1316 add_timer_randomness(&extract_timer_state
, nbytes
);
1319 /* Wipe data just returned from memory */
1320 memset(tmp
, 0, sizeof(tmp
));
1326 * This function is the exported kernel interface. It returns some
1327 * number of good random numbers, suitable for seeding TCP sequence
1330 void get_random_bytes(void *buf
, int nbytes
)
1332 if (sec_random_state
)
1333 extract_entropy(sec_random_state
, (char *) buf
, nbytes
,
1334 EXTRACT_ENTROPY_SECONDARY
);
1335 else if (random_state
)
1336 extract_entropy(random_state
, (char *) buf
, nbytes
, 0);
1338 printk(KERN_NOTICE
"get_random_bytes called before "
1339 "random driver initialization\n");
1342 /*********************************************************************
1344 * Functions to interface with Linux
1346 *********************************************************************/
1349 * Initialize the random pool with standard stuff.
1351 * NOTE: This is an OS-dependent function.
1353 static void init_std_data(struct entropy_store
*r
)
1360 do_gettimeofday(&tv
);
1361 words
[0] = tv
.tv_sec
;
1362 words
[1] = tv
.tv_usec
;
1363 add_entropy_words(r
, words
, 2);
1366 * This doesn't lock system.utsname. However, we are generating
1367 * entropy so a race with a name set here is fine.
1369 p
= (char *) &system_utsname
;
1370 for (i
= sizeof(system_utsname
) / sizeof(words
); i
; i
--) {
1371 memcpy(words
, p
, sizeof(words
));
1372 add_entropy_words(r
, words
, sizeof(words
)/4);
1377 void __init
rand_initialize(void)
1381 if (create_entropy_store(DEFAULT_POOL_SIZE
, &random_state
))
1382 return; /* Error, return */
1383 if (batch_entropy_init(BATCH_ENTROPY_SIZE
, random_state
))
1384 return; /* Error, return */
1385 if (create_entropy_store(SECONDARY_POOL_SIZE
, &sec_random_state
))
1386 return; /* Error, return */
1387 clear_entropy_store(random_state
);
1388 clear_entropy_store(sec_random_state
);
1389 init_std_data(random_state
);
1390 #ifdef CONFIG_SYSCTL
1391 sysctl_init_random(random_state
);
1393 for (i
= 0; i
< NR_IRQS
; i
++)
1394 irq_timer_state
[i
] = NULL
;
1395 for (i
= 0; i
< MAX_BLKDEV
; i
++)
1396 blkdev_timer_state
[i
] = NULL
;
1397 memset(&keyboard_timer_state
, 0, sizeof(struct timer_rand_state
));
1398 memset(&mouse_timer_state
, 0, sizeof(struct timer_rand_state
));
1399 memset(&extract_timer_state
, 0, sizeof(struct timer_rand_state
));
1400 extract_timer_state
.dont_count_entropy
= 1;
1403 void rand_initialize_irq(int irq
)
1405 struct timer_rand_state
*state
;
1407 if (irq
>= NR_IRQS
|| irq_timer_state
[irq
])
1411 * If kmalloc returns null, we just won't use that entropy
1414 state
= kmalloc(sizeof(struct timer_rand_state
), GFP_KERNEL
);
1416 memset(state
, 0, sizeof(struct timer_rand_state
));
1417 irq_timer_state
[irq
] = state
;
1421 void rand_initialize_blkdev(int major
, int mode
)
1423 struct timer_rand_state
*state
;
1425 if (major
>= MAX_BLKDEV
|| blkdev_timer_state
[major
])
1429 * If kmalloc returns null, we just won't use that entropy
1432 state
= kmalloc(sizeof(struct timer_rand_state
), mode
);
1434 memset(state
, 0, sizeof(struct timer_rand_state
));
1435 blkdev_timer_state
[major
] = state
;
1441 random_read(struct file
* file
, char * buf
, size_t nbytes
, loff_t
*ppos
)
1443 DECLARE_WAITQUEUE(wait
, current
);
1444 ssize_t n
, retval
= 0, count
= 0;
1449 add_wait_queue(&random_read_wait
, &wait
);
1450 while (nbytes
> 0) {
1451 set_current_state(TASK_INTERRUPTIBLE
);
1454 if (n
> SEC_XFER_SIZE
)
1456 if (n
> random_state
->entropy_count
/ 8)
1457 n
= random_state
->entropy_count
/ 8;
1459 if (file
->f_flags
& O_NONBLOCK
) {
1463 if (signal_pending(current
)) {
1464 retval
= -ERESTARTSYS
;
1470 n
= extract_entropy(sec_random_state
, buf
, n
,
1471 EXTRACT_ENTROPY_USER
|
1472 EXTRACT_ENTROPY_SECONDARY
);
1480 break; /* This break makes the device work */
1481 /* like a named pipe */
1483 current
->state
= TASK_RUNNING
;
1484 remove_wait_queue(&random_read_wait
, &wait
);
1487 * If we gave the user some bytes, update the access time.
1490 UPDATE_ATIME(file
->f_dentry
->d_inode
);
1493 return (count
? count
: retval
);
1497 urandom_read(struct file
* file
, char * buf
,
1498 size_t nbytes
, loff_t
*ppos
)
1500 return extract_entropy(sec_random_state
, buf
, nbytes
,
1501 EXTRACT_ENTROPY_USER
|
1502 EXTRACT_ENTROPY_SECONDARY
);
1506 random_poll(struct file
*file
, poll_table
* wait
)
1510 poll_wait(file
, &random_read_wait
, wait
);
1511 poll_wait(file
, &random_write_wait
, wait
);
1513 if (random_state
->entropy_count
>= random_read_wakeup_thresh
)
1514 mask
|= POLLIN
| POLLRDNORM
;
1515 if (random_state
->entropy_count
< random_write_wakeup_thresh
)
1516 mask
|= POLLOUT
| POLLWRNORM
;
1521 random_write(struct file
* file
, const char * buffer
,
1522 size_t count
, loff_t
*ppos
)
1527 const char *p
= buffer
;
1531 bytes
= MIN(c
, sizeof(buf
));
1533 bytes
-= copy_from_user(&buf
, p
, bytes
);
1541 /* Convert bytes to words */
1542 bytes
= (bytes
+ 3) / sizeof(__u32
);
1543 add_entropy_words(random_state
, buf
, bytes
);
1546 return (ssize_t
)ret
;
1548 file
->f_dentry
->d_inode
->i_mtime
= CURRENT_TIME
;
1549 mark_inode_dirty(file
->f_dentry
->d_inode
);
1550 return (ssize_t
)(p
- buffer
);
1555 random_ioctl(struct inode
* inode
, struct file
* file
,
1556 unsigned int cmd
, unsigned long arg
)
1558 int *p
, size
, ent_count
;
1563 ent_count
= random_state
->entropy_count
;
1564 if (put_user(ent_count
, (int *) arg
))
1567 case RNDADDTOENTCNT
:
1568 if (!capable(CAP_SYS_ADMIN
))
1570 if (get_user(ent_count
, (int *) arg
))
1572 credit_entropy_store(random_state
, ent_count
);
1574 * Wake up waiting processes if we have enough
1577 if (random_state
->entropy_count
>= random_read_wakeup_thresh
)
1578 wake_up_interruptible(&random_read_wait
);
1581 if (!capable(CAP_SYS_ADMIN
))
1584 ent_count
= random_state
->entropy_count
;
1585 if (put_user(ent_count
, p
++))
1588 if (get_user(size
, p
))
1590 if (put_user(random_state
->poolinfo
.poolwords
, p
++))
1594 if (size
> random_state
->poolinfo
.poolwords
)
1595 size
= random_state
->poolinfo
.poolwords
;
1596 if (copy_to_user(p
, random_state
->pool
, size
*sizeof(__u32
)))
1600 if (!capable(CAP_SYS_ADMIN
))
1603 if (get_user(ent_count
, p
++))
1607 if (get_user(size
, p
++))
1609 retval
= random_write(file
, (const char *) p
,
1610 size
, &file
->f_pos
);
1613 credit_entropy_store(random_state
, ent_count
);
1615 * Wake up waiting processes if we have enough
1618 if (random_state
->entropy_count
>= random_read_wakeup_thresh
)
1619 wake_up_interruptible(&random_read_wait
);
1622 if (!capable(CAP_SYS_ADMIN
))
1624 random_state
->entropy_count
= 0;
1627 /* Clear the entropy pool and associated counters. */
1628 if (!capable(CAP_SYS_ADMIN
))
1630 clear_entropy_store(random_state
);
1631 init_std_data(random_state
);
1638 struct file_operations random_fops
= {
1639 NULL
, /* random_lseek */
1642 NULL
, /* random_readdir */
1643 random_poll
, /* random_poll */
1645 NULL
, /* random_mmap */
1646 NULL
, /* no special open code */
1648 NULL
/* no special release code */
1651 struct file_operations urandom_fops
= {
1652 NULL
, /* unrandom_lseek */
1655 NULL
, /* urandom_readdir */
1656 NULL
, /* urandom_poll */
1658 NULL
, /* urandom_mmap */
1659 NULL
, /* no special open code */
1661 NULL
/* no special release code */
1664 /***************************************************************
1665 * Random UUID interface
1667 * Used here for a Boot ID, but can be useful for other kernel
1669 ***************************************************************/
1672 * Generate random UUID
1674 void generate_random_uuid(unsigned char uuid_out
[16])
1676 get_random_bytes(uuid_out
, 16);
1677 /* Set UUID version to 4 --- truely random generation */
1678 uuid_out
[6] = (uuid_out
[6] & 0x0F) | 0x40;
1679 /* Set the UUID variant to DCE */
1680 uuid_out
[8] = (uuid_out
[8] & 0x3F) | 0x80;
1683 /********************************************************************
1687 ********************************************************************/
1689 #ifdef CONFIG_SYSCTL
1691 #include <linux/sysctl.h>
1693 static int sysctl_poolsize
;
1694 static int min_read_thresh
, max_read_thresh
;
1695 static int min_write_thresh
, max_write_thresh
;
1696 static char sysctl_bootid
[16];
1699 * This function handles a request from the user to change the pool size
1700 * of the primary entropy store.
1702 static int change_poolsize(int poolsize
)
1704 struct entropy_store
*new_store
, *old_store
;
1707 if ((ret
= create_entropy_store(poolsize
, &new_store
)))
1710 add_entropy_words(new_store
, random_state
->pool
,
1711 random_state
->poolinfo
.poolwords
);
1712 credit_entropy_store(new_store
, random_state
->entropy_count
);
1714 sysctl_init_random(new_store
);
1715 old_store
= random_state
;
1716 random_state
= batch_tqueue
.data
= new_store
;
1717 free_entropy_store(old_store
);
1721 static int proc_do_poolsize(ctl_table
*table
, int write
, struct file
*filp
,
1722 void *buffer
, size_t *lenp
)
1726 sysctl_poolsize
= random_state
->poolinfo
.poolwords
* 4;
1728 ret
= proc_dointvec(table
, write
, filp
, buffer
, lenp
);
1729 if (ret
|| !write
||
1730 (sysctl_poolsize
== random_state
->poolinfo
.poolwords
* 4))
1733 return change_poolsize(sysctl_poolsize
);
1736 static int poolsize_strategy(ctl_table
*table
, int *name
, int nlen
,
1737 void *oldval
, size_t *oldlenp
,
1738 void *newval
, size_t newlen
, void **context
)
1742 sysctl_poolsize
= random_state
->poolinfo
.poolwords
* 4;
1745 * We only handle the write case, since the read case gets
1746 * handled by the default handler (and we don't care if the
1747 * write case happens twice; it's harmless).
1749 if (newval
&& newlen
) {
1751 if (len
> table
->maxlen
)
1752 len
= table
->maxlen
;
1753 if (copy_from_user(table
->data
, newval
, len
))
1757 if (sysctl_poolsize
!= random_state
->poolinfo
.poolwords
* 4)
1758 return change_poolsize(sysctl_poolsize
);
1764 * These functions is used to return both the bootid UUID, and random
1765 * UUID. The difference is in whether table->data is NULL; if it is,
1766 * then a new UUID is generated and returned to the user.
1768 * If the user accesses this via the proc interface, it will be returned
1769 * as an ASCII string in the standard UUID format. If accesses via the
1770 * sysctl system call, it is returned as 16 bytes of binary data.
1772 static int proc_do_uuid(ctl_table
*table
, int write
, struct file
*filp
,
1773 void *buffer
, size_t *lenp
)
1775 ctl_table fake_table
;
1776 unsigned char buf
[64], tmp_uuid
[16], *uuid
;
1784 generate_random_uuid(uuid
);
1786 sprintf(buf
, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
1787 "%02x%02x%02x%02x%02x%02x",
1788 uuid
[0], uuid
[1], uuid
[2], uuid
[3],
1789 uuid
[4], uuid
[5], uuid
[6], uuid
[7],
1790 uuid
[8], uuid
[9], uuid
[10], uuid
[11],
1791 uuid
[12], uuid
[13], uuid
[14], uuid
[15]);
1792 fake_table
.data
= buf
;
1793 fake_table
.maxlen
= sizeof(buf
);
1795 return proc_dostring(&fake_table
, write
, filp
, buffer
, lenp
);
1798 static int uuid_strategy(ctl_table
*table
, int *name
, int nlen
,
1799 void *oldval
, size_t *oldlenp
,
1800 void *newval
, size_t newlen
, void **context
)
1802 unsigned char tmp_uuid
[16], *uuid
;
1805 if (!oldval
|| !oldlenp
)
1814 generate_random_uuid(uuid
);
1816 get_user(len
, oldlenp
);
1820 if (copy_to_user(oldval
, table
->data
, len
))
1822 if (put_user(len
, oldlenp
))
1828 ctl_table random_table
[] = {
1829 {RANDOM_POOLSIZE
, "poolsize",
1830 &sysctl_poolsize
, sizeof(int), 0644, NULL
,
1831 &proc_do_poolsize
, &poolsize_strategy
},
1832 {RANDOM_ENTROPY_COUNT
, "entropy_avail",
1833 NULL
, sizeof(int), 0444, NULL
,
1835 {RANDOM_READ_THRESH
, "read_wakeup_threshold",
1836 &random_read_wakeup_thresh
, sizeof(int), 0644, NULL
,
1837 &proc_dointvec_minmax
, &sysctl_intvec
, 0,
1838 &min_read_thresh
, &max_read_thresh
},
1839 {RANDOM_WRITE_THRESH
, "write_wakeup_threshold",
1840 &random_write_wakeup_thresh
, sizeof(int), 0644, NULL
,
1841 &proc_dointvec_minmax
, &sysctl_intvec
, 0,
1842 &min_write_thresh
, &max_write_thresh
},
1843 {RANDOM_BOOT_ID
, "boot_id",
1844 &sysctl_bootid
, 16, 0444, NULL
,
1845 &proc_do_uuid
, &uuid_strategy
},
1846 {RANDOM_UUID
, "uuid",
1847 NULL
, 16, 0444, NULL
,
1848 &proc_do_uuid
, &uuid_strategy
},
1852 static void sysctl_init_random(struct entropy_store
*random_state
)
1854 min_read_thresh
= 8;
1855 min_write_thresh
= 0;
1856 max_read_thresh
= max_write_thresh
=
1857 random_state
->poolinfo
.poolwords
* 32;
1858 random_table
[1].data
= &random_state
->entropy_count
;
1860 #endif /* CONFIG_SYSCTL */
1862 /********************************************************************
1864 * Random funtions for networking
1866 ********************************************************************/
1869 * TCP initial sequence number picking. This uses the random number
1870 * generator to pick an initial secret value. This value is hashed
1871 * along with the TCP endpoint information to provide a unique
1872 * starting point for each pair of TCP endpoints. This defeats
1873 * attacks which rely on guessing the initial TCP sequence number.
1874 * This algorithm was suggested by Steve Bellovin.
1876 * Using a very strong hash was taking an appreciable amount of the total
1877 * TCP connection establishment time, so this is a weaker hash,
1878 * compensated for by changing the secret periodically.
1881 /* F, G and H are basic MD4 functions: selection, majority, parity */
1882 #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
1883 #define G(x, y, z) (((x) & (y)) + (((x) ^ (y)) & (z)))
1884 #define H(x, y, z) ((x) ^ (y) ^ (z))
1887 * The generic round function. The application is so specific that
1888 * we don't bother protecting all the arguments with parens, as is generally
1889 * good macro practice, in favor of extra legibility.
1890 * Rotation is separate from addition to prevent recomputation
1892 #define ROUND(f, a, b, c, d, x, s) \
1893 (a += f(b, c, d) + x, a = (a << s) | (a >> (32-s)))
1895 #define K2 013240474631UL
1896 #define K3 015666365641UL
1899 * Basic cut-down MD4 transform. Returns only 32 bits of result.
1901 static __u32
halfMD4Transform (__u32
const buf
[4], __u32
const in
[8])
1903 __u32 a
= buf
[0], b
= buf
[1], c
= buf
[2], d
= buf
[3];
1906 ROUND(F
, a
, b
, c
, d
, in
[0] + K1
, 3);
1907 ROUND(F
, d
, a
, b
, c
, in
[1] + K1
, 7);
1908 ROUND(F
, c
, d
, a
, b
, in
[2] + K1
, 11);
1909 ROUND(F
, b
, c
, d
, a
, in
[3] + K1
, 19);
1910 ROUND(F
, a
, b
, c
, d
, in
[4] + K1
, 3);
1911 ROUND(F
, d
, a
, b
, c
, in
[5] + K1
, 7);
1912 ROUND(F
, c
, d
, a
, b
, in
[6] + K1
, 11);
1913 ROUND(F
, b
, c
, d
, a
, in
[7] + K1
, 19);
1916 ROUND(G
, a
, b
, c
, d
, in
[1] + K2
, 3);
1917 ROUND(G
, d
, a
, b
, c
, in
[3] + K2
, 5);
1918 ROUND(G
, c
, d
, a
, b
, in
[5] + K2
, 9);
1919 ROUND(G
, b
, c
, d
, a
, in
[7] + K2
, 13);
1920 ROUND(G
, a
, b
, c
, d
, in
[0] + K2
, 3);
1921 ROUND(G
, d
, a
, b
, c
, in
[2] + K2
, 5);
1922 ROUND(G
, c
, d
, a
, b
, in
[4] + K2
, 9);
1923 ROUND(G
, b
, c
, d
, a
, in
[6] + K2
, 13);
1926 ROUND(H
, a
, b
, c
, d
, in
[3] + K3
, 3);
1927 ROUND(H
, d
, a
, b
, c
, in
[7] + K3
, 9);
1928 ROUND(H
, c
, d
, a
, b
, in
[2] + K3
, 11);
1929 ROUND(H
, b
, c
, d
, a
, in
[6] + K3
, 15);
1930 ROUND(H
, a
, b
, c
, d
, in
[1] + K3
, 3);
1931 ROUND(H
, d
, a
, b
, c
, in
[5] + K3
, 9);
1932 ROUND(H
, c
, d
, a
, b
, in
[0] + K3
, 11);
1933 ROUND(H
, b
, c
, d
, a
, in
[4] + K3
, 15);
1935 return buf
[1] + b
; /* "most hashed" word */
1936 /* Alternative: return sum of all words? */
1939 #if 0 /* May be needed for IPv6 */
1941 static __u32
twothirdsMD4Transform (__u32
const buf
[4], __u32
const in
[12])
1943 __u32 a
= buf
[0], b
= buf
[1], c
= buf
[2], d
= buf
[3];
1946 ROUND(F
, a
, b
, c
, d
, in
[ 0] + K1
, 3);
1947 ROUND(F
, d
, a
, b
, c
, in
[ 1] + K1
, 7);
1948 ROUND(F
, c
, d
, a
, b
, in
[ 2] + K1
, 11);
1949 ROUND(F
, b
, c
, d
, a
, in
[ 3] + K1
, 19);
1950 ROUND(F
, a
, b
, c
, d
, in
[ 4] + K1
, 3);
1951 ROUND(F
, d
, a
, b
, c
, in
[ 5] + K1
, 7);
1952 ROUND(F
, c
, d
, a
, b
, in
[ 6] + K1
, 11);
1953 ROUND(F
, b
, c
, d
, a
, in
[ 7] + K1
, 19);
1954 ROUND(F
, a
, b
, c
, d
, in
[ 8] + K1
, 3);
1955 ROUND(F
, d
, a
, b
, c
, in
[ 9] + K1
, 7);
1956 ROUND(F
, c
, d
, a
, b
, in
[10] + K1
, 11);
1957 ROUND(F
, b
, c
, d
, a
, in
[11] + K1
, 19);
1960 ROUND(G
, a
, b
, c
, d
, in
[ 1] + K2
, 3);
1961 ROUND(G
, d
, a
, b
, c
, in
[ 3] + K2
, 5);
1962 ROUND(G
, c
, d
, a
, b
, in
[ 5] + K2
, 9);
1963 ROUND(G
, b
, c
, d
, a
, in
[ 7] + K2
, 13);
1964 ROUND(G
, a
, b
, c
, d
, in
[ 9] + K2
, 3);
1965 ROUND(G
, d
, a
, b
, c
, in
[11] + K2
, 5);
1966 ROUND(G
, c
, d
, a
, b
, in
[ 0] + K2
, 9);
1967 ROUND(G
, b
, c
, d
, a
, in
[ 2] + K2
, 13);
1968 ROUND(G
, a
, b
, c
, d
, in
[ 4] + K2
, 3);
1969 ROUND(G
, d
, a
, b
, c
, in
[ 6] + K2
, 5);
1970 ROUND(G
, c
, d
, a
, b
, in
[ 8] + K2
, 9);
1971 ROUND(G
, b
, c
, d
, a
, in
[10] + K2
, 13);
1974 ROUND(H
, a
, b
, c
, d
, in
[ 3] + K3
, 3);
1975 ROUND(H
, d
, a
, b
, c
, in
[ 7] + K3
, 9);
1976 ROUND(H
, c
, d
, a
, b
, in
[11] + K3
, 11);
1977 ROUND(H
, b
, c
, d
, a
, in
[ 2] + K3
, 15);
1978 ROUND(H
, a
, b
, c
, d
, in
[ 6] + K3
, 3);
1979 ROUND(H
, d
, a
, b
, c
, in
[10] + K3
, 9);
1980 ROUND(H
, c
, d
, a
, b
, in
[ 1] + K3
, 11);
1981 ROUND(H
, b
, c
, d
, a
, in
[ 5] + K3
, 15);
1982 ROUND(H
, a
, b
, c
, d
, in
[ 9] + K3
, 3);
1983 ROUND(H
, d
, a
, b
, c
, in
[ 0] + K3
, 9);
1984 ROUND(H
, c
, d
, a
, b
, in
[ 4] + K3
, 11);
1985 ROUND(H
, b
, c
, d
, a
, in
[ 8] + K3
, 15);
1987 return buf
[1] + b
; /* "most hashed" word */
1988 /* Alternative: return sum of all words? */
2000 /* This should not be decreased so low that ISNs wrap too fast. */
2001 #define REKEY_INTERVAL 300
2002 #define HASH_BITS 24
2004 __u32
secure_tcp_sequence_number(__u32 saddr
, __u32 daddr
,
2005 __u16 sport
, __u16 dport
)
2007 static __u32 rekey_time
= 0;
2008 static __u32 count
= 0;
2009 static __u32 secret
[12];
2014 * Pick a random secret every REKEY_INTERVAL seconds.
2016 do_gettimeofday(&tv
); /* We need the usecs below... */
2018 if (!rekey_time
|| (tv
.tv_sec
- rekey_time
) > REKEY_INTERVAL
) {
2019 rekey_time
= tv
.tv_sec
;
2020 /* First three words are overwritten below. */
2021 get_random_bytes(&secret
[3], sizeof(secret
)-12);
2022 count
= (tv
.tv_sec
/REKEY_INTERVAL
) << HASH_BITS
;
2026 * Pick a unique starting offset for each TCP connection endpoints
2027 * (saddr, daddr, sport, dport).
2028 * Note that the words are placed into the first words to be
2029 * mixed in with the halfMD4. This is because the starting
2030 * vector is also a random secret (at secret+8), and further
2031 * hashing fixed data into it isn't going to improve anything,
2032 * so we should get started with the variable data.
2036 secret
[2]=(sport
<< 16) + dport
;
2038 seq
= (halfMD4Transform(secret
+8, secret
) &
2039 ((1<<HASH_BITS
)-1)) + count
;
2042 * As close as possible to RFC 793, which
2043 * suggests using a 250 kHz clock.
2044 * Further reading shows this assumes 2 Mb/s networks.
2045 * For 10 Mb/s Ethernet, a 1 MHz clock is appropriate.
2046 * That's funny, Linux has one built in! Use it!
2047 * (Networks are faster now - should this be increased?)
2049 seq
+= tv
.tv_usec
+ tv
.tv_sec
*1000000;
2051 printk("init_seq(%lx, %lx, %d, %d) = %d\n",
2052 saddr
, daddr
, sport
, dport
, seq
);
2057 #ifdef CONFIG_SYN_COOKIES
2059 * Secure SYN cookie computation. This is the algorithm worked out by
2060 * Dan Bernstein and Eric Schenk.
2062 * For linux I implement the 1 minute counter by looking at the jiffies clock.
2063 * The count is passed in as a parameter, so this code doesn't much care.
2066 #define COOKIEBITS 24 /* Upper bits store count */
2067 #define COOKIEMASK (((__u32)1 << COOKIEBITS) - 1)
2069 static int syncookie_init
= 0;
2070 static __u32 syncookie_secret
[2][16-3+HASH_BUFFER_SIZE
];
2072 __u32
secure_tcp_syn_cookie(__u32 saddr
, __u32 daddr
, __u16 sport
,
2073 __u16 dport
, __u32 sseq
, __u32 count
, __u32 data
)
2075 __u32 tmp
[16 + HASH_BUFFER_SIZE
+ HASH_EXTRA_SIZE
];
2079 * Pick two random secrets the first time we need a cookie.
2081 if (syncookie_init
== 0) {
2082 get_random_bytes(syncookie_secret
, sizeof(syncookie_secret
));
2087 * Compute the secure sequence number.
2088 * The output should be:
2089 * HASH(sec1,saddr,sport,daddr,dport,sec1) + sseq + (count * 2^24)
2090 * + (HASH(sec2,saddr,sport,daddr,dport,count,sec2) % 2^24).
2091 * Where sseq is their sequence number and count increases every
2093 * As an extra hack, we add a small "data" value that encodes the
2094 * MSS into the second hash value.
2097 memcpy(tmp
+3, syncookie_secret
[0], sizeof(syncookie_secret
[0]));
2100 tmp
[2]=(sport
<< 16) + dport
;
2101 HASH_TRANSFORM(tmp
+16, tmp
);
2102 seq
= tmp
[17] + sseq
+ (count
<< COOKIEBITS
);
2104 memcpy(tmp
+3, syncookie_secret
[1], sizeof(syncookie_secret
[1]));
2107 tmp
[2]=(sport
<< 16) + dport
;
2108 tmp
[3] = count
; /* minute counter */
2109 HASH_TRANSFORM(tmp
+16, tmp
);
2111 /* Add in the second hash and the data */
2112 return seq
+ ((tmp
[17] + data
) & COOKIEMASK
);
2116 * This retrieves the small "data" value from the syncookie.
2117 * If the syncookie is bad, the data returned will be out of
2118 * range. This must be checked by the caller.
2120 * The count value used to generate the cookie must be within
2121 * "maxdiff" if the current (passed-in) "count". The return value
2122 * is (__u32)-1 if this test fails.
2124 __u32
check_tcp_syn_cookie(__u32 cookie
, __u32 saddr
, __u32 daddr
, __u16 sport
,
2125 __u16 dport
, __u32 sseq
, __u32 count
, __u32 maxdiff
)
2127 __u32 tmp
[16 + HASH_BUFFER_SIZE
+ HASH_EXTRA_SIZE
];
2130 if (syncookie_init
== 0)
2131 return (__u32
)-1; /* Well, duh! */
2133 /* Strip away the layers from the cookie */
2134 memcpy(tmp
+3, syncookie_secret
[0], sizeof(syncookie_secret
[0]));
2137 tmp
[2]=(sport
<< 16) + dport
;
2138 HASH_TRANSFORM(tmp
+16, tmp
);
2139 cookie
-= tmp
[17] + sseq
;
2140 /* Cookie is now reduced to (count * 2^24) ^ (hash % 2^24) */
2142 diff
= (count
- (cookie
>> COOKIEBITS
)) & ((__u32
)-1 >> COOKIEBITS
);
2143 if (diff
>= maxdiff
)
2146 memcpy(tmp
+3, syncookie_secret
[1], sizeof(syncookie_secret
[1]));
2149 tmp
[2] = (sport
<< 16) + dport
;
2150 tmp
[3] = count
- diff
; /* minute counter */
2151 HASH_TRANSFORM(tmp
+16, tmp
);
2153 return (cookie
- tmp
[17]) & COOKIEMASK
; /* Leaving the data behind */