root/drivers/char/random.c

/* [previous][next][first][last][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. rand_initialize
  2. rand_initialize_irq
  3. rand_initialize_blkdev
  4. add_entropy_word
  5. add_timer_randomness
  6. add_keyboard_randomness
  7. add_mouse_randomness
  8. add_interrupt_randomness
  9. add_blkdev_randomness
  10. MD5Transform
  11. extract_entropy
  12. get_random_bytes
  13. random_read
  14. random_read_unlimited
  15. random_select
  16. random_write
  17. random_ioctl

   1 /*
   2  * random.c -- A strong random number generator
   3  *
   4  * Version 0.95, last modified 4-Nov-95
   5  * 
   6  * Copyright Theodore Ts'o, 1994, 1995.  All rights reserved.
   7  *
   8  * Redistribution and use in source and binary forms, with or without
   9  * modification, are permitted provided that the following conditions
  10  * are met:
  11  * 1. Redistributions of source code must retain the above copyright
  12  *    notice, and the entire permission notice in its entirety,
  13  *    including the disclaimer of warranties.
  14  * 2. Redistributions in binary form must reproduce the above copyright
  15  *    notice, this list of conditions and the following disclaimer in the
  16  *    documentation and/or other materials provided with the distribution.
  17  * 3. The name of the author may not be used to endorse or promote
  18  *    products derived from this software without specific prior
  19  *    written permission.
  20  * 
  21  * ALTERNATIVELY, this product may be distributed under the terms of
  22  * the GNU Public License, in which case the provisions of the GPL are
  23  * required INSTEAD OF the above restrictions.  (This clause is
  24  * necessary due to a potential bad interaction between the GPL and
  25  * the restrictions contained in a BSD-style copyright.)
  26  * 
  27  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
  28  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  29  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  30  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
  31  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  32  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  33  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  35  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  37  * OF THE POSSIBILITY OF SUCH DAMAGE.
  38  */
  39 
  40 /*
  41  * (now, with legal B.S. out of the way.....) 
  42  * 
  43  * This routine gathers environmental noise from device drivers, etc.,
  44  * and returns good random numbers, suitable for cryptographic use.
  45  * Besides the obvious cryptographic uses, these numbers are also good
  46  * for seeding TCP sequence numbers, and other places where it is
  47  * desireable to have numbers which are not only random, but hard to
  48  * predict by an attacker.
  49  *
  50  * Theory of operation
  51  * ===================
  52  * 
  53  * Computers are very predictable devices.  Hence it is extremely hard
  54  * to produce truely random numbers on a computer --- as opposed to
  55  * pseudo-random numbers, which can easily generated by using a
  56  * algorithm.  Unfortunately, it is very easy for attackers to guess
  57  * the sequence of pseudo-random number generators, and for some
  58  * applications this is not acceptable.  So instead, we must try to
  59  * gather "environmental noise" from the computer's environment, which
  60  * must be hard for outside attackers to observe, and use that to
  61  * generate random numbers.  In a Unix environment, this is best done
  62  * from inside the kernel.
  63  * 
  64  * Sources of randomness from the environment include inter-keyboard
  65  * timings, inter-interrupt timings from some interrupts, and other
  66  * events which are both (a) non-deterministic and (b) hard for an
  67  * outside observer to measure.  Randomness from these sources are
  68  * added to an "entropy pool", which is mixed using a CRC-like function.
  69  * This is not cryptographically strong, but it is adequate assuming
  70  * the randomness is not chosen maliciously, and it is fast enough that
  71  * the overhead of doing it on every interrupt is very reasonable.
  72  * As random bytes are mixed into the entropy pool, the routines keep
  73  * an *estimate* of how many bits of randomness have been stored into
  74  * the random number generator's internal state.
  75  * 
  76  * When random bytes are desired, they are obtained by taking the MD5
  77  * hash of the contents of the "entropy pool".  The MD5 hash avoids
  78  * exposing the internal state of the entropy pool.  It is believed to
  79  * be computationally infeasible to derive any useful information
  80  * about the input of MD5 from its output.  Even if it is possible to
  81  * analyze MD5 in some clever way, as long as the amount of data
  82  * returned from the generator is less than the inherent entropy in
  83  * the pool, the output data is totally unpredictable.  For this
  84  * reason, the routine decreases its internal estimate of how many
  85  * bits of "true randomness" are contained in the entropy pool as it
  86  * outputs random numbers.
  87  * 
  88  * If this estimate goes to zero, the routine can still generate
  89  * random numbers; however, an attacker may (at least in theory) be
  90  * able to infer the future output of the generator from prior
  91  * outputs.  This requires successful cryptanalysis of MD5, which is
  92  * not believed to be feasible, but there is a remote possiblility.
  93  * Nonetheless, these numbers should be useful for the vast majority
  94  * of purposes.
  95  * 
  96  * Exported interfaces ---- output
  97  * ===============================
  98  * 
  99  * There are three exported interfaces; the first is one designed to
 100  * be used from within the kernel:
 101  *
 102  *      void get_random_bytes(void *buf, int nbytes);
 103  *
 104  * This interface will return the requested number of random bytes,
 105  * and place it in the requested buffer.
 106  * 
 107  * The two other interfaces are two character devices /dev/random and
 108  * /dev/urandom.  /dev/random is suitable for use when very high
 109  * quality randomness is desired (for example, for key generation or
 110  * one-time pads), as it will only return a maximum of the number of
 111  * bits of randomness (as estimated by the random number generator)
 112  * contained in the entropy pool.
 113  * 
 114  * The /dev/urandom device does not have this limit, and will return
 115  * as many bytes as are requested.  As more and more random bytes are
 116  * requested without giving time for the entropy pool to recharge,
 117  * this will result in random numbers that are merely cryptographically
 118  * strong.  For many applications, however, this is acceptable.
 119  *
 120  * Exported interfaces ---- input
 121  * ==============================
 122  * 
 123  * The current exported interfaces for gathering environmental noise
 124  * from the devices are:
 125  * 
 126  *      void add_keyboard_randomness(unsigned char scancode);
 127  *      void add_mouse_randomness(__u32 mouse_data);
 128  *      void add_interrupt_randomness(int irq);
 129  *      void add_blkdev_randomness(int irq);
 130  * 
 131  * add_keyboard_randomness() uses the inter-keypress timing, as well as the
 132  * scancode as random inputs into the "entropy pool".
 133  * 
 134  * add_mouse_randomness() uses the mouse interrupt timing, as well as
 135  * the reported position of the mouse from the hardware.
 136  *
 137  * add_interrupt_randomness() uses the inter-interrupt timing as random
 138  * inputs to the entropy pool.  Note that not all interrupts are good
 139  * sources of randomness!  For example, the timer interrupts is not a
 140  * good choice, because the periodicity of the interrupts is to
 141  * regular, and hence predictable to an attacker.  Disk interrupts are
 142  * a better measure, since the timing of the disk interrupts are more
 143  * unpredictable.
 144  * 
 145  * add_blkdev_randomness() times the finishing time of block requests.
 146  * 
 147  * All of these routines try to estimate how many bits of randomness a
 148  * particular randomness source.  They do this by keeping track of the
 149  * first and second order deltas of the event timings.
 150  *
 151  * Acknowledgements:
 152  * =================
 153  *
 154  * Ideas for constructing this random number generator were derived
 155  * from the Pretty Good Privacy's random number generator, and from
 156  * private discussions with Phil Karn.  Colin Plumb provided a faster
 157  * random number generator, which speed up the mixing function of the
 158  * entropy pool, taken from PGP 3.0 (under development).  It has since
 159  * been modified by myself to provide better mixing in the case where
 160  * the input values to add_entropy_word() are mostly small numbers.
 161  * 
 162  * Any flaws in the design are solely my responsibility, and should
 163  * not be attributed to the Phil, Colin, or any of authors of PGP.
 164  * 
 165  * The code for MD5 transform was taken from Colin Plumb's
 166  * implementation, which has been placed in the public domain.  The
 167  * MD5 cryptographic checksum was devised by Ronald Rivest, and is
 168  * documented in RFC 1321, "The MD5 Message Digest Algorithm".
 169  * 
 170  * Further background information on this topic may be obtained from
 171  * RFC 1750, "Randomness Recommendations for Security", by Donald
 172  * Eastlake, Steve Crocker, and Jeff Schiller.
 173  */
 174 
 175 #include <linux/sched.h>
 176 #include <linux/kernel.h>
 177 #include <linux/major.h>
 178 #include <linux/string.h>
 179 #include <linux/fcntl.h>
 180 #include <linux/malloc.h>
 181 #include <linux/random.h>
 182 
 183 #include <asm/segment.h>
 184 #include <asm/irq.h>
 185 #include <asm/io.h>
 186 
 187 /*
 188  * The pool is stirred with a primitive polynomial of degree 128
 189  * over GF(2), namely x^128 + x^99 + x^59 + x^31 + x^9 + x^7 + 1.
 190  * For a pool of size 64, try x^64+x^62+x^38+x^10+x^6+x+1.
 191  */
 192 #define POOLWORDS 128    /* Power of 2 - note that this is 32-bit words */
 193 #define POOLBITS (POOLWORDS*32)
 194 #if POOLWORDS == 128
 195 #define TAP1    99     /* The polynomial taps */
 196 #define TAP2    59
 197 #define TAP3    31
 198 #define TAP4    9
 199 #define TAP5    7
 200 #elif POOLWORDS == 64
 201 #define TAP1    62      /* The polynomial taps */
 202 #define TAP2    38
 203 #define TAP3    10
 204 #define TAP4    6
 205 #define TAP5    1
 206 #else
 207 #error No primitive polynomial available for chosen POOLWORDS
 208 #endif
 209 
 210 /* There is actually only one of these, globally. */
 211 struct random_bucket {
 212         unsigned add_ptr;
 213         unsigned entropy_count;
 214         int input_rotate;
 215         __u32 *pool;
 216 };
 217 
 218 /* There is one of these per entropy source */
 219 struct timer_rand_state {
 220         unsigned long   last_time;
 221         int             last_delta;
 222         int             dont_count_entropy:1;
 223 };
 224 
 225 static struct random_bucket random_state;
 226 static __u32 random_pool[POOLWORDS];
 227 static struct timer_rand_state keyboard_timer_state;
 228 static struct timer_rand_state mouse_timer_state;
 229 static struct timer_rand_state extract_timer_state;
 230 static struct timer_rand_state *irq_timer_state[NR_IRQS];
 231 static struct timer_rand_state *blkdev_timer_state[MAX_BLKDEV];
 232 static struct wait_queue *random_wait;
 233 
 234 static int random_read(struct inode * inode, struct file * file,
 235                        char * buf, int nbytes);
 236 static int random_read_unlimited(struct inode * inode, struct file * file,
 237                                  char * buf, int nbytes);
 238 static int random_select(struct inode *inode, struct file *file,
 239                          int sel_type, select_table * wait);
 240 static int random_write(struct inode * inode, struct file * file,
 241                         const char * buffer, int count);
 242 static int random_ioctl(struct inode * inode, struct file * file,
 243                         unsigned int cmd, unsigned long arg);
 244 
 245 
 246 #ifndef MIN
 247 #define MIN(a,b) (((a) < (b)) ? (a) : (b))
 248 #endif
 249         
 250 void rand_initialize(void)
     /* [previous][next][first][last][top][bottom][index][help] */
 251 {
 252         random_state.add_ptr = 0;
 253         random_state.entropy_count = 0;
 254         random_state.pool = random_pool;
 255         memset(irq_timer_state, 0, sizeof(irq_timer_state));
 256         memset(blkdev_timer_state, 0, sizeof(blkdev_timer_state));
 257         extract_timer_state.dont_count_entropy = 1;
 258         random_wait = NULL;
 259 }
 260 
 261 void rand_initialize_irq(int irq)
     /* [previous][next][first][last][top][bottom][index][help] */
 262 {
 263         struct timer_rand_state *state;
 264         
 265         if (irq >= NR_IRQS || irq_timer_state[irq])
 266                 return;
 267 
 268         /*
 269          * If kamlloc returns null, we just won't use that entropy
 270          * source.
 271          */
 272         state = kmalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
 273         if (state) {
 274                 irq_timer_state[irq] = state;
 275                 memset(state, 0, sizeof(struct timer_rand_state));
 276         }
 277 }
 278 
 279 void rand_initialize_blkdev(int major)
     /* [previous][next][first][last][top][bottom][index][help] */
 280 {
 281         struct timer_rand_state *state;
 282         
 283         if (major >= MAX_BLKDEV || blkdev_timer_state[major])
 284                 return;
 285 
 286         /*
 287          * If kamlloc returns null, we just won't use that entropy
 288          * source.
 289          */
 290         state = kmalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
 291         if (state) {
 292                 blkdev_timer_state[major] = state;
 293                 memset(state, 0, sizeof(struct timer_rand_state));
 294         }
 295 }
 296 
 297 /*
 298  * This function adds a byte into the entropy "pool".  It does not
 299  * update the entropy estimate.  The caller must do this if appropriate.
 300  *
 301  * The pool is stirred with a primitive polynomial of degree 128
 302  * over GF(2), namely x^128 + x^99 + x^59 + x^31 + x^9 + x^7 + 1.
 303  * For a pool of size 64, try x^64+x^62+x^38+x^10+x^6+x+1.
 304  * 
 305  * We rotate the input word by a changing number of bits, to help
 306  * assure that all bits in the entropy get toggled.  Otherwise, if we
 307  * consistently feed the entropy pool small numbers (like jiffies and
 308  * scancodes, for example), the upper bits of the entropy pool don't
 309  * get affected. --- TYT, 10/11/95
 310  */
 311 static inline void add_entropy_word(struct random_bucket *r,
     /* [previous][next][first][last][top][bottom][index][help] */
 312                                     const __u32 input)
 313 {
 314         unsigned i;
 315         __u32 w;
 316 
 317         w = (input << r->input_rotate) | (input >> (32 - r->input_rotate));
 318         i = r->add_ptr = (r->add_ptr - 1) & (POOLWORDS-1);
 319         if (i)
 320                 r->input_rotate = (r->input_rotate + 7) & 31;
 321         else
 322                 /*
 323                  * At the beginning of the pool, add an extra 7 bits
 324                  * rotation, so that successive passes spread the
 325                  * input bits across the pool evenly.
 326                  */
 327                 r->input_rotate = (r->input_rotate + 14) & 31;
 328 
 329         /* XOR in the various taps */
 330         w ^= r->pool[(i+TAP1)&(POOLWORDS-1)];
 331         w ^= r->pool[(i+TAP2)&(POOLWORDS-1)];
 332         w ^= r->pool[(i+TAP3)&(POOLWORDS-1)];
 333         w ^= r->pool[(i+TAP4)&(POOLWORDS-1)];
 334         w ^= r->pool[(i+TAP5)&(POOLWORDS-1)];
 335         w ^= r->pool[i];
 336         /* Rotate w left 1 bit (stolen from SHA) and store */
 337         r->pool[i] = (w << 1) | (w >> 31);
 338 }
 339 
 340 /*
 341  * This function adds entropy to the entropy "pool" by using timing
 342  * delays.  It uses the timer_rand_state structure to make an estimate
 343  * of how many bits of entropy this call has added to the pool.
 344  *
 345  * The number "num" is also added to the pool - it should somehow describe
 346  * the type of event which just happened.  This is currently 0-255 for
 347  * keyboard scan codes, and 256 upwards for interrupts.
 348  * On the i386, this is assumed to be at most 16 bits, and the high bits
 349  * are used for a high-resolution timer.
 350  *
 351  * TODO: Read the time stamp register on the Pentium.
 352  */
 353 static void add_timer_randomness(struct random_bucket *r,
     /* [previous][next][first][last][top][bottom][index][help] */
 354                                  struct timer_rand_state *state, unsigned num)
 355 {
 356         int     delta, delta2;
 357         unsigned        nbits;
 358         __u32           time;
 359 
 360 #if defined (__i386__)
 361         if (x86_capability & 16) {
 362                 unsigned long low, high;
 363                 __asm__(".byte 0x0f,0x31"
 364                         :"=a" (low), "=d" (high));
 365                 time = (__u32) low;
 366                 num ^= (__u32) high;
 367         } else {
 368 #if 0
 369                 /*
 370                  * On a 386, read the high resolution timer.  We assume that
 371                  * this gives us 2 bits of randomness.
 372                  *
 373                  * This is turned off for now because of the speed hit
 374                  * it entails.
 375                  */ 
 376                 outb_p(0x00, 0x43);     /* latch the count ASAP */
 377                 num |= inb_p(0x40) << 16;
 378                 num |= inb(0x40) << 24;
 379                 if (!state->dont_count_entropy)
 380                         r->entropy_count += 2;
 381 #endif
 382                 
 383                 time = jiffies;
 384         }
 385 #else
 386         time = jiffies;
 387 #endif
 388 
 389         add_entropy_word(r, (__u32) num);
 390         add_entropy_word(r, time);
 391 
 392         /*
 393          * Calculate number of bits of randomness we probably
 394          * added.  We take into account the first and second order
 395          * deltas in order to make our estimate.
 396          */
 397         if (!state->dont_count_entropy) {
 398                 delta = time - state->last_time;
 399                 state->last_time = time;
 400 
 401                 delta2 = delta - state->last_delta;
 402                 state->last_delta = delta;
 403 
 404                 if (delta < 0) delta = -delta;
 405                 if (delta2 < 0) delta2 = -delta2;
 406                 delta = MIN(delta, delta2) >> 1;
 407                 for (nbits = 0; delta; nbits++)
 408                         delta >>= 1;
 409 
 410                 r->entropy_count += nbits;
 411         
 412                 /* Prevent overflow */
 413                 if (r->entropy_count > POOLBITS)
 414                         r->entropy_count = POOLBITS;
 415         }
 416                 
 417         wake_up_interruptible(&random_wait);    
 418 }
 419 
 420 void add_keyboard_randomness(unsigned char scancode)
     /* [previous][next][first][last][top][bottom][index][help] */
 421 {
 422         add_timer_randomness(&random_state, &keyboard_timer_state, scancode);
 423 }
 424 
 425 void add_mouse_randomness(__u32 mouse_data)
     /* [previous][next][first][last][top][bottom][index][help] */
 426 {
 427         add_timer_randomness(&random_state, &mouse_timer_state, mouse_data);
 428 }
 429 
 430 void add_interrupt_randomness(int irq)
     /* [previous][next][first][last][top][bottom][index][help] */
 431 {
 432         if (irq >= NR_IRQS || irq_timer_state[irq] == 0)
 433                 return;
 434 
 435         add_timer_randomness(&random_state, irq_timer_state[irq], 0x100+irq);
 436 }
 437 
 438 void add_blkdev_randomness(int major)
     /* [previous][next][first][last][top][bottom][index][help] */
 439 {
 440         if (major >= MAX_BLKDEV || blkdev_timer_state[major] == 0)
 441                 return;
 442 
 443         add_timer_randomness(&random_state, blkdev_timer_state[major],
 444                              0x200+major);
 445 }
 446 
 447 /*
 448  * MD5 transform algorithm, taken from code written by Colin Plumb,
 449  * and put into the public domain
 450  *
 451  * QUESTION: Replace this with SHA, which as generally received better
 452  * reviews from the cryptographic community?
 453  */
 454 
 455 /* The four core functions - F1 is optimized somewhat */
 456 
 457 /* #define F1(x, y, z) (x & y | ~x & z) */
 458 #define F1(x, y, z) (z ^ (x & (y ^ z)))
 459 #define F2(x, y, z) F1(z, x, y)
 460 #define F3(x, y, z) (x ^ y ^ z)
 461 #define F4(x, y, z) (y ^ (x | ~z))
 462 
 463 /* This is the central step in the MD5 algorithm. */
 464 #define MD5STEP(f, w, x, y, z, data, s) \
 465         ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
 466 
 467 /*
 468  * The core of the MD5 algorithm, this alters an existing MD5 hash to
 469  * reflect the addition of 16 longwords of new data.  MD5Update blocks
 470  * the data and converts bytes into longwords for this routine.
 471  */
 472 static void MD5Transform(__u32 buf[4],
     /* [previous][next][first][last][top][bottom][index][help] */
 473                          __u32 const in[16])
 474 {
 475         __u32 a, b, c, d;
 476 
 477         a = buf[0];
 478         b = buf[1];
 479         c = buf[2];
 480         d = buf[3];
 481 
 482         MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478,  7);
 483         MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
 484         MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
 485         MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
 486         MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf,  7);
 487         MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
 488         MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
 489         MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
 490         MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8,  7);
 491         MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
 492         MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
 493         MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
 494         MD5STEP(F1, a, b, c, d, in[12]+0x6b901122,  7);
 495         MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
 496         MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
 497         MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
 498 
 499         MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562,  5);
 500         MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340,  9);
 501         MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
 502         MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
 503         MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d,  5);
 504         MD5STEP(F2, d, a, b, c, in[10]+0x02441453,  9);
 505         MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
 506         MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
 507         MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6,  5);
 508         MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6,  9);
 509         MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
 510         MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
 511         MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905,  5);
 512         MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8,  9);
 513         MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
 514         MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
 515 
 516         MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942,  4);
 517         MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
 518         MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
 519         MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
 520         MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44,  4);
 521         MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
 522         MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
 523         MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
 524         MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6,  4);
 525         MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
 526         MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
 527         MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
 528         MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039,  4);
 529         MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
 530         MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
 531         MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
 532 
 533         MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244,  6);
 534         MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
 535         MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
 536         MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
 537         MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3,  6);
 538         MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
 539         MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
 540         MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
 541         MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f,  6);
 542         MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
 543         MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
 544         MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
 545         MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82,  6);
 546         MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
 547         MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
 548         MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
 549 
 550         buf[0] += a;
 551         buf[1] += b;
 552         buf[2] += c;
 553         buf[3] += d;
 554 }
 555 
 556 #undef F1
 557 #undef F2
 558 #undef F3
 559 #undef F4
 560 #undef MD5STEP
 561 
 562 
 563 #if POOLWORDS % 16
 564 #error extract_entropy() assumes that POOLWORDS is a multiple of 16 words.
 565 #endif
 566 /*
 567  * This function extracts randomness from the "entropy pool", and
 568  * returns it in a buffer.  This function computes how many remaining
 569  * bits of entropy are left in the pool, but it does not restrict the
 570  * number of bytes that are actually obtained.
 571  */
 572 static inline int extract_entropy(struct random_bucket *r, char * buf,
     /* [previous][next][first][last][top][bottom][index][help] */
 573                                   int nbytes, int to_user)
 574 {
 575         int ret, i;
 576         __u32 tmp[4];
 577         
 578         add_timer_randomness(r, &extract_timer_state, nbytes);
 579         
 580         /* Redundant, but just in case... */
 581         if (r->entropy_count > POOLBITS) 
 582                 r->entropy_count = POOLBITS;
 583         /* Why is this here?  Left in from Ted Ts'o.  Perhaps to limit time. */
 584         if (nbytes > 32768)
 585                 nbytes = 32768;
 586 
 587         ret = nbytes;
 588         if (r->entropy_count / 8 >= nbytes)
 589                 r->entropy_count -= nbytes*8;
 590         else
 591                 r->entropy_count = 0;
 592 
 593         while (nbytes) {
 594                 /* Hash the pool to get the output */
 595                 tmp[0] = 0x67452301;
 596                 tmp[1] = 0xefcdab89;
 597                 tmp[2] = 0x98badcfe;
 598                 tmp[3] = 0x10325476;
 599                 for (i = 0; i < POOLWORDS; i += 16)
 600                         MD5Transform(tmp, r->pool+i);
 601                 /* Modify pool so next hash will produce different results */
 602                 add_entropy_word(r, tmp[0]);
 603                 add_entropy_word(r, tmp[1]);
 604                 add_entropy_word(r, tmp[2]);
 605                 add_entropy_word(r, tmp[3]);
 606                 /*
 607                  * Run the MD5 Transform one more time, since we want
 608                  * to add at least minimal obscuring of the inputs to
 609                  * add_entropy_word().  --- TYT
 610                  */
 611                 MD5Transform(tmp, r->pool);
 612                 
 613                 /* Copy data to destination buffer */
 614                 i = MIN(nbytes, 16);
 615                 if (to_user)
 616                         memcpy_tofs(buf, (__u8 const *)tmp, i);
 617                 else
 618                         memcpy(buf, (__u8 const *)tmp, i);
 619                 nbytes -= i;
 620                 buf += i;
 621         }
 622 
 623         /* Wipe data from memory */
 624         memset(tmp, 0, sizeof(tmp));
 625         
 626         return ret;
 627 }
 628 
 629 /*
 630  * This function is the exported kernel interface.  It returns some
 631  * number of good random numbers, suitable for seeding TCP sequence
 632  * numbers, etc.
 633  */
 634 void get_random_bytes(void *buf, int nbytes)
     /* [previous][next][first][last][top][bottom][index][help] */
 635 {
 636         extract_entropy(&random_state, (char *) buf, nbytes, 0);
 637 }
 638 
 639 static int
 640 random_read(struct inode * inode, struct file * file, char * buf, int nbytes)
     /* [previous][next][first][last][top][bottom][index][help] */
 641 {
 642         struct wait_queue       wait = { current, NULL };
 643         int                     n;
 644         int                     retval = 0;
 645         int                     count = 0;
 646         
 647         if (nbytes == 0)
 648                 return 0;
 649 
 650         add_wait_queue(&random_wait, &wait);
 651         while (nbytes > 0) {
 652                 current->state = TASK_INTERRUPTIBLE;
 653                 
 654                 n = nbytes;
 655                 if (n > random_state.entropy_count / 8)
 656                         n = random_state.entropy_count / 8;
 657                 if (n == 0) {
 658                         if (file->f_flags & O_NONBLOCK) {
 659                                 retval = -EAGAIN;
 660                                 break;
 661                         }
 662                         if (current->signal & ~current->blocked) {
 663                                 retval = -ERESTARTSYS;
 664                                 break;
 665                         }
 666                         schedule();
 667                         continue;
 668                 }
 669                 n = extract_entropy(&random_state, buf, n, 1);
 670                 count += n;
 671                 buf += n;
 672                 nbytes -= n;
 673                 break;          /* This break makes the device work */
 674                                 /* like a named pipe */
 675         }
 676         current->state = TASK_RUNNING;
 677         remove_wait_queue(&random_wait, &wait);
 678 
 679         return (count ? count : retval);
 680 }
 681 
 682 static int
 683 random_read_unlimited(struct inode * inode, struct file * file,
     /* [previous][next][first][last][top][bottom][index][help] */
 684                       char * buf, int nbytes)
 685 {
 686         return extract_entropy(&random_state, buf, nbytes, 1);
 687 }
 688 
 689 static int
 690 random_select(struct inode *inode, struct file *file,
     /* [previous][next][first][last][top][bottom][index][help] */
 691                       int sel_type, select_table * wait)
 692 {
 693         if (sel_type == SEL_IN) {
 694                 if (random_state.entropy_count >= 8)
 695                         return 1;
 696                 select_wait(&random_wait, wait);
 697         }
 698         return 0;
 699 }
 700 
 701 static int
 702 random_write(struct inode * inode, struct file * file,
     /* [previous][next][first][last][top][bottom][index][help] */
 703              const char * buffer, int count)
 704 {
 705         int i;
 706         __u32 word, *p;
 707 
 708         for (i = count, p = (__u32 *)buffer;
 709              i >= sizeof(__u32);
 710              i-= sizeof(__u32), p++) {
 711                 memcpy_fromfs(&word, p, sizeof(__u32));
 712                 add_entropy_word(&random_state, word);
 713         }
 714         if (i) {
 715                 word = 0;
 716                 memcpy_fromfs(&word, p, i);
 717                 add_entropy_word(&random_state, word);
 718         }
 719         if (inode)
 720                 inode->i_mtime = CURRENT_TIME;
 721         return count;
 722 }
 723 
 724 static int
 725 random_ioctl(struct inode * inode, struct file * file,
     /* [previous][next][first][last][top][bottom][index][help] */
 726              unsigned int cmd, unsigned long arg)
 727 {
 728         int *p, size, ent_count;
 729         int retval;
 730         
 731         switch (cmd) {
 732         case RNDGETENTCNT:
 733                 retval = verify_area(VERIFY_WRITE, (void *) arg, sizeof(int));
 734                 if (retval)
 735                         return(retval);
 736                 put_user(random_state.entropy_count, (int *) arg);
 737                 return 0;
 738         case RNDADDTOENTCNT:
 739                 if (!suser())
 740                         return -EPERM;
 741                 retval = verify_area(VERIFY_READ, (void *) arg, sizeof(int));
 742                 if (retval)
 743                         return(retval);
 744                 random_state.entropy_count += get_user((int *) arg);
 745                 if (random_state.entropy_count > POOLBITS)
 746                         random_state.entropy_count = POOLBITS;
 747                 return 0;
 748         case RNDGETPOOL:
 749                 if (!suser())
 750                         return -EPERM;
 751                 p = (int *) arg;
 752                 retval = verify_area(VERIFY_WRITE, (void *) p, sizeof(int));
 753                 if (retval)
 754                         return(retval);
 755                 put_user(random_state.entropy_count, p++);
 756                 retval = verify_area(VERIFY_READ, (void *) p, sizeof(int));
 757                 if (retval)
 758                         return(retval);
 759                 size = get_user(p);
 760                 put_user(POOLWORDS, p);
 761                 if (size < 0)
 762                         return -EINVAL;
 763                 if (size > POOLWORDS)
 764                         size = POOLWORDS;
 765                 memcpy_tofs(++p, random_state.pool,
 766                             size*sizeof(__u32));
 767                 return 0;
 768         case RNDADDENTROPY:
 769                 if (!suser())
 770                         return -EPERM;
 771                 p = (int *) arg;
 772                 retval = verify_area(VERIFY_READ, (void *) p, 2*sizeof(int));
 773                 if (retval)
 774                         return(retval);
 775                 ent_count = get_user(p++);
 776                 size = get_user(p++);
 777                 (void) random_write(0, file, (const char *) p, size);
 778                 random_state.entropy_count += ent_count;
 779                 if (random_state.entropy_count > POOLBITS)
 780                         random_state.entropy_count = POOLBITS;
 781                 return 0;
 782         case RNDZAPENTCNT:
 783                 if (!suser())
 784                         return -EPERM;
 785                 random_state.entropy_count = 0;
 786                 return 0;
 787         default:
 788                 return -EINVAL;
 789         }
 790 }
 791 
 792 struct file_operations random_fops = {
 793         NULL,           /* random_lseek */
 794         random_read,
 795         random_write,
 796         NULL,           /* random_readdir */
 797         random_select,  /* random_select */
 798         random_ioctl,
 799         NULL,           /* random_mmap */
 800         NULL,           /* no special open code */
 801         NULL            /* no special release code */
 802 };
 803 
 804 struct file_operations urandom_fops = {
 805         NULL,           /* unrandom_lseek */
 806         random_read_unlimited,
 807         random_write,
 808         NULL,           /* urandom_readdir */
 809         NULL,           /* urandom_select */
 810         random_ioctl,
 811         NULL,           /* urandom_mmap */
 812         NULL,           /* no special open code */
 813         NULL            /* no special release code */
 814 };
 815 

/* [previous][next][first][last][top][bottom][index][help] */