1 /* $OpenBSD: arc4random.c,v 1.54 2015/09/13 08:31:47 guenther 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 <fcntl.h>
27 #include <limits.h>
28 #include <signal.h>
29 #include <stdint.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <unistd.h>
33 #include <sys/types.h>
34 #include <sys/time.h>
35
36 #define KEYSTREAM_ONLY
37 #include "chacha_private.h"
38
39 #define minimum(a, b) ((a) < (b) ? (a) : (b))
40
41 #if defined(__GNUC__) || defined(_MSC_VER)
42 #define inline __inline
43 #else /* __GNUC__ || _MSC_VER */
44 #define inline
45 #endif /* !__GNUC__ && !_MSC_VER */
46
47 #define KEYSZ 32
48 #define IVSZ 8
49 #define BLOCKSZ 64
50 #define RSBUFSZ (16*BLOCKSZ)
51
52 /* Marked MAP_INHERIT_ZERO, so zero'd out in fork children. */
53 static struct _rs {
54 size_t rs_have; /* valid bytes at end of rs_buf */
55 size_t rs_count; /* bytes till reseed */
56 } *rs;
57
58 /* Maybe be preserved in fork children, if _rs_allocate() decides. */
59 static struct _rsx {
60 chacha_ctx rs_chacha; /* chacha context for random keystream */
61 u_char rs_buf[RSBUFSZ]; /* keystream blocks */
62 } *rsx;
63
64
65 /*
66 * Stub functions for portability.
67 */
68
69 #include <sys/mman.h>
70
71 #include <pthread.h>
72 #include <signal.h>
73
74 static pthread_mutex_t arc4random_mtx = PTHREAD_MUTEX_INITIALIZER;
75 #define _ARC4_LOCK() pthread_mutex_lock(&arc4random_mtx)
76 #define _ARC4_UNLOCK() pthread_mutex_unlock(&arc4random_mtx)
77
78 #ifdef __GLIBC__
79 extern void *__dso_handle;
80 extern int __register_atfork(void (*)(void), void(*)(void), void (*)(void), void *);
81 #define _ARC4_ATFORK(f) __register_atfork(NULL, NULL, (f), __dso_handle)
82 #else
83 /*
84 * Unfortunately, pthread_atfork() is broken on FreeBSD (at least 9 and 10) if
85 * a program does not link to -lthr. Callbacks registered with pthread_atfork()
86 * appear to fail silently. So, it is not always possible to detect a PID
87 * wraparound.
88 */
89 #define _ARC4_ATFORK(f) pthread_atfork(NULL, NULL, (f))
90 #endif
91
92 static inline void
_getentropy_fail(void)93 _getentropy_fail(void)
94 {
95 raise(SIGKILL);
96 }
97
98 static volatile sig_atomic_t _rs_forked;
99
100 static inline void
_rs_forkhandler(void)101 _rs_forkhandler(void)
102 {
103 _rs_forked = 1;
104 }
105
106 static inline void
_rs_forkdetect(void)107 _rs_forkdetect(void)
108 {
109 static pid_t _rs_pid = 0;
110 pid_t pid = getpid();
111
112 if (_rs_pid == 0 || _rs_pid != pid || _rs_forked) {
113 _rs_pid = pid;
114 _rs_forked = 0;
115 if (rs)
116 memset(rs, 0, sizeof(*rs));
117 }
118 }
119
120 static inline int
_rs_allocate(struct _rs ** rsp,struct _rsx ** rsxp)121 _rs_allocate(struct _rs **rsp, struct _rsx **rsxp)
122 {
123 if ((*rsp = mmap(NULL, sizeof(**rsp), PROT_READ|PROT_WRITE,
124 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED)
125 return (-1);
126
127 if ((*rsxp = mmap(NULL, sizeof(**rsxp), PROT_READ|PROT_WRITE,
128 MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
129 munmap(*rsp, sizeof(**rsp));
130 return (-1);
131 }
132
133 _ARC4_ATFORK(_rs_forkhandler);
134 return (0);
135 }
136
137 static inline void _rs_rekey(u_char *dat, size_t datlen);
138
139 static inline void
_rs_init(u_char * buf,size_t n)140 _rs_init(u_char *buf, size_t n)
141 {
142 if (n < KEYSZ + IVSZ)
143 return;
144
145 if (rs == NULL) {
146 if (_rs_allocate(&rs, &rsx) == -1)
147 abort();
148 }
149
150 chacha_keysetup(&rsx->rs_chacha, buf, KEYSZ * 8, 0);
151 chacha_ivsetup(&rsx->rs_chacha, buf + KEYSZ);
152 }
153
154 static void
_rs_stir(void)155 _rs_stir(void)
156 {
157 u_char rnd[KEYSZ + IVSZ];
158
159 if (getentropy(rnd, sizeof rnd) == -1)
160 _getentropy_fail();
161
162 if (!rs)
163 _rs_init(rnd, sizeof(rnd));
164 else
165 _rs_rekey(rnd, sizeof(rnd));
166 explicit_bzero(rnd, sizeof(rnd)); /* discard source seed */
167
168 /* invalidate rs_buf */
169 rs->rs_have = 0;
170 memset(rsx->rs_buf, 0, sizeof(rsx->rs_buf));
171
172 rs->rs_count = 1600000;
173 }
174
175 static inline void
_rs_stir_if_needed(size_t len)176 _rs_stir_if_needed(size_t len)
177 {
178 _rs_forkdetect();
179 if (!rs || rs->rs_count <= len)
180 _rs_stir();
181 if (rs->rs_count <= len)
182 rs->rs_count = 0;
183 else
184 rs->rs_count -= len;
185 }
186
187 static inline void
_rs_rekey(u_char * dat,size_t datlen)188 _rs_rekey(u_char *dat, size_t datlen)
189 {
190 #ifndef KEYSTREAM_ONLY
191 memset(rsx->rs_buf, 0, sizeof(rsx->rs_buf));
192 #endif
193 /* fill rs_buf with the keystream */
194 chacha_encrypt_bytes(&rsx->rs_chacha, rsx->rs_buf,
195 rsx->rs_buf, sizeof(rsx->rs_buf));
196 /* mix in optional user provided data */
197 if (dat) {
198 size_t i, m;
199
200 m = minimum(datlen, KEYSZ + IVSZ);
201 for (i = 0; i < m; i++)
202 rsx->rs_buf[i] ^= dat[i];
203 }
204 /* immediately reinit for backtracking resistance */
205 _rs_init(rsx->rs_buf, KEYSZ + IVSZ);
206 memset(rsx->rs_buf, 0, KEYSZ + IVSZ);
207 rs->rs_have = sizeof(rsx->rs_buf) - KEYSZ - IVSZ;
208 }
209
210 static inline void
_rs_random_buf(void * _buf,size_t n)211 _rs_random_buf(void *_buf, size_t n)
212 {
213 u_char *buf = (u_char *)_buf;
214 u_char *keystream;
215 size_t m;
216
217 _rs_stir_if_needed(n);
218 while (n > 0) {
219 if (rs->rs_have > 0) {
220 m = minimum(n, rs->rs_have);
221 keystream = rsx->rs_buf + sizeof(rsx->rs_buf)
222 - rs->rs_have;
223 memcpy(buf, keystream, m);
224 memset(keystream, 0, m);
225 buf += m;
226 n -= m;
227 rs->rs_have -= m;
228 }
229 if (rs->rs_have == 0)
230 _rs_rekey(NULL, 0);
231 }
232 }
233
234 static inline void
_rs_random_u32(uint32_t * val)235 _rs_random_u32(uint32_t *val)
236 {
237 u_char *keystream;
238
239 _rs_stir_if_needed(sizeof(*val));
240 if (rs->rs_have < sizeof(*val))
241 _rs_rekey(NULL, 0);
242 keystream = rsx->rs_buf + sizeof(rsx->rs_buf) - rs->rs_have;
243 memcpy(val, keystream, sizeof(*val));
244 memset(keystream, 0, sizeof(*val));
245 rs->rs_have -= sizeof(*val);
246 }
247
248 uint32_t
arc4random(void)249 arc4random(void)
250 {
251 uint32_t val;
252
253 _ARC4_LOCK();
254 _rs_random_u32(&val);
255 _ARC4_UNLOCK();
256 return val;
257 }
258
259 void
arc4random_buf(void * buf,size_t n)260 arc4random_buf(void *buf, size_t n)
261 {
262 _ARC4_LOCK();
263 _rs_random_buf(buf, n);
264 _ARC4_UNLOCK();
265 }
266