xref: /freebsd/contrib/unbound/compat/arc4random.c (revision 8cee2ebac54a1c4a6b9cc1ee877ead57e529b7c2)
1 /*      $OpenBSD: arc4random.c,v 1.41 2014/07/12 13:24: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  *
8  * Permission to use, copy, modify, and distribute this software for any
9  * purpose with or without fee is hereby granted, provided that the above
10  * copyright notice and this permission notice appear in all copies.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19  */
20 #include "config.h"
21 
22 /*
23  * ChaCha based random number generator for OpenBSD.
24  */
25 
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <signal.h>
29 #ifdef HAVE_STDINT_H
30 #include <stdint.h>
31 #endif
32 #include <stdlib.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <sys/types.h>
36 #include <sys/param.h>
37 #include <sys/time.h>
38 #ifndef UB_ON_WINDOWS
39 #include <sys/mman.h>
40 #endif
41 
42 #define KEYSTREAM_ONLY
43 #include "chacha_private.h"
44 
45 #define arc4_min(a, b) ((a) < (b) ? (a) : (b))
46 #ifdef __GNUC__
47 #define inline __inline
48 #else				/* !__GNUC__ */
49 #define inline
50 #endif				/* !__GNUC__ */
51 #ifndef MAP_ANON
52 #define MAP_ANON MAP_ANONYMOUS
53 #endif
54 
55 #define KEYSZ	32
56 #define IVSZ	8
57 #define BLOCKSZ	64
58 #define RSBUFSZ	(16*BLOCKSZ)
59 
60 /* Marked MAP_INHERIT_ZERO, so zero'd out in fork children. */
61 static struct {
62 	size_t		rs_have;	/* valid bytes at end of rs_buf */
63 	size_t		rs_count;	/* bytes till reseed */
64 } *rs;
65 
66 /* Preserved in fork children. */
67 static struct {
68 	chacha_ctx	rs_chacha;	/* chacha context for random keystream */
69 	u_char		rs_buf[RSBUFSZ];	/* keystream blocks */
70 } *rsx;
71 
72 static inline void _rs_rekey(u_char *dat, size_t datlen);
73 
74 /*
75  * Basic sanity checking; wish we could do better.
76  */
77 static int
78 fallback_gotdata(char *buf, size_t len)
79 {
80 	char	any_set = 0;
81 	size_t	i;
82 
83 	for (i = 0; i < len; ++i)
84 		any_set |= buf[i];
85 	if (any_set == 0)
86 		return -1;
87 	return 0;
88 }
89 
90 /* fallback for getentropy in case libc returns failure */
91 static int
92 fallback_getentropy_urandom(void *buf, size_t len)
93 {
94 	size_t i;
95 	int fd, flags;
96 	int save_errno = errno;
97 
98 start:
99 
100 	flags = O_RDONLY;
101 #ifdef O_NOFOLLOW
102 	flags |= O_NOFOLLOW;
103 #endif
104 #ifdef O_CLOEXEC
105 	flags |= O_CLOEXEC;
106 #endif
107 	fd = open("/dev/urandom", flags, 0);
108 	if (fd == -1) {
109 		if (errno == EINTR)
110 			goto start;
111 		goto nodevrandom;
112 	}
113 #ifndef O_CLOEXEC
114 #  ifdef HAVE_FCNTL
115 	fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
116 #  endif
117 #endif
118 	for (i = 0; i < len; ) {
119 		size_t wanted = len - i;
120 		ssize_t ret = read(fd, (char*)buf + i, wanted);
121 
122 		if (ret == -1) {
123 			if (errno == EAGAIN || errno == EINTR)
124 				continue;
125 			close(fd);
126 			goto nodevrandom;
127 		}
128 		i += ret;
129 	}
130 	close(fd);
131 	if (fallback_gotdata(buf, len) == 0) {
132 		errno = save_errno;
133 		return 0;		/* satisfied */
134 	}
135 nodevrandom:
136 	errno = EIO;
137 	return -1;
138 }
139 
140 static inline void
141 _rs_init(u_char *buf, size_t n)
142 {
143 	assert(buf);
144 	if (n < KEYSZ + IVSZ)
145 		return;
146 
147 	if (rs == NULL) {
148 #ifndef UB_ON_WINDOWS
149 		if ((rs = mmap(NULL, sizeof(*rs), PROT_READ|PROT_WRITE,
150 		    MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED)
151 			abort();
152 #ifdef MAP_INHERIT_ZERO
153 		if (minherit(rs, sizeof(*rs), MAP_INHERIT_ZERO) == -1)
154 			abort();
155 #endif
156 #else /* WINDOWS */
157 		rs = malloc(sizeof(*rs));
158 		if(!rs)
159 			abort();
160 #endif
161 	}
162 	if (rsx == NULL) {
163 #ifndef UB_ON_WINDOWS
164 		if ((rsx = mmap(NULL, sizeof(*rsx), PROT_READ|PROT_WRITE,
165 		    MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED)
166 			abort();
167 #else /* WINDOWS */
168 		rsx = malloc(sizeof(*rsx));
169 		if(!rsx)
170 			abort();
171 #endif
172 	}
173 
174 	chacha_keysetup(&rsx->rs_chacha, buf, KEYSZ * 8, 0);
175 	chacha_ivsetup(&rsx->rs_chacha, buf + KEYSZ);
176 }
177 
178 static void
179 _rs_stir(void)
180 {
181 	u_char rnd[KEYSZ + IVSZ];
182 
183 	if (getentropy(rnd, sizeof rnd) == -1) {
184 		if(errno != ENOSYS ||
185 			fallback_getentropy_urandom(rnd, sizeof rnd) == -1) {
186 #ifdef SIGKILL
187 			raise(SIGKILL);
188 #else
189 			exit(9); /* windows */
190 #endif
191 		}
192 	}
193 
194 	if (!rs)
195 		_rs_init(rnd, sizeof(rnd));
196 	else
197 		_rs_rekey(rnd, sizeof(rnd));
198 	explicit_bzero(rnd, sizeof(rnd));	/* discard source seed */
199 
200 	/* invalidate rs_buf */
201 	rs->rs_have = 0;
202 	memset(rsx->rs_buf, 0, sizeof(rsx->rs_buf));
203 
204 	rs->rs_count = 1600000;
205 }
206 
207 static inline void
208 _rs_stir_if_needed(size_t len)
209 {
210 #ifndef MAP_INHERIT_ZERO
211 	static pid_t _rs_pid = 0;
212 	pid_t pid = getpid();
213 
214 	/* If a system lacks MAP_INHERIT_ZERO, resort to getpid() */
215 	if (_rs_pid == 0 || _rs_pid != pid) {
216 		_rs_pid = pid;
217 		if (rs)
218 			rs->rs_count = 0;
219 	}
220 #endif
221 	if (!rs || rs->rs_count <= len)
222 		_rs_stir();
223 	if (rs->rs_count <= len)
224 		rs->rs_count = 0;
225 	else
226 		rs->rs_count -= len;
227 }
228 
229 static inline void
230 _rs_rekey(u_char *dat, size_t datlen)
231 {
232 #ifndef KEYSTREAM_ONLY
233 	memset(rsx->rs_buf, 0, sizeof(rsx->rs_buf));
234 #endif
235 	/* fill rs_buf with the keystream */
236 	chacha_encrypt_bytes(&rsx->rs_chacha, rsx->rs_buf,
237 	    rsx->rs_buf, sizeof(rsx->rs_buf));
238 	/* mix in optional user provided data */
239 	if (dat) {
240 		size_t i, m;
241 
242 		m = arc4_min(datlen, KEYSZ + IVSZ);
243 		for (i = 0; i < m; i++)
244 			rsx->rs_buf[i] ^= dat[i];
245 	}
246 	/* immediately reinit for backtracking resistance */
247 	_rs_init(rsx->rs_buf, KEYSZ + IVSZ);
248 	memset(rsx->rs_buf, 0, KEYSZ + IVSZ);
249 	rs->rs_have = sizeof(rsx->rs_buf) - KEYSZ - IVSZ;
250 }
251 
252 static inline void
253 _rs_random_buf(void *_buf, size_t n)
254 {
255 	u_char *buf = (u_char *)_buf;
256 	u_char *keystream;
257 	size_t m;
258 
259 	_rs_stir_if_needed(n);
260 	while (n > 0) {
261 		if (rs->rs_have > 0) {
262 			m = arc4_min(n, rs->rs_have);
263 			keystream = rsx->rs_buf + sizeof(rsx->rs_buf)
264 			    - rs->rs_have;
265 			memcpy(buf, keystream, m);
266 			memset(keystream, 0, m);
267 			buf += m;
268 			n -= m;
269 			rs->rs_have -= m;
270 		}
271 		if (rs->rs_have == 0)
272 			_rs_rekey(NULL, 0);
273 	}
274 }
275 
276 static inline void
277 _rs_random_u32(uint32_t *val)
278 {
279 	u_char *keystream;
280 	_rs_stir_if_needed(sizeof(*val));
281 	if (rs->rs_have < sizeof(*val))
282 		_rs_rekey(NULL, 0);
283 	keystream = rsx->rs_buf + sizeof(rsx->rs_buf) - rs->rs_have;
284 	memcpy(val, keystream, sizeof(*val));
285 	memset(keystream, 0, sizeof(*val));
286 	rs->rs_have -= sizeof(*val);
287 }
288 
289 uint32_t
290 arc4random(void)
291 {
292 	uint32_t val;
293 
294 	_ARC4_LOCK();
295 	_rs_random_u32(&val);
296 	_ARC4_UNLOCK();
297 	return val;
298 }
299 
300 void
301 arc4random_buf(void *buf, size_t n)
302 {
303 	_ARC4_LOCK();
304 	_rs_random_buf(buf, n);
305 	_ARC4_UNLOCK();
306 }
307