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