upgrade to linux 2.6.10-1.12_FC2
[linux-2.6.git] / drivers / char / random.c
1 /*
2  * random.c -- A strong random number generator
3  *
4  * Version 1.89, last modified 19-Sep-99
5  * 
6  * Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999.  All
7  * rights reserved.
8  *
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.
21  * 
22  * ALTERNATIVELY, this product may be distributed under the terms of
23  * the GNU General Public License, in which case the provisions of the GPL are
24  * required INSTEAD OF the above restrictions.  (This clause is
25  * necessary due to a potential bad interaction between the GPL and
26  * the restrictions contained in a BSD-style copyright.)
27  * 
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.
40  */
41
42 /*
43  * (now, with legal B.S. out of the way.....) 
44  * 
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.
51  *
52  * Theory of operation
53  * ===================
54  * 
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.
65  * 
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.
77  * 
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.
89  * 
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.
97  * 
98  * Exported interfaces ---- output
99  * ===============================
100  * 
101  * There are three exported interfaces; the first is one designed to
102  * be used from within the kernel:
103  *
104  *      void get_random_bytes(void *buf, int nbytes);
105  *
106  * This interface will return the requested number of random bytes,
107  * and place it in the requested buffer.
108  * 
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.
115  * 
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.
121  *
122  * Exported interfaces ---- input
123  * ==============================
124  * 
125  * The current exported interfaces for gathering environmental noise
126  * from the devices are:
127  * 
128  *      void add_keyboard_randomness(unsigned char scancode);
129  *      void add_mouse_randomness(__u32 mouse_data);
130  *      void add_interrupt_randomness(int irq);
131  * 
132  * add_keyboard_randomness() uses the inter-keypress timing, as well as the
133  * scancode as random inputs into the "entropy pool".
134  * 
135  * add_mouse_randomness() uses the mouse interrupt timing, as well as
136  * the reported position of the mouse from the hardware.
137  *
138  * add_interrupt_randomness() uses the inter-interrupt timing as random
139  * inputs to the entropy pool.  Note that not all interrupts are good
140  * sources of randomness!  For example, the timer interrupts is not a
141  * good choice, because the periodicity of the interrupts is too
142  * regular, and hence predictable to an attacker.  Disk interrupts are
143  * a better measure, since the timing of the disk interrupts are more
144  * unpredictable.
145  * 
146  * All of these routines try to estimate how many bits of randomness a
147  * particular randomness source.  They do this by keeping track of the
148  * first and second order deltas of the event timings.
149  *
150  * Ensuring unpredictability at system startup
151  * ============================================
152  * 
153  * When any operating system starts up, it will go through a sequence
154  * of actions that are fairly predictable by an adversary, especially
155  * if the start-up does not involve interaction with a human operator.
156  * This reduces the actual number of bits of unpredictability in the
157  * entropy pool below the value in entropy_count.  In order to
158  * counteract this effect, it helps to carry information in the
159  * entropy pool across shut-downs and start-ups.  To do this, put the
160  * following lines an appropriate script which is run during the boot
161  * sequence: 
162  *
163  *      echo "Initializing random number generator..."
164  *      random_seed=/var/run/random-seed
165  *      # Carry a random seed from start-up to start-up
166  *      # Load and then save the whole entropy pool
167  *      if [ -f $random_seed ]; then
168  *              cat $random_seed >/dev/urandom
169  *      else
170  *              touch $random_seed
171  *      fi
172  *      chmod 600 $random_seed
173  *      poolfile=/proc/sys/kernel/random/poolsize
174  *      [ -r $poolfile ] && bytes=`cat $poolfile` || bytes=512
175  *      dd if=/dev/urandom of=$random_seed count=1 bs=$bytes
176  *
177  * and the following lines in an appropriate script which is run as
178  * the system is shutdown:
179  *
180  *      # Carry a random seed from shut-down to start-up
181  *      # Save the whole entropy pool
182  *      echo "Saving random seed..."
183  *      random_seed=/var/run/random-seed
184  *      touch $random_seed
185  *      chmod 600 $random_seed
186  *      poolfile=/proc/sys/kernel/random/poolsize
187  *      [ -r $poolfile ] && bytes=`cat $poolfile` || bytes=512
188  *      dd if=/dev/urandom of=$random_seed count=1 bs=$bytes
189  *
190  * For example, on most modern systems using the System V init
191  * scripts, such code fragments would be found in
192  * /etc/rc.d/init.d/random.  On older Linux systems, the correct script
193  * location might be in /etc/rcb.d/rc.local or /etc/rc.d/rc.0.
194  * 
195  * Effectively, these commands cause the contents of the entropy pool
196  * to be saved at shut-down time and reloaded into the entropy pool at
197  * start-up.  (The 'dd' in the addition to the bootup script is to
198  * make sure that /etc/random-seed is different for every start-up,
199  * even if the system crashes without executing rc.0.)  Even with
200  * complete knowledge of the start-up activities, predicting the state
201  * of the entropy pool requires knowledge of the previous history of
202  * the system.
203  *
204  * Configuring the /dev/random driver under Linux
205  * ==============================================
206  *
207  * The /dev/random driver under Linux uses minor numbers 8 and 9 of
208  * the /dev/mem major number (#1).  So if your system does not have
209  * /dev/random and /dev/urandom created already, they can be created
210  * by using the commands:
211  *
212  *      mknod /dev/random c 1 8
213  *      mknod /dev/urandom c 1 9
214  * 
215  * Acknowledgements:
216  * =================
217  *
218  * Ideas for constructing this random number generator were derived
219  * from Pretty Good Privacy's random number generator, and from private
220  * discussions with Phil Karn.  Colin Plumb provided a faster random
221  * number generator, which speed up the mixing function of the entropy
222  * pool, taken from PGPfone.  Dale Worley has also contributed many
223  * useful ideas and suggestions to improve this driver.
224  * 
225  * Any flaws in the design are solely my responsibility, and should
226  * not be attributed to the Phil, Colin, or any of authors of PGP.
227  * 
228  * The code for SHA transform was taken from Peter Gutmann's
229  * implementation, which has been placed in the public domain.
230  * The code for MD5 transform was taken from Colin Plumb's
231  * implementation, which has been placed in the public domain.
232  * The MD5 cryptographic checksum was devised by Ronald Rivest, and is
233  * documented in RFC 1321, "The MD5 Message Digest Algorithm".
234  * 
235  * Further background information on this topic may be obtained from
236  * RFC 1750, "Randomness Recommendations for Security", by Donald
237  * Eastlake, Steve Crocker, and Jeff Schiller.
238  */
239
240 #include <linux/utsname.h>
241 #include <linux/config.h>
242 #include <linux/module.h>
243 #include <linux/kernel.h>
244 #include <linux/major.h>
245 #include <linux/string.h>
246 #include <linux/fcntl.h>
247 #include <linux/slab.h>
248 #include <linux/random.h>
249 #include <linux/poll.h>
250 #include <linux/init.h>
251 #include <linux/fs.h>
252 #include <linux/workqueue.h>
253 #include <linux/genhd.h>
254 #include <linux/interrupt.h>
255 #include <linux/spinlock.h>
256 #include <linux/percpu.h>
257
258 #include <asm/processor.h>
259 #include <asm/uaccess.h>
260 #include <asm/irq.h>
261 #include <asm/io.h>
262
263 /*
264  * Configuration information
265  */
266 #define DEFAULT_POOL_SIZE 512
267 #define SECONDARY_POOL_SIZE 128
268 #define BATCH_ENTROPY_SIZE 256
269 #define USE_SHA
270
271 /*
272  * The minimum number of bits of entropy before we wake up a read on
273  * /dev/random.  Should be enough to do a significant reseed.
274  */
275 static int random_read_wakeup_thresh = 64;
276
277 /*
278  * If the entropy count falls under this number of bits, then we
279  * should wake up processes which are selecting or polling on write
280  * access to /dev/random.
281  */
282 static int random_write_wakeup_thresh = 128;
283
284 /*
285  * When the input pool goes over trickle_thresh, start dropping most
286  * samples to avoid wasting CPU time and reduce lock contention.
287  */
288
289 static int trickle_thresh = DEFAULT_POOL_SIZE * 7;
290
291 static DEFINE_PER_CPU(int, trickle_count) = 0;
292
293 /*
294  * A pool of size .poolwords is stirred with a primitive polynomial
295  * of degree .poolwords over GF(2).  The taps for various sizes are
296  * defined below.  They are chosen to be evenly spaced (minimum RMS
297  * distance from evenly spaced; the numbers in the comments are a
298  * scaled squared error sum) except for the last tap, which is 1 to
299  * get the twisting happening as fast as possible.
300  */
301 static struct poolinfo {
302         int     poolwords;
303         int     tap1, tap2, tap3, tap4, tap5;
304 } poolinfo_table[] = {
305         /* x^2048 + x^1638 + x^1231 + x^819 + x^411 + x + 1  -- 115 */
306         { 2048, 1638,   1231,   819,    411,    1 },
307
308         /* x^1024 + x^817 + x^615 + x^412 + x^204 + x + 1 -- 290 */
309         { 1024, 817,    615,    412,    204,    1 },
310 #if 0                           /* Alternate polynomial */
311         /* x^1024 + x^819 + x^616 + x^410 + x^207 + x^2 + 1 -- 115 */
312         { 1024, 819,    616,    410,    207,    2 },
313 #endif
314
315         /* x^512 + x^411 + x^308 + x^208 + x^104 + x + 1 -- 225 */
316         { 512,  411,    308,    208,    104,    1 },
317 #if 0                           /* Alternates */
318         /* x^512 + x^409 + x^307 + x^206 + x^102 + x^2 + 1 -- 95 */
319         { 512,  409,    307,    206,    102,    2 },
320         /* x^512 + x^409 + x^309 + x^205 + x^103 + x^2 + 1 -- 95 */
321         { 512,  409,    309,    205,    103,    2 },
322 #endif
323
324         /* x^256 + x^205 + x^155 + x^101 + x^52 + x + 1 -- 125 */
325         { 256,  205,    155,    101,    52,     1 },
326
327         /* x^128 + x^103 + x^76 + x^51 +x^25 + x + 1 -- 105 */
328         { 128,  103,    76,     51,     25,     1 },
329 #if 0   /* Alternate polynomial */
330         /* x^128 + x^103 + x^78 + x^51 + x^27 + x^2 + 1 -- 70 */
331         { 128,  103,    78,     51,     27,     2 },
332 #endif
333
334         /* x^64 + x^52 + x^39 + x^26 + x^14 + x + 1 -- 15 */
335         { 64,   52,     39,     26,     14,     1 },
336
337         /* x^32 + x^26 + x^20 + x^14 + x^7 + x + 1 -- 15 */
338         { 32,   26,     20,     14,     7,      1 },
339
340         { 0,    0,      0,      0,      0,      0 },
341 };
342
343 #define POOLBITS        poolwords*32
344 #define POOLBYTES       poolwords*4
345
346 /*
347  * For the purposes of better mixing, we use the CRC-32 polynomial as
348  * well to make a twisted Generalized Feedback Shift Reigster
349  *
350  * (See M. Matsumoto & Y. Kurita, 1992.  Twisted GFSR generators.  ACM
351  * Transactions on Modeling and Computer Simulation 2(3):179-194.
352  * Also see M. Matsumoto & Y. Kurita, 1994.  Twisted GFSR generators
353  * II.  ACM Transactions on Mdeling and Computer Simulation 4:254-266)
354  *
355  * Thanks to Colin Plumb for suggesting this.
356  * 
357  * We have not analyzed the resultant polynomial to prove it primitive;
358  * in fact it almost certainly isn't.  Nonetheless, the irreducible factors
359  * of a random large-degree polynomial over GF(2) are more than large enough
360  * that periodicity is not a concern.
361  * 
362  * The input hash is much less sensitive than the output hash.  All
363  * that we want of it is that it be a good non-cryptographic hash;
364  * i.e. it not produce collisions when fed "random" data of the sort
365  * we expect to see.  As long as the pool state differs for different
366  * inputs, we have preserved the input entropy and done a good job.
367  * The fact that an intelligent attacker can construct inputs that
368  * will produce controlled alterations to the pool's state is not
369  * important because we don't consider such inputs to contribute any
370  * randomness.  The only property we need with respect to them is that
371  * the attacker can't increase his/her knowledge of the pool's state.
372  * Since all additions are reversible (knowing the final state and the
373  * input, you can reconstruct the initial state), if an attacker has
374  * any uncertainty about the initial state, he/she can only shuffle
375  * that uncertainty about, but never cause any collisions (which would
376  * decrease the uncertainty).
377  *
378  * The chosen system lets the state of the pool be (essentially) the input
379  * modulo the generator polymnomial.  Now, for random primitive polynomials,
380  * this is a universal class of hash functions, meaning that the chance
381  * of a collision is limited by the attacker's knowledge of the generator
382  * polynomail, so if it is chosen at random, an attacker can never force
383  * a collision.  Here, we use a fixed polynomial, but we *can* assume that
384  * ###--> it is unknown to the processes generating the input entropy. <-###
385  * Because of this important property, this is a good, collision-resistant
386  * hash; hash collisions will occur no more often than chance.
387  */
388
389 /*
390  * Linux 2.2 compatibility
391  */
392 #ifndef DECLARE_WAITQUEUE
393 #define DECLARE_WAITQUEUE(WAIT, PTR)    struct wait_queue WAIT = { PTR, NULL }
394 #endif
395 #ifndef DECLARE_WAIT_QUEUE_HEAD
396 #define DECLARE_WAIT_QUEUE_HEAD(WAIT) struct wait_queue *WAIT
397 #endif
398
399 /*
400  * Static global variables
401  */
402 static struct entropy_store *random_state; /* The default global store */
403 static struct entropy_store *sec_random_state; /* secondary store */
404 static struct entropy_store *urandom_state; /* For urandom */
405 static DECLARE_WAIT_QUEUE_HEAD(random_read_wait);
406 static DECLARE_WAIT_QUEUE_HEAD(random_write_wait);
407
408 /*
409  * Forward procedure declarations
410  */
411 #ifdef CONFIG_SYSCTL
412 static void sysctl_init_random(struct entropy_store *random_state);
413 #endif
414
415 /*****************************************************************
416  *
417  * Utility functions, with some ASM defined functions for speed
418  * purposes
419  * 
420  *****************************************************************/
421
422 /*
423  * Unfortunately, while the GCC optimizer for the i386 understands how
424  * to optimize a static rotate left of x bits, it doesn't know how to
425  * deal with a variable rotate of x bits.  So we use a bit of asm magic.
426  */
427 #if (!defined (__i386__))
428 static inline __u32 rotate_left(int i, __u32 word)
429 {
430         return (word << i) | (word >> (32 - i));
431         
432 }
433 #else
434 static inline __u32 rotate_left(int i, __u32 word)
435 {
436         __asm__("roll %%cl,%0"
437                 :"=r" (word)
438                 :"0" (word),"c" (i));
439         return word;
440 }
441 #endif
442
443 /*
444  * More asm magic....
445  * 
446  * For entropy estimation, we need to do an integral base 2
447  * logarithm.  
448  *
449  * Note the "12bits" suffix - this is used for numbers between
450  * 0 and 4095 only.  This allows a few shortcuts.
451  */
452 #if 0   /* Slow but clear version */
453 static inline __u32 int_ln_12bits(__u32 word)
454 {
455         __u32 nbits = 0;
456         
457         while (word >>= 1)
458                 nbits++;
459         return nbits;
460 }
461 #else   /* Faster (more clever) version, courtesy Colin Plumb */
462 static inline __u32 int_ln_12bits(__u32 word)
463 {
464         /* Smear msbit right to make an n-bit mask */
465         word |= word >> 8;
466         word |= word >> 4;
467         word |= word >> 2;
468         word |= word >> 1;
469         /* Remove one bit to make this a logarithm */
470         word >>= 1;
471         /* Count the bits set in the word */
472         word -= (word >> 1) & 0x555;
473         word = (word & 0x333) + ((word >> 2) & 0x333);
474         word += (word >> 4);
475         word += (word >> 8);
476         return word & 15;
477 }
478 #endif
479
480 #if 0
481 #define DEBUG_ENT(fmt, arg...) printk(KERN_DEBUG "random: " fmt, ## arg)
482 #else
483 #define DEBUG_ENT(fmt, arg...) do {} while (0)
484 #endif
485
486 /**********************************************************************
487  *
488  * OS independent entropy store.   Here are the functions which handle
489  * storing entropy in an entropy pool.
490  * 
491  **********************************************************************/
492
493 struct entropy_store {
494         /* mostly-read data: */
495         struct poolinfo poolinfo;
496         __u32           *pool;
497         const char      *name;
498
499         /* read-write data: */
500         spinlock_t lock ____cacheline_aligned_in_smp;
501         unsigned        add_ptr;
502         int             entropy_count;
503         int             input_rotate;
504 };
505
506 /*
507  * Initialize the entropy store.  The input argument is the size of
508  * the random pool.
509  *
510  * Returns an negative error if there is a problem.
511  */
512 static int create_entropy_store(int size, const char *name,
513                                 struct entropy_store **ret_bucket)
514 {
515         struct  entropy_store   *r;
516         struct  poolinfo        *p;
517         int     poolwords;
518
519         poolwords = (size + 3) / 4; /* Convert bytes->words */
520         /* The pool size must be a multiple of 16 32-bit words */
521         poolwords = ((poolwords + 15) / 16) * 16;
522
523         for (p = poolinfo_table; p->poolwords; p++) {
524                 if (poolwords == p->poolwords)
525                         break;
526         }
527         if (p->poolwords == 0)
528                 return -EINVAL;
529
530         r = kmalloc(sizeof(struct entropy_store), GFP_KERNEL);
531         if (!r)
532                 return -ENOMEM;
533
534         memset (r, 0, sizeof(struct entropy_store));
535         r->poolinfo = *p;
536
537         r->pool = kmalloc(POOLBYTES, GFP_KERNEL);
538         if (!r->pool) {
539                 kfree(r);
540                 return -ENOMEM;
541         }
542         memset(r->pool, 0, POOLBYTES);
543         r->lock = SPIN_LOCK_UNLOCKED;
544         r->name = name;
545         *ret_bucket = r;
546         return 0;
547 }
548
549 /* Clear the entropy pool and associated counters. */
550 static void clear_entropy_store(struct entropy_store *r)
551 {
552         r->add_ptr = 0;
553         r->entropy_count = 0;
554         r->input_rotate = 0;
555         memset(r->pool, 0, r->poolinfo.POOLBYTES);
556 }
557 #ifdef CONFIG_SYSCTL
558 static void free_entropy_store(struct entropy_store *r)
559 {
560         if (r->pool)
561                 kfree(r->pool);
562         kfree(r);
563 }
564 #endif
565 /*
566  * This function adds a byte into the entropy "pool".  It does not
567  * update the entropy estimate.  The caller should call
568  * credit_entropy_store if this is appropriate.
569  * 
570  * The pool is stirred with a primitive polynomial of the appropriate
571  * degree, and then twisted.  We twist by three bits at a time because
572  * it's cheap to do so and helps slightly in the expected case where
573  * the entropy is concentrated in the low-order bits.
574  */
575 static void __add_entropy_words(struct entropy_store *r, const __u32 *in,
576                                 int nwords, __u32 out[16])
577 {
578         static __u32 const twist_table[8] = {
579                          0, 0x3b6e20c8, 0x76dc4190, 0x4db26158,
580                 0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278 };
581         unsigned long i, add_ptr, tap1, tap2, tap3, tap4, tap5;
582         int new_rotate, input_rotate;
583         int wordmask = r->poolinfo.poolwords - 1;
584         __u32 w, next_w;
585         unsigned long flags;
586
587         /* Taps are constant, so we can load them without holding r->lock.  */
588         tap1 = r->poolinfo.tap1;
589         tap2 = r->poolinfo.tap2;
590         tap3 = r->poolinfo.tap3;
591         tap4 = r->poolinfo.tap4;
592         tap5 = r->poolinfo.tap5;
593         next_w = *in++;
594
595         spin_lock_irqsave(&r->lock, flags);
596         prefetch_range(r->pool, wordmask);
597         input_rotate = r->input_rotate;
598         add_ptr = r->add_ptr;
599
600         while (nwords--) {
601                 w = rotate_left(input_rotate, next_w);
602                 if (nwords > 0)
603                         next_w = *in++;
604                 i = add_ptr = (add_ptr - 1) & wordmask;
605                 /*
606                  * Normally, we add 7 bits of rotation to the pool.
607                  * At the beginning of the pool, add an extra 7 bits
608                  * rotation, so that successive passes spread the
609                  * input bits across the pool evenly.
610                  */
611                 new_rotate = input_rotate + 14;
612                 if (i)
613                         new_rotate = input_rotate + 7;
614                 input_rotate = new_rotate & 31;
615
616                 /* XOR in the various taps */
617                 w ^= r->pool[(i + tap1) & wordmask];
618                 w ^= r->pool[(i + tap2) & wordmask];
619                 w ^= r->pool[(i + tap3) & wordmask];
620                 w ^= r->pool[(i + tap4) & wordmask];
621                 w ^= r->pool[(i + tap5) & wordmask];
622                 w ^= r->pool[i];
623                 r->pool[i] = (w >> 3) ^ twist_table[w & 7];
624         }
625
626         r->input_rotate = input_rotate;
627         r->add_ptr = add_ptr;
628
629         if (out) {
630                 for (i = 0; i < 16; i++) {
631                         out[i] = r->pool[add_ptr];
632                         add_ptr = (add_ptr - 1) & wordmask;
633                 }
634         }
635
636         spin_unlock_irqrestore(&r->lock, flags);
637 }
638
639 static inline void add_entropy_words(struct entropy_store *r, const __u32 *in,
640                                      int nwords)
641 {
642         __add_entropy_words(r, in, nwords, NULL);
643 }
644
645
646 /*
647  * Credit (or debit) the entropy store with n bits of entropy
648  */
649 static void credit_entropy_store(struct entropy_store *r, int nbits)
650 {
651         unsigned long flags;
652
653         spin_lock_irqsave(&r->lock, flags);
654
655         if (r->entropy_count + nbits < 0) {
656                 DEBUG_ENT("negative entropy/overflow (%d+%d)\n",
657                           r->entropy_count, nbits);
658                 r->entropy_count = 0;
659         } else if (r->entropy_count + nbits > r->poolinfo.POOLBITS) {
660                 r->entropy_count = r->poolinfo.POOLBITS;
661         } else {
662                 r->entropy_count += nbits;
663                 if (nbits)
664                         DEBUG_ENT("Added %d entropy credits to %s, now %d\n",
665                                   nbits, r->name, r->entropy_count);
666         }
667
668         spin_unlock_irqrestore(&r->lock, flags);
669 }
670
671 /**********************************************************************
672  *
673  * Entropy batch input management
674  *
675  * We batch entropy to be added to avoid increasing interrupt latency
676  *
677  **********************************************************************/
678
679 struct sample {
680         __u32 data[2];
681         int credit;
682 };
683
684 static struct sample *batch_entropy_pool, *batch_entropy_copy;
685 static int      batch_head, batch_tail;
686 static spinlock_t batch_lock = SPIN_LOCK_UNLOCKED;
687
688 static int      batch_max;
689 static void batch_entropy_process(void *private_);
690 static DECLARE_WORK(batch_work, batch_entropy_process, NULL);
691
692 /* note: the size must be a power of 2 */
693 static int __init batch_entropy_init(int size, struct entropy_store *r)
694 {
695         batch_entropy_pool = kmalloc(size*sizeof(struct sample), GFP_KERNEL);
696         if (!batch_entropy_pool)
697                 return -1;
698         batch_entropy_copy = kmalloc(size*sizeof(struct sample), GFP_KERNEL);
699         if (!batch_entropy_copy) {
700                 kfree(batch_entropy_pool);
701                 return -1;
702         }
703         batch_head = batch_tail = 0;
704         batch_work.data = r;
705         batch_max = size;
706         return 0;
707 }
708
709 /*
710  * Changes to the entropy data is put into a queue rather than being added to
711  * the entropy counts directly.  This is presumably to avoid doing heavy
712  * hashing calculations during an interrupt in add_timer_randomness().
713  * Instead, the entropy is only added to the pool by keventd.
714  */
715 static void batch_entropy_store(u32 a, u32 b, int num)
716 {
717         int new;
718         unsigned long flags;
719
720         if (!batch_max)
721                 return;
722
723         spin_lock_irqsave(&batch_lock, flags);
724
725         batch_entropy_pool[batch_head].data[0] = a;
726         batch_entropy_pool[batch_head].data[1] = b;
727         batch_entropy_pool[batch_head].credit = num;
728
729         if (((batch_head - batch_tail) & (batch_max-1)) >= (batch_max / 2)) {
730                 /*
731                  * Schedule it for the next timer tick:
732                  */
733                 schedule_delayed_work(&batch_work, 1);
734         }
735
736         new = (batch_head+1) & (batch_max-1);
737         if (new == batch_tail) {
738                 DEBUG_ENT("batch entropy buffer full\n");
739         } else {
740                 batch_head = new;
741         }
742
743         spin_unlock_irqrestore(&batch_lock, flags);
744 }
745
746 /*
747  * Flush out the accumulated entropy operations, adding entropy to the passed
748  * store (normally random_state).  If that store has enough entropy, alternate
749  * between randomizing the data of the primary and secondary stores.
750  */
751 static void batch_entropy_process(void *private_)
752 {
753         struct entropy_store *r = (struct entropy_store *) private_, *p;
754         int max_entropy = r->poolinfo.POOLBITS;
755         unsigned head, tail;
756
757         /* Mixing into the pool is expensive, so copy over the batch
758          * data and release the batch lock. The pool is at least half
759          * full, so don't worry too much about copying only the used
760          * part.
761          */
762         spin_lock_irq(&batch_lock);
763
764         memcpy(batch_entropy_copy, batch_entropy_pool,
765                batch_max*sizeof(struct sample));
766
767         head = batch_head;
768         tail = batch_tail;
769         batch_tail = batch_head;
770
771         spin_unlock_irq(&batch_lock);
772
773         p = r;
774         while (head != tail) {
775                 if (r->entropy_count >= max_entropy) {
776                         r = (r == sec_random_state) ?   random_state :
777                                                         sec_random_state;
778                         max_entropy = r->poolinfo.POOLBITS;
779                 }
780                 add_entropy_words(r, batch_entropy_copy[tail].data, 2);
781                 credit_entropy_store(r, batch_entropy_copy[tail].credit);
782                 tail = (tail+1) & (batch_max-1);
783         }
784         if (p->entropy_count >= random_read_wakeup_thresh)
785                 wake_up_interruptible(&random_read_wait);
786 }
787
788 /*********************************************************************
789  *
790  * Entropy input management
791  *
792  *********************************************************************/
793
794 /* There is one of these per entropy source */
795 struct timer_rand_state {
796         cycles_t        last_time;
797         long            last_delta,last_delta2;
798         unsigned        dont_count_entropy:1;
799 };
800
801 static struct timer_rand_state keyboard_timer_state;
802 static struct timer_rand_state mouse_timer_state;
803 static struct timer_rand_state extract_timer_state;
804 static struct timer_rand_state *irq_timer_state[NR_IRQS];
805
806 /*
807  * This function adds entropy to the entropy "pool" by using timing
808  * delays.  It uses the timer_rand_state structure to make an estimate
809  * of how many bits of entropy this call has added to the pool.
810  *
811  * The number "num" is also added to the pool - it should somehow describe
812  * the type of event which just happened.  This is currently 0-255 for
813  * keyboard scan codes, and 256 upwards for interrupts.
814  *
815  */
816 static void add_timer_randomness(struct timer_rand_state *state, unsigned num)
817 {
818         cycles_t        time;
819         long            delta, delta2, delta3;
820         int             entropy = 0;
821
822         preempt_disable();
823         /* if over the trickle threshold, use only 1 in 4096 samples */
824         if ( random_state->entropy_count > trickle_thresh &&
825              (__get_cpu_var(trickle_count)++ & 0xfff))
826                 goto out;
827
828         /*
829          * Use get_cycles() if implemented, otherwise fall back to
830          * jiffies.
831          */
832         time = get_cycles();
833         if (time)
834                 num ^= (u32)((time >> 31) >> 1);
835         else
836                 time = jiffies;
837
838         /*
839          * Calculate number of bits of randomness we probably added.
840          * We take into account the first, second and third-order deltas
841          * in order to make our estimate.
842          */
843         if (!state->dont_count_entropy) {
844                 delta = time - state->last_time;
845                 state->last_time = time;
846
847                 delta2 = delta - state->last_delta;
848                 state->last_delta = delta;
849
850                 delta3 = delta2 - state->last_delta2;
851                 state->last_delta2 = delta2;
852
853                 if (delta < 0)
854                         delta = -delta;
855                 if (delta2 < 0)
856                         delta2 = -delta2;
857                 if (delta3 < 0)
858                         delta3 = -delta3;
859                 if (delta > delta2)
860                         delta = delta2;
861                 if (delta > delta3)
862                         delta = delta3;
863
864                 /*
865                  * delta is now minimum absolute delta.
866                  * Round down by 1 bit on general principles,
867                  * and limit entropy entimate to 12 bits.
868                  */
869                 delta >>= 1;
870                 delta &= (1 << 12) - 1;
871
872                 entropy = int_ln_12bits(delta);
873         }
874         batch_entropy_store(num, time, entropy);
875 out:
876         preempt_enable();
877 }
878
879 void add_keyboard_randomness(unsigned char scancode)
880 {
881         static unsigned char last_scancode;
882         /* ignore autorepeat (multiple key down w/o key up) */
883         if (scancode != last_scancode) {
884                 last_scancode = scancode;
885                 add_timer_randomness(&keyboard_timer_state, scancode);
886         }
887 }
888
889 void add_mouse_randomness(__u32 mouse_data)
890 {
891         add_timer_randomness(&mouse_timer_state, mouse_data);
892 }
893
894 EXPORT_SYMBOL(add_mouse_randomness);
895
896 void add_interrupt_randomness(int irq)
897 {
898         if (irq >= NR_IRQS || irq_timer_state[irq] == 0)
899                 return;
900
901         add_timer_randomness(irq_timer_state[irq], 0x100+irq);
902 }
903
904 void add_disk_randomness(struct gendisk *disk)
905 {
906         if (!disk || !disk->random)
907                 return;
908         /* first major is 1, so we get >= 0x200 here */
909         add_timer_randomness(disk->random, 0x100+MKDEV(disk->major, disk->first_minor));
910 }
911
912 EXPORT_SYMBOL(add_disk_randomness);
913
914 /******************************************************************
915  *
916  * Hash function definition
917  *
918  *******************************************************************/
919
920 /*
921  * This chunk of code defines a function
922  * void HASH_TRANSFORM(__u32 digest[HASH_BUFFER_SIZE + HASH_EXTRA_SIZE],
923  *              __u32 const data[16])
924  * 
925  * The function hashes the input data to produce a digest in the first
926  * HASH_BUFFER_SIZE words of the digest[] array, and uses HASH_EXTRA_SIZE
927  * more words for internal purposes.  (This buffer is exported so the
928  * caller can wipe it once rather than this code doing it each call,
929  * and tacking it onto the end of the digest[] array is the quick and
930  * dirty way of doing it.)
931  *
932  * It so happens that MD5 and SHA share most of the initial vector
933  * used to initialize the digest[] array before the first call:
934  * 1) 0x67452301
935  * 2) 0xefcdab89
936  * 3) 0x98badcfe
937  * 4) 0x10325476
938  * 5) 0xc3d2e1f0 (SHA only)
939  * 
940  * For /dev/random purposes, the length of the data being hashed is
941  * fixed in length, so appending a bit count in the usual way is not
942  * cryptographically necessary.
943  */
944
945 #ifdef USE_SHA
946
947 #define HASH_BUFFER_SIZE 5
948 #define HASH_EXTRA_SIZE 80
949 #define HASH_TRANSFORM SHATransform
950
951 /* Various size/speed tradeoffs are available.  Choose 0..3. */
952 #define SHA_CODE_SIZE 0
953
954 /*
955  * SHA transform algorithm, taken from code written by Peter Gutmann,
956  * and placed in the public domain.
957  */
958
959 /* The SHA f()-functions.  */
960
961 #define f1(x,y,z)   ( z ^ (x & (y^z)) )         /* Rounds  0-19: x ? y : z */
962 #define f2(x,y,z)   (x ^ y ^ z)                 /* Rounds 20-39: XOR */
963 #define f3(x,y,z)   ( (x & y) + (z & (x ^ y)) ) /* Rounds 40-59: majority */
964 #define f4(x,y,z)   (x ^ y ^ z)                 /* Rounds 60-79: XOR */
965
966 /* The SHA Mysterious Constants */
967
968 #define K1  0x5A827999L                 /* Rounds  0-19: sqrt(2) * 2^30 */
969 #define K2  0x6ED9EBA1L                 /* Rounds 20-39: sqrt(3) * 2^30 */
970 #define K3  0x8F1BBCDCL                 /* Rounds 40-59: sqrt(5) * 2^30 */
971 #define K4  0xCA62C1D6L                 /* Rounds 60-79: sqrt(10) * 2^30 */
972
973 #define ROTL(n,X)  ( ( ( X ) << n ) | ( ( X ) >> ( 32 - n ) ) )
974
975 #define subRound(a, b, c, d, e, f, k, data) \
976     ( e += ROTL( 5, a ) + f( b, c, d ) + k + data, b = ROTL( 30, b ) )
977
978
979 static void SHATransform(__u32 digest[85], __u32 const data[16])
980 {
981     __u32 A, B, C, D, E;     /* Local vars */
982     __u32 TEMP;
983     int i;
984 #define W (digest + HASH_BUFFER_SIZE)   /* Expanded data array */
985
986     /*
987      * Do the preliminary expansion of 16 to 80 words.  Doing it
988      * out-of-line line this is faster than doing it in-line on
989      * register-starved machines like the x86, and not really any
990      * slower on real processors.
991      */
992     memcpy(W, data, 16*sizeof(__u32));
993     for (i = 0; i < 64; i++) {
994             TEMP = W[i] ^ W[i+2] ^ W[i+8] ^ W[i+13];
995             W[i+16] = ROTL(1, TEMP);
996     }
997
998     /* Set up first buffer and local data buffer */
999     A = digest[ 0 ];
1000     B = digest[ 1 ];
1001     C = digest[ 2 ];
1002     D = digest[ 3 ];
1003     E = digest[ 4 ];
1004
1005     /* Heavy mangling, in 4 sub-rounds of 20 iterations each. */
1006 #if SHA_CODE_SIZE == 0
1007     /*
1008      * Approximately 50% of the speed of the largest version, but
1009      * takes up 1/16 the space.  Saves about 6k on an i386 kernel.
1010      */
1011     for (i = 0; i < 80; i++) {
1012         if (i < 40) {
1013             if (i < 20)
1014                 TEMP = f1(B, C, D) + K1;
1015             else
1016                 TEMP = f2(B, C, D) + K2;
1017         } else {
1018             if (i < 60)
1019                 TEMP = f3(B, C, D) + K3;
1020             else
1021                 TEMP = f4(B, C, D) + K4;
1022         }
1023         TEMP += ROTL(5, A) + E + W[i];
1024         E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
1025     }
1026 #elif SHA_CODE_SIZE == 1
1027     for (i = 0; i < 20; i++) {
1028         TEMP = f1(B, C, D) + K1 + ROTL(5, A) + E + W[i];
1029         E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
1030     }
1031     for (; i < 40; i++) {
1032         TEMP = f2(B, C, D) + K2 + ROTL(5, A) + E + W[i];
1033         E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
1034     }
1035     for (; i < 60; i++) {
1036         TEMP = f3(B, C, D) + K3 + ROTL(5, A) + E + W[i];
1037         E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
1038     }
1039     for (; i < 80; i++) {
1040         TEMP = f4(B, C, D) + K4 + ROTL(5, A) + E + W[i];
1041         E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
1042     }
1043 #elif SHA_CODE_SIZE == 2
1044     for (i = 0; i < 20; i += 5) {
1045         subRound( A, B, C, D, E, f1, K1, W[ i   ] );
1046         subRound( E, A, B, C, D, f1, K1, W[ i+1 ] );
1047         subRound( D, E, A, B, C, f1, K1, W[ i+2 ] );
1048         subRound( C, D, E, A, B, f1, K1, W[ i+3 ] );
1049         subRound( B, C, D, E, A, f1, K1, W[ i+4 ] );
1050     }
1051     for (; i < 40; i += 5) {
1052         subRound( A, B, C, D, E, f2, K2, W[ i   ] );
1053         subRound( E, A, B, C, D, f2, K2, W[ i+1 ] );
1054         subRound( D, E, A, B, C, f2, K2, W[ i+2 ] );
1055         subRound( C, D, E, A, B, f2, K2, W[ i+3 ] );
1056         subRound( B, C, D, E, A, f2, K2, W[ i+4 ] );
1057     }
1058     for (; i < 60; i += 5) {
1059         subRound( A, B, C, D, E, f3, K3, W[ i   ] );
1060         subRound( E, A, B, C, D, f3, K3, W[ i+1 ] );
1061         subRound( D, E, A, B, C, f3, K3, W[ i+2 ] );
1062         subRound( C, D, E, A, B, f3, K3, W[ i+3 ] );
1063         subRound( B, C, D, E, A, f3, K3, W[ i+4 ] );
1064     }
1065     for (; i < 80; i += 5) {
1066         subRound( A, B, C, D, E, f4, K4, W[ i   ] );
1067         subRound( E, A, B, C, D, f4, K4, W[ i+1 ] );
1068         subRound( D, E, A, B, C, f4, K4, W[ i+2 ] );
1069         subRound( C, D, E, A, B, f4, K4, W[ i+3 ] );
1070         subRound( B, C, D, E, A, f4, K4, W[ i+4 ] );
1071     }
1072 #elif SHA_CODE_SIZE == 3 /* Really large version */
1073     subRound( A, B, C, D, E, f1, K1, W[  0 ] );
1074     subRound( E, A, B, C, D, f1, K1, W[  1 ] );
1075     subRound( D, E, A, B, C, f1, K1, W[  2 ] );
1076     subRound( C, D, E, A, B, f1, K1, W[  3 ] );
1077     subRound( B, C, D, E, A, f1, K1, W[  4 ] );
1078     subRound( A, B, C, D, E, f1, K1, W[  5 ] );
1079     subRound( E, A, B, C, D, f1, K1, W[  6 ] );
1080     subRound( D, E, A, B, C, f1, K1, W[  7 ] );
1081     subRound( C, D, E, A, B, f1, K1, W[  8 ] );
1082     subRound( B, C, D, E, A, f1, K1, W[  9 ] );
1083     subRound( A, B, C, D, E, f1, K1, W[ 10 ] );
1084     subRound( E, A, B, C, D, f1, K1, W[ 11 ] );
1085     subRound( D, E, A, B, C, f1, K1, W[ 12 ] );
1086     subRound( C, D, E, A, B, f1, K1, W[ 13 ] );
1087     subRound( B, C, D, E, A, f1, K1, W[ 14 ] );
1088     subRound( A, B, C, D, E, f1, K1, W[ 15 ] );
1089     subRound( E, A, B, C, D, f1, K1, W[ 16 ] );
1090     subRound( D, E, A, B, C, f1, K1, W[ 17 ] );
1091     subRound( C, D, E, A, B, f1, K1, W[ 18 ] );
1092     subRound( B, C, D, E, A, f1, K1, W[ 19 ] );
1093
1094     subRound( A, B, C, D, E, f2, K2, W[ 20 ] );
1095     subRound( E, A, B, C, D, f2, K2, W[ 21 ] );
1096     subRound( D, E, A, B, C, f2, K2, W[ 22 ] );
1097     subRound( C, D, E, A, B, f2, K2, W[ 23 ] );
1098     subRound( B, C, D, E, A, f2, K2, W[ 24 ] );
1099     subRound( A, B, C, D, E, f2, K2, W[ 25 ] );
1100     subRound( E, A, B, C, D, f2, K2, W[ 26 ] );
1101     subRound( D, E, A, B, C, f2, K2, W[ 27 ] );
1102     subRound( C, D, E, A, B, f2, K2, W[ 28 ] );
1103     subRound( B, C, D, E, A, f2, K2, W[ 29 ] );
1104     subRound( A, B, C, D, E, f2, K2, W[ 30 ] );
1105     subRound( E, A, B, C, D, f2, K2, W[ 31 ] );
1106     subRound( D, E, A, B, C, f2, K2, W[ 32 ] );
1107     subRound( C, D, E, A, B, f2, K2, W[ 33 ] );
1108     subRound( B, C, D, E, A, f2, K2, W[ 34 ] );
1109     subRound( A, B, C, D, E, f2, K2, W[ 35 ] );
1110     subRound( E, A, B, C, D, f2, K2, W[ 36 ] );
1111     subRound( D, E, A, B, C, f2, K2, W[ 37 ] );
1112     subRound( C, D, E, A, B, f2, K2, W[ 38 ] );
1113     subRound( B, C, D, E, A, f2, K2, W[ 39 ] );
1114     
1115     subRound( A, B, C, D, E, f3, K3, W[ 40 ] );
1116     subRound( E, A, B, C, D, f3, K3, W[ 41 ] );
1117     subRound( D, E, A, B, C, f3, K3, W[ 42 ] );
1118     subRound( C, D, E, A, B, f3, K3, W[ 43 ] );
1119     subRound( B, C, D, E, A, f3, K3, W[ 44 ] );
1120     subRound( A, B, C, D, E, f3, K3, W[ 45 ] );
1121     subRound( E, A, B, C, D, f3, K3, W[ 46 ] );
1122     subRound( D, E, A, B, C, f3, K3, W[ 47 ] );
1123     subRound( C, D, E, A, B, f3, K3, W[ 48 ] );
1124     subRound( B, C, D, E, A, f3, K3, W[ 49 ] );
1125     subRound( A, B, C, D, E, f3, K3, W[ 50 ] );
1126     subRound( E, A, B, C, D, f3, K3, W[ 51 ] );
1127     subRound( D, E, A, B, C, f3, K3, W[ 52 ] );
1128     subRound( C, D, E, A, B, f3, K3, W[ 53 ] );
1129     subRound( B, C, D, E, A, f3, K3, W[ 54 ] );
1130     subRound( A, B, C, D, E, f3, K3, W[ 55 ] );
1131     subRound( E, A, B, C, D, f3, K3, W[ 56 ] );
1132     subRound( D, E, A, B, C, f3, K3, W[ 57 ] );
1133     subRound( C, D, E, A, B, f3, K3, W[ 58 ] );
1134     subRound( B, C, D, E, A, f3, K3, W[ 59 ] );
1135
1136     subRound( A, B, C, D, E, f4, K4, W[ 60 ] );
1137     subRound( E, A, B, C, D, f4, K4, W[ 61 ] );
1138     subRound( D, E, A, B, C, f4, K4, W[ 62 ] );
1139     subRound( C, D, E, A, B, f4, K4, W[ 63 ] );
1140     subRound( B, C, D, E, A, f4, K4, W[ 64 ] );
1141     subRound( A, B, C, D, E, f4, K4, W[ 65 ] );
1142     subRound( E, A, B, C, D, f4, K4, W[ 66 ] );
1143     subRound( D, E, A, B, C, f4, K4, W[ 67 ] );
1144     subRound( C, D, E, A, B, f4, K4, W[ 68 ] );
1145     subRound( B, C, D, E, A, f4, K4, W[ 69 ] );
1146     subRound( A, B, C, D, E, f4, K4, W[ 70 ] );
1147     subRound( E, A, B, C, D, f4, K4, W[ 71 ] );
1148     subRound( D, E, A, B, C, f4, K4, W[ 72 ] );
1149     subRound( C, D, E, A, B, f4, K4, W[ 73 ] );
1150     subRound( B, C, D, E, A, f4, K4, W[ 74 ] );
1151     subRound( A, B, C, D, E, f4, K4, W[ 75 ] );
1152     subRound( E, A, B, C, D, f4, K4, W[ 76 ] );
1153     subRound( D, E, A, B, C, f4, K4, W[ 77 ] );
1154     subRound( C, D, E, A, B, f4, K4, W[ 78 ] );
1155     subRound( B, C, D, E, A, f4, K4, W[ 79 ] );
1156 #else
1157 #error Illegal SHA_CODE_SIZE
1158 #endif
1159
1160     /* Build message digest */
1161     digest[ 0 ] += A;
1162     digest[ 1 ] += B;
1163     digest[ 2 ] += C;
1164     digest[ 3 ] += D;
1165     digest[ 4 ] += E;
1166
1167         /* W is wiped by the caller */
1168 #undef W
1169 }
1170
1171 #undef ROTL
1172 #undef f1
1173 #undef f2
1174 #undef f3
1175 #undef f4
1176 #undef K1       
1177 #undef K2
1178 #undef K3       
1179 #undef K4       
1180 #undef subRound
1181         
1182 #else /* !USE_SHA - Use MD5 */
1183
1184 #define HASH_BUFFER_SIZE 4
1185 #define HASH_EXTRA_SIZE 0
1186 #define HASH_TRANSFORM MD5Transform
1187         
1188 /*
1189  * MD5 transform algorithm, taken from code written by Colin Plumb,
1190  * and put into the public domain
1191  */
1192
1193 /* The four core functions - F1 is optimized somewhat */
1194
1195 /* #define F1(x, y, z) (x & y | ~x & z) */
1196 #define F1(x, y, z) (z ^ (x & (y ^ z)))
1197 #define F2(x, y, z) F1(z, x, y)
1198 #define F3(x, y, z) (x ^ y ^ z)
1199 #define F4(x, y, z) (y ^ (x | ~z))
1200
1201 /* This is the central step in the MD5 algorithm. */
1202 #define MD5STEP(f, w, x, y, z, data, s) \
1203         ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
1204
1205 /*
1206  * The core of the MD5 algorithm, this alters an existing MD5 hash to
1207  * reflect the addition of 16 longwords of new data.  MD5Update blocks
1208  * the data and converts bytes into longwords for this routine.
1209  */
1210 static void MD5Transform(__u32 buf[HASH_BUFFER_SIZE], __u32 const in[16])
1211 {
1212         __u32 a, b, c, d;
1213
1214         a = buf[0];
1215         b = buf[1];
1216         c = buf[2];
1217         d = buf[3];
1218
1219         MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478,  7);
1220         MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
1221         MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
1222         MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
1223         MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf,  7);
1224         MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
1225         MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
1226         MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
1227         MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8,  7);
1228         MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
1229         MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
1230         MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
1231         MD5STEP(F1, a, b, c, d, in[12]+0x6b901122,  7);
1232         MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
1233         MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
1234         MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
1235
1236         MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562,  5);
1237         MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340,  9);
1238         MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
1239         MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
1240         MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d,  5);
1241         MD5STEP(F2, d, a, b, c, in[10]+0x02441453,  9);
1242         MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
1243         MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
1244         MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6,  5);
1245         MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6,  9);
1246         MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
1247         MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
1248         MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905,  5);
1249         MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8,  9);
1250         MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
1251         MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
1252
1253         MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942,  4);
1254         MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
1255         MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
1256         MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
1257         MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44,  4);
1258         MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
1259         MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
1260         MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
1261         MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6,  4);
1262         MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
1263         MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
1264         MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
1265         MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039,  4);
1266         MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
1267         MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
1268         MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
1269
1270         MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244,  6);
1271         MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
1272         MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
1273         MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
1274         MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3,  6);
1275         MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
1276         MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
1277         MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
1278         MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f,  6);
1279         MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
1280         MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
1281         MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
1282         MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82,  6);
1283         MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
1284         MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
1285         MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
1286
1287         buf[0] += a;
1288         buf[1] += b;
1289         buf[2] += c;
1290         buf[3] += d;
1291 }
1292
1293 #undef F1
1294 #undef F2
1295 #undef F3
1296 #undef F4
1297 #undef MD5STEP
1298
1299 #endif /* !USE_SHA */
1300
1301 /*********************************************************************
1302  *
1303  * Entropy extraction routines
1304  *
1305  *********************************************************************/
1306
1307 #define EXTRACT_ENTROPY_USER            1
1308 #define EXTRACT_ENTROPY_SECONDARY       2
1309 #define EXTRACT_ENTROPY_LIMIT           4
1310 #define TMP_BUF_SIZE                    (HASH_BUFFER_SIZE + HASH_EXTRA_SIZE)
1311 #define SEC_XFER_SIZE                   (TMP_BUF_SIZE*4)
1312
1313 static ssize_t extract_entropy(struct entropy_store *r, void * buf,
1314                                size_t nbytes, int flags);
1315
1316 /*
1317  * This utility inline function is responsible for transfering entropy
1318  * from the primary pool to the secondary extraction pool. We make
1319  * sure we pull enough for a 'catastrophic reseed'.
1320  */
1321 static inline void xfer_secondary_pool(struct entropy_store *r,
1322                                        size_t nbytes, __u32 *tmp)
1323 {
1324         if (r->entropy_count < nbytes * 8 &&
1325             r->entropy_count < r->poolinfo.POOLBITS) {
1326                 int bytes = max_t(int, random_read_wakeup_thresh / 8,
1327                                 min_t(int, nbytes, TMP_BUF_SIZE));
1328
1329                 DEBUG_ENT("%04d %04d : going to reseed %s with %d bits "
1330                           "(%d of %d requested)\n",
1331                           random_state->entropy_count,
1332                           sec_random_state->entropy_count,
1333                           r->name, bytes * 8, nbytes * 8, r->entropy_count);
1334
1335                 bytes=extract_entropy(random_state, tmp, bytes,
1336                                       EXTRACT_ENTROPY_LIMIT);
1337                 add_entropy_words(r, tmp, bytes);
1338                 credit_entropy_store(r, bytes*8);
1339         }
1340 }
1341
1342 /*
1343  * This function extracts randomness from the "entropy pool", and
1344  * returns it in a buffer.  This function computes how many remaining
1345  * bits of entropy are left in the pool, but it does not restrict the
1346  * number of bytes that are actually obtained.  If the EXTRACT_ENTROPY_USER
1347  * flag is given, then the buf pointer is assumed to be in user space.
1348  *
1349  * If the EXTRACT_ENTROPY_SECONDARY flag is given, then we are actually
1350  * extracting entropy from the secondary pool, and can refill from the
1351  * primary pool if needed.
1352  *
1353  * Note: extract_entropy() assumes that .poolwords is a multiple of 16 words.
1354  */
1355 static ssize_t extract_entropy(struct entropy_store *r, void * buf,
1356                                size_t nbytes, int flags)
1357 {
1358         ssize_t ret, i;
1359         __u32 tmp[TMP_BUF_SIZE], data[16];
1360         __u32 x;
1361         unsigned long cpuflags;
1362
1363
1364         /* Redundant, but just in case... */
1365         if (r->entropy_count > r->poolinfo.POOLBITS)
1366                 r->entropy_count = r->poolinfo.POOLBITS;
1367
1368         if (flags & EXTRACT_ENTROPY_SECONDARY)
1369                 xfer_secondary_pool(r, nbytes, tmp);
1370
1371         /* Hold lock while accounting */
1372         spin_lock_irqsave(&r->lock, cpuflags);
1373
1374         DEBUG_ENT("%04d %04d : trying to extract %d bits from %s\n",
1375                   random_state->entropy_count,
1376                   sec_random_state->entropy_count,
1377                   nbytes * 8, r->name);
1378
1379         if (flags & EXTRACT_ENTROPY_LIMIT && nbytes >= r->entropy_count / 8)
1380                 nbytes = r->entropy_count / 8;
1381
1382         if (r->entropy_count / 8 >= nbytes)
1383                 r->entropy_count -= nbytes*8;
1384         else
1385                 r->entropy_count = 0;
1386
1387         if (r->entropy_count < random_write_wakeup_thresh)
1388                 wake_up_interruptible(&random_write_wait);
1389
1390         DEBUG_ENT("Debiting %d entropy credits from %s%s\n",
1391                   nbytes * 8, r->name,
1392                   flags & EXTRACT_ENTROPY_LIMIT ? "" : " (unlimited)");
1393
1394         spin_unlock_irqrestore(&r->lock, cpuflags);
1395
1396         ret = 0;
1397         while (nbytes) {
1398                 /*
1399                  * Check if we need to break out or reschedule....
1400                  */
1401                 if ((flags & EXTRACT_ENTROPY_USER) && need_resched()) {
1402                         if (signal_pending(current)) {
1403                                 if (ret == 0)
1404                                         ret = -ERESTARTSYS;
1405                                 break;
1406                         }
1407
1408                         DEBUG_ENT("%04d %04d : extract feeling sleepy (%d bytes left)\n",
1409                                   random_state->entropy_count,
1410                                   sec_random_state->entropy_count, nbytes);
1411
1412                         schedule();
1413
1414                         DEBUG_ENT("%04d %04d : extract woke up\n",
1415                                   random_state->entropy_count,
1416                                   sec_random_state->entropy_count);
1417                 }
1418
1419                 /* Hash the pool to get the output */
1420                 tmp[0] = 0x67452301;
1421                 tmp[1] = 0xefcdab89;
1422                 tmp[2] = 0x98badcfe;
1423                 tmp[3] = 0x10325476;
1424 #ifdef USE_SHA
1425                 tmp[4] = 0xc3d2e1f0;
1426 #endif
1427                 /*
1428                  * As we hash the pool, we mix intermediate values of
1429                  * the hash back into the pool.  This eliminates
1430                  * backtracking attacks (where the attacker knows
1431                  * the state of the pool plus the current outputs, and
1432                  * attempts to find previous ouputs), unless the hash
1433                  * function can be inverted.
1434                  */
1435                 for (i = 0, x = 0; i < r->poolinfo.poolwords; i += 16, x+=2) {
1436                         HASH_TRANSFORM(tmp, r->pool+i);
1437                         add_entropy_words(r, &tmp[x%HASH_BUFFER_SIZE], 1);
1438                 }
1439
1440                 /*
1441                  * To avoid duplicates, we atomically extract a
1442                  * portion of the pool while mixing, and hash one
1443                  * final time.
1444                  */
1445                 __add_entropy_words(r, &tmp[x%HASH_BUFFER_SIZE], 1, data);
1446                 HASH_TRANSFORM(tmp, data);
1447
1448                 /*
1449                  * In case the hash function has some recognizable
1450                  * output pattern, we fold it in half.
1451                  */
1452                 for (i = 0; i <  HASH_BUFFER_SIZE/2; i++)
1453                         tmp[i] ^= tmp[i + (HASH_BUFFER_SIZE+1)/2];
1454 #if HASH_BUFFER_SIZE & 1        /* There's a middle word to deal with */
1455                 x = tmp[HASH_BUFFER_SIZE/2];
1456                 x ^= (x >> 16);         /* Fold it in half */
1457                 ((__u16 *)tmp)[HASH_BUFFER_SIZE-1] = (__u16)x;
1458 #endif
1459                 
1460                 /* Copy data to destination buffer */
1461                 i = min(nbytes, HASH_BUFFER_SIZE*sizeof(__u32)/2);
1462                 if (flags & EXTRACT_ENTROPY_USER) {
1463                         i -= copy_to_user(buf, (__u8 const *)tmp, i);
1464                         if (!i) {
1465                                 ret = -EFAULT;
1466                                 break;
1467                         }
1468                 } else
1469                         memcpy(buf, (__u8 const *)tmp, i);
1470                 nbytes -= i;
1471                 buf += i;
1472                 ret += i;
1473         }
1474
1475         /* Wipe data just returned from memory */
1476         memset(tmp, 0, sizeof(tmp));
1477         
1478         return ret;
1479 }
1480
1481 /*
1482  * This function is the exported kernel interface.  It returns some
1483  * number of good random numbers, suitable for seeding TCP sequence
1484  * numbers, etc.
1485  */
1486 void get_random_bytes(void *buf, int nbytes)
1487 {
1488         struct entropy_store *r = urandom_state;
1489         int flags = EXTRACT_ENTROPY_SECONDARY;
1490
1491         if (!r)
1492                 r = sec_random_state;
1493         if (!r) {
1494                 r = random_state;
1495                 flags = 0;
1496         }
1497         if (!r) {
1498                 printk(KERN_NOTICE "get_random_bytes called before "
1499                                    "random driver initialization\n");
1500                 return;
1501         }
1502         extract_entropy(r, (char *) buf, nbytes, flags);
1503 }
1504
1505 EXPORT_SYMBOL(get_random_bytes);
1506
1507 /*********************************************************************
1508  *
1509  * Functions to interface with Linux
1510  *
1511  *********************************************************************/
1512
1513 /*
1514  * Initialize the random pool with standard stuff.
1515  *
1516  * NOTE: This is an OS-dependent function.
1517  */
1518 static void init_std_data(struct entropy_store *r)
1519 {
1520         struct timeval  tv;
1521         __u32           words[2];
1522         char            *p;
1523         int             i;
1524
1525         do_gettimeofday(&tv);
1526         words[0] = tv.tv_sec;
1527         words[1] = tv.tv_usec;
1528         add_entropy_words(r, words, 2);
1529
1530         /*
1531          *      This doesn't lock system.utsname. However, we are generating
1532          *      entropy so a race with a name set here is fine.
1533          */
1534         p = (char *) &system_utsname;
1535         for (i = sizeof(system_utsname) / sizeof(words); i; i--) {
1536                 memcpy(words, p, sizeof(words));
1537                 add_entropy_words(r, words, sizeof(words)/4);
1538                 p += sizeof(words);
1539         }
1540 }
1541
1542 static int __init rand_initialize(void)
1543 {
1544         int i;
1545
1546         if (create_entropy_store(DEFAULT_POOL_SIZE, "primary", &random_state))
1547                 goto err;
1548         if (batch_entropy_init(BATCH_ENTROPY_SIZE, random_state))
1549                 goto err;
1550         if (create_entropy_store(SECONDARY_POOL_SIZE, "secondary",
1551                                  &sec_random_state))
1552                 goto err;
1553         if (create_entropy_store(SECONDARY_POOL_SIZE, "urandom",
1554                                  &urandom_state))
1555                 goto err;
1556         clear_entropy_store(random_state);
1557         clear_entropy_store(sec_random_state);
1558         clear_entropy_store(urandom_state);
1559         init_std_data(random_state);
1560         init_std_data(sec_random_state);
1561         init_std_data(urandom_state);
1562 #ifdef CONFIG_SYSCTL
1563         sysctl_init_random(random_state);
1564 #endif
1565         for (i = 0; i < NR_IRQS; i++)
1566                 irq_timer_state[i] = NULL;
1567         memset(&keyboard_timer_state, 0, sizeof(struct timer_rand_state));
1568         memset(&mouse_timer_state, 0, sizeof(struct timer_rand_state));
1569         memset(&extract_timer_state, 0, sizeof(struct timer_rand_state));
1570         extract_timer_state.dont_count_entropy = 1;
1571         return 0;
1572 err:
1573         return -1;
1574 }
1575 module_init(rand_initialize);
1576
1577 void rand_initialize_irq(int irq)
1578 {
1579         struct timer_rand_state *state;
1580         
1581         if (irq >= NR_IRQS || irq_timer_state[irq])
1582                 return;
1583
1584         /*
1585          * If kmalloc returns null, we just won't use that entropy
1586          * source.
1587          */
1588         state = kmalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
1589         if (state) {
1590                 memset(state, 0, sizeof(struct timer_rand_state));
1591                 irq_timer_state[irq] = state;
1592         }
1593 }
1594  
1595 void rand_initialize_disk(struct gendisk *disk)
1596 {
1597         struct timer_rand_state *state;
1598         
1599         /*
1600          * If kmalloc returns null, we just won't use that entropy
1601          * source.
1602          */
1603         state = kmalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
1604         if (state) {
1605                 memset(state, 0, sizeof(struct timer_rand_state));
1606                 disk->random = state;
1607         }
1608 }
1609
1610 static ssize_t
1611 random_read(struct file * file, char __user * buf, size_t nbytes, loff_t *ppos)
1612 {
1613         DECLARE_WAITQUEUE(wait, current);
1614         ssize_t                 n, retval = 0, count = 0;
1615         
1616         if (nbytes == 0)
1617                 return 0;
1618
1619         while (nbytes > 0) {
1620                 n = nbytes;
1621                 if (n > SEC_XFER_SIZE)
1622                         n = SEC_XFER_SIZE;
1623
1624                 DEBUG_ENT("%04d %04d : reading %d bits, p: %d s: %d\n",
1625                           random_state->entropy_count,
1626                           sec_random_state->entropy_count,
1627                           n*8, random_state->entropy_count,
1628                           sec_random_state->entropy_count);
1629
1630                 n = extract_entropy(sec_random_state, buf, n,
1631                                     EXTRACT_ENTROPY_USER |
1632                                     EXTRACT_ENTROPY_LIMIT |
1633                                     EXTRACT_ENTROPY_SECONDARY);
1634
1635                 DEBUG_ENT("%04d %04d : read got %d bits (%d still needed)\n",
1636                           random_state->entropy_count,
1637                           sec_random_state->entropy_count,
1638                           n*8, (nbytes-n)*8);
1639
1640                 if (n == 0) {
1641                         if (file->f_flags & O_NONBLOCK) {
1642                                 retval = -EAGAIN;
1643                                 break;
1644                         }
1645                         if (signal_pending(current)) {
1646                                 retval = -ERESTARTSYS;
1647                                 break;
1648                         }
1649
1650                         DEBUG_ENT("%04d %04d : sleeping?\n",
1651                                   random_state->entropy_count,
1652                                   sec_random_state->entropy_count);
1653
1654                         set_current_state(TASK_INTERRUPTIBLE);
1655                         add_wait_queue(&random_read_wait, &wait);
1656
1657                         if (sec_random_state->entropy_count / 8 == 0)
1658                                 schedule();
1659
1660                         set_current_state(TASK_RUNNING);
1661                         remove_wait_queue(&random_read_wait, &wait);
1662
1663                         DEBUG_ENT("%04d %04d : waking up\n",
1664                                   random_state->entropy_count,
1665                                   sec_random_state->entropy_count);
1666
1667                         continue;
1668                 }
1669
1670                 if (n < 0) {
1671                         retval = n;
1672                         break;
1673                 }
1674                 count += n;
1675                 buf += n;
1676                 nbytes -= n;
1677                 break;          /* This break makes the device work */
1678                                 /* like a named pipe */
1679         }
1680
1681         /*
1682          * If we gave the user some bytes, update the access time.
1683          */
1684         if (count)
1685                 file_accessed(file);
1686         
1687         return (count ? count : retval);
1688 }
1689
1690 static ssize_t
1691 urandom_read(struct file * file, char __user * buf,
1692                       size_t nbytes, loff_t *ppos)
1693 {
1694         int flags = EXTRACT_ENTROPY_USER;
1695         unsigned long cpuflags;
1696
1697         spin_lock_irqsave(&random_state->lock, cpuflags);
1698         if (random_state->entropy_count > random_state->poolinfo.POOLBITS)
1699                 flags |= EXTRACT_ENTROPY_SECONDARY;
1700         spin_unlock_irqrestore(&random_state->lock, cpuflags);
1701
1702         return extract_entropy(urandom_state, buf, nbytes, flags);
1703 }
1704
1705 static unsigned int
1706 random_poll(struct file *file, poll_table * wait)
1707 {
1708         unsigned int mask;
1709
1710         poll_wait(file, &random_read_wait, wait);
1711         poll_wait(file, &random_write_wait, wait);
1712         mask = 0;
1713         if (random_state->entropy_count >= random_read_wakeup_thresh)
1714                 mask |= POLLIN | POLLRDNORM;
1715         if (random_state->entropy_count < random_write_wakeup_thresh)
1716                 mask |= POLLOUT | POLLWRNORM;
1717         return mask;
1718 }
1719
1720 static ssize_t
1721 random_write(struct file * file, const char __user * buffer,
1722              size_t count, loff_t *ppos)
1723 {
1724         int             ret = 0;
1725         size_t          bytes;
1726         __u32           buf[16];
1727         const char      __user *p = buffer;
1728         size_t          c = count;
1729
1730         while (c > 0) {
1731                 bytes = min(c, sizeof(buf));
1732
1733                 bytes -= copy_from_user(&buf, p, bytes);
1734                 if (!bytes) {
1735                         ret = -EFAULT;
1736                         break;
1737                 }
1738                 c -= bytes;
1739                 p += bytes;
1740
1741                 add_entropy_words(random_state, buf, (bytes + 3) / 4);
1742         }
1743         if (p == buffer) {
1744                 return (ssize_t)ret;
1745         } else {
1746                 file->f_dentry->d_inode->i_mtime = CURRENT_TIME;
1747                 mark_inode_dirty(file->f_dentry->d_inode);
1748                 return (ssize_t)(p - buffer);
1749         }
1750 }
1751
1752 static int
1753 random_ioctl(struct inode * inode, struct file * file,
1754              unsigned int cmd, unsigned long arg)
1755 {
1756         int size, ent_count;
1757         int __user *p = (int __user *)arg;
1758         int retval;
1759         
1760         switch (cmd) {
1761         case RNDGETENTCNT:
1762                 ent_count = random_state->entropy_count;
1763                 if (put_user(ent_count, p))
1764                         return -EFAULT;
1765                 return 0;
1766         case RNDADDTOENTCNT:
1767                 if (!capable(CAP_SYS_ADMIN))
1768                         return -EPERM;
1769                 if (get_user(ent_count, p))
1770                         return -EFAULT;
1771                 credit_entropy_store(random_state, ent_count);
1772                 /*
1773                  * Wake up waiting processes if we have enough
1774                  * entropy.
1775                  */
1776                 if (random_state->entropy_count >= random_read_wakeup_thresh)
1777                         wake_up_interruptible(&random_read_wait);
1778                 return 0;
1779         case RNDADDENTROPY:
1780                 if (!capable(CAP_SYS_ADMIN))
1781                         return -EPERM;
1782                 if (get_user(ent_count, p++))
1783                         return -EFAULT;
1784                 if (ent_count < 0)
1785                         return -EINVAL;
1786                 if (get_user(size, p++))
1787                         return -EFAULT;
1788                 retval = random_write(file, (const char __user *) p,
1789                                       size, &file->f_pos);
1790                 if (retval < 0)
1791                         return retval;
1792                 credit_entropy_store(random_state, ent_count);
1793                 /*
1794                  * Wake up waiting processes if we have enough
1795                  * entropy.
1796                  */
1797                 if (random_state->entropy_count >= random_read_wakeup_thresh)
1798                         wake_up_interruptible(&random_read_wait);
1799                 return 0;
1800         case RNDZAPENTCNT:
1801                 if (!capable(CAP_SYS_ADMIN))
1802                         return -EPERM;
1803                 random_state->entropy_count = 0;
1804                 return 0;
1805         case RNDCLEARPOOL:
1806                 /* Clear the entropy pool and associated counters. */
1807                 if (!capable(CAP_SYS_ADMIN))
1808                         return -EPERM;
1809                 clear_entropy_store(random_state);
1810                 init_std_data(random_state);
1811                 return 0;
1812         default:
1813                 return -EINVAL;
1814         }
1815 }
1816
1817 struct file_operations random_fops = {
1818         .read           = random_read,
1819         .write          = random_write,
1820         .poll           = random_poll,
1821         .ioctl          = random_ioctl,
1822 };
1823
1824 struct file_operations urandom_fops = {
1825         .read           = urandom_read,
1826         .write          = random_write,
1827         .ioctl          = random_ioctl,
1828 };
1829
1830 /***************************************************************
1831  * Random UUID interface
1832  * 
1833  * Used here for a Boot ID, but can be useful for other kernel 
1834  * drivers.
1835  ***************************************************************/
1836
1837 /*
1838  * Generate random UUID
1839  */
1840 void generate_random_uuid(unsigned char uuid_out[16])
1841 {
1842         get_random_bytes(uuid_out, 16);
1843         /* Set UUID version to 4 --- truely random generation */
1844         uuid_out[6] = (uuid_out[6] & 0x0F) | 0x40;
1845         /* Set the UUID variant to DCE */
1846         uuid_out[8] = (uuid_out[8] & 0x3F) | 0x80;
1847 }
1848
1849 EXPORT_SYMBOL(generate_random_uuid);
1850
1851 /********************************************************************
1852  *
1853  * Sysctl interface
1854  *
1855  ********************************************************************/
1856
1857 #ifdef CONFIG_SYSCTL
1858
1859 #include <linux/sysctl.h>
1860
1861 static int sysctl_poolsize;
1862 static int min_read_thresh, max_read_thresh;
1863 static int min_write_thresh, max_write_thresh;
1864 static char sysctl_bootid[16];
1865
1866 /*
1867  * This function handles a request from the user to change the pool size 
1868  * of the primary entropy store.
1869  */
1870 static int change_poolsize(int poolsize)
1871 {
1872         struct entropy_store    *new_store, *old_store;
1873         int                     ret;
1874         
1875         if ((ret = create_entropy_store(poolsize, random_state->name,
1876                                         &new_store)))
1877                 return ret;
1878
1879         add_entropy_words(new_store, random_state->pool,
1880                           random_state->poolinfo.poolwords);
1881         credit_entropy_store(new_store, random_state->entropy_count);
1882
1883         sysctl_init_random(new_store);
1884         old_store = random_state;
1885         random_state = batch_work.data = new_store;
1886         free_entropy_store(old_store);
1887         return 0;
1888 }
1889
1890 static int proc_do_poolsize(ctl_table *table, int write, struct file *filp,
1891                             void __user *buffer, size_t *lenp, loff_t *ppos)
1892 {
1893         int     ret;
1894
1895         sysctl_poolsize = random_state->poolinfo.POOLBYTES;
1896
1897         ret = proc_dointvec(table, write, filp, buffer, lenp, ppos);
1898         if (ret || !write ||
1899             (sysctl_poolsize == random_state->poolinfo.POOLBYTES))
1900                 return ret;
1901
1902         return change_poolsize(sysctl_poolsize);
1903 }
1904
1905 static int poolsize_strategy(ctl_table *table, int __user *name, int nlen,
1906                              void __user *oldval, size_t __user *oldlenp,
1907                              void __user *newval, size_t newlen, void **context)
1908 {
1909         unsigned int    len;
1910         
1911         sysctl_poolsize = random_state->poolinfo.POOLBYTES;
1912
1913         /*
1914          * We only handle the write case, since the read case gets
1915          * handled by the default handler (and we don't care if the
1916          * write case happens twice; it's harmless).
1917          */
1918         if (newval && newlen) {
1919                 len = newlen;
1920                 if (len > table->maxlen)
1921                         len = table->maxlen;
1922                 if (copy_from_user(table->data, newval, len))
1923                         return -EFAULT;
1924         }
1925
1926         if (sysctl_poolsize != random_state->poolinfo.POOLBYTES)
1927                 return change_poolsize(sysctl_poolsize);
1928
1929         return 0;
1930 }
1931
1932 /*
1933  * These functions is used to return both the bootid UUID, and random
1934  * UUID.  The difference is in whether table->data is NULL; if it is,
1935  * then a new UUID is generated and returned to the user.
1936  * 
1937  * If the user accesses this via the proc interface, it will be returned
1938  * as an ASCII string in the standard UUID format.  If accesses via the 
1939  * sysctl system call, it is returned as 16 bytes of binary data.
1940  */
1941 static int proc_do_uuid(ctl_table *table, int write, struct file *filp,
1942                         void __user *buffer, size_t *lenp, loff_t *ppos)
1943 {
1944         ctl_table       fake_table;
1945         unsigned char   buf[64], tmp_uuid[16], *uuid;
1946
1947         uuid = table->data;
1948         if (!uuid) {
1949                 uuid = tmp_uuid;
1950                 uuid[8] = 0;
1951         }
1952         if (uuid[8] == 0)
1953                 generate_random_uuid(uuid);
1954
1955         sprintf(buf, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
1956                 "%02x%02x%02x%02x%02x%02x",
1957                 uuid[0],  uuid[1],  uuid[2],  uuid[3],
1958                 uuid[4],  uuid[5],  uuid[6],  uuid[7],
1959                 uuid[8],  uuid[9],  uuid[10], uuid[11],
1960                 uuid[12], uuid[13], uuid[14], uuid[15]);
1961         fake_table.data = buf;
1962         fake_table.maxlen = sizeof(buf);
1963
1964         return proc_dostring(&fake_table, write, filp, buffer, lenp, ppos);
1965 }
1966
1967 static int uuid_strategy(ctl_table *table, int __user *name, int nlen,
1968                          void __user *oldval, size_t __user *oldlenp,
1969                          void __user *newval, size_t newlen, void **context)
1970 {
1971         unsigned char   tmp_uuid[16], *uuid;
1972         unsigned int    len;
1973
1974         if (!oldval || !oldlenp)
1975                 return 1;
1976
1977         uuid = table->data;
1978         if (!uuid) {
1979                 uuid = tmp_uuid;
1980                 uuid[8] = 0;
1981         }
1982         if (uuid[8] == 0)
1983                 generate_random_uuid(uuid);
1984
1985         if (get_user(len, oldlenp))
1986                 return -EFAULT;
1987         if (len) {
1988                 if (len > 16)
1989                         len = 16;
1990                 if (copy_to_user(oldval, uuid, len) ||
1991                     put_user(len, oldlenp))
1992                         return -EFAULT;
1993         }
1994         return 1;
1995 }
1996
1997 ctl_table random_table[] = {
1998         {
1999                 .ctl_name       = RANDOM_POOLSIZE,
2000                 .procname       = "poolsize",
2001                 .data           = &sysctl_poolsize,
2002                 .maxlen         = sizeof(int),
2003                 .mode           = 0644,
2004                 .proc_handler   = &proc_do_poolsize,
2005                 .strategy       = &poolsize_strategy,
2006         },
2007         {
2008                 .ctl_name       = RANDOM_ENTROPY_COUNT,
2009                 .procname       = "entropy_avail",
2010                 .maxlen         = sizeof(int),
2011                 .mode           = 0444,
2012                 .proc_handler   = &proc_dointvec,
2013         },
2014         {
2015                 .ctl_name       = RANDOM_READ_THRESH,
2016                 .procname       = "read_wakeup_threshold",
2017                 .data           = &random_read_wakeup_thresh,
2018                 .maxlen         = sizeof(int),
2019                 .mode           = 0644,
2020                 .proc_handler   = &proc_dointvec_minmax,
2021                 .strategy       = &sysctl_intvec,
2022                 .extra1         = &min_read_thresh,
2023                 .extra2         = &max_read_thresh,
2024         },
2025         {
2026                 .ctl_name       = RANDOM_WRITE_THRESH,
2027                 .procname       = "write_wakeup_threshold",
2028                 .data           = &random_write_wakeup_thresh,
2029                 .maxlen         = sizeof(int),
2030                 .mode           = 0644,
2031                 .proc_handler   = &proc_dointvec_minmax,
2032                 .strategy       = &sysctl_intvec,
2033                 .extra1         = &min_write_thresh,
2034                 .extra2         = &max_write_thresh,
2035         },
2036         {
2037                 .ctl_name       = RANDOM_BOOT_ID,
2038                 .procname       = "boot_id",
2039                 .data           = &sysctl_bootid,
2040                 .maxlen         = 16,
2041                 .mode           = 0444,
2042                 .proc_handler   = &proc_do_uuid,
2043                 .strategy       = &uuid_strategy,
2044         },
2045         {
2046                 .ctl_name       = RANDOM_UUID,
2047                 .procname       = "uuid",
2048                 .maxlen         = 16,
2049                 .mode           = 0444,
2050                 .proc_handler   = &proc_do_uuid,
2051                 .strategy       = &uuid_strategy,
2052         },
2053         { .ctl_name = 0 }
2054 };
2055
2056 static void sysctl_init_random(struct entropy_store *random_state)
2057 {
2058         min_read_thresh = 8;
2059         min_write_thresh = 0;
2060         max_read_thresh = max_write_thresh = random_state->poolinfo.POOLBITS;
2061         random_table[1].data = &random_state->entropy_count;
2062 }
2063 #endif  /* CONFIG_SYSCTL */
2064
2065 /********************************************************************
2066  *
2067  * Random funtions for networking
2068  *
2069  ********************************************************************/
2070
2071 #ifdef CONFIG_INET
2072 /*
2073  * TCP initial sequence number picking.  This uses the random number
2074  * generator to pick an initial secret value.  This value is hashed
2075  * along with the TCP endpoint information to provide a unique
2076  * starting point for each pair of TCP endpoints.  This defeats
2077  * attacks which rely on guessing the initial TCP sequence number.
2078  * This algorithm was suggested by Steve Bellovin.
2079  *
2080  * Using a very strong hash was taking an appreciable amount of the total
2081  * TCP connection establishment time, so this is a weaker hash,
2082  * compensated for by changing the secret periodically.
2083  */
2084
2085 /* F, G and H are basic MD4 functions: selection, majority, parity */
2086 #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
2087 #define G(x, y, z) (((x) & (y)) + (((x) ^ (y)) & (z)))
2088 #define H(x, y, z) ((x) ^ (y) ^ (z))
2089
2090 /*
2091  * The generic round function.  The application is so specific that
2092  * we don't bother protecting all the arguments with parens, as is generally
2093  * good macro practice, in favor of extra legibility.
2094  * Rotation is separate from addition to prevent recomputation
2095  */
2096 #define ROUND(f, a, b, c, d, x, s)      \
2097         (a += f(b, c, d) + x, a = (a << s) | (a >> (32-s)))
2098 #define K1 0
2099 #define K2 013240474631UL
2100 #define K3 015666365641UL
2101
2102 /*
2103  * Basic cut-down MD4 transform.  Returns only 32 bits of result.
2104  */
2105 static __u32 halfMD4Transform (__u32 const buf[4], __u32 const in[8])
2106 {
2107         __u32   a = buf[0], b = buf[1], c = buf[2], d = buf[3];
2108
2109         /* Round 1 */
2110         ROUND(F, a, b, c, d, in[0] + K1,  3);
2111         ROUND(F, d, a, b, c, in[1] + K1,  7);
2112         ROUND(F, c, d, a, b, in[2] + K1, 11);
2113         ROUND(F, b, c, d, a, in[3] + K1, 19);
2114         ROUND(F, a, b, c, d, in[4] + K1,  3);
2115         ROUND(F, d, a, b, c, in[5] + K1,  7);
2116         ROUND(F, c, d, a, b, in[6] + K1, 11);
2117         ROUND(F, b, c, d, a, in[7] + K1, 19);
2118
2119         /* Round 2 */
2120         ROUND(G, a, b, c, d, in[1] + K2,  3);
2121         ROUND(G, d, a, b, c, in[3] + K2,  5);
2122         ROUND(G, c, d, a, b, in[5] + K2,  9);
2123         ROUND(G, b, c, d, a, in[7] + K2, 13);
2124         ROUND(G, a, b, c, d, in[0] + K2,  3);
2125         ROUND(G, d, a, b, c, in[2] + K2,  5);
2126         ROUND(G, c, d, a, b, in[4] + K2,  9);
2127         ROUND(G, b, c, d, a, in[6] + K2, 13);
2128
2129         /* Round 3 */
2130         ROUND(H, a, b, c, d, in[3] + K3,  3);
2131         ROUND(H, d, a, b, c, in[7] + K3,  9);
2132         ROUND(H, c, d, a, b, in[2] + K3, 11);
2133         ROUND(H, b, c, d, a, in[6] + K3, 15);
2134         ROUND(H, a, b, c, d, in[1] + K3,  3);
2135         ROUND(H, d, a, b, c, in[5] + K3,  9);
2136         ROUND(H, c, d, a, b, in[0] + K3, 11);
2137         ROUND(H, b, c, d, a, in[4] + K3, 15);
2138
2139         return buf[1] + b;      /* "most hashed" word */
2140         /* Alternative: return sum of all words? */
2141 }
2142
2143 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
2144
2145 static __u32 twothirdsMD4Transform (__u32 const buf[4], __u32 const in[12])
2146 {
2147         __u32   a = buf[0], b = buf[1], c = buf[2], d = buf[3];
2148
2149         /* Round 1 */
2150         ROUND(F, a, b, c, d, in[ 0] + K1,  3);
2151         ROUND(F, d, a, b, c, in[ 1] + K1,  7);
2152         ROUND(F, c, d, a, b, in[ 2] + K1, 11);
2153         ROUND(F, b, c, d, a, in[ 3] + K1, 19);
2154         ROUND(F, a, b, c, d, in[ 4] + K1,  3);
2155         ROUND(F, d, a, b, c, in[ 5] + K1,  7);
2156         ROUND(F, c, d, a, b, in[ 6] + K1, 11);
2157         ROUND(F, b, c, d, a, in[ 7] + K1, 19);
2158         ROUND(F, a, b, c, d, in[ 8] + K1,  3);
2159         ROUND(F, d, a, b, c, in[ 9] + K1,  7);
2160         ROUND(F, c, d, a, b, in[10] + K1, 11);
2161         ROUND(F, b, c, d, a, in[11] + K1, 19);
2162
2163         /* Round 2 */
2164         ROUND(G, a, b, c, d, in[ 1] + K2,  3);
2165         ROUND(G, d, a, b, c, in[ 3] + K2,  5);
2166         ROUND(G, c, d, a, b, in[ 5] + K2,  9);
2167         ROUND(G, b, c, d, a, in[ 7] + K2, 13);
2168         ROUND(G, a, b, c, d, in[ 9] + K2,  3);
2169         ROUND(G, d, a, b, c, in[11] + K2,  5);
2170         ROUND(G, c, d, a, b, in[ 0] + K2,  9);
2171         ROUND(G, b, c, d, a, in[ 2] + K2, 13);
2172         ROUND(G, a, b, c, d, in[ 4] + K2,  3);
2173         ROUND(G, d, a, b, c, in[ 6] + K2,  5);
2174         ROUND(G, c, d, a, b, in[ 8] + K2,  9);
2175         ROUND(G, b, c, d, a, in[10] + K2, 13);
2176
2177         /* Round 3 */
2178         ROUND(H, a, b, c, d, in[ 3] + K3,  3);
2179         ROUND(H, d, a, b, c, in[ 7] + K3,  9);
2180         ROUND(H, c, d, a, b, in[11] + K3, 11);
2181         ROUND(H, b, c, d, a, in[ 2] + K3, 15);
2182         ROUND(H, a, b, c, d, in[ 6] + K3,  3);
2183         ROUND(H, d, a, b, c, in[10] + K3,  9);
2184         ROUND(H, c, d, a, b, in[ 1] + K3, 11);
2185         ROUND(H, b, c, d, a, in[ 5] + K3, 15);
2186         ROUND(H, a, b, c, d, in[ 9] + K3,  3);
2187         ROUND(H, d, a, b, c, in[ 0] + K3,  9);
2188         ROUND(H, c, d, a, b, in[ 4] + K3, 11);
2189         ROUND(H, b, c, d, a, in[ 8] + K3, 15);
2190
2191         return buf[1] + b;      /* "most hashed" word */
2192         /* Alternative: return sum of all words? */
2193 }
2194 #endif
2195
2196 #undef ROUND
2197 #undef F
2198 #undef G
2199 #undef H
2200 #undef K1
2201 #undef K2
2202 #undef K3
2203
2204 /* This should not be decreased so low that ISNs wrap too fast. */
2205 #define REKEY_INTERVAL  (300*HZ)
2206 /*
2207  * Bit layout of the tcp sequence numbers (before adding current time):
2208  * bit 24-31: increased after every key exchange
2209  * bit 0-23: hash(source,dest)
2210  *
2211  * The implementation is similar to the algorithm described
2212  * in the Appendix of RFC 1185, except that
2213  * - it uses a 1 MHz clock instead of a 250 kHz clock
2214  * - it performs a rekey every 5 minutes, which is equivalent
2215  *      to a (source,dest) tulple dependent forward jump of the
2216  *      clock by 0..2^(HASH_BITS+1)
2217  *
2218  * Thus the average ISN wraparound time is 68 minutes instead of
2219  * 4.55 hours.
2220  *
2221  * SMP cleanup and lock avoidance with poor man's RCU.
2222  *                      Manfred Spraul <manfred@colorfullife.com>
2223  *              
2224  */
2225 #define COUNT_BITS      8
2226 #define COUNT_MASK      ( (1<<COUNT_BITS)-1)
2227 #define HASH_BITS       24
2228 #define HASH_MASK       ( (1<<HASH_BITS)-1 )
2229
2230 static struct keydata {
2231         __u32   count;          // already shifted to the final position
2232         __u32   secret[12];
2233 } ____cacheline_aligned ip_keydata[2];
2234
2235 static unsigned int ip_cnt;
2236
2237 static void rekey_seq_generator(void *private_);
2238
2239 static DECLARE_WORK(rekey_work, rekey_seq_generator, NULL);
2240
2241 /*
2242  * Lock avoidance:
2243  * The ISN generation runs lockless - it's just a hash over random data.
2244  * State changes happen every 5 minutes when the random key is replaced.
2245  * Synchronization is performed by having two copies of the hash function
2246  * state and rekey_seq_generator always updates the inactive copy.
2247  * The copy is then activated by updating ip_cnt.
2248  * The implementation breaks down if someone blocks the thread
2249  * that processes SYN requests for more than 5 minutes. Should never
2250  * happen, and even if that happens only a not perfectly compliant
2251  * ISN is generated, nothing fatal.
2252  */
2253 static void rekey_seq_generator(void *private_)
2254 {
2255         struct keydata *keyptr = &ip_keydata[1^(ip_cnt&1)];
2256
2257         get_random_bytes(keyptr->secret, sizeof(keyptr->secret));
2258         keyptr->count = (ip_cnt&COUNT_MASK)<<HASH_BITS;
2259         smp_wmb();
2260         ip_cnt++;
2261         schedule_delayed_work(&rekey_work, REKEY_INTERVAL);
2262 }
2263
2264 static inline struct keydata *get_keyptr(void)
2265 {
2266         struct keydata *keyptr = &ip_keydata[ip_cnt&1];
2267
2268         smp_rmb();
2269
2270         return keyptr;
2271 }
2272
2273 static __init int seqgen_init(void)
2274 {
2275         rekey_seq_generator(NULL);
2276         return 0;
2277 }
2278 late_initcall(seqgen_init);
2279
2280 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
2281 __u32 secure_tcpv6_sequence_number(__u32 *saddr, __u32 *daddr,
2282                                    __u16 sport, __u16 dport)
2283 {
2284         struct timeval  tv;
2285         __u32           seq;
2286         __u32           hash[12];
2287         struct keydata *keyptr = get_keyptr();
2288
2289         /* The procedure is the same as for IPv4, but addresses are longer.
2290          * Thus we must use twothirdsMD4Transform.
2291          */
2292
2293
2294         memcpy(hash, saddr, 16);
2295         hash[4]=(sport << 16) + dport;
2296         memcpy(&hash[5],keyptr->secret,sizeof(__u32)*7);
2297
2298         seq = twothirdsMD4Transform(daddr, hash) & HASH_MASK;
2299         seq += keyptr->count;
2300
2301         do_gettimeofday(&tv);
2302         seq += tv.tv_usec + tv.tv_sec*1000000;
2303
2304         return seq;
2305 }
2306 EXPORT_SYMBOL(secure_tcpv6_sequence_number);
2307 #endif
2308
2309 __u32 secure_tcp_sequence_number(__u32 saddr, __u32 daddr,
2310                                  __u16 sport, __u16 dport)
2311 {
2312         struct timeval  tv;
2313         __u32           seq;
2314         __u32   hash[4];
2315         struct keydata *keyptr = get_keyptr();
2316
2317         /*
2318          *  Pick a unique starting offset for each TCP connection endpoints
2319          *  (saddr, daddr, sport, dport).
2320          *  Note that the words are placed into the starting vector, which is 
2321          *  then mixed with a partial MD4 over random data.
2322          */
2323         hash[0]=saddr;
2324         hash[1]=daddr;
2325         hash[2]=(sport << 16) + dport;
2326         hash[3]=keyptr->secret[11];
2327
2328         seq = halfMD4Transform(hash, keyptr->secret) & HASH_MASK;
2329         seq += keyptr->count;
2330         /*
2331          *      As close as possible to RFC 793, which
2332          *      suggests using a 250 kHz clock.
2333          *      Further reading shows this assumes 2 Mb/s networks.
2334          *      For 10 Mb/s Ethernet, a 1 MHz clock is appropriate.
2335          *      That's funny, Linux has one built in!  Use it!
2336          *      (Networks are faster now - should this be increased?)
2337          */
2338         do_gettimeofday(&tv);
2339         seq += tv.tv_usec + tv.tv_sec*1000000;
2340 #if 0
2341         printk("init_seq(%lx, %lx, %d, %d) = %d\n",
2342                saddr, daddr, sport, dport, seq);
2343 #endif
2344         return seq;
2345 }
2346
2347 EXPORT_SYMBOL(secure_tcp_sequence_number);
2348
2349 /*  The code below is shamelessly stolen from secure_tcp_sequence_number().
2350  *  All blames to Andrey V. Savochkin <saw@msu.ru>.
2351  */
2352 __u32 secure_ip_id(__u32 daddr)
2353 {
2354         struct keydata *keyptr;
2355         __u32 hash[4];
2356
2357         keyptr = get_keyptr();
2358
2359         /*
2360          *  Pick a unique starting offset for each IP destination.
2361          *  The dest ip address is placed in the starting vector,
2362          *  which is then hashed with random data.
2363          */
2364         hash[0] = daddr;
2365         hash[1] = keyptr->secret[9];
2366         hash[2] = keyptr->secret[10];
2367         hash[3] = keyptr->secret[11];
2368
2369         return halfMD4Transform(hash, keyptr->secret);
2370 }
2371
2372 #ifdef CONFIG_SYN_COOKIES
2373 /*
2374  * Secure SYN cookie computation. This is the algorithm worked out by
2375  * Dan Bernstein and Eric Schenk.
2376  *
2377  * For linux I implement the 1 minute counter by looking at the jiffies clock.
2378  * The count is passed in as a parameter, so this code doesn't much care.
2379  */
2380
2381 #define COOKIEBITS 24   /* Upper bits store count */
2382 #define COOKIEMASK (((__u32)1 << COOKIEBITS) - 1)
2383
2384 static int      syncookie_init;
2385 static __u32    syncookie_secret[2][16-3+HASH_BUFFER_SIZE];
2386
2387 __u32 secure_tcp_syn_cookie(__u32 saddr, __u32 daddr, __u16 sport,
2388                 __u16 dport, __u32 sseq, __u32 count, __u32 data)
2389 {
2390         __u32   tmp[16 + HASH_BUFFER_SIZE + HASH_EXTRA_SIZE];
2391         __u32   seq;
2392
2393         /*
2394          * Pick two random secrets the first time we need a cookie.
2395          */
2396         if (syncookie_init == 0) {
2397                 get_random_bytes(syncookie_secret, sizeof(syncookie_secret));
2398                 syncookie_init = 1;
2399         }
2400
2401         /*
2402          * Compute the secure sequence number.
2403          * The output should be:
2404          *   HASH(sec1,saddr,sport,daddr,dport,sec1) + sseq + (count * 2^24)
2405          *      + (HASH(sec2,saddr,sport,daddr,dport,count,sec2) % 2^24).
2406          * Where sseq is their sequence number and count increases every
2407          * minute by 1.
2408          * As an extra hack, we add a small "data" value that encodes the
2409          * MSS into the second hash value.
2410          */
2411
2412         memcpy(tmp+3, syncookie_secret[0], sizeof(syncookie_secret[0]));
2413         tmp[0]=saddr;
2414         tmp[1]=daddr;
2415         tmp[2]=(sport << 16) + dport;
2416         HASH_TRANSFORM(tmp+16, tmp);
2417         seq = tmp[17] + sseq + (count << COOKIEBITS);
2418
2419         memcpy(tmp+3, syncookie_secret[1], sizeof(syncookie_secret[1]));
2420         tmp[0]=saddr;
2421         tmp[1]=daddr;
2422         tmp[2]=(sport << 16) + dport;
2423         tmp[3] = count; /* minute counter */
2424         HASH_TRANSFORM(tmp+16, tmp);
2425
2426         /* Add in the second hash and the data */
2427         return seq + ((tmp[17] + data) & COOKIEMASK);
2428 }
2429
2430 /*
2431  * This retrieves the small "data" value from the syncookie.
2432  * If the syncookie is bad, the data returned will be out of
2433  * range.  This must be checked by the caller.
2434  *
2435  * The count value used to generate the cookie must be within
2436  * "maxdiff" if the current (passed-in) "count".  The return value
2437  * is (__u32)-1 if this test fails.
2438  */
2439 __u32 check_tcp_syn_cookie(__u32 cookie, __u32 saddr, __u32 daddr, __u16 sport,
2440                 __u16 dport, __u32 sseq, __u32 count, __u32 maxdiff)
2441 {
2442         __u32   tmp[16 + HASH_BUFFER_SIZE + HASH_EXTRA_SIZE];
2443         __u32   diff;
2444
2445         if (syncookie_init == 0)
2446                 return (__u32)-1;       /* Well, duh! */
2447
2448         /* Strip away the layers from the cookie */
2449         memcpy(tmp+3, syncookie_secret[0], sizeof(syncookie_secret[0]));
2450         tmp[0]=saddr;
2451         tmp[1]=daddr;
2452         tmp[2]=(sport << 16) + dport;
2453         HASH_TRANSFORM(tmp+16, tmp);
2454         cookie -= tmp[17] + sseq;
2455         /* Cookie is now reduced to (count * 2^24) ^ (hash % 2^24) */
2456
2457         diff = (count - (cookie >> COOKIEBITS)) & ((__u32)-1 >> COOKIEBITS);
2458         if (diff >= maxdiff)
2459                 return (__u32)-1;
2460
2461         memcpy(tmp+3, syncookie_secret[1], sizeof(syncookie_secret[1]));
2462         tmp[0] = saddr;
2463         tmp[1] = daddr;
2464         tmp[2] = (sport << 16) + dport;
2465         tmp[3] = count - diff;  /* minute counter */
2466         HASH_TRANSFORM(tmp+16, tmp);
2467
2468         return (cookie - tmp[17]) & COOKIEMASK; /* Leaving the data behind */
2469 }
2470 #endif
2471 #endif /* CONFIG_INET */
2472
2473 /*
2474  * Get a random word:
2475  */
2476 unsigned int get_random_int(void)
2477 {
2478         unsigned int val = 0;
2479
2480         if (!exec_shield_randomize)
2481                 return 0;
2482
2483 #ifdef CONFIG_X86_HAS_TSC
2484         rdtscl(val);
2485 #endif
2486         val += current->pid + jiffies + (int)val;
2487
2488         /*
2489          * Use IP's RNG. It suits our purpose perfectly: it re-keys itself
2490          * every second, from the entropy pool (and thus creates a limited
2491          * drain on it), and uses halfMD4Transform within the second. We
2492          * also spice it with the TSC (if available), jiffies, PID and the
2493          * stack address:
2494          */
2495         return secure_ip_id(val);
2496 }
2497
2498 unsigned long randomize_range(unsigned long start, unsigned long end, unsigned long len)
2499 {
2500         unsigned long range = end - len - start;
2501         if (end <= start + len)
2502                 return 0;
2503         return PAGE_ALIGN(get_random_int() % range + start);
2504 }
2505