random.c 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643
  1. // SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
  2. /*
  3. * Copyright (C) 2017-2022 Jason A. Donenfeld <[email protected]>. All Rights Reserved.
  4. * Copyright Matt Mackall <[email protected]>, 2003, 2004, 2005
  5. * Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999. All rights reserved.
  6. *
  7. * This driver produces cryptographically secure pseudorandom data. It is divided
  8. * into roughly six sections, each with a section header:
  9. *
  10. * - Initialization and readiness waiting.
  11. * - Fast key erasure RNG, the "crng".
  12. * - Entropy accumulation and extraction routines.
  13. * - Entropy collection routines.
  14. * - Userspace reader/writer interfaces.
  15. * - Sysctl interface.
  16. *
  17. * The high level overview is that there is one input pool, into which
  18. * various pieces of data are hashed. Prior to initialization, some of that
  19. * data is then "credited" as having a certain number of bits of entropy.
  20. * When enough bits of entropy are available, the hash is finalized and
  21. * handed as a key to a stream cipher that expands it indefinitely for
  22. * various consumers. This key is periodically refreshed as the various
  23. * entropy collectors, described below, add data to the input pool.
  24. */
  25. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  26. #include <linux/utsname.h>
  27. #include <linux/module.h>
  28. #include <linux/kernel.h>
  29. #include <linux/major.h>
  30. #include <linux/string.h>
  31. #include <linux/fcntl.h>
  32. #include <linux/slab.h>
  33. #include <linux/random.h>
  34. #include <linux/poll.h>
  35. #include <linux/init.h>
  36. #include <linux/fs.h>
  37. #include <linux/blkdev.h>
  38. #include <linux/interrupt.h>
  39. #include <linux/mm.h>
  40. #include <linux/nodemask.h>
  41. #include <linux/spinlock.h>
  42. #include <linux/kthread.h>
  43. #include <linux/percpu.h>
  44. #include <linux/ptrace.h>
  45. #include <linux/workqueue.h>
  46. #include <linux/irq.h>
  47. #include <linux/ratelimit.h>
  48. #include <linux/syscalls.h>
  49. #include <linux/completion.h>
  50. #include <linux/uuid.h>
  51. #include <linux/uaccess.h>
  52. #include <linux/suspend.h>
  53. #include <linux/siphash.h>
  54. #include <crypto/chacha.h>
  55. #include <crypto/blake2s.h>
  56. #include <asm/processor.h>
  57. #include <asm/irq.h>
  58. #include <asm/irq_regs.h>
  59. #include <asm/io.h>
  60. /*********************************************************************
  61. *
  62. * Initialization and readiness waiting.
  63. *
  64. * Much of the RNG infrastructure is devoted to various dependencies
  65. * being able to wait until the RNG has collected enough entropy and
  66. * is ready for safe consumption.
  67. *
  68. *********************************************************************/
  69. /*
  70. * crng_init is protected by base_crng->lock, and only increases
  71. * its value (from empty->early->ready).
  72. */
  73. static enum {
  74. CRNG_EMPTY = 0, /* Little to no entropy collected */
  75. CRNG_EARLY = 1, /* At least POOL_EARLY_BITS collected */
  76. CRNG_READY = 2 /* Fully initialized with POOL_READY_BITS collected */
  77. } crng_init __read_mostly = CRNG_EMPTY;
  78. static DEFINE_STATIC_KEY_FALSE(crng_is_ready);
  79. #define crng_ready() (static_branch_likely(&crng_is_ready) || crng_init >= CRNG_READY)
  80. /* Various types of waiters for crng_init->CRNG_READY transition. */
  81. static DECLARE_WAIT_QUEUE_HEAD(crng_init_wait);
  82. static struct fasync_struct *fasync;
  83. /* Control how we warn userspace. */
  84. static struct ratelimit_state urandom_warning =
  85. RATELIMIT_STATE_INIT_FLAGS("urandom_warning", HZ, 3, RATELIMIT_MSG_ON_RELEASE);
  86. static int ratelimit_disable __read_mostly =
  87. IS_ENABLED(CONFIG_WARN_ALL_UNSEEDED_RANDOM);
  88. module_param_named(ratelimit_disable, ratelimit_disable, int, 0644);
  89. MODULE_PARM_DESC(ratelimit_disable, "Disable random ratelimit suppression");
  90. /*
  91. * Returns whether or not the input pool has been seeded and thus guaranteed
  92. * to supply cryptographically secure random numbers. This applies to: the
  93. * /dev/urandom device, the get_random_bytes function, and the get_random_{u8,
  94. * u16,u32,u64,long} family of functions.
  95. *
  96. * Returns: true if the input pool has been seeded.
  97. * false if the input pool has not been seeded.
  98. */
  99. bool rng_is_initialized(void)
  100. {
  101. return crng_ready();
  102. }
  103. EXPORT_SYMBOL(rng_is_initialized);
  104. static void __cold crng_set_ready(struct work_struct *work)
  105. {
  106. static_branch_enable(&crng_is_ready);
  107. }
  108. /* Used by wait_for_random_bytes(), and considered an entropy collector, below. */
  109. static void try_to_generate_entropy(void);
  110. /*
  111. * Wait for the input pool to be seeded and thus guaranteed to supply
  112. * cryptographically secure random numbers. This applies to: the /dev/urandom
  113. * device, the get_random_bytes function, and the get_random_{u8,u16,u32,u64,
  114. * int,long} family of functions. Using any of these functions without first
  115. * calling this function forfeits the guarantee of security.
  116. *
  117. * Returns: 0 if the input pool has been seeded.
  118. * -ERESTARTSYS if the function was interrupted by a signal.
  119. */
  120. int wait_for_random_bytes(void)
  121. {
  122. while (!crng_ready()) {
  123. int ret;
  124. try_to_generate_entropy();
  125. ret = wait_event_interruptible_timeout(crng_init_wait, crng_ready(), HZ);
  126. if (ret)
  127. return ret > 0 ? 0 : ret;
  128. }
  129. return 0;
  130. }
  131. EXPORT_SYMBOL(wait_for_random_bytes);
  132. #define warn_unseeded_randomness() \
  133. if (IS_ENABLED(CONFIG_WARN_ALL_UNSEEDED_RANDOM) && !crng_ready()) \
  134. printk_deferred(KERN_NOTICE "random: %s called from %pS with crng_init=%d\n", \
  135. __func__, (void *)_RET_IP_, crng_init)
  136. /*********************************************************************
  137. *
  138. * Fast key erasure RNG, the "crng".
  139. *
  140. * These functions expand entropy from the entropy extractor into
  141. * long streams for external consumption using the "fast key erasure"
  142. * RNG described at <https://blog.cr.yp.to/20170723-random.html>.
  143. *
  144. * There are a few exported interfaces for use by other drivers:
  145. *
  146. * void get_random_bytes(void *buf, size_t len)
  147. * u8 get_random_u8()
  148. * u16 get_random_u16()
  149. * u32 get_random_u32()
  150. * u32 get_random_u32_below(u32 ceil)
  151. * u32 get_random_u32_above(u32 floor)
  152. * u32 get_random_u32_inclusive(u32 floor, u32 ceil)
  153. * u64 get_random_u64()
  154. * unsigned long get_random_long()
  155. *
  156. * These interfaces will return the requested number of random bytes
  157. * into the given buffer or as a return value. This is equivalent to
  158. * a read from /dev/urandom. The u8, u16, u32, u64, long family of
  159. * functions may be higher performance for one-off random integers,
  160. * because they do a bit of buffering and do not invoke reseeding
  161. * until the buffer is emptied.
  162. *
  163. *********************************************************************/
  164. enum {
  165. CRNG_RESEED_START_INTERVAL = HZ,
  166. CRNG_RESEED_INTERVAL = 60 * HZ
  167. };
  168. static struct {
  169. u8 key[CHACHA_KEY_SIZE] __aligned(__alignof__(long));
  170. unsigned long birth;
  171. unsigned long generation;
  172. spinlock_t lock;
  173. } base_crng = {
  174. .lock = __SPIN_LOCK_UNLOCKED(base_crng.lock)
  175. };
  176. struct crng {
  177. u8 key[CHACHA_KEY_SIZE];
  178. unsigned long generation;
  179. local_lock_t lock;
  180. };
  181. static DEFINE_PER_CPU(struct crng, crngs) = {
  182. .generation = ULONG_MAX,
  183. .lock = INIT_LOCAL_LOCK(crngs.lock),
  184. };
  185. /* Used by crng_reseed() and crng_make_state() to extract a new seed from the input pool. */
  186. static void extract_entropy(void *buf, size_t len);
  187. /* This extracts a new crng key from the input pool. */
  188. static void crng_reseed(void)
  189. {
  190. unsigned long flags;
  191. unsigned long next_gen;
  192. u8 key[CHACHA_KEY_SIZE];
  193. extract_entropy(key, sizeof(key));
  194. /*
  195. * We copy the new key into the base_crng, overwriting the old one,
  196. * and update the generation counter. We avoid hitting ULONG_MAX,
  197. * because the per-cpu crngs are initialized to ULONG_MAX, so this
  198. * forces new CPUs that come online to always initialize.
  199. */
  200. spin_lock_irqsave(&base_crng.lock, flags);
  201. memcpy(base_crng.key, key, sizeof(base_crng.key));
  202. next_gen = base_crng.generation + 1;
  203. if (next_gen == ULONG_MAX)
  204. ++next_gen;
  205. WRITE_ONCE(base_crng.generation, next_gen);
  206. WRITE_ONCE(base_crng.birth, jiffies);
  207. if (!static_branch_likely(&crng_is_ready))
  208. crng_init = CRNG_READY;
  209. spin_unlock_irqrestore(&base_crng.lock, flags);
  210. memzero_explicit(key, sizeof(key));
  211. }
  212. /*
  213. * This generates a ChaCha block using the provided key, and then
  214. * immediately overwrites that key with half the block. It returns
  215. * the resultant ChaCha state to the user, along with the second
  216. * half of the block containing 32 bytes of random data that may
  217. * be used; random_data_len may not be greater than 32.
  218. *
  219. * The returned ChaCha state contains within it a copy of the old
  220. * key value, at index 4, so the state should always be zeroed out
  221. * immediately after using in order to maintain forward secrecy.
  222. * If the state cannot be erased in a timely manner, then it is
  223. * safer to set the random_data parameter to &chacha_state[4] so
  224. * that this function overwrites it before returning.
  225. */
  226. static void crng_fast_key_erasure(u8 key[CHACHA_KEY_SIZE],
  227. u32 chacha_state[CHACHA_STATE_WORDS],
  228. u8 *random_data, size_t random_data_len)
  229. {
  230. u8 first_block[CHACHA_BLOCK_SIZE];
  231. BUG_ON(random_data_len > 32);
  232. chacha_init_consts(chacha_state);
  233. memcpy(&chacha_state[4], key, CHACHA_KEY_SIZE);
  234. memset(&chacha_state[12], 0, sizeof(u32) * 4);
  235. chacha20_block(chacha_state, first_block);
  236. memcpy(key, first_block, CHACHA_KEY_SIZE);
  237. memcpy(random_data, first_block + CHACHA_KEY_SIZE, random_data_len);
  238. memzero_explicit(first_block, sizeof(first_block));
  239. }
  240. /*
  241. * Return the interval until the next reseeding, which is normally
  242. * CRNG_RESEED_INTERVAL, but during early boot, it is at an interval
  243. * proportional to the uptime.
  244. */
  245. static unsigned int crng_reseed_interval(void)
  246. {
  247. static bool early_boot = true;
  248. if (unlikely(READ_ONCE(early_boot))) {
  249. time64_t uptime = ktime_get_seconds();
  250. if (uptime >= CRNG_RESEED_INTERVAL / HZ * 2)
  251. WRITE_ONCE(early_boot, false);
  252. else
  253. return max_t(unsigned int, CRNG_RESEED_START_INTERVAL,
  254. (unsigned int)uptime / 2 * HZ);
  255. }
  256. return CRNG_RESEED_INTERVAL;
  257. }
  258. /*
  259. * This function returns a ChaCha state that you may use for generating
  260. * random data. It also returns up to 32 bytes on its own of random data
  261. * that may be used; random_data_len may not be greater than 32.
  262. */
  263. static void crng_make_state(u32 chacha_state[CHACHA_STATE_WORDS],
  264. u8 *random_data, size_t random_data_len)
  265. {
  266. unsigned long flags;
  267. struct crng *crng;
  268. BUG_ON(random_data_len > 32);
  269. /*
  270. * For the fast path, we check whether we're ready, unlocked first, and
  271. * then re-check once locked later. In the case where we're really not
  272. * ready, we do fast key erasure with the base_crng directly, extracting
  273. * when crng_init is CRNG_EMPTY.
  274. */
  275. if (!crng_ready()) {
  276. bool ready;
  277. spin_lock_irqsave(&base_crng.lock, flags);
  278. ready = crng_ready();
  279. if (!ready) {
  280. if (crng_init == CRNG_EMPTY)
  281. extract_entropy(base_crng.key, sizeof(base_crng.key));
  282. crng_fast_key_erasure(base_crng.key, chacha_state,
  283. random_data, random_data_len);
  284. }
  285. spin_unlock_irqrestore(&base_crng.lock, flags);
  286. if (!ready)
  287. return;
  288. }
  289. /*
  290. * If the base_crng is old enough, we reseed, which in turn bumps the
  291. * generation counter that we check below.
  292. */
  293. if (unlikely(time_is_before_jiffies(READ_ONCE(base_crng.birth) + crng_reseed_interval())))
  294. crng_reseed();
  295. local_lock_irqsave(&crngs.lock, flags);
  296. crng = raw_cpu_ptr(&crngs);
  297. /*
  298. * If our per-cpu crng is older than the base_crng, then it means
  299. * somebody reseeded the base_crng. In that case, we do fast key
  300. * erasure on the base_crng, and use its output as the new key
  301. * for our per-cpu crng. This brings us up to date with base_crng.
  302. */
  303. if (unlikely(crng->generation != READ_ONCE(base_crng.generation))) {
  304. spin_lock(&base_crng.lock);
  305. crng_fast_key_erasure(base_crng.key, chacha_state,
  306. crng->key, sizeof(crng->key));
  307. crng->generation = base_crng.generation;
  308. spin_unlock(&base_crng.lock);
  309. }
  310. /*
  311. * Finally, when we've made it this far, our per-cpu crng has an up
  312. * to date key, and we can do fast key erasure with it to produce
  313. * some random data and a ChaCha state for the caller. All other
  314. * branches of this function are "unlikely", so most of the time we
  315. * should wind up here immediately.
  316. */
  317. crng_fast_key_erasure(crng->key, chacha_state, random_data, random_data_len);
  318. local_unlock_irqrestore(&crngs.lock, flags);
  319. }
  320. static void _get_random_bytes(void *buf, size_t len)
  321. {
  322. u32 chacha_state[CHACHA_STATE_WORDS];
  323. u8 tmp[CHACHA_BLOCK_SIZE];
  324. size_t first_block_len;
  325. if (!len)
  326. return;
  327. first_block_len = min_t(size_t, 32, len);
  328. crng_make_state(chacha_state, buf, first_block_len);
  329. len -= first_block_len;
  330. buf += first_block_len;
  331. while (len) {
  332. if (len < CHACHA_BLOCK_SIZE) {
  333. chacha20_block(chacha_state, tmp);
  334. memcpy(buf, tmp, len);
  335. memzero_explicit(tmp, sizeof(tmp));
  336. break;
  337. }
  338. chacha20_block(chacha_state, buf);
  339. if (unlikely(chacha_state[12] == 0))
  340. ++chacha_state[13];
  341. len -= CHACHA_BLOCK_SIZE;
  342. buf += CHACHA_BLOCK_SIZE;
  343. }
  344. memzero_explicit(chacha_state, sizeof(chacha_state));
  345. }
  346. /*
  347. * This function is the exported kernel interface. It returns some number of
  348. * good random numbers, suitable for key generation, seeding TCP sequence
  349. * numbers, etc. In order to ensure that the randomness returned by this
  350. * function is okay, the function wait_for_random_bytes() should be called and
  351. * return 0 at least once at any point prior.
  352. */
  353. void get_random_bytes(void *buf, size_t len)
  354. {
  355. warn_unseeded_randomness();
  356. _get_random_bytes(buf, len);
  357. }
  358. EXPORT_SYMBOL(get_random_bytes);
  359. static ssize_t get_random_bytes_user(struct iov_iter *iter)
  360. {
  361. u32 chacha_state[CHACHA_STATE_WORDS];
  362. u8 block[CHACHA_BLOCK_SIZE];
  363. size_t ret = 0, copied;
  364. if (unlikely(!iov_iter_count(iter)))
  365. return 0;
  366. /*
  367. * Immediately overwrite the ChaCha key at index 4 with random
  368. * bytes, in case userspace causes copy_to_iter() below to sleep
  369. * forever, so that we still retain forward secrecy in that case.
  370. */
  371. crng_make_state(chacha_state, (u8 *)&chacha_state[4], CHACHA_KEY_SIZE);
  372. /*
  373. * However, if we're doing a read of len <= 32, we don't need to
  374. * use chacha_state after, so we can simply return those bytes to
  375. * the user directly.
  376. */
  377. if (iov_iter_count(iter) <= CHACHA_KEY_SIZE) {
  378. ret = copy_to_iter(&chacha_state[4], CHACHA_KEY_SIZE, iter);
  379. goto out_zero_chacha;
  380. }
  381. for (;;) {
  382. chacha20_block(chacha_state, block);
  383. if (unlikely(chacha_state[12] == 0))
  384. ++chacha_state[13];
  385. copied = copy_to_iter(block, sizeof(block), iter);
  386. ret += copied;
  387. if (!iov_iter_count(iter) || copied != sizeof(block))
  388. break;
  389. BUILD_BUG_ON(PAGE_SIZE % sizeof(block) != 0);
  390. if (ret % PAGE_SIZE == 0) {
  391. if (signal_pending(current))
  392. break;
  393. cond_resched();
  394. }
  395. }
  396. memzero_explicit(block, sizeof(block));
  397. out_zero_chacha:
  398. memzero_explicit(chacha_state, sizeof(chacha_state));
  399. return ret ? ret : -EFAULT;
  400. }
  401. /*
  402. * Batched entropy returns random integers. The quality of the random
  403. * number is good as /dev/urandom. In order to ensure that the randomness
  404. * provided by this function is okay, the function wait_for_random_bytes()
  405. * should be called and return 0 at least once at any point prior.
  406. */
  407. #define DEFINE_BATCHED_ENTROPY(type) \
  408. struct batch_ ##type { \
  409. /* \
  410. * We make this 1.5x a ChaCha block, so that we get the \
  411. * remaining 32 bytes from fast key erasure, plus one full \
  412. * block from the detached ChaCha state. We can increase \
  413. * the size of this later if needed so long as we keep the \
  414. * formula of (integer_blocks + 0.5) * CHACHA_BLOCK_SIZE. \
  415. */ \
  416. type entropy[CHACHA_BLOCK_SIZE * 3 / (2 * sizeof(type))]; \
  417. local_lock_t lock; \
  418. unsigned long generation; \
  419. unsigned int position; \
  420. }; \
  421. \
  422. static DEFINE_PER_CPU(struct batch_ ##type, batched_entropy_ ##type) = { \
  423. .lock = INIT_LOCAL_LOCK(batched_entropy_ ##type.lock), \
  424. .position = UINT_MAX \
  425. }; \
  426. \
  427. type get_random_ ##type(void) \
  428. { \
  429. type ret; \
  430. unsigned long flags; \
  431. struct batch_ ##type *batch; \
  432. unsigned long next_gen; \
  433. \
  434. warn_unseeded_randomness(); \
  435. \
  436. if (!crng_ready()) { \
  437. _get_random_bytes(&ret, sizeof(ret)); \
  438. return ret; \
  439. } \
  440. \
  441. local_lock_irqsave(&batched_entropy_ ##type.lock, flags); \
  442. batch = raw_cpu_ptr(&batched_entropy_##type); \
  443. \
  444. next_gen = READ_ONCE(base_crng.generation); \
  445. if (batch->position >= ARRAY_SIZE(batch->entropy) || \
  446. next_gen != batch->generation) { \
  447. _get_random_bytes(batch->entropy, sizeof(batch->entropy)); \
  448. batch->position = 0; \
  449. batch->generation = next_gen; \
  450. } \
  451. \
  452. ret = batch->entropy[batch->position]; \
  453. batch->entropy[batch->position] = 0; \
  454. ++batch->position; \
  455. local_unlock_irqrestore(&batched_entropy_ ##type.lock, flags); \
  456. return ret; \
  457. } \
  458. EXPORT_SYMBOL(get_random_ ##type);
  459. DEFINE_BATCHED_ENTROPY(u8)
  460. DEFINE_BATCHED_ENTROPY(u16)
  461. DEFINE_BATCHED_ENTROPY(u32)
  462. DEFINE_BATCHED_ENTROPY(u64)
  463. u32 __get_random_u32_below(u32 ceil)
  464. {
  465. /*
  466. * This is the slow path for variable ceil. It is still fast, most of
  467. * the time, by doing traditional reciprocal multiplication and
  468. * opportunistically comparing the lower half to ceil itself, before
  469. * falling back to computing a larger bound, and then rejecting samples
  470. * whose lower half would indicate a range indivisible by ceil. The use
  471. * of `-ceil % ceil` is analogous to `2^32 % ceil`, but is computable
  472. * in 32-bits.
  473. */
  474. u32 rand = get_random_u32();
  475. u64 mult;
  476. /*
  477. * This function is technically undefined for ceil == 0, and in fact
  478. * for the non-underscored constant version in the header, we build bug
  479. * on that. But for the non-constant case, it's convenient to have that
  480. * evaluate to being a straight call to get_random_u32(), so that
  481. * get_random_u32_inclusive() can work over its whole range without
  482. * undefined behavior.
  483. */
  484. if (unlikely(!ceil))
  485. return rand;
  486. mult = (u64)ceil * rand;
  487. if (unlikely((u32)mult < ceil)) {
  488. u32 bound = -ceil % ceil;
  489. while (unlikely((u32)mult < bound))
  490. mult = (u64)ceil * get_random_u32();
  491. }
  492. return mult >> 32;
  493. }
  494. EXPORT_SYMBOL(__get_random_u32_below);
  495. #ifdef CONFIG_SMP
  496. /*
  497. * This function is called when the CPU is coming up, with entry
  498. * CPUHP_RANDOM_PREPARE, which comes before CPUHP_WORKQUEUE_PREP.
  499. */
  500. int __cold random_prepare_cpu(unsigned int cpu)
  501. {
  502. /*
  503. * When the cpu comes back online, immediately invalidate both
  504. * the per-cpu crng and all batches, so that we serve fresh
  505. * randomness.
  506. */
  507. per_cpu_ptr(&crngs, cpu)->generation = ULONG_MAX;
  508. per_cpu_ptr(&batched_entropy_u8, cpu)->position = UINT_MAX;
  509. per_cpu_ptr(&batched_entropy_u16, cpu)->position = UINT_MAX;
  510. per_cpu_ptr(&batched_entropy_u32, cpu)->position = UINT_MAX;
  511. per_cpu_ptr(&batched_entropy_u64, cpu)->position = UINT_MAX;
  512. return 0;
  513. }
  514. #endif
  515. /**********************************************************************
  516. *
  517. * Entropy accumulation and extraction routines.
  518. *
  519. * Callers may add entropy via:
  520. *
  521. * static void mix_pool_bytes(const void *buf, size_t len)
  522. *
  523. * After which, if added entropy should be credited:
  524. *
  525. * static void credit_init_bits(size_t bits)
  526. *
  527. * Finally, extract entropy via:
  528. *
  529. * static void extract_entropy(void *buf, size_t len)
  530. *
  531. **********************************************************************/
  532. enum {
  533. POOL_BITS = BLAKE2S_HASH_SIZE * 8,
  534. POOL_READY_BITS = POOL_BITS, /* When crng_init->CRNG_READY */
  535. POOL_EARLY_BITS = POOL_READY_BITS / 2 /* When crng_init->CRNG_EARLY */
  536. };
  537. static struct {
  538. struct blake2s_state hash;
  539. spinlock_t lock;
  540. unsigned int init_bits;
  541. } input_pool = {
  542. .hash.h = { BLAKE2S_IV0 ^ (0x01010000 | BLAKE2S_HASH_SIZE),
  543. BLAKE2S_IV1, BLAKE2S_IV2, BLAKE2S_IV3, BLAKE2S_IV4,
  544. BLAKE2S_IV5, BLAKE2S_IV6, BLAKE2S_IV7 },
  545. .hash.outlen = BLAKE2S_HASH_SIZE,
  546. .lock = __SPIN_LOCK_UNLOCKED(input_pool.lock),
  547. };
  548. static void _mix_pool_bytes(const void *buf, size_t len)
  549. {
  550. blake2s_update(&input_pool.hash, buf, len);
  551. }
  552. /*
  553. * This function adds bytes into the input pool. It does not
  554. * update the initialization bit counter; the caller should call
  555. * credit_init_bits if this is appropriate.
  556. */
  557. static void mix_pool_bytes(const void *buf, size_t len)
  558. {
  559. unsigned long flags;
  560. spin_lock_irqsave(&input_pool.lock, flags);
  561. _mix_pool_bytes(buf, len);
  562. spin_unlock_irqrestore(&input_pool.lock, flags);
  563. }
  564. /*
  565. * This is an HKDF-like construction for using the hashed collected entropy
  566. * as a PRF key, that's then expanded block-by-block.
  567. */
  568. static void extract_entropy(void *buf, size_t len)
  569. {
  570. unsigned long flags;
  571. u8 seed[BLAKE2S_HASH_SIZE], next_key[BLAKE2S_HASH_SIZE];
  572. struct {
  573. unsigned long rdseed[32 / sizeof(long)];
  574. size_t counter;
  575. } block;
  576. size_t i, longs;
  577. for (i = 0; i < ARRAY_SIZE(block.rdseed);) {
  578. longs = arch_get_random_seed_longs(&block.rdseed[i], ARRAY_SIZE(block.rdseed) - i);
  579. if (longs) {
  580. i += longs;
  581. continue;
  582. }
  583. longs = arch_get_random_longs(&block.rdseed[i], ARRAY_SIZE(block.rdseed) - i);
  584. if (longs) {
  585. i += longs;
  586. continue;
  587. }
  588. block.rdseed[i++] = random_get_entropy();
  589. }
  590. spin_lock_irqsave(&input_pool.lock, flags);
  591. /* seed = HASHPRF(last_key, entropy_input) */
  592. blake2s_final(&input_pool.hash, seed);
  593. /* next_key = HASHPRF(seed, RDSEED || 0) */
  594. block.counter = 0;
  595. blake2s(next_key, (u8 *)&block, seed, sizeof(next_key), sizeof(block), sizeof(seed));
  596. blake2s_init_key(&input_pool.hash, BLAKE2S_HASH_SIZE, next_key, sizeof(next_key));
  597. spin_unlock_irqrestore(&input_pool.lock, flags);
  598. memzero_explicit(next_key, sizeof(next_key));
  599. while (len) {
  600. i = min_t(size_t, len, BLAKE2S_HASH_SIZE);
  601. /* output = HASHPRF(seed, RDSEED || ++counter) */
  602. ++block.counter;
  603. blake2s(buf, (u8 *)&block, seed, i, sizeof(block), sizeof(seed));
  604. len -= i;
  605. buf += i;
  606. }
  607. memzero_explicit(seed, sizeof(seed));
  608. memzero_explicit(&block, sizeof(block));
  609. }
  610. #define credit_init_bits(bits) if (!crng_ready()) _credit_init_bits(bits)
  611. static void __cold _credit_init_bits(size_t bits)
  612. {
  613. static struct execute_work set_ready;
  614. unsigned int new, orig, add;
  615. unsigned long flags;
  616. if (!bits)
  617. return;
  618. add = min_t(size_t, bits, POOL_BITS);
  619. orig = READ_ONCE(input_pool.init_bits);
  620. do {
  621. new = min_t(unsigned int, POOL_BITS, orig + add);
  622. } while (!try_cmpxchg(&input_pool.init_bits, &orig, new));
  623. if (orig < POOL_READY_BITS && new >= POOL_READY_BITS) {
  624. crng_reseed(); /* Sets crng_init to CRNG_READY under base_crng.lock. */
  625. if (static_key_initialized)
  626. execute_in_process_context(crng_set_ready, &set_ready);
  627. wake_up_interruptible(&crng_init_wait);
  628. kill_fasync(&fasync, SIGIO, POLL_IN);
  629. pr_notice("crng init done\n");
  630. if (urandom_warning.missed)
  631. pr_notice("%d urandom warning(s) missed due to ratelimiting\n",
  632. urandom_warning.missed);
  633. } else if (orig < POOL_EARLY_BITS && new >= POOL_EARLY_BITS) {
  634. spin_lock_irqsave(&base_crng.lock, flags);
  635. /* Check if crng_init is CRNG_EMPTY, to avoid race with crng_reseed(). */
  636. if (crng_init == CRNG_EMPTY) {
  637. extract_entropy(base_crng.key, sizeof(base_crng.key));
  638. crng_init = CRNG_EARLY;
  639. }
  640. spin_unlock_irqrestore(&base_crng.lock, flags);
  641. }
  642. }
  643. /**********************************************************************
  644. *
  645. * Entropy collection routines.
  646. *
  647. * The following exported functions are used for pushing entropy into
  648. * the above entropy accumulation routines:
  649. *
  650. * void add_device_randomness(const void *buf, size_t len);
  651. * void add_hwgenerator_randomness(const void *buf, size_t len, size_t entropy);
  652. * void add_bootloader_randomness(const void *buf, size_t len);
  653. * void add_vmfork_randomness(const void *unique_vm_id, size_t len);
  654. * void add_interrupt_randomness(int irq);
  655. * void add_input_randomness(unsigned int type, unsigned int code, unsigned int value);
  656. * void add_disk_randomness(struct gendisk *disk);
  657. *
  658. * add_device_randomness() adds data to the input pool that
  659. * is likely to differ between two devices (or possibly even per boot).
  660. * This would be things like MAC addresses or serial numbers, or the
  661. * read-out of the RTC. This does *not* credit any actual entropy to
  662. * the pool, but it initializes the pool to different values for devices
  663. * that might otherwise be identical and have very little entropy
  664. * available to them (particularly common in the embedded world).
  665. *
  666. * add_hwgenerator_randomness() is for true hardware RNGs, and will credit
  667. * entropy as specified by the caller. If the entropy pool is full it will
  668. * block until more entropy is needed.
  669. *
  670. * add_bootloader_randomness() is called by bootloader drivers, such as EFI
  671. * and device tree, and credits its input depending on whether or not the
  672. * configuration option CONFIG_RANDOM_TRUST_BOOTLOADER is set.
  673. *
  674. * add_vmfork_randomness() adds a unique (but not necessarily secret) ID
  675. * representing the current instance of a VM to the pool, without crediting,
  676. * and then force-reseeds the crng so that it takes effect immediately.
  677. *
  678. * add_interrupt_randomness() uses the interrupt timing as random
  679. * inputs to the entropy pool. Using the cycle counters and the irq source
  680. * as inputs, it feeds the input pool roughly once a second or after 64
  681. * interrupts, crediting 1 bit of entropy for whichever comes first.
  682. *
  683. * add_input_randomness() uses the input layer interrupt timing, as well
  684. * as the event type information from the hardware.
  685. *
  686. * add_disk_randomness() uses what amounts to the seek time of block
  687. * layer request events, on a per-disk_devt basis, as input to the
  688. * entropy pool. Note that high-speed solid state drives with very low
  689. * seek times do not make for good sources of entropy, as their seek
  690. * times are usually fairly consistent.
  691. *
  692. * The last two routines try to estimate how many bits of entropy
  693. * to credit. They do this by keeping track of the first and second
  694. * order deltas of the event timings.
  695. *
  696. **********************************************************************/
  697. static bool trust_cpu __initdata = IS_ENABLED(CONFIG_RANDOM_TRUST_CPU);
  698. static bool trust_bootloader __initdata = IS_ENABLED(CONFIG_RANDOM_TRUST_BOOTLOADER);
  699. static int __init parse_trust_cpu(char *arg)
  700. {
  701. return kstrtobool(arg, &trust_cpu);
  702. }
  703. static int __init parse_trust_bootloader(char *arg)
  704. {
  705. return kstrtobool(arg, &trust_bootloader);
  706. }
  707. early_param("random.trust_cpu", parse_trust_cpu);
  708. early_param("random.trust_bootloader", parse_trust_bootloader);
  709. static int random_pm_notification(struct notifier_block *nb, unsigned long action, void *data)
  710. {
  711. unsigned long flags, entropy = random_get_entropy();
  712. /*
  713. * Encode a representation of how long the system has been suspended,
  714. * in a way that is distinct from prior system suspends.
  715. */
  716. ktime_t stamps[] = { ktime_get(), ktime_get_boottime(), ktime_get_real() };
  717. spin_lock_irqsave(&input_pool.lock, flags);
  718. _mix_pool_bytes(&action, sizeof(action));
  719. _mix_pool_bytes(stamps, sizeof(stamps));
  720. _mix_pool_bytes(&entropy, sizeof(entropy));
  721. spin_unlock_irqrestore(&input_pool.lock, flags);
  722. if (crng_ready() && (action == PM_RESTORE_PREPARE ||
  723. (action == PM_POST_SUSPEND && !IS_ENABLED(CONFIG_PM_AUTOSLEEP) &&
  724. !IS_ENABLED(CONFIG_PM_USERSPACE_AUTOSLEEP)))) {
  725. crng_reseed();
  726. pr_notice("crng reseeded on system resumption\n");
  727. }
  728. return 0;
  729. }
  730. static struct notifier_block pm_notifier = { .notifier_call = random_pm_notification };
  731. /*
  732. * This is called extremely early, before time keeping functionality is
  733. * available, but arch randomness is. Interrupts are not yet enabled.
  734. */
  735. void __init random_init_early(const char *command_line)
  736. {
  737. unsigned long entropy[BLAKE2S_BLOCK_SIZE / sizeof(long)];
  738. size_t i, longs, arch_bits;
  739. #if defined(LATENT_ENTROPY_PLUGIN)
  740. static const u8 compiletime_seed[BLAKE2S_BLOCK_SIZE] __initconst __latent_entropy;
  741. _mix_pool_bytes(compiletime_seed, sizeof(compiletime_seed));
  742. #endif
  743. for (i = 0, arch_bits = sizeof(entropy) * 8; i < ARRAY_SIZE(entropy);) {
  744. longs = arch_get_random_seed_longs_early(entropy, ARRAY_SIZE(entropy) - i);
  745. if (longs) {
  746. _mix_pool_bytes(entropy, sizeof(*entropy) * longs);
  747. i += longs;
  748. continue;
  749. }
  750. longs = arch_get_random_longs_early(entropy, ARRAY_SIZE(entropy) - i);
  751. if (longs) {
  752. _mix_pool_bytes(entropy, sizeof(*entropy) * longs);
  753. i += longs;
  754. continue;
  755. }
  756. arch_bits -= sizeof(*entropy) * 8;
  757. ++i;
  758. }
  759. _mix_pool_bytes(init_utsname(), sizeof(*(init_utsname())));
  760. _mix_pool_bytes(command_line, strlen(command_line));
  761. /* Reseed if already seeded by earlier phases. */
  762. if (crng_ready())
  763. crng_reseed();
  764. else if (trust_cpu)
  765. _credit_init_bits(arch_bits);
  766. }
  767. /*
  768. * This is called a little bit after the prior function, and now there is
  769. * access to timestamps counters. Interrupts are not yet enabled.
  770. */
  771. void __init random_init(void)
  772. {
  773. unsigned long entropy = random_get_entropy();
  774. ktime_t now = ktime_get_real();
  775. _mix_pool_bytes(&now, sizeof(now));
  776. _mix_pool_bytes(&entropy, sizeof(entropy));
  777. add_latent_entropy();
  778. /*
  779. * If we were initialized by the cpu or bootloader before jump labels
  780. * are initialized, then we should enable the static branch here, where
  781. * it's guaranteed that jump labels have been initialized.
  782. */
  783. if (!static_branch_likely(&crng_is_ready) && crng_init >= CRNG_READY)
  784. crng_set_ready(NULL);
  785. /* Reseed if already seeded by earlier phases. */
  786. if (crng_ready())
  787. crng_reseed();
  788. WARN_ON(register_pm_notifier(&pm_notifier));
  789. WARN(!entropy, "Missing cycle counter and fallback timer; RNG "
  790. "entropy collection will consequently suffer.");
  791. }
  792. /*
  793. * Add device- or boot-specific data to the input pool to help
  794. * initialize it.
  795. *
  796. * None of this adds any entropy; it is meant to avoid the problem of
  797. * the entropy pool having similar initial state across largely
  798. * identical devices.
  799. */
  800. void add_device_randomness(const void *buf, size_t len)
  801. {
  802. unsigned long entropy = random_get_entropy();
  803. unsigned long flags;
  804. spin_lock_irqsave(&input_pool.lock, flags);
  805. _mix_pool_bytes(&entropy, sizeof(entropy));
  806. _mix_pool_bytes(buf, len);
  807. spin_unlock_irqrestore(&input_pool.lock, flags);
  808. }
  809. EXPORT_SYMBOL(add_device_randomness);
  810. /*
  811. * Interface for in-kernel drivers of true hardware RNGs.
  812. * Those devices may produce endless random bits and will be throttled
  813. * when our pool is full.
  814. */
  815. void add_hwgenerator_randomness(const void *buf, size_t len, size_t entropy)
  816. {
  817. mix_pool_bytes(buf, len);
  818. credit_init_bits(entropy);
  819. /*
  820. * Throttle writing to once every reseed interval, unless we're not yet
  821. * initialized or no entropy is credited.
  822. */
  823. if (!kthread_should_stop() && (crng_ready() || !entropy))
  824. schedule_timeout_interruptible(crng_reseed_interval());
  825. }
  826. EXPORT_SYMBOL_GPL(add_hwgenerator_randomness);
  827. /*
  828. * Handle random seed passed by bootloader, and credit it if
  829. * CONFIG_RANDOM_TRUST_BOOTLOADER is set.
  830. */
  831. void __init add_bootloader_randomness(const void *buf, size_t len)
  832. {
  833. mix_pool_bytes(buf, len);
  834. if (trust_bootloader)
  835. credit_init_bits(len * 8);
  836. }
  837. #if IS_ENABLED(CONFIG_VMGENID)
  838. static BLOCKING_NOTIFIER_HEAD(vmfork_chain);
  839. /*
  840. * Handle a new unique VM ID, which is unique, not secret, so we
  841. * don't credit it, but we do immediately force a reseed after so
  842. * that it's used by the crng posthaste.
  843. */
  844. void __cold add_vmfork_randomness(const void *unique_vm_id, size_t len)
  845. {
  846. add_device_randomness(unique_vm_id, len);
  847. if (crng_ready()) {
  848. crng_reseed();
  849. pr_notice("crng reseeded due to virtual machine fork\n");
  850. }
  851. blocking_notifier_call_chain(&vmfork_chain, 0, NULL);
  852. }
  853. #if IS_MODULE(CONFIG_VMGENID)
  854. EXPORT_SYMBOL_GPL(add_vmfork_randomness);
  855. #endif
  856. int __cold register_random_vmfork_notifier(struct notifier_block *nb)
  857. {
  858. return blocking_notifier_chain_register(&vmfork_chain, nb);
  859. }
  860. EXPORT_SYMBOL_GPL(register_random_vmfork_notifier);
  861. int __cold unregister_random_vmfork_notifier(struct notifier_block *nb)
  862. {
  863. return blocking_notifier_chain_unregister(&vmfork_chain, nb);
  864. }
  865. EXPORT_SYMBOL_GPL(unregister_random_vmfork_notifier);
  866. #endif
  867. struct fast_pool {
  868. unsigned long pool[4];
  869. unsigned long last;
  870. unsigned int count;
  871. struct timer_list mix;
  872. };
  873. static void mix_interrupt_randomness(struct timer_list *work);
  874. static DEFINE_PER_CPU(struct fast_pool, irq_randomness) = {
  875. #ifdef CONFIG_64BIT
  876. #define FASTMIX_PERM SIPHASH_PERMUTATION
  877. .pool = { SIPHASH_CONST_0, SIPHASH_CONST_1, SIPHASH_CONST_2, SIPHASH_CONST_3 },
  878. #else
  879. #define FASTMIX_PERM HSIPHASH_PERMUTATION
  880. .pool = { HSIPHASH_CONST_0, HSIPHASH_CONST_1, HSIPHASH_CONST_2, HSIPHASH_CONST_3 },
  881. #endif
  882. .mix = __TIMER_INITIALIZER(mix_interrupt_randomness, 0)
  883. };
  884. /*
  885. * This is [Half]SipHash-1-x, starting from an empty key. Because
  886. * the key is fixed, it assumes that its inputs are non-malicious,
  887. * and therefore this has no security on its own. s represents the
  888. * four-word SipHash state, while v represents a two-word input.
  889. */
  890. static void fast_mix(unsigned long s[4], unsigned long v1, unsigned long v2)
  891. {
  892. s[3] ^= v1;
  893. FASTMIX_PERM(s[0], s[1], s[2], s[3]);
  894. s[0] ^= v1;
  895. s[3] ^= v2;
  896. FASTMIX_PERM(s[0], s[1], s[2], s[3]);
  897. s[0] ^= v2;
  898. }
  899. #ifdef CONFIG_SMP
  900. /*
  901. * This function is called when the CPU has just come online, with
  902. * entry CPUHP_AP_RANDOM_ONLINE, just after CPUHP_AP_WORKQUEUE_ONLINE.
  903. */
  904. int __cold random_online_cpu(unsigned int cpu)
  905. {
  906. /*
  907. * During CPU shutdown and before CPU onlining, add_interrupt_
  908. * randomness() may schedule mix_interrupt_randomness(), and
  909. * set the MIX_INFLIGHT flag. However, because the worker can
  910. * be scheduled on a different CPU during this period, that
  911. * flag will never be cleared. For that reason, we zero out
  912. * the flag here, which runs just after workqueues are onlined
  913. * for the CPU again. This also has the effect of setting the
  914. * irq randomness count to zero so that new accumulated irqs
  915. * are fresh.
  916. */
  917. per_cpu_ptr(&irq_randomness, cpu)->count = 0;
  918. return 0;
  919. }
  920. #endif
  921. static void mix_interrupt_randomness(struct timer_list *work)
  922. {
  923. struct fast_pool *fast_pool = container_of(work, struct fast_pool, mix);
  924. /*
  925. * The size of the copied stack pool is explicitly 2 longs so that we
  926. * only ever ingest half of the siphash output each time, retaining
  927. * the other half as the next "key" that carries over. The entropy is
  928. * supposed to be sufficiently dispersed between bits so on average
  929. * we don't wind up "losing" some.
  930. */
  931. unsigned long pool[2];
  932. unsigned int count;
  933. /* Check to see if we're running on the wrong CPU due to hotplug. */
  934. local_irq_disable();
  935. if (fast_pool != this_cpu_ptr(&irq_randomness)) {
  936. local_irq_enable();
  937. return;
  938. }
  939. /*
  940. * Copy the pool to the stack so that the mixer always has a
  941. * consistent view, before we reenable irqs again.
  942. */
  943. memcpy(pool, fast_pool->pool, sizeof(pool));
  944. count = fast_pool->count;
  945. fast_pool->count = 0;
  946. fast_pool->last = jiffies;
  947. local_irq_enable();
  948. mix_pool_bytes(pool, sizeof(pool));
  949. credit_init_bits(clamp_t(unsigned int, (count & U16_MAX) / 64, 1, sizeof(pool) * 8));
  950. memzero_explicit(pool, sizeof(pool));
  951. }
  952. void add_interrupt_randomness(int irq)
  953. {
  954. enum { MIX_INFLIGHT = 1U << 31 };
  955. unsigned long entropy = random_get_entropy();
  956. struct fast_pool *fast_pool = this_cpu_ptr(&irq_randomness);
  957. struct pt_regs *regs = get_irq_regs();
  958. unsigned int new_count;
  959. fast_mix(fast_pool->pool, entropy,
  960. (regs ? instruction_pointer(regs) : _RET_IP_) ^ swab(irq));
  961. new_count = ++fast_pool->count;
  962. if (new_count & MIX_INFLIGHT)
  963. return;
  964. if (new_count < 1024 && !time_is_before_jiffies(fast_pool->last + HZ))
  965. return;
  966. fast_pool->count |= MIX_INFLIGHT;
  967. if (!timer_pending(&fast_pool->mix)) {
  968. fast_pool->mix.expires = jiffies;
  969. add_timer_on(&fast_pool->mix, raw_smp_processor_id());
  970. }
  971. }
  972. EXPORT_SYMBOL_GPL(add_interrupt_randomness);
  973. /* There is one of these per entropy source */
  974. struct timer_rand_state {
  975. unsigned long last_time;
  976. long last_delta, last_delta2;
  977. };
  978. /*
  979. * This function adds entropy to the entropy "pool" by using timing
  980. * delays. It uses the timer_rand_state structure to make an estimate
  981. * of how many bits of entropy this call has added to the pool. The
  982. * value "num" is also added to the pool; it should somehow describe
  983. * the type of event that just happened.
  984. */
  985. static void add_timer_randomness(struct timer_rand_state *state, unsigned int num)
  986. {
  987. unsigned long entropy = random_get_entropy(), now = jiffies, flags;
  988. long delta, delta2, delta3;
  989. unsigned int bits;
  990. /*
  991. * If we're in a hard IRQ, add_interrupt_randomness() will be called
  992. * sometime after, so mix into the fast pool.
  993. */
  994. if (in_hardirq()) {
  995. fast_mix(this_cpu_ptr(&irq_randomness)->pool, entropy, num);
  996. } else {
  997. spin_lock_irqsave(&input_pool.lock, flags);
  998. _mix_pool_bytes(&entropy, sizeof(entropy));
  999. _mix_pool_bytes(&num, sizeof(num));
  1000. spin_unlock_irqrestore(&input_pool.lock, flags);
  1001. }
  1002. if (crng_ready())
  1003. return;
  1004. /*
  1005. * Calculate number of bits of randomness we probably added.
  1006. * We take into account the first, second and third-order deltas
  1007. * in order to make our estimate.
  1008. */
  1009. delta = now - READ_ONCE(state->last_time);
  1010. WRITE_ONCE(state->last_time, now);
  1011. delta2 = delta - READ_ONCE(state->last_delta);
  1012. WRITE_ONCE(state->last_delta, delta);
  1013. delta3 = delta2 - READ_ONCE(state->last_delta2);
  1014. WRITE_ONCE(state->last_delta2, delta2);
  1015. if (delta < 0)
  1016. delta = -delta;
  1017. if (delta2 < 0)
  1018. delta2 = -delta2;
  1019. if (delta3 < 0)
  1020. delta3 = -delta3;
  1021. if (delta > delta2)
  1022. delta = delta2;
  1023. if (delta > delta3)
  1024. delta = delta3;
  1025. /*
  1026. * delta is now minimum absolute delta. Round down by 1 bit
  1027. * on general principles, and limit entropy estimate to 11 bits.
  1028. */
  1029. bits = min(fls(delta >> 1), 11);
  1030. /*
  1031. * As mentioned above, if we're in a hard IRQ, add_interrupt_randomness()
  1032. * will run after this, which uses a different crediting scheme of 1 bit
  1033. * per every 64 interrupts. In order to let that function do accounting
  1034. * close to the one in this function, we credit a full 64/64 bit per bit,
  1035. * and then subtract one to account for the extra one added.
  1036. */
  1037. if (in_hardirq())
  1038. this_cpu_ptr(&irq_randomness)->count += max(1u, bits * 64) - 1;
  1039. else
  1040. _credit_init_bits(bits);
  1041. }
  1042. void add_input_randomness(unsigned int type, unsigned int code, unsigned int value)
  1043. {
  1044. static unsigned char last_value;
  1045. static struct timer_rand_state input_timer_state = { INITIAL_JIFFIES };
  1046. /* Ignore autorepeat and the like. */
  1047. if (value == last_value)
  1048. return;
  1049. last_value = value;
  1050. add_timer_randomness(&input_timer_state,
  1051. (type << 4) ^ code ^ (code >> 4) ^ value);
  1052. }
  1053. EXPORT_SYMBOL_GPL(add_input_randomness);
  1054. #ifdef CONFIG_BLOCK
  1055. void add_disk_randomness(struct gendisk *disk)
  1056. {
  1057. if (!disk || !disk->random)
  1058. return;
  1059. /* First major is 1, so we get >= 0x200 here. */
  1060. add_timer_randomness(disk->random, 0x100 + disk_devt(disk));
  1061. }
  1062. EXPORT_SYMBOL_GPL(add_disk_randomness);
  1063. void __cold rand_initialize_disk(struct gendisk *disk)
  1064. {
  1065. struct timer_rand_state *state;
  1066. /*
  1067. * If kzalloc returns null, we just won't use that entropy
  1068. * source.
  1069. */
  1070. state = kzalloc(sizeof(struct timer_rand_state), GFP_KERNEL);
  1071. if (state) {
  1072. state->last_time = INITIAL_JIFFIES;
  1073. disk->random = state;
  1074. }
  1075. }
  1076. #endif
  1077. struct entropy_timer_state {
  1078. unsigned long entropy;
  1079. struct timer_list timer;
  1080. unsigned int samples, samples_per_bit;
  1081. };
  1082. /*
  1083. * Each time the timer fires, we expect that we got an unpredictable
  1084. * jump in the cycle counter. Even if the timer is running on another
  1085. * CPU, the timer activity will be touching the stack of the CPU that is
  1086. * generating entropy..
  1087. *
  1088. * Note that we don't re-arm the timer in the timer itself - we are
  1089. * happy to be scheduled away, since that just makes the load more
  1090. * complex, but we do not want the timer to keep ticking unless the
  1091. * entropy loop is running.
  1092. *
  1093. * So the re-arming always happens in the entropy loop itself.
  1094. */
  1095. static void __cold entropy_timer(struct timer_list *timer)
  1096. {
  1097. struct entropy_timer_state *state = container_of(timer, struct entropy_timer_state, timer);
  1098. if (++state->samples == state->samples_per_bit) {
  1099. credit_init_bits(1);
  1100. state->samples = 0;
  1101. }
  1102. }
  1103. /*
  1104. * If we have an actual cycle counter, see if we can
  1105. * generate enough entropy with timing noise
  1106. */
  1107. static void __cold try_to_generate_entropy(void)
  1108. {
  1109. enum { NUM_TRIAL_SAMPLES = 8192, MAX_SAMPLES_PER_BIT = HZ / 15 };
  1110. struct entropy_timer_state stack;
  1111. unsigned int i, num_different = 0;
  1112. unsigned long last = random_get_entropy();
  1113. for (i = 0; i < NUM_TRIAL_SAMPLES - 1; ++i) {
  1114. stack.entropy = random_get_entropy();
  1115. if (stack.entropy != last)
  1116. ++num_different;
  1117. last = stack.entropy;
  1118. }
  1119. stack.samples_per_bit = DIV_ROUND_UP(NUM_TRIAL_SAMPLES, num_different + 1);
  1120. if (stack.samples_per_bit > MAX_SAMPLES_PER_BIT)
  1121. return;
  1122. stack.samples = 0;
  1123. timer_setup_on_stack(&stack.timer, entropy_timer, 0);
  1124. while (!crng_ready() && !signal_pending(current)) {
  1125. if (!timer_pending(&stack.timer))
  1126. mod_timer(&stack.timer, jiffies);
  1127. mix_pool_bytes(&stack.entropy, sizeof(stack.entropy));
  1128. schedule();
  1129. stack.entropy = random_get_entropy();
  1130. }
  1131. del_timer_sync(&stack.timer);
  1132. destroy_timer_on_stack(&stack.timer);
  1133. mix_pool_bytes(&stack.entropy, sizeof(stack.entropy));
  1134. }
  1135. /**********************************************************************
  1136. *
  1137. * Userspace reader/writer interfaces.
  1138. *
  1139. * getrandom(2) is the primary modern interface into the RNG and should
  1140. * be used in preference to anything else.
  1141. *
  1142. * Reading from /dev/random has the same functionality as calling
  1143. * getrandom(2) with flags=0. In earlier versions, however, it had
  1144. * vastly different semantics and should therefore be avoided, to
  1145. * prevent backwards compatibility issues.
  1146. *
  1147. * Reading from /dev/urandom has the same functionality as calling
  1148. * getrandom(2) with flags=GRND_INSECURE. Because it does not block
  1149. * waiting for the RNG to be ready, it should not be used.
  1150. *
  1151. * Writing to either /dev/random or /dev/urandom adds entropy to
  1152. * the input pool but does not credit it.
  1153. *
  1154. * Polling on /dev/random indicates when the RNG is initialized, on
  1155. * the read side, and when it wants new entropy, on the write side.
  1156. *
  1157. * Both /dev/random and /dev/urandom have the same set of ioctls for
  1158. * adding entropy, getting the entropy count, zeroing the count, and
  1159. * reseeding the crng.
  1160. *
  1161. **********************************************************************/
  1162. SYSCALL_DEFINE3(getrandom, char __user *, ubuf, size_t, len, unsigned int, flags)
  1163. {
  1164. struct iov_iter iter;
  1165. struct iovec iov;
  1166. int ret;
  1167. if (flags & ~(GRND_NONBLOCK | GRND_RANDOM | GRND_INSECURE))
  1168. return -EINVAL;
  1169. /*
  1170. * Requesting insecure and blocking randomness at the same time makes
  1171. * no sense.
  1172. */
  1173. if ((flags & (GRND_INSECURE | GRND_RANDOM)) == (GRND_INSECURE | GRND_RANDOM))
  1174. return -EINVAL;
  1175. if (!crng_ready() && !(flags & GRND_INSECURE)) {
  1176. if (flags & GRND_NONBLOCK)
  1177. return -EAGAIN;
  1178. ret = wait_for_random_bytes();
  1179. if (unlikely(ret))
  1180. return ret;
  1181. }
  1182. ret = import_single_range(ITER_DEST, ubuf, len, &iov, &iter);
  1183. if (unlikely(ret))
  1184. return ret;
  1185. return get_random_bytes_user(&iter);
  1186. }
  1187. static __poll_t random_poll(struct file *file, poll_table *wait)
  1188. {
  1189. poll_wait(file, &crng_init_wait, wait);
  1190. return crng_ready() ? EPOLLIN | EPOLLRDNORM : EPOLLOUT | EPOLLWRNORM;
  1191. }
  1192. static ssize_t write_pool_user(struct iov_iter *iter)
  1193. {
  1194. u8 block[BLAKE2S_BLOCK_SIZE];
  1195. ssize_t ret = 0;
  1196. size_t copied;
  1197. if (unlikely(!iov_iter_count(iter)))
  1198. return 0;
  1199. for (;;) {
  1200. copied = copy_from_iter(block, sizeof(block), iter);
  1201. ret += copied;
  1202. mix_pool_bytes(block, copied);
  1203. if (!iov_iter_count(iter) || copied != sizeof(block))
  1204. break;
  1205. BUILD_BUG_ON(PAGE_SIZE % sizeof(block) != 0);
  1206. if (ret % PAGE_SIZE == 0) {
  1207. if (signal_pending(current))
  1208. break;
  1209. cond_resched();
  1210. }
  1211. }
  1212. memzero_explicit(block, sizeof(block));
  1213. return ret ? ret : -EFAULT;
  1214. }
  1215. static ssize_t random_write_iter(struct kiocb *kiocb, struct iov_iter *iter)
  1216. {
  1217. return write_pool_user(iter);
  1218. }
  1219. static ssize_t urandom_read_iter(struct kiocb *kiocb, struct iov_iter *iter)
  1220. {
  1221. static int maxwarn = 10;
  1222. /*
  1223. * Opportunistically attempt to initialize the RNG on platforms that
  1224. * have fast cycle counters, but don't (for now) require it to succeed.
  1225. */
  1226. if (!crng_ready())
  1227. try_to_generate_entropy();
  1228. if (!crng_ready()) {
  1229. if (!ratelimit_disable && maxwarn <= 0)
  1230. ++urandom_warning.missed;
  1231. else if (ratelimit_disable || __ratelimit(&urandom_warning)) {
  1232. --maxwarn;
  1233. pr_notice("%s: uninitialized urandom read (%zu bytes read)\n",
  1234. current->comm, iov_iter_count(iter));
  1235. }
  1236. }
  1237. return get_random_bytes_user(iter);
  1238. }
  1239. static ssize_t random_read_iter(struct kiocb *kiocb, struct iov_iter *iter)
  1240. {
  1241. int ret;
  1242. if (!crng_ready() &&
  1243. ((kiocb->ki_flags & (IOCB_NOWAIT | IOCB_NOIO)) ||
  1244. (kiocb->ki_filp->f_flags & O_NONBLOCK)))
  1245. return -EAGAIN;
  1246. ret = wait_for_random_bytes();
  1247. if (ret != 0)
  1248. return ret;
  1249. return get_random_bytes_user(iter);
  1250. }
  1251. static long random_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
  1252. {
  1253. int __user *p = (int __user *)arg;
  1254. int ent_count;
  1255. switch (cmd) {
  1256. case RNDGETENTCNT:
  1257. /* Inherently racy, no point locking. */
  1258. if (put_user(input_pool.init_bits, p))
  1259. return -EFAULT;
  1260. return 0;
  1261. case RNDADDTOENTCNT:
  1262. if (!capable(CAP_SYS_ADMIN))
  1263. return -EPERM;
  1264. if (get_user(ent_count, p))
  1265. return -EFAULT;
  1266. if (ent_count < 0)
  1267. return -EINVAL;
  1268. credit_init_bits(ent_count);
  1269. return 0;
  1270. case RNDADDENTROPY: {
  1271. struct iov_iter iter;
  1272. struct iovec iov;
  1273. ssize_t ret;
  1274. int len;
  1275. if (!capable(CAP_SYS_ADMIN))
  1276. return -EPERM;
  1277. if (get_user(ent_count, p++))
  1278. return -EFAULT;
  1279. if (ent_count < 0)
  1280. return -EINVAL;
  1281. if (get_user(len, p++))
  1282. return -EFAULT;
  1283. ret = import_single_range(ITER_SOURCE, p, len, &iov, &iter);
  1284. if (unlikely(ret))
  1285. return ret;
  1286. ret = write_pool_user(&iter);
  1287. if (unlikely(ret < 0))
  1288. return ret;
  1289. /* Since we're crediting, enforce that it was all written into the pool. */
  1290. if (unlikely(ret != len))
  1291. return -EFAULT;
  1292. credit_init_bits(ent_count);
  1293. return 0;
  1294. }
  1295. case RNDZAPENTCNT:
  1296. case RNDCLEARPOOL:
  1297. /* No longer has any effect. */
  1298. if (!capable(CAP_SYS_ADMIN))
  1299. return -EPERM;
  1300. return 0;
  1301. case RNDRESEEDCRNG:
  1302. if (!capable(CAP_SYS_ADMIN))
  1303. return -EPERM;
  1304. if (!crng_ready())
  1305. return -ENODATA;
  1306. crng_reseed();
  1307. return 0;
  1308. default:
  1309. return -EINVAL;
  1310. }
  1311. }
  1312. static int random_fasync(int fd, struct file *filp, int on)
  1313. {
  1314. return fasync_helper(fd, filp, on, &fasync);
  1315. }
  1316. const struct file_operations random_fops = {
  1317. .read_iter = random_read_iter,
  1318. .write_iter = random_write_iter,
  1319. .poll = random_poll,
  1320. .unlocked_ioctl = random_ioctl,
  1321. .compat_ioctl = compat_ptr_ioctl,
  1322. .fasync = random_fasync,
  1323. .llseek = noop_llseek,
  1324. .splice_read = generic_file_splice_read,
  1325. .splice_write = iter_file_splice_write,
  1326. };
  1327. const struct file_operations urandom_fops = {
  1328. .read_iter = urandom_read_iter,
  1329. .write_iter = random_write_iter,
  1330. .unlocked_ioctl = random_ioctl,
  1331. .compat_ioctl = compat_ptr_ioctl,
  1332. .fasync = random_fasync,
  1333. .llseek = noop_llseek,
  1334. .splice_read = generic_file_splice_read,
  1335. .splice_write = iter_file_splice_write,
  1336. };
  1337. /********************************************************************
  1338. *
  1339. * Sysctl interface.
  1340. *
  1341. * These are partly unused legacy knobs with dummy values to not break
  1342. * userspace and partly still useful things. They are usually accessible
  1343. * in /proc/sys/kernel/random/ and are as follows:
  1344. *
  1345. * - boot_id - a UUID representing the current boot.
  1346. *
  1347. * - uuid - a random UUID, different each time the file is read.
  1348. *
  1349. * - poolsize - the number of bits of entropy that the input pool can
  1350. * hold, tied to the POOL_BITS constant.
  1351. *
  1352. * - entropy_avail - the number of bits of entropy currently in the
  1353. * input pool. Always <= poolsize.
  1354. *
  1355. * - write_wakeup_threshold - the amount of entropy in the input pool
  1356. * below which write polls to /dev/random will unblock, requesting
  1357. * more entropy, tied to the POOL_READY_BITS constant. It is writable
  1358. * to avoid breaking old userspaces, but writing to it does not
  1359. * change any behavior of the RNG.
  1360. *
  1361. * - urandom_min_reseed_secs - fixed to the value CRNG_RESEED_INTERVAL.
  1362. * It is writable to avoid breaking old userspaces, but writing
  1363. * to it does not change any behavior of the RNG.
  1364. *
  1365. ********************************************************************/
  1366. #ifdef CONFIG_SYSCTL
  1367. #include <linux/sysctl.h>
  1368. static int sysctl_random_min_urandom_seed = CRNG_RESEED_INTERVAL / HZ;
  1369. static int sysctl_random_write_wakeup_bits = POOL_READY_BITS;
  1370. static int sysctl_poolsize = POOL_BITS;
  1371. static u8 sysctl_bootid[UUID_SIZE];
  1372. /*
  1373. * This function is used to return both the bootid UUID, and random
  1374. * UUID. The difference is in whether table->data is NULL; if it is,
  1375. * then a new UUID is generated and returned to the user.
  1376. */
  1377. static int proc_do_uuid(struct ctl_table *table, int write, void *buf,
  1378. size_t *lenp, loff_t *ppos)
  1379. {
  1380. u8 tmp_uuid[UUID_SIZE], *uuid;
  1381. char uuid_string[UUID_STRING_LEN + 1];
  1382. struct ctl_table fake_table = {
  1383. .data = uuid_string,
  1384. .maxlen = UUID_STRING_LEN
  1385. };
  1386. if (write)
  1387. return -EPERM;
  1388. uuid = table->data;
  1389. if (!uuid) {
  1390. uuid = tmp_uuid;
  1391. generate_random_uuid(uuid);
  1392. } else {
  1393. static DEFINE_SPINLOCK(bootid_spinlock);
  1394. spin_lock(&bootid_spinlock);
  1395. if (!uuid[8])
  1396. generate_random_uuid(uuid);
  1397. spin_unlock(&bootid_spinlock);
  1398. }
  1399. snprintf(uuid_string, sizeof(uuid_string), "%pU", uuid);
  1400. return proc_dostring(&fake_table, 0, buf, lenp, ppos);
  1401. }
  1402. /* The same as proc_dointvec, but writes don't change anything. */
  1403. static int proc_do_rointvec(struct ctl_table *table, int write, void *buf,
  1404. size_t *lenp, loff_t *ppos)
  1405. {
  1406. return write ? 0 : proc_dointvec(table, 0, buf, lenp, ppos);
  1407. }
  1408. static struct ctl_table random_table[] = {
  1409. {
  1410. .procname = "poolsize",
  1411. .data = &sysctl_poolsize,
  1412. .maxlen = sizeof(int),
  1413. .mode = 0444,
  1414. .proc_handler = proc_dointvec,
  1415. },
  1416. {
  1417. .procname = "entropy_avail",
  1418. .data = &input_pool.init_bits,
  1419. .maxlen = sizeof(int),
  1420. .mode = 0444,
  1421. .proc_handler = proc_dointvec,
  1422. },
  1423. {
  1424. .procname = "write_wakeup_threshold",
  1425. .data = &sysctl_random_write_wakeup_bits,
  1426. .maxlen = sizeof(int),
  1427. .mode = 0644,
  1428. .proc_handler = proc_do_rointvec,
  1429. },
  1430. {
  1431. .procname = "urandom_min_reseed_secs",
  1432. .data = &sysctl_random_min_urandom_seed,
  1433. .maxlen = sizeof(int),
  1434. .mode = 0644,
  1435. .proc_handler = proc_do_rointvec,
  1436. },
  1437. {
  1438. .procname = "boot_id",
  1439. .data = &sysctl_bootid,
  1440. .mode = 0444,
  1441. .proc_handler = proc_do_uuid,
  1442. },
  1443. {
  1444. .procname = "uuid",
  1445. .mode = 0444,
  1446. .proc_handler = proc_do_uuid,
  1447. },
  1448. { }
  1449. };
  1450. /*
  1451. * random_init() is called before sysctl_init(),
  1452. * so we cannot call register_sysctl_init() in random_init()
  1453. */
  1454. static int __init random_sysctls_init(void)
  1455. {
  1456. register_sysctl_init("kernel/random", random_table);
  1457. return 0;
  1458. }
  1459. device_initcall(random_sysctls_init);
  1460. #endif