/*1* random.c -- A strong random number generator2*3* Copyright Matt Mackall <[email protected]>, 2003, 2004, 20054*5* Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999. All6* rights reserved.7*8* Redistribution and use in source and binary forms, with or without9* modification, are permitted provided that the following conditions10* are met:11* 1. Redistributions of source code must retain the above copyright12* notice, and the entire permission notice in its entirety,13* including the disclaimer of warranties.14* 2. Redistributions in binary form must reproduce the above copyright15* notice, this list of conditions and the following disclaimer in the16* documentation and/or other materials provided with the distribution.17* 3. The name of the author may not be used to endorse or promote18* products derived from this software without specific prior19* written permission.20*21* ALTERNATIVELY, this product may be distributed under the terms of22* the GNU General Public License, in which case the provisions of the GPL are23* required INSTEAD OF the above restrictions. (This clause is24* necessary due to a potential bad interaction between the GPL and25* the restrictions contained in a BSD-style copyright.)26*27* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED28* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES29* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF30* WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE31* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR32* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT33* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR34* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF35* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT36* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE37* USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH38* DAMAGE.39*/4041/*42* (now, with legal B.S. out of the way.....)43*44* This routine gathers environmental noise from device drivers, etc.,45* and returns good random numbers, suitable for cryptographic use.46* Besides the obvious cryptographic uses, these numbers are also good47* for seeding TCP sequence numbers, and other places where it is48* desirable to have numbers which are not only random, but hard to49* predict by an attacker.50*51* Theory of operation52* ===================53*54* Computers are very predictable devices. Hence it is extremely hard55* to produce truly random numbers on a computer --- as opposed to56* pseudo-random numbers, which can easily generated by using a57* algorithm. Unfortunately, it is very easy for attackers to guess58* the sequence of pseudo-random number generators, and for some59* applications this is not acceptable. So instead, we must try to60* gather "environmental noise" from the computer's environment, which61* must be hard for outside attackers to observe, and use that to62* generate random numbers. In a Unix environment, this is best done63* from inside the kernel.64*65* Sources of randomness from the environment include inter-keyboard66* timings, inter-interrupt timings from some interrupts, and other67* events which are both (a) non-deterministic and (b) hard for an68* outside observer to measure. Randomness from these sources are69* added to an "entropy pool", which is mixed using a CRC-like function.70* This is not cryptographically strong, but it is adequate assuming71* the randomness is not chosen maliciously, and it is fast enough that72* the overhead of doing it on every interrupt is very reasonable.73* As random bytes are mixed into the entropy pool, the routines keep74* an *estimate* of how many bits of randomness have been stored into75* the random number generator's internal state.76*77* When random bytes are desired, they are obtained by taking the SHA78* hash of the contents of the "entropy pool". The SHA hash avoids79* exposing the internal state of the entropy pool. It is believed to80* be computationally infeasible to derive any useful information81* about the input of SHA from its output. Even if it is possible to82* analyze SHA in some clever way, as long as the amount of data83* returned from the generator is less than the inherent entropy in84* the pool, the output data is totally unpredictable. For this85* reason, the routine decreases its internal estimate of how many86* bits of "true randomness" are contained in the entropy pool as it87* outputs random numbers.88*89* If this estimate goes to zero, the routine can still generate90* random numbers; however, an attacker may (at least in theory) be91* able to infer the future output of the generator from prior92* outputs. This requires successful cryptanalysis of SHA, which is93* not believed to be feasible, but there is a remote possibility.94* Nonetheless, these numbers should be useful for the vast majority95* of purposes.96*97* Exported interfaces ---- output98* ===============================99*100* There are three exported interfaces; the first is one designed to101* be used from within the kernel:102*103* void get_random_bytes(void *buf, int nbytes);104*105* This interface will return the requested number of random bytes,106* and place it in the requested buffer.107*108* The two other interfaces are two character devices /dev/random and109* /dev/urandom. /dev/random is suitable for use when very high110* quality randomness is desired (for example, for key generation or111* one-time pads), as it will only return a maximum of the number of112* bits of randomness (as estimated by the random number generator)113* contained in the entropy pool.114*115* The /dev/urandom device does not have this limit, and will return116* as many bytes as are requested. As more and more random bytes are117* requested without giving time for the entropy pool to recharge,118* this will result in random numbers that are merely cryptographically119* strong. For many applications, however, this is acceptable.120*121* Exported interfaces ---- input122* ==============================123*124* The current exported interfaces for gathering environmental noise125* from the devices are:126*127* void add_input_randomness(unsigned int type, unsigned int code,128* unsigned int value);129* void add_interrupt_randomness(int irq);130* void add_disk_randomness(struct gendisk *disk);131*132* add_input_randomness() uses the input layer interrupt timing, as well as133* the event type information from the hardware.134*135* add_interrupt_randomness() uses the inter-interrupt timing as random136* inputs to the entropy pool. Note that not all interrupts are good137* sources of randomness! For example, the timer interrupts is not a138* good choice, because the periodicity of the interrupts is too139* regular, and hence predictable to an attacker. Network Interface140* Controller interrupts are a better measure, since the timing of the141* NIC interrupts are more unpredictable.142*143* add_disk_randomness() uses what amounts to the seek time of block144* layer request events, on a per-disk_devt basis, as input to the145* entropy pool. Note that high-speed solid state drives with very low146* seek times do not make for good sources of entropy, as their seek147* times are usually fairly consistent.148*149* All of these routines try to estimate how many bits of randomness a150* particular randomness source. They do this by keeping track of the151* first and second order deltas of the event timings.152*153* Ensuring unpredictability at system startup154* ============================================155*156* When any operating system starts up, it will go through a sequence157* of actions that are fairly predictable by an adversary, especially158* if the start-up does not involve interaction with a human operator.159* This reduces the actual number of bits of unpredictability in the160* entropy pool below the value in entropy_count. In order to161* counteract this effect, it helps to carry information in the162* entropy pool across shut-downs and start-ups. To do this, put the163* following lines an appropriate script which is run during the boot164* sequence:165*166* echo "Initializing random number generator..."167* random_seed=/var/run/random-seed168* # Carry a random seed from start-up to start-up169* # Load and then save the whole entropy pool170* if [ -f $random_seed ]; then171* cat $random_seed >/dev/urandom172* else173* touch $random_seed174* fi175* chmod 600 $random_seed176* dd if=/dev/urandom of=$random_seed count=1 bs=512177*178* and the following lines in an appropriate script which is run as179* the system is shutdown:180*181* # Carry a random seed from shut-down to start-up182* # Save the whole entropy pool183* echo "Saving random seed..."184* random_seed=/var/run/random-seed185* touch $random_seed186* chmod 600 $random_seed187* dd if=/dev/urandom of=$random_seed count=1 bs=512188*189* For example, on most modern systems using the System V init190* scripts, such code fragments would be found in191* /etc/rc.d/init.d/random. On older Linux systems, the correct script192* location might be in /etc/rcb.d/rc.local or /etc/rc.d/rc.0.193*194* Effectively, these commands cause the contents of the entropy pool195* to be saved at shut-down time and reloaded into the entropy pool at196* start-up. (The 'dd' in the addition to the bootup script is to197* make sure that /etc/random-seed is different for every start-up,198* even if the system crashes without executing rc.0.) Even with199* complete knowledge of the start-up activities, predicting the state200* of the entropy pool requires knowledge of the previous history of201* the system.202*203* Configuring the /dev/random driver under Linux204* ==============================================205*206* The /dev/random driver under Linux uses minor numbers 8 and 9 of207* the /dev/mem major number (#1). So if your system does not have208* /dev/random and /dev/urandom created already, they can be created209* by using the commands:210*211* mknod /dev/random c 1 8212* mknod /dev/urandom c 1 9213*214* Acknowledgements:215* =================216*217* Ideas for constructing this random number generator were derived218* from Pretty Good Privacy's random number generator, and from private219* discussions with Phil Karn. Colin Plumb provided a faster random220* number generator, which speed up the mixing function of the entropy221* pool, taken from PGPfone. Dale Worley has also contributed many222* useful ideas and suggestions to improve this driver.223*224* Any flaws in the design are solely my responsibility, and should225* not be attributed to the Phil, Colin, or any of authors of PGP.226*227* Further background information on this topic may be obtained from228* RFC 1750, "Randomness Recommendations for Security", by Donald229* Eastlake, Steve Crocker, and Jeff Schiller.230*/231232#include <linux/utsname.h>233#include <linux/module.h>234#include <linux/kernel.h>235#include <linux/major.h>236#include <linux/string.h>237#include <linux/fcntl.h>238#include <linux/slab.h>239#include <linux/random.h>240#include <linux/poll.h>241#include <linux/init.h>242#include <linux/fs.h>243#include <linux/genhd.h>244#include <linux/interrupt.h>245#include <linux/mm.h>246#include <linux/spinlock.h>247#include <linux/percpu.h>248#include <linux/cryptohash.h>249#include <linux/fips.h>250251#ifdef CONFIG_GENERIC_HARDIRQS252# include <linux/irq.h>253#endif254255#include <asm/processor.h>256#include <asm/uaccess.h>257#include <asm/irq.h>258#include <asm/io.h>259260/*261* Configuration information262*/263#define INPUT_POOL_WORDS 128264#define OUTPUT_POOL_WORDS 32265#define SEC_XFER_SIZE 512266#define EXTRACT_SIZE 10267268/*269* The minimum number of bits of entropy before we wake up a read on270* /dev/random. Should be enough to do a significant reseed.271*/272static int random_read_wakeup_thresh = 64;273274/*275* If the entropy count falls under this number of bits, then we276* should wake up processes which are selecting or polling on write277* access to /dev/random.278*/279static int random_write_wakeup_thresh = 128;280281/*282* When the input pool goes over trickle_thresh, start dropping most283* samples to avoid wasting CPU time and reduce lock contention.284*/285286static int trickle_thresh __read_mostly = INPUT_POOL_WORDS * 28;287288static DEFINE_PER_CPU(int, trickle_count);289290/*291* A pool of size .poolwords is stirred with a primitive polynomial292* of degree .poolwords over GF(2). The taps for various sizes are293* defined below. They are chosen to be evenly spaced (minimum RMS294* distance from evenly spaced; the numbers in the comments are a295* scaled squared error sum) except for the last tap, which is 1 to296* get the twisting happening as fast as possible.297*/298static struct poolinfo {299int poolwords;300int tap1, tap2, tap3, tap4, tap5;301} poolinfo_table[] = {302/* x^128 + x^103 + x^76 + x^51 +x^25 + x + 1 -- 105 */303{ 128, 103, 76, 51, 25, 1 },304/* x^32 + x^26 + x^20 + x^14 + x^7 + x + 1 -- 15 */305{ 32, 26, 20, 14, 7, 1 },306#if 0307/* x^2048 + x^1638 + x^1231 + x^819 + x^411 + x + 1 -- 115 */308{ 2048, 1638, 1231, 819, 411, 1 },309310/* x^1024 + x^817 + x^615 + x^412 + x^204 + x + 1 -- 290 */311{ 1024, 817, 615, 412, 204, 1 },312313/* x^1024 + x^819 + x^616 + x^410 + x^207 + x^2 + 1 -- 115 */314{ 1024, 819, 616, 410, 207, 2 },315316/* x^512 + x^411 + x^308 + x^208 + x^104 + x + 1 -- 225 */317{ 512, 411, 308, 208, 104, 1 },318319/* x^512 + x^409 + x^307 + x^206 + x^102 + x^2 + 1 -- 95 */320{ 512, 409, 307, 206, 102, 2 },321/* x^512 + x^409 + x^309 + x^205 + x^103 + x^2 + 1 -- 95 */322{ 512, 409, 309, 205, 103, 2 },323324/* x^256 + x^205 + x^155 + x^101 + x^52 + x + 1 -- 125 */325{ 256, 205, 155, 101, 52, 1 },326327/* x^128 + x^103 + x^78 + x^51 + x^27 + x^2 + 1 -- 70 */328{ 128, 103, 78, 51, 27, 2 },329330/* x^64 + x^52 + x^39 + x^26 + x^14 + x + 1 -- 15 */331{ 64, 52, 39, 26, 14, 1 },332#endif333};334335#define POOLBITS poolwords*32336#define POOLBYTES poolwords*4337338/*339* For the purposes of better mixing, we use the CRC-32 polynomial as340* well to make a twisted Generalized Feedback Shift Reigster341*342* (See M. Matsumoto & Y. Kurita, 1992. Twisted GFSR generators. ACM343* Transactions on Modeling and Computer Simulation 2(3):179-194.344* Also see M. Matsumoto & Y. Kurita, 1994. Twisted GFSR generators345* II. ACM Transactions on Mdeling and Computer Simulation 4:254-266)346*347* Thanks to Colin Plumb for suggesting this.348*349* We have not analyzed the resultant polynomial to prove it primitive;350* in fact it almost certainly isn't. Nonetheless, the irreducible factors351* of a random large-degree polynomial over GF(2) are more than large enough352* that periodicity is not a concern.353*354* The input hash is much less sensitive than the output hash. All355* that we want of it is that it be a good non-cryptographic hash;356* i.e. it not produce collisions when fed "random" data of the sort357* we expect to see. As long as the pool state differs for different358* inputs, we have preserved the input entropy and done a good job.359* The fact that an intelligent attacker can construct inputs that360* will produce controlled alterations to the pool's state is not361* important because we don't consider such inputs to contribute any362* randomness. The only property we need with respect to them is that363* the attacker can't increase his/her knowledge of the pool's state.364* Since all additions are reversible (knowing the final state and the365* input, you can reconstruct the initial state), if an attacker has366* any uncertainty about the initial state, he/she can only shuffle367* that uncertainty about, but never cause any collisions (which would368* decrease the uncertainty).369*370* The chosen system lets the state of the pool be (essentially) the input371* modulo the generator polymnomial. Now, for random primitive polynomials,372* this is a universal class of hash functions, meaning that the chance373* of a collision is limited by the attacker's knowledge of the generator374* polynomail, so if it is chosen at random, an attacker can never force375* a collision. Here, we use a fixed polynomial, but we *can* assume that376* ###--> it is unknown to the processes generating the input entropy. <-###377* Because of this important property, this is a good, collision-resistant378* hash; hash collisions will occur no more often than chance.379*/380381/*382* Static global variables383*/384static DECLARE_WAIT_QUEUE_HEAD(random_read_wait);385static DECLARE_WAIT_QUEUE_HEAD(random_write_wait);386static struct fasync_struct *fasync;387388#if 0389static int debug;390module_param(debug, bool, 0644);391#define DEBUG_ENT(fmt, arg...) do { \392if (debug) \393printk(KERN_DEBUG "random %04d %04d %04d: " \394fmt,\395input_pool.entropy_count,\396blocking_pool.entropy_count,\397nonblocking_pool.entropy_count,\398## arg); } while (0)399#else400#define DEBUG_ENT(fmt, arg...) do {} while (0)401#endif402403/**********************************************************************404*405* OS independent entropy store. Here are the functions which handle406* storing entropy in an entropy pool.407*408**********************************************************************/409410struct entropy_store;411struct entropy_store {412/* read-only data: */413struct poolinfo *poolinfo;414__u32 *pool;415const char *name;416struct entropy_store *pull;417int limit;418419/* read-write data: */420spinlock_t lock;421unsigned add_ptr;422int entropy_count;423int input_rotate;424__u8 last_data[EXTRACT_SIZE];425};426427static __u32 input_pool_data[INPUT_POOL_WORDS];428static __u32 blocking_pool_data[OUTPUT_POOL_WORDS];429static __u32 nonblocking_pool_data[OUTPUT_POOL_WORDS];430431static struct entropy_store input_pool = {432.poolinfo = &poolinfo_table[0],433.name = "input",434.limit = 1,435.lock = __SPIN_LOCK_UNLOCKED(&input_pool.lock),436.pool = input_pool_data437};438439static struct entropy_store blocking_pool = {440.poolinfo = &poolinfo_table[1],441.name = "blocking",442.limit = 1,443.pull = &input_pool,444.lock = __SPIN_LOCK_UNLOCKED(&blocking_pool.lock),445.pool = blocking_pool_data446};447448static struct entropy_store nonblocking_pool = {449.poolinfo = &poolinfo_table[1],450.name = "nonblocking",451.pull = &input_pool,452.lock = __SPIN_LOCK_UNLOCKED(&nonblocking_pool.lock),453.pool = nonblocking_pool_data454};455456/*457* This function adds bytes into the entropy "pool". It does not458* update the entropy estimate. The caller should call459* credit_entropy_bits if this is appropriate.460*461* The pool is stirred with a primitive polynomial of the appropriate462* degree, and then twisted. We twist by three bits at a time because463* it's cheap to do so and helps slightly in the expected case where464* the entropy is concentrated in the low-order bits.465*/466static void mix_pool_bytes_extract(struct entropy_store *r, const void *in,467int nbytes, __u8 out[64])468{469static __u32 const twist_table[8] = {4700x00000000, 0x3b6e20c8, 0x76dc4190, 0x4db26158,4710xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278 };472unsigned long i, j, tap1, tap2, tap3, tap4, tap5;473int input_rotate;474int wordmask = r->poolinfo->poolwords - 1;475const char *bytes = in;476__u32 w;477unsigned long flags;478479/* Taps are constant, so we can load them without holding r->lock. */480tap1 = r->poolinfo->tap1;481tap2 = r->poolinfo->tap2;482tap3 = r->poolinfo->tap3;483tap4 = r->poolinfo->tap4;484tap5 = r->poolinfo->tap5;485486spin_lock_irqsave(&r->lock, flags);487input_rotate = r->input_rotate;488i = r->add_ptr;489490/* mix one byte at a time to simplify size handling and churn faster */491while (nbytes--) {492w = rol32(*bytes++, input_rotate & 31);493i = (i - 1) & wordmask;494495/* XOR in the various taps */496w ^= r->pool[i];497w ^= r->pool[(i + tap1) & wordmask];498w ^= r->pool[(i + tap2) & wordmask];499w ^= r->pool[(i + tap3) & wordmask];500w ^= r->pool[(i + tap4) & wordmask];501w ^= r->pool[(i + tap5) & wordmask];502503/* Mix the result back in with a twist */504r->pool[i] = (w >> 3) ^ twist_table[w & 7];505506/*507* Normally, we add 7 bits of rotation to the pool.508* At the beginning of the pool, add an extra 7 bits509* rotation, so that successive passes spread the510* input bits across the pool evenly.511*/512input_rotate += i ? 7 : 14;513}514515r->input_rotate = input_rotate;516r->add_ptr = i;517518if (out)519for (j = 0; j < 16; j++)520((__u32 *)out)[j] = r->pool[(i - j) & wordmask];521522spin_unlock_irqrestore(&r->lock, flags);523}524525static void mix_pool_bytes(struct entropy_store *r, const void *in, int bytes)526{527mix_pool_bytes_extract(r, in, bytes, NULL);528}529530/*531* Credit (or debit) the entropy store with n bits of entropy532*/533static void credit_entropy_bits(struct entropy_store *r, int nbits)534{535unsigned long flags;536int entropy_count;537538if (!nbits)539return;540541spin_lock_irqsave(&r->lock, flags);542543DEBUG_ENT("added %d entropy credits to %s\n", nbits, r->name);544entropy_count = r->entropy_count;545entropy_count += nbits;546if (entropy_count < 0) {547DEBUG_ENT("negative entropy/overflow\n");548entropy_count = 0;549} else if (entropy_count > r->poolinfo->POOLBITS)550entropy_count = r->poolinfo->POOLBITS;551r->entropy_count = entropy_count;552553/* should we wake readers? */554if (r == &input_pool && entropy_count >= random_read_wakeup_thresh) {555wake_up_interruptible(&random_read_wait);556kill_fasync(&fasync, SIGIO, POLL_IN);557}558spin_unlock_irqrestore(&r->lock, flags);559}560561/*********************************************************************562*563* Entropy input management564*565*********************************************************************/566567/* There is one of these per entropy source */568struct timer_rand_state {569cycles_t last_time;570long last_delta, last_delta2;571unsigned dont_count_entropy:1;572};573574#ifndef CONFIG_GENERIC_HARDIRQS575576static struct timer_rand_state *irq_timer_state[NR_IRQS];577578static struct timer_rand_state *get_timer_rand_state(unsigned int irq)579{580return irq_timer_state[irq];581}582583static void set_timer_rand_state(unsigned int irq,584struct timer_rand_state *state)585{586irq_timer_state[irq] = state;587}588589#else590591static struct timer_rand_state *get_timer_rand_state(unsigned int irq)592{593struct irq_desc *desc;594595desc = irq_to_desc(irq);596597return desc->timer_rand_state;598}599600static void set_timer_rand_state(unsigned int irq,601struct timer_rand_state *state)602{603struct irq_desc *desc;604605desc = irq_to_desc(irq);606607desc->timer_rand_state = state;608}609#endif610611static struct timer_rand_state input_timer_state;612613/*614* This function adds entropy to the entropy "pool" by using timing615* delays. It uses the timer_rand_state structure to make an estimate616* of how many bits of entropy this call has added to the pool.617*618* The number "num" is also added to the pool - it should somehow describe619* the type of event which just happened. This is currently 0-255 for620* keyboard scan codes, and 256 upwards for interrupts.621*622*/623static void add_timer_randomness(struct timer_rand_state *state, unsigned num)624{625struct {626cycles_t cycles;627long jiffies;628unsigned num;629} sample;630long delta, delta2, delta3;631632preempt_disable();633/* if over the trickle threshold, use only 1 in 4096 samples */634if (input_pool.entropy_count > trickle_thresh &&635((__this_cpu_inc_return(trickle_count) - 1) & 0xfff))636goto out;637638sample.jiffies = jiffies;639sample.cycles = get_cycles();640sample.num = num;641mix_pool_bytes(&input_pool, &sample, sizeof(sample));642643/*644* Calculate number of bits of randomness we probably added.645* We take into account the first, second and third-order deltas646* in order to make our estimate.647*/648649if (!state->dont_count_entropy) {650delta = sample.jiffies - state->last_time;651state->last_time = sample.jiffies;652653delta2 = delta - state->last_delta;654state->last_delta = delta;655656delta3 = delta2 - state->last_delta2;657state->last_delta2 = delta2;658659if (delta < 0)660delta = -delta;661if (delta2 < 0)662delta2 = -delta2;663if (delta3 < 0)664delta3 = -delta3;665if (delta > delta2)666delta = delta2;667if (delta > delta3)668delta = delta3;669670/*671* delta is now minimum absolute delta.672* Round down by 1 bit on general principles,673* and limit entropy entimate to 12 bits.674*/675credit_entropy_bits(&input_pool,676min_t(int, fls(delta>>1), 11));677}678out:679preempt_enable();680}681682void add_input_randomness(unsigned int type, unsigned int code,683unsigned int value)684{685static unsigned char last_value;686687/* ignore autorepeat and the like */688if (value == last_value)689return;690691DEBUG_ENT("input event\n");692last_value = value;693add_timer_randomness(&input_timer_state,694(type << 4) ^ code ^ (code >> 4) ^ value);695}696EXPORT_SYMBOL_GPL(add_input_randomness);697698void add_interrupt_randomness(int irq)699{700struct timer_rand_state *state;701702state = get_timer_rand_state(irq);703704if (state == NULL)705return;706707DEBUG_ENT("irq event %d\n", irq);708add_timer_randomness(state, 0x100 + irq);709}710711#ifdef CONFIG_BLOCK712void add_disk_randomness(struct gendisk *disk)713{714if (!disk || !disk->random)715return;716/* first major is 1, so we get >= 0x200 here */717DEBUG_ENT("disk event %d:%d\n",718MAJOR(disk_devt(disk)), MINOR(disk_devt(disk)));719720add_timer_randomness(disk->random, 0x100 + disk_devt(disk));721}722#endif723724/*********************************************************************725*726* Entropy extraction routines727*728*********************************************************************/729730static ssize_t extract_entropy(struct entropy_store *r, void *buf,731size_t nbytes, int min, int rsvd);732733/*734* This utility inline function is responsible for transferring entropy735* from the primary pool to the secondary extraction pool. We make736* sure we pull enough for a 'catastrophic reseed'.737*/738static void xfer_secondary_pool(struct entropy_store *r, size_t nbytes)739{740__u32 tmp[OUTPUT_POOL_WORDS];741742if (r->pull && r->entropy_count < nbytes * 8 &&743r->entropy_count < r->poolinfo->POOLBITS) {744/* If we're limited, always leave two wakeup worth's BITS */745int rsvd = r->limit ? 0 : random_read_wakeup_thresh/4;746int bytes = nbytes;747748/* pull at least as many as BYTES as wakeup BITS */749bytes = max_t(int, bytes, random_read_wakeup_thresh / 8);750/* but never more than the buffer size */751bytes = min_t(int, bytes, sizeof(tmp));752753DEBUG_ENT("going to reseed %s with %d bits "754"(%d of %d requested)\n",755r->name, bytes * 8, nbytes * 8, r->entropy_count);756757bytes = extract_entropy(r->pull, tmp, bytes,758random_read_wakeup_thresh / 8, rsvd);759mix_pool_bytes(r, tmp, bytes);760credit_entropy_bits(r, bytes*8);761}762}763764/*765* These functions extracts randomness from the "entropy pool", and766* returns it in a buffer.767*768* The min parameter specifies the minimum amount we can pull before769* failing to avoid races that defeat catastrophic reseeding while the770* reserved parameter indicates how much entropy we must leave in the771* pool after each pull to avoid starving other readers.772*773* Note: extract_entropy() assumes that .poolwords is a multiple of 16 words.774*/775776static size_t account(struct entropy_store *r, size_t nbytes, int min,777int reserved)778{779unsigned long flags;780781/* Hold lock while accounting */782spin_lock_irqsave(&r->lock, flags);783784BUG_ON(r->entropy_count > r->poolinfo->POOLBITS);785DEBUG_ENT("trying to extract %d bits from %s\n",786nbytes * 8, r->name);787788/* Can we pull enough? */789if (r->entropy_count / 8 < min + reserved) {790nbytes = 0;791} else {792/* If limited, never pull more than available */793if (r->limit && nbytes + reserved >= r->entropy_count / 8)794nbytes = r->entropy_count/8 - reserved;795796if (r->entropy_count / 8 >= nbytes + reserved)797r->entropy_count -= nbytes*8;798else799r->entropy_count = reserved;800801if (r->entropy_count < random_write_wakeup_thresh) {802wake_up_interruptible(&random_write_wait);803kill_fasync(&fasync, SIGIO, POLL_OUT);804}805}806807DEBUG_ENT("debiting %d entropy credits from %s%s\n",808nbytes * 8, r->name, r->limit ? "" : " (unlimited)");809810spin_unlock_irqrestore(&r->lock, flags);811812return nbytes;813}814815static void extract_buf(struct entropy_store *r, __u8 *out)816{817int i;818__u32 hash[5], workspace[SHA_WORKSPACE_WORDS];819__u8 extract[64];820821/* Generate a hash across the pool, 16 words (512 bits) at a time */822sha_init(hash);823for (i = 0; i < r->poolinfo->poolwords; i += 16)824sha_transform(hash, (__u8 *)(r->pool + i), workspace);825826/*827* We mix the hash back into the pool to prevent backtracking828* attacks (where the attacker knows the state of the pool829* plus the current outputs, and attempts to find previous830* ouputs), unless the hash function can be inverted. By831* mixing at least a SHA1 worth of hash data back, we make832* brute-forcing the feedback as hard as brute-forcing the833* hash.834*/835mix_pool_bytes_extract(r, hash, sizeof(hash), extract);836837/*838* To avoid duplicates, we atomically extract a portion of the839* pool while mixing, and hash one final time.840*/841sha_transform(hash, extract, workspace);842memset(extract, 0, sizeof(extract));843memset(workspace, 0, sizeof(workspace));844845/*846* In case the hash function has some recognizable output847* pattern, we fold it in half. Thus, we always feed back848* twice as much data as we output.849*/850hash[0] ^= hash[3];851hash[1] ^= hash[4];852hash[2] ^= rol32(hash[2], 16);853memcpy(out, hash, EXTRACT_SIZE);854memset(hash, 0, sizeof(hash));855}856857static ssize_t extract_entropy(struct entropy_store *r, void *buf,858size_t nbytes, int min, int reserved)859{860ssize_t ret = 0, i;861__u8 tmp[EXTRACT_SIZE];862unsigned long flags;863864xfer_secondary_pool(r, nbytes);865nbytes = account(r, nbytes, min, reserved);866867while (nbytes) {868extract_buf(r, tmp);869870if (fips_enabled) {871spin_lock_irqsave(&r->lock, flags);872if (!memcmp(tmp, r->last_data, EXTRACT_SIZE))873panic("Hardware RNG duplicated output!\n");874memcpy(r->last_data, tmp, EXTRACT_SIZE);875spin_unlock_irqrestore(&r->lock, flags);876}877i = min_t(int, nbytes, EXTRACT_SIZE);878memcpy(buf, tmp, i);879nbytes -= i;880buf += i;881ret += i;882}883884/* Wipe data just returned from memory */885memset(tmp, 0, sizeof(tmp));886887return ret;888}889890static ssize_t extract_entropy_user(struct entropy_store *r, void __user *buf,891size_t nbytes)892{893ssize_t ret = 0, i;894__u8 tmp[EXTRACT_SIZE];895896xfer_secondary_pool(r, nbytes);897nbytes = account(r, nbytes, 0, 0);898899while (nbytes) {900if (need_resched()) {901if (signal_pending(current)) {902if (ret == 0)903ret = -ERESTARTSYS;904break;905}906schedule();907}908909extract_buf(r, tmp);910i = min_t(int, nbytes, EXTRACT_SIZE);911if (copy_to_user(buf, tmp, i)) {912ret = -EFAULT;913break;914}915916nbytes -= i;917buf += i;918ret += i;919}920921/* Wipe data just returned from memory */922memset(tmp, 0, sizeof(tmp));923924return ret;925}926927/*928* This function is the exported kernel interface. It returns some929* number of good random numbers, suitable for seeding TCP sequence930* numbers, etc.931*/932void get_random_bytes(void *buf, int nbytes)933{934extract_entropy(&nonblocking_pool, buf, nbytes, 0, 0);935}936EXPORT_SYMBOL(get_random_bytes);937938/*939* init_std_data - initialize pool with system data940*941* @r: pool to initialize942*943* This function clears the pool's entropy count and mixes some system944* data into the pool to prepare it for use. The pool is not cleared945* as that can only decrease the entropy in the pool.946*/947static void init_std_data(struct entropy_store *r)948{949ktime_t now;950unsigned long flags;951952spin_lock_irqsave(&r->lock, flags);953r->entropy_count = 0;954spin_unlock_irqrestore(&r->lock, flags);955956now = ktime_get_real();957mix_pool_bytes(r, &now, sizeof(now));958mix_pool_bytes(r, utsname(), sizeof(*(utsname())));959}960961static int rand_initialize(void)962{963init_std_data(&input_pool);964init_std_data(&blocking_pool);965init_std_data(&nonblocking_pool);966return 0;967}968module_init(rand_initialize);969970void rand_initialize_irq(int irq)971{972struct timer_rand_state *state;973974state = get_timer_rand_state(irq);975976if (state)977return;978979/*980* If kzalloc returns null, we just won't use that entropy981* source.982*/983state = kzalloc(sizeof(struct timer_rand_state), GFP_KERNEL);984if (state)985set_timer_rand_state(irq, state);986}987988#ifdef CONFIG_BLOCK989void rand_initialize_disk(struct gendisk *disk)990{991struct timer_rand_state *state;992993/*994* If kzalloc returns null, we just won't use that entropy995* source.996*/997state = kzalloc(sizeof(struct timer_rand_state), GFP_KERNEL);998if (state)999disk->random = state;1000}1001#endif10021003static ssize_t1004random_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)1005{1006ssize_t n, retval = 0, count = 0;10071008if (nbytes == 0)1009return 0;10101011while (nbytes > 0) {1012n = nbytes;1013if (n > SEC_XFER_SIZE)1014n = SEC_XFER_SIZE;10151016DEBUG_ENT("reading %d bits\n", n*8);10171018n = extract_entropy_user(&blocking_pool, buf, n);10191020DEBUG_ENT("read got %d bits (%d still needed)\n",1021n*8, (nbytes-n)*8);10221023if (n == 0) {1024if (file->f_flags & O_NONBLOCK) {1025retval = -EAGAIN;1026break;1027}10281029DEBUG_ENT("sleeping?\n");10301031wait_event_interruptible(random_read_wait,1032input_pool.entropy_count >=1033random_read_wakeup_thresh);10341035DEBUG_ENT("awake\n");10361037if (signal_pending(current)) {1038retval = -ERESTARTSYS;1039break;1040}10411042continue;1043}10441045if (n < 0) {1046retval = n;1047break;1048}1049count += n;1050buf += n;1051nbytes -= n;1052break; /* This break makes the device work */1053/* like a named pipe */1054}10551056return (count ? count : retval);1057}10581059static ssize_t1060urandom_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)1061{1062return extract_entropy_user(&nonblocking_pool, buf, nbytes);1063}10641065static unsigned int1066random_poll(struct file *file, poll_table * wait)1067{1068unsigned int mask;10691070poll_wait(file, &random_read_wait, wait);1071poll_wait(file, &random_write_wait, wait);1072mask = 0;1073if (input_pool.entropy_count >= random_read_wakeup_thresh)1074mask |= POLLIN | POLLRDNORM;1075if (input_pool.entropy_count < random_write_wakeup_thresh)1076mask |= POLLOUT | POLLWRNORM;1077return mask;1078}10791080static int1081write_pool(struct entropy_store *r, const char __user *buffer, size_t count)1082{1083size_t bytes;1084__u32 buf[16];1085const char __user *p = buffer;10861087while (count > 0) {1088bytes = min(count, sizeof(buf));1089if (copy_from_user(&buf, p, bytes))1090return -EFAULT;10911092count -= bytes;1093p += bytes;10941095mix_pool_bytes(r, buf, bytes);1096cond_resched();1097}10981099return 0;1100}11011102static ssize_t random_write(struct file *file, const char __user *buffer,1103size_t count, loff_t *ppos)1104{1105size_t ret;11061107ret = write_pool(&blocking_pool, buffer, count);1108if (ret)1109return ret;1110ret = write_pool(&nonblocking_pool, buffer, count);1111if (ret)1112return ret;11131114return (ssize_t)count;1115}11161117static long random_ioctl(struct file *f, unsigned int cmd, unsigned long arg)1118{1119int size, ent_count;1120int __user *p = (int __user *)arg;1121int retval;11221123switch (cmd) {1124case RNDGETENTCNT:1125/* inherently racy, no point locking */1126if (put_user(input_pool.entropy_count, p))1127return -EFAULT;1128return 0;1129case RNDADDTOENTCNT:1130if (!capable(CAP_SYS_ADMIN))1131return -EPERM;1132if (get_user(ent_count, p))1133return -EFAULT;1134credit_entropy_bits(&input_pool, ent_count);1135return 0;1136case RNDADDENTROPY:1137if (!capable(CAP_SYS_ADMIN))1138return -EPERM;1139if (get_user(ent_count, p++))1140return -EFAULT;1141if (ent_count < 0)1142return -EINVAL;1143if (get_user(size, p++))1144return -EFAULT;1145retval = write_pool(&input_pool, (const char __user *)p,1146size);1147if (retval < 0)1148return retval;1149credit_entropy_bits(&input_pool, ent_count);1150return 0;1151case RNDZAPENTCNT:1152case RNDCLEARPOOL:1153/* Clear the entropy pool counters. */1154if (!capable(CAP_SYS_ADMIN))1155return -EPERM;1156rand_initialize();1157return 0;1158default:1159return -EINVAL;1160}1161}11621163static int random_fasync(int fd, struct file *filp, int on)1164{1165return fasync_helper(fd, filp, on, &fasync);1166}11671168const struct file_operations random_fops = {1169.read = random_read,1170.write = random_write,1171.poll = random_poll,1172.unlocked_ioctl = random_ioctl,1173.fasync = random_fasync,1174.llseek = noop_llseek,1175};11761177const struct file_operations urandom_fops = {1178.read = urandom_read,1179.write = random_write,1180.unlocked_ioctl = random_ioctl,1181.fasync = random_fasync,1182.llseek = noop_llseek,1183};11841185/***************************************************************1186* Random UUID interface1187*1188* Used here for a Boot ID, but can be useful for other kernel1189* drivers.1190***************************************************************/11911192/*1193* Generate random UUID1194*/1195void generate_random_uuid(unsigned char uuid_out[16])1196{1197get_random_bytes(uuid_out, 16);1198/* Set UUID version to 4 --- truly random generation */1199uuid_out[6] = (uuid_out[6] & 0x0F) | 0x40;1200/* Set the UUID variant to DCE */1201uuid_out[8] = (uuid_out[8] & 0x3F) | 0x80;1202}1203EXPORT_SYMBOL(generate_random_uuid);12041205/********************************************************************1206*1207* Sysctl interface1208*1209********************************************************************/12101211#ifdef CONFIG_SYSCTL12121213#include <linux/sysctl.h>12141215static int min_read_thresh = 8, min_write_thresh;1216static int max_read_thresh = INPUT_POOL_WORDS * 32;1217static int max_write_thresh = INPUT_POOL_WORDS * 32;1218static char sysctl_bootid[16];12191220/*1221* These functions is used to return both the bootid UUID, and random1222* UUID. The difference is in whether table->data is NULL; if it is,1223* then a new UUID is generated and returned to the user.1224*1225* If the user accesses this via the proc interface, it will be returned1226* as an ASCII string in the standard UUID format. If accesses via the1227* sysctl system call, it is returned as 16 bytes of binary data.1228*/1229static int proc_do_uuid(ctl_table *table, int write,1230void __user *buffer, size_t *lenp, loff_t *ppos)1231{1232ctl_table fake_table;1233unsigned char buf[64], tmp_uuid[16], *uuid;12341235uuid = table->data;1236if (!uuid) {1237uuid = tmp_uuid;1238uuid[8] = 0;1239}1240if (uuid[8] == 0)1241generate_random_uuid(uuid);12421243sprintf(buf, "%pU", uuid);12441245fake_table.data = buf;1246fake_table.maxlen = sizeof(buf);12471248return proc_dostring(&fake_table, write, buffer, lenp, ppos);1249}12501251static int sysctl_poolsize = INPUT_POOL_WORDS * 32;1252ctl_table random_table[] = {1253{1254.procname = "poolsize",1255.data = &sysctl_poolsize,1256.maxlen = sizeof(int),1257.mode = 0444,1258.proc_handler = proc_dointvec,1259},1260{1261.procname = "entropy_avail",1262.maxlen = sizeof(int),1263.mode = 0444,1264.proc_handler = proc_dointvec,1265.data = &input_pool.entropy_count,1266},1267{1268.procname = "read_wakeup_threshold",1269.data = &random_read_wakeup_thresh,1270.maxlen = sizeof(int),1271.mode = 0644,1272.proc_handler = proc_dointvec_minmax,1273.extra1 = &min_read_thresh,1274.extra2 = &max_read_thresh,1275},1276{1277.procname = "write_wakeup_threshold",1278.data = &random_write_wakeup_thresh,1279.maxlen = sizeof(int),1280.mode = 0644,1281.proc_handler = proc_dointvec_minmax,1282.extra1 = &min_write_thresh,1283.extra2 = &max_write_thresh,1284},1285{1286.procname = "boot_id",1287.data = &sysctl_bootid,1288.maxlen = 16,1289.mode = 0444,1290.proc_handler = proc_do_uuid,1291},1292{1293.procname = "uuid",1294.maxlen = 16,1295.mode = 0444,1296.proc_handler = proc_do_uuid,1297},1298{ }1299};1300#endif /* CONFIG_SYSCTL */13011302/********************************************************************1303*1304* Random functions for networking1305*1306********************************************************************/13071308/*1309* TCP initial sequence number picking. This uses the random number1310* generator to pick an initial secret value. This value is hashed1311* along with the TCP endpoint information to provide a unique1312* starting point for each pair of TCP endpoints. This defeats1313* attacks which rely on guessing the initial TCP sequence number.1314* This algorithm was suggested by Steve Bellovin.1315*1316* Using a very strong hash was taking an appreciable amount of the total1317* TCP connection establishment time, so this is a weaker hash,1318* compensated for by changing the secret periodically.1319*/13201321/* F, G and H are basic MD4 functions: selection, majority, parity */1322#define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))1323#define G(x, y, z) (((x) & (y)) + (((x) ^ (y)) & (z)))1324#define H(x, y, z) ((x) ^ (y) ^ (z))13251326/*1327* The generic round function. The application is so specific that1328* we don't bother protecting all the arguments with parens, as is generally1329* good macro practice, in favor of extra legibility.1330* Rotation is separate from addition to prevent recomputation1331*/1332#define ROUND(f, a, b, c, d, x, s) \1333(a += f(b, c, d) + x, a = (a << s) | (a >> (32 - s)))1334#define K1 01335#define K2 013240474631UL1336#define K3 015666365641UL13371338#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)13391340static __u32 twothirdsMD4Transform(__u32 const buf[4], __u32 const in[12])1341{1342__u32 a = buf[0], b = buf[1], c = buf[2], d = buf[3];13431344/* Round 1 */1345ROUND(F, a, b, c, d, in[ 0] + K1, 3);1346ROUND(F, d, a, b, c, in[ 1] + K1, 7);1347ROUND(F, c, d, a, b, in[ 2] + K1, 11);1348ROUND(F, b, c, d, a, in[ 3] + K1, 19);1349ROUND(F, a, b, c, d, in[ 4] + K1, 3);1350ROUND(F, d, a, b, c, in[ 5] + K1, 7);1351ROUND(F, c, d, a, b, in[ 6] + K1, 11);1352ROUND(F, b, c, d, a, in[ 7] + K1, 19);1353ROUND(F, a, b, c, d, in[ 8] + K1, 3);1354ROUND(F, d, a, b, c, in[ 9] + K1, 7);1355ROUND(F, c, d, a, b, in[10] + K1, 11);1356ROUND(F, b, c, d, a, in[11] + K1, 19);13571358/* Round 2 */1359ROUND(G, a, b, c, d, in[ 1] + K2, 3);1360ROUND(G, d, a, b, c, in[ 3] + K2, 5);1361ROUND(G, c, d, a, b, in[ 5] + K2, 9);1362ROUND(G, b, c, d, a, in[ 7] + K2, 13);1363ROUND(G, a, b, c, d, in[ 9] + K2, 3);1364ROUND(G, d, a, b, c, in[11] + K2, 5);1365ROUND(G, c, d, a, b, in[ 0] + K2, 9);1366ROUND(G, b, c, d, a, in[ 2] + K2, 13);1367ROUND(G, a, b, c, d, in[ 4] + K2, 3);1368ROUND(G, d, a, b, c, in[ 6] + K2, 5);1369ROUND(G, c, d, a, b, in[ 8] + K2, 9);1370ROUND(G, b, c, d, a, in[10] + K2, 13);13711372/* Round 3 */1373ROUND(H, a, b, c, d, in[ 3] + K3, 3);1374ROUND(H, d, a, b, c, in[ 7] + K3, 9);1375ROUND(H, c, d, a, b, in[11] + K3, 11);1376ROUND(H, b, c, d, a, in[ 2] + K3, 15);1377ROUND(H, a, b, c, d, in[ 6] + K3, 3);1378ROUND(H, d, a, b, c, in[10] + K3, 9);1379ROUND(H, c, d, a, b, in[ 1] + K3, 11);1380ROUND(H, b, c, d, a, in[ 5] + K3, 15);1381ROUND(H, a, b, c, d, in[ 9] + K3, 3);1382ROUND(H, d, a, b, c, in[ 0] + K3, 9);1383ROUND(H, c, d, a, b, in[ 4] + K3, 11);1384ROUND(H, b, c, d, a, in[ 8] + K3, 15);13851386return buf[1] + b; /* "most hashed" word */1387/* Alternative: return sum of all words? */1388}1389#endif13901391#undef ROUND1392#undef F1393#undef G1394#undef H1395#undef K11396#undef K21397#undef K313981399/* This should not be decreased so low that ISNs wrap too fast. */1400#define REKEY_INTERVAL (300 * HZ)1401/*1402* Bit layout of the tcp sequence numbers (before adding current time):1403* bit 24-31: increased after every key exchange1404* bit 0-23: hash(source,dest)1405*1406* The implementation is similar to the algorithm described1407* in the Appendix of RFC 1185, except that1408* - it uses a 1 MHz clock instead of a 250 kHz clock1409* - it performs a rekey every 5 minutes, which is equivalent1410* to a (source,dest) tulple dependent forward jump of the1411* clock by 0..2^(HASH_BITS+1)1412*1413* Thus the average ISN wraparound time is 68 minutes instead of1414* 4.55 hours.1415*1416* SMP cleanup and lock avoidance with poor man's RCU.1417* Manfred Spraul <[email protected]>1418*1419*/1420#define COUNT_BITS 81421#define COUNT_MASK ((1 << COUNT_BITS) - 1)1422#define HASH_BITS 241423#define HASH_MASK ((1 << HASH_BITS) - 1)14241425static struct keydata {1426__u32 count; /* already shifted to the final position */1427__u32 secret[12];1428} ____cacheline_aligned ip_keydata[2];14291430static unsigned int ip_cnt;14311432static void rekey_seq_generator(struct work_struct *work);14331434static DECLARE_DELAYED_WORK(rekey_work, rekey_seq_generator);14351436/*1437* Lock avoidance:1438* The ISN generation runs lockless - it's just a hash over random data.1439* State changes happen every 5 minutes when the random key is replaced.1440* Synchronization is performed by having two copies of the hash function1441* state and rekey_seq_generator always updates the inactive copy.1442* The copy is then activated by updating ip_cnt.1443* The implementation breaks down if someone blocks the thread1444* that processes SYN requests for more than 5 minutes. Should never1445* happen, and even if that happens only a not perfectly compliant1446* ISN is generated, nothing fatal.1447*/1448static void rekey_seq_generator(struct work_struct *work)1449{1450struct keydata *keyptr = &ip_keydata[1 ^ (ip_cnt & 1)];14511452get_random_bytes(keyptr->secret, sizeof(keyptr->secret));1453keyptr->count = (ip_cnt & COUNT_MASK) << HASH_BITS;1454smp_wmb();1455ip_cnt++;1456schedule_delayed_work(&rekey_work,1457round_jiffies_relative(REKEY_INTERVAL));1458}14591460static inline struct keydata *get_keyptr(void)1461{1462struct keydata *keyptr = &ip_keydata[ip_cnt & 1];14631464smp_rmb();14651466return keyptr;1467}14681469static __init int seqgen_init(void)1470{1471rekey_seq_generator(NULL);1472return 0;1473}1474late_initcall(seqgen_init);14751476#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)1477__u32 secure_tcpv6_sequence_number(__be32 *saddr, __be32 *daddr,1478__be16 sport, __be16 dport)1479{1480__u32 seq;1481__u32 hash[12];1482struct keydata *keyptr = get_keyptr();14831484/* The procedure is the same as for IPv4, but addresses are longer.1485* Thus we must use twothirdsMD4Transform.1486*/14871488memcpy(hash, saddr, 16);1489hash[4] = ((__force u16)sport << 16) + (__force u16)dport;1490memcpy(&hash[5], keyptr->secret, sizeof(__u32) * 7);14911492seq = twothirdsMD4Transform((const __u32 *)daddr, hash) & HASH_MASK;1493seq += keyptr->count;14941495seq += ktime_to_ns(ktime_get_real());14961497return seq;1498}1499EXPORT_SYMBOL(secure_tcpv6_sequence_number);1500#endif15011502/* The code below is shamelessly stolen from secure_tcp_sequence_number().1503* All blames to Andrey V. Savochkin <[email protected]>.1504*/1505__u32 secure_ip_id(__be32 daddr)1506{1507struct keydata *keyptr;1508__u32 hash[4];15091510keyptr = get_keyptr();15111512/*1513* Pick a unique starting offset for each IP destination.1514* The dest ip address is placed in the starting vector,1515* which is then hashed with random data.1516*/1517hash[0] = (__force __u32)daddr;1518hash[1] = keyptr->secret[9];1519hash[2] = keyptr->secret[10];1520hash[3] = keyptr->secret[11];15211522return half_md4_transform(hash, keyptr->secret);1523}15241525#ifdef CONFIG_INET15261527__u32 secure_tcp_sequence_number(__be32 saddr, __be32 daddr,1528__be16 sport, __be16 dport)1529{1530__u32 seq;1531__u32 hash[4];1532struct keydata *keyptr = get_keyptr();15331534/*1535* Pick a unique starting offset for each TCP connection endpoints1536* (saddr, daddr, sport, dport).1537* Note that the words are placed into the starting vector, which is1538* then mixed with a partial MD4 over random data.1539*/1540hash[0] = (__force u32)saddr;1541hash[1] = (__force u32)daddr;1542hash[2] = ((__force u16)sport << 16) + (__force u16)dport;1543hash[3] = keyptr->secret[11];15441545seq = half_md4_transform(hash, keyptr->secret) & HASH_MASK;1546seq += keyptr->count;1547/*1548* As close as possible to RFC 793, which1549* suggests using a 250 kHz clock.1550* Further reading shows this assumes 2 Mb/s networks.1551* For 10 Mb/s Ethernet, a 1 MHz clock is appropriate.1552* For 10 Gb/s Ethernet, a 1 GHz clock should be ok, but1553* we also need to limit the resolution so that the u32 seq1554* overlaps less than one time per MSL (2 minutes).1555* Choosing a clock of 64 ns period is OK. (period of 274 s)1556*/1557seq += ktime_to_ns(ktime_get_real()) >> 6;15581559return seq;1560}15611562/* Generate secure starting point for ephemeral IPV4 transport port search */1563u32 secure_ipv4_port_ephemeral(__be32 saddr, __be32 daddr, __be16 dport)1564{1565struct keydata *keyptr = get_keyptr();1566u32 hash[4];15671568/*1569* Pick a unique starting offset for each ephemeral port search1570* (saddr, daddr, dport) and 48bits of random data.1571*/1572hash[0] = (__force u32)saddr;1573hash[1] = (__force u32)daddr;1574hash[2] = (__force u32)dport ^ keyptr->secret[10];1575hash[3] = keyptr->secret[11];15761577return half_md4_transform(hash, keyptr->secret);1578}1579EXPORT_SYMBOL_GPL(secure_ipv4_port_ephemeral);15801581#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)1582u32 secure_ipv6_port_ephemeral(const __be32 *saddr, const __be32 *daddr,1583__be16 dport)1584{1585struct keydata *keyptr = get_keyptr();1586u32 hash[12];15871588memcpy(hash, saddr, 16);1589hash[4] = (__force u32)dport;1590memcpy(&hash[5], keyptr->secret, sizeof(__u32) * 7);15911592return twothirdsMD4Transform((const __u32 *)daddr, hash);1593}1594#endif15951596#if defined(CONFIG_IP_DCCP) || defined(CONFIG_IP_DCCP_MODULE)1597/* Similar to secure_tcp_sequence_number but generate a 48 bit value1598* bit's 32-47 increase every key exchange1599* 0-31 hash(source, dest)1600*/1601u64 secure_dccp_sequence_number(__be32 saddr, __be32 daddr,1602__be16 sport, __be16 dport)1603{1604u64 seq;1605__u32 hash[4];1606struct keydata *keyptr = get_keyptr();16071608hash[0] = (__force u32)saddr;1609hash[1] = (__force u32)daddr;1610hash[2] = ((__force u16)sport << 16) + (__force u16)dport;1611hash[3] = keyptr->secret[11];16121613seq = half_md4_transform(hash, keyptr->secret);1614seq |= ((u64)keyptr->count) << (32 - HASH_BITS);16151616seq += ktime_to_ns(ktime_get_real());1617seq &= (1ull << 48) - 1;16181619return seq;1620}1621EXPORT_SYMBOL(secure_dccp_sequence_number);1622#endif16231624#endif /* CONFIG_INET */162516261627/*1628* Get a random word for internal kernel use only. Similar to urandom but1629* with the goal of minimal entropy pool depletion. As a result, the random1630* value is not cryptographically secure but for several uses the cost of1631* depleting entropy is too high1632*/1633DEFINE_PER_CPU(__u32 [4], get_random_int_hash);1634unsigned int get_random_int(void)1635{1636struct keydata *keyptr;1637__u32 *hash = get_cpu_var(get_random_int_hash);1638int ret;16391640keyptr = get_keyptr();1641hash[0] += current->pid + jiffies + get_cycles();16421643ret = half_md4_transform(hash, keyptr->secret);1644put_cpu_var(get_random_int_hash);16451646return ret;1647}16481649/*1650* randomize_range() returns a start address such that1651*1652* [...... <range> .....]1653* start end1654*1655* a <range> with size "len" starting at the return value is inside in the1656* area defined by [start, end], but is otherwise randomized.1657*/1658unsigned long1659randomize_range(unsigned long start, unsigned long end, unsigned long len)1660{1661unsigned long range = end - len - start;16621663if (end <= start + len)1664return 0;1665return PAGE_ALIGN(get_random_int() % range + start);1666}166716681669