xref: /freebsd/lib/libc/gen/arc4random.c (revision 069ac18495ad8fde2748bc94b0f80a50250bb01d)
1 /*	$OpenBSD: arc4random.c,v 1.58 2022/07/31 13:41:45 tb Exp $	*/
2 
3 /*
4  * Copyright (c) 1996, David Mazieres <dm@uun.org>
5  * Copyright (c) 2008, Damien Miller <djm@openbsd.org>
6  * Copyright (c) 2013, Markus Friedl <markus@openbsd.org>
7  * Copyright (c) 2014, Theo de Raadt <deraadt@openbsd.org>
8  *
9  * Permission to use, copy, modify, and distribute this software for any
10  * purpose with or without fee is hereby granted, provided that the above
11  * copyright notice and this permission notice appear in all copies.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20  */
21 
22 /*
23  * ChaCha based random number generator for OpenBSD.
24  */
25 
26 #include "namespace.h"
27 #if defined(__FreeBSD__)
28 #include <assert.h>
29 #endif
30 #include <fcntl.h>
31 #include <limits.h>
32 #include <pthread.h>
33 #include <signal.h>
34 #include <stdint.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <sys/types.h>
39 #include <sys/time.h>
40 
41 #include "libc_private.h"
42 #include "un-namespace.h"
43 
44 #define CHACHA_EMBED
45 #define KEYSTREAM_ONLY
46 #if defined(__FreeBSD__)
47 #define ARC4RANDOM_FXRNG 1
48 #else
49 #define ARC4RANDOM_FXRNG 0
50 #endif
51 #include "chacha.c"
52 
53 #define minimum(a, b) ((a) < (b) ? (a) : (b))
54 
55 #if defined(__GNUC__) || defined(_MSC_VER)
56 #define inline __inline
57 #else				/* __GNUC__ || _MSC_VER */
58 #define inline
59 #endif				/* !__GNUC__ && !_MSC_VER */
60 
61 #define KEYSZ	32
62 #define IVSZ	8
63 #define BLOCKSZ	64
64 #define RSBUFSZ	(16*BLOCKSZ)
65 
66 #define REKEY_BASE	(1024*1024) /* NB. should be a power of 2 */
67 
68 /* Marked INHERIT_ZERO, so zero'd out in fork children. */
69 static struct _rs {
70 	size_t		rs_have;	/* valid bytes at end of rs_buf */
71 	size_t		rs_count;	/* bytes till reseed */
72 } *rs;
73 
74 /* Maybe be preserved in fork children, if _rs_allocate() decides. */
75 static struct _rsx {
76 	chacha_ctx	rs_chacha;	/* chacha context for random keystream */
77 	u_char		rs_buf[RSBUFSZ];	/* keystream blocks */
78 #ifdef __FreeBSD__
79 	uint32_t	rs_seed_generation;	/* 32-bit userspace RNG version */
80 #endif
81 } *rsx;
82 
83 static inline int _rs_allocate(struct _rs **, struct _rsx **);
84 static inline void _rs_forkdetect(void);
85 #include "arc4random.h"
86 
87 static inline void _rs_rekey(u_char *dat, size_t datlen);
88 
89 static inline void
90 _rs_init(u_char *buf, size_t n)
91 {
92 	if (n < KEYSZ + IVSZ)
93 		return;
94 
95 	if (rs == NULL) {
96 		if (_rs_allocate(&rs, &rsx) == -1)
97 			_exit(1);
98 	}
99 
100 	chacha_keysetup(&rsx->rs_chacha, buf, KEYSZ * 8);
101 	chacha_ivsetup(&rsx->rs_chacha, buf + KEYSZ, NULL);
102 }
103 
104 static void
105 _rs_stir(void)
106 {
107 	u_char rnd[KEYSZ + IVSZ];
108 	uint32_t rekey_fuzz = 0;
109 
110 #if defined(__FreeBSD__)
111 	bool need_init;
112 
113 	/*
114 	 * De-couple allocation (which locates the vdso_fxrngp pointer in
115 	 * auxinfo) from initialization.  This allows us to read the root seed
116 	 * version before we fetch system entropy, maintaining the invariant
117 	 * that the PRF was seeded with entropy from rs_seed_generation or a
118 	 * later generation.  But never seeded from an earlier generation.
119 	 * This invariant prevents us from missing a root reseed event.
120 	 */
121 	need_init = false;
122 	if (rs == NULL) {
123 		if (_rs_allocate(&rs, &rsx) == -1)
124 			abort();
125 		need_init = true;
126 	}
127 	/*
128 	 * Transition period: new userspace on old kernel.  This should become
129 	 * a hard error at some point, if the scheme is adopted.
130 	 */
131 	if (vdso_fxrngp != NULL)
132 		rsx->rs_seed_generation =
133 		    fxrng_load_acq_generation(&vdso_fxrngp->fx_generation32);
134 #endif
135 
136 	if (getentropy(rnd, sizeof rnd) == -1)
137 		_getentropy_fail();
138 
139 #if !defined(__FreeBSD__)
140 	if (!rs)
141 		_rs_init(rnd, sizeof(rnd));
142 #else /* __FreeBSD__ */
143 	assert(rs != NULL);
144 	if (need_init)
145 		_rs_init(rnd, sizeof(rnd));
146 #endif
147 	else
148 		_rs_rekey(rnd, sizeof(rnd));
149 	explicit_bzero(rnd, sizeof(rnd));	/* discard source seed */
150 
151 	/* invalidate rs_buf */
152 	rs->rs_have = 0;
153 	memset(rsx->rs_buf, 0, sizeof(rsx->rs_buf));
154 
155 	/* rekey interval should not be predictable */
156 	chacha_encrypt_bytes(&rsx->rs_chacha, (uint8_t *)&rekey_fuzz,
157 	    (uint8_t *)&rekey_fuzz, sizeof(rekey_fuzz));
158 	rs->rs_count = REKEY_BASE + (rekey_fuzz % REKEY_BASE);
159 }
160 
161 static inline void
162 _rs_stir_if_needed(size_t len)
163 {
164 	_rs_forkdetect();
165 	if (!rs || rs->rs_count <= len)
166 		_rs_stir();
167 	if (rs->rs_count <= len)
168 		rs->rs_count = 0;
169 	else
170 		rs->rs_count -= len;
171 }
172 
173 static inline void
174 _rs_rekey(u_char *dat, size_t datlen)
175 {
176 #ifndef KEYSTREAM_ONLY
177 	memset(rsx->rs_buf, 0, sizeof(rsx->rs_buf));
178 #endif
179 	/* fill rs_buf with the keystream */
180 	chacha_encrypt_bytes(&rsx->rs_chacha, rsx->rs_buf,
181 	    rsx->rs_buf, sizeof(rsx->rs_buf));
182 	/* mix in optional user provided data */
183 	if (dat) {
184 		size_t i, m;
185 
186 		m = minimum(datlen, KEYSZ + IVSZ);
187 		for (i = 0; i < m; i++)
188 			rsx->rs_buf[i] ^= dat[i];
189 	}
190 	/* immediately reinit for backtracking resistance */
191 	_rs_init(rsx->rs_buf, KEYSZ + IVSZ);
192 	memset(rsx->rs_buf, 0, KEYSZ + IVSZ);
193 	rs->rs_have = sizeof(rsx->rs_buf) - KEYSZ - IVSZ;
194 }
195 
196 static inline void
197 _rs_random_buf(void *_buf, size_t n)
198 {
199 	u_char *buf = (u_char *)_buf;
200 	u_char *keystream;
201 	size_t m;
202 
203 	_rs_stir_if_needed(n);
204 	while (n > 0) {
205 		if (rs->rs_have > 0) {
206 			m = minimum(n, rs->rs_have);
207 			keystream = rsx->rs_buf + sizeof(rsx->rs_buf)
208 			    - rs->rs_have;
209 			memcpy(buf, keystream, m);
210 			memset(keystream, 0, m);
211 			buf += m;
212 			n -= m;
213 			rs->rs_have -= m;
214 		}
215 		if (rs->rs_have == 0)
216 			_rs_rekey(NULL, 0);
217 	}
218 }
219 
220 static inline void
221 _rs_random_u32(uint32_t *val)
222 {
223 	u_char *keystream;
224 
225 	_rs_stir_if_needed(sizeof(*val));
226 	if (rs->rs_have < sizeof(*val))
227 		_rs_rekey(NULL, 0);
228 	keystream = rsx->rs_buf + sizeof(rsx->rs_buf) - rs->rs_have;
229 	memcpy(val, keystream, sizeof(*val));
230 	memset(keystream, 0, sizeof(*val));
231 	rs->rs_have -= sizeof(*val);
232 }
233 
234 uint32_t
235 arc4random(void)
236 {
237 	uint32_t val;
238 
239 	_ARC4_LOCK();
240 	_rs_random_u32(&val);
241 	_ARC4_UNLOCK();
242 	return val;
243 }
244 
245 void
246 arc4random_buf(void *buf, size_t n)
247 {
248 	_ARC4_LOCK();
249 	_rs_random_buf(buf, n);
250 	_ARC4_UNLOCK();
251 }
252