xref: /freebsd/lib/libc/gen/arc4random.c (revision e9ac41698b2f322d55ccf9da50a3596edb2c1800)
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 <ssp/ssp.h>
39 #include <sys/types.h>
40 #include <sys/time.h>
41 
42 #include "libc_private.h"
43 #include "un-namespace.h"
44 
45 #define CHACHA_EMBED
46 #define KEYSTREAM_ONLY
47 #if defined(__FreeBSD__)
48 #define ARC4RANDOM_FXRNG 1
49 #else
50 #define ARC4RANDOM_FXRNG 0
51 #endif
52 #include "chacha.c"
53 
54 #define minimum(a, b) ((a) < (b) ? (a) : (b))
55 
56 #if defined(__GNUC__) || defined(_MSC_VER)
57 #define inline __inline
58 #else				/* __GNUC__ || _MSC_VER */
59 #define inline
60 #endif				/* !__GNUC__ && !_MSC_VER */
61 
62 #define KEYSZ	32
63 #define IVSZ	8
64 #define BLOCKSZ	64
65 #define RSBUFSZ	(16*BLOCKSZ)
66 
67 #define REKEY_BASE	(1024*1024) /* NB. should be a power of 2 */
68 
69 /* Marked INHERIT_ZERO, so zero'd out in fork children. */
70 static struct _rs {
71 	size_t		rs_have;	/* valid bytes at end of rs_buf */
72 	size_t		rs_count;	/* bytes till reseed */
73 } *rs;
74 
75 /* Maybe be preserved in fork children, if _rs_allocate() decides. */
76 static struct _rsx {
77 	chacha_ctx	rs_chacha;	/* chacha context for random keystream */
78 	u_char		rs_buf[RSBUFSZ];	/* keystream blocks */
79 #ifdef __FreeBSD__
80 	uint32_t	rs_seed_generation;	/* 32-bit userspace RNG version */
81 #endif
82 } *rsx;
83 
84 static inline int _rs_allocate(struct _rs **, struct _rsx **);
85 static inline void _rs_forkdetect(void);
86 #include "arc4random.h"
87 
88 static inline void _rs_rekey(u_char *dat, size_t datlen);
89 
90 static inline void
91 _rs_init(u_char *buf, size_t n)
92 {
93 	if (n < KEYSZ + IVSZ)
94 		return;
95 
96 	if (rs == NULL) {
97 		if (_rs_allocate(&rs, &rsx) == -1)
98 			_exit(1);
99 	}
100 
101 	chacha_keysetup(&rsx->rs_chacha, buf, KEYSZ * 8);
102 	chacha_ivsetup(&rsx->rs_chacha, buf + KEYSZ, NULL);
103 }
104 
105 static void
106 _rs_stir(void)
107 {
108 	u_char rnd[KEYSZ + IVSZ];
109 	uint32_t rekey_fuzz = 0;
110 
111 #if defined(__FreeBSD__)
112 	bool need_init;
113 
114 	/*
115 	 * De-couple allocation (which locates the vdso_fxrngp pointer in
116 	 * auxinfo) from initialization.  This allows us to read the root seed
117 	 * version before we fetch system entropy, maintaining the invariant
118 	 * that the PRF was seeded with entropy from rs_seed_generation or a
119 	 * later generation.  But never seeded from an earlier generation.
120 	 * This invariant prevents us from missing a root reseed event.
121 	 */
122 	need_init = false;
123 	if (rs == NULL) {
124 		if (_rs_allocate(&rs, &rsx) == -1)
125 			abort();
126 		need_init = true;
127 	}
128 	/*
129 	 * Transition period: new userspace on old kernel.  This should become
130 	 * a hard error at some point, if the scheme is adopted.
131 	 */
132 	if (vdso_fxrngp != NULL)
133 		rsx->rs_seed_generation =
134 		    fxrng_load_acq_generation(&vdso_fxrngp->fx_generation32);
135 #endif
136 
137 	if (getentropy(rnd, sizeof rnd) == -1)
138 		_getentropy_fail();
139 
140 #if !defined(__FreeBSD__)
141 	if (!rs)
142 		_rs_init(rnd, sizeof(rnd));
143 #else /* __FreeBSD__ */
144 	assert(rs != NULL);
145 	if (need_init)
146 		_rs_init(rnd, sizeof(rnd));
147 #endif
148 	else
149 		_rs_rekey(rnd, sizeof(rnd));
150 	explicit_bzero(rnd, sizeof(rnd));	/* discard source seed */
151 
152 	/* invalidate rs_buf */
153 	rs->rs_have = 0;
154 	memset(rsx->rs_buf, 0, sizeof(rsx->rs_buf));
155 
156 	/* rekey interval should not be predictable */
157 	chacha_encrypt_bytes(&rsx->rs_chacha, (uint8_t *)&rekey_fuzz,
158 	    (uint8_t *)&rekey_fuzz, sizeof(rekey_fuzz));
159 	rs->rs_count = REKEY_BASE + (rekey_fuzz % REKEY_BASE);
160 }
161 
162 static inline void
163 _rs_stir_if_needed(size_t len)
164 {
165 	_rs_forkdetect();
166 	if (!rs || rs->rs_count <= len)
167 		_rs_stir();
168 	if (rs->rs_count <= len)
169 		rs->rs_count = 0;
170 	else
171 		rs->rs_count -= len;
172 }
173 
174 static inline void
175 _rs_rekey(u_char *dat, size_t datlen)
176 {
177 #ifndef KEYSTREAM_ONLY
178 	memset(rsx->rs_buf, 0, sizeof(rsx->rs_buf));
179 #endif
180 	/* fill rs_buf with the keystream */
181 	chacha_encrypt_bytes(&rsx->rs_chacha, rsx->rs_buf,
182 	    rsx->rs_buf, sizeof(rsx->rs_buf));
183 	/* mix in optional user provided data */
184 	if (dat) {
185 		size_t i, m;
186 
187 		m = minimum(datlen, KEYSZ + IVSZ);
188 		for (i = 0; i < m; i++)
189 			rsx->rs_buf[i] ^= dat[i];
190 	}
191 	/* immediately reinit for backtracking resistance */
192 	_rs_init(rsx->rs_buf, KEYSZ + IVSZ);
193 	memset(rsx->rs_buf, 0, KEYSZ + IVSZ);
194 	rs->rs_have = sizeof(rsx->rs_buf) - KEYSZ - IVSZ;
195 }
196 
197 static inline void
198 _rs_random_buf(void *_buf, size_t n)
199 {
200 	u_char *buf = (u_char *)_buf;
201 	u_char *keystream;
202 	size_t m;
203 
204 	_rs_stir_if_needed(n);
205 	while (n > 0) {
206 		if (rs->rs_have > 0) {
207 			m = minimum(n, rs->rs_have);
208 			keystream = rsx->rs_buf + sizeof(rsx->rs_buf)
209 			    - rs->rs_have;
210 			memcpy(buf, keystream, m);
211 			memset(keystream, 0, m);
212 			buf += m;
213 			n -= m;
214 			rs->rs_have -= m;
215 		}
216 		if (rs->rs_have == 0)
217 			_rs_rekey(NULL, 0);
218 	}
219 }
220 
221 static inline void
222 _rs_random_u32(uint32_t *val)
223 {
224 	u_char *keystream;
225 
226 	_rs_stir_if_needed(sizeof(*val));
227 	if (rs->rs_have < sizeof(*val))
228 		_rs_rekey(NULL, 0);
229 	keystream = rsx->rs_buf + sizeof(rsx->rs_buf) - rs->rs_have;
230 	memcpy(val, keystream, sizeof(*val));
231 	memset(keystream, 0, sizeof(*val));
232 	rs->rs_have -= sizeof(*val);
233 }
234 
235 uint32_t
236 arc4random(void)
237 {
238 	uint32_t val;
239 
240 	_ARC4_LOCK();
241 	_rs_random_u32(&val);
242 	_ARC4_UNLOCK();
243 	return val;
244 }
245 
246 void
247 __ssp_real(arc4random_buf)(void *buf, size_t n)
248 {
249 	_ARC4_LOCK();
250 	_rs_random_buf(buf, n);
251 	_ARC4_UNLOCK();
252 }
253