The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/drivers/char/random.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

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

Cache object: e8c084167f3097336f7911b456e75446


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.