random.c 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480
  1. /*
  2. * random.c -- A strong random number generator
  3. *
  4. * Copyright Matt Mackall <mpm@selenic.com>, 2003, 2004, 2005
  5. *
  6. * Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999. All
  7. * rights reserved.
  8. *
  9. * Redistribution and use in source and binary forms, with or without
  10. * modification, are permitted provided that the following conditions
  11. * are met:
  12. * 1. Redistributions of source code must retain the above copyright
  13. * notice, and the entire permission notice in its entirety,
  14. * including the disclaimer of warranties.
  15. * 2. Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in the
  17. * documentation and/or other materials provided with the distribution.
  18. * 3. The name of the author may not be used to endorse or promote
  19. * products derived from this software without specific prior
  20. * written permission.
  21. *
  22. * ALTERNATIVELY, this product may be distributed under the terms of
  23. * the GNU General Public License, in which case the provisions of the GPL are
  24. * required INSTEAD OF the above restrictions. (This clause is
  25. * necessary due to a potential bad interaction between the GPL and
  26. * the restrictions contained in a BSD-style copyright.)
  27. *
  28. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
  29. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  30. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
  31. * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
  32. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  33. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
  34. * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  35. * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  36. * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  37. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  38. * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
  39. * DAMAGE.
  40. */
  41. /*
  42. * (now, with legal B.S. out of the way.....)
  43. *
  44. * This routine gathers environmental noise from device drivers, etc.,
  45. * and returns good random numbers, suitable for cryptographic use.
  46. * Besides the obvious cryptographic uses, these numbers are also good
  47. * for seeding TCP sequence numbers, and other places where it is
  48. * desirable to have numbers which are not only random, but hard to
  49. * predict by an attacker.
  50. *
  51. * Theory of operation
  52. * ===================
  53. *
  54. * Computers are very predictable devices. Hence it is extremely hard
  55. * to produce truly random numbers on a computer --- as opposed to
  56. * pseudo-random numbers, which can easily generated by using a
  57. * algorithm. Unfortunately, it is very easy for attackers to guess
  58. * the sequence of pseudo-random number generators, and for some
  59. * applications this is not acceptable. So instead, we must try to
  60. * gather "environmental noise" from the computer's environment, which
  61. * must be hard for outside attackers to observe, and use that to
  62. * generate random numbers. In a Unix environment, this is best done
  63. * from inside the kernel.
  64. *
  65. * Sources of randomness from the environment include inter-keyboard
  66. * timings, inter-interrupt timings from some interrupts, and other
  67. * events which are both (a) non-deterministic and (b) hard for an
  68. * outside observer to measure. Randomness from these sources are
  69. * added to an "entropy pool", which is mixed using a CRC-like function.
  70. * This is not cryptographically strong, but it is adequate assuming
  71. * the randomness is not chosen maliciously, and it is fast enough that
  72. * the overhead of doing it on every interrupt is very reasonable.
  73. * As random bytes are mixed into the entropy pool, the routines keep
  74. * an *estimate* of how many bits of randomness have been stored into
  75. * the random number generator's internal state.
  76. *
  77. * When random bytes are desired, they are obtained by taking the SHA
  78. * hash of the contents of the "entropy pool". The SHA hash avoids
  79. * exposing the internal state of the entropy pool. It is believed to
  80. * be computationally infeasible to derive any useful information
  81. * about the input of SHA from its output. Even if it is possible to
  82. * analyze SHA in some clever way, as long as the amount of data
  83. * returned from the generator is less than the inherent entropy in
  84. * the pool, the output data is totally unpredictable. For this
  85. * reason, the routine decreases its internal estimate of how many
  86. * bits of "true randomness" are contained in the entropy pool as it
  87. * outputs random numbers.
  88. *
  89. * If this estimate goes to zero, the routine can still generate
  90. * random numbers; however, an attacker may (at least in theory) be
  91. * able to infer the future output of the generator from prior
  92. * outputs. This requires successful cryptanalysis of SHA, which is
  93. * not believed to be feasible, but there is a remote possibility.
  94. * Nonetheless, these numbers should be useful for the vast majority
  95. * of purposes.
  96. *
  97. * Exported interfaces ---- output
  98. * ===============================
  99. *
  100. * There are three exported interfaces; the first is one designed to
  101. * be used from within the kernel:
  102. *
  103. * void get_random_bytes(void *buf, int nbytes);
  104. *
  105. * This interface will return the requested number of random bytes,
  106. * and place it in the requested buffer.
  107. *
  108. * The two other interfaces are two character devices /dev/random and
  109. * /dev/urandom. /dev/random is suitable for use when very high
  110. * quality randomness is desired (for example, for key generation or
  111. * one-time pads), as it will only return a maximum of the number of
  112. * bits of randomness (as estimated by the random number generator)
  113. * contained in the entropy pool.
  114. *
  115. * The /dev/urandom device does not have this limit, and will return
  116. * as many bytes as are requested. As more and more random bytes are
  117. * requested without giving time for the entropy pool to recharge,
  118. * this will result in random numbers that are merely cryptographically
  119. * strong. For many applications, however, this is acceptable.
  120. *
  121. * Exported interfaces ---- input
  122. * ==============================
  123. *
  124. * The current exported interfaces for gathering environmental noise
  125. * from the devices are:
  126. *
  127. * void add_device_randomness(const void *buf, unsigned int size);
  128. * void add_input_randomness(unsigned int type, unsigned int code,
  129. * unsigned int value);
  130. * void add_interrupt_randomness(int irq, int irq_flags);
  131. * void add_disk_randomness(struct gendisk *disk);
  132. *
  133. * add_device_randomness() is for adding data to the random pool that
  134. * is likely to differ between two devices (or possibly even per boot).
  135. * This would be things like MAC addresses or serial numbers, or the
  136. * read-out of the RTC. This does *not* add any actual entropy to the
  137. * pool, but it initializes the pool to different values for devices
  138. * that might otherwise be identical and have very little entropy
  139. * available to them (particularly common in the embedded world).
  140. *
  141. * add_input_randomness() uses the input layer interrupt timing, as well as
  142. * the event type information from the hardware.
  143. *
  144. * add_interrupt_randomness() uses the interrupt timing as random
  145. * inputs to the entropy pool. Using the cycle counters and the irq source
  146. * as inputs, it feeds the randomness roughly once a second.
  147. *
  148. * add_disk_randomness() uses what amounts to the seek time of block
  149. * layer request events, on a per-disk_devt basis, as input to the
  150. * entropy pool. Note that high-speed solid state drives with very low
  151. * seek times do not make for good sources of entropy, as their seek
  152. * times are usually fairly consistent.
  153. *
  154. * All of these routines try to estimate how many bits of randomness a
  155. * particular randomness source. They do this by keeping track of the
  156. * first and second order deltas of the event timings.
  157. *
  158. * Ensuring unpredictability at system startup
  159. * ============================================
  160. *
  161. * When any operating system starts up, it will go through a sequence
  162. * of actions that are fairly predictable by an adversary, especially
  163. * if the start-up does not involve interaction with a human operator.
  164. * This reduces the actual number of bits of unpredictability in the
  165. * entropy pool below the value in entropy_count. In order to
  166. * counteract this effect, it helps to carry information in the
  167. * entropy pool across shut-downs and start-ups. To do this, put the
  168. * following lines an appropriate script which is run during the boot
  169. * sequence:
  170. *
  171. * echo "Initializing random number generator..."
  172. * random_seed=/var/run/random-seed
  173. * # Carry a random seed from start-up to start-up
  174. * # Load and then save the whole entropy pool
  175. * if [ -f $random_seed ]; then
  176. * cat $random_seed >/dev/urandom
  177. * else
  178. * touch $random_seed
  179. * fi
  180. * chmod 600 $random_seed
  181. * dd if=/dev/urandom of=$random_seed count=1 bs=512
  182. *
  183. * and the following lines in an appropriate script which is run as
  184. * the system is shutdown:
  185. *
  186. * # Carry a random seed from shut-down to start-up
  187. * # Save the whole entropy pool
  188. * echo "Saving random seed..."
  189. * random_seed=/var/run/random-seed
  190. * touch $random_seed
  191. * chmod 600 $random_seed
  192. * dd if=/dev/urandom of=$random_seed count=1 bs=512
  193. *
  194. * For example, on most modern systems using the System V init
  195. * scripts, such code fragments would be found in
  196. * /etc/rc.d/init.d/random. On older Linux systems, the correct script
  197. * location might be in /etc/rcb.d/rc.local or /etc/rc.d/rc.0.
  198. *
  199. * Effectively, these commands cause the contents of the entropy pool
  200. * to be saved at shut-down time and reloaded into the entropy pool at
  201. * start-up. (The 'dd' in the addition to the bootup script is to
  202. * make sure that /etc/random-seed is different for every start-up,
  203. * even if the system crashes without executing rc.0.) Even with
  204. * complete knowledge of the start-up activities, predicting the state
  205. * of the entropy pool requires knowledge of the previous history of
  206. * the system.
  207. *
  208. * Configuring the /dev/random driver under Linux
  209. * ==============================================
  210. *
  211. * The /dev/random driver under Linux uses minor numbers 8 and 9 of
  212. * the /dev/mem major number (#1). So if your system does not have
  213. * /dev/random and /dev/urandom created already, they can be created
  214. * by using the commands:
  215. *
  216. * mknod /dev/random c 1 8
  217. * mknod /dev/urandom c 1 9
  218. *
  219. * Acknowledgements:
  220. * =================
  221. *
  222. * Ideas for constructing this random number generator were derived
  223. * from Pretty Good Privacy's random number generator, and from private
  224. * discussions with Phil Karn. Colin Plumb provided a faster random
  225. * number generator, which speed up the mixing function of the entropy
  226. * pool, taken from PGPfone. Dale Worley has also contributed many
  227. * useful ideas and suggestions to improve this driver.
  228. *
  229. * Any flaws in the design are solely my responsibility, and should
  230. * not be attributed to the Phil, Colin, or any of authors of PGP.
  231. *
  232. * Further background information on this topic may be obtained from
  233. * RFC 1750, "Randomness Recommendations for Security", by Donald
  234. * Eastlake, Steve Crocker, and Jeff Schiller.
  235. */
  236. #include <linux/utsname.h>
  237. #include <linux/module.h>
  238. #include <linux/kernel.h>
  239. #include <linux/major.h>
  240. #include <linux/string.h>
  241. #include <linux/fcntl.h>
  242. #include <linux/slab.h>
  243. #include <linux/random.h>
  244. #include <linux/poll.h>
  245. #include <linux/init.h>
  246. #include <linux/fs.h>
  247. #include <linux/genhd.h>
  248. #include <linux/interrupt.h>
  249. #include <linux/mm.h>
  250. #include <linux/spinlock.h>
  251. #include <linux/percpu.h>
  252. #include <linux/cryptohash.h>
  253. #include <linux/fips.h>
  254. #include <linux/ptrace.h>
  255. #include <linux/kmemcheck.h>
  256. #ifdef CONFIG_GENERIC_HARDIRQS
  257. # include <linux/irq.h>
  258. #endif
  259. #include <asm/processor.h>
  260. #include <asm/uaccess.h>
  261. #include <asm/irq.h>
  262. #include <asm/irq_regs.h>
  263. #include <asm/io.h>
  264. #define CREATE_TRACE_POINTS
  265. #include <trace/events/random.h>
  266. /*
  267. * Configuration information
  268. */
  269. #define INPUT_POOL_WORDS 128
  270. #define OUTPUT_POOL_WORDS 32
  271. #define SEC_XFER_SIZE 512
  272. #define EXTRACT_SIZE 10
  273. /*
  274. * The minimum number of bits of entropy before we wake up a read on
  275. * /dev/random. Should be enough to do a significant reseed.
  276. */
  277. static int random_read_wakeup_thresh = 64;
  278. /*
  279. * If the entropy count falls under this number of bits, then we
  280. * should wake up processes which are selecting or polling on write
  281. * access to /dev/random.
  282. */
  283. static int random_write_wakeup_thresh = 128;
  284. /*
  285. * When the input pool goes over trickle_thresh, start dropping most
  286. * samples to avoid wasting CPU time and reduce lock contention.
  287. */
  288. static int trickle_thresh __read_mostly = INPUT_POOL_WORDS * 28;
  289. static DEFINE_PER_CPU(int, trickle_count);
  290. /*
  291. * A pool of size .poolwords is stirred with a primitive polynomial
  292. * of degree .poolwords over GF(2). The taps for various sizes are
  293. * defined below. They are chosen to be evenly spaced (minimum RMS
  294. * distance from evenly spaced; the numbers in the comments are a
  295. * scaled squared error sum) except for the last tap, which is 1 to
  296. * get the twisting happening as fast as possible.
  297. */
  298. static struct poolinfo {
  299. int poolwords;
  300. int tap1, tap2, tap3, tap4, tap5;
  301. } poolinfo_table[] = {
  302. /* x^128 + x^103 + x^76 + x^51 +x^25 + x + 1 -- 105 */
  303. { 128, 103, 76, 51, 25, 1 },
  304. /* x^32 + x^26 + x^20 + x^14 + x^7 + x + 1 -- 15 */
  305. { 32, 26, 20, 14, 7, 1 },
  306. #if 0
  307. /* x^2048 + x^1638 + x^1231 + x^819 + x^411 + x + 1 -- 115 */
  308. { 2048, 1638, 1231, 819, 411, 1 },
  309. /* x^1024 + x^817 + x^615 + x^412 + x^204 + x + 1 -- 290 */
  310. { 1024, 817, 615, 412, 204, 1 },
  311. /* x^1024 + x^819 + x^616 + x^410 + x^207 + x^2 + 1 -- 115 */
  312. { 1024, 819, 616, 410, 207, 2 },
  313. /* x^512 + x^411 + x^308 + x^208 + x^104 + x + 1 -- 225 */
  314. { 512, 411, 308, 208, 104, 1 },
  315. /* x^512 + x^409 + x^307 + x^206 + x^102 + x^2 + 1 -- 95 */
  316. { 512, 409, 307, 206, 102, 2 },
  317. /* x^512 + x^409 + x^309 + x^205 + x^103 + x^2 + 1 -- 95 */
  318. { 512, 409, 309, 205, 103, 2 },
  319. /* x^256 + x^205 + x^155 + x^101 + x^52 + x + 1 -- 125 */
  320. { 256, 205, 155, 101, 52, 1 },
  321. /* x^128 + x^103 + x^78 + x^51 + x^27 + x^2 + 1 -- 70 */
  322. { 128, 103, 78, 51, 27, 2 },
  323. /* x^64 + x^52 + x^39 + x^26 + x^14 + x + 1 -- 15 */
  324. { 64, 52, 39, 26, 14, 1 },
  325. #endif
  326. };
  327. #define POOLBITS poolwords*32
  328. #define POOLBYTES poolwords*4
  329. /*
  330. * For the purposes of better mixing, we use the CRC-32 polynomial as
  331. * well to make a twisted Generalized Feedback Shift Reigster
  332. *
  333. * (See M. Matsumoto & Y. Kurita, 1992. Twisted GFSR generators. ACM
  334. * Transactions on Modeling and Computer Simulation 2(3):179-194.
  335. * Also see M. Matsumoto & Y. Kurita, 1994. Twisted GFSR generators
  336. * II. ACM Transactions on Mdeling and Computer Simulation 4:254-266)
  337. *
  338. * Thanks to Colin Plumb for suggesting this.
  339. *
  340. * We have not analyzed the resultant polynomial to prove it primitive;
  341. * in fact it almost certainly isn't. Nonetheless, the irreducible factors
  342. * of a random large-degree polynomial over GF(2) are more than large enough
  343. * that periodicity is not a concern.
  344. *
  345. * The input hash is much less sensitive than the output hash. All
  346. * that we want of it is that it be a good non-cryptographic hash;
  347. * i.e. it not produce collisions when fed "random" data of the sort
  348. * we expect to see. As long as the pool state differs for different
  349. * inputs, we have preserved the input entropy and done a good job.
  350. * The fact that an intelligent attacker can construct inputs that
  351. * will produce controlled alterations to the pool's state is not
  352. * important because we don't consider such inputs to contribute any
  353. * randomness. The only property we need with respect to them is that
  354. * the attacker can't increase his/her knowledge of the pool's state.
  355. * Since all additions are reversible (knowing the final state and the
  356. * input, you can reconstruct the initial state), if an attacker has
  357. * any uncertainty about the initial state, he/she can only shuffle
  358. * that uncertainty about, but never cause any collisions (which would
  359. * decrease the uncertainty).
  360. *
  361. * The chosen system lets the state of the pool be (essentially) the input
  362. * modulo the generator polymnomial. Now, for random primitive polynomials,
  363. * this is a universal class of hash functions, meaning that the chance
  364. * of a collision is limited by the attacker's knowledge of the generator
  365. * polynomail, so if it is chosen at random, an attacker can never force
  366. * a collision. Here, we use a fixed polynomial, but we *can* assume that
  367. * ###--> it is unknown to the processes generating the input entropy. <-###
  368. * Because of this important property, this is a good, collision-resistant
  369. * hash; hash collisions will occur no more often than chance.
  370. */
  371. /*
  372. * Static global variables
  373. */
  374. static DECLARE_WAIT_QUEUE_HEAD(random_read_wait);
  375. static DECLARE_WAIT_QUEUE_HEAD(random_write_wait);
  376. static struct fasync_struct *fasync;
  377. #if 0
  378. static bool debug;
  379. module_param(debug, bool, 0644);
  380. #define DEBUG_ENT(fmt, arg...) do { \
  381. if (debug) \
  382. printk(KERN_DEBUG "random %04d %04d %04d: " \
  383. fmt,\
  384. input_pool.entropy_count,\
  385. blocking_pool.entropy_count,\
  386. nonblocking_pool.entropy_count,\
  387. ## arg); } while (0)
  388. #else
  389. #define DEBUG_ENT(fmt, arg...) do {} while (0)
  390. #endif
  391. /**********************************************************************
  392. *
  393. * OS independent entropy store. Here are the functions which handle
  394. * storing entropy in an entropy pool.
  395. *
  396. **********************************************************************/
  397. struct entropy_store;
  398. struct entropy_store {
  399. /* read-only data: */
  400. struct poolinfo *poolinfo;
  401. __u32 *pool;
  402. const char *name;
  403. struct entropy_store *pull;
  404. int limit;
  405. /* read-write data: */
  406. spinlock_t lock;
  407. unsigned add_ptr;
  408. unsigned input_rotate;
  409. int entropy_count;
  410. int entropy_total;
  411. unsigned int initialized:1;
  412. __u8 last_data[EXTRACT_SIZE];
  413. };
  414. static __u32 input_pool_data[INPUT_POOL_WORDS];
  415. static __u32 blocking_pool_data[OUTPUT_POOL_WORDS];
  416. static __u32 nonblocking_pool_data[OUTPUT_POOL_WORDS];
  417. static struct entropy_store input_pool = {
  418. .poolinfo = &poolinfo_table[0],
  419. .name = "input",
  420. .limit = 1,
  421. .lock = __SPIN_LOCK_UNLOCKED(&input_pool.lock),
  422. .pool = input_pool_data
  423. };
  424. static struct entropy_store blocking_pool = {
  425. .poolinfo = &poolinfo_table[1],
  426. .name = "blocking",
  427. .limit = 1,
  428. .pull = &input_pool,
  429. .lock = __SPIN_LOCK_UNLOCKED(&blocking_pool.lock),
  430. .pool = blocking_pool_data
  431. };
  432. static struct entropy_store nonblocking_pool = {
  433. .poolinfo = &poolinfo_table[1],
  434. .name = "nonblocking",
  435. .pull = &input_pool,
  436. .lock = __SPIN_LOCK_UNLOCKED(&nonblocking_pool.lock),
  437. .pool = nonblocking_pool_data
  438. };
  439. static __u32 const twist_table[8] = {
  440. 0x00000000, 0x3b6e20c8, 0x76dc4190, 0x4db26158,
  441. 0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278 };
  442. /*
  443. * This function adds bytes into the entropy "pool". It does not
  444. * update the entropy estimate. The caller should call
  445. * credit_entropy_bits if this is appropriate.
  446. *
  447. * The pool is stirred with a primitive polynomial of the appropriate
  448. * degree, and then twisted. We twist by three bits at a time because
  449. * it's cheap to do so and helps slightly in the expected case where
  450. * the entropy is concentrated in the low-order bits.
  451. */
  452. static void _mix_pool_bytes(struct entropy_store *r, const void *in,
  453. int nbytes, __u8 out[64])
  454. {
  455. unsigned long i, j, tap1, tap2, tap3, tap4, tap5;
  456. int input_rotate;
  457. int wordmask = r->poolinfo->poolwords - 1;
  458. const char *bytes = in;
  459. __u32 w;
  460. tap1 = r->poolinfo->tap1;
  461. tap2 = r->poolinfo->tap2;
  462. tap3 = r->poolinfo->tap3;
  463. tap4 = r->poolinfo->tap4;
  464. tap5 = r->poolinfo->tap5;
  465. smp_rmb();
  466. input_rotate = ACCESS_ONCE(r->input_rotate);
  467. i = ACCESS_ONCE(r->add_ptr);
  468. /* mix one byte at a time to simplify size handling and churn faster */
  469. while (nbytes--) {
  470. w = rol32(*bytes++, input_rotate & 31);
  471. i = (i - 1) & wordmask;
  472. /* XOR in the various taps */
  473. w ^= r->pool[i];
  474. w ^= r->pool[(i + tap1) & wordmask];
  475. w ^= r->pool[(i + tap2) & wordmask];
  476. w ^= r->pool[(i + tap3) & wordmask];
  477. w ^= r->pool[(i + tap4) & wordmask];
  478. w ^= r->pool[(i + tap5) & wordmask];
  479. /* Mix the result back in with a twist */
  480. r->pool[i] = (w >> 3) ^ twist_table[w & 7];
  481. /*
  482. * Normally, we add 7 bits of rotation to the pool.
  483. * At the beginning of the pool, add an extra 7 bits
  484. * rotation, so that successive passes spread the
  485. * input bits across the pool evenly.
  486. */
  487. input_rotate += i ? 7 : 14;
  488. }
  489. ACCESS_ONCE(r->input_rotate) = input_rotate;
  490. ACCESS_ONCE(r->add_ptr) = i;
  491. smp_wmb();
  492. if (out)
  493. for (j = 0; j < 16; j++)
  494. ((__u32 *)out)[j] = r->pool[(i - j) & wordmask];
  495. }
  496. static void __mix_pool_bytes(struct entropy_store *r, const void *in,
  497. int nbytes, __u8 out[64])
  498. {
  499. trace_mix_pool_bytes_nolock(r->name, nbytes, _RET_IP_);
  500. _mix_pool_bytes(r, in, nbytes, out);
  501. }
  502. static void mix_pool_bytes(struct entropy_store *r, const void *in,
  503. int nbytes, __u8 out[64])
  504. {
  505. unsigned long flags;
  506. trace_mix_pool_bytes(r->name, nbytes, _RET_IP_);
  507. spin_lock_irqsave(&r->lock, flags);
  508. _mix_pool_bytes(r, in, nbytes, out);
  509. spin_unlock_irqrestore(&r->lock, flags);
  510. }
  511. struct fast_pool {
  512. __u32 pool[4];
  513. unsigned long last;
  514. unsigned short count;
  515. unsigned char rotate;
  516. unsigned char last_timer_intr;
  517. };
  518. /*
  519. * This is a fast mixing routine used by the interrupt randomness
  520. * collector. It's hardcoded for an 128 bit pool and assumes that any
  521. * locks that might be needed are taken by the caller.
  522. */
  523. static void fast_mix(struct fast_pool *f, const void *in, int nbytes)
  524. {
  525. const char *bytes = in;
  526. __u32 w;
  527. unsigned i = f->count;
  528. unsigned input_rotate = f->rotate;
  529. while (nbytes--) {
  530. w = rol32(*bytes++, input_rotate & 31) ^ f->pool[i & 3] ^
  531. f->pool[(i + 1) & 3];
  532. f->pool[i & 3] = (w >> 3) ^ twist_table[w & 7];
  533. input_rotate += (i++ & 3) ? 7 : 14;
  534. }
  535. f->count = i;
  536. f->rotate = input_rotate;
  537. }
  538. /*
  539. * Credit (or debit) the entropy store with n bits of entropy
  540. */
  541. static void credit_entropy_bits(struct entropy_store *r, int nbits)
  542. {
  543. int entropy_count, orig;
  544. if (!nbits)
  545. return;
  546. DEBUG_ENT("added %d entropy credits to %s\n", nbits, r->name);
  547. retry:
  548. entropy_count = orig = ACCESS_ONCE(r->entropy_count);
  549. entropy_count += nbits;
  550. if (entropy_count < 0) {
  551. DEBUG_ENT("negative entropy/overflow\n");
  552. entropy_count = 0;
  553. } else if (entropy_count > r->poolinfo->POOLBITS)
  554. entropy_count = r->poolinfo->POOLBITS;
  555. if (cmpxchg(&r->entropy_count, orig, entropy_count) != orig)
  556. goto retry;
  557. if (!r->initialized && nbits > 0) {
  558. r->entropy_total += nbits;
  559. if (r->entropy_total > 128)
  560. r->initialized = 1;
  561. }
  562. trace_credit_entropy_bits(r->name, nbits, entropy_count,
  563. r->entropy_total, _RET_IP_);
  564. /* should we wake readers? */
  565. if (r == &input_pool && entropy_count >= random_read_wakeup_thresh) {
  566. wake_up_interruptible(&random_read_wait);
  567. kill_fasync(&fasync, SIGIO, POLL_IN);
  568. }
  569. }
  570. /*********************************************************************
  571. *
  572. * Entropy input management
  573. *
  574. *********************************************************************/
  575. /* There is one of these per entropy source */
  576. struct timer_rand_state {
  577. cycles_t last_time;
  578. long last_delta, last_delta2;
  579. unsigned dont_count_entropy:1;
  580. };
  581. /*
  582. * Add device- or boot-specific data to the input and nonblocking
  583. * pools to help initialize them to unique values.
  584. *
  585. * None of this adds any entropy, it is meant to avoid the
  586. * problem of the nonblocking pool having similar initial state
  587. * across largely identical devices.
  588. */
  589. void add_device_randomness(const void *buf, unsigned int size)
  590. {
  591. unsigned long time = get_cycles() ^ jiffies;
  592. mix_pool_bytes(&input_pool, buf, size, NULL);
  593. mix_pool_bytes(&input_pool, &time, sizeof(time), NULL);
  594. mix_pool_bytes(&nonblocking_pool, buf, size, NULL);
  595. mix_pool_bytes(&nonblocking_pool, &time, sizeof(time), NULL);
  596. }
  597. EXPORT_SYMBOL(add_device_randomness);
  598. static struct timer_rand_state input_timer_state;
  599. /*
  600. * This function adds entropy to the entropy "pool" by using timing
  601. * delays. It uses the timer_rand_state structure to make an estimate
  602. * of how many bits of entropy this call has added to the pool.
  603. *
  604. * The number "num" is also added to the pool - it should somehow describe
  605. * the type of event which just happened. This is currently 0-255 for
  606. * keyboard scan codes, and 256 upwards for interrupts.
  607. *
  608. */
  609. static void add_timer_randomness(struct timer_rand_state *state, unsigned num)
  610. {
  611. struct {
  612. long jiffies;
  613. unsigned cycles;
  614. unsigned num;
  615. } sample;
  616. long delta, delta2, delta3;
  617. preempt_disable();
  618. /* if over the trickle threshold, use only 1 in 4096 samples */
  619. if (input_pool.entropy_count > trickle_thresh &&
  620. ((__this_cpu_inc_return(trickle_count) - 1) & 0xfff))
  621. goto out;
  622. sample.jiffies = jiffies;
  623. sample.cycles = get_cycles();
  624. sample.num = num;
  625. mix_pool_bytes(&input_pool, &sample, sizeof(sample), NULL);
  626. /*
  627. * Calculate number of bits of randomness we probably added.
  628. * We take into account the first, second and third-order deltas
  629. * in order to make our estimate.
  630. */
  631. if (!state->dont_count_entropy) {
  632. delta = sample.jiffies - state->last_time;
  633. state->last_time = sample.jiffies;
  634. delta2 = delta - state->last_delta;
  635. state->last_delta = delta;
  636. delta3 = delta2 - state->last_delta2;
  637. state->last_delta2 = delta2;
  638. if (delta < 0)
  639. delta = -delta;
  640. if (delta2 < 0)
  641. delta2 = -delta2;
  642. if (delta3 < 0)
  643. delta3 = -delta3;
  644. if (delta > delta2)
  645. delta = delta2;
  646. if (delta > delta3)
  647. delta = delta3;
  648. /*
  649. * delta is now minimum absolute delta.
  650. * Round down by 1 bit on general principles,
  651. * and limit entropy entimate to 12 bits.
  652. */
  653. credit_entropy_bits(&input_pool,
  654. min_t(int, fls(delta>>1), 11));
  655. }
  656. out:
  657. preempt_enable();
  658. }
  659. void add_input_randomness(unsigned int type, unsigned int code,
  660. unsigned int value)
  661. {
  662. static unsigned char last_value;
  663. /* ignore autorepeat and the like */
  664. if (value == last_value)
  665. return;
  666. DEBUG_ENT("input event\n");
  667. last_value = value;
  668. add_timer_randomness(&input_timer_state,
  669. (type << 4) ^ code ^ (code >> 4) ^ value);
  670. }
  671. EXPORT_SYMBOL_GPL(add_input_randomness);
  672. static DEFINE_PER_CPU(struct fast_pool, irq_randomness);
  673. void add_interrupt_randomness(int irq, int irq_flags)
  674. {
  675. struct entropy_store *r;
  676. struct fast_pool *fast_pool = &__get_cpu_var(irq_randomness);
  677. struct pt_regs *regs = get_irq_regs();
  678. unsigned long now = jiffies;
  679. __u32 input[4], cycles = get_cycles();
  680. input[0] = cycles ^ jiffies;
  681. input[1] = irq;
  682. if (regs) {
  683. __u64 ip = instruction_pointer(regs);
  684. input[2] = ip;
  685. input[3] = ip >> 32;
  686. }
  687. fast_mix(fast_pool, input, sizeof(input));
  688. if ((fast_pool->count & 1023) &&
  689. !time_after(now, fast_pool->last + HZ))
  690. return;
  691. fast_pool->last = now;
  692. r = nonblocking_pool.initialized ? &input_pool : &nonblocking_pool;
  693. __mix_pool_bytes(r, &fast_pool->pool, sizeof(fast_pool->pool), NULL);
  694. /*
  695. * If we don't have a valid cycle counter, and we see
  696. * back-to-back timer interrupts, then skip giving credit for
  697. * any entropy.
  698. */
  699. if (cycles == 0) {
  700. if (irq_flags & __IRQF_TIMER) {
  701. if (fast_pool->last_timer_intr)
  702. return;
  703. fast_pool->last_timer_intr = 1;
  704. } else
  705. fast_pool->last_timer_intr = 0;
  706. }
  707. credit_entropy_bits(r, 1);
  708. }
  709. #ifdef CONFIG_BLOCK
  710. void add_disk_randomness(struct gendisk *disk)
  711. {
  712. if (!disk || !disk->random)
  713. return;
  714. /* first major is 1, so we get >= 0x200 here */
  715. DEBUG_ENT("disk event %d:%d\n",
  716. MAJOR(disk_devt(disk)), MINOR(disk_devt(disk)));
  717. add_timer_randomness(disk->random, 0x100 + disk_devt(disk));
  718. }
  719. #endif
  720. /*********************************************************************
  721. *
  722. * Entropy extraction routines
  723. *
  724. *********************************************************************/
  725. static ssize_t extract_entropy(struct entropy_store *r, void *buf,
  726. size_t nbytes, int min, int rsvd);
  727. /*
  728. * This utility inline function is responsible for transferring entropy
  729. * from the primary pool to the secondary extraction pool. We make
  730. * sure we pull enough for a 'catastrophic reseed'.
  731. */
  732. static void xfer_secondary_pool(struct entropy_store *r, size_t nbytes)
  733. {
  734. union {
  735. __u32 tmp[OUTPUT_POOL_WORDS];
  736. long hwrand[4];
  737. } u;
  738. int i;
  739. if (r->pull && r->entropy_count < nbytes * 8 &&
  740. r->entropy_count < r->poolinfo->POOLBITS) {
  741. /* If we're limited, always leave two wakeup worth's BITS */
  742. int rsvd = r->limit ? 0 : random_read_wakeup_thresh/4;
  743. int bytes = nbytes;
  744. /* pull at least as many as BYTES as wakeup BITS */
  745. bytes = max_t(int, bytes, random_read_wakeup_thresh / 8);
  746. /* but never more than the buffer size */
  747. bytes = min_t(int, bytes, sizeof(u.tmp));
  748. DEBUG_ENT("going to reseed %s with %d bits "
  749. "(%d of %d requested)\n",
  750. r->name, bytes * 8, nbytes * 8, r->entropy_count);
  751. bytes = extract_entropy(r->pull, u.tmp, bytes,
  752. random_read_wakeup_thresh / 8, rsvd);
  753. mix_pool_bytes(r, u.tmp, bytes, NULL);
  754. credit_entropy_bits(r, bytes*8);
  755. }
  756. kmemcheck_mark_initialized(&u.hwrand, sizeof(u.hwrand));
  757. for (i = 0; i < 4; i++)
  758. if (arch_get_random_long(&u.hwrand[i]))
  759. break;
  760. if (i)
  761. mix_pool_bytes(r, &u.hwrand, sizeof(u.hwrand), 0);
  762. }
  763. /*
  764. * These functions extracts randomness from the "entropy pool", and
  765. * returns it in a buffer.
  766. *
  767. * The min parameter specifies the minimum amount we can pull before
  768. * failing to avoid races that defeat catastrophic reseeding while the
  769. * reserved parameter indicates how much entropy we must leave in the
  770. * pool after each pull to avoid starving other readers.
  771. *
  772. * Note: extract_entropy() assumes that .poolwords is a multiple of 16 words.
  773. */
  774. static size_t account(struct entropy_store *r, size_t nbytes, int min,
  775. int reserved)
  776. {
  777. unsigned long flags;
  778. /* Hold lock while accounting */
  779. spin_lock_irqsave(&r->lock, flags);
  780. BUG_ON(r->entropy_count > r->poolinfo->POOLBITS);
  781. DEBUG_ENT("trying to extract %d bits from %s\n",
  782. nbytes * 8, r->name);
  783. /* Can we pull enough? */
  784. if (r->entropy_count / 8 < min + reserved) {
  785. nbytes = 0;
  786. } else {
  787. /* If limited, never pull more than available */
  788. if (r->limit && nbytes + reserved >= r->entropy_count / 8)
  789. nbytes = r->entropy_count/8 - reserved;
  790. if (r->entropy_count / 8 >= nbytes + reserved)
  791. r->entropy_count -= nbytes*8;
  792. else
  793. r->entropy_count = reserved;
  794. if (r->entropy_count < random_write_wakeup_thresh) {
  795. wake_up_interruptible(&random_write_wait);
  796. kill_fasync(&fasync, SIGIO, POLL_OUT);
  797. }
  798. }
  799. DEBUG_ENT("debiting %d entropy credits from %s%s\n",
  800. nbytes * 8, r->name, r->limit ? "" : " (unlimited)");
  801. spin_unlock_irqrestore(&r->lock, flags);
  802. return nbytes;
  803. }
  804. static void extract_buf(struct entropy_store *r, __u8 *out)
  805. {
  806. int i;
  807. __u32 hash[5], workspace[SHA_WORKSPACE_WORDS];
  808. __u8 extract[64];
  809. unsigned long flags;
  810. /* Generate a hash across the pool, 16 words (512 bits) at a time */
  811. sha_init(hash);
  812. spin_lock_irqsave(&r->lock, flags);
  813. for (i = 0; i < r->poolinfo->poolwords; i += 16)
  814. sha_transform(hash, (__u8 *)(r->pool + i), workspace);
  815. /*
  816. * We mix the hash back into the pool to prevent backtracking
  817. * attacks (where the attacker knows the state of the pool
  818. * plus the current outputs, and attempts to find previous
  819. * ouputs), unless the hash function can be inverted. By
  820. * mixing at least a SHA1 worth of hash data back, we make
  821. * brute-forcing the feedback as hard as brute-forcing the
  822. * hash.
  823. */
  824. __mix_pool_bytes(r, hash, sizeof(hash), extract);
  825. spin_unlock_irqrestore(&r->lock, flags);
  826. /*
  827. * To avoid duplicates, we atomically extract a portion of the
  828. * pool while mixing, and hash one final time.
  829. */
  830. sha_transform(hash, extract, workspace);
  831. memset(extract, 0, sizeof(extract));
  832. memset(workspace, 0, sizeof(workspace));
  833. /*
  834. * In case the hash function has some recognizable output
  835. * pattern, we fold it in half. Thus, we always feed back
  836. * twice as much data as we output.
  837. */
  838. hash[0] ^= hash[3];
  839. hash[1] ^= hash[4];
  840. hash[2] ^= rol32(hash[2], 16);
  841. memcpy(out, hash, EXTRACT_SIZE);
  842. memset(hash, 0, sizeof(hash));
  843. }
  844. static ssize_t extract_entropy(struct entropy_store *r, void *buf,
  845. size_t nbytes, int min, int reserved)
  846. {
  847. ssize_t ret = 0, i;
  848. __u8 tmp[EXTRACT_SIZE];
  849. trace_extract_entropy(r->name, nbytes, r->entropy_count, _RET_IP_);
  850. xfer_secondary_pool(r, nbytes);
  851. nbytes = account(r, nbytes, min, reserved);
  852. while (nbytes) {
  853. extract_buf(r, tmp);
  854. if (fips_enabled) {
  855. unsigned long flags;
  856. spin_lock_irqsave(&r->lock, flags);
  857. if (!memcmp(tmp, r->last_data, EXTRACT_SIZE))
  858. panic("Hardware RNG duplicated output!\n");
  859. memcpy(r->last_data, tmp, EXTRACT_SIZE);
  860. spin_unlock_irqrestore(&r->lock, flags);
  861. }
  862. i = min_t(int, nbytes, EXTRACT_SIZE);
  863. memcpy(buf, tmp, i);
  864. nbytes -= i;
  865. buf += i;
  866. ret += i;
  867. }
  868. /* Wipe data just returned from memory */
  869. memset(tmp, 0, sizeof(tmp));
  870. return ret;
  871. }
  872. static ssize_t extract_entropy_user(struct entropy_store *r, void __user *buf,
  873. size_t nbytes)
  874. {
  875. ssize_t ret = 0, i;
  876. __u8 tmp[EXTRACT_SIZE];
  877. trace_extract_entropy_user(r->name, nbytes, r->entropy_count, _RET_IP_);
  878. xfer_secondary_pool(r, nbytes);
  879. nbytes = account(r, nbytes, 0, 0);
  880. while (nbytes) {
  881. if (need_resched()) {
  882. if (signal_pending(current)) {
  883. if (ret == 0)
  884. ret = -ERESTARTSYS;
  885. break;
  886. }
  887. schedule();
  888. }
  889. extract_buf(r, tmp);
  890. i = min_t(int, nbytes, EXTRACT_SIZE);
  891. if (copy_to_user(buf, tmp, i)) {
  892. ret = -EFAULT;
  893. break;
  894. }
  895. nbytes -= i;
  896. buf += i;
  897. ret += i;
  898. }
  899. /* Wipe data just returned from memory */
  900. memset(tmp, 0, sizeof(tmp));
  901. return ret;
  902. }
  903. /*
  904. * This function is the exported kernel interface. It returns some
  905. * number of good random numbers, suitable for key generation, seeding
  906. * TCP sequence numbers, etc. It does not use the hw random number
  907. * generator, if available; use get_random_bytes_arch() for that.
  908. */
  909. void get_random_bytes(void *buf, int nbytes)
  910. {
  911. extract_entropy(&nonblocking_pool, buf, nbytes, 0, 0);
  912. }
  913. EXPORT_SYMBOL(get_random_bytes);
  914. /*
  915. * This function will use the architecture-specific hardware random
  916. * number generator if it is available. The arch-specific hw RNG will
  917. * almost certainly be faster than what we can do in software, but it
  918. * is impossible to verify that it is implemented securely (as
  919. * opposed, to, say, the AES encryption of a sequence number using a
  920. * key known by the NSA). So it's useful if we need the speed, but
  921. * only if we're willing to trust the hardware manufacturer not to
  922. * have put in a back door.
  923. */
  924. void get_random_bytes_arch(void *buf, int nbytes)
  925. {
  926. char *p = buf;
  927. trace_get_random_bytes(nbytes, _RET_IP_);
  928. while (nbytes) {
  929. unsigned long v;
  930. int chunk = min(nbytes, (int)sizeof(unsigned long));
  931. if (!arch_get_random_long(&v))
  932. break;
  933. memcpy(p, &v, chunk);
  934. p += chunk;
  935. nbytes -= chunk;
  936. }
  937. if (nbytes)
  938. extract_entropy(&nonblocking_pool, p, nbytes, 0, 0);
  939. }
  940. EXPORT_SYMBOL(get_random_bytes_arch);
  941. /*
  942. * init_std_data - initialize pool with system data
  943. *
  944. * @r: pool to initialize
  945. *
  946. * This function clears the pool's entropy count and mixes some system
  947. * data into the pool to prepare it for use. The pool is not cleared
  948. * as that can only decrease the entropy in the pool.
  949. */
  950. static void init_std_data(struct entropy_store *r)
  951. {
  952. int i;
  953. ktime_t now = ktime_get_real();
  954. unsigned long rv;
  955. r->entropy_count = 0;
  956. r->entropy_total = 0;
  957. mix_pool_bytes(r, &now, sizeof(now), NULL);
  958. for (i = r->poolinfo->POOLBYTES; i > 0; i -= sizeof(rv)) {
  959. if (!arch_get_random_long(&rv))
  960. break;
  961. mix_pool_bytes(r, &rv, sizeof(rv), NULL);
  962. }
  963. mix_pool_bytes(r, utsname(), sizeof(*(utsname())), NULL);
  964. }
  965. /*
  966. * Note that setup_arch() may call add_device_randomness()
  967. * long before we get here. This allows seeding of the pools
  968. * with some platform dependent data very early in the boot
  969. * process. But it limits our options here. We must use
  970. * statically allocated structures that already have all
  971. * initializations complete at compile time. We should also
  972. * take care not to overwrite the precious per platform data
  973. * we were given.
  974. */
  975. static int rand_initialize(void)
  976. {
  977. init_std_data(&input_pool);
  978. init_std_data(&blocking_pool);
  979. init_std_data(&nonblocking_pool);
  980. return 0;
  981. }
  982. module_init(rand_initialize);
  983. #ifdef CONFIG_BLOCK
  984. void rand_initialize_disk(struct gendisk *disk)
  985. {
  986. struct timer_rand_state *state;
  987. /*
  988. * If kzalloc returns null, we just won't use that entropy
  989. * source.
  990. */
  991. state = kzalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
  992. if (state)
  993. disk->random = state;
  994. }
  995. #endif
  996. static ssize_t
  997. random_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
  998. {
  999. ssize_t n, retval = 0, count = 0;
  1000. if (nbytes == 0)
  1001. return 0;
  1002. while (nbytes > 0) {
  1003. n = nbytes;
  1004. if (n > SEC_XFER_SIZE)
  1005. n = SEC_XFER_SIZE;
  1006. DEBUG_ENT("reading %d bits\n", n*8);
  1007. n = extract_entropy_user(&blocking_pool, buf, n);
  1008. DEBUG_ENT("read got %d bits (%d still needed)\n",
  1009. n*8, (nbytes-n)*8);
  1010. if (n == 0) {
  1011. if (file->f_flags & O_NONBLOCK) {
  1012. retval = -EAGAIN;
  1013. break;
  1014. }
  1015. DEBUG_ENT("sleeping?\n");
  1016. wait_event_interruptible(random_read_wait,
  1017. input_pool.entropy_count >=
  1018. random_read_wakeup_thresh);
  1019. DEBUG_ENT("awake\n");
  1020. if (signal_pending(current)) {
  1021. retval = -ERESTARTSYS;
  1022. break;
  1023. }
  1024. continue;
  1025. }
  1026. if (n < 0) {
  1027. retval = n;
  1028. break;
  1029. }
  1030. count += n;
  1031. buf += n;
  1032. nbytes -= n;
  1033. break; /* This break makes the device work */
  1034. /* like a named pipe */
  1035. }
  1036. return (count ? count : retval);
  1037. }
  1038. static ssize_t
  1039. urandom_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
  1040. {
  1041. return extract_entropy_user(&nonblocking_pool, buf, nbytes);
  1042. }
  1043. static unsigned int
  1044. random_poll(struct file *file, poll_table * wait)
  1045. {
  1046. unsigned int mask;
  1047. poll_wait(file, &random_read_wait, wait);
  1048. poll_wait(file, &random_write_wait, wait);
  1049. mask = 0;
  1050. if (input_pool.entropy_count >= random_read_wakeup_thresh)
  1051. mask |= POLLIN | POLLRDNORM;
  1052. if (input_pool.entropy_count < random_write_wakeup_thresh)
  1053. mask |= POLLOUT | POLLWRNORM;
  1054. return mask;
  1055. }
  1056. static int
  1057. write_pool(struct entropy_store *r, const char __user *buffer, size_t count)
  1058. {
  1059. size_t bytes;
  1060. __u32 buf[16];
  1061. const char __user *p = buffer;
  1062. while (count > 0) {
  1063. bytes = min(count, sizeof(buf));
  1064. if (copy_from_user(&buf, p, bytes))
  1065. return -EFAULT;
  1066. count -= bytes;
  1067. p += bytes;
  1068. mix_pool_bytes(r, buf, bytes, NULL);
  1069. cond_resched();
  1070. }
  1071. return 0;
  1072. }
  1073. static ssize_t random_write(struct file *file, const char __user *buffer,
  1074. size_t count, loff_t *ppos)
  1075. {
  1076. size_t ret;
  1077. ret = write_pool(&blocking_pool, buffer, count);
  1078. if (ret)
  1079. return ret;
  1080. ret = write_pool(&nonblocking_pool, buffer, count);
  1081. if (ret)
  1082. return ret;
  1083. return (ssize_t)count;
  1084. }
  1085. static long random_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
  1086. {
  1087. int size, ent_count;
  1088. int __user *p = (int __user *)arg;
  1089. int retval;
  1090. switch (cmd) {
  1091. case RNDGETENTCNT:
  1092. /* inherently racy, no point locking */
  1093. if (put_user(input_pool.entropy_count, p))
  1094. return -EFAULT;
  1095. return 0;
  1096. case RNDADDTOENTCNT:
  1097. if (!capable(CAP_SYS_ADMIN))
  1098. return -EPERM;
  1099. if (get_user(ent_count, p))
  1100. return -EFAULT;
  1101. credit_entropy_bits(&input_pool, ent_count);
  1102. return 0;
  1103. case RNDADDENTROPY:
  1104. if (!capable(CAP_SYS_ADMIN))
  1105. return -EPERM;
  1106. if (get_user(ent_count, p++))
  1107. return -EFAULT;
  1108. if (ent_count < 0)
  1109. return -EINVAL;
  1110. if (get_user(size, p++))
  1111. return -EFAULT;
  1112. retval = write_pool(&input_pool, (const char __user *)p,
  1113. size);
  1114. if (retval < 0)
  1115. return retval;
  1116. credit_entropy_bits(&input_pool, ent_count);
  1117. return 0;
  1118. case RNDZAPENTCNT:
  1119. case RNDCLEARPOOL:
  1120. /* Clear the entropy pool counters. */
  1121. if (!capable(CAP_SYS_ADMIN))
  1122. return -EPERM;
  1123. rand_initialize();
  1124. return 0;
  1125. default:
  1126. return -EINVAL;
  1127. }
  1128. }
  1129. static int random_fasync(int fd, struct file *filp, int on)
  1130. {
  1131. return fasync_helper(fd, filp, on, &fasync);
  1132. }
  1133. const struct file_operations random_fops = {
  1134. .read = random_read,
  1135. .write = random_write,
  1136. .poll = random_poll,
  1137. .unlocked_ioctl = random_ioctl,
  1138. .fasync = random_fasync,
  1139. .llseek = noop_llseek,
  1140. };
  1141. const struct file_operations urandom_fops = {
  1142. .read = urandom_read,
  1143. .write = random_write,
  1144. .unlocked_ioctl = random_ioctl,
  1145. .fasync = random_fasync,
  1146. .llseek = noop_llseek,
  1147. };
  1148. /***************************************************************
  1149. * Random UUID interface
  1150. *
  1151. * Used here for a Boot ID, but can be useful for other kernel
  1152. * drivers.
  1153. ***************************************************************/
  1154. /*
  1155. * Generate random UUID
  1156. */
  1157. void generate_random_uuid(unsigned char uuid_out[16])
  1158. {
  1159. get_random_bytes(uuid_out, 16);
  1160. /* Set UUID version to 4 --- truly random generation */
  1161. uuid_out[6] = (uuid_out[6] & 0x0F) | 0x40;
  1162. /* Set the UUID variant to DCE */
  1163. uuid_out[8] = (uuid_out[8] & 0x3F) | 0x80;
  1164. }
  1165. EXPORT_SYMBOL(generate_random_uuid);
  1166. /********************************************************************
  1167. *
  1168. * Sysctl interface
  1169. *
  1170. ********************************************************************/
  1171. #ifdef CONFIG_SYSCTL
  1172. #include <linux/sysctl.h>
  1173. static int min_read_thresh = 8, min_write_thresh;
  1174. static int max_read_thresh = INPUT_POOL_WORDS * 32;
  1175. static int max_write_thresh = INPUT_POOL_WORDS * 32;
  1176. static char sysctl_bootid[16];
  1177. /*
  1178. * These functions is used to return both the bootid UUID, and random
  1179. * UUID. The difference is in whether table->data is NULL; if it is,
  1180. * then a new UUID is generated and returned to the user.
  1181. *
  1182. * If the user accesses this via the proc interface, it will be returned
  1183. * as an ASCII string in the standard UUID format. If accesses via the
  1184. * sysctl system call, it is returned as 16 bytes of binary data.
  1185. */
  1186. static int proc_do_uuid(ctl_table *table, int write,
  1187. void __user *buffer, size_t *lenp, loff_t *ppos)
  1188. {
  1189. ctl_table fake_table;
  1190. unsigned char buf[64], tmp_uuid[16], *uuid;
  1191. uuid = table->data;
  1192. if (!uuid) {
  1193. uuid = tmp_uuid;
  1194. generate_random_uuid(uuid);
  1195. } else {
  1196. static DEFINE_SPINLOCK(bootid_spinlock);
  1197. spin_lock(&bootid_spinlock);
  1198. if (!uuid[8])
  1199. generate_random_uuid(uuid);
  1200. spin_unlock(&bootid_spinlock);
  1201. }
  1202. sprintf(buf, "%pU", uuid);
  1203. fake_table.data = buf;
  1204. fake_table.maxlen = sizeof(buf);
  1205. return proc_dostring(&fake_table, write, buffer, lenp, ppos);
  1206. }
  1207. static int sysctl_poolsize = INPUT_POOL_WORDS * 32;
  1208. extern ctl_table random_table[];
  1209. ctl_table random_table[] = {
  1210. {
  1211. .procname = "poolsize",
  1212. .data = &sysctl_poolsize,
  1213. .maxlen = sizeof(int),
  1214. .mode = 0444,
  1215. .proc_handler = proc_dointvec,
  1216. },
  1217. {
  1218. .procname = "entropy_avail",
  1219. .maxlen = sizeof(int),
  1220. .mode = 0444,
  1221. .proc_handler = proc_dointvec,
  1222. .data = &input_pool.entropy_count,
  1223. },
  1224. {
  1225. .procname = "read_wakeup_threshold",
  1226. .data = &random_read_wakeup_thresh,
  1227. .maxlen = sizeof(int),
  1228. .mode = 0644,
  1229. .proc_handler = proc_dointvec_minmax,
  1230. .extra1 = &min_read_thresh,
  1231. .extra2 = &max_read_thresh,
  1232. },
  1233. {
  1234. .procname = "write_wakeup_threshold",
  1235. .data = &random_write_wakeup_thresh,
  1236. .maxlen = sizeof(int),
  1237. .mode = 0644,
  1238. .proc_handler = proc_dointvec_minmax,
  1239. .extra1 = &min_write_thresh,
  1240. .extra2 = &max_write_thresh,
  1241. },
  1242. {
  1243. .procname = "boot_id",
  1244. .data = &sysctl_bootid,
  1245. .maxlen = 16,
  1246. .mode = 0444,
  1247. .proc_handler = proc_do_uuid,
  1248. },
  1249. {
  1250. .procname = "uuid",
  1251. .maxlen = 16,
  1252. .mode = 0444,
  1253. .proc_handler = proc_do_uuid,
  1254. },
  1255. { }
  1256. };
  1257. #endif /* CONFIG_SYSCTL */
  1258. static u32 random_int_secret[MD5_MESSAGE_BYTES / 4] ____cacheline_aligned;
  1259. static int __init random_int_secret_init(void)
  1260. {
  1261. get_random_bytes(random_int_secret, sizeof(random_int_secret));
  1262. return 0;
  1263. }
  1264. late_initcall(random_int_secret_init);
  1265. /*
  1266. * Get a random word for internal kernel use only. Similar to urandom but
  1267. * with the goal of minimal entropy pool depletion. As a result, the random
  1268. * value is not cryptographically secure but for several uses the cost of
  1269. * depleting entropy is too high
  1270. */
  1271. static DEFINE_PER_CPU(__u32 [MD5_DIGEST_WORDS], get_random_int_hash);
  1272. unsigned int get_random_int(void)
  1273. {
  1274. __u32 *hash;
  1275. unsigned int ret;
  1276. if (arch_get_random_int(&ret))
  1277. return ret;
  1278. hash = get_cpu_var(get_random_int_hash);
  1279. hash[0] += current->pid + jiffies + get_cycles();
  1280. md5_transform(hash, random_int_secret);
  1281. ret = hash[0];
  1282. put_cpu_var(get_random_int_hash);
  1283. return ret;
  1284. }
  1285. /*
  1286. * randomize_range() returns a start address such that
  1287. *
  1288. * [...... <range> .....]
  1289. * start end
  1290. *
  1291. * a <range> with size "len" starting at the return value is inside in the
  1292. * area defined by [start, end], but is otherwise randomized.
  1293. */
  1294. unsigned long
  1295. randomize_range(unsigned long start, unsigned long end, unsigned long len)
  1296. {
  1297. unsigned long range = end - len - start;
  1298. if (end <= start + len)
  1299. return 0;
  1300. return PAGE_ALIGN(get_random_int() % range + start);
  1301. }