1 /* $NetBSD: arc4random.c,v 1.30 2015/05/13 23:15:57 justin Exp $ */ 2 3 /*- 4 * Copyright (c) 2014 The NetBSD Foundation, Inc. 5 * All rights reserved. 6 * 7 * This code is derived from software contributed to The NetBSD Foundation 8 * by Taylor R. Campbell. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 29 * POSSIBILITY OF SUCH DAMAGE. 30 */ 31 32 /* 33 * Legacy arc4random(3) API from OpenBSD reimplemented using the 34 * ChaCha20 PRF, with per-thread state. 35 * 36 * Security model: 37 * - An attacker who sees some outputs cannot predict past or future 38 * outputs. 39 * - An attacker who sees the PRNG state cannot predict past outputs. 40 * - An attacker who sees a child's PRNG state cannot predict past or 41 * future outputs in the parent, or in other children. 42 * 43 * The arc4random(3) API may abort the process if: 44 * 45 * (a) the crypto self-test fails, 46 * (b) pthread_atfork or thr_keycreate fail, or 47 * (c) sysctl(KERN_ARND) fails when reseeding the PRNG. 48 * 49 * The crypto self-test, pthread_atfork, and thr_keycreate occur only 50 * once, on the first use of any of the arc4random(3) API. KERN_ARND 51 * is unlikely to fail later unless the kernel is seriously broken. 52 */ 53 54 #include <sys/cdefs.h> 55 __RCSID("$NetBSD: arc4random.c,v 1.30 2015/05/13 23:15:57 justin Exp $"); 56 57 #include "namespace.h" 58 #include "reentrant.h" 59 60 #include <sys/bitops.h> 61 #include <sys/endian.h> 62 #include <sys/errno.h> 63 #if defined(__minix) 64 #include <sys/fcntl.h> 65 #endif 66 #include <sys/mman.h> 67 #include <sys/sysctl.h> 68 69 #include <assert.h> 70 #include <sha2.h> 71 #include <stdbool.h> 72 #include <stdint.h> 73 #include <stdlib.h> 74 #include <string.h> 75 #include <unistd.h> 76 77 #ifdef __weak_alias 78 __weak_alias(arc4random,_arc4random) 79 __weak_alias(arc4random_addrandom,_arc4random_addrandom) 80 __weak_alias(arc4random_buf,_arc4random_buf) 81 __weak_alias(arc4random_stir,_arc4random_stir) 82 __weak_alias(arc4random_uniform,_arc4random_uniform) 83 #endif 84 85 /* 86 * For standard ChaCha, use le32dec/le32enc. We don't need that for 87 * the purposes of a nondeterministic random number generator -- we 88 * don't need to be bit-for-bit compatible over any wire. 89 */ 90 91 static inline uint32_t 92 crypto_le32dec(const void *p) 93 { 94 uint32_t v; 95 96 (void)memcpy(&v, p, sizeof v); 97 98 return v; 99 } 100 101 static inline void 102 crypto_le32enc(void *p, uint32_t v) 103 { 104 105 (void)memcpy(p, &v, sizeof v); 106 } 107 108 /* ChaCha core */ 109 110 #define crypto_core_OUTPUTBYTES 64 111 #define crypto_core_INPUTBYTES 16 112 #define crypto_core_KEYBYTES 32 113 #define crypto_core_CONSTBYTES 16 114 115 #define crypto_core_ROUNDS 20 116 117 static uint32_t 118 rotate(uint32_t u, unsigned c) 119 { 120 121 return (u << c) | (u >> (32 - c)); 122 } 123 124 #define QUARTERROUND(a, b, c, d) do { \ 125 (a) += (b); (d) ^= (a); (d) = rotate((d), 16); \ 126 (c) += (d); (b) ^= (c); (b) = rotate((b), 12); \ 127 (a) += (b); (d) ^= (a); (d) = rotate((d), 8); \ 128 (c) += (d); (b) ^= (c); (b) = rotate((b), 7); \ 129 } while (/*CONSTCOND*/0) 130 131 const uint8_t crypto_core_constant32[16] = "expand 32-byte k"; 132 133 static void 134 crypto_core(uint8_t *out, const uint8_t *in, const uint8_t *k, 135 const uint8_t *c) 136 { 137 uint32_t x0,x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15; 138 uint32_t j0,j1,j2,j3,j4,j5,j6,j7,j8,j9,j10,j11,j12,j13,j14,j15; 139 int i; 140 141 j0 = x0 = crypto_le32dec(c + 0); 142 j1 = x1 = crypto_le32dec(c + 4); 143 j2 = x2 = crypto_le32dec(c + 8); 144 j3 = x3 = crypto_le32dec(c + 12); 145 j4 = x4 = crypto_le32dec(k + 0); 146 j5 = x5 = crypto_le32dec(k + 4); 147 j6 = x6 = crypto_le32dec(k + 8); 148 j7 = x7 = crypto_le32dec(k + 12); 149 j8 = x8 = crypto_le32dec(k + 16); 150 j9 = x9 = crypto_le32dec(k + 20); 151 j10 = x10 = crypto_le32dec(k + 24); 152 j11 = x11 = crypto_le32dec(k + 28); 153 j12 = x12 = crypto_le32dec(in + 0); 154 j13 = x13 = crypto_le32dec(in + 4); 155 j14 = x14 = crypto_le32dec(in + 8); 156 j15 = x15 = crypto_le32dec(in + 12); 157 158 for (i = crypto_core_ROUNDS; i > 0; i -= 2) { 159 QUARTERROUND( x0, x4, x8,x12); 160 QUARTERROUND( x1, x5, x9,x13); 161 QUARTERROUND( x2, x6,x10,x14); 162 QUARTERROUND( x3, x7,x11,x15); 163 QUARTERROUND( x0, x5,x10,x15); 164 QUARTERROUND( x1, x6,x11,x12); 165 QUARTERROUND( x2, x7, x8,x13); 166 QUARTERROUND( x3, x4, x9,x14); 167 } 168 169 crypto_le32enc(out + 0, x0 + j0); 170 crypto_le32enc(out + 4, x1 + j1); 171 crypto_le32enc(out + 8, x2 + j2); 172 crypto_le32enc(out + 12, x3 + j3); 173 crypto_le32enc(out + 16, x4 + j4); 174 crypto_le32enc(out + 20, x5 + j5); 175 crypto_le32enc(out + 24, x6 + j6); 176 crypto_le32enc(out + 28, x7 + j7); 177 crypto_le32enc(out + 32, x8 + j8); 178 crypto_le32enc(out + 36, x9 + j9); 179 crypto_le32enc(out + 40, x10 + j10); 180 crypto_le32enc(out + 44, x11 + j11); 181 crypto_le32enc(out + 48, x12 + j12); 182 crypto_le32enc(out + 52, x13 + j13); 183 crypto_le32enc(out + 56, x14 + j14); 184 crypto_le32enc(out + 60, x15 + j15); 185 } 186 187 /* ChaCha self-test */ 188 189 #ifdef _DIAGNOSTIC 190 191 /* 192 * Test vector for ChaCha20 from 193 * <http://tools.ietf.org/html/draft-strombergson-chacha-test-vectors-00>, 194 * test vectors for ChaCha12 and ChaCha8 and for big-endian machines 195 * generated by the same crypto_core code with crypto_core_ROUNDS and 196 * crypto_le32enc/dec varied. 197 */ 198 199 static const uint8_t crypto_core_selftest_vector[64] = { 200 #if _BYTE_ORDER == _LITTLE_ENDIAN 201 # if crypto_core_ROUNDS == 8 202 0x3e,0x00,0xef,0x2f,0x89,0x5f,0x40,0xd6, 203 0x7f,0x5b,0xb8,0xe8,0x1f,0x09,0xa5,0xa1, 204 0x2c,0x84,0x0e,0xc3,0xce,0x9a,0x7f,0x3b, 205 0x18,0x1b,0xe1,0x88,0xef,0x71,0x1a,0x1e, 206 0x98,0x4c,0xe1,0x72,0xb9,0x21,0x6f,0x41, 207 0x9f,0x44,0x53,0x67,0x45,0x6d,0x56,0x19, 208 0x31,0x4a,0x42,0xa3,0xda,0x86,0xb0,0x01, 209 0x38,0x7b,0xfd,0xb8,0x0e,0x0c,0xfe,0x42, 210 # elif crypto_core_ROUNDS == 12 211 0x9b,0xf4,0x9a,0x6a,0x07,0x55,0xf9,0x53, 212 0x81,0x1f,0xce,0x12,0x5f,0x26,0x83,0xd5, 213 0x04,0x29,0xc3,0xbb,0x49,0xe0,0x74,0x14, 214 0x7e,0x00,0x89,0xa5,0x2e,0xae,0x15,0x5f, 215 0x05,0x64,0xf8,0x79,0xd2,0x7a,0xe3,0xc0, 216 0x2c,0xe8,0x28,0x34,0xac,0xfa,0x8c,0x79, 217 0x3a,0x62,0x9f,0x2c,0xa0,0xde,0x69,0x19, 218 0x61,0x0b,0xe8,0x2f,0x41,0x13,0x26,0xbe, 219 # elif crypto_core_ROUNDS == 20 220 0x76,0xb8,0xe0,0xad,0xa0,0xf1,0x3d,0x90, 221 0x40,0x5d,0x6a,0xe5,0x53,0x86,0xbd,0x28, 222 0xbd,0xd2,0x19,0xb8,0xa0,0x8d,0xed,0x1a, 223 0xa8,0x36,0xef,0xcc,0x8b,0x77,0x0d,0xc7, 224 0xda,0x41,0x59,0x7c,0x51,0x57,0x48,0x8d, 225 0x77,0x24,0xe0,0x3f,0xb8,0xd8,0x4a,0x37, 226 0x6a,0x43,0xb8,0xf4,0x15,0x18,0xa1,0x1c, 227 0xc3,0x87,0xb6,0x69,0xb2,0xee,0x65,0x86, 228 # else 229 # error crypto_core_ROUNDS must be 8, 12, or 20. 230 # endif 231 #elif _BYTE_ORDER == _BIG_ENDIAN 232 # if crypto_core_ROUNDS == 8 233 0x9a,0x13,0x07,0xe3,0x38,0x18,0x9e,0x99, 234 0x15,0x37,0x16,0x4d,0x04,0xe6,0x48,0x9a, 235 0x07,0xd6,0xe8,0x7a,0x02,0xf9,0xf5,0xc7, 236 0x3f,0xa9,0xc2,0x0a,0xe1,0xc6,0x62,0xea, 237 0x80,0xaf,0xb6,0x51,0xca,0x52,0x43,0x87, 238 0xe3,0xa6,0xa6,0x61,0x11,0xf5,0xe6,0xcf, 239 0x09,0x0f,0xdc,0x9d,0xc3,0xc3,0xbb,0x43, 240 0xd7,0xfa,0x70,0x42,0xbf,0xa5,0xee,0xa2, 241 # elif crypto_core_ROUNDS == 12 242 0xcf,0x6c,0x16,0x48,0xbf,0xf4,0xba,0x85, 243 0x32,0x69,0xd3,0x98,0xc8,0x7d,0xcd,0x3f, 244 0xdc,0x76,0x6b,0xa2,0x7b,0xcb,0x17,0x4d, 245 0x05,0xda,0xdd,0xd8,0x62,0x54,0xbf,0xe0, 246 0x65,0xed,0x0e,0xf4,0x01,0x7e,0x3c,0x05, 247 0x35,0xb2,0x7a,0x60,0xf3,0x8f,0x12,0x33, 248 0x24,0x60,0xcd,0x85,0xfe,0x4c,0xf3,0x39, 249 0xb1,0x0e,0x3e,0xe0,0xba,0xa6,0x2f,0xa9, 250 # elif crypto_core_ROUNDS == 20 251 0x83,0x8b,0xf8,0x75,0xf7,0xde,0x9d,0x8c, 252 0x33,0x14,0x72,0x28,0xd1,0xbe,0x88,0xe5, 253 0x94,0xb5,0xed,0xb8,0x56,0xb5,0x9e,0x0c, 254 0x64,0x6a,0xaf,0xd9,0xa7,0x49,0x10,0x59, 255 0xba,0x3a,0x82,0xf8,0x4a,0x70,0x9c,0x00, 256 0x82,0x2c,0xae,0xc6,0xd7,0x1c,0x2e,0xda, 257 0x2a,0xfb,0x61,0x70,0x2b,0xd1,0xbf,0x8b, 258 0x95,0xbc,0x23,0xb6,0x4b,0x60,0x02,0xec, 259 # else 260 # error crypto_core_ROUNDS must be 8, 12, or 20. 261 # endif 262 #else 263 # error Byte order must be little-endian or big-endian. 264 #endif 265 }; 266 267 static int 268 crypto_core_selftest(void) 269 { 270 const uint8_t nonce[crypto_core_INPUTBYTES] = {0}; 271 const uint8_t key[crypto_core_KEYBYTES] = {0}; 272 uint8_t block[64]; 273 unsigned i; 274 275 crypto_core(block, nonce, key, crypto_core_constant32); 276 for (i = 0; i < 64; i++) { 277 if (block[i] != crypto_core_selftest_vector[i]) 278 return EIO; 279 } 280 281 return 0; 282 } 283 284 #else /* !_DIAGNOSTIC */ 285 286 static int 287 crypto_core_selftest(void) 288 { 289 290 return 0; 291 } 292 293 #endif 294 295 /* PRNG */ 296 297 /* 298 * For a state s, rather than use ChaCha20 as a stream cipher to 299 * generate the concatenation ChaCha20_s(0) || ChaCha20_s(1) || ..., we 300 * split ChaCha20_s(0) into s' || x and yield x for the first request, 301 * split ChaCha20_s'(0) into s'' || y and yield y for the second 302 * request, &c. This provides backtracking resistance: an attacker who 303 * finds s'' can't recover s' or x. 304 */ 305 306 #define crypto_prng_SEEDBYTES crypto_core_KEYBYTES 307 #define crypto_prng_MAXOUTPUTBYTES \ 308 (crypto_core_OUTPUTBYTES - crypto_prng_SEEDBYTES) 309 310 struct crypto_prng { 311 uint8_t state[crypto_prng_SEEDBYTES]; 312 }; 313 314 static void 315 crypto_prng_seed(struct crypto_prng *prng, const void *seed) 316 { 317 318 (void)memcpy(prng->state, seed, crypto_prng_SEEDBYTES); 319 } 320 321 static void 322 crypto_prng_buf(struct crypto_prng *prng, void *buf, size_t n) 323 { 324 const uint8_t nonce[crypto_core_INPUTBYTES] = {0}; 325 uint8_t output[crypto_core_OUTPUTBYTES]; 326 327 _DIAGASSERT(n <= crypto_prng_MAXOUTPUTBYTES); 328 __CTASSERT(sizeof prng->state + crypto_prng_MAXOUTPUTBYTES 329 <= sizeof output); 330 331 crypto_core(output, nonce, prng->state, crypto_core_constant32); 332 (void)memcpy(prng->state, output, sizeof prng->state); 333 (void)memcpy(buf, output + sizeof prng->state, n); 334 (void)explicit_memset(output, 0, sizeof output); 335 } 336 337 /* One-time stream: expand short single-use secret into long secret */ 338 339 #define crypto_onetimestream_SEEDBYTES crypto_core_KEYBYTES 340 341 static void 342 crypto_onetimestream(const void *seed, void *buf, size_t n) 343 { 344 uint32_t nonce[crypto_core_INPUTBYTES / sizeof(uint32_t)] = {0}; 345 uint8_t block[crypto_core_OUTPUTBYTES]; 346 uint8_t *p8, *p32; 347 const uint8_t *nonce8 = (const uint8_t *)(void *)nonce; 348 size_t ni, nb, nf; 349 350 /* 351 * Guarantee we can generate up to n bytes. We have 352 * 2^(8*INPUTBYTES) possible inputs yielding output of 353 * OUTPUTBYTES*2^(8*INPUTBYTES) bytes. It suffices to require 354 * that sizeof n > (1/CHAR_BIT) log_2 n be less than 355 * (1/CHAR_BIT) log_2 of the total output stream length. We 356 * have 357 * 358 * log_2 (o 2^(8 i)) = log_2 o + log_2 2^(8 i) 359 * = log_2 o + 8 i. 360 */ 361 __CTASSERT(CHAR_BIT * sizeof n <= 362 (/*LINTED*/ilog2(crypto_core_OUTPUTBYTES) + 8 * crypto_core_INPUTBYTES)); 363 364 p8 = buf; 365 p32 = (uint8_t *)roundup2((uintptr_t)p8, 4); 366 ni = p32 - p8; 367 if (n < ni) 368 ni = n; 369 nb = (n - ni) / sizeof block; 370 nf = (n - ni) % sizeof block; 371 372 _DIAGASSERT(((uintptr_t)p32 & 3) == 0); 373 _DIAGASSERT(ni <= n); 374 _DIAGASSERT(nb <= (n / sizeof block)); 375 _DIAGASSERT(nf <= n); 376 _DIAGASSERT(n == (ni + (nb * sizeof block) + nf)); 377 _DIAGASSERT(ni < 4); 378 _DIAGASSERT(nf < sizeof block); 379 380 if (ni) { 381 crypto_core(block, nonce8, seed, crypto_core_constant32); 382 nonce[0]++; 383 (void)memcpy(p8, block, ni); 384 } 385 while (nb--) { 386 crypto_core(p32, nonce8, seed, crypto_core_constant32); 387 if (++nonce[0] == 0) 388 nonce[1]++; 389 p32 += crypto_core_OUTPUTBYTES; 390 } 391 if (nf) { 392 crypto_core(block, nonce8, seed, crypto_core_constant32); 393 if (++nonce[0] == 0) 394 nonce[1]++; 395 (void)memcpy(p32, block, nf); 396 } 397 398 if (ni | nf) 399 (void)explicit_memset(block, 0, sizeof block); 400 } 401 402 /* arc4random state: per-thread, per-process (zeroed in child on fork) */ 403 404 struct arc4random_prng { 405 struct crypto_prng arc4_prng; 406 bool arc4_seeded; 407 }; 408 409 static void 410 arc4random_prng_addrandom(struct arc4random_prng *prng, const void *data, 411 size_t datalen) 412 { 413 #if !defined(__minix) 414 const int mib[] = { CTL_KERN, KERN_ARND }; 415 #endif /* !defined(__minix) */ 416 SHA256_CTX ctx; 417 uint8_t buf[crypto_prng_SEEDBYTES]; 418 size_t buflen = sizeof buf; 419 420 __CTASSERT(sizeof buf == SHA256_DIGEST_LENGTH); 421 422 SHA256_Init(&ctx); 423 424 crypto_prng_buf(&prng->arc4_prng, buf, sizeof buf); 425 SHA256_Update(&ctx, buf, sizeof buf); 426 427 #if defined(__minix) 428 /* LSC: We do not have a compatibility layer for the 429 * KERN_ARND call, so do it the old way... */ 430 int fd; 431 432 fd = open("/dev/urandom", O_RDONLY); 433 if (fd != -1) { 434 (void)read(fd, buf, buflen); 435 close(fd); 436 } 437 438 /* fd < 0 or failed sysctl ? Ah, what the heck. We'll just take 439 * whatever was on the stack... */ 440 #else 441 if (sysctl(mib, (u_int)__arraycount(mib), buf, &buflen, NULL, 0) == -1) 442 abort(); 443 #endif /* !defined(__minix) */ 444 if (buflen != sizeof buf) 445 abort(); 446 SHA256_Update(&ctx, buf, sizeof buf); 447 448 if (data != NULL) 449 SHA256_Update(&ctx, data, datalen); 450 451 SHA256_Final(buf, &ctx); 452 (void)explicit_memset(&ctx, 0, sizeof ctx); 453 454 /* reseed(SHA256(prng() || sysctl(KERN_ARND) || data)) */ 455 crypto_prng_seed(&prng->arc4_prng, buf); 456 (void)explicit_memset(buf, 0, sizeof buf); 457 prng->arc4_seeded = true; 458 } 459 460 #ifdef _REENTRANT 461 static struct arc4random_prng * 462 arc4random_prng_create(void) 463 { 464 struct arc4random_prng *prng; 465 const size_t size = roundup(sizeof(*prng), sysconf(_SC_PAGESIZE)); 466 467 prng = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0); 468 if (prng == MAP_FAILED) 469 goto fail0; 470 if (minherit(prng, size, MAP_INHERIT_ZERO) == -1) 471 goto fail1; 472 473 return prng; 474 475 fail1: (void)munmap(prng, size); 476 fail0: return NULL; 477 } 478 #endif 479 480 #ifdef _REENTRANT 481 static void 482 arc4random_prng_destroy(struct arc4random_prng *prng) 483 { 484 const size_t size = roundup(sizeof(*prng), sysconf(_SC_PAGESIZE)); 485 486 (void)explicit_memset(prng, 0, sizeof(*prng)); 487 (void)munmap(prng, size); 488 } 489 #endif 490 491 /* Library state */ 492 493 static struct arc4random_global { 494 #ifdef _REENTRANT 495 mutex_t lock; 496 thread_key_t thread_key; 497 #endif 498 struct arc4random_prng prng; 499 bool initialized; 500 } arc4random_global = { 501 #ifdef _REENTRANT 502 .lock = MUTEX_INITIALIZER, 503 #endif 504 .initialized = false, 505 }; 506 507 static void 508 arc4random_atfork_prepare(void) 509 { 510 511 mutex_lock(&arc4random_global.lock); 512 (void)explicit_memset(&arc4random_global.prng, 0, 513 sizeof arc4random_global.prng); 514 } 515 516 static void 517 arc4random_atfork_parent(void) 518 { 519 520 mutex_unlock(&arc4random_global.lock); 521 } 522 523 static void 524 arc4random_atfork_child(void) 525 { 526 527 mutex_unlock(&arc4random_global.lock); 528 } 529 530 #ifdef _REENTRANT 531 static void 532 arc4random_tsd_destructor(void *p) 533 { 534 struct arc4random_prng *const prng = p; 535 536 arc4random_prng_destroy(prng); 537 } 538 #endif 539 540 static void 541 arc4random_initialize(void) 542 { 543 544 mutex_lock(&arc4random_global.lock); 545 if (!arc4random_global.initialized) { 546 if (crypto_core_selftest() != 0) 547 abort(); 548 #if !defined(__minix) 549 if (pthread_atfork(&arc4random_atfork_prepare, 550 &arc4random_atfork_parent, &arc4random_atfork_child) 551 != 0) 552 abort(); 553 #endif /* !defined(__minix) */ 554 #ifdef _REENTRANT 555 if (thr_keycreate(&arc4random_global.thread_key, 556 &arc4random_tsd_destructor) != 0) 557 abort(); 558 #endif 559 arc4random_global.initialized = true; 560 } 561 mutex_unlock(&arc4random_global.lock); 562 } 563 564 static struct arc4random_prng * 565 arc4random_prng_get(void) 566 { 567 struct arc4random_prng *prng = NULL; 568 569 /* Make sure the library is initialized. */ 570 if (__predict_false(!arc4random_global.initialized)) 571 arc4random_initialize(); 572 573 #ifdef _REENTRANT 574 /* Get or create the per-thread PRNG state. */ 575 prng = thr_getspecific(arc4random_global.thread_key); 576 if (__predict_false(prng == NULL)) { 577 prng = arc4random_prng_create(); 578 thr_setspecific(arc4random_global.thread_key, prng); 579 } 580 #endif 581 582 /* If we can't create it, fall back to the global PRNG. */ 583 if (__predict_false(prng == NULL)) { 584 mutex_lock(&arc4random_global.lock); 585 prng = &arc4random_global.prng; 586 } 587 588 /* Guarantee the PRNG is seeded. */ 589 if (__predict_false(!prng->arc4_seeded)) 590 arc4random_prng_addrandom(prng, NULL, 0); 591 592 return prng; 593 } 594 595 static void 596 arc4random_prng_put(struct arc4random_prng *prng) 597 { 598 599 /* If we had fallen back to the global PRNG, unlock it. */ 600 if (__predict_false(prng == &arc4random_global.prng)) 601 mutex_unlock(&arc4random_global.lock); 602 } 603 604 /* Public API */ 605 606 uint32_t 607 arc4random(void) 608 { 609 struct arc4random_prng *prng; 610 uint32_t v; 611 612 prng = arc4random_prng_get(); 613 crypto_prng_buf(&prng->arc4_prng, &v, sizeof v); 614 arc4random_prng_put(prng); 615 616 return v; 617 } 618 619 void 620 arc4random_buf(void *buf, size_t len) 621 { 622 struct arc4random_prng *prng; 623 624 if (len <= crypto_prng_MAXOUTPUTBYTES) { 625 prng = arc4random_prng_get(); 626 crypto_prng_buf(&prng->arc4_prng, buf, len); 627 arc4random_prng_put(prng); 628 } else { 629 uint8_t seed[crypto_onetimestream_SEEDBYTES]; 630 631 prng = arc4random_prng_get(); 632 crypto_prng_buf(&prng->arc4_prng, seed, sizeof seed); 633 arc4random_prng_put(prng); 634 635 crypto_onetimestream(seed, buf, len); 636 (void)explicit_memset(seed, 0, sizeof seed); 637 } 638 } 639 640 uint32_t 641 arc4random_uniform(uint32_t bound) 642 { 643 struct arc4random_prng *prng; 644 uint32_t minimum, r; 645 646 /* 647 * We want a uniform random choice in [0, n), and arc4random() 648 * makes a uniform random choice in [0, 2^32). If we reduce 649 * that modulo n, values in [0, 2^32 mod n) will be represented 650 * slightly more than values in [2^32 mod n, n). Instead we 651 * choose only from [2^32 mod n, 2^32) by rejecting samples in 652 * [0, 2^32 mod n), to avoid counting the extra representative 653 * of [0, 2^32 mod n). To compute 2^32 mod n, note that 654 * 655 * 2^32 mod n = 2^32 mod n - 0 656 * = 2^32 mod n - n mod n 657 * = (2^32 - n) mod n, 658 * 659 * the last of which is what we compute in 32-bit arithmetic. 660 */ 661 minimum = (-bound % bound); 662 663 prng = arc4random_prng_get(); 664 do crypto_prng_buf(&prng->arc4_prng, &r, sizeof r); 665 while (__predict_false(r < minimum)); 666 arc4random_prng_put(prng); 667 668 return (r % bound); 669 } 670 671 void 672 arc4random_stir(void) 673 { 674 struct arc4random_prng *prng; 675 676 prng = arc4random_prng_get(); 677 arc4random_prng_addrandom(prng, NULL, 0); 678 arc4random_prng_put(prng); 679 } 680 681 /* 682 * Silly signature here is for hysterical raisins. Should instead be 683 * const void *data and size_t datalen. 684 */ 685 void 686 arc4random_addrandom(u_char *data, int datalen) 687 { 688 struct arc4random_prng *prng; 689 690 _DIAGASSERT(0 <= datalen); 691 692 prng = arc4random_prng_get(); 693 arc4random_prng_addrandom(prng, data, datalen); 694 arc4random_prng_put(prng); 695 } 696 697 #ifdef _ARC4RANDOM_TEST 698 699 #include <sys/wait.h> 700 701 #include <err.h> 702 #include <stdio.h> 703 704 int 705 main(int argc __unused, char **argv __unused) 706 { 707 unsigned char gubbish[] = "random gubbish"; 708 const uint8_t zero64[64] = {0}; 709 uint8_t buf[2048]; 710 unsigned i, a, n; 711 712 /* Test arc4random: should not be deterministic. */ 713 if (printf("arc4random: %08"PRIx32"\n", arc4random()) < 0) 714 err(1, "printf"); 715 716 /* Test stirring: should definitely not be deterministic. */ 717 arc4random_stir(); 718 719 /* Test small buffer. */ 720 arc4random_buf(buf, 8); 721 if (printf("arc4randombuf small:") < 0) 722 err(1, "printf"); 723 for (i = 0; i < 8; i++) 724 if (printf(" %02x", buf[i]) < 0) 725 err(1, "printf"); 726 if (printf("\n") < 0) 727 err(1, "printf"); 728 729 /* Test addrandom: should not make the rest deterministic. */ 730 arc4random_addrandom(gubbish, sizeof gubbish); 731 732 /* Test large buffer. */ 733 arc4random_buf(buf, sizeof buf); 734 if (printf("arc4randombuf_large:") < 0) 735 err(1, "printf"); 736 for (i = 0; i < sizeof buf; i++) 737 if (printf(" %02x", buf[i]) < 0) 738 err(1, "printf"); 739 if (printf("\n") < 0) 740 err(1, "printf"); 741 742 /* Test misaligned small and large. */ 743 for (a = 0; a < 64; a++) { 744 for (n = a; n < sizeof buf; n++) { 745 (void)memset(buf, 0, sizeof buf); 746 arc4random_buf(buf, n - a); 747 if (memcmp(buf + n - a, zero64, a) != 0) 748 errx(1, "arc4random buffer overflow 0"); 749 750 (void)memset(buf, 0, sizeof buf); 751 arc4random_buf(buf + a, n - a); 752 if (memcmp(buf, zero64, a) != 0) 753 errx(1, "arc4random buffer overflow 1"); 754 755 if ((2*a) <= n) { 756 (void)memset(buf, 0, sizeof buf); 757 arc4random_buf(buf + a, n - a - a); 758 if (memcmp(buf + n - a, zero64, a) != 0) 759 errx(1, 760 "arc4random buffer overflow 2"); 761 } 762 } 763 } 764 765 /* Test fork-safety. */ 766 { 767 pid_t pid, rpid; 768 int status; 769 770 pid = fork(); 771 switch (pid) { 772 case -1: 773 err(1, "fork"); 774 case 0: 775 _exit(arc4random_prng_get()->arc4_seeded); 776 default: 777 rpid = waitpid(pid, &status, 0); 778 if (rpid == -1) 779 err(1, "waitpid"); 780 if (rpid != pid) 781 errx(1, "waitpid returned wrong pid" 782 ": %"PRIdMAX" != %"PRIdMAX, 783 (intmax_t)rpid, 784 (intmax_t)pid); 785 if (WIFEXITED(status)) { 786 if (WEXITSTATUS(status) != 0) 787 errx(1, "child exited with %d", 788 WEXITSTATUS(status)); 789 } else if (WIFSIGNALED(status)) { 790 errx(1, "child terminated on signal %d", 791 WTERMSIG(status)); 792 } else { 793 errx(1, "child died mysteriously: %d", status); 794 } 795 } 796 } 797 798 /* XXX Test multithreaded fork safety...? */ 799 800 return 0; 801 } 802 #endif 803