xref: /linux/drivers/char/random.c (revision f331c0296f2a9fee0d396a70598b954062603015)
11da177e4SLinus Torvalds /*
21da177e4SLinus Torvalds  * random.c -- A strong random number generator
31da177e4SLinus Torvalds  *
49e95ce27SMatt Mackall  * Copyright Matt Mackall <mpm@selenic.com>, 2003, 2004, 2005
51da177e4SLinus Torvalds  *
61da177e4SLinus Torvalds  * Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999.  All
71da177e4SLinus Torvalds  * rights reserved.
81da177e4SLinus Torvalds  *
91da177e4SLinus Torvalds  * Redistribution and use in source and binary forms, with or without
101da177e4SLinus Torvalds  * modification, are permitted provided that the following conditions
111da177e4SLinus Torvalds  * are met:
121da177e4SLinus Torvalds  * 1. Redistributions of source code must retain the above copyright
131da177e4SLinus Torvalds  *    notice, and the entire permission notice in its entirety,
141da177e4SLinus Torvalds  *    including the disclaimer of warranties.
151da177e4SLinus Torvalds  * 2. Redistributions in binary form must reproduce the above copyright
161da177e4SLinus Torvalds  *    notice, this list of conditions and the following disclaimer in the
171da177e4SLinus Torvalds  *    documentation and/or other materials provided with the distribution.
181da177e4SLinus Torvalds  * 3. The name of the author may not be used to endorse or promote
191da177e4SLinus Torvalds  *    products derived from this software without specific prior
201da177e4SLinus Torvalds  *    written permission.
211da177e4SLinus Torvalds  *
221da177e4SLinus Torvalds  * ALTERNATIVELY, this product may be distributed under the terms of
231da177e4SLinus Torvalds  * the GNU General Public License, in which case the provisions of the GPL are
241da177e4SLinus Torvalds  * required INSTEAD OF the above restrictions.  (This clause is
251da177e4SLinus Torvalds  * necessary due to a potential bad interaction between the GPL and
261da177e4SLinus Torvalds  * the restrictions contained in a BSD-style copyright.)
271da177e4SLinus Torvalds  *
281da177e4SLinus Torvalds  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
291da177e4SLinus Torvalds  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
301da177e4SLinus Torvalds  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
311da177e4SLinus Torvalds  * WHICH ARE HEREBY DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE
321da177e4SLinus Torvalds  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
331da177e4SLinus Torvalds  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
341da177e4SLinus Torvalds  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
351da177e4SLinus Torvalds  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
361da177e4SLinus Torvalds  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
371da177e4SLinus Torvalds  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
381da177e4SLinus Torvalds  * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
391da177e4SLinus Torvalds  * DAMAGE.
401da177e4SLinus Torvalds  */
411da177e4SLinus Torvalds 
421da177e4SLinus Torvalds /*
431da177e4SLinus Torvalds  * (now, with legal B.S. out of the way.....)
441da177e4SLinus Torvalds  *
451da177e4SLinus Torvalds  * This routine gathers environmental noise from device drivers, etc.,
461da177e4SLinus Torvalds  * and returns good random numbers, suitable for cryptographic use.
471da177e4SLinus Torvalds  * Besides the obvious cryptographic uses, these numbers are also good
481da177e4SLinus Torvalds  * for seeding TCP sequence numbers, and other places where it is
491da177e4SLinus Torvalds  * desirable to have numbers which are not only random, but hard to
501da177e4SLinus Torvalds  * predict by an attacker.
511da177e4SLinus Torvalds  *
521da177e4SLinus Torvalds  * Theory of operation
531da177e4SLinus Torvalds  * ===================
541da177e4SLinus Torvalds  *
551da177e4SLinus Torvalds  * Computers are very predictable devices.  Hence it is extremely hard
561da177e4SLinus Torvalds  * to produce truly random numbers on a computer --- as opposed to
571da177e4SLinus Torvalds  * pseudo-random numbers, which can easily generated by using a
581da177e4SLinus Torvalds  * algorithm.  Unfortunately, it is very easy for attackers to guess
591da177e4SLinus Torvalds  * the sequence of pseudo-random number generators, and for some
601da177e4SLinus Torvalds  * applications this is not acceptable.  So instead, we must try to
611da177e4SLinus Torvalds  * gather "environmental noise" from the computer's environment, which
621da177e4SLinus Torvalds  * must be hard for outside attackers to observe, and use that to
631da177e4SLinus Torvalds  * generate random numbers.  In a Unix environment, this is best done
641da177e4SLinus Torvalds  * from inside the kernel.
651da177e4SLinus Torvalds  *
661da177e4SLinus Torvalds  * Sources of randomness from the environment include inter-keyboard
671da177e4SLinus Torvalds  * timings, inter-interrupt timings from some interrupts, and other
681da177e4SLinus Torvalds  * events which are both (a) non-deterministic and (b) hard for an
691da177e4SLinus Torvalds  * outside observer to measure.  Randomness from these sources are
701da177e4SLinus Torvalds  * added to an "entropy pool", which is mixed using a CRC-like function.
711da177e4SLinus Torvalds  * This is not cryptographically strong, but it is adequate assuming
721da177e4SLinus Torvalds  * the randomness is not chosen maliciously, and it is fast enough that
731da177e4SLinus Torvalds  * the overhead of doing it on every interrupt is very reasonable.
741da177e4SLinus Torvalds  * As random bytes are mixed into the entropy pool, the routines keep
751da177e4SLinus Torvalds  * an *estimate* of how many bits of randomness have been stored into
761da177e4SLinus Torvalds  * the random number generator's internal state.
771da177e4SLinus Torvalds  *
781da177e4SLinus Torvalds  * When random bytes are desired, they are obtained by taking the SHA
791da177e4SLinus Torvalds  * hash of the contents of the "entropy pool".  The SHA hash avoids
801da177e4SLinus Torvalds  * exposing the internal state of the entropy pool.  It is believed to
811da177e4SLinus Torvalds  * be computationally infeasible to derive any useful information
821da177e4SLinus Torvalds  * about the input of SHA from its output.  Even if it is possible to
831da177e4SLinus Torvalds  * analyze SHA in some clever way, as long as the amount of data
841da177e4SLinus Torvalds  * returned from the generator is less than the inherent entropy in
851da177e4SLinus Torvalds  * the pool, the output data is totally unpredictable.  For this
861da177e4SLinus Torvalds  * reason, the routine decreases its internal estimate of how many
871da177e4SLinus Torvalds  * bits of "true randomness" are contained in the entropy pool as it
881da177e4SLinus Torvalds  * outputs random numbers.
891da177e4SLinus Torvalds  *
901da177e4SLinus Torvalds  * If this estimate goes to zero, the routine can still generate
911da177e4SLinus Torvalds  * random numbers; however, an attacker may (at least in theory) be
921da177e4SLinus Torvalds  * able to infer the future output of the generator from prior
931da177e4SLinus Torvalds  * outputs.  This requires successful cryptanalysis of SHA, which is
941da177e4SLinus Torvalds  * not believed to be feasible, but there is a remote possibility.
951da177e4SLinus Torvalds  * Nonetheless, these numbers should be useful for the vast majority
961da177e4SLinus Torvalds  * of purposes.
971da177e4SLinus Torvalds  *
981da177e4SLinus Torvalds  * Exported interfaces ---- output
991da177e4SLinus Torvalds  * ===============================
1001da177e4SLinus Torvalds  *
1011da177e4SLinus Torvalds  * There are three exported interfaces; the first is one designed to
1021da177e4SLinus Torvalds  * be used from within the kernel:
1031da177e4SLinus Torvalds  *
1041da177e4SLinus Torvalds  * 	void get_random_bytes(void *buf, int nbytes);
1051da177e4SLinus Torvalds  *
1061da177e4SLinus Torvalds  * This interface will return the requested number of random bytes,
1071da177e4SLinus Torvalds  * and place it in the requested buffer.
1081da177e4SLinus Torvalds  *
1091da177e4SLinus Torvalds  * The two other interfaces are two character devices /dev/random and
1101da177e4SLinus Torvalds  * /dev/urandom.  /dev/random is suitable for use when very high
1111da177e4SLinus Torvalds  * quality randomness is desired (for example, for key generation or
1121da177e4SLinus Torvalds  * one-time pads), as it will only return a maximum of the number of
1131da177e4SLinus Torvalds  * bits of randomness (as estimated by the random number generator)
1141da177e4SLinus Torvalds  * contained in the entropy pool.
1151da177e4SLinus Torvalds  *
1161da177e4SLinus Torvalds  * The /dev/urandom device does not have this limit, and will return
1171da177e4SLinus Torvalds  * as many bytes as are requested.  As more and more random bytes are
1181da177e4SLinus Torvalds  * requested without giving time for the entropy pool to recharge,
1191da177e4SLinus Torvalds  * this will result in random numbers that are merely cryptographically
1201da177e4SLinus Torvalds  * strong.  For many applications, however, this is acceptable.
1211da177e4SLinus Torvalds  *
1221da177e4SLinus Torvalds  * Exported interfaces ---- input
1231da177e4SLinus Torvalds  * ==============================
1241da177e4SLinus Torvalds  *
1251da177e4SLinus Torvalds  * The current exported interfaces for gathering environmental noise
1261da177e4SLinus Torvalds  * from the devices are:
1271da177e4SLinus Torvalds  *
1281da177e4SLinus Torvalds  * 	void add_input_randomness(unsigned int type, unsigned int code,
1291da177e4SLinus Torvalds  *                                unsigned int value);
1301da177e4SLinus Torvalds  * 	void add_interrupt_randomness(int irq);
1311da177e4SLinus Torvalds  *
1321da177e4SLinus Torvalds  * add_input_randomness() uses the input layer interrupt timing, as well as
1331da177e4SLinus Torvalds  * the event type information from the hardware.
1341da177e4SLinus Torvalds  *
1351da177e4SLinus Torvalds  * add_interrupt_randomness() uses the inter-interrupt timing as random
1361da177e4SLinus Torvalds  * inputs to the entropy pool.  Note that not all interrupts are good
1371da177e4SLinus Torvalds  * sources of randomness!  For example, the timer interrupts is not a
1381da177e4SLinus Torvalds  * good choice, because the periodicity of the interrupts is too
1391da177e4SLinus Torvalds  * regular, and hence predictable to an attacker.  Disk interrupts are
1401da177e4SLinus Torvalds  * a better measure, since the timing of the disk interrupts are more
1411da177e4SLinus Torvalds  * unpredictable.
1421da177e4SLinus Torvalds  *
1431da177e4SLinus Torvalds  * All of these routines try to estimate how many bits of randomness a
1441da177e4SLinus Torvalds  * particular randomness source.  They do this by keeping track of the
1451da177e4SLinus Torvalds  * first and second order deltas of the event timings.
1461da177e4SLinus Torvalds  *
1471da177e4SLinus Torvalds  * Ensuring unpredictability at system startup
1481da177e4SLinus Torvalds  * ============================================
1491da177e4SLinus Torvalds  *
1501da177e4SLinus Torvalds  * When any operating system starts up, it will go through a sequence
1511da177e4SLinus Torvalds  * of actions that are fairly predictable by an adversary, especially
1521da177e4SLinus Torvalds  * if the start-up does not involve interaction with a human operator.
1531da177e4SLinus Torvalds  * This reduces the actual number of bits of unpredictability in the
1541da177e4SLinus Torvalds  * entropy pool below the value in entropy_count.  In order to
1551da177e4SLinus Torvalds  * counteract this effect, it helps to carry information in the
1561da177e4SLinus Torvalds  * entropy pool across shut-downs and start-ups.  To do this, put the
1571da177e4SLinus Torvalds  * following lines an appropriate script which is run during the boot
1581da177e4SLinus Torvalds  * sequence:
1591da177e4SLinus Torvalds  *
1601da177e4SLinus Torvalds  *	echo "Initializing random number generator..."
1611da177e4SLinus Torvalds  *	random_seed=/var/run/random-seed
1621da177e4SLinus Torvalds  *	# Carry a random seed from start-up to start-up
1631da177e4SLinus Torvalds  *	# Load and then save the whole entropy pool
1641da177e4SLinus Torvalds  *	if [ -f $random_seed ]; then
1651da177e4SLinus Torvalds  *		cat $random_seed >/dev/urandom
1661da177e4SLinus Torvalds  *	else
1671da177e4SLinus Torvalds  *		touch $random_seed
1681da177e4SLinus Torvalds  *	fi
1691da177e4SLinus Torvalds  *	chmod 600 $random_seed
1701da177e4SLinus Torvalds  *	dd if=/dev/urandom of=$random_seed count=1 bs=512
1711da177e4SLinus Torvalds  *
1721da177e4SLinus Torvalds  * and the following lines in an appropriate script which is run as
1731da177e4SLinus Torvalds  * the system is shutdown:
1741da177e4SLinus Torvalds  *
1751da177e4SLinus Torvalds  *	# Carry a random seed from shut-down to start-up
1761da177e4SLinus Torvalds  *	# Save the whole entropy pool
1771da177e4SLinus Torvalds  *	echo "Saving random seed..."
1781da177e4SLinus Torvalds  *	random_seed=/var/run/random-seed
1791da177e4SLinus Torvalds  *	touch $random_seed
1801da177e4SLinus Torvalds  *	chmod 600 $random_seed
1811da177e4SLinus Torvalds  *	dd if=/dev/urandom of=$random_seed count=1 bs=512
1821da177e4SLinus Torvalds  *
1831da177e4SLinus Torvalds  * For example, on most modern systems using the System V init
1841da177e4SLinus Torvalds  * scripts, such code fragments would be found in
1851da177e4SLinus Torvalds  * /etc/rc.d/init.d/random.  On older Linux systems, the correct script
1861da177e4SLinus Torvalds  * location might be in /etc/rcb.d/rc.local or /etc/rc.d/rc.0.
1871da177e4SLinus Torvalds  *
1881da177e4SLinus Torvalds  * Effectively, these commands cause the contents of the entropy pool
1891da177e4SLinus Torvalds  * to be saved at shut-down time and reloaded into the entropy pool at
1901da177e4SLinus Torvalds  * start-up.  (The 'dd' in the addition to the bootup script is to
1911da177e4SLinus Torvalds  * make sure that /etc/random-seed is different for every start-up,
1921da177e4SLinus Torvalds  * even if the system crashes without executing rc.0.)  Even with
1931da177e4SLinus Torvalds  * complete knowledge of the start-up activities, predicting the state
1941da177e4SLinus Torvalds  * of the entropy pool requires knowledge of the previous history of
1951da177e4SLinus Torvalds  * the system.
1961da177e4SLinus Torvalds  *
1971da177e4SLinus Torvalds  * Configuring the /dev/random driver under Linux
1981da177e4SLinus Torvalds  * ==============================================
1991da177e4SLinus Torvalds  *
2001da177e4SLinus Torvalds  * The /dev/random driver under Linux uses minor numbers 8 and 9 of
2011da177e4SLinus Torvalds  * the /dev/mem major number (#1).  So if your system does not have
2021da177e4SLinus Torvalds  * /dev/random and /dev/urandom created already, they can be created
2031da177e4SLinus Torvalds  * by using the commands:
2041da177e4SLinus Torvalds  *
2051da177e4SLinus Torvalds  * 	mknod /dev/random c 1 8
2061da177e4SLinus Torvalds  * 	mknod /dev/urandom c 1 9
2071da177e4SLinus Torvalds  *
2081da177e4SLinus Torvalds  * Acknowledgements:
2091da177e4SLinus Torvalds  * =================
2101da177e4SLinus Torvalds  *
2111da177e4SLinus Torvalds  * Ideas for constructing this random number generator were derived
2121da177e4SLinus Torvalds  * from Pretty Good Privacy's random number generator, and from private
2131da177e4SLinus Torvalds  * discussions with Phil Karn.  Colin Plumb provided a faster random
2141da177e4SLinus Torvalds  * number generator, which speed up the mixing function of the entropy
2151da177e4SLinus Torvalds  * pool, taken from PGPfone.  Dale Worley has also contributed many
2161da177e4SLinus Torvalds  * useful ideas and suggestions to improve this driver.
2171da177e4SLinus Torvalds  *
2181da177e4SLinus Torvalds  * Any flaws in the design are solely my responsibility, and should
2191da177e4SLinus Torvalds  * not be attributed to the Phil, Colin, or any of authors of PGP.
2201da177e4SLinus Torvalds  *
2211da177e4SLinus Torvalds  * Further background information on this topic may be obtained from
2221da177e4SLinus Torvalds  * RFC 1750, "Randomness Recommendations for Security", by Donald
2231da177e4SLinus Torvalds  * Eastlake, Steve Crocker, and Jeff Schiller.
2241da177e4SLinus Torvalds  */
2251da177e4SLinus Torvalds 
2261da177e4SLinus Torvalds #include <linux/utsname.h>
2271da177e4SLinus Torvalds #include <linux/module.h>
2281da177e4SLinus Torvalds #include <linux/kernel.h>
2291da177e4SLinus Torvalds #include <linux/major.h>
2301da177e4SLinus Torvalds #include <linux/string.h>
2311da177e4SLinus Torvalds #include <linux/fcntl.h>
2321da177e4SLinus Torvalds #include <linux/slab.h>
2331da177e4SLinus Torvalds #include <linux/random.h>
2341da177e4SLinus Torvalds #include <linux/poll.h>
2351da177e4SLinus Torvalds #include <linux/init.h>
2361da177e4SLinus Torvalds #include <linux/fs.h>
2371da177e4SLinus Torvalds #include <linux/genhd.h>
2381da177e4SLinus Torvalds #include <linux/interrupt.h>
23927ac792cSAndrea Righi #include <linux/mm.h>
2401da177e4SLinus Torvalds #include <linux/spinlock.h>
2411da177e4SLinus Torvalds #include <linux/percpu.h>
2421da177e4SLinus Torvalds #include <linux/cryptohash.h>
2431da177e4SLinus Torvalds 
2441da177e4SLinus Torvalds #include <asm/processor.h>
2451da177e4SLinus Torvalds #include <asm/uaccess.h>
2461da177e4SLinus Torvalds #include <asm/irq.h>
2471da177e4SLinus Torvalds #include <asm/io.h>
2481da177e4SLinus Torvalds 
2491da177e4SLinus Torvalds /*
2501da177e4SLinus Torvalds  * Configuration information
2511da177e4SLinus Torvalds  */
2521da177e4SLinus Torvalds #define INPUT_POOL_WORDS 128
2531da177e4SLinus Torvalds #define OUTPUT_POOL_WORDS 32
2541da177e4SLinus Torvalds #define SEC_XFER_SIZE 512
2551da177e4SLinus Torvalds 
2561da177e4SLinus Torvalds /*
2571da177e4SLinus Torvalds  * The minimum number of bits of entropy before we wake up a read on
2581da177e4SLinus Torvalds  * /dev/random.  Should be enough to do a significant reseed.
2591da177e4SLinus Torvalds  */
2601da177e4SLinus Torvalds static int random_read_wakeup_thresh = 64;
2611da177e4SLinus Torvalds 
2621da177e4SLinus Torvalds /*
2631da177e4SLinus Torvalds  * If the entropy count falls under this number of bits, then we
2641da177e4SLinus Torvalds  * should wake up processes which are selecting or polling on write
2651da177e4SLinus Torvalds  * access to /dev/random.
2661da177e4SLinus Torvalds  */
2671da177e4SLinus Torvalds static int random_write_wakeup_thresh = 128;
2681da177e4SLinus Torvalds 
2691da177e4SLinus Torvalds /*
2701da177e4SLinus Torvalds  * When the input pool goes over trickle_thresh, start dropping most
2711da177e4SLinus Torvalds  * samples to avoid wasting CPU time and reduce lock contention.
2721da177e4SLinus Torvalds  */
2731da177e4SLinus Torvalds 
2746c036527SChristoph Lameter static int trickle_thresh __read_mostly = INPUT_POOL_WORDS * 28;
2751da177e4SLinus Torvalds 
27690b75ee5SMatt Mackall static DEFINE_PER_CPU(int, trickle_count);
2771da177e4SLinus Torvalds 
2781da177e4SLinus Torvalds /*
2791da177e4SLinus Torvalds  * A pool of size .poolwords is stirred with a primitive polynomial
2801da177e4SLinus Torvalds  * of degree .poolwords over GF(2).  The taps for various sizes are
2811da177e4SLinus Torvalds  * defined below.  They are chosen to be evenly spaced (minimum RMS
2821da177e4SLinus Torvalds  * distance from evenly spaced; the numbers in the comments are a
2831da177e4SLinus Torvalds  * scaled squared error sum) except for the last tap, which is 1 to
2841da177e4SLinus Torvalds  * get the twisting happening as fast as possible.
2851da177e4SLinus Torvalds  */
2861da177e4SLinus Torvalds static struct poolinfo {
2871da177e4SLinus Torvalds 	int poolwords;
2881da177e4SLinus Torvalds 	int tap1, tap2, tap3, tap4, tap5;
2891da177e4SLinus Torvalds } poolinfo_table[] = {
2901da177e4SLinus Torvalds 	/* x^128 + x^103 + x^76 + x^51 +x^25 + x + 1 -- 105 */
2911da177e4SLinus Torvalds 	{ 128,	103,	76,	51,	25,	1 },
2921da177e4SLinus Torvalds 	/* x^32 + x^26 + x^20 + x^14 + x^7 + x + 1 -- 15 */
2931da177e4SLinus Torvalds 	{ 32,	26,	20,	14,	7,	1 },
2941da177e4SLinus Torvalds #if 0
2951da177e4SLinus Torvalds 	/* x^2048 + x^1638 + x^1231 + x^819 + x^411 + x + 1  -- 115 */
2961da177e4SLinus Torvalds 	{ 2048,	1638,	1231,	819,	411,	1 },
2971da177e4SLinus Torvalds 
2981da177e4SLinus Torvalds 	/* x^1024 + x^817 + x^615 + x^412 + x^204 + x + 1 -- 290 */
2991da177e4SLinus Torvalds 	{ 1024,	817,	615,	412,	204,	1 },
3001da177e4SLinus Torvalds 
3011da177e4SLinus Torvalds 	/* x^1024 + x^819 + x^616 + x^410 + x^207 + x^2 + 1 -- 115 */
3021da177e4SLinus Torvalds 	{ 1024,	819,	616,	410,	207,	2 },
3031da177e4SLinus Torvalds 
3041da177e4SLinus Torvalds 	/* x^512 + x^411 + x^308 + x^208 + x^104 + x + 1 -- 225 */
3051da177e4SLinus Torvalds 	{ 512,	411,	308,	208,	104,	1 },
3061da177e4SLinus Torvalds 
3071da177e4SLinus Torvalds 	/* x^512 + x^409 + x^307 + x^206 + x^102 + x^2 + 1 -- 95 */
3081da177e4SLinus Torvalds 	{ 512,	409,	307,	206,	102,	2 },
3091da177e4SLinus Torvalds 	/* x^512 + x^409 + x^309 + x^205 + x^103 + x^2 + 1 -- 95 */
3101da177e4SLinus Torvalds 	{ 512,	409,	309,	205,	103,	2 },
3111da177e4SLinus Torvalds 
3121da177e4SLinus Torvalds 	/* x^256 + x^205 + x^155 + x^101 + x^52 + x + 1 -- 125 */
3131da177e4SLinus Torvalds 	{ 256,	205,	155,	101,	52,	1 },
3141da177e4SLinus Torvalds 
3151da177e4SLinus Torvalds 	/* x^128 + x^103 + x^78 + x^51 + x^27 + x^2 + 1 -- 70 */
3161da177e4SLinus Torvalds 	{ 128,	103,	78,	51,	27,	2 },
3171da177e4SLinus Torvalds 
3181da177e4SLinus Torvalds 	/* x^64 + x^52 + x^39 + x^26 + x^14 + x + 1 -- 15 */
3191da177e4SLinus Torvalds 	{ 64,	52,	39,	26,	14,	1 },
3201da177e4SLinus Torvalds #endif
3211da177e4SLinus Torvalds };
3221da177e4SLinus Torvalds 
3231da177e4SLinus Torvalds #define POOLBITS	poolwords*32
3241da177e4SLinus Torvalds #define POOLBYTES	poolwords*4
3251da177e4SLinus Torvalds 
3261da177e4SLinus Torvalds /*
3271da177e4SLinus Torvalds  * For the purposes of better mixing, we use the CRC-32 polynomial as
3281da177e4SLinus Torvalds  * well to make a twisted Generalized Feedback Shift Reigster
3291da177e4SLinus Torvalds  *
3301da177e4SLinus Torvalds  * (See M. Matsumoto & Y. Kurita, 1992.  Twisted GFSR generators.  ACM
3311da177e4SLinus Torvalds  * Transactions on Modeling and Computer Simulation 2(3):179-194.
3321da177e4SLinus Torvalds  * Also see M. Matsumoto & Y. Kurita, 1994.  Twisted GFSR generators
3331da177e4SLinus Torvalds  * II.  ACM Transactions on Mdeling and Computer Simulation 4:254-266)
3341da177e4SLinus Torvalds  *
3351da177e4SLinus Torvalds  * Thanks to Colin Plumb for suggesting this.
3361da177e4SLinus Torvalds  *
3371da177e4SLinus Torvalds  * We have not analyzed the resultant polynomial to prove it primitive;
3381da177e4SLinus Torvalds  * in fact it almost certainly isn't.  Nonetheless, the irreducible factors
3391da177e4SLinus Torvalds  * of a random large-degree polynomial over GF(2) are more than large enough
3401da177e4SLinus Torvalds  * that periodicity is not a concern.
3411da177e4SLinus Torvalds  *
3421da177e4SLinus Torvalds  * The input hash is much less sensitive than the output hash.  All
3431da177e4SLinus Torvalds  * that we want of it is that it be a good non-cryptographic hash;
3441da177e4SLinus Torvalds  * i.e. it not produce collisions when fed "random" data of the sort
3451da177e4SLinus Torvalds  * we expect to see.  As long as the pool state differs for different
3461da177e4SLinus Torvalds  * inputs, we have preserved the input entropy and done a good job.
3471da177e4SLinus Torvalds  * The fact that an intelligent attacker can construct inputs that
3481da177e4SLinus Torvalds  * will produce controlled alterations to the pool's state is not
3491da177e4SLinus Torvalds  * important because we don't consider such inputs to contribute any
3501da177e4SLinus Torvalds  * randomness.  The only property we need with respect to them is that
3511da177e4SLinus Torvalds  * the attacker can't increase his/her knowledge of the pool's state.
3521da177e4SLinus Torvalds  * Since all additions are reversible (knowing the final state and the
3531da177e4SLinus Torvalds  * input, you can reconstruct the initial state), if an attacker has
3541da177e4SLinus Torvalds  * any uncertainty about the initial state, he/she can only shuffle
3551da177e4SLinus Torvalds  * that uncertainty about, but never cause any collisions (which would
3561da177e4SLinus Torvalds  * decrease the uncertainty).
3571da177e4SLinus Torvalds  *
3581da177e4SLinus Torvalds  * The chosen system lets the state of the pool be (essentially) the input
3591da177e4SLinus Torvalds  * modulo the generator polymnomial.  Now, for random primitive polynomials,
3601da177e4SLinus Torvalds  * this is a universal class of hash functions, meaning that the chance
3611da177e4SLinus Torvalds  * of a collision is limited by the attacker's knowledge of the generator
3621da177e4SLinus Torvalds  * polynomail, so if it is chosen at random, an attacker can never force
3631da177e4SLinus Torvalds  * a collision.  Here, we use a fixed polynomial, but we *can* assume that
3641da177e4SLinus Torvalds  * ###--> it is unknown to the processes generating the input entropy. <-###
3651da177e4SLinus Torvalds  * Because of this important property, this is a good, collision-resistant
3661da177e4SLinus Torvalds  * hash; hash collisions will occur no more often than chance.
3671da177e4SLinus Torvalds  */
3681da177e4SLinus Torvalds 
3691da177e4SLinus Torvalds /*
3701da177e4SLinus Torvalds  * Static global variables
3711da177e4SLinus Torvalds  */
3721da177e4SLinus Torvalds static DECLARE_WAIT_QUEUE_HEAD(random_read_wait);
3731da177e4SLinus Torvalds static DECLARE_WAIT_QUEUE_HEAD(random_write_wait);
3749a6f70bbSJeff Dike static struct fasync_struct *fasync;
3751da177e4SLinus Torvalds 
3761da177e4SLinus Torvalds #if 0
37790b75ee5SMatt Mackall static int debug;
3781da177e4SLinus Torvalds module_param(debug, bool, 0644);
37990b75ee5SMatt Mackall #define DEBUG_ENT(fmt, arg...) do { \
38090b75ee5SMatt Mackall 	if (debug) \
3811da177e4SLinus Torvalds 		printk(KERN_DEBUG "random %04d %04d %04d: " \
3821da177e4SLinus Torvalds 		fmt,\
3831da177e4SLinus Torvalds 		input_pool.entropy_count,\
3841da177e4SLinus Torvalds 		blocking_pool.entropy_count,\
3851da177e4SLinus Torvalds 		nonblocking_pool.entropy_count,\
3861da177e4SLinus Torvalds 		## arg); } while (0)
3871da177e4SLinus Torvalds #else
3881da177e4SLinus Torvalds #define DEBUG_ENT(fmt, arg...) do {} while (0)
3891da177e4SLinus Torvalds #endif
3901da177e4SLinus Torvalds 
3911da177e4SLinus Torvalds /**********************************************************************
3921da177e4SLinus Torvalds  *
3931da177e4SLinus Torvalds  * OS independent entropy store.   Here are the functions which handle
3941da177e4SLinus Torvalds  * storing entropy in an entropy pool.
3951da177e4SLinus Torvalds  *
3961da177e4SLinus Torvalds  **********************************************************************/
3971da177e4SLinus Torvalds 
3981da177e4SLinus Torvalds struct entropy_store;
3991da177e4SLinus Torvalds struct entropy_store {
40043358209SMatt Mackall 	/* read-only data: */
4011da177e4SLinus Torvalds 	struct poolinfo *poolinfo;
4021da177e4SLinus Torvalds 	__u32 *pool;
4031da177e4SLinus Torvalds 	const char *name;
4041da177e4SLinus Torvalds 	int limit;
4051da177e4SLinus Torvalds 	struct entropy_store *pull;
4061da177e4SLinus Torvalds 
4071da177e4SLinus Torvalds 	/* read-write data: */
40843358209SMatt Mackall 	spinlock_t lock;
4091da177e4SLinus Torvalds 	unsigned add_ptr;
4108b76f46aSAndrew Morton 	int entropy_count;	/* Must at no time exceed ->POOLBITS! */
4111da177e4SLinus Torvalds 	int input_rotate;
4121da177e4SLinus Torvalds };
4131da177e4SLinus Torvalds 
4141da177e4SLinus Torvalds static __u32 input_pool_data[INPUT_POOL_WORDS];
4151da177e4SLinus Torvalds static __u32 blocking_pool_data[OUTPUT_POOL_WORDS];
4161da177e4SLinus Torvalds static __u32 nonblocking_pool_data[OUTPUT_POOL_WORDS];
4171da177e4SLinus Torvalds 
4181da177e4SLinus Torvalds static struct entropy_store input_pool = {
4191da177e4SLinus Torvalds 	.poolinfo = &poolinfo_table[0],
4201da177e4SLinus Torvalds 	.name = "input",
4211da177e4SLinus Torvalds 	.limit = 1,
422e4d91918SIngo Molnar 	.lock = __SPIN_LOCK_UNLOCKED(&input_pool.lock),
4231da177e4SLinus Torvalds 	.pool = input_pool_data
4241da177e4SLinus Torvalds };
4251da177e4SLinus Torvalds 
4261da177e4SLinus Torvalds static struct entropy_store blocking_pool = {
4271da177e4SLinus Torvalds 	.poolinfo = &poolinfo_table[1],
4281da177e4SLinus Torvalds 	.name = "blocking",
4291da177e4SLinus Torvalds 	.limit = 1,
4301da177e4SLinus Torvalds 	.pull = &input_pool,
431e4d91918SIngo Molnar 	.lock = __SPIN_LOCK_UNLOCKED(&blocking_pool.lock),
4321da177e4SLinus Torvalds 	.pool = blocking_pool_data
4331da177e4SLinus Torvalds };
4341da177e4SLinus Torvalds 
4351da177e4SLinus Torvalds static struct entropy_store nonblocking_pool = {
4361da177e4SLinus Torvalds 	.poolinfo = &poolinfo_table[1],
4371da177e4SLinus Torvalds 	.name = "nonblocking",
4381da177e4SLinus Torvalds 	.pull = &input_pool,
439e4d91918SIngo Molnar 	.lock = __SPIN_LOCK_UNLOCKED(&nonblocking_pool.lock),
4401da177e4SLinus Torvalds 	.pool = nonblocking_pool_data
4411da177e4SLinus Torvalds };
4421da177e4SLinus Torvalds 
4431da177e4SLinus Torvalds /*
444e68e5b66SMatt Mackall  * This function adds bytes into the entropy "pool".  It does not
4451da177e4SLinus Torvalds  * update the entropy estimate.  The caller should call
446adc782daSMatt Mackall  * credit_entropy_bits if this is appropriate.
4471da177e4SLinus Torvalds  *
4481da177e4SLinus Torvalds  * The pool is stirred with a primitive polynomial of the appropriate
4491da177e4SLinus Torvalds  * degree, and then twisted.  We twist by three bits at a time because
4501da177e4SLinus Torvalds  * it's cheap to do so and helps slightly in the expected case where
4511da177e4SLinus Torvalds  * the entropy is concentrated in the low-order bits.
4521da177e4SLinus Torvalds  */
453e68e5b66SMatt Mackall static void mix_pool_bytes_extract(struct entropy_store *r, const void *in,
454e68e5b66SMatt Mackall 				   int nbytes, __u8 out[64])
4551da177e4SLinus Torvalds {
4561da177e4SLinus Torvalds 	static __u32 const twist_table[8] = {
4571da177e4SLinus Torvalds 		0x00000000, 0x3b6e20c8, 0x76dc4190, 0x4db26158,
4581da177e4SLinus Torvalds 		0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278 };
459993ba211SMatt Mackall 	unsigned long i, j, tap1, tap2, tap3, tap4, tap5;
460feee7697SMatt Mackall 	int input_rotate;
4611da177e4SLinus Torvalds 	int wordmask = r->poolinfo->poolwords - 1;
462e68e5b66SMatt Mackall 	const char *bytes = in;
4636d38b827SMatt Mackall 	__u32 w;
4641da177e4SLinus Torvalds 	unsigned long flags;
4651da177e4SLinus Torvalds 
4661da177e4SLinus Torvalds 	/* Taps are constant, so we can load them without holding r->lock.  */
4671da177e4SLinus Torvalds 	tap1 = r->poolinfo->tap1;
4681da177e4SLinus Torvalds 	tap2 = r->poolinfo->tap2;
4691da177e4SLinus Torvalds 	tap3 = r->poolinfo->tap3;
4701da177e4SLinus Torvalds 	tap4 = r->poolinfo->tap4;
4711da177e4SLinus Torvalds 	tap5 = r->poolinfo->tap5;
4721da177e4SLinus Torvalds 
4731da177e4SLinus Torvalds 	spin_lock_irqsave(&r->lock, flags);
4741da177e4SLinus Torvalds 	input_rotate = r->input_rotate;
475993ba211SMatt Mackall 	i = r->add_ptr;
4761da177e4SLinus Torvalds 
477e68e5b66SMatt Mackall 	/* mix one byte at a time to simplify size handling and churn faster */
478e68e5b66SMatt Mackall 	while (nbytes--) {
479e68e5b66SMatt Mackall 		w = rol32(*bytes++, input_rotate & 31);
480993ba211SMatt Mackall 		i = (i - 1) & wordmask;
4811da177e4SLinus Torvalds 
4821da177e4SLinus Torvalds 		/* XOR in the various taps */
483993ba211SMatt Mackall 		w ^= r->pool[i];
4841da177e4SLinus Torvalds 		w ^= r->pool[(i + tap1) & wordmask];
4851da177e4SLinus Torvalds 		w ^= r->pool[(i + tap2) & wordmask];
4861da177e4SLinus Torvalds 		w ^= r->pool[(i + tap3) & wordmask];
4871da177e4SLinus Torvalds 		w ^= r->pool[(i + tap4) & wordmask];
4881da177e4SLinus Torvalds 		w ^= r->pool[(i + tap5) & wordmask];
489993ba211SMatt Mackall 
490993ba211SMatt Mackall 		/* Mix the result back in with a twist */
4911da177e4SLinus Torvalds 		r->pool[i] = (w >> 3) ^ twist_table[w & 7];
492feee7697SMatt Mackall 
493feee7697SMatt Mackall 		/*
494feee7697SMatt Mackall 		 * Normally, we add 7 bits of rotation to the pool.
495feee7697SMatt Mackall 		 * At the beginning of the pool, add an extra 7 bits
496feee7697SMatt Mackall 		 * rotation, so that successive passes spread the
497feee7697SMatt Mackall 		 * input bits across the pool evenly.
498feee7697SMatt Mackall 		 */
499feee7697SMatt Mackall 		input_rotate += i ? 7 : 14;
5001da177e4SLinus Torvalds 	}
5011da177e4SLinus Torvalds 
5021da177e4SLinus Torvalds 	r->input_rotate = input_rotate;
503993ba211SMatt Mackall 	r->add_ptr = i;
5041da177e4SLinus Torvalds 
505993ba211SMatt Mackall 	if (out)
506993ba211SMatt Mackall 		for (j = 0; j < 16; j++)
507e68e5b66SMatt Mackall 			((__u32 *)out)[j] = r->pool[(i - j) & wordmask];
5081da177e4SLinus Torvalds 
5091da177e4SLinus Torvalds 	spin_unlock_irqrestore(&r->lock, flags);
5101da177e4SLinus Torvalds }
5111da177e4SLinus Torvalds 
512e68e5b66SMatt Mackall static void mix_pool_bytes(struct entropy_store *r, const void *in, int bytes)
5131da177e4SLinus Torvalds {
514e68e5b66SMatt Mackall        mix_pool_bytes_extract(r, in, bytes, NULL);
5151da177e4SLinus Torvalds }
5161da177e4SLinus Torvalds 
5171da177e4SLinus Torvalds /*
5181da177e4SLinus Torvalds  * Credit (or debit) the entropy store with n bits of entropy
5191da177e4SLinus Torvalds  */
520adc782daSMatt Mackall static void credit_entropy_bits(struct entropy_store *r, int nbits)
5211da177e4SLinus Torvalds {
5221da177e4SLinus Torvalds 	unsigned long flags;
5238b76f46aSAndrew Morton 	int entropy_count;
5241da177e4SLinus Torvalds 
525adc782daSMatt Mackall 	if (!nbits)
526adc782daSMatt Mackall 		return;
527adc782daSMatt Mackall 
5281da177e4SLinus Torvalds 	spin_lock_irqsave(&r->lock, flags);
5291da177e4SLinus Torvalds 
530adc782daSMatt Mackall 	DEBUG_ENT("added %d entropy credits to %s\n", nbits, r->name);
5318b76f46aSAndrew Morton 	entropy_count = r->entropy_count;
5328b76f46aSAndrew Morton 	entropy_count += nbits;
5338b76f46aSAndrew Morton 	if (entropy_count < 0) {
534adc782daSMatt Mackall 		DEBUG_ENT("negative entropy/overflow\n");
5358b76f46aSAndrew Morton 		entropy_count = 0;
5368b76f46aSAndrew Morton 	} else if (entropy_count > r->poolinfo->POOLBITS)
5378b76f46aSAndrew Morton 		entropy_count = r->poolinfo->POOLBITS;
5388b76f46aSAndrew Morton 	r->entropy_count = entropy_count;
5391da177e4SLinus Torvalds 
54088c730daSMatt Mackall 	/* should we wake readers? */
5418b76f46aSAndrew Morton 	if (r == &input_pool && entropy_count >= random_read_wakeup_thresh) {
54288c730daSMatt Mackall 		wake_up_interruptible(&random_read_wait);
5439a6f70bbSJeff Dike 		kill_fasync(&fasync, SIGIO, POLL_IN);
5449a6f70bbSJeff Dike 	}
5451da177e4SLinus Torvalds 	spin_unlock_irqrestore(&r->lock, flags);
5461da177e4SLinus Torvalds }
5471da177e4SLinus Torvalds 
5481da177e4SLinus Torvalds /*********************************************************************
5491da177e4SLinus Torvalds  *
5501da177e4SLinus Torvalds  * Entropy input management
5511da177e4SLinus Torvalds  *
5521da177e4SLinus Torvalds  *********************************************************************/
5531da177e4SLinus Torvalds 
5541da177e4SLinus Torvalds /* There is one of these per entropy source */
5551da177e4SLinus Torvalds struct timer_rand_state {
5561da177e4SLinus Torvalds 	cycles_t last_time;
5571da177e4SLinus Torvalds 	long last_delta, last_delta2;
5581da177e4SLinus Torvalds 	unsigned dont_count_entropy:1;
5591da177e4SLinus Torvalds };
5601da177e4SLinus Torvalds 
5611da177e4SLinus Torvalds static struct timer_rand_state input_timer_state;
5621da177e4SLinus Torvalds static struct timer_rand_state *irq_timer_state[NR_IRQS];
5631da177e4SLinus Torvalds 
5641da177e4SLinus Torvalds /*
5651da177e4SLinus Torvalds  * This function adds entropy to the entropy "pool" by using timing
5661da177e4SLinus Torvalds  * delays.  It uses the timer_rand_state structure to make an estimate
5671da177e4SLinus Torvalds  * of how many bits of entropy this call has added to the pool.
5681da177e4SLinus Torvalds  *
5691da177e4SLinus Torvalds  * The number "num" is also added to the pool - it should somehow describe
5701da177e4SLinus Torvalds  * the type of event which just happened.  This is currently 0-255 for
5711da177e4SLinus Torvalds  * keyboard scan codes, and 256 upwards for interrupts.
5721da177e4SLinus Torvalds  *
5731da177e4SLinus Torvalds  */
5741da177e4SLinus Torvalds static void add_timer_randomness(struct timer_rand_state *state, unsigned num)
5751da177e4SLinus Torvalds {
5761da177e4SLinus Torvalds 	struct {
5771da177e4SLinus Torvalds 		cycles_t cycles;
5781da177e4SLinus Torvalds 		long jiffies;
5791da177e4SLinus Torvalds 		unsigned num;
5801da177e4SLinus Torvalds 	} sample;
5811da177e4SLinus Torvalds 	long delta, delta2, delta3;
5821da177e4SLinus Torvalds 
5831da177e4SLinus Torvalds 	preempt_disable();
5841da177e4SLinus Torvalds 	/* if over the trickle threshold, use only 1 in 4096 samples */
5851da177e4SLinus Torvalds 	if (input_pool.entropy_count > trickle_thresh &&
5861da177e4SLinus Torvalds 	    (__get_cpu_var(trickle_count)++ & 0xfff))
5871da177e4SLinus Torvalds 		goto out;
5881da177e4SLinus Torvalds 
5891da177e4SLinus Torvalds 	sample.jiffies = jiffies;
5901da177e4SLinus Torvalds 	sample.cycles = get_cycles();
5911da177e4SLinus Torvalds 	sample.num = num;
592e68e5b66SMatt Mackall 	mix_pool_bytes(&input_pool, &sample, sizeof(sample));
5931da177e4SLinus Torvalds 
5941da177e4SLinus Torvalds 	/*
5951da177e4SLinus Torvalds 	 * Calculate number of bits of randomness we probably added.
5961da177e4SLinus Torvalds 	 * We take into account the first, second and third-order deltas
5971da177e4SLinus Torvalds 	 * in order to make our estimate.
5981da177e4SLinus Torvalds 	 */
5991da177e4SLinus Torvalds 
6001da177e4SLinus Torvalds 	if (!state->dont_count_entropy) {
6011da177e4SLinus Torvalds 		delta = sample.jiffies - state->last_time;
6021da177e4SLinus Torvalds 		state->last_time = sample.jiffies;
6031da177e4SLinus Torvalds 
6041da177e4SLinus Torvalds 		delta2 = delta - state->last_delta;
6051da177e4SLinus Torvalds 		state->last_delta = delta;
6061da177e4SLinus Torvalds 
6071da177e4SLinus Torvalds 		delta3 = delta2 - state->last_delta2;
6081da177e4SLinus Torvalds 		state->last_delta2 = delta2;
6091da177e4SLinus Torvalds 
6101da177e4SLinus Torvalds 		if (delta < 0)
6111da177e4SLinus Torvalds 			delta = -delta;
6121da177e4SLinus Torvalds 		if (delta2 < 0)
6131da177e4SLinus Torvalds 			delta2 = -delta2;
6141da177e4SLinus Torvalds 		if (delta3 < 0)
6151da177e4SLinus Torvalds 			delta3 = -delta3;
6161da177e4SLinus Torvalds 		if (delta > delta2)
6171da177e4SLinus Torvalds 			delta = delta2;
6181da177e4SLinus Torvalds 		if (delta > delta3)
6191da177e4SLinus Torvalds 			delta = delta3;
6201da177e4SLinus Torvalds 
6211da177e4SLinus Torvalds 		/*
6221da177e4SLinus Torvalds 		 * delta is now minimum absolute delta.
6231da177e4SLinus Torvalds 		 * Round down by 1 bit on general principles,
6241da177e4SLinus Torvalds 		 * and limit entropy entimate to 12 bits.
6251da177e4SLinus Torvalds 		 */
626adc782daSMatt Mackall 		credit_entropy_bits(&input_pool,
6271da177e4SLinus Torvalds 				    min_t(int, fls(delta>>1), 11));
6281da177e4SLinus Torvalds 	}
6291da177e4SLinus Torvalds out:
6301da177e4SLinus Torvalds 	preempt_enable();
6311da177e4SLinus Torvalds }
6321da177e4SLinus Torvalds 
633d251575aSStephen Hemminger void add_input_randomness(unsigned int type, unsigned int code,
6341da177e4SLinus Torvalds 				 unsigned int value)
6351da177e4SLinus Torvalds {
6361da177e4SLinus Torvalds 	static unsigned char last_value;
6371da177e4SLinus Torvalds 
6381da177e4SLinus Torvalds 	/* ignore autorepeat and the like */
6391da177e4SLinus Torvalds 	if (value == last_value)
6401da177e4SLinus Torvalds 		return;
6411da177e4SLinus Torvalds 
6421da177e4SLinus Torvalds 	DEBUG_ENT("input event\n");
6431da177e4SLinus Torvalds 	last_value = value;
6441da177e4SLinus Torvalds 	add_timer_randomness(&input_timer_state,
6451da177e4SLinus Torvalds 			     (type << 4) ^ code ^ (code >> 4) ^ value);
6461da177e4SLinus Torvalds }
64780fc9f53SDmitry Torokhov EXPORT_SYMBOL_GPL(add_input_randomness);
6481da177e4SLinus Torvalds 
6491da177e4SLinus Torvalds void add_interrupt_randomness(int irq)
6501da177e4SLinus Torvalds {
651c80544dcSStephen Hemminger 	if (irq >= NR_IRQS || irq_timer_state[irq] == NULL)
6521da177e4SLinus Torvalds 		return;
6531da177e4SLinus Torvalds 
6541da177e4SLinus Torvalds 	DEBUG_ENT("irq event %d\n", irq);
6551da177e4SLinus Torvalds 	add_timer_randomness(irq_timer_state[irq], 0x100 + irq);
6561da177e4SLinus Torvalds }
6571da177e4SLinus Torvalds 
6589361401eSDavid Howells #ifdef CONFIG_BLOCK
6591da177e4SLinus Torvalds void add_disk_randomness(struct gendisk *disk)
6601da177e4SLinus Torvalds {
6611da177e4SLinus Torvalds 	if (!disk || !disk->random)
6621da177e4SLinus Torvalds 		return;
6631da177e4SLinus Torvalds 	/* first major is 1, so we get >= 0x200 here */
664*f331c029STejun Heo 	DEBUG_ENT("disk event %d:%d\n",
665*f331c029STejun Heo 		  MAJOR(disk_devt(disk)), MINOR(disk_devt(disk)));
6661da177e4SLinus Torvalds 
667*f331c029STejun Heo 	add_timer_randomness(disk->random, 0x100 + disk_devt(disk));
6681da177e4SLinus Torvalds }
6699361401eSDavid Howells #endif
6701da177e4SLinus Torvalds 
6711da177e4SLinus Torvalds #define EXTRACT_SIZE 10
6721da177e4SLinus Torvalds 
6731da177e4SLinus Torvalds /*********************************************************************
6741da177e4SLinus Torvalds  *
6751da177e4SLinus Torvalds  * Entropy extraction routines
6761da177e4SLinus Torvalds  *
6771da177e4SLinus Torvalds  *********************************************************************/
6781da177e4SLinus Torvalds 
6791da177e4SLinus Torvalds static ssize_t extract_entropy(struct entropy_store *r, void *buf,
6801da177e4SLinus Torvalds 			       size_t nbytes, int min, int rsvd);
6811da177e4SLinus Torvalds 
6821da177e4SLinus Torvalds /*
6831da177e4SLinus Torvalds  * This utility inline function is responsible for transfering entropy
6841da177e4SLinus Torvalds  * from the primary pool to the secondary extraction pool. We make
6851da177e4SLinus Torvalds  * sure we pull enough for a 'catastrophic reseed'.
6861da177e4SLinus Torvalds  */
6871da177e4SLinus Torvalds static void xfer_secondary_pool(struct entropy_store *r, size_t nbytes)
6881da177e4SLinus Torvalds {
6891da177e4SLinus Torvalds 	__u32 tmp[OUTPUT_POOL_WORDS];
6901da177e4SLinus Torvalds 
6911da177e4SLinus Torvalds 	if (r->pull && r->entropy_count < nbytes * 8 &&
6921da177e4SLinus Torvalds 	    r->entropy_count < r->poolinfo->POOLBITS) {
6935a021e9fSMatt Mackall 		/* If we're limited, always leave two wakeup worth's BITS */
6941da177e4SLinus Torvalds 		int rsvd = r->limit ? 0 : random_read_wakeup_thresh/4;
6955a021e9fSMatt Mackall 		int bytes = nbytes;
6965a021e9fSMatt Mackall 
6975a021e9fSMatt Mackall 		/* pull at least as many as BYTES as wakeup BITS */
6985a021e9fSMatt Mackall 		bytes = max_t(int, bytes, random_read_wakeup_thresh / 8);
6995a021e9fSMatt Mackall 		/* but never more than the buffer size */
7005a021e9fSMatt Mackall 		bytes = min_t(int, bytes, sizeof(tmp));
7011da177e4SLinus Torvalds 
7021da177e4SLinus Torvalds 		DEBUG_ENT("going to reseed %s with %d bits "
7031da177e4SLinus Torvalds 			  "(%d of %d requested)\n",
7041da177e4SLinus Torvalds 			  r->name, bytes * 8, nbytes * 8, r->entropy_count);
7051da177e4SLinus Torvalds 
7061da177e4SLinus Torvalds 		bytes = extract_entropy(r->pull, tmp, bytes,
7071da177e4SLinus Torvalds 					random_read_wakeup_thresh / 8, rsvd);
708e68e5b66SMatt Mackall 		mix_pool_bytes(r, tmp, bytes);
709adc782daSMatt Mackall 		credit_entropy_bits(r, bytes*8);
7101da177e4SLinus Torvalds 	}
7111da177e4SLinus Torvalds }
7121da177e4SLinus Torvalds 
7131da177e4SLinus Torvalds /*
7141da177e4SLinus Torvalds  * These functions extracts randomness from the "entropy pool", and
7151da177e4SLinus Torvalds  * returns it in a buffer.
7161da177e4SLinus Torvalds  *
7171da177e4SLinus Torvalds  * The min parameter specifies the minimum amount we can pull before
7181da177e4SLinus Torvalds  * failing to avoid races that defeat catastrophic reseeding while the
7191da177e4SLinus Torvalds  * reserved parameter indicates how much entropy we must leave in the
7201da177e4SLinus Torvalds  * pool after each pull to avoid starving other readers.
7211da177e4SLinus Torvalds  *
7221da177e4SLinus Torvalds  * Note: extract_entropy() assumes that .poolwords is a multiple of 16 words.
7231da177e4SLinus Torvalds  */
7241da177e4SLinus Torvalds 
7251da177e4SLinus Torvalds static size_t account(struct entropy_store *r, size_t nbytes, int min,
7261da177e4SLinus Torvalds 		      int reserved)
7271da177e4SLinus Torvalds {
7281da177e4SLinus Torvalds 	unsigned long flags;
7291da177e4SLinus Torvalds 
7301da177e4SLinus Torvalds 	BUG_ON(r->entropy_count > r->poolinfo->POOLBITS);
7311da177e4SLinus Torvalds 
7321da177e4SLinus Torvalds 	/* Hold lock while accounting */
7331da177e4SLinus Torvalds 	spin_lock_irqsave(&r->lock, flags);
7341da177e4SLinus Torvalds 
7351da177e4SLinus Torvalds 	DEBUG_ENT("trying to extract %d bits from %s\n",
7361da177e4SLinus Torvalds 		  nbytes * 8, r->name);
7371da177e4SLinus Torvalds 
7381da177e4SLinus Torvalds 	/* Can we pull enough? */
7391da177e4SLinus Torvalds 	if (r->entropy_count / 8 < min + reserved) {
7401da177e4SLinus Torvalds 		nbytes = 0;
7411da177e4SLinus Torvalds 	} else {
7421da177e4SLinus Torvalds 		/* If limited, never pull more than available */
7431da177e4SLinus Torvalds 		if (r->limit && nbytes + reserved >= r->entropy_count / 8)
7441da177e4SLinus Torvalds 			nbytes = r->entropy_count/8 - reserved;
7451da177e4SLinus Torvalds 
7461da177e4SLinus Torvalds 		if (r->entropy_count / 8 >= nbytes + reserved)
7471da177e4SLinus Torvalds 			r->entropy_count -= nbytes*8;
7481da177e4SLinus Torvalds 		else
7491da177e4SLinus Torvalds 			r->entropy_count = reserved;
7501da177e4SLinus Torvalds 
7519a6f70bbSJeff Dike 		if (r->entropy_count < random_write_wakeup_thresh) {
7521da177e4SLinus Torvalds 			wake_up_interruptible(&random_write_wait);
7539a6f70bbSJeff Dike 			kill_fasync(&fasync, SIGIO, POLL_OUT);
7549a6f70bbSJeff Dike 		}
7551da177e4SLinus Torvalds 	}
7561da177e4SLinus Torvalds 
7571da177e4SLinus Torvalds 	DEBUG_ENT("debiting %d entropy credits from %s%s\n",
7581da177e4SLinus Torvalds 		  nbytes * 8, r->name, r->limit ? "" : " (unlimited)");
7591da177e4SLinus Torvalds 
7601da177e4SLinus Torvalds 	spin_unlock_irqrestore(&r->lock, flags);
7611da177e4SLinus Torvalds 
7621da177e4SLinus Torvalds 	return nbytes;
7631da177e4SLinus Torvalds }
7641da177e4SLinus Torvalds 
7651da177e4SLinus Torvalds static void extract_buf(struct entropy_store *r, __u8 *out)
7661da177e4SLinus Torvalds {
767602b6aeeSMatt Mackall 	int i;
768e68e5b66SMatt Mackall 	__u32 hash[5], workspace[SHA_WORKSPACE_WORDS];
769e68e5b66SMatt Mackall 	__u8 extract[64];
7701da177e4SLinus Torvalds 
7711c0ad3d4SMatt Mackall 	/* Generate a hash across the pool, 16 words (512 bits) at a time */
772ffd8d3faSMatt Mackall 	sha_init(hash);
7731c0ad3d4SMatt Mackall 	for (i = 0; i < r->poolinfo->poolwords; i += 16)
774ffd8d3faSMatt Mackall 		sha_transform(hash, (__u8 *)(r->pool + i), workspace);
7751da177e4SLinus Torvalds 
7761da177e4SLinus Torvalds 	/*
7771c0ad3d4SMatt Mackall 	 * We mix the hash back into the pool to prevent backtracking
7781c0ad3d4SMatt Mackall 	 * attacks (where the attacker knows the state of the pool
7791c0ad3d4SMatt Mackall 	 * plus the current outputs, and attempts to find previous
7801c0ad3d4SMatt Mackall 	 * ouputs), unless the hash function can be inverted. By
7811c0ad3d4SMatt Mackall 	 * mixing at least a SHA1 worth of hash data back, we make
7821c0ad3d4SMatt Mackall 	 * brute-forcing the feedback as hard as brute-forcing the
7831c0ad3d4SMatt Mackall 	 * hash.
7841da177e4SLinus Torvalds 	 */
785e68e5b66SMatt Mackall 	mix_pool_bytes_extract(r, hash, sizeof(hash), extract);
7861c0ad3d4SMatt Mackall 
7871c0ad3d4SMatt Mackall 	/*
7881c0ad3d4SMatt Mackall 	 * To avoid duplicates, we atomically extract a portion of the
7891c0ad3d4SMatt Mackall 	 * pool while mixing, and hash one final time.
7901c0ad3d4SMatt Mackall 	 */
791e68e5b66SMatt Mackall 	sha_transform(hash, extract, workspace);
792ffd8d3faSMatt Mackall 	memset(extract, 0, sizeof(extract));
793ffd8d3faSMatt Mackall 	memset(workspace, 0, sizeof(workspace));
7941da177e4SLinus Torvalds 
7951da177e4SLinus Torvalds 	/*
7961c0ad3d4SMatt Mackall 	 * In case the hash function has some recognizable output
7971c0ad3d4SMatt Mackall 	 * pattern, we fold it in half. Thus, we always feed back
7981c0ad3d4SMatt Mackall 	 * twice as much data as we output.
7991da177e4SLinus Torvalds 	 */
800ffd8d3faSMatt Mackall 	hash[0] ^= hash[3];
801ffd8d3faSMatt Mackall 	hash[1] ^= hash[4];
802ffd8d3faSMatt Mackall 	hash[2] ^= rol32(hash[2], 16);
803ffd8d3faSMatt Mackall 	memcpy(out, hash, EXTRACT_SIZE);
804ffd8d3faSMatt Mackall 	memset(hash, 0, sizeof(hash));
8051da177e4SLinus Torvalds }
8061da177e4SLinus Torvalds 
8071da177e4SLinus Torvalds static ssize_t extract_entropy(struct entropy_store *r, void *buf,
8081da177e4SLinus Torvalds 			       size_t nbytes, int min, int reserved)
8091da177e4SLinus Torvalds {
8101da177e4SLinus Torvalds 	ssize_t ret = 0, i;
8111da177e4SLinus Torvalds 	__u8 tmp[EXTRACT_SIZE];
8121da177e4SLinus Torvalds 
8131da177e4SLinus Torvalds 	xfer_secondary_pool(r, nbytes);
8141da177e4SLinus Torvalds 	nbytes = account(r, nbytes, min, reserved);
8151da177e4SLinus Torvalds 
8161da177e4SLinus Torvalds 	while (nbytes) {
8171da177e4SLinus Torvalds 		extract_buf(r, tmp);
8181da177e4SLinus Torvalds 		i = min_t(int, nbytes, EXTRACT_SIZE);
8191da177e4SLinus Torvalds 		memcpy(buf, tmp, i);
8201da177e4SLinus Torvalds 		nbytes -= i;
8211da177e4SLinus Torvalds 		buf += i;
8221da177e4SLinus Torvalds 		ret += i;
8231da177e4SLinus Torvalds 	}
8241da177e4SLinus Torvalds 
8251da177e4SLinus Torvalds 	/* Wipe data just returned from memory */
8261da177e4SLinus Torvalds 	memset(tmp, 0, sizeof(tmp));
8271da177e4SLinus Torvalds 
8281da177e4SLinus Torvalds 	return ret;
8291da177e4SLinus Torvalds }
8301da177e4SLinus Torvalds 
8311da177e4SLinus Torvalds static ssize_t extract_entropy_user(struct entropy_store *r, void __user *buf,
8321da177e4SLinus Torvalds 				    size_t nbytes)
8331da177e4SLinus Torvalds {
8341da177e4SLinus Torvalds 	ssize_t ret = 0, i;
8351da177e4SLinus Torvalds 	__u8 tmp[EXTRACT_SIZE];
8361da177e4SLinus Torvalds 
8371da177e4SLinus Torvalds 	xfer_secondary_pool(r, nbytes);
8381da177e4SLinus Torvalds 	nbytes = account(r, nbytes, 0, 0);
8391da177e4SLinus Torvalds 
8401da177e4SLinus Torvalds 	while (nbytes) {
8411da177e4SLinus Torvalds 		if (need_resched()) {
8421da177e4SLinus Torvalds 			if (signal_pending(current)) {
8431da177e4SLinus Torvalds 				if (ret == 0)
8441da177e4SLinus Torvalds 					ret = -ERESTARTSYS;
8451da177e4SLinus Torvalds 				break;
8461da177e4SLinus Torvalds 			}
8471da177e4SLinus Torvalds 			schedule();
8481da177e4SLinus Torvalds 		}
8491da177e4SLinus Torvalds 
8501da177e4SLinus Torvalds 		extract_buf(r, tmp);
8511da177e4SLinus Torvalds 		i = min_t(int, nbytes, EXTRACT_SIZE);
8521da177e4SLinus Torvalds 		if (copy_to_user(buf, tmp, i)) {
8531da177e4SLinus Torvalds 			ret = -EFAULT;
8541da177e4SLinus Torvalds 			break;
8551da177e4SLinus Torvalds 		}
8561da177e4SLinus Torvalds 
8571da177e4SLinus Torvalds 		nbytes -= i;
8581da177e4SLinus Torvalds 		buf += i;
8591da177e4SLinus Torvalds 		ret += i;
8601da177e4SLinus Torvalds 	}
8611da177e4SLinus Torvalds 
8621da177e4SLinus Torvalds 	/* Wipe data just returned from memory */
8631da177e4SLinus Torvalds 	memset(tmp, 0, sizeof(tmp));
8641da177e4SLinus Torvalds 
8651da177e4SLinus Torvalds 	return ret;
8661da177e4SLinus Torvalds }
8671da177e4SLinus Torvalds 
8681da177e4SLinus Torvalds /*
8691da177e4SLinus Torvalds  * This function is the exported kernel interface.  It returns some
8701da177e4SLinus Torvalds  * number of good random numbers, suitable for seeding TCP sequence
8711da177e4SLinus Torvalds  * numbers, etc.
8721da177e4SLinus Torvalds  */
8731da177e4SLinus Torvalds void get_random_bytes(void *buf, int nbytes)
8741da177e4SLinus Torvalds {
8751da177e4SLinus Torvalds 	extract_entropy(&nonblocking_pool, buf, nbytes, 0, 0);
8761da177e4SLinus Torvalds }
8771da177e4SLinus Torvalds EXPORT_SYMBOL(get_random_bytes);
8781da177e4SLinus Torvalds 
8791da177e4SLinus Torvalds /*
8801da177e4SLinus Torvalds  * init_std_data - initialize pool with system data
8811da177e4SLinus Torvalds  *
8821da177e4SLinus Torvalds  * @r: pool to initialize
8831da177e4SLinus Torvalds  *
8841da177e4SLinus Torvalds  * This function clears the pool's entropy count and mixes some system
8851da177e4SLinus Torvalds  * data into the pool to prepare it for use. The pool is not cleared
8861da177e4SLinus Torvalds  * as that can only decrease the entropy in the pool.
8871da177e4SLinus Torvalds  */
8881da177e4SLinus Torvalds static void init_std_data(struct entropy_store *r)
8891da177e4SLinus Torvalds {
890f8595815SEric Dumazet 	ktime_t now;
8911da177e4SLinus Torvalds 	unsigned long flags;
8921da177e4SLinus Torvalds 
8931da177e4SLinus Torvalds 	spin_lock_irqsave(&r->lock, flags);
8941da177e4SLinus Torvalds 	r->entropy_count = 0;
8951da177e4SLinus Torvalds 	spin_unlock_irqrestore(&r->lock, flags);
8961da177e4SLinus Torvalds 
897f8595815SEric Dumazet 	now = ktime_get_real();
898e68e5b66SMatt Mackall 	mix_pool_bytes(r, &now, sizeof(now));
899e68e5b66SMatt Mackall 	mix_pool_bytes(r, utsname(), sizeof(*(utsname())));
9001da177e4SLinus Torvalds }
9011da177e4SLinus Torvalds 
90253c3f63eSMatt Mackall static int rand_initialize(void)
9031da177e4SLinus Torvalds {
9041da177e4SLinus Torvalds 	init_std_data(&input_pool);
9051da177e4SLinus Torvalds 	init_std_data(&blocking_pool);
9061da177e4SLinus Torvalds 	init_std_data(&nonblocking_pool);
9071da177e4SLinus Torvalds 	return 0;
9081da177e4SLinus Torvalds }
9091da177e4SLinus Torvalds module_init(rand_initialize);
9101da177e4SLinus Torvalds 
9111da177e4SLinus Torvalds void rand_initialize_irq(int irq)
9121da177e4SLinus Torvalds {
9131da177e4SLinus Torvalds 	struct timer_rand_state *state;
9141da177e4SLinus Torvalds 
9151da177e4SLinus Torvalds 	if (irq >= NR_IRQS || irq_timer_state[irq])
9161da177e4SLinus Torvalds 		return;
9171da177e4SLinus Torvalds 
9181da177e4SLinus Torvalds 	/*
919f8595815SEric Dumazet 	 * If kzalloc returns null, we just won't use that entropy
9201da177e4SLinus Torvalds 	 * source.
9211da177e4SLinus Torvalds 	 */
922f8595815SEric Dumazet 	state = kzalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
923f8595815SEric Dumazet 	if (state)
9241da177e4SLinus Torvalds 		irq_timer_state[irq] = state;
9251da177e4SLinus Torvalds }
9261da177e4SLinus Torvalds 
9279361401eSDavid Howells #ifdef CONFIG_BLOCK
9281da177e4SLinus Torvalds void rand_initialize_disk(struct gendisk *disk)
9291da177e4SLinus Torvalds {
9301da177e4SLinus Torvalds 	struct timer_rand_state *state;
9311da177e4SLinus Torvalds 
9321da177e4SLinus Torvalds 	/*
933f8595815SEric Dumazet 	 * If kzalloc returns null, we just won't use that entropy
9341da177e4SLinus Torvalds 	 * source.
9351da177e4SLinus Torvalds 	 */
936f8595815SEric Dumazet 	state = kzalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
937f8595815SEric Dumazet 	if (state)
9381da177e4SLinus Torvalds 		disk->random = state;
9391da177e4SLinus Torvalds }
9409361401eSDavid Howells #endif
9411da177e4SLinus Torvalds 
9421da177e4SLinus Torvalds static ssize_t
9431da177e4SLinus Torvalds random_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
9441da177e4SLinus Torvalds {
9451da177e4SLinus Torvalds 	ssize_t n, retval = 0, count = 0;
9461da177e4SLinus Torvalds 
9471da177e4SLinus Torvalds 	if (nbytes == 0)
9481da177e4SLinus Torvalds 		return 0;
9491da177e4SLinus Torvalds 
9501da177e4SLinus Torvalds 	while (nbytes > 0) {
9511da177e4SLinus Torvalds 		n = nbytes;
9521da177e4SLinus Torvalds 		if (n > SEC_XFER_SIZE)
9531da177e4SLinus Torvalds 			n = SEC_XFER_SIZE;
9541da177e4SLinus Torvalds 
9551da177e4SLinus Torvalds 		DEBUG_ENT("reading %d bits\n", n*8);
9561da177e4SLinus Torvalds 
9571da177e4SLinus Torvalds 		n = extract_entropy_user(&blocking_pool, buf, n);
9581da177e4SLinus Torvalds 
9591da177e4SLinus Torvalds 		DEBUG_ENT("read got %d bits (%d still needed)\n",
9601da177e4SLinus Torvalds 			  n*8, (nbytes-n)*8);
9611da177e4SLinus Torvalds 
9621da177e4SLinus Torvalds 		if (n == 0) {
9631da177e4SLinus Torvalds 			if (file->f_flags & O_NONBLOCK) {
9641da177e4SLinus Torvalds 				retval = -EAGAIN;
9651da177e4SLinus Torvalds 				break;
9661da177e4SLinus Torvalds 			}
9671da177e4SLinus Torvalds 
9681da177e4SLinus Torvalds 			DEBUG_ENT("sleeping?\n");
9691da177e4SLinus Torvalds 
9701da177e4SLinus Torvalds 			wait_event_interruptible(random_read_wait,
9711da177e4SLinus Torvalds 				input_pool.entropy_count >=
9721da177e4SLinus Torvalds 						 random_read_wakeup_thresh);
9731da177e4SLinus Torvalds 
9741da177e4SLinus Torvalds 			DEBUG_ENT("awake\n");
9751da177e4SLinus Torvalds 
9761da177e4SLinus Torvalds 			if (signal_pending(current)) {
9771da177e4SLinus Torvalds 				retval = -ERESTARTSYS;
9781da177e4SLinus Torvalds 				break;
9791da177e4SLinus Torvalds 			}
9801da177e4SLinus Torvalds 
9811da177e4SLinus Torvalds 			continue;
9821da177e4SLinus Torvalds 		}
9831da177e4SLinus Torvalds 
9841da177e4SLinus Torvalds 		if (n < 0) {
9851da177e4SLinus Torvalds 			retval = n;
9861da177e4SLinus Torvalds 			break;
9871da177e4SLinus Torvalds 		}
9881da177e4SLinus Torvalds 		count += n;
9891da177e4SLinus Torvalds 		buf += n;
9901da177e4SLinus Torvalds 		nbytes -= n;
9911da177e4SLinus Torvalds 		break;		/* This break makes the device work */
9921da177e4SLinus Torvalds 				/* like a named pipe */
9931da177e4SLinus Torvalds 	}
9941da177e4SLinus Torvalds 
9951da177e4SLinus Torvalds 	/*
9961da177e4SLinus Torvalds 	 * If we gave the user some bytes, update the access time.
9971da177e4SLinus Torvalds 	 */
9981da177e4SLinus Torvalds 	if (count)
9991da177e4SLinus Torvalds 		file_accessed(file);
10001da177e4SLinus Torvalds 
10011da177e4SLinus Torvalds 	return (count ? count : retval);
10021da177e4SLinus Torvalds }
10031da177e4SLinus Torvalds 
10041da177e4SLinus Torvalds static ssize_t
100590b75ee5SMatt Mackall urandom_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
10061da177e4SLinus Torvalds {
10071da177e4SLinus Torvalds 	return extract_entropy_user(&nonblocking_pool, buf, nbytes);
10081da177e4SLinus Torvalds }
10091da177e4SLinus Torvalds 
10101da177e4SLinus Torvalds static unsigned int
10111da177e4SLinus Torvalds random_poll(struct file *file, poll_table * wait)
10121da177e4SLinus Torvalds {
10131da177e4SLinus Torvalds 	unsigned int mask;
10141da177e4SLinus Torvalds 
10151da177e4SLinus Torvalds 	poll_wait(file, &random_read_wait, wait);
10161da177e4SLinus Torvalds 	poll_wait(file, &random_write_wait, wait);
10171da177e4SLinus Torvalds 	mask = 0;
10181da177e4SLinus Torvalds 	if (input_pool.entropy_count >= random_read_wakeup_thresh)
10191da177e4SLinus Torvalds 		mask |= POLLIN | POLLRDNORM;
10201da177e4SLinus Torvalds 	if (input_pool.entropy_count < random_write_wakeup_thresh)
10211da177e4SLinus Torvalds 		mask |= POLLOUT | POLLWRNORM;
10221da177e4SLinus Torvalds 	return mask;
10231da177e4SLinus Torvalds }
10241da177e4SLinus Torvalds 
10257f397dcdSMatt Mackall static int
10267f397dcdSMatt Mackall write_pool(struct entropy_store *r, const char __user *buffer, size_t count)
10277f397dcdSMatt Mackall {
10287f397dcdSMatt Mackall 	size_t bytes;
10297f397dcdSMatt Mackall 	__u32 buf[16];
10307f397dcdSMatt Mackall 	const char __user *p = buffer;
10317f397dcdSMatt Mackall 
10327f397dcdSMatt Mackall 	while (count > 0) {
10337f397dcdSMatt Mackall 		bytes = min(count, sizeof(buf));
10347f397dcdSMatt Mackall 		if (copy_from_user(&buf, p, bytes))
10357f397dcdSMatt Mackall 			return -EFAULT;
10367f397dcdSMatt Mackall 
10377f397dcdSMatt Mackall 		count -= bytes;
10387f397dcdSMatt Mackall 		p += bytes;
10397f397dcdSMatt Mackall 
1040e68e5b66SMatt Mackall 		mix_pool_bytes(r, buf, bytes);
104191f3f1e3SMatt Mackall 		cond_resched();
10427f397dcdSMatt Mackall 	}
10437f397dcdSMatt Mackall 
10447f397dcdSMatt Mackall 	return 0;
10457f397dcdSMatt Mackall }
10467f397dcdSMatt Mackall 
104790b75ee5SMatt Mackall static ssize_t random_write(struct file *file, const char __user *buffer,
10481da177e4SLinus Torvalds 			    size_t count, loff_t *ppos)
10491da177e4SLinus Torvalds {
10507f397dcdSMatt Mackall 	size_t ret;
1051a7113a96SJosef Sipek 	struct inode *inode = file->f_path.dentry->d_inode;
10527f397dcdSMatt Mackall 
10537f397dcdSMatt Mackall 	ret = write_pool(&blocking_pool, buffer, count);
10547f397dcdSMatt Mackall 	if (ret)
10557f397dcdSMatt Mackall 		return ret;
10567f397dcdSMatt Mackall 	ret = write_pool(&nonblocking_pool, buffer, count);
10577f397dcdSMatt Mackall 	if (ret)
10587f397dcdSMatt Mackall 		return ret;
10597f397dcdSMatt Mackall 
10601da177e4SLinus Torvalds 	inode->i_mtime = current_fs_time(inode->i_sb);
10611da177e4SLinus Torvalds 	mark_inode_dirty(inode);
10627f397dcdSMatt Mackall 	return (ssize_t)count;
10631da177e4SLinus Torvalds }
10641da177e4SLinus Torvalds 
106543ae4860SMatt Mackall static long random_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
10661da177e4SLinus Torvalds {
10671da177e4SLinus Torvalds 	int size, ent_count;
10681da177e4SLinus Torvalds 	int __user *p = (int __user *)arg;
10691da177e4SLinus Torvalds 	int retval;
10701da177e4SLinus Torvalds 
10711da177e4SLinus Torvalds 	switch (cmd) {
10721da177e4SLinus Torvalds 	case RNDGETENTCNT:
107343ae4860SMatt Mackall 		/* inherently racy, no point locking */
107443ae4860SMatt Mackall 		if (put_user(input_pool.entropy_count, p))
10751da177e4SLinus Torvalds 			return -EFAULT;
10761da177e4SLinus Torvalds 		return 0;
10771da177e4SLinus Torvalds 	case RNDADDTOENTCNT:
10781da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
10791da177e4SLinus Torvalds 			return -EPERM;
10801da177e4SLinus Torvalds 		if (get_user(ent_count, p))
10811da177e4SLinus Torvalds 			return -EFAULT;
1082adc782daSMatt Mackall 		credit_entropy_bits(&input_pool, ent_count);
10831da177e4SLinus Torvalds 		return 0;
10841da177e4SLinus Torvalds 	case RNDADDENTROPY:
10851da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
10861da177e4SLinus Torvalds 			return -EPERM;
10871da177e4SLinus Torvalds 		if (get_user(ent_count, p++))
10881da177e4SLinus Torvalds 			return -EFAULT;
10891da177e4SLinus Torvalds 		if (ent_count < 0)
10901da177e4SLinus Torvalds 			return -EINVAL;
10911da177e4SLinus Torvalds 		if (get_user(size, p++))
10921da177e4SLinus Torvalds 			return -EFAULT;
10937f397dcdSMatt Mackall 		retval = write_pool(&input_pool, (const char __user *)p,
10947f397dcdSMatt Mackall 				    size);
10951da177e4SLinus Torvalds 		if (retval < 0)
10961da177e4SLinus Torvalds 			return retval;
1097adc782daSMatt Mackall 		credit_entropy_bits(&input_pool, ent_count);
10981da177e4SLinus Torvalds 		return 0;
10991da177e4SLinus Torvalds 	case RNDZAPENTCNT:
11001da177e4SLinus Torvalds 	case RNDCLEARPOOL:
11011da177e4SLinus Torvalds 		/* Clear the entropy pool counters. */
11021da177e4SLinus Torvalds 		if (!capable(CAP_SYS_ADMIN))
11031da177e4SLinus Torvalds 			return -EPERM;
110453c3f63eSMatt Mackall 		rand_initialize();
11051da177e4SLinus Torvalds 		return 0;
11061da177e4SLinus Torvalds 	default:
11071da177e4SLinus Torvalds 		return -EINVAL;
11081da177e4SLinus Torvalds 	}
11091da177e4SLinus Torvalds }
11101da177e4SLinus Torvalds 
11119a6f70bbSJeff Dike static int random_fasync(int fd, struct file *filp, int on)
11129a6f70bbSJeff Dike {
11139a6f70bbSJeff Dike 	return fasync_helper(fd, filp, on, &fasync);
11149a6f70bbSJeff Dike }
11159a6f70bbSJeff Dike 
11169a6f70bbSJeff Dike static int random_release(struct inode *inode, struct file *filp)
11179a6f70bbSJeff Dike {
11189a6f70bbSJeff Dike 	return fasync_helper(-1, filp, 0, &fasync);
11199a6f70bbSJeff Dike }
11209a6f70bbSJeff Dike 
11212b8693c0SArjan van de Ven const struct file_operations random_fops = {
11221da177e4SLinus Torvalds 	.read  = random_read,
11231da177e4SLinus Torvalds 	.write = random_write,
11241da177e4SLinus Torvalds 	.poll  = random_poll,
112543ae4860SMatt Mackall 	.unlocked_ioctl = random_ioctl,
11269a6f70bbSJeff Dike 	.fasync = random_fasync,
11279a6f70bbSJeff Dike 	.release = random_release,
11281da177e4SLinus Torvalds };
11291da177e4SLinus Torvalds 
11302b8693c0SArjan van de Ven const struct file_operations urandom_fops = {
11311da177e4SLinus Torvalds 	.read  = urandom_read,
11321da177e4SLinus Torvalds 	.write = random_write,
113343ae4860SMatt Mackall 	.unlocked_ioctl = random_ioctl,
11349a6f70bbSJeff Dike 	.fasync = random_fasync,
11359a6f70bbSJeff Dike 	.release = random_release,
11361da177e4SLinus Torvalds };
11371da177e4SLinus Torvalds 
11381da177e4SLinus Torvalds /***************************************************************
11391da177e4SLinus Torvalds  * Random UUID interface
11401da177e4SLinus Torvalds  *
11411da177e4SLinus Torvalds  * Used here for a Boot ID, but can be useful for other kernel
11421da177e4SLinus Torvalds  * drivers.
11431da177e4SLinus Torvalds  ***************************************************************/
11441da177e4SLinus Torvalds 
11451da177e4SLinus Torvalds /*
11461da177e4SLinus Torvalds  * Generate random UUID
11471da177e4SLinus Torvalds  */
11481da177e4SLinus Torvalds void generate_random_uuid(unsigned char uuid_out[16])
11491da177e4SLinus Torvalds {
11501da177e4SLinus Torvalds 	get_random_bytes(uuid_out, 16);
11511da177e4SLinus Torvalds 	/* Set UUID version to 4 --- truely random generation */
11521da177e4SLinus Torvalds 	uuid_out[6] = (uuid_out[6] & 0x0F) | 0x40;
11531da177e4SLinus Torvalds 	/* Set the UUID variant to DCE */
11541da177e4SLinus Torvalds 	uuid_out[8] = (uuid_out[8] & 0x3F) | 0x80;
11551da177e4SLinus Torvalds }
11561da177e4SLinus Torvalds EXPORT_SYMBOL(generate_random_uuid);
11571da177e4SLinus Torvalds 
11581da177e4SLinus Torvalds /********************************************************************
11591da177e4SLinus Torvalds  *
11601da177e4SLinus Torvalds  * Sysctl interface
11611da177e4SLinus Torvalds  *
11621da177e4SLinus Torvalds  ********************************************************************/
11631da177e4SLinus Torvalds 
11641da177e4SLinus Torvalds #ifdef CONFIG_SYSCTL
11651da177e4SLinus Torvalds 
11661da177e4SLinus Torvalds #include <linux/sysctl.h>
11671da177e4SLinus Torvalds 
11681da177e4SLinus Torvalds static int min_read_thresh = 8, min_write_thresh;
11691da177e4SLinus Torvalds static int max_read_thresh = INPUT_POOL_WORDS * 32;
11701da177e4SLinus Torvalds static int max_write_thresh = INPUT_POOL_WORDS * 32;
11711da177e4SLinus Torvalds static char sysctl_bootid[16];
11721da177e4SLinus Torvalds 
11731da177e4SLinus Torvalds /*
11741da177e4SLinus Torvalds  * These functions is used to return both the bootid UUID, and random
11751da177e4SLinus Torvalds  * UUID.  The difference is in whether table->data is NULL; if it is,
11761da177e4SLinus Torvalds  * then a new UUID is generated and returned to the user.
11771da177e4SLinus Torvalds  *
11781da177e4SLinus Torvalds  * If the user accesses this via the proc interface, it will be returned
11791da177e4SLinus Torvalds  * as an ASCII string in the standard UUID format.  If accesses via the
11801da177e4SLinus Torvalds  * sysctl system call, it is returned as 16 bytes of binary data.
11811da177e4SLinus Torvalds  */
11821da177e4SLinus Torvalds static int proc_do_uuid(ctl_table *table, int write, struct file *filp,
11831da177e4SLinus Torvalds 			void __user *buffer, size_t *lenp, loff_t *ppos)
11841da177e4SLinus Torvalds {
11851da177e4SLinus Torvalds 	ctl_table fake_table;
11861da177e4SLinus Torvalds 	unsigned char buf[64], tmp_uuid[16], *uuid;
11871da177e4SLinus Torvalds 
11881da177e4SLinus Torvalds 	uuid = table->data;
11891da177e4SLinus Torvalds 	if (!uuid) {
11901da177e4SLinus Torvalds 		uuid = tmp_uuid;
11911da177e4SLinus Torvalds 		uuid[8] = 0;
11921da177e4SLinus Torvalds 	}
11931da177e4SLinus Torvalds 	if (uuid[8] == 0)
11941da177e4SLinus Torvalds 		generate_random_uuid(uuid);
11951da177e4SLinus Torvalds 
11961da177e4SLinus Torvalds 	sprintf(buf, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
11971da177e4SLinus Torvalds 		"%02x%02x%02x%02x%02x%02x",
11981da177e4SLinus Torvalds 		uuid[0],  uuid[1],  uuid[2],  uuid[3],
11991da177e4SLinus Torvalds 		uuid[4],  uuid[5],  uuid[6],  uuid[7],
12001da177e4SLinus Torvalds 		uuid[8],  uuid[9],  uuid[10], uuid[11],
12011da177e4SLinus Torvalds 		uuid[12], uuid[13], uuid[14], uuid[15]);
12021da177e4SLinus Torvalds 	fake_table.data = buf;
12031da177e4SLinus Torvalds 	fake_table.maxlen = sizeof(buf);
12041da177e4SLinus Torvalds 
12051da177e4SLinus Torvalds 	return proc_dostring(&fake_table, write, filp, buffer, lenp, ppos);
12061da177e4SLinus Torvalds }
12071da177e4SLinus Torvalds 
12081da177e4SLinus Torvalds static int uuid_strategy(ctl_table *table, int __user *name, int nlen,
12091da177e4SLinus Torvalds 			 void __user *oldval, size_t __user *oldlenp,
12101f29bcd7SAlexey Dobriyan 			 void __user *newval, size_t newlen)
12111da177e4SLinus Torvalds {
12121da177e4SLinus Torvalds 	unsigned char tmp_uuid[16], *uuid;
12131da177e4SLinus Torvalds 	unsigned int len;
12141da177e4SLinus Torvalds 
12151da177e4SLinus Torvalds 	if (!oldval || !oldlenp)
12161da177e4SLinus Torvalds 		return 1;
12171da177e4SLinus Torvalds 
12181da177e4SLinus Torvalds 	uuid = table->data;
12191da177e4SLinus Torvalds 	if (!uuid) {
12201da177e4SLinus Torvalds 		uuid = tmp_uuid;
12211da177e4SLinus Torvalds 		uuid[8] = 0;
12221da177e4SLinus Torvalds 	}
12231da177e4SLinus Torvalds 	if (uuid[8] == 0)
12241da177e4SLinus Torvalds 		generate_random_uuid(uuid);
12251da177e4SLinus Torvalds 
12261da177e4SLinus Torvalds 	if (get_user(len, oldlenp))
12271da177e4SLinus Torvalds 		return -EFAULT;
12281da177e4SLinus Torvalds 	if (len) {
12291da177e4SLinus Torvalds 		if (len > 16)
12301da177e4SLinus Torvalds 			len = 16;
12311da177e4SLinus Torvalds 		if (copy_to_user(oldval, uuid, len) ||
12321da177e4SLinus Torvalds 		    put_user(len, oldlenp))
12331da177e4SLinus Torvalds 			return -EFAULT;
12341da177e4SLinus Torvalds 	}
12351da177e4SLinus Torvalds 	return 1;
12361da177e4SLinus Torvalds }
12371da177e4SLinus Torvalds 
12381da177e4SLinus Torvalds static int sysctl_poolsize = INPUT_POOL_WORDS * 32;
12391da177e4SLinus Torvalds ctl_table random_table[] = {
12401da177e4SLinus Torvalds 	{
12411da177e4SLinus Torvalds 		.ctl_name 	= RANDOM_POOLSIZE,
12421da177e4SLinus Torvalds 		.procname	= "poolsize",
12431da177e4SLinus Torvalds 		.data		= &sysctl_poolsize,
12441da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
12451da177e4SLinus Torvalds 		.mode		= 0444,
12461da177e4SLinus Torvalds 		.proc_handler	= &proc_dointvec,
12471da177e4SLinus Torvalds 	},
12481da177e4SLinus Torvalds 	{
12491da177e4SLinus Torvalds 		.ctl_name	= RANDOM_ENTROPY_COUNT,
12501da177e4SLinus Torvalds 		.procname	= "entropy_avail",
12511da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
12521da177e4SLinus Torvalds 		.mode		= 0444,
12531da177e4SLinus Torvalds 		.proc_handler	= &proc_dointvec,
12541da177e4SLinus Torvalds 		.data		= &input_pool.entropy_count,
12551da177e4SLinus Torvalds 	},
12561da177e4SLinus Torvalds 	{
12571da177e4SLinus Torvalds 		.ctl_name	= RANDOM_READ_THRESH,
12581da177e4SLinus Torvalds 		.procname	= "read_wakeup_threshold",
12591da177e4SLinus Torvalds 		.data		= &random_read_wakeup_thresh,
12601da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
12611da177e4SLinus Torvalds 		.mode		= 0644,
12621da177e4SLinus Torvalds 		.proc_handler	= &proc_dointvec_minmax,
12631da177e4SLinus Torvalds 		.strategy	= &sysctl_intvec,
12641da177e4SLinus Torvalds 		.extra1		= &min_read_thresh,
12651da177e4SLinus Torvalds 		.extra2		= &max_read_thresh,
12661da177e4SLinus Torvalds 	},
12671da177e4SLinus Torvalds 	{
12681da177e4SLinus Torvalds 		.ctl_name	= RANDOM_WRITE_THRESH,
12691da177e4SLinus Torvalds 		.procname	= "write_wakeup_threshold",
12701da177e4SLinus Torvalds 		.data		= &random_write_wakeup_thresh,
12711da177e4SLinus Torvalds 		.maxlen		= sizeof(int),
12721da177e4SLinus Torvalds 		.mode		= 0644,
12731da177e4SLinus Torvalds 		.proc_handler	= &proc_dointvec_minmax,
12741da177e4SLinus Torvalds 		.strategy	= &sysctl_intvec,
12751da177e4SLinus Torvalds 		.extra1		= &min_write_thresh,
12761da177e4SLinus Torvalds 		.extra2		= &max_write_thresh,
12771da177e4SLinus Torvalds 	},
12781da177e4SLinus Torvalds 	{
12791da177e4SLinus Torvalds 		.ctl_name	= RANDOM_BOOT_ID,
12801da177e4SLinus Torvalds 		.procname	= "boot_id",
12811da177e4SLinus Torvalds 		.data		= &sysctl_bootid,
12821da177e4SLinus Torvalds 		.maxlen		= 16,
12831da177e4SLinus Torvalds 		.mode		= 0444,
12841da177e4SLinus Torvalds 		.proc_handler	= &proc_do_uuid,
12851da177e4SLinus Torvalds 		.strategy	= &uuid_strategy,
12861da177e4SLinus Torvalds 	},
12871da177e4SLinus Torvalds 	{
12881da177e4SLinus Torvalds 		.ctl_name	= RANDOM_UUID,
12891da177e4SLinus Torvalds 		.procname	= "uuid",
12901da177e4SLinus Torvalds 		.maxlen		= 16,
12911da177e4SLinus Torvalds 		.mode		= 0444,
12921da177e4SLinus Torvalds 		.proc_handler	= &proc_do_uuid,
12931da177e4SLinus Torvalds 		.strategy	= &uuid_strategy,
12941da177e4SLinus Torvalds 	},
12951da177e4SLinus Torvalds 	{ .ctl_name = 0 }
12961da177e4SLinus Torvalds };
12971da177e4SLinus Torvalds #endif 	/* CONFIG_SYSCTL */
12981da177e4SLinus Torvalds 
12991da177e4SLinus Torvalds /********************************************************************
13001da177e4SLinus Torvalds  *
13011da177e4SLinus Torvalds  * Random funtions for networking
13021da177e4SLinus Torvalds  *
13031da177e4SLinus Torvalds  ********************************************************************/
13041da177e4SLinus Torvalds 
13051da177e4SLinus Torvalds /*
13061da177e4SLinus Torvalds  * TCP initial sequence number picking.  This uses the random number
13071da177e4SLinus Torvalds  * generator to pick an initial secret value.  This value is hashed
13081da177e4SLinus Torvalds  * along with the TCP endpoint information to provide a unique
13091da177e4SLinus Torvalds  * starting point for each pair of TCP endpoints.  This defeats
13101da177e4SLinus Torvalds  * attacks which rely on guessing the initial TCP sequence number.
13111da177e4SLinus Torvalds  * This algorithm was suggested by Steve Bellovin.
13121da177e4SLinus Torvalds  *
13131da177e4SLinus Torvalds  * Using a very strong hash was taking an appreciable amount of the total
13141da177e4SLinus Torvalds  * TCP connection establishment time, so this is a weaker hash,
13151da177e4SLinus Torvalds  * compensated for by changing the secret periodically.
13161da177e4SLinus Torvalds  */
13171da177e4SLinus Torvalds 
13181da177e4SLinus Torvalds /* F, G and H are basic MD4 functions: selection, majority, parity */
13191da177e4SLinus Torvalds #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
13201da177e4SLinus Torvalds #define G(x, y, z) (((x) & (y)) + (((x) ^ (y)) & (z)))
13211da177e4SLinus Torvalds #define H(x, y, z) ((x) ^ (y) ^ (z))
13221da177e4SLinus Torvalds 
13231da177e4SLinus Torvalds /*
13241da177e4SLinus Torvalds  * The generic round function.  The application is so specific that
13251da177e4SLinus Torvalds  * we don't bother protecting all the arguments with parens, as is generally
13261da177e4SLinus Torvalds  * good macro practice, in favor of extra legibility.
13271da177e4SLinus Torvalds  * Rotation is separate from addition to prevent recomputation
13281da177e4SLinus Torvalds  */
13291da177e4SLinus Torvalds #define ROUND(f, a, b, c, d, x, s)	\
13301da177e4SLinus Torvalds 	(a += f(b, c, d) + x, a = (a << s) | (a >> (32 - s)))
13311da177e4SLinus Torvalds #define K1 0
13321da177e4SLinus Torvalds #define K2 013240474631UL
13331da177e4SLinus Torvalds #define K3 015666365641UL
13341da177e4SLinus Torvalds 
13351da177e4SLinus Torvalds #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
13361da177e4SLinus Torvalds 
13371da177e4SLinus Torvalds static __u32 twothirdsMD4Transform(__u32 const buf[4], __u32 const in[12])
13381da177e4SLinus Torvalds {
13391da177e4SLinus Torvalds 	__u32 a = buf[0], b = buf[1], c = buf[2], d = buf[3];
13401da177e4SLinus Torvalds 
13411da177e4SLinus Torvalds 	/* Round 1 */
13421da177e4SLinus Torvalds 	ROUND(F, a, b, c, d, in[ 0] + K1,  3);
13431da177e4SLinus Torvalds 	ROUND(F, d, a, b, c, in[ 1] + K1,  7);
13441da177e4SLinus Torvalds 	ROUND(F, c, d, a, b, in[ 2] + K1, 11);
13451da177e4SLinus Torvalds 	ROUND(F, b, c, d, a, in[ 3] + K1, 19);
13461da177e4SLinus Torvalds 	ROUND(F, a, b, c, d, in[ 4] + K1,  3);
13471da177e4SLinus Torvalds 	ROUND(F, d, a, b, c, in[ 5] + K1,  7);
13481da177e4SLinus Torvalds 	ROUND(F, c, d, a, b, in[ 6] + K1, 11);
13491da177e4SLinus Torvalds 	ROUND(F, b, c, d, a, in[ 7] + K1, 19);
13501da177e4SLinus Torvalds 	ROUND(F, a, b, c, d, in[ 8] + K1,  3);
13511da177e4SLinus Torvalds 	ROUND(F, d, a, b, c, in[ 9] + K1,  7);
13521da177e4SLinus Torvalds 	ROUND(F, c, d, a, b, in[10] + K1, 11);
13531da177e4SLinus Torvalds 	ROUND(F, b, c, d, a, in[11] + K1, 19);
13541da177e4SLinus Torvalds 
13551da177e4SLinus Torvalds 	/* Round 2 */
13561da177e4SLinus Torvalds 	ROUND(G, a, b, c, d, in[ 1] + K2,  3);
13571da177e4SLinus Torvalds 	ROUND(G, d, a, b, c, in[ 3] + K2,  5);
13581da177e4SLinus Torvalds 	ROUND(G, c, d, a, b, in[ 5] + K2,  9);
13591da177e4SLinus Torvalds 	ROUND(G, b, c, d, a, in[ 7] + K2, 13);
13601da177e4SLinus Torvalds 	ROUND(G, a, b, c, d, in[ 9] + K2,  3);
13611da177e4SLinus Torvalds 	ROUND(G, d, a, b, c, in[11] + K2,  5);
13621da177e4SLinus Torvalds 	ROUND(G, c, d, a, b, in[ 0] + K2,  9);
13631da177e4SLinus Torvalds 	ROUND(G, b, c, d, a, in[ 2] + K2, 13);
13641da177e4SLinus Torvalds 	ROUND(G, a, b, c, d, in[ 4] + K2,  3);
13651da177e4SLinus Torvalds 	ROUND(G, d, a, b, c, in[ 6] + K2,  5);
13661da177e4SLinus Torvalds 	ROUND(G, c, d, a, b, in[ 8] + K2,  9);
13671da177e4SLinus Torvalds 	ROUND(G, b, c, d, a, in[10] + K2, 13);
13681da177e4SLinus Torvalds 
13691da177e4SLinus Torvalds 	/* Round 3 */
13701da177e4SLinus Torvalds 	ROUND(H, a, b, c, d, in[ 3] + K3,  3);
13711da177e4SLinus Torvalds 	ROUND(H, d, a, b, c, in[ 7] + K3,  9);
13721da177e4SLinus Torvalds 	ROUND(H, c, d, a, b, in[11] + K3, 11);
13731da177e4SLinus Torvalds 	ROUND(H, b, c, d, a, in[ 2] + K3, 15);
13741da177e4SLinus Torvalds 	ROUND(H, a, b, c, d, in[ 6] + K3,  3);
13751da177e4SLinus Torvalds 	ROUND(H, d, a, b, c, in[10] + K3,  9);
13761da177e4SLinus Torvalds 	ROUND(H, c, d, a, b, in[ 1] + K3, 11);
13771da177e4SLinus Torvalds 	ROUND(H, b, c, d, a, in[ 5] + K3, 15);
13781da177e4SLinus Torvalds 	ROUND(H, a, b, c, d, in[ 9] + K3,  3);
13791da177e4SLinus Torvalds 	ROUND(H, d, a, b, c, in[ 0] + K3,  9);
13801da177e4SLinus Torvalds 	ROUND(H, c, d, a, b, in[ 4] + K3, 11);
13811da177e4SLinus Torvalds 	ROUND(H, b, c, d, a, in[ 8] + K3, 15);
13821da177e4SLinus Torvalds 
13831da177e4SLinus Torvalds 	return buf[1] + b; /* "most hashed" word */
13841da177e4SLinus Torvalds 	/* Alternative: return sum of all words? */
13851da177e4SLinus Torvalds }
13861da177e4SLinus Torvalds #endif
13871da177e4SLinus Torvalds 
13881da177e4SLinus Torvalds #undef ROUND
13891da177e4SLinus Torvalds #undef F
13901da177e4SLinus Torvalds #undef G
13911da177e4SLinus Torvalds #undef H
13921da177e4SLinus Torvalds #undef K1
13931da177e4SLinus Torvalds #undef K2
13941da177e4SLinus Torvalds #undef K3
13951da177e4SLinus Torvalds 
13961da177e4SLinus Torvalds /* This should not be decreased so low that ISNs wrap too fast. */
13971da177e4SLinus Torvalds #define REKEY_INTERVAL (300 * HZ)
13981da177e4SLinus Torvalds /*
13991da177e4SLinus Torvalds  * Bit layout of the tcp sequence numbers (before adding current time):
14001da177e4SLinus Torvalds  * bit 24-31: increased after every key exchange
14011da177e4SLinus Torvalds  * bit 0-23: hash(source,dest)
14021da177e4SLinus Torvalds  *
14031da177e4SLinus Torvalds  * The implementation is similar to the algorithm described
14041da177e4SLinus Torvalds  * in the Appendix of RFC 1185, except that
14051da177e4SLinus Torvalds  * - it uses a 1 MHz clock instead of a 250 kHz clock
14061da177e4SLinus Torvalds  * - it performs a rekey every 5 minutes, which is equivalent
14071da177e4SLinus Torvalds  * 	to a (source,dest) tulple dependent forward jump of the
14081da177e4SLinus Torvalds  * 	clock by 0..2^(HASH_BITS+1)
14091da177e4SLinus Torvalds  *
14101da177e4SLinus Torvalds  * Thus the average ISN wraparound time is 68 minutes instead of
14111da177e4SLinus Torvalds  * 4.55 hours.
14121da177e4SLinus Torvalds  *
14131da177e4SLinus Torvalds  * SMP cleanup and lock avoidance with poor man's RCU.
14141da177e4SLinus Torvalds  * 			Manfred Spraul <manfred@colorfullife.com>
14151da177e4SLinus Torvalds  *
14161da177e4SLinus Torvalds  */
14171da177e4SLinus Torvalds #define COUNT_BITS 8
14181da177e4SLinus Torvalds #define COUNT_MASK ((1 << COUNT_BITS) - 1)
14191da177e4SLinus Torvalds #define HASH_BITS 24
14201da177e4SLinus Torvalds #define HASH_MASK ((1 << HASH_BITS) - 1)
14211da177e4SLinus Torvalds 
14221da177e4SLinus Torvalds static struct keydata {
14231da177e4SLinus Torvalds 	__u32 count; /* already shifted to the final position */
14241da177e4SLinus Torvalds 	__u32 secret[12];
14251da177e4SLinus Torvalds } ____cacheline_aligned ip_keydata[2];
14261da177e4SLinus Torvalds 
14271da177e4SLinus Torvalds static unsigned int ip_cnt;
14281da177e4SLinus Torvalds 
142965f27f38SDavid Howells static void rekey_seq_generator(struct work_struct *work);
14301da177e4SLinus Torvalds 
143165f27f38SDavid Howells static DECLARE_DELAYED_WORK(rekey_work, rekey_seq_generator);
14321da177e4SLinus Torvalds 
14331da177e4SLinus Torvalds /*
14341da177e4SLinus Torvalds  * Lock avoidance:
14351da177e4SLinus Torvalds  * The ISN generation runs lockless - it's just a hash over random data.
14361da177e4SLinus Torvalds  * State changes happen every 5 minutes when the random key is replaced.
14371da177e4SLinus Torvalds  * Synchronization is performed by having two copies of the hash function
14381da177e4SLinus Torvalds  * state and rekey_seq_generator always updates the inactive copy.
14391da177e4SLinus Torvalds  * The copy is then activated by updating ip_cnt.
14401da177e4SLinus Torvalds  * The implementation breaks down if someone blocks the thread
14411da177e4SLinus Torvalds  * that processes SYN requests for more than 5 minutes. Should never
14421da177e4SLinus Torvalds  * happen, and even if that happens only a not perfectly compliant
14431da177e4SLinus Torvalds  * ISN is generated, nothing fatal.
14441da177e4SLinus Torvalds  */
144565f27f38SDavid Howells static void rekey_seq_generator(struct work_struct *work)
14461da177e4SLinus Torvalds {
14471da177e4SLinus Torvalds 	struct keydata *keyptr = &ip_keydata[1 ^ (ip_cnt & 1)];
14481da177e4SLinus Torvalds 
14491da177e4SLinus Torvalds 	get_random_bytes(keyptr->secret, sizeof(keyptr->secret));
14501da177e4SLinus Torvalds 	keyptr->count = (ip_cnt & COUNT_MASK) << HASH_BITS;
14511da177e4SLinus Torvalds 	smp_wmb();
14521da177e4SLinus Torvalds 	ip_cnt++;
14531da177e4SLinus Torvalds 	schedule_delayed_work(&rekey_work, REKEY_INTERVAL);
14541da177e4SLinus Torvalds }
14551da177e4SLinus Torvalds 
14561da177e4SLinus Torvalds static inline struct keydata *get_keyptr(void)
14571da177e4SLinus Torvalds {
14581da177e4SLinus Torvalds 	struct keydata *keyptr = &ip_keydata[ip_cnt & 1];
14591da177e4SLinus Torvalds 
14601da177e4SLinus Torvalds 	smp_rmb();
14611da177e4SLinus Torvalds 
14621da177e4SLinus Torvalds 	return keyptr;
14631da177e4SLinus Torvalds }
14641da177e4SLinus Torvalds 
14651da177e4SLinus Torvalds static __init int seqgen_init(void)
14661da177e4SLinus Torvalds {
14671da177e4SLinus Torvalds 	rekey_seq_generator(NULL);
14681da177e4SLinus Torvalds 	return 0;
14691da177e4SLinus Torvalds }
14701da177e4SLinus Torvalds late_initcall(seqgen_init);
14711da177e4SLinus Torvalds 
14721da177e4SLinus Torvalds #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
1473b09b845cSAl Viro __u32 secure_tcpv6_sequence_number(__be32 *saddr, __be32 *daddr,
1474b09b845cSAl Viro 				   __be16 sport, __be16 dport)
14751da177e4SLinus Torvalds {
14761da177e4SLinus Torvalds 	__u32 seq;
14771da177e4SLinus Torvalds 	__u32 hash[12];
14781da177e4SLinus Torvalds 	struct keydata *keyptr = get_keyptr();
14791da177e4SLinus Torvalds 
14801da177e4SLinus Torvalds 	/* The procedure is the same as for IPv4, but addresses are longer.
14811da177e4SLinus Torvalds 	 * Thus we must use twothirdsMD4Transform.
14821da177e4SLinus Torvalds 	 */
14831da177e4SLinus Torvalds 
14841da177e4SLinus Torvalds 	memcpy(hash, saddr, 16);
1485b09b845cSAl Viro 	hash[4] = ((__force u16)sport << 16) + (__force u16)dport;
14861da177e4SLinus Torvalds 	memcpy(&hash[5], keyptr->secret, sizeof(__u32) * 7);
14871da177e4SLinus Torvalds 
1488b09b845cSAl Viro 	seq = twothirdsMD4Transform((const __u32 *)daddr, hash) & HASH_MASK;
14891da177e4SLinus Torvalds 	seq += keyptr->count;
14901da177e4SLinus Torvalds 
14916dd10a62SEric Dumazet 	seq += ktime_to_ns(ktime_get_real());
14921da177e4SLinus Torvalds 
14931da177e4SLinus Torvalds 	return seq;
14941da177e4SLinus Torvalds }
14951da177e4SLinus Torvalds EXPORT_SYMBOL(secure_tcpv6_sequence_number);
14961da177e4SLinus Torvalds #endif
14971da177e4SLinus Torvalds 
14981da177e4SLinus Torvalds /*  The code below is shamelessly stolen from secure_tcp_sequence_number().
14991da177e4SLinus Torvalds  *  All blames to Andrey V. Savochkin <saw@msu.ru>.
15001da177e4SLinus Torvalds  */
1501b09b845cSAl Viro __u32 secure_ip_id(__be32 daddr)
15021da177e4SLinus Torvalds {
15031da177e4SLinus Torvalds 	struct keydata *keyptr;
15041da177e4SLinus Torvalds 	__u32 hash[4];
15051da177e4SLinus Torvalds 
15061da177e4SLinus Torvalds 	keyptr = get_keyptr();
15071da177e4SLinus Torvalds 
15081da177e4SLinus Torvalds 	/*
15091da177e4SLinus Torvalds 	 *  Pick a unique starting offset for each IP destination.
15101da177e4SLinus Torvalds 	 *  The dest ip address is placed in the starting vector,
15111da177e4SLinus Torvalds 	 *  which is then hashed with random data.
15121da177e4SLinus Torvalds 	 */
1513b09b845cSAl Viro 	hash[0] = (__force __u32)daddr;
15141da177e4SLinus Torvalds 	hash[1] = keyptr->secret[9];
15151da177e4SLinus Torvalds 	hash[2] = keyptr->secret[10];
15161da177e4SLinus Torvalds 	hash[3] = keyptr->secret[11];
15171da177e4SLinus Torvalds 
15181da177e4SLinus Torvalds 	return half_md4_transform(hash, keyptr->secret);
15191da177e4SLinus Torvalds }
15201da177e4SLinus Torvalds 
15211da177e4SLinus Torvalds #ifdef CONFIG_INET
15221da177e4SLinus Torvalds 
1523b09b845cSAl Viro __u32 secure_tcp_sequence_number(__be32 saddr, __be32 daddr,
1524b09b845cSAl Viro 				 __be16 sport, __be16 dport)
15251da177e4SLinus Torvalds {
15261da177e4SLinus Torvalds 	__u32 seq;
15271da177e4SLinus Torvalds 	__u32 hash[4];
15281da177e4SLinus Torvalds 	struct keydata *keyptr = get_keyptr();
15291da177e4SLinus Torvalds 
15301da177e4SLinus Torvalds 	/*
15311da177e4SLinus Torvalds 	 *  Pick a unique starting offset for each TCP connection endpoints
15321da177e4SLinus Torvalds 	 *  (saddr, daddr, sport, dport).
15331da177e4SLinus Torvalds 	 *  Note that the words are placed into the starting vector, which is
15341da177e4SLinus Torvalds 	 *  then mixed with a partial MD4 over random data.
15351da177e4SLinus Torvalds 	 */
1536b09b845cSAl Viro 	hash[0] = (__force u32)saddr;
1537b09b845cSAl Viro 	hash[1] = (__force u32)daddr;
1538b09b845cSAl Viro 	hash[2] = ((__force u16)sport << 16) + (__force u16)dport;
15391da177e4SLinus Torvalds 	hash[3] = keyptr->secret[11];
15401da177e4SLinus Torvalds 
15411da177e4SLinus Torvalds 	seq = half_md4_transform(hash, keyptr->secret) & HASH_MASK;
15421da177e4SLinus Torvalds 	seq += keyptr->count;
15431da177e4SLinus Torvalds 	/*
15441da177e4SLinus Torvalds 	 *	As close as possible to RFC 793, which
15451da177e4SLinus Torvalds 	 *	suggests using a 250 kHz clock.
15461da177e4SLinus Torvalds 	 *	Further reading shows this assumes 2 Mb/s networks.
15479b42c336SEric Dumazet 	 *	For 10 Mb/s Ethernet, a 1 MHz clock is appropriate.
15489b42c336SEric Dumazet 	 *	For 10 Gb/s Ethernet, a 1 GHz clock should be ok, but
15499b42c336SEric Dumazet 	 *	we also need to limit the resolution so that the u32 seq
15509b42c336SEric Dumazet 	 *	overlaps less than one time per MSL (2 minutes).
15519b42c336SEric Dumazet 	 *	Choosing a clock of 64 ns period is OK. (period of 274 s)
15521da177e4SLinus Torvalds 	 */
15536dd10a62SEric Dumazet 	seq += ktime_to_ns(ktime_get_real()) >> 6;
155490b75ee5SMatt Mackall 
15551da177e4SLinus Torvalds 	return seq;
15561da177e4SLinus Torvalds }
15571da177e4SLinus Torvalds 
1558a7f5e7f1SArnaldo Carvalho de Melo /* Generate secure starting point for ephemeral IPV4 transport port search */
1559b09b845cSAl Viro u32 secure_ipv4_port_ephemeral(__be32 saddr, __be32 daddr, __be16 dport)
15601da177e4SLinus Torvalds {
15611da177e4SLinus Torvalds 	struct keydata *keyptr = get_keyptr();
15621da177e4SLinus Torvalds 	u32 hash[4];
15631da177e4SLinus Torvalds 
15641da177e4SLinus Torvalds 	/*
15651da177e4SLinus Torvalds 	 *  Pick a unique starting offset for each ephemeral port search
15661da177e4SLinus Torvalds 	 *  (saddr, daddr, dport) and 48bits of random data.
15671da177e4SLinus Torvalds 	 */
1568b09b845cSAl Viro 	hash[0] = (__force u32)saddr;
1569b09b845cSAl Viro 	hash[1] = (__force u32)daddr;
1570b09b845cSAl Viro 	hash[2] = (__force u32)dport ^ keyptr->secret[10];
15711da177e4SLinus Torvalds 	hash[3] = keyptr->secret[11];
15721da177e4SLinus Torvalds 
15731da177e4SLinus Torvalds 	return half_md4_transform(hash, keyptr->secret);
15741da177e4SLinus Torvalds }
15759f593653SStephen Hemminger EXPORT_SYMBOL_GPL(secure_ipv4_port_ephemeral);
15761da177e4SLinus Torvalds 
15771da177e4SLinus Torvalds #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
157890b75ee5SMatt Mackall u32 secure_ipv6_port_ephemeral(const __be32 *saddr, const __be32 *daddr,
157990b75ee5SMatt Mackall 			       __be16 dport)
15801da177e4SLinus Torvalds {
15811da177e4SLinus Torvalds 	struct keydata *keyptr = get_keyptr();
15821da177e4SLinus Torvalds 	u32 hash[12];
15831da177e4SLinus Torvalds 
15841da177e4SLinus Torvalds 	memcpy(hash, saddr, 16);
1585b09b845cSAl Viro 	hash[4] = (__force u32)dport;
15861da177e4SLinus Torvalds 	memcpy(&hash[5], keyptr->secret, sizeof(__u32) * 7);
15871da177e4SLinus Torvalds 
1588b09b845cSAl Viro 	return twothirdsMD4Transform((const __u32 *)daddr, hash);
15891da177e4SLinus Torvalds }
15901da177e4SLinus Torvalds #endif
15911da177e4SLinus Torvalds 
1592c4365c92SArnaldo Carvalho de Melo #if defined(CONFIG_IP_DCCP) || defined(CONFIG_IP_DCCP_MODULE)
1593c4365c92SArnaldo Carvalho de Melo /* Similar to secure_tcp_sequence_number but generate a 48 bit value
1594c4365c92SArnaldo Carvalho de Melo  * bit's 32-47 increase every key exchange
1595c4365c92SArnaldo Carvalho de Melo  *       0-31  hash(source, dest)
1596c4365c92SArnaldo Carvalho de Melo  */
1597b09b845cSAl Viro u64 secure_dccp_sequence_number(__be32 saddr, __be32 daddr,
1598b09b845cSAl Viro 				__be16 sport, __be16 dport)
1599c4365c92SArnaldo Carvalho de Melo {
1600c4365c92SArnaldo Carvalho de Melo 	u64 seq;
1601c4365c92SArnaldo Carvalho de Melo 	__u32 hash[4];
1602c4365c92SArnaldo Carvalho de Melo 	struct keydata *keyptr = get_keyptr();
1603c4365c92SArnaldo Carvalho de Melo 
1604b09b845cSAl Viro 	hash[0] = (__force u32)saddr;
1605b09b845cSAl Viro 	hash[1] = (__force u32)daddr;
1606b09b845cSAl Viro 	hash[2] = ((__force u16)sport << 16) + (__force u16)dport;
1607c4365c92SArnaldo Carvalho de Melo 	hash[3] = keyptr->secret[11];
1608c4365c92SArnaldo Carvalho de Melo 
1609c4365c92SArnaldo Carvalho de Melo 	seq = half_md4_transform(hash, keyptr->secret);
1610c4365c92SArnaldo Carvalho de Melo 	seq |= ((u64)keyptr->count) << (32 - HASH_BITS);
1611c4365c92SArnaldo Carvalho de Melo 
16126dd10a62SEric Dumazet 	seq += ktime_to_ns(ktime_get_real());
1613c4365c92SArnaldo Carvalho de Melo 	seq &= (1ull << 48) - 1;
161490b75ee5SMatt Mackall 
1615c4365c92SArnaldo Carvalho de Melo 	return seq;
1616c4365c92SArnaldo Carvalho de Melo }
1617c4365c92SArnaldo Carvalho de Melo EXPORT_SYMBOL(secure_dccp_sequence_number);
1618c4365c92SArnaldo Carvalho de Melo #endif
1619c4365c92SArnaldo Carvalho de Melo 
16201da177e4SLinus Torvalds #endif /* CONFIG_INET */
16211da177e4SLinus Torvalds 
16221da177e4SLinus Torvalds 
16231da177e4SLinus Torvalds /*
16241da177e4SLinus Torvalds  * Get a random word for internal kernel use only. Similar to urandom but
16251da177e4SLinus Torvalds  * with the goal of minimal entropy pool depletion. As a result, the random
16261da177e4SLinus Torvalds  * value is not cryptographically secure but for several uses the cost of
16271da177e4SLinus Torvalds  * depleting entropy is too high
16281da177e4SLinus Torvalds  */
16291da177e4SLinus Torvalds unsigned int get_random_int(void)
16301da177e4SLinus Torvalds {
16311da177e4SLinus Torvalds 	/*
16321da177e4SLinus Torvalds 	 * Use IP's RNG. It suits our purpose perfectly: it re-keys itself
16331da177e4SLinus Torvalds 	 * every second, from the entropy pool (and thus creates a limited
16341da177e4SLinus Torvalds 	 * drain on it), and uses halfMD4Transform within the second. We
16351da177e4SLinus Torvalds 	 * also mix it with jiffies and the PID:
16361da177e4SLinus Torvalds 	 */
1637b09b845cSAl Viro 	return secure_ip_id((__force __be32)(current->pid + jiffies));
16381da177e4SLinus Torvalds }
16391da177e4SLinus Torvalds 
16401da177e4SLinus Torvalds /*
16411da177e4SLinus Torvalds  * randomize_range() returns a start address such that
16421da177e4SLinus Torvalds  *
16431da177e4SLinus Torvalds  *    [...... <range> .....]
16441da177e4SLinus Torvalds  *  start                  end
16451da177e4SLinus Torvalds  *
16461da177e4SLinus Torvalds  * a <range> with size "len" starting at the return value is inside in the
16471da177e4SLinus Torvalds  * area defined by [start, end], but is otherwise randomized.
16481da177e4SLinus Torvalds  */
16491da177e4SLinus Torvalds unsigned long
16501da177e4SLinus Torvalds randomize_range(unsigned long start, unsigned long end, unsigned long len)
16511da177e4SLinus Torvalds {
16521da177e4SLinus Torvalds 	unsigned long range = end - len - start;
16531da177e4SLinus Torvalds 
16541da177e4SLinus Torvalds 	if (end <= start + len)
16551da177e4SLinus Torvalds 		return 0;
16561da177e4SLinus Torvalds 	return PAGE_ALIGN(get_random_int() % range + start);
16571da177e4SLinus Torvalds }
1658