xref: /freebsd/lib/libc/gen/arc4random.c (revision a521f2116473fbd8c09db395518f060a27d02334)
1 /*	$OpenBSD: arc4random.c,v 1.55 2019/03/24 17:56:54 deraadt 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 <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
28 
29 #include "namespace.h"
30 #if defined(__FreeBSD__)
31 #include <assert.h>
32 #endif
33 #include <fcntl.h>
34 #include <limits.h>
35 #include <pthread.h>
36 #include <signal.h>
37 #include <stdint.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <unistd.h>
41 #include <sys/types.h>
42 #include <sys/time.h>
43 
44 #include "libc_private.h"
45 #include "un-namespace.h"
46 
47 #define CHACHA_EMBED
48 #define KEYSTREAM_ONLY
49 #if defined(__FreeBSD__)
50 #define ARC4RANDOM_FXRNG 1
51 #else
52 #define ARC4RANDOM_FXRNG 0
53 #endif
54 #include "chacha.c"
55 
56 #define minimum(a, b) ((a) < (b) ? (a) : (b))
57 
58 #if defined(__GNUC__) || defined(_MSC_VER)
59 #define inline __inline
60 #else				/* __GNUC__ || _MSC_VER */
61 #define inline
62 #endif				/* !__GNUC__ && !_MSC_VER */
63 
64 #define KEYSZ	32
65 #define IVSZ	8
66 #define BLOCKSZ	64
67 #define RSBUFSZ	(16*BLOCKSZ)
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 
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 	rs->rs_count = 1600000;
156 }
157 
158 static inline void
159 _rs_stir_if_needed(size_t len)
160 {
161 	_rs_forkdetect();
162 	if (!rs || rs->rs_count <= len)
163 		_rs_stir();
164 	if (rs->rs_count <= len)
165 		rs->rs_count = 0;
166 	else
167 		rs->rs_count -= len;
168 }
169 
170 static inline void
171 _rs_rekey(u_char *dat, size_t datlen)
172 {
173 #ifndef KEYSTREAM_ONLY
174 	memset(rsx->rs_buf, 0, sizeof(rsx->rs_buf));
175 #endif
176 	/* fill rs_buf with the keystream */
177 	chacha_encrypt_bytes(&rsx->rs_chacha, rsx->rs_buf,
178 	    rsx->rs_buf, sizeof(rsx->rs_buf));
179 	/* mix in optional user provided data */
180 	if (dat) {
181 		size_t i, m;
182 
183 		m = minimum(datlen, KEYSZ + IVSZ);
184 		for (i = 0; i < m; i++)
185 			rsx->rs_buf[i] ^= dat[i];
186 	}
187 	/* immediately reinit for backtracking resistance */
188 	_rs_init(rsx->rs_buf, KEYSZ + IVSZ);
189 	memset(rsx->rs_buf, 0, KEYSZ + IVSZ);
190 	rs->rs_have = sizeof(rsx->rs_buf) - KEYSZ - IVSZ;
191 }
192 
193 static inline void
194 _rs_random_buf(void *_buf, size_t n)
195 {
196 	u_char *buf = (u_char *)_buf;
197 	u_char *keystream;
198 	size_t m;
199 
200 	_rs_stir_if_needed(n);
201 	while (n > 0) {
202 		if (rs->rs_have > 0) {
203 			m = minimum(n, rs->rs_have);
204 			keystream = rsx->rs_buf + sizeof(rsx->rs_buf)
205 			    - rs->rs_have;
206 			memcpy(buf, keystream, m);
207 			memset(keystream, 0, m);
208 			buf += m;
209 			n -= m;
210 			rs->rs_have -= m;
211 		}
212 		if (rs->rs_have == 0)
213 			_rs_rekey(NULL, 0);
214 	}
215 }
216 
217 static inline void
218 _rs_random_u32(uint32_t *val)
219 {
220 	u_char *keystream;
221 
222 	_rs_stir_if_needed(sizeof(*val));
223 	if (rs->rs_have < sizeof(*val))
224 		_rs_rekey(NULL, 0);
225 	keystream = rsx->rs_buf + sizeof(rsx->rs_buf) - rs->rs_have;
226 	memcpy(val, keystream, sizeof(*val));
227 	memset(keystream, 0, sizeof(*val));
228 	rs->rs_have -= sizeof(*val);
229 }
230 
231 uint32_t
232 arc4random(void)
233 {
234 	uint32_t val;
235 
236 	_ARC4_LOCK();
237 	_rs_random_u32(&val);
238 	_ARC4_UNLOCK();
239 	return val;
240 }
241 
242 void
243 arc4random_buf(void *buf, size_t n)
244 {
245 	_ARC4_LOCK();
246 	_rs_random_buf(buf, n);
247 	_ARC4_UNLOCK();
248 }
249