1 /* $OpenBSD: rnd.c,v 1.182 2016/07/15 19:02:30 tom Exp $ */ 2 3 /* 4 * Copyright (c) 2011 Theo de Raadt. 5 * Copyright (c) 2008 Damien Miller. 6 * Copyright (c) 1996, 1997, 2000-2002 Michael Shalayeff. 7 * Copyright (c) 2013 Markus Friedl. 8 * Copyright Theodore Ts'o, 1994, 1995, 1996, 1997, 1998, 1999. 9 * All rights reserved. 10 * 11 * Redistribution and use in source and binary forms, with or without 12 * modification, are permitted provided that the following conditions 13 * are met: 14 * 1. Redistributions of source code must retain the above copyright 15 * notice, and the entire permission notice in its entirety, 16 * including the disclaimer of warranties. 17 * 2. Redistributions in binary form must reproduce the above copyright 18 * notice, this list of conditions and the following disclaimer in the 19 * documentation and/or other materials provided with the distribution. 20 * 3. The name of the author may not be used to endorse or promote 21 * products derived from this software without specific prior 22 * written permission. 23 * 24 * ALTERNATIVELY, this product may be distributed under the terms of 25 * the GNU Public License, in which case the provisions of the GPL are 26 * required INSTEAD OF the above restrictions. (This clause is 27 * necessary due to a potential bad interaction between the GPL and 28 * the restrictions contained in a BSD-style copyright.) 29 * 30 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED 31 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 33 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, 34 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 35 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 36 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 37 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 38 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 39 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 40 * OF THE POSSIBILITY OF SUCH DAMAGE. 41 */ 42 43 /* 44 * Computers are very predictable devices. Hence it is extremely hard 45 * to produce truly random numbers on a computer --- as opposed to 46 * pseudo-random numbers, which can be easily generated by using an 47 * algorithm. Unfortunately, it is very easy for attackers to guess 48 * the sequence of pseudo-random number generators, and for some 49 * applications this is not acceptable. Instead, we must try to 50 * gather "environmental noise" from the computer's environment, which 51 * must be hard for outside attackers to observe and use to 52 * generate random numbers. In a Unix environment, this is best done 53 * from inside the kernel. 54 * 55 * Sources of randomness from the environment include inter-keyboard 56 * timings, inter-interrupt timings from some interrupts, and other 57 * events which are both (a) non-deterministic and (b) hard for an 58 * outside observer to measure. Randomness from these sources is 59 * added to the "rnd states" queue; this is used as much of the 60 * source material which is mixed on occasion using a CRC-like function 61 * into the "entropy pool". This is not cryptographically strong, but 62 * it is adequate assuming the randomness is not chosen maliciously, 63 * and it is very fast because the interrupt-time event is only to add 64 * a small random token to the "rnd states" queue. 65 * 66 * When random bytes are desired, they are obtained by pulling from 67 * the entropy pool and running a SHA512 hash. The SHA512 hash avoids 68 * exposing the internal state of the entropy pool. Even if it is 69 * possible to analyze SHA512 in some clever way, as long as the amount 70 * of data returned from the generator is less than the inherent 71 * entropy in the pool, the output data is totally unpredictable. For 72 * this reason, the routine decreases its internal estimate of how many 73 * bits of "true randomness" are contained in the entropy pool as it 74 * outputs random numbers. 75 * 76 * If this estimate goes to zero, the SHA512 hash will continue to generate 77 * output since there is no true risk because the SHA512 output is not 78 * exported outside this subsystem. It is next used as input to seed a 79 * ChaCha20 stream cipher, which is re-seeded from time to time. This 80 * design provides very high amounts of output data from a potentially 81 * small entropy base, at high enough speeds to encourage use of random 82 * numbers in nearly any situation. Before OpenBSD 5.5, the RC4 stream 83 * cipher (also known as ARC4) was used instead of ChaCha20. 84 * 85 * The output of this single ChaCha20 engine is then shared amongst many 86 * consumers in the kernel and userland via a few interfaces: 87 * arc4random_buf(), arc4random(), arc4random_uniform(), randomread() 88 * for the set of /dev/random nodes, the sysctl kern.arandom, and the 89 * system call getentropy(), which provides seeds for process-context 90 * pseudorandom generators. 91 * 92 * Acknowledgements: 93 * ================= 94 * 95 * Ideas for constructing this random number generator were derived 96 * from Pretty Good Privacy's random number generator, and from private 97 * discussions with Phil Karn. Colin Plumb provided a faster random 98 * number generator, which speeds up the mixing function of the entropy 99 * pool, taken from PGPfone. Dale Worley has also contributed many 100 * useful ideas and suggestions to improve this driver. 101 * 102 * Any flaws in the design are solely my responsibility, and should 103 * not be attributed to the Phil, Colin, or any of the authors of PGP. 104 * 105 * Further background information on this topic may be obtained from 106 * RFC 1750, "Randomness Recommendations for Security", by Donald 107 * Eastlake, Steve Crocker, and Jeff Schiller. 108 * 109 * Using a RC4 stream cipher as 2nd stage after the MD5 (now SHA512) output 110 * is the result of work by David Mazieres. 111 */ 112 113 #include <sys/param.h> 114 #include <sys/systm.h> 115 #include <sys/disk.h> 116 #include <sys/event.h> 117 #include <sys/limits.h> 118 #include <sys/time.h> 119 #include <sys/ioctl.h> 120 #include <sys/malloc.h> 121 #include <sys/fcntl.h> 122 #include <sys/timeout.h> 123 #include <sys/mutex.h> 124 #include <sys/task.h> 125 #include <sys/msgbuf.h> 126 #include <sys/mount.h> 127 #include <sys/syscallargs.h> 128 129 #include <crypto/sha2.h> 130 131 #define KEYSTREAM_ONLY 132 #include <crypto/chacha_private.h> 133 134 #include <dev/rndvar.h> 135 136 /* 137 * For the purposes of better mixing, we use the CRC-32 polynomial as 138 * well to make a twisted Generalized Feedback Shift Register 139 * 140 * (See M. Matsumoto & Y. Kurita, 1992. Twisted GFSR generators. ACM 141 * Transactions on Modeling and Computer Simulation 2(3):179-194. 142 * Also see M. Matsumoto & Y. Kurita, 1994. Twisted GFSR generators 143 * II. ACM Transactions on Mdeling and Computer Simulation 4:254-266) 144 * 145 * Thanks to Colin Plumb for suggesting this. 146 * 147 * We have not analyzed the resultant polynomial to prove it primitive; 148 * in fact it almost certainly isn't. Nonetheless, the irreducible factors 149 * of a random large-degree polynomial over GF(2) are more than large enough 150 * that periodicity is not a concern. 151 * 152 * The input hash is much less sensitive than the output hash. All 153 * we want from it is to be a good non-cryptographic hash - 154 * i.e. to not produce collisions when fed "random" data of the sort 155 * we expect to see. As long as the pool state differs for different 156 * inputs, we have preserved the input entropy and done a good job. 157 * The fact that an intelligent attacker can construct inputs that 158 * will produce controlled alterations to the pool's state is not 159 * important because we don't consider such inputs to contribute any 160 * randomness. The only property we need with respect to them is that 161 * the attacker can't increase his/her knowledge of the pool's state. 162 * Since all additions are reversible (knowing the final state and the 163 * input, you can reconstruct the initial state), if an attacker has 164 * any uncertainty about the initial state, he/she can only shuffle 165 * that uncertainty about, but never cause any collisions (which would 166 * decrease the uncertainty). 167 * 168 * The chosen system lets the state of the pool be (essentially) the input 169 * modulo the generator polynomial. Now, for random primitive polynomials, 170 * this is a universal class of hash functions, meaning that the chance 171 * of a collision is limited by the attacker's knowledge of the generator 172 * polynomial, so if it is chosen at random, an attacker can never force 173 * a collision. Here, we use a fixed polynomial, but we *can* assume that 174 * ###--> it is unknown to the processes generating the input entropy. <-### 175 * Because of this important property, this is a good, collision-resistant 176 * hash; hash collisions will occur no more often than chance. 177 */ 178 179 /* 180 * Stirring polynomials over GF(2) for various pool sizes. Used in 181 * add_entropy_words() below. 182 * 183 * The polynomial terms are chosen to be evenly spaced (minimum RMS 184 * distance from evenly spaced; except for the last tap, which is 1 to 185 * get the twisting happening as fast as possible. 186 * 187 * The reultant polynomial is: 188 * 2^POOLWORDS + 2^POOL_TAP1 + 2^POOL_TAP2 + 2^POOL_TAP3 + 2^POOL_TAP4 + 1 189 */ 190 #define POOLWORDS 2048 191 #define POOLBYTES (POOLWORDS*4) 192 #define POOLMASK (POOLWORDS - 1) 193 #define POOL_TAP1 1638 194 #define POOL_TAP2 1231 195 #define POOL_TAP3 819 196 #define POOL_TAP4 411 197 198 struct mutex entropylock = MUTEX_INITIALIZER(IPL_HIGH); 199 200 /* 201 * Raw entropy collection from device drivers; at interrupt context or not. 202 * add_*_randomness() provide data which is put into the entropy queue. 203 * Almost completely under the entropylock. 204 */ 205 struct timer_rand_state { /* There is one of these per entropy source */ 206 u_int last_time; 207 u_int last_delta; 208 u_int last_delta2; 209 u_int dont_count_entropy : 1; 210 u_int max_entropy : 1; 211 } rnd_states[RND_SRC_NUM]; 212 213 #define QEVLEN (1024 / sizeof(struct rand_event)) 214 #define QEVSLOW (QEVLEN * 3 / 4) /* yet another 0.75 for 60-minutes hour /-; */ 215 #define QEVSBITS 10 216 217 #define KEYSZ 32 218 #define IVSZ 8 219 #define BLOCKSZ 64 220 #define RSBUFSZ (16*BLOCKSZ) 221 #define EBUFSIZE KEYSZ + IVSZ 222 223 struct rand_event { 224 struct timer_rand_state *re_state; 225 u_int re_time; 226 u_int re_val; 227 } rnd_event_space[QEVLEN]; 228 /* index of next free slot */ 229 u_int rnd_event_idx; 230 231 struct timeout rnd_timeout; 232 233 u_int32_t entropy_pool[POOLWORDS] __attribute__((section(".openbsd.randomdata"))); 234 u_int entropy_add_ptr; 235 u_char entropy_input_rotate; 236 237 void dequeue_randomness(void *); 238 void add_entropy_words(const u_int32_t *, u_int); 239 void extract_entropy(u_int8_t *) 240 __attribute__((__bounded__(__minbytes__,1,EBUFSIZE))); 241 242 int filt_randomread(struct knote *, long); 243 void filt_randomdetach(struct knote *); 244 int filt_randomwrite(struct knote *, long); 245 246 static void _rs_seed(u_char *, size_t); 247 248 struct filterops randomread_filtops = 249 { 1, NULL, filt_randomdetach, filt_randomread }; 250 struct filterops randomwrite_filtops = 251 { 1, NULL, filt_randomdetach, filt_randomwrite }; 252 253 static __inline struct rand_event * 254 rnd_get(void) 255 { 256 if (rnd_event_idx == 0) 257 return NULL; 258 /* if it wrapped around, start dequeuing at the end */ 259 if (rnd_event_idx > QEVLEN) 260 rnd_event_idx = QEVLEN; 261 262 return &rnd_event_space[--rnd_event_idx]; 263 } 264 265 static __inline struct rand_event * 266 rnd_put(void) 267 { 268 u_int idx = rnd_event_idx++; 269 270 /* allow wrapping. caller will use xor. */ 271 idx = idx % QEVLEN; 272 273 return &rnd_event_space[idx]; 274 } 275 276 static __inline u_int 277 rnd_qlen(void) 278 { 279 return rnd_event_idx; 280 } 281 282 /* 283 * This function adds entropy to the entropy pool by using timing 284 * delays. It uses the timer_rand_state structure to make an estimate 285 * of how many bits of entropy this call has added to the pool. 286 * 287 * The number "val" is also added to the pool - it should somehow describe 288 * the type of event which just happened. Currently the values of 0-255 289 * are for keyboard scan codes, 256 and upwards - for interrupts. 290 */ 291 void 292 enqueue_randomness(u_int state, u_int val) 293 { 294 int delta, delta2, delta3; 295 struct timer_rand_state *p; 296 struct rand_event *rep; 297 struct timespec ts; 298 u_int time, nbits; 299 300 #ifdef DIAGNOSTIC 301 if (state >= RND_SRC_NUM) 302 return; 303 #endif 304 305 if (timeout_initialized(&rnd_timeout)) 306 nanotime(&ts); 307 308 p = &rnd_states[state]; 309 val += state << 13; 310 311 time = (ts.tv_nsec >> 10) + (ts.tv_sec << 20); 312 nbits = 0; 313 314 /* 315 * Calculate the number of bits of randomness that we probably 316 * added. We take into account the first and second order 317 * deltas in order to make our estimate. 318 */ 319 if (!p->dont_count_entropy) { 320 delta = time - p->last_time; 321 delta2 = delta - p->last_delta; 322 delta3 = delta2 - p->last_delta2; 323 324 if (delta < 0) delta = -delta; 325 if (delta2 < 0) delta2 = -delta2; 326 if (delta3 < 0) delta3 = -delta3; 327 if (delta > delta2) delta = delta2; 328 if (delta > delta3) delta = delta3; 329 delta3 = delta >>= 1; 330 /* 331 * delta &= 0xfff; 332 * we don't do it since our time sheet is different from linux 333 */ 334 335 if (delta & 0xffff0000) { 336 nbits = 16; 337 delta >>= 16; 338 } 339 if (delta & 0xff00) { 340 nbits += 8; 341 delta >>= 8; 342 } 343 if (delta & 0xf0) { 344 nbits += 4; 345 delta >>= 4; 346 } 347 if (delta & 0xc) { 348 nbits += 2; 349 delta >>= 2; 350 } 351 if (delta & 2) { 352 nbits += 1; 353 delta >>= 1; 354 } 355 if (delta & 1) 356 nbits++; 357 } else if (p->max_entropy) 358 nbits = 8 * sizeof(val) - 1; 359 360 /* given the multi-order delta logic above, this should never happen */ 361 if (nbits >= 32) 362 return; 363 364 mtx_enter(&entropylock); 365 if (!p->dont_count_entropy) { 366 p->last_time = time; 367 p->last_delta = delta3; 368 p->last_delta2 = delta2; 369 } 370 371 rep = rnd_put(); 372 373 rep->re_state = p; 374 rep->re_time += ts.tv_nsec ^ (ts.tv_sec << 20); 375 rep->re_val += val; 376 377 if (rnd_qlen() > QEVSLOW/2 && timeout_initialized(&rnd_timeout) && 378 !timeout_pending(&rnd_timeout)) 379 timeout_add(&rnd_timeout, 1); 380 381 mtx_leave(&entropylock); 382 } 383 384 /* 385 * This function adds a byte into the entropy pool. It does not 386 * update the entropy estimate. The caller must do this if appropriate. 387 * 388 * The pool is stirred with a polynomial of degree POOLWORDS over GF(2); 389 * see POOL_TAP[1-4] above 390 * 391 * Rotate the input word by a changing number of bits, to help assure 392 * that all bits in the entropy get toggled. Otherwise, if the pool 393 * is consistently fed small numbers (such as keyboard scan codes) 394 * then the upper bits of the entropy pool will frequently remain 395 * untouched. 396 */ 397 void 398 add_entropy_words(const u_int32_t *buf, u_int n) 399 { 400 /* derived from IEEE 802.3 CRC-32 */ 401 static const u_int32_t twist_table[8] = { 402 0x00000000, 0x3b6e20c8, 0x76dc4190, 0x4db26158, 403 0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278 404 }; 405 406 for (; n--; buf++) { 407 u_int32_t w = (*buf << entropy_input_rotate) | 408 (*buf >> ((32 - entropy_input_rotate) & 31)); 409 u_int i = entropy_add_ptr = 410 (entropy_add_ptr - 1) & POOLMASK; 411 /* 412 * Normally, we add 7 bits of rotation to the pool. 413 * At the beginning of the pool, add an extra 7 bits 414 * rotation, so that successive passes spread the 415 * input bits across the pool evenly. 416 */ 417 entropy_input_rotate = 418 (entropy_input_rotate + (i ? 7 : 14)) & 31; 419 420 /* XOR pool contents corresponding to polynomial terms */ 421 w ^= entropy_pool[(i + POOL_TAP1) & POOLMASK] ^ 422 entropy_pool[(i + POOL_TAP2) & POOLMASK] ^ 423 entropy_pool[(i + POOL_TAP3) & POOLMASK] ^ 424 entropy_pool[(i + POOL_TAP4) & POOLMASK] ^ 425 entropy_pool[(i + 1) & POOLMASK] ^ 426 entropy_pool[i]; /* + 2^POOLWORDS */ 427 428 entropy_pool[i] = (w >> 3) ^ twist_table[w & 7]; 429 } 430 } 431 432 /* 433 * Pulls entropy out of the queue and throws merges it into the pool 434 * with the CRC. 435 */ 436 /* ARGSUSED */ 437 void 438 dequeue_randomness(void *v) 439 { 440 struct rand_event *rep; 441 u_int32_t buf[2]; 442 443 mtx_enter(&entropylock); 444 445 if (timeout_initialized(&rnd_timeout)) 446 timeout_del(&rnd_timeout); 447 448 while ((rep = rnd_get())) { 449 buf[0] = rep->re_time; 450 buf[1] = rep->re_val; 451 mtx_leave(&entropylock); 452 453 add_entropy_words(buf, 2); 454 455 mtx_enter(&entropylock); 456 } 457 mtx_leave(&entropylock); 458 } 459 460 /* 461 * Grabs a chunk from the entropy_pool[] and slams it through SHA512 when 462 * requested. 463 */ 464 void 465 extract_entropy(u_int8_t *buf) 466 { 467 static u_int32_t extract_pool[POOLWORDS]; 468 u_char digest[SHA512_DIGEST_LENGTH]; 469 SHA2_CTX shactx; 470 471 #if SHA512_DIGEST_LENGTH < EBUFSIZE 472 #error "need more bigger hash output" 473 #endif 474 475 /* 476 * INTENTIONALLY not protected by entropylock. Races during 477 * memcpy() result in acceptable input data; races during 478 * SHA512Update() would create nasty data dependencies. We 479 * do not rely on this as a benefit, but if it happens, cool. 480 */ 481 memcpy(extract_pool, entropy_pool, sizeof(extract_pool)); 482 483 /* Hash the pool to get the output */ 484 SHA512Init(&shactx); 485 SHA512Update(&shactx, (u_int8_t *)extract_pool, sizeof(extract_pool)); 486 SHA512Final(digest, &shactx); 487 488 /* Copy data to destination buffer */ 489 memcpy(buf, digest, EBUFSIZE); 490 491 /* Modify pool so next hash will produce different results */ 492 add_timer_randomness(EBUFSIZE); 493 dequeue_randomness(NULL); 494 495 /* Wipe data from memory */ 496 explicit_bzero(extract_pool, sizeof(extract_pool)); 497 explicit_bzero(digest, sizeof(digest)); 498 } 499 500 /* random keystream by ChaCha */ 501 502 void arc4_reinit(void *v); /* timeout to start reinit */ 503 void arc4_init(void *); /* actually do the reinit */ 504 505 struct mutex rndlock = MUTEX_INITIALIZER(IPL_HIGH); 506 struct timeout arc4_timeout; 507 struct task arc4_task = TASK_INITIALIZER(arc4_init, NULL); 508 509 static int rs_initialized; 510 static chacha_ctx rs; /* chacha context for random keystream */ 511 /* keystream blocks (also chacha seed from boot) */ 512 static u_char rs_buf[RSBUFSZ] __attribute__((section(".openbsd.randomdata"))); 513 static size_t rs_have; /* valid bytes at end of rs_buf */ 514 static size_t rs_count; /* bytes till reseed */ 515 516 void 517 suspend_randomness(void) 518 { 519 struct timespec ts; 520 521 getnanotime(&ts); 522 add_true_randomness(ts.tv_sec); 523 add_true_randomness(ts.tv_nsec); 524 525 dequeue_randomness(NULL); 526 rs_count = 0; 527 arc4random_buf(entropy_pool, sizeof(entropy_pool)); 528 } 529 530 void 531 resume_randomness(char *buf, size_t buflen) 532 { 533 struct timespec ts; 534 535 if (buf && buflen) 536 _rs_seed(buf, buflen); 537 getnanotime(&ts); 538 add_true_randomness(ts.tv_sec); 539 add_true_randomness(ts.tv_nsec); 540 541 dequeue_randomness(NULL); 542 rs_count = 0; 543 } 544 545 static inline void _rs_rekey(u_char *dat, size_t datlen); 546 547 static inline void 548 _rs_init(u_char *buf, size_t n) 549 { 550 KASSERT(n >= KEYSZ + IVSZ); 551 chacha_keysetup(&rs, buf, KEYSZ * 8); 552 chacha_ivsetup(&rs, buf + KEYSZ, NULL); 553 } 554 555 static void 556 _rs_seed(u_char *buf, size_t n) 557 { 558 _rs_rekey(buf, n); 559 560 /* invalidate rs_buf */ 561 rs_have = 0; 562 memset(rs_buf, 0, RSBUFSZ); 563 564 rs_count = 1600000; 565 } 566 567 static void 568 _rs_stir(int do_lock) 569 { 570 struct timespec ts; 571 u_int8_t buf[EBUFSIZE], *p; 572 int i; 573 574 /* 575 * Use SHA512 PRNG data and a system timespec; early in the boot 576 * process this is the best we can do -- some architectures do 577 * not collect entropy very well during this time, but may have 578 * clock information which is better than nothing. 579 */ 580 extract_entropy(buf); 581 582 nanotime(&ts); 583 for (p = (u_int8_t *)&ts, i = 0; i < sizeof(ts); i++) 584 buf[i] ^= p[i]; 585 586 if (do_lock) 587 mtx_enter(&rndlock); 588 _rs_seed(buf, sizeof(buf)); 589 if (do_lock) 590 mtx_leave(&rndlock); 591 592 explicit_bzero(buf, sizeof(buf)); 593 } 594 595 static inline void 596 _rs_stir_if_needed(size_t len) 597 { 598 if (!rs_initialized) { 599 _rs_init(rs_buf, KEYSZ + IVSZ); 600 rs_count = 1024 * 1024 * 1024; /* until main() runs */ 601 rs_initialized = 1; 602 } else if (rs_count <= len) 603 _rs_stir(0); 604 else 605 rs_count -= len; 606 } 607 608 static inline void 609 _rs_rekey(u_char *dat, size_t datlen) 610 { 611 #ifndef KEYSTREAM_ONLY 612 memset(rs_buf, 0, RSBUFSZ); 613 #endif 614 /* fill rs_buf with the keystream */ 615 chacha_encrypt_bytes(&rs, rs_buf, rs_buf, RSBUFSZ); 616 /* mix in optional user provided data */ 617 if (dat) { 618 size_t i, m; 619 620 m = MIN(datlen, KEYSZ + IVSZ); 621 for (i = 0; i < m; i++) 622 rs_buf[i] ^= dat[i]; 623 } 624 /* immediately reinit for backtracking resistance */ 625 _rs_init(rs_buf, KEYSZ + IVSZ); 626 memset(rs_buf, 0, KEYSZ + IVSZ); 627 rs_have = RSBUFSZ - KEYSZ - IVSZ; 628 } 629 630 static inline void 631 _rs_random_buf(void *_buf, size_t n) 632 { 633 u_char *buf = (u_char *)_buf; 634 size_t m; 635 636 _rs_stir_if_needed(n); 637 while (n > 0) { 638 if (rs_have > 0) { 639 m = MIN(n, rs_have); 640 memcpy(buf, rs_buf + RSBUFSZ - rs_have, m); 641 memset(rs_buf + RSBUFSZ - rs_have, 0, m); 642 buf += m; 643 n -= m; 644 rs_have -= m; 645 } 646 if (rs_have == 0) 647 _rs_rekey(NULL, 0); 648 } 649 } 650 651 static inline void 652 _rs_random_u32(u_int32_t *val) 653 { 654 _rs_stir_if_needed(sizeof(*val)); 655 if (rs_have < sizeof(*val)) 656 _rs_rekey(NULL, 0); 657 memcpy(val, rs_buf + RSBUFSZ - rs_have, sizeof(*val)); 658 memset(rs_buf + RSBUFSZ - rs_have, 0, sizeof(*val)); 659 rs_have -= sizeof(*val); 660 return; 661 } 662 663 /* Return one word of randomness from a ChaCha20 generator */ 664 u_int32_t 665 arc4random(void) 666 { 667 u_int32_t ret; 668 669 mtx_enter(&rndlock); 670 _rs_random_u32(&ret); 671 mtx_leave(&rndlock); 672 return ret; 673 } 674 675 /* 676 * Fill a buffer of arbitrary length with ChaCha20-derived randomness. 677 */ 678 void 679 arc4random_buf(void *buf, size_t n) 680 { 681 mtx_enter(&rndlock); 682 _rs_random_buf(buf, n); 683 mtx_leave(&rndlock); 684 } 685 686 /* 687 * Calculate a uniformly distributed random number less than upper_bound 688 * avoiding "modulo bias". 689 * 690 * Uniformity is achieved by generating new random numbers until the one 691 * returned is outside the range [0, 2**32 % upper_bound). This 692 * guarantees the selected random number will be inside 693 * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound) 694 * after reduction modulo upper_bound. 695 */ 696 u_int32_t 697 arc4random_uniform(u_int32_t upper_bound) 698 { 699 u_int32_t r, min; 700 701 if (upper_bound < 2) 702 return 0; 703 704 /* 2**32 % x == (2**32 - x) % x */ 705 min = -upper_bound % upper_bound; 706 707 /* 708 * This could theoretically loop forever but each retry has 709 * p > 0.5 (worst case, usually far better) of selecting a 710 * number inside the range we need, so it should rarely need 711 * to re-roll. 712 */ 713 for (;;) { 714 r = arc4random(); 715 if (r >= min) 716 break; 717 } 718 719 return r % upper_bound; 720 } 721 722 /* ARGSUSED */ 723 void 724 arc4_init(void *null) 725 { 726 _rs_stir(1); 727 } 728 729 /* 730 * Called by timeout to mark arc4 for stirring, 731 */ 732 void 733 arc4_reinit(void *v) 734 { 735 task_add(systq, &arc4_task); 736 /* 10 minutes, per dm@'s suggestion */ 737 timeout_add_sec(&arc4_timeout, 10 * 60); 738 } 739 740 /* 741 * Start periodic services inside the random subsystem, which pull 742 * entropy forward, hash it, and re-seed the random stream as needed. 743 */ 744 void 745 random_start(void) 746 { 747 #if !defined(NO_PROPOLICE) 748 extern long __guard_local; 749 750 if (__guard_local == 0) 751 printf("warning: no entropy supplied by boot loader\n"); 752 #endif 753 754 rnd_states[RND_SRC_TIMER].dont_count_entropy = 1; 755 rnd_states[RND_SRC_TRUE].dont_count_entropy = 1; 756 rnd_states[RND_SRC_TRUE].max_entropy = 1; 757 758 /* Provide some data from this kernel */ 759 add_entropy_words((u_int32_t *)version, 760 strlen(version) / sizeof(u_int32_t)); 761 762 /* Provide some data from this kernel */ 763 add_entropy_words((u_int32_t *)cfdata, 764 8192 / sizeof(u_int32_t)); 765 766 /* Message buffer may contain data from previous boot */ 767 if (msgbufp->msg_magic == MSG_MAGIC) 768 add_entropy_words((u_int32_t *)msgbufp->msg_bufc, 769 msgbufp->msg_bufs / sizeof(u_int32_t)); 770 771 rs_initialized = 1; 772 dequeue_randomness(NULL); 773 arc4_init(NULL); 774 timeout_set(&arc4_timeout, arc4_reinit, NULL); 775 arc4_reinit(NULL); 776 timeout_set(&rnd_timeout, dequeue_randomness, NULL); 777 } 778 779 int 780 randomopen(dev_t dev, int flag, int mode, struct proc *p) 781 { 782 return 0; 783 } 784 785 int 786 randomclose(dev_t dev, int flag, int mode, struct proc *p) 787 { 788 return 0; 789 } 790 791 /* 792 * Maximum number of bytes to serve directly from the main ChaCha 793 * pool. Larger requests are served from a discrete ChaCha instance keyed 794 * from the main pool. 795 */ 796 #define ARC4_MAIN_MAX_BYTES 2048 797 798 int 799 randomread(dev_t dev, struct uio *uio, int ioflag) 800 { 801 u_char lbuf[KEYSZ+IVSZ]; 802 chacha_ctx lctx; 803 size_t total = uio->uio_resid; 804 u_char *buf; 805 int myctx = 0, ret = 0; 806 807 if (uio->uio_resid == 0) 808 return 0; 809 810 buf = malloc(POOLBYTES, M_TEMP, M_WAITOK); 811 if (total > ARC4_MAIN_MAX_BYTES) { 812 arc4random_buf(lbuf, sizeof(lbuf)); 813 chacha_keysetup(&lctx, lbuf, KEYSZ * 8); 814 chacha_ivsetup(&lctx, lbuf + KEYSZ, NULL); 815 explicit_bzero(lbuf, sizeof(lbuf)); 816 myctx = 1; 817 } 818 819 while (ret == 0 && uio->uio_resid > 0) { 820 size_t n = ulmin(POOLBYTES, uio->uio_resid); 821 822 if (myctx) { 823 #ifndef KEYSTREAM_ONLY 824 memset(buf, 0, n); 825 #endif 826 chacha_encrypt_bytes(&lctx, buf, buf, n); 827 } else 828 arc4random_buf(buf, n); 829 ret = uiomove(buf, n, uio); 830 if (ret == 0 && uio->uio_resid > 0) 831 yield(); 832 } 833 if (myctx) 834 explicit_bzero(&lctx, sizeof(lctx)); 835 explicit_bzero(buf, POOLBYTES); 836 free(buf, M_TEMP, POOLBYTES); 837 return ret; 838 } 839 840 int 841 randomwrite(dev_t dev, struct uio *uio, int flags) 842 { 843 int ret = 0, newdata = 0; 844 u_int32_t *buf; 845 846 if (uio->uio_resid == 0) 847 return 0; 848 849 buf = malloc(POOLBYTES, M_TEMP, M_WAITOK); 850 851 while (ret == 0 && uio->uio_resid > 0) { 852 size_t n = ulmin(POOLBYTES, uio->uio_resid); 853 854 ret = uiomove(buf, n, uio); 855 if (ret != 0) 856 break; 857 while (n % sizeof(u_int32_t)) 858 ((u_int8_t *)buf)[n++] = 0; 859 add_entropy_words(buf, n / 4); 860 if (uio->uio_resid > 0) 861 yield(); 862 newdata = 1; 863 } 864 865 if (newdata) 866 arc4_init(NULL); 867 868 explicit_bzero(buf, POOLBYTES); 869 free(buf, M_TEMP, POOLBYTES); 870 return ret; 871 } 872 873 int 874 randomkqfilter(dev_t dev, struct knote *kn) 875 { 876 switch (kn->kn_filter) { 877 case EVFILT_READ: 878 kn->kn_fop = &randomread_filtops; 879 break; 880 case EVFILT_WRITE: 881 kn->kn_fop = &randomwrite_filtops; 882 break; 883 default: 884 return (EINVAL); 885 } 886 887 return (0); 888 } 889 890 void 891 filt_randomdetach(struct knote *kn) 892 { 893 } 894 895 int 896 filt_randomread(struct knote *kn, long hint) 897 { 898 kn->kn_data = ARC4_MAIN_MAX_BYTES; 899 return (1); 900 } 901 902 int 903 filt_randomwrite(struct knote *kn, long hint) 904 { 905 kn->kn_data = POOLBYTES; 906 return (1); 907 } 908 909 int 910 randomioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct proc *p) 911 { 912 switch (cmd) { 913 case FIOASYNC: 914 /* No async flag in softc so this is a no-op. */ 915 break; 916 case FIONBIO: 917 /* Handled in the upper FS layer. */ 918 break; 919 default: 920 return ENOTTY; 921 } 922 return 0; 923 } 924 925 int 926 sys_getentropy(struct proc *p, void *v, register_t *retval) 927 { 928 struct sys_getentropy_args /* { 929 syscallarg(void *) buf; 930 syscallarg(size_t) nbyte; 931 } */ *uap = v; 932 char buf[256]; 933 int error; 934 935 if (SCARG(uap, nbyte) > sizeof(buf)) 936 return (EIO); 937 arc4random_buf(buf, SCARG(uap, nbyte)); 938 if ((error = copyout(buf, SCARG(uap, buf), SCARG(uap, nbyte))) != 0) 939 return (error); 940 explicit_bzero(buf, sizeof(buf)); 941 retval[0] = 0; 942 return (0); 943 } 944