OpenCores
URL https://opencores.org/ocsvn/or1k/or1k/trunk

Subversion Repositories or1k

[/] [or1k/] [trunk/] [linux/] [linux-2.4/] [drivers/] [char/] [random.c] - Blame information for rev 1774

Go to most recent revision | Details | Compare with Previous | View Log

Line No. Rev Author Line
1 1275 phoenix
/*
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
                :"0" (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
#ifndef CONFIG_ARCH_S390
719
static struct timer_rand_state *irq_timer_state[NR_IRQS];
720
#endif
721
static struct timer_rand_state *blkdev_timer_state[MAX_BLKDEV];
722
 
723
/*
724
 * This function adds entropy to the entropy "pool" by using timing
725
 * delays.  It uses the timer_rand_state structure to make an estimate
726
 * of how many bits of entropy this call has added to the pool.
727
 *
728
 * The number "num" is also added to the pool - it should somehow describe
729
 * the type of event which just happened.  This is currently 0-255 for
730
 * keyboard scan codes, and 256 upwards for interrupts.
731
 * On the i386, this is assumed to be at most 16 bits, and the high bits
732
 * are used for a high-resolution timer.
733
 *
734
 */
735
static void add_timer_randomness(struct timer_rand_state *state, unsigned num)
736
{
737
        __u32           time;
738
        __s32           delta, delta2, delta3;
739
        int             entropy = 0;
740
 
741
#if defined (__i386__)
742
        if (cpu_has_tsc) {
743
                __u32 high;
744
                rdtsc(time, high);
745
                num ^= high;
746
        } else {
747
                time = jiffies;
748
        }
749
#elif defined (__x86_64__)
750
        __u32 high;
751
        rdtsc(time, high);
752
        num ^= high;
753
#else
754
        time = jiffies;
755
#endif
756
 
757
        /*
758
         * Calculate number of bits of randomness we probably added.
759
         * We take into account the first, second and third-order deltas
760
         * in order to make our estimate.
761
         */
762
        if (!state->dont_count_entropy) {
763
                delta = time - state->last_time;
764
                state->last_time = time;
765
 
766
                delta2 = delta - state->last_delta;
767
                state->last_delta = delta;
768
 
769
                delta3 = delta2 - state->last_delta2;
770
                state->last_delta2 = delta2;
771
 
772
                if (delta < 0)
773
                        delta = -delta;
774
                if (delta2 < 0)
775
                        delta2 = -delta2;
776
                if (delta3 < 0)
777
                        delta3 = -delta3;
778
                if (delta > delta2)
779
                        delta = delta2;
780
                if (delta > delta3)
781
                        delta = delta3;
782
 
783
                /*
784
                 * delta is now minimum absolute delta.
785
                 * Round down by 1 bit on general principles,
786
                 * and limit entropy entimate to 12 bits.
787
                 */
788
                delta >>= 1;
789
                delta &= (1 << 12) - 1;
790
 
791
                entropy = int_ln_12bits(delta);
792
        }
793
        batch_entropy_store(num, time, entropy);
794
}
795
 
796
#ifndef CONFIG_ARCH_S390
797
void add_keyboard_randomness(unsigned char scancode)
798
{
799
        static unsigned char last_scancode;
800
        /* ignore autorepeat (multiple key down w/o key up) */
801
        if (scancode != last_scancode) {
802
                last_scancode = scancode;
803
                add_timer_randomness(&keyboard_timer_state, scancode);
804
        }
805
}
806
 
807
void add_mouse_randomness(__u32 mouse_data)
808
{
809
        add_timer_randomness(&mouse_timer_state, mouse_data);
810
}
811
 
812
void add_interrupt_randomness(int irq)
813
{
814
        if (irq >= NR_IRQS || irq_timer_state[irq] == 0)
815
                return;
816
 
817
        add_timer_randomness(irq_timer_state[irq], 0x100+irq);
818
}
819
#endif
820
 
821
void add_blkdev_randomness(int major)
822
{
823
        if (major >= MAX_BLKDEV)
824
                return;
825
 
826
        if (blkdev_timer_state[major] == 0) {
827
                rand_initialize_blkdev(major, GFP_ATOMIC);
828
                if (blkdev_timer_state[major] == 0)
829
                        return;
830
        }
831
 
832
        add_timer_randomness(blkdev_timer_state[major], 0x200+major);
833
}
834
 
835
/******************************************************************
836
 *
837
 * Hash function definition
838
 *
839
 *******************************************************************/
840
 
841
/*
842
 * This chunk of code defines a function
843
 * void HASH_TRANSFORM(__u32 digest[HASH_BUFFER_SIZE + HASH_EXTRA_SIZE],
844
 *              __u32 const data[16])
845
 *
846
 * The function hashes the input data to produce a digest in the first
847
 * HASH_BUFFER_SIZE words of the digest[] array, and uses HASH_EXTRA_SIZE
848
 * more words for internal purposes.  (This buffer is exported so the
849
 * caller can wipe it once rather than this code doing it each call,
850
 * and tacking it onto the end of the digest[] array is the quick and
851
 * dirty way of doing it.)
852
 *
853
 * It so happens that MD5 and SHA share most of the initial vector
854
 * used to initialize the digest[] array before the first call:
855
 * 1) 0x67452301
856
 * 2) 0xefcdab89
857
 * 3) 0x98badcfe
858
 * 4) 0x10325476
859
 * 5) 0xc3d2e1f0 (SHA only)
860
 *
861
 * For /dev/random purposes, the length of the data being hashed is
862
 * fixed in length, so appending a bit count in the usual way is not
863
 * cryptographically necessary.
864
 */
865
 
866
#ifdef USE_SHA
867
 
868
#define HASH_BUFFER_SIZE 5
869
#define HASH_EXTRA_SIZE 80
870
#define HASH_TRANSFORM SHATransform
871
 
872
/* Various size/speed tradeoffs are available.  Choose 0..3. */
873
#define SHA_CODE_SIZE 0
874
 
875
/*
876
 * SHA transform algorithm, taken from code written by Peter Gutmann,
877
 * and placed in the public domain.
878
 */
879
 
880
/* The SHA f()-functions.  */
881
 
882
#define f1(x,y,z)   ( z ^ (x & (y^z)) )         /* Rounds  0-19: x ? y : z */
883
#define f2(x,y,z)   (x ^ y ^ z)                 /* Rounds 20-39: XOR */
884
#define f3(x,y,z)   ( (x & y) + (z & (x ^ y)) ) /* Rounds 40-59: majority */
885
#define f4(x,y,z)   (x ^ y ^ z)                 /* Rounds 60-79: XOR */
886
 
887
/* The SHA Mysterious Constants */
888
 
889
#define K1  0x5A827999L                 /* Rounds  0-19: sqrt(2) * 2^30 */
890
#define K2  0x6ED9EBA1L                 /* Rounds 20-39: sqrt(3) * 2^30 */
891
#define K3  0x8F1BBCDCL                 /* Rounds 40-59: sqrt(5) * 2^30 */
892
#define K4  0xCA62C1D6L                 /* Rounds 60-79: sqrt(10) * 2^30 */
893
 
894
#define ROTL(n,X)  ( ( ( X ) << n ) | ( ( X ) >> ( 32 - n ) ) )
895
 
896
#define subRound(a, b, c, d, e, f, k, data) \
897
    ( e += ROTL( 5, a ) + f( b, c, d ) + k + data, b = ROTL( 30, b ) )
898
 
899
 
900
static void SHATransform(__u32 digest[85], __u32 const data[16])
901
{
902
    __u32 A, B, C, D, E;     /* Local vars */
903
    __u32 TEMP;
904
    int i;
905
#define W (digest + HASH_BUFFER_SIZE)   /* Expanded data array */
906
 
907
    /*
908
     * Do the preliminary expansion of 16 to 80 words.  Doing it
909
     * out-of-line line this is faster than doing it in-line on
910
     * register-starved machines like the x86, and not really any
911
     * slower on real processors.
912
     */
913
    memcpy(W, data, 16*sizeof(__u32));
914
    for (i = 0; i < 64; i++) {
915
            TEMP = W[i] ^ W[i+2] ^ W[i+8] ^ W[i+13];
916
            W[i+16] = ROTL(1, TEMP);
917
    }
918
 
919
    /* Set up first buffer and local data buffer */
920
    A = digest[ 0 ];
921
    B = digest[ 1 ];
922
    C = digest[ 2 ];
923
    D = digest[ 3 ];
924
    E = digest[ 4 ];
925
 
926
    /* Heavy mangling, in 4 sub-rounds of 20 iterations each. */
927
#if SHA_CODE_SIZE == 0
928
    /*
929
     * Approximately 50% of the speed of the largest version, but
930
     * takes up 1/16 the space.  Saves about 6k on an i386 kernel.
931
     */
932
    for (i = 0; i < 80; i++) {
933
        if (i < 40) {
934
            if (i < 20)
935
                TEMP = f1(B, C, D) + K1;
936
            else
937
                TEMP = f2(B, C, D) + K2;
938
        } else {
939
            if (i < 60)
940
                TEMP = f3(B, C, D) + K3;
941
            else
942
                TEMP = f4(B, C, D) + K4;
943
        }
944
        TEMP += ROTL(5, A) + E + W[i];
945
        E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
946
    }
947
#elif SHA_CODE_SIZE == 1
948
    for (i = 0; i < 20; i++) {
949
        TEMP = f1(B, C, D) + K1 + ROTL(5, A) + E + W[i];
950
        E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
951
    }
952
    for (; i < 40; i++) {
953
        TEMP = f2(B, C, D) + K2 + ROTL(5, A) + E + W[i];
954
        E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
955
    }
956
    for (; i < 60; i++) {
957
        TEMP = f3(B, C, D) + K3 + ROTL(5, A) + E + W[i];
958
        E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
959
    }
960
    for (; i < 80; i++) {
961
        TEMP = f4(B, C, D) + K4 + ROTL(5, A) + E + W[i];
962
        E = D; D = C; C = ROTL(30, B); B = A; A = TEMP;
963
    }
964
#elif SHA_CODE_SIZE == 2
965
    for (i = 0; i < 20; i += 5) {
966
        subRound( A, B, C, D, E, f1, K1, W[ i   ] );
967
        subRound( E, A, B, C, D, f1, K1, W[ i+1 ] );
968
        subRound( D, E, A, B, C, f1, K1, W[ i+2 ] );
969
        subRound( C, D, E, A, B, f1, K1, W[ i+3 ] );
970
        subRound( B, C, D, E, A, f1, K1, W[ i+4 ] );
971
    }
972
    for (; i < 40; i += 5) {
973
        subRound( A, B, C, D, E, f2, K2, W[ i   ] );
974
        subRound( E, A, B, C, D, f2, K2, W[ i+1 ] );
975
        subRound( D, E, A, B, C, f2, K2, W[ i+2 ] );
976
        subRound( C, D, E, A, B, f2, K2, W[ i+3 ] );
977
        subRound( B, C, D, E, A, f2, K2, W[ i+4 ] );
978
    }
979
    for (; i < 60; i += 5) {
980
        subRound( A, B, C, D, E, f3, K3, W[ i   ] );
981
        subRound( E, A, B, C, D, f3, K3, W[ i+1 ] );
982
        subRound( D, E, A, B, C, f3, K3, W[ i+2 ] );
983
        subRound( C, D, E, A, B, f3, K3, W[ i+3 ] );
984
        subRound( B, C, D, E, A, f3, K3, W[ i+4 ] );
985
    }
986
    for (; i < 80; i += 5) {
987
        subRound( A, B, C, D, E, f4, K4, W[ i   ] );
988
        subRound( E, A, B, C, D, f4, K4, W[ i+1 ] );
989
        subRound( D, E, A, B, C, f4, K4, W[ i+2 ] );
990
        subRound( C, D, E, A, B, f4, K4, W[ i+3 ] );
991
        subRound( B, C, D, E, A, f4, K4, W[ i+4 ] );
992
    }
993
#elif SHA_CODE_SIZE == 3 /* Really large version */
994
    subRound( A, B, C, D, E, f1, K1, W[  0 ] );
995
    subRound( E, A, B, C, D, f1, K1, W[  1 ] );
996
    subRound( D, E, A, B, C, f1, K1, W[  2 ] );
997
    subRound( C, D, E, A, B, f1, K1, W[  3 ] );
998
    subRound( B, C, D, E, A, f1, K1, W[  4 ] );
999
    subRound( A, B, C, D, E, f1, K1, W[  5 ] );
1000
    subRound( E, A, B, C, D, f1, K1, W[  6 ] );
1001
    subRound( D, E, A, B, C, f1, K1, W[  7 ] );
1002
    subRound( C, D, E, A, B, f1, K1, W[  8 ] );
1003
    subRound( B, C, D, E, A, f1, K1, W[  9 ] );
1004
    subRound( A, B, C, D, E, f1, K1, W[ 10 ] );
1005
    subRound( E, A, B, C, D, f1, K1, W[ 11 ] );
1006
    subRound( D, E, A, B, C, f1, K1, W[ 12 ] );
1007
    subRound( C, D, E, A, B, f1, K1, W[ 13 ] );
1008
    subRound( B, C, D, E, A, f1, K1, W[ 14 ] );
1009
    subRound( A, B, C, D, E, f1, K1, W[ 15 ] );
1010
    subRound( E, A, B, C, D, f1, K1, W[ 16 ] );
1011
    subRound( D, E, A, B, C, f1, K1, W[ 17 ] );
1012
    subRound( C, D, E, A, B, f1, K1, W[ 18 ] );
1013
    subRound( B, C, D, E, A, f1, K1, W[ 19 ] );
1014
 
1015
    subRound( A, B, C, D, E, f2, K2, W[ 20 ] );
1016
    subRound( E, A, B, C, D, f2, K2, W[ 21 ] );
1017
    subRound( D, E, A, B, C, f2, K2, W[ 22 ] );
1018
    subRound( C, D, E, A, B, f2, K2, W[ 23 ] );
1019
    subRound( B, C, D, E, A, f2, K2, W[ 24 ] );
1020
    subRound( A, B, C, D, E, f2, K2, W[ 25 ] );
1021
    subRound( E, A, B, C, D, f2, K2, W[ 26 ] );
1022
    subRound( D, E, A, B, C, f2, K2, W[ 27 ] );
1023
    subRound( C, D, E, A, B, f2, K2, W[ 28 ] );
1024
    subRound( B, C, D, E, A, f2, K2, W[ 29 ] );
1025
    subRound( A, B, C, D, E, f2, K2, W[ 30 ] );
1026
    subRound( E, A, B, C, D, f2, K2, W[ 31 ] );
1027
    subRound( D, E, A, B, C, f2, K2, W[ 32 ] );
1028
    subRound( C, D, E, A, B, f2, K2, W[ 33 ] );
1029
    subRound( B, C, D, E, A, f2, K2, W[ 34 ] );
1030
    subRound( A, B, C, D, E, f2, K2, W[ 35 ] );
1031
    subRound( E, A, B, C, D, f2, K2, W[ 36 ] );
1032
    subRound( D, E, A, B, C, f2, K2, W[ 37 ] );
1033
    subRound( C, D, E, A, B, f2, K2, W[ 38 ] );
1034
    subRound( B, C, D, E, A, f2, K2, W[ 39 ] );
1035
 
1036
    subRound( A, B, C, D, E, f3, K3, W[ 40 ] );
1037
    subRound( E, A, B, C, D, f3, K3, W[ 41 ] );
1038
    subRound( D, E, A, B, C, f3, K3, W[ 42 ] );
1039
    subRound( C, D, E, A, B, f3, K3, W[ 43 ] );
1040
    subRound( B, C, D, E, A, f3, K3, W[ 44 ] );
1041
    subRound( A, B, C, D, E, f3, K3, W[ 45 ] );
1042
    subRound( E, A, B, C, D, f3, K3, W[ 46 ] );
1043
    subRound( D, E, A, B, C, f3, K3, W[ 47 ] );
1044
    subRound( C, D, E, A, B, f3, K3, W[ 48 ] );
1045
    subRound( B, C, D, E, A, f3, K3, W[ 49 ] );
1046
    subRound( A, B, C, D, E, f3, K3, W[ 50 ] );
1047
    subRound( E, A, B, C, D, f3, K3, W[ 51 ] );
1048
    subRound( D, E, A, B, C, f3, K3, W[ 52 ] );
1049
    subRound( C, D, E, A, B, f3, K3, W[ 53 ] );
1050
    subRound( B, C, D, E, A, f3, K3, W[ 54 ] );
1051
    subRound( A, B, C, D, E, f3, K3, W[ 55 ] );
1052
    subRound( E, A, B, C, D, f3, K3, W[ 56 ] );
1053
    subRound( D, E, A, B, C, f3, K3, W[ 57 ] );
1054
    subRound( C, D, E, A, B, f3, K3, W[ 58 ] );
1055
    subRound( B, C, D, E, A, f3, K3, W[ 59 ] );
1056
 
1057
    subRound( A, B, C, D, E, f4, K4, W[ 60 ] );
1058
    subRound( E, A, B, C, D, f4, K4, W[ 61 ] );
1059
    subRound( D, E, A, B, C, f4, K4, W[ 62 ] );
1060
    subRound( C, D, E, A, B, f4, K4, W[ 63 ] );
1061
    subRound( B, C, D, E, A, f4, K4, W[ 64 ] );
1062
    subRound( A, B, C, D, E, f4, K4, W[ 65 ] );
1063
    subRound( E, A, B, C, D, f4, K4, W[ 66 ] );
1064
    subRound( D, E, A, B, C, f4, K4, W[ 67 ] );
1065
    subRound( C, D, E, A, B, f4, K4, W[ 68 ] );
1066
    subRound( B, C, D, E, A, f4, K4, W[ 69 ] );
1067
    subRound( A, B, C, D, E, f4, K4, W[ 70 ] );
1068
    subRound( E, A, B, C, D, f4, K4, W[ 71 ] );
1069
    subRound( D, E, A, B, C, f4, K4, W[ 72 ] );
1070
    subRound( C, D, E, A, B, f4, K4, W[ 73 ] );
1071
    subRound( B, C, D, E, A, f4, K4, W[ 74 ] );
1072
    subRound( A, B, C, D, E, f4, K4, W[ 75 ] );
1073
    subRound( E, A, B, C, D, f4, K4, W[ 76 ] );
1074
    subRound( D, E, A, B, C, f4, K4, W[ 77 ] );
1075
    subRound( C, D, E, A, B, f4, K4, W[ 78 ] );
1076
    subRound( B, C, D, E, A, f4, K4, W[ 79 ] );
1077
#else
1078
#error Illegal SHA_CODE_SIZE
1079
#endif
1080
 
1081
    /* Build message digest */
1082
    digest[ 0 ] += A;
1083
    digest[ 1 ] += B;
1084
    digest[ 2 ] += C;
1085
    digest[ 3 ] += D;
1086
    digest[ 4 ] += E;
1087
 
1088
        /* W is wiped by the caller */
1089
#undef W
1090
}
1091
 
1092
#undef ROTL
1093
#undef f1
1094
#undef f2
1095
#undef f3
1096
#undef f4
1097
#undef K1       
1098
#undef K2
1099
#undef K3       
1100
#undef K4       
1101
#undef subRound
1102
 
1103
#else /* !USE_SHA - Use MD5 */
1104
 
1105
#define HASH_BUFFER_SIZE 4
1106
#define HASH_EXTRA_SIZE 0
1107
#define HASH_TRANSFORM MD5Transform
1108
 
1109
/*
1110
 * MD5 transform algorithm, taken from code written by Colin Plumb,
1111
 * and put into the public domain
1112
 */
1113
 
1114
/* The four core functions - F1 is optimized somewhat */
1115
 
1116
/* #define F1(x, y, z) (x & y | ~x & z) */
1117
#define F1(x, y, z) (z ^ (x & (y ^ z)))
1118
#define F2(x, y, z) F1(z, x, y)
1119
#define F3(x, y, z) (x ^ y ^ z)
1120
#define F4(x, y, z) (y ^ (x | ~z))
1121
 
1122
/* This is the central step in the MD5 algorithm. */
1123
#define MD5STEP(f, w, x, y, z, data, s) \
1124
        ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
1125
 
1126
/*
1127
 * The core of the MD5 algorithm, this alters an existing MD5 hash to
1128
 * reflect the addition of 16 longwords of new data.  MD5Update blocks
1129
 * the data and converts bytes into longwords for this routine.
1130
 */
1131
static void MD5Transform(__u32 buf[HASH_BUFFER_SIZE], __u32 const in[16])
1132
{
1133
        __u32 a, b, c, d;
1134
 
1135
        a = buf[0];
1136
        b = buf[1];
1137
        c = buf[2];
1138
        d = buf[3];
1139
 
1140
        MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478,  7);
1141
        MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
1142
        MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
1143
        MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
1144
        MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf,  7);
1145
        MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
1146
        MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
1147
        MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
1148
        MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8,  7);
1149
        MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
1150
        MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
1151
        MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
1152
        MD5STEP(F1, a, b, c, d, in[12]+0x6b901122,  7);
1153
        MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
1154
        MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
1155
        MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
1156
 
1157
        MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562,  5);
1158
        MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340,  9);
1159
        MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
1160
        MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
1161
        MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d,  5);
1162
        MD5STEP(F2, d, a, b, c, in[10]+0x02441453,  9);
1163
        MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
1164
        MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
1165
        MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6,  5);
1166
        MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6,  9);
1167
        MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
1168
        MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
1169
        MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905,  5);
1170
        MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8,  9);
1171
        MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
1172
        MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
1173
 
1174
        MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942,  4);
1175
        MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
1176
        MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
1177
        MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
1178
        MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44,  4);
1179
        MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
1180
        MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
1181
        MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
1182
        MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6,  4);
1183
        MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
1184
        MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
1185
        MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
1186
        MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039,  4);
1187
        MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
1188
        MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
1189
        MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
1190
 
1191
        MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244,  6);
1192
        MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
1193
        MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
1194
        MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
1195
        MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3,  6);
1196
        MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
1197
        MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
1198
        MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
1199
        MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f,  6);
1200
        MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
1201
        MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
1202
        MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
1203
        MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82,  6);
1204
        MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
1205
        MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
1206
        MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
1207
 
1208
        buf[0] += a;
1209
        buf[1] += b;
1210
        buf[2] += c;
1211
        buf[3] += d;
1212
}
1213
 
1214
#undef F1
1215
#undef F2
1216
#undef F3
1217
#undef F4
1218
#undef MD5STEP
1219
 
1220
#endif /* !USE_SHA */
1221
 
1222
/*********************************************************************
1223
 *
1224
 * Entropy extraction routines
1225
 *
1226
 *********************************************************************/
1227
 
1228
#define EXTRACT_ENTROPY_USER            1
1229
#define EXTRACT_ENTROPY_SECONDARY       2
1230
#define TMP_BUF_SIZE                    (HASH_BUFFER_SIZE + HASH_EXTRA_SIZE)
1231
#define SEC_XFER_SIZE                   (TMP_BUF_SIZE*4)
1232
 
1233
static ssize_t extract_entropy(struct entropy_store *r, void * buf,
1234
                               size_t nbytes, int flags);
1235
 
1236
/*
1237
 * This utility inline function is responsible for transfering entropy
1238
 * from the primary pool to the secondary extraction pool.  We pull
1239
 * randomness under two conditions; one is if there isn't enough entropy
1240
 * in the secondary pool.  The other is after we have extracted 1024 bytes,
1241
 * at which point we do a "catastrophic reseeding".
1242
 */
1243
static inline void xfer_secondary_pool(struct entropy_store *r,
1244
                                       size_t nbytes, __u32 *tmp)
1245
{
1246
        if (r->entropy_count < nbytes * 8 &&
1247
            r->entropy_count < r->poolinfo.POOLBITS) {
1248
                int nwords = min_t(int,
1249
                                   r->poolinfo.poolwords - r->entropy_count/32,
1250
                                   sizeof(tmp) / 4);
1251
 
1252
                DEBUG_ENT("xfer %d from primary to %s (have %d, need %d)\n",
1253
                          nwords * 32,
1254
                          r == sec_random_state ? "secondary" : "unknown",
1255
                          r->entropy_count, nbytes * 8);
1256
 
1257
                extract_entropy(random_state, tmp, nwords * 4, 0);
1258
                add_entropy_words(r, tmp, nwords);
1259
                credit_entropy_store(r, nwords * 32);
1260
        }
1261
        if (r->extract_count > 1024) {
1262
                DEBUG_ENT("reseeding %s with %d from primary\n",
1263
                          r == sec_random_state ? "secondary" : "unknown",
1264
                          sizeof(tmp) * 8);
1265
                extract_entropy(random_state, tmp, sizeof(tmp), 0);
1266
                add_entropy_words(r, tmp, sizeof(tmp) / 4);
1267
                r->extract_count = 0;
1268
        }
1269
}
1270
 
1271
/*
1272
 * This function extracts randomness from the "entropy pool", and
1273
 * returns it in a buffer.  This function computes how many remaining
1274
 * bits of entropy are left in the pool, but it does not restrict the
1275
 * number of bytes that are actually obtained.  If the EXTRACT_ENTROPY_USER
1276
 * flag is given, then the buf pointer is assumed to be in user space.
1277
 *
1278
 * If the EXTRACT_ENTROPY_SECONDARY flag is given, then we are actually
1279
 * extracting entropy from the secondary pool, and can refill from the
1280
 * primary pool if needed.
1281
 *
1282
 * Note: extract_entropy() assumes that .poolwords is a multiple of 16 words.
1283
 */
1284
static ssize_t extract_entropy(struct entropy_store *r, void * buf,
1285
                               size_t nbytes, int flags)
1286
{
1287
        ssize_t ret, i;
1288
        __u32 tmp[TMP_BUF_SIZE];
1289
        __u32 x;
1290
 
1291
        add_timer_randomness(&extract_timer_state, nbytes);
1292
 
1293
        /* Redundant, but just in case... */
1294
        if (r->entropy_count > r->poolinfo.POOLBITS)
1295
                r->entropy_count = r->poolinfo.POOLBITS;
1296
 
1297
        if (flags & EXTRACT_ENTROPY_SECONDARY)
1298
                xfer_secondary_pool(r, nbytes, tmp);
1299
 
1300
        DEBUG_ENT("%s has %d bits, want %d bits\n",
1301
                  r == sec_random_state ? "secondary" :
1302
                  r == random_state ? "primary" : "unknown",
1303
                  r->entropy_count, nbytes * 8);
1304
 
1305
        if (r->entropy_count / 8 >= nbytes)
1306
                r->entropy_count -= nbytes*8;
1307
        else
1308
                r->entropy_count = 0;
1309
 
1310
        if (r->entropy_count < random_write_wakeup_thresh)
1311
                wake_up_interruptible(&random_write_wait);
1312
 
1313
        r->extract_count += nbytes;
1314
 
1315
        ret = 0;
1316
        while (nbytes) {
1317
                /*
1318
                 * Check if we need to break out or reschedule....
1319
                 */
1320
                if ((flags & EXTRACT_ENTROPY_USER) && current->need_resched) {
1321
                        if (signal_pending(current)) {
1322
                                if (ret == 0)
1323
                                        ret = -ERESTARTSYS;
1324
                                break;
1325
                        }
1326
                        schedule();
1327
                }
1328
 
1329
                /* Hash the pool to get the output */
1330
                tmp[0] = 0x67452301;
1331
                tmp[1] = 0xefcdab89;
1332
                tmp[2] = 0x98badcfe;
1333
                tmp[3] = 0x10325476;
1334
#ifdef USE_SHA
1335
                tmp[4] = 0xc3d2e1f0;
1336
#endif
1337
                /*
1338
                 * As we hash the pool, we mix intermediate values of
1339
                 * the hash back into the pool.  This eliminates
1340
                 * backtracking attacks (where the attacker knows
1341
                 * the state of the pool plus the current outputs, and
1342
                 * attempts to find previous ouputs), unless the hash
1343
                 * function can be inverted.
1344
                 */
1345
                for (i = 0, x = 0; i < r->poolinfo.poolwords; i += 16, x+=2) {
1346
                        HASH_TRANSFORM(tmp, r->pool+i);
1347
                        add_entropy_words(r, &tmp[x%HASH_BUFFER_SIZE], 1);
1348
                }
1349
 
1350
                /*
1351
                 * In case the hash function has some recognizable
1352
                 * output pattern, we fold it in half.
1353
                 */
1354
                for (i = 0; i <  HASH_BUFFER_SIZE/2; i++)
1355
                        tmp[i] ^= tmp[i + (HASH_BUFFER_SIZE+1)/2];
1356
#if HASH_BUFFER_SIZE & 1        /* There's a middle word to deal with */
1357
                x = tmp[HASH_BUFFER_SIZE/2];
1358
                x ^= (x >> 16);         /* Fold it in half */
1359
                ((__u16 *)tmp)[HASH_BUFFER_SIZE-1] = (__u16)x;
1360
#endif
1361
 
1362
                /* Copy data to destination buffer */
1363
                i = min(nbytes, HASH_BUFFER_SIZE*sizeof(__u32)/2);
1364
                if (flags & EXTRACT_ENTROPY_USER) {
1365
                        i -= copy_to_user(buf, (__u8 const *)tmp, i);
1366
                        if (!i) {
1367
                                ret = -EFAULT;
1368
                                break;
1369
                        }
1370
                } else
1371
                        memcpy(buf, (__u8 const *)tmp, i);
1372
                nbytes -= i;
1373
                buf += i;
1374
                ret += i;
1375
                add_timer_randomness(&extract_timer_state, nbytes);
1376
        }
1377
 
1378
        /* Wipe data just returned from memory */
1379
        memset(tmp, 0, sizeof(tmp));
1380
 
1381
        return ret;
1382
}
1383
 
1384
/*
1385
 * This function is the exported kernel interface.  It returns some
1386
 * number of good random numbers, suitable for seeding TCP sequence
1387
 * numbers, etc.
1388
 */
1389
void get_random_bytes(void *buf, int nbytes)
1390
{
1391
        if (sec_random_state)
1392
                extract_entropy(sec_random_state, (char *) buf, nbytes,
1393
                                EXTRACT_ENTROPY_SECONDARY);
1394
        else if (random_state)
1395
                extract_entropy(random_state, (char *) buf, nbytes, 0);
1396
        else
1397
                printk(KERN_NOTICE "get_random_bytes called before "
1398
                                   "random driver initialization\n");
1399
}
1400
 
1401
/*********************************************************************
1402
 *
1403
 * Functions to interface with Linux
1404
 *
1405
 *********************************************************************/
1406
 
1407
/*
1408
 * Initialize the random pool with standard stuff.
1409
 *
1410
 * NOTE: This is an OS-dependent function.
1411
 */
1412
static void init_std_data(struct entropy_store *r)
1413
{
1414
        struct timeval  tv;
1415
        __u32           words[2];
1416
        char            *p;
1417
        int             i;
1418
 
1419
        do_gettimeofday(&tv);
1420
        words[0] = tv.tv_sec;
1421
        words[1] = tv.tv_usec;
1422
        add_entropy_words(r, words, 2);
1423
 
1424
        /*
1425
         *      This doesn't lock system.utsname. However, we are generating
1426
         *      entropy so a race with a name set here is fine.
1427
         */
1428
        p = (char *) &system_utsname;
1429
        for (i = sizeof(system_utsname) / sizeof(words); i; i--) {
1430
                memcpy(words, p, sizeof(words));
1431
                add_entropy_words(r, words, sizeof(words)/4);
1432
                p += sizeof(words);
1433
        }
1434
}
1435
 
1436
void __init rand_initialize(void)
1437
{
1438
        int i;
1439
 
1440
        if (create_entropy_store(DEFAULT_POOL_SIZE, &random_state))
1441
                return;         /* Error, return */
1442
        if (batch_entropy_init(BATCH_ENTROPY_SIZE, random_state))
1443
                return;         /* Error, return */
1444
        if (create_entropy_store(SECONDARY_POOL_SIZE, &sec_random_state))
1445
                return;         /* Error, return */
1446
        clear_entropy_store(random_state);
1447
        clear_entropy_store(sec_random_state);
1448
        init_std_data(random_state);
1449
#ifdef CONFIG_SYSCTL
1450
        sysctl_init_random(random_state);
1451
#endif
1452
#ifndef CONFIG_ARCH_S390
1453
        for (i = 0; i < NR_IRQS; i++)
1454
                irq_timer_state[i] = NULL;
1455
#endif
1456
        for (i = 0; i < MAX_BLKDEV; i++)
1457
                blkdev_timer_state[i] = NULL;
1458
        memset(&keyboard_timer_state, 0, sizeof(struct timer_rand_state));
1459
        memset(&mouse_timer_state, 0, sizeof(struct timer_rand_state));
1460
        memset(&extract_timer_state, 0, sizeof(struct timer_rand_state));
1461
        extract_timer_state.dont_count_entropy = 1;
1462
}
1463
 
1464
#ifndef CONFIG_ARCH_S390
1465
void rand_initialize_irq(int irq)
1466
{
1467
        struct timer_rand_state *state;
1468
 
1469
        if (irq >= NR_IRQS || irq_timer_state[irq])
1470
                return;
1471
 
1472
        /*
1473
         * If kmalloc returns null, we just won't use that entropy
1474
         * source.
1475
         */
1476
        state = kmalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
1477
        if (state) {
1478
                memset(state, 0, sizeof(struct timer_rand_state));
1479
                irq_timer_state[irq] = state;
1480
        }
1481
}
1482
#endif
1483
 
1484
void rand_initialize_blkdev(int major, int mode)
1485
{
1486
        struct timer_rand_state *state;
1487
 
1488
        if (major >= MAX_BLKDEV || blkdev_timer_state[major])
1489
                return;
1490
 
1491
        /*
1492
         * If kmalloc returns null, we just won't use that entropy
1493
         * source.
1494
         */
1495
        state = kmalloc(sizeof(struct timer_rand_state), mode);
1496
        if (state) {
1497
                memset(state, 0, sizeof(struct timer_rand_state));
1498
                blkdev_timer_state[major] = state;
1499
        }
1500
}
1501
 
1502
 
1503
static ssize_t
1504
random_read(struct file * file, char * buf, size_t nbytes, loff_t *ppos)
1505
{
1506
        DECLARE_WAITQUEUE(wait, current);
1507
        ssize_t                 n, retval = 0, count = 0;
1508
 
1509
        if (nbytes == 0)
1510
                return 0;
1511
 
1512
        add_wait_queue(&random_read_wait, &wait);
1513
        while (nbytes > 0) {
1514
                set_current_state(TASK_INTERRUPTIBLE);
1515
 
1516
                n = nbytes;
1517
                if (n > SEC_XFER_SIZE)
1518
                        n = SEC_XFER_SIZE;
1519
                if (n > random_state->entropy_count / 8)
1520
                        n = random_state->entropy_count / 8;
1521
                if (n == 0) {
1522
                        if (file->f_flags & O_NONBLOCK) {
1523
                                retval = -EAGAIN;
1524
                                break;
1525
                        }
1526
                        if (signal_pending(current)) {
1527
                                retval = -ERESTARTSYS;
1528
                                break;
1529
                        }
1530
                        schedule();
1531
                        continue;
1532
                }
1533
                n = extract_entropy(sec_random_state, buf, n,
1534
                                    EXTRACT_ENTROPY_USER |
1535
                                    EXTRACT_ENTROPY_SECONDARY);
1536
                if (n < 0) {
1537
                        retval = n;
1538
                        break;
1539
                }
1540
                count += n;
1541
                buf += n;
1542
                nbytes -= n;
1543
                break;          /* This break makes the device work */
1544
                                /* like a named pipe */
1545
        }
1546
        current->state = TASK_RUNNING;
1547
        remove_wait_queue(&random_read_wait, &wait);
1548
 
1549
        /*
1550
         * If we gave the user some bytes, update the access time.
1551
         */
1552
        if (count != 0) {
1553
                UPDATE_ATIME(file->f_dentry->d_inode);
1554
        }
1555
 
1556
        return (count ? count : retval);
1557
}
1558
 
1559
static ssize_t
1560
urandom_read(struct file * file, char * buf,
1561
                      size_t nbytes, loff_t *ppos)
1562
{
1563
        return extract_entropy(sec_random_state, buf, nbytes,
1564
                               EXTRACT_ENTROPY_USER |
1565
                               EXTRACT_ENTROPY_SECONDARY);
1566
}
1567
 
1568
static unsigned int
1569
random_poll(struct file *file, poll_table * wait)
1570
{
1571
        unsigned int mask;
1572
 
1573
        poll_wait(file, &random_read_wait, wait);
1574
        poll_wait(file, &random_write_wait, wait);
1575
        mask = 0;
1576
        if (random_state->entropy_count >= random_read_wakeup_thresh)
1577
                mask |= POLLIN | POLLRDNORM;
1578
        if (random_state->entropy_count < random_write_wakeup_thresh)
1579
                mask |= POLLOUT | POLLWRNORM;
1580
        return mask;
1581
}
1582
 
1583
static ssize_t
1584
random_write(struct file * file, const char * buffer,
1585
             size_t count, loff_t *ppos)
1586
{
1587
        int             ret = 0;
1588
        size_t          bytes;
1589
        __u32           buf[16];
1590
        const char      *p = buffer;
1591
        size_t          c = count;
1592
 
1593
        while (c > 0) {
1594
                bytes = min(c, sizeof(buf));
1595
 
1596
                bytes -= copy_from_user(&buf, p, bytes);
1597
                if (!bytes) {
1598
                        ret = -EFAULT;
1599
                        break;
1600
                }
1601
                c -= bytes;
1602
                p += bytes;
1603
 
1604
                add_entropy_words(random_state, buf, (bytes + 3) / 4);
1605
        }
1606
        if (p == buffer) {
1607
                return (ssize_t)ret;
1608
        } else {
1609
                file->f_dentry->d_inode->i_mtime = CURRENT_TIME;
1610
                mark_inode_dirty(file->f_dentry->d_inode);
1611
                return (ssize_t)(p - buffer);
1612
        }
1613
}
1614
 
1615
static int
1616
random_ioctl(struct inode * inode, struct file * file,
1617
             unsigned int cmd, unsigned long arg)
1618
{
1619
        int *p, size, ent_count;
1620
        int retval;
1621
 
1622
        switch (cmd) {
1623
        case RNDGETENTCNT:
1624
                ent_count = random_state->entropy_count;
1625
                if (put_user(ent_count, (int *) arg))
1626
                        return -EFAULT;
1627
                return 0;
1628
        case RNDADDTOENTCNT:
1629
                if (!capable(CAP_SYS_ADMIN))
1630
                        return -EPERM;
1631
                if (get_user(ent_count, (int *) arg))
1632
                        return -EFAULT;
1633
                credit_entropy_store(random_state, ent_count);
1634
                /*
1635
                 * Wake up waiting processes if we have enough
1636
                 * entropy.
1637
                 */
1638
                if (random_state->entropy_count >= random_read_wakeup_thresh)
1639
                        wake_up_interruptible(&random_read_wait);
1640
                return 0;
1641
        case RNDGETPOOL:
1642
                if (!capable(CAP_SYS_ADMIN))
1643
                        return -EPERM;
1644
                p = (int *) arg;
1645
                ent_count = random_state->entropy_count;
1646
                if (put_user(ent_count, p++) ||
1647
                    get_user(size, p) ||
1648
                    put_user(random_state->poolinfo.poolwords, p++))
1649
                        return -EFAULT;
1650
                if (size < 0)
1651
                        return -EINVAL;
1652
                if (size > random_state->poolinfo.poolwords)
1653
                        size = random_state->poolinfo.poolwords;
1654
                if (copy_to_user(p, random_state->pool, size * sizeof(__u32)))
1655
                        return -EFAULT;
1656
                return 0;
1657
        case RNDADDENTROPY:
1658
                if (!capable(CAP_SYS_ADMIN))
1659
                        return -EPERM;
1660
                p = (int *) arg;
1661
                if (get_user(ent_count, p++))
1662
                        return -EFAULT;
1663
                if (ent_count < 0)
1664
                        return -EINVAL;
1665
                if (get_user(size, p++))
1666
                        return -EFAULT;
1667
                retval = random_write(file, (const char *) p,
1668
                                      size, &file->f_pos);
1669
                if (retval < 0)
1670
                        return retval;
1671
                credit_entropy_store(random_state, ent_count);
1672
                /*
1673
                 * Wake up waiting processes if we have enough
1674
                 * entropy.
1675
                 */
1676
                if (random_state->entropy_count >= random_read_wakeup_thresh)
1677
                        wake_up_interruptible(&random_read_wait);
1678
                return 0;
1679
        case RNDZAPENTCNT:
1680
                if (!capable(CAP_SYS_ADMIN))
1681
                        return -EPERM;
1682
                random_state->entropy_count = 0;
1683
                return 0;
1684
        case RNDCLEARPOOL:
1685
                /* Clear the entropy pool and associated counters. */
1686
                if (!capable(CAP_SYS_ADMIN))
1687
                        return -EPERM;
1688
                clear_entropy_store(random_state);
1689
                init_std_data(random_state);
1690
                return 0;
1691
        default:
1692
                return -EINVAL;
1693
        }
1694
}
1695
 
1696
struct file_operations random_fops = {
1697
        read:           random_read,
1698
        write:          random_write,
1699
        poll:           random_poll,
1700
        ioctl:          random_ioctl,
1701
};
1702
 
1703
struct file_operations urandom_fops = {
1704
        read:           urandom_read,
1705
        write:          random_write,
1706
        ioctl:          random_ioctl,
1707
};
1708
 
1709
/***************************************************************
1710
 * Random UUID interface
1711
 *
1712
 * Used here for a Boot ID, but can be useful for other kernel
1713
 * drivers.
1714
 ***************************************************************/
1715
 
1716
/*
1717
 * Generate random UUID
1718
 */
1719
void generate_random_uuid(unsigned char uuid_out[16])
1720
{
1721
        get_random_bytes(uuid_out, 16);
1722
        /* Set UUID version to 4 --- truely random generation */
1723
        uuid_out[6] = (uuid_out[6] & 0x0F) | 0x40;
1724
        /* Set the UUID variant to DCE */
1725
        uuid_out[8] = (uuid_out[8] & 0x3F) | 0x80;
1726
}
1727
 
1728
/********************************************************************
1729
 *
1730
 * Sysctl interface
1731
 *
1732
 ********************************************************************/
1733
 
1734
#ifdef CONFIG_SYSCTL
1735
 
1736
#include <linux/sysctl.h>
1737
 
1738
static int sysctl_poolsize;
1739
static int min_read_thresh, max_read_thresh;
1740
static int min_write_thresh, max_write_thresh;
1741
static char sysctl_bootid[16];
1742
 
1743
/*
1744
 * This function handles a request from the user to change the pool size
1745
 * of the primary entropy store.
1746
 */
1747
static int change_poolsize(int poolsize)
1748
{
1749
        struct entropy_store    *new_store, *old_store;
1750
        int                     ret;
1751
 
1752
        if ((ret = create_entropy_store(poolsize, &new_store)))
1753
                return ret;
1754
 
1755
        add_entropy_words(new_store, random_state->pool,
1756
                          random_state->poolinfo.poolwords);
1757
        credit_entropy_store(new_store, random_state->entropy_count);
1758
 
1759
        sysctl_init_random(new_store);
1760
        old_store = random_state;
1761
        random_state = batch_tqueue.data = new_store;
1762
        free_entropy_store(old_store);
1763
        return 0;
1764
}
1765
 
1766
static int proc_do_poolsize(ctl_table *table, int write, struct file *filp,
1767
                            void *buffer, size_t *lenp)
1768
{
1769
        int     ret;
1770
 
1771
        sysctl_poolsize = random_state->poolinfo.POOLBYTES;
1772
 
1773
        ret = proc_dointvec(table, write, filp, buffer, lenp);
1774
        if (ret || !write ||
1775
            (sysctl_poolsize == random_state->poolinfo.POOLBYTES))
1776
                return ret;
1777
 
1778
        return change_poolsize(sysctl_poolsize);
1779
}
1780
 
1781
static int poolsize_strategy(ctl_table *table, int *name, int nlen,
1782
                             void *oldval, size_t *oldlenp,
1783
                             void *newval, size_t newlen, void **context)
1784
{
1785
        int     len;
1786
 
1787
        sysctl_poolsize = random_state->poolinfo.POOLBYTES;
1788
 
1789
        /*
1790
         * We only handle the write case, since the read case gets
1791
         * handled by the default handler (and we don't care if the
1792
         * write case happens twice; it's harmless).
1793
         */
1794
        if (newval && newlen) {
1795
                len = newlen;
1796
                if (len > table->maxlen)
1797
                        len = table->maxlen;
1798
                if (copy_from_user(table->data, newval, len))
1799
                        return -EFAULT;
1800
        }
1801
 
1802
        if (sysctl_poolsize != random_state->poolinfo.POOLBYTES)
1803
                return change_poolsize(sysctl_poolsize);
1804
 
1805
        return 0;
1806
}
1807
 
1808
/*
1809
 * These functions is used to return both the bootid UUID, and random
1810
 * UUID.  The difference is in whether table->data is NULL; if it is,
1811
 * then a new UUID is generated and returned to the user.
1812
 *
1813
 * If the user accesses this via the proc interface, it will be returned
1814
 * as an ASCII string in the standard UUID format.  If accesses via the
1815
 * sysctl system call, it is returned as 16 bytes of binary data.
1816
 */
1817
static int proc_do_uuid(ctl_table *table, int write, struct file *filp,
1818
                        void *buffer, size_t *lenp)
1819
{
1820
        ctl_table       fake_table;
1821
        unsigned char   buf[64], tmp_uuid[16], *uuid;
1822
 
1823
        uuid = table->data;
1824
        if (!uuid) {
1825
                uuid = tmp_uuid;
1826
                uuid[8] = 0;
1827
        }
1828
        if (uuid[8] == 0)
1829
                generate_random_uuid(uuid);
1830
 
1831
        sprintf(buf, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
1832
                "%02x%02x%02x%02x%02x%02x",
1833
                uuid[0],  uuid[1],  uuid[2],  uuid[3],
1834
                uuid[4],  uuid[5],  uuid[6],  uuid[7],
1835
                uuid[8],  uuid[9],  uuid[10], uuid[11],
1836
                uuid[12], uuid[13], uuid[14], uuid[15]);
1837
        fake_table.data = buf;
1838
        fake_table.maxlen = sizeof(buf);
1839
 
1840
        return proc_dostring(&fake_table, write, filp, buffer, lenp);
1841
}
1842
 
1843
static int uuid_strategy(ctl_table *table, int *name, int nlen,
1844
                         void *oldval, size_t *oldlenp,
1845
                         void *newval, size_t newlen, void **context)
1846
{
1847
        unsigned char   tmp_uuid[16], *uuid;
1848
        unsigned int    len;
1849
 
1850
        if (!oldval || !oldlenp)
1851
                return 1;
1852
 
1853
        uuid = table->data;
1854
        if (!uuid) {
1855
                uuid = tmp_uuid;
1856
                uuid[8] = 0;
1857
        }
1858
        if (uuid[8] == 0)
1859
                generate_random_uuid(uuid);
1860
 
1861
        if (get_user(len, oldlenp))
1862
                return -EFAULT;
1863
        if (len) {
1864
                if (len > 16)
1865
                        len = 16;
1866
                if (copy_to_user(oldval, uuid, len) ||
1867
                    put_user(len, oldlenp))
1868
                        return -EFAULT;
1869
        }
1870
        return 1;
1871
}
1872
 
1873
ctl_table random_table[] = {
1874
        {RANDOM_POOLSIZE, "poolsize",
1875
         &sysctl_poolsize, sizeof(int), 0644, NULL,
1876
         &proc_do_poolsize, &poolsize_strategy},
1877
        {RANDOM_ENTROPY_COUNT, "entropy_avail",
1878
         NULL, sizeof(int), 0444, NULL,
1879
         &proc_dointvec},
1880
        {RANDOM_READ_THRESH, "read_wakeup_threshold",
1881
         &random_read_wakeup_thresh, sizeof(int), 0644, NULL,
1882
         &proc_dointvec_minmax, &sysctl_intvec, 0,
1883
         &min_read_thresh, &max_read_thresh},
1884
        {RANDOM_WRITE_THRESH, "write_wakeup_threshold",
1885
         &random_write_wakeup_thresh, sizeof(int), 0644, NULL,
1886
         &proc_dointvec_minmax, &sysctl_intvec, 0,
1887
         &min_write_thresh, &max_write_thresh},
1888
        {RANDOM_BOOT_ID, "boot_id",
1889
         &sysctl_bootid, 16, 0444, NULL,
1890
         &proc_do_uuid, &uuid_strategy},
1891
        {RANDOM_UUID, "uuid",
1892
         NULL, 16, 0444, NULL,
1893
         &proc_do_uuid, &uuid_strategy},
1894
        {0}
1895
};
1896
 
1897
static void sysctl_init_random(struct entropy_store *random_state)
1898
{
1899
        min_read_thresh = 8;
1900
        min_write_thresh = 0;
1901
        max_read_thresh = max_write_thresh = random_state->poolinfo.POOLBITS;
1902
        random_table[1].data = &random_state->entropy_count;
1903
}
1904
#endif  /* CONFIG_SYSCTL */
1905
 
1906
/********************************************************************
1907
 *
1908
 * Random funtions for networking
1909
 *
1910
 ********************************************************************/
1911
 
1912
/*
1913
 * TCP initial sequence number picking.  This uses the random number
1914
 * generator to pick an initial secret value.  This value is hashed
1915
 * along with the TCP endpoint information to provide a unique
1916
 * starting point for each pair of TCP endpoints.  This defeats
1917
 * attacks which rely on guessing the initial TCP sequence number.
1918
 * This algorithm was suggested by Steve Bellovin.
1919
 *
1920
 * Using a very strong hash was taking an appreciable amount of the total
1921
 * TCP connection establishment time, so this is a weaker hash,
1922
 * compensated for by changing the secret periodically.
1923
 */
1924
 
1925
/* F, G and H are basic MD4 functions: selection, majority, parity */
1926
#define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
1927
#define G(x, y, z) (((x) & (y)) + (((x) ^ (y)) & (z)))
1928
#define H(x, y, z) ((x) ^ (y) ^ (z))
1929
 
1930
/*
1931
 * The generic round function.  The application is so specific that
1932
 * we don't bother protecting all the arguments with parens, as is generally
1933
 * good macro practice, in favor of extra legibility.
1934
 * Rotation is separate from addition to prevent recomputation
1935
 */
1936
#define ROUND(f, a, b, c, d, x, s)      \
1937
        (a += f(b, c, d) + x, a = (a << s) | (a >> (32-s)))
1938
#define K1 0
1939
#define K2 013240474631UL
1940
#define K3 015666365641UL
1941
 
1942
/*
1943
 * Basic cut-down MD4 transform.  Returns only 32 bits of result.
1944
 */
1945
static __u32 halfMD4Transform (__u32 const buf[4], __u32 const in[8])
1946
{
1947
        __u32   a = buf[0], b = buf[1], c = buf[2], d = buf[3];
1948
 
1949
        /* Round 1 */
1950
        ROUND(F, a, b, c, d, in[0] + K1,  3);
1951
        ROUND(F, d, a, b, c, in[1] + K1,  7);
1952
        ROUND(F, c, d, a, b, in[2] + K1, 11);
1953
        ROUND(F, b, c, d, a, in[3] + K1, 19);
1954
        ROUND(F, a, b, c, d, in[4] + K1,  3);
1955
        ROUND(F, d, a, b, c, in[5] + K1,  7);
1956
        ROUND(F, c, d, a, b, in[6] + K1, 11);
1957
        ROUND(F, b, c, d, a, in[7] + K1, 19);
1958
 
1959
        /* Round 2 */
1960
        ROUND(G, a, b, c, d, in[1] + K2,  3);
1961
        ROUND(G, d, a, b, c, in[3] + K2,  5);
1962
        ROUND(G, c, d, a, b, in[5] + K2,  9);
1963
        ROUND(G, b, c, d, a, in[7] + K2, 13);
1964
        ROUND(G, a, b, c, d, in[0] + K2,  3);
1965
        ROUND(G, d, a, b, c, in[2] + K2,  5);
1966
        ROUND(G, c, d, a, b, in[4] + K2,  9);
1967
        ROUND(G, b, c, d, a, in[6] + K2, 13);
1968
 
1969
        /* Round 3 */
1970
        ROUND(H, a, b, c, d, in[3] + K3,  3);
1971
        ROUND(H, d, a, b, c, in[7] + K3,  9);
1972
        ROUND(H, c, d, a, b, in[2] + K3, 11);
1973
        ROUND(H, b, c, d, a, in[6] + K3, 15);
1974
        ROUND(H, a, b, c, d, in[1] + K3,  3);
1975
        ROUND(H, d, a, b, c, in[5] + K3,  9);
1976
        ROUND(H, c, d, a, b, in[0] + K3, 11);
1977
        ROUND(H, b, c, d, a, in[4] + K3, 15);
1978
 
1979
        return buf[1] + b;      /* "most hashed" word */
1980
        /* Alternative: return sum of all words? */
1981
}
1982
 
1983
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
1984
 
1985
static __u32 twothirdsMD4Transform (__u32 const buf[4], __u32 const in[12])
1986
{
1987
        __u32   a = buf[0], b = buf[1], c = buf[2], d = buf[3];
1988
 
1989
        /* Round 1 */
1990
        ROUND(F, a, b, c, d, in[ 0] + K1,  3);
1991
        ROUND(F, d, a, b, c, in[ 1] + K1,  7);
1992
        ROUND(F, c, d, a, b, in[ 2] + K1, 11);
1993
        ROUND(F, b, c, d, a, in[ 3] + K1, 19);
1994
        ROUND(F, a, b, c, d, in[ 4] + K1,  3);
1995
        ROUND(F, d, a, b, c, in[ 5] + K1,  7);
1996
        ROUND(F, c, d, a, b, in[ 6] + K1, 11);
1997
        ROUND(F, b, c, d, a, in[ 7] + K1, 19);
1998
        ROUND(F, a, b, c, d, in[ 8] + K1,  3);
1999
        ROUND(F, d, a, b, c, in[ 9] + K1,  7);
2000
        ROUND(F, c, d, a, b, in[10] + K1, 11);
2001
        ROUND(F, b, c, d, a, in[11] + K1, 19);
2002
 
2003
        /* Round 2 */
2004
        ROUND(G, a, b, c, d, in[ 1] + K2,  3);
2005
        ROUND(G, d, a, b, c, in[ 3] + K2,  5);
2006
        ROUND(G, c, d, a, b, in[ 5] + K2,  9);
2007
        ROUND(G, b, c, d, a, in[ 7] + K2, 13);
2008
        ROUND(G, a, b, c, d, in[ 9] + K2,  3);
2009
        ROUND(G, d, a, b, c, in[11] + K2,  5);
2010
        ROUND(G, c, d, a, b, in[ 0] + K2,  9);
2011
        ROUND(G, b, c, d, a, in[ 2] + K2, 13);
2012
        ROUND(G, a, b, c, d, in[ 4] + K2,  3);
2013
        ROUND(G, d, a, b, c, in[ 6] + K2,  5);
2014
        ROUND(G, c, d, a, b, in[ 8] + K2,  9);
2015
        ROUND(G, b, c, d, a, in[10] + K2, 13);
2016
 
2017
        /* Round 3 */
2018
        ROUND(H, a, b, c, d, in[ 3] + K3,  3);
2019
        ROUND(H, d, a, b, c, in[ 7] + K3,  9);
2020
        ROUND(H, c, d, a, b, in[11] + K3, 11);
2021
        ROUND(H, b, c, d, a, in[ 2] + K3, 15);
2022
        ROUND(H, a, b, c, d, in[ 6] + K3,  3);
2023
        ROUND(H, d, a, b, c, in[10] + K3,  9);
2024
        ROUND(H, c, d, a, b, in[ 1] + K3, 11);
2025
        ROUND(H, b, c, d, a, in[ 5] + K3, 15);
2026
        ROUND(H, a, b, c, d, in[ 9] + K3,  3);
2027
        ROUND(H, d, a, b, c, in[ 0] + K3,  9);
2028
        ROUND(H, c, d, a, b, in[ 4] + K3, 11);
2029
        ROUND(H, b, c, d, a, in[ 8] + K3, 15);
2030
 
2031
        return buf[1] + b;      /* "most hashed" word */
2032
        /* Alternative: return sum of all words? */
2033
}
2034
#endif
2035
 
2036
#undef ROUND
2037
#undef F
2038
#undef G
2039
#undef H
2040
#undef K1
2041
#undef K2
2042
#undef K3
2043
 
2044
/* This should not be decreased so low that ISNs wrap too fast. */
2045
#define REKEY_INTERVAL  300
2046
/*
2047
 * Bit layout of the tcp sequence numbers (before adding current time):
2048
 * bit 24-31: increased after every key exchange
2049
 * bit 0-23: hash(source,dest)
2050
 *
2051
 * The implementation is similar to the algorithm described
2052
 * in the Appendix of RFC 1185, except that
2053
 * - it uses a 1 MHz clock instead of a 250 kHz clock
2054
 * - it performs a rekey every 5 minutes, which is equivalent
2055
 *      to a (source,dest) tulple dependent forward jump of the
2056
 *      clock by 0..2^(HASH_BITS+1)
2057
 *
2058
 * Thus the average ISN wraparound time is 68 minutes instead of
2059
 * 4.55 hours.
2060
 *
2061
 * SMP cleanup and lock avoidance with poor man's RCU.
2062
 *                      Manfred Spraul <manfred@colorfullife.com>
2063
 *
2064
 */
2065
#define COUNT_BITS      8
2066
#define COUNT_MASK      ( (1<<COUNT_BITS)-1)
2067
#define HASH_BITS       24
2068
#define HASH_MASK       ( (1<<HASH_BITS)-1 )
2069
 
2070
static struct keydata {
2071
        time_t rekey_time;
2072
        __u32   count;          // already shifted to the final position
2073
        __u32   secret[12];
2074
} ____cacheline_aligned ip_keydata[2];
2075
 
2076
static spinlock_t ip_lock = SPIN_LOCK_UNLOCKED;
2077
static unsigned int ip_cnt;
2078
 
2079
static struct keydata *__check_and_rekey(time_t time)
2080
{
2081
        struct keydata *keyptr;
2082
        spin_lock_bh(&ip_lock);
2083
        keyptr = &ip_keydata[ip_cnt&1];
2084
        if (!keyptr->rekey_time || (time - keyptr->rekey_time) > REKEY_INTERVAL) {
2085
                keyptr = &ip_keydata[1^(ip_cnt&1)];
2086
                keyptr->rekey_time = time;
2087
                get_random_bytes(keyptr->secret, sizeof(keyptr->secret));
2088
                keyptr->count = (ip_cnt&COUNT_MASK)<<HASH_BITS;
2089
                mb();
2090
                ip_cnt++;
2091
        }
2092
        spin_unlock_bh(&ip_lock);
2093
        return keyptr;
2094
}
2095
 
2096
static inline struct keydata *check_and_rekey(time_t time)
2097
{
2098
        struct keydata *keyptr = &ip_keydata[ip_cnt&1];
2099
 
2100
        rmb();
2101
        if (!keyptr->rekey_time || (time - keyptr->rekey_time) > REKEY_INTERVAL) {
2102
                keyptr = __check_and_rekey(time);
2103
        }
2104
 
2105
        return keyptr;
2106
}
2107
 
2108
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
2109
__u32 secure_tcpv6_sequence_number(__u32 *saddr, __u32 *daddr,
2110
                                   __u16 sport, __u16 dport)
2111
{
2112
        struct timeval  tv;
2113
        __u32           seq;
2114
        __u32           hash[12];
2115
        struct keydata *keyptr;
2116
 
2117
        /* The procedure is the same as for IPv4, but addresses are longer.
2118
         * Thus we must use twothirdsMD4Transform.
2119
         */
2120
 
2121
        do_gettimeofday(&tv);   /* We need the usecs below... */
2122
        keyptr = check_and_rekey(tv.tv_sec);
2123
 
2124
        memcpy(hash, saddr, 16);
2125
        hash[4]=(sport << 16) + dport;
2126
        memcpy(&hash[5],keyptr->secret,sizeof(__u32)*7);
2127
 
2128
        seq = twothirdsMD4Transform(daddr, hash) & HASH_MASK;
2129
        seq += keyptr->count;
2130
        seq += tv.tv_usec + tv.tv_sec*1000000;
2131
 
2132
        return seq;
2133
}
2134
 
2135
__u32 secure_ipv6_id(__u32 *daddr)
2136
{
2137
        struct keydata *keyptr;
2138
 
2139
        keyptr = check_and_rekey(CURRENT_TIME);
2140
 
2141
        return halfMD4Transform(daddr, keyptr->secret);
2142
}
2143
 
2144
#endif
2145
 
2146
 
2147
__u32 secure_tcp_sequence_number(__u32 saddr, __u32 daddr,
2148
                                 __u16 sport, __u16 dport)
2149
{
2150
        struct timeval  tv;
2151
        __u32           seq;
2152
        __u32   hash[4];
2153
        struct keydata *keyptr;
2154
 
2155
        /*
2156
         * Pick a random secret every REKEY_INTERVAL seconds.
2157
         */
2158
        do_gettimeofday(&tv);   /* We need the usecs below... */
2159
        keyptr = check_and_rekey(tv.tv_sec);
2160
 
2161
        /*
2162
         *  Pick a unique starting offset for each TCP connection endpoints
2163
         *  (saddr, daddr, sport, dport).
2164
         *  Note that the words are placed into the starting vector, which is
2165
         *  then mixed with a partial MD4 over random data.
2166
         */
2167
        hash[0]=saddr;
2168
        hash[1]=daddr;
2169
        hash[2]=(sport << 16) + dport;
2170
        hash[3]=keyptr->secret[11];
2171
 
2172
        seq = halfMD4Transform(hash, keyptr->secret) & HASH_MASK;
2173
        seq += keyptr->count;
2174
        /*
2175
         *      As close as possible to RFC 793, which
2176
         *      suggests using a 250 kHz clock.
2177
         *      Further reading shows this assumes 2 Mb/s networks.
2178
         *      For 10 Mb/s Ethernet, a 1 MHz clock is appropriate.
2179
         *      That's funny, Linux has one built in!  Use it!
2180
         *      (Networks are faster now - should this be increased?)
2181
         */
2182
        seq += tv.tv_usec + tv.tv_sec*1000000;
2183
#if 0
2184
        printk("init_seq(%lx, %lx, %d, %d) = %d\n",
2185
               saddr, daddr, sport, dport, seq);
2186
#endif
2187
        return seq;
2188
}
2189
 
2190
/*  The code below is shamelessly stolen from secure_tcp_sequence_number().
2191
 *  All blames to Andrey V. Savochkin <saw@msu.ru>.
2192
 */
2193
__u32 secure_ip_id(__u32 daddr)
2194
{
2195
        struct keydata *keyptr;
2196
        __u32 hash[4];
2197
 
2198
        keyptr = check_and_rekey(CURRENT_TIME);
2199
 
2200
        /*
2201
         *  Pick a unique starting offset for each IP destination.
2202
         *  The dest ip address is placed in the starting vector,
2203
         *  which is then hashed with random data.
2204
         */
2205
        hash[0] = daddr;
2206
        hash[1] = keyptr->secret[9];
2207
        hash[2] = keyptr->secret[10];
2208
        hash[3] = keyptr->secret[11];
2209
 
2210
        return halfMD4Transform(hash, keyptr->secret);
2211
}
2212
 
2213
#ifdef CONFIG_SYN_COOKIES
2214
/*
2215
 * Secure SYN cookie computation. This is the algorithm worked out by
2216
 * Dan Bernstein and Eric Schenk.
2217
 *
2218
 * For linux I implement the 1 minute counter by looking at the jiffies clock.
2219
 * The count is passed in as a parameter, so this code doesn't much care.
2220
 */
2221
 
2222
#define COOKIEBITS 24   /* Upper bits store count */
2223
#define COOKIEMASK (((__u32)1 << COOKIEBITS) - 1)
2224
 
2225
static int      syncookie_init;
2226
static __u32    syncookie_secret[2][16-3+HASH_BUFFER_SIZE];
2227
 
2228
__u32 secure_tcp_syn_cookie(__u32 saddr, __u32 daddr, __u16 sport,
2229
                __u16 dport, __u32 sseq, __u32 count, __u32 data)
2230
{
2231
        __u32   tmp[16 + HASH_BUFFER_SIZE + HASH_EXTRA_SIZE];
2232
        __u32   seq;
2233
 
2234
        /*
2235
         * Pick two random secrets the first time we need a cookie.
2236
         */
2237
        if (syncookie_init == 0) {
2238
                get_random_bytes(syncookie_secret, sizeof(syncookie_secret));
2239
                syncookie_init = 1;
2240
        }
2241
 
2242
        /*
2243
         * Compute the secure sequence number.
2244
         * The output should be:
2245
         *   HASH(sec1,saddr,sport,daddr,dport,sec1) + sseq + (count * 2^24)
2246
         *      + (HASH(sec2,saddr,sport,daddr,dport,count,sec2) % 2^24).
2247
         * Where sseq is their sequence number and count increases every
2248
         * minute by 1.
2249
         * As an extra hack, we add a small "data" value that encodes the
2250
         * MSS into the second hash value.
2251
         */
2252
 
2253
        memcpy(tmp+3, syncookie_secret[0], sizeof(syncookie_secret[0]));
2254
        tmp[0]=saddr;
2255
        tmp[1]=daddr;
2256
        tmp[2]=(sport << 16) + dport;
2257
        HASH_TRANSFORM(tmp+16, tmp);
2258
        seq = tmp[17] + sseq + (count << COOKIEBITS);
2259
 
2260
        memcpy(tmp+3, syncookie_secret[1], sizeof(syncookie_secret[1]));
2261
        tmp[0]=saddr;
2262
        tmp[1]=daddr;
2263
        tmp[2]=(sport << 16) + dport;
2264
        tmp[3] = count; /* minute counter */
2265
        HASH_TRANSFORM(tmp+16, tmp);
2266
 
2267
        /* Add in the second hash and the data */
2268
        return seq + ((tmp[17] + data) & COOKIEMASK);
2269
}
2270
 
2271
/*
2272
 * This retrieves the small "data" value from the syncookie.
2273
 * If the syncookie is bad, the data returned will be out of
2274
 * range.  This must be checked by the caller.
2275
 *
2276
 * The count value used to generate the cookie must be within
2277
 * "maxdiff" if the current (passed-in) "count".  The return value
2278
 * is (__u32)-1 if this test fails.
2279
 */
2280
__u32 check_tcp_syn_cookie(__u32 cookie, __u32 saddr, __u32 daddr, __u16 sport,
2281
                __u16 dport, __u32 sseq, __u32 count, __u32 maxdiff)
2282
{
2283
        __u32   tmp[16 + HASH_BUFFER_SIZE + HASH_EXTRA_SIZE];
2284
        __u32   diff;
2285
 
2286
        if (syncookie_init == 0)
2287
                return (__u32)-1;       /* Well, duh! */
2288
 
2289
        /* Strip away the layers from the cookie */
2290
        memcpy(tmp+3, syncookie_secret[0], sizeof(syncookie_secret[0]));
2291
        tmp[0]=saddr;
2292
        tmp[1]=daddr;
2293
        tmp[2]=(sport << 16) + dport;
2294
        HASH_TRANSFORM(tmp+16, tmp);
2295
        cookie -= tmp[17] + sseq;
2296
        /* Cookie is now reduced to (count * 2^24) ^ (hash % 2^24) */
2297
 
2298
        diff = (count - (cookie >> COOKIEBITS)) & ((__u32)-1 >> COOKIEBITS);
2299
        if (diff >= maxdiff)
2300
                return (__u32)-1;
2301
 
2302
        memcpy(tmp+3, syncookie_secret[1], sizeof(syncookie_secret[1]));
2303
        tmp[0] = saddr;
2304
        tmp[1] = daddr;
2305
        tmp[2] = (sport << 16) + dport;
2306
        tmp[3] = count - diff;  /* minute counter */
2307
        HASH_TRANSFORM(tmp+16, tmp);
2308
 
2309
        return (cookie - tmp[17]) & COOKIEMASK; /* Leaving the data behind */
2310
}
2311
#endif
2312
 
2313
 
2314
 
2315
#ifndef CONFIG_ARCH_S390
2316
EXPORT_SYMBOL(add_keyboard_randomness);
2317
EXPORT_SYMBOL(add_mouse_randomness);
2318
EXPORT_SYMBOL(add_interrupt_randomness);
2319
#endif
2320
EXPORT_SYMBOL(add_blkdev_randomness);
2321
EXPORT_SYMBOL(batch_entropy_store);
2322
EXPORT_SYMBOL(generate_random_uuid);
2323
 

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.