Fri Mar 25 22:13:23 2016 UTC ()
KNF


(riastradh)
diff -r1.30 -r1.31 src/lib/libc/gen/arc4random.c

cvs diff -r1.30 -r1.31 src/lib/libc/gen/arc4random.c (switch to unified diff)

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