xref: /freebsd/contrib/unbound/compat/arc4random.c (revision 1f4bcc459a76b7aa664f3fd557684cd0ba6da352)
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 
52 #define KEYSZ	32
53 #define IVSZ	8
54 #define BLOCKSZ	64
55 #define RSBUFSZ	(16*BLOCKSZ)
56 
57 /* Marked MAP_INHERIT_ZERO, so zero'd out in fork children. */
58 static struct {
59 	size_t		rs_have;	/* valid bytes at end of rs_buf */
60 	size_t		rs_count;	/* bytes till reseed */
61 } *rs;
62 
63 /* Preserved in fork children. */
64 static struct {
65 	chacha_ctx	rs_chacha;	/* chacha context for random keystream */
66 	u_char		rs_buf[RSBUFSZ];	/* keystream blocks */
67 } *rsx;
68 
69 static inline void _rs_rekey(u_char *dat, size_t datlen);
70 
71 static inline void
72 _rs_init(u_char *buf, size_t n)
73 {
74 	if (n < KEYSZ + IVSZ)
75 		return;
76 
77 	if (rs == NULL) {
78 #ifndef UB_ON_WINDOWS
79 		if ((rs = mmap(NULL, sizeof(*rs), PROT_READ|PROT_WRITE,
80 		    MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED)
81 			abort();
82 #ifdef MAP_INHERIT_ZERO
83 		if (minherit(rs, sizeof(*rs), MAP_INHERIT_ZERO) == -1)
84 			abort();
85 #endif
86 #else /* WINDOWS */
87 		rs = malloc(sizeof(*rs));
88 		if(!rs)
89 			abort();
90 #endif
91 	}
92 	if (rsx == NULL) {
93 #ifndef UB_ON_WINDOWS
94 		if ((rsx = mmap(NULL, sizeof(*rsx), PROT_READ|PROT_WRITE,
95 		    MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED)
96 			abort();
97 #else /* WINDOWS */
98 		rsx = malloc(sizeof(*rsx));
99 		if(!rsx)
100 			abort();
101 #endif
102 	}
103 
104 	chacha_keysetup(&rsx->rs_chacha, buf, KEYSZ * 8, 0);
105 	chacha_ivsetup(&rsx->rs_chacha, buf + KEYSZ);
106 }
107 
108 static void
109 _rs_stir(void)
110 {
111 	u_char rnd[KEYSZ + IVSZ];
112 
113 	if (getentropy(rnd, sizeof rnd) == -1) {
114 #ifdef SIGKILL
115 		raise(SIGKILL);
116 #else
117 		exit(9); /* windows */
118 #endif
119 	}
120 
121 	if (!rs)
122 		_rs_init(rnd, sizeof(rnd));
123 	else
124 		_rs_rekey(rnd, sizeof(rnd));
125 	explicit_bzero(rnd, sizeof(rnd));	/* discard source seed */
126 
127 	/* invalidate rs_buf */
128 	rs->rs_have = 0;
129 	memset(rsx->rs_buf, 0, sizeof(rsx->rs_buf));
130 
131 	rs->rs_count = 1600000;
132 }
133 
134 static inline void
135 _rs_stir_if_needed(size_t len)
136 {
137 #ifndef MAP_INHERIT_ZERO
138 	static pid_t _rs_pid = 0;
139 	pid_t pid = getpid();
140 
141 	/* If a system lacks MAP_INHERIT_ZERO, resort to getpid() */
142 	if (_rs_pid == 0 || _rs_pid != pid) {
143 		_rs_pid = pid;
144 		if (rs)
145 			rs->rs_count = 0;
146 	}
147 #endif
148 	if (!rs || rs->rs_count <= len)
149 		_rs_stir();
150 	if (rs->rs_count <= len)
151 		rs->rs_count = 0;
152 	else
153 		rs->rs_count -= len;
154 }
155 
156 static inline void
157 _rs_rekey(u_char *dat, size_t datlen)
158 {
159 #ifndef KEYSTREAM_ONLY
160 	memset(rsx->rs_buf, 0, sizeof(rsx->rs_buf));
161 #endif
162 	/* fill rs_buf with the keystream */
163 	chacha_encrypt_bytes(&rsx->rs_chacha, rsx->rs_buf,
164 	    rsx->rs_buf, sizeof(rsx->rs_buf));
165 	/* mix in optional user provided data */
166 	if (dat) {
167 		size_t i, m;
168 
169 		m = arc4_min(datlen, KEYSZ + IVSZ);
170 		for (i = 0; i < m; i++)
171 			rsx->rs_buf[i] ^= dat[i];
172 	}
173 	/* immediately reinit for backtracking resistance */
174 	_rs_init(rsx->rs_buf, KEYSZ + IVSZ);
175 	memset(rsx->rs_buf, 0, KEYSZ + IVSZ);
176 	rs->rs_have = sizeof(rsx->rs_buf) - KEYSZ - IVSZ;
177 }
178 
179 static inline void
180 _rs_random_buf(void *_buf, size_t n)
181 {
182 	u_char *buf = (u_char *)_buf;
183 	u_char *keystream;
184 	size_t m;
185 
186 	_rs_stir_if_needed(n);
187 	while (n > 0) {
188 		if (rs->rs_have > 0) {
189 			m = arc4_min(n, rs->rs_have);
190 			keystream = rsx->rs_buf + sizeof(rsx->rs_buf)
191 			    - rs->rs_have;
192 			memcpy(buf, keystream, m);
193 			memset(keystream, 0, m);
194 			buf += m;
195 			n -= m;
196 			rs->rs_have -= m;
197 		}
198 		if (rs->rs_have == 0)
199 			_rs_rekey(NULL, 0);
200 	}
201 }
202 
203 static inline void
204 _rs_random_u32(uint32_t *val)
205 {
206 	u_char *keystream;
207 	_rs_stir_if_needed(sizeof(*val));
208 	if (rs->rs_have < sizeof(*val))
209 		_rs_rekey(NULL, 0);
210 	keystream = rsx->rs_buf + sizeof(rsx->rs_buf) - rs->rs_have;
211 	memcpy(val, keystream, sizeof(*val));
212 	memset(keystream, 0, sizeof(*val));
213 	rs->rs_have -= sizeof(*val);
214 }
215 
216 uint32_t
217 arc4random(void)
218 {
219 	uint32_t val;
220 
221 	_ARC4_LOCK();
222 	_rs_random_u32(&val);
223 	_ARC4_UNLOCK();
224 	return val;
225 }
226 
227 void
228 arc4random_buf(void *buf, size_t n)
229 {
230 	_ARC4_LOCK();
231 	_rs_random_buf(buf, n);
232 	_ARC4_UNLOCK();
233 }
234