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 #define _DEFAULT_SOURCE
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <signal.h>
30 #include <stdint.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <unistd.h>
34 #include <sys/types.h>
35 #include <sys/time.h>
36 
37 #define KEYSTREAM_ONLY
38 #include "chacha_private.h"
39 
40 #define minimum(a, b) ((a) < (b) ? (a) : (b))
41 
42 #if defined(__GNUC__) || defined(_MSC_VER)
43 #define inline __inline
44 #else				/* __GNUC__ || _MSC_VER */
45 #define inline
46 #endif				/* !__GNUC__ && !_MSC_VER */
47 
48 #define KEYSZ	32
49 #define IVSZ	8
50 #define BLOCKSZ	64
51 #define RSBUFSZ	(16*BLOCKSZ)
52 
53 #if SIZE_MAX <= 65535
54 #define REKEY_BASE	((size_t)  32 * 1024) /* NB. should be a power of 2 */
55 #elif SIZE_MAX <= 1048575
56 #define REKEY_BASE	((size_t) 256 * 1024) /* NB. should be a power of 2 */
57 #else
58 #define REKEY_BASE	((size_t)1024 * 1024) /* NB. should be a power of 2 */
59 #endif
60 
61 /* Marked MAP_INHERIT_ZERO, so zero'd out in fork children. */
62 static struct _rs {
63 	size_t		rs_have;	/* valid bytes at end of rs_buf */
64 	size_t		rs_count;	/* bytes till reseed */
65 } *rs;
66 
67 /* Maybe be preserved in fork children, if _rs_allocate() decides. */
68 static struct _rsx {
69 	chacha_ctx	rs_chacha;	/* chacha context for random keystream */
70 	unsigned char	rs_buf[RSBUFSZ];	/* keystream blocks */
71 } *rsx;
72 
73 static inline int _rs_allocate(struct _rs **, struct _rsx **);
74 static inline void _rs_forkdetect(void);
75 #include "arc4random.h"
76 
77 static inline void _rs_rekey(unsigned char *dat, size_t datlen);
78 
79 static inline void
_rs_init(unsigned char * buf,size_t n)80 _rs_init(unsigned char *buf, size_t n)
81 {
82 	if (n < KEYSZ + IVSZ)
83 		return;
84 
85 	if (rs == NULL) {
86 		if (_rs_allocate(&rs, &rsx) == -1)
87 			abort();
88 	}
89 
90 	chacha_keysetup(&rsx->rs_chacha, buf, KEYSZ * 8);
91 	chacha_ivsetup(&rsx->rs_chacha, buf + KEYSZ);
92 }
93 
94 static void
_rs_stir(void)95 _rs_stir(void)
96 {
97 	uint8_t rnd[KEYSZ + IVSZ];
98 	uint32_t rekey_fuzz = 0;
99 
100 	memset(rnd, 0, (KEYSZ + IVSZ) * sizeof(u_char));
101 
102 	if (getentropy(rnd, sizeof rnd) == -1)
103 		_getentropy_fail();
104 
105 	if (!rs)
106 		_rs_init(rnd, sizeof(rnd));
107 	else
108 		_rs_rekey(rnd, sizeof(rnd));
109 	explicit_bzero(rnd, sizeof(rnd));	/* discard source seed */
110 
111 	/* invalidate rs_buf */
112 	rs->rs_have = 0;
113 	memset(rsx->rs_buf, 0, sizeof(rsx->rs_buf));
114 
115 	/* rekey interval should not be predictable */
116 	chacha_encrypt_bytes(&rsx->rs_chacha, (uint8_t *)&rekey_fuzz,
117 	    (uint8_t *)&rekey_fuzz, sizeof(rekey_fuzz));
118 	rs->rs_count = REKEY_BASE + (rekey_fuzz % REKEY_BASE);
119 }
120 
121 static inline void
_rs_stir_if_needed(size_t len)122 _rs_stir_if_needed(size_t len)
123 {
124 	_rs_forkdetect();
125 	if (!rs || rs->rs_count <= len)
126 		_rs_stir();
127 	if (rs->rs_count <= len)
128 		rs->rs_count = 0;
129 	else
130 		rs->rs_count -= len;
131 }
132 
133 static inline void
_rs_rekey(unsigned char * dat,size_t datlen)134 _rs_rekey(unsigned char *dat, size_t datlen)
135 {
136 #ifndef KEYSTREAM_ONLY
137 	memset(rsx->rs_buf, 0, sizeof(rsx->rs_buf));
138 #endif
139 	/* fill rs_buf with the keystream */
140 	chacha_encrypt_bytes(&rsx->rs_chacha, rsx->rs_buf,
141 	    rsx->rs_buf, sizeof(rsx->rs_buf));
142 	/* mix in optional user provided data */
143 	if (dat) {
144 		size_t i, m;
145 
146 		m = minimum(datlen, KEYSZ + IVSZ);
147 		for (i = 0; i < m; i++)
148 			rsx->rs_buf[i] ^= dat[i];
149 	}
150 	/* immediately reinit for backtracking resistance */
151 	_rs_init(rsx->rs_buf, KEYSZ + IVSZ);
152 	memset(rsx->rs_buf, 0, KEYSZ + IVSZ);
153 	rs->rs_have = sizeof(rsx->rs_buf) - KEYSZ - IVSZ;
154 }
155 
156 static inline void
_rs_random_buf(void * _buf,size_t n)157 _rs_random_buf(void *_buf, size_t n)
158 {
159 	unsigned char *buf = (unsigned char *)_buf;
160 	unsigned char *keystream;
161 	size_t m;
162 
163 	_rs_stir_if_needed(n);
164 	while (n > 0) {
165 		if (rs->rs_have > 0) {
166 			m = minimum(n, rs->rs_have);
167 			keystream = rsx->rs_buf + sizeof(rsx->rs_buf)
168 			    - rs->rs_have;
169 			memcpy(buf, keystream, m);
170 			memset(keystream, 0, m);
171 			buf += m;
172 			n -= m;
173 			rs->rs_have -= m;
174 		}
175 		if (rs->rs_have == 0)
176 			_rs_rekey(NULL, 0);
177 	}
178 }
179 
180 static inline void
_rs_random_u32(uint32_t * val)181 _rs_random_u32(uint32_t *val)
182 {
183 	unsigned char *keystream;
184 
185 	_rs_stir_if_needed(sizeof(*val));
186 	if (rs->rs_have < sizeof(*val))
187 		_rs_rekey(NULL, 0);
188 	keystream = rsx->rs_buf + sizeof(rsx->rs_buf) - rs->rs_have;
189 	memcpy(val, keystream, sizeof(*val));
190 	memset(keystream, 0, sizeof(*val));
191 	rs->rs_have -= sizeof(*val);
192 }
193 
194 uint32_t
arc4random(void)195 arc4random(void)
196 {
197 	uint32_t val;
198 
199 #ifndef __SINGLE_THREAD__
200 	_ARC4_LOCK();
201 #endif
202 	_rs_random_u32(&val);
203 #ifndef __SINGLE_THREAD__
204 	_ARC4_UNLOCK();
205 #endif
206 	return val;
207 }
208 
209 void
arc4random_buf(void * buf,size_t n)210 arc4random_buf(void *buf, size_t n)
211 {
212 #ifndef __SINGLE_THREAD__
213 	_ARC4_LOCK();
214 #endif
215 	_rs_random_buf(buf, n);
216 #ifndef __SINGLE_THREAD__
217 	_ARC4_UNLOCK();
218 #endif
219 }
220