xref: /openbsd-src/lib/libc/crypt/arc4random.c (revision 953a29a88441fb1db0009d5bc618709ca257334e)
1 /*	$OpenBSD: arc4random.c,v 1.33 2014/06/13 18:58:58 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 
21 /*
22  * ChaCha based random number generator for OpenBSD.
23  */
24 
25 #include <fcntl.h>
26 #include <limits.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30 #include <sys/types.h>
31 #include <sys/param.h>
32 #include <sys/time.h>
33 #include <sys/sysctl.h>
34 #include <sys/mman.h>
35 
36 #include "thread_private.h"
37 
38 #define KEYSTREAM_ONLY
39 #include "chacha_private.h"
40 
41 #ifdef __GNUC__
42 #define inline __inline
43 #else				/* !__GNUC__ */
44 #define inline
45 #endif				/* !__GNUC__ */
46 
47 #define KEYSZ	32
48 #define IVSZ	8
49 #define BLOCKSZ	64
50 #define RSBUFSZ	(16*BLOCKSZ)
51 static int rs_initialized;
52 static pid_t rs_stir_pid;
53 static chacha_ctx *rs;		/* chacha context for random keystream */
54 static u_char *rs_buf;		/* keystream blocks */
55 static size_t rs_have;		/* valid bytes at end of rs_buf */
56 static size_t rs_count;		/* bytes till reseed */
57 
58 static inline void _rs_rekey(u_char *dat, size_t datlen);
59 
60 static inline void
61 _rs_init(u_char *buf, size_t n)
62 {
63 	if (n < KEYSZ + IVSZ)
64 		return;
65 
66 	if (rs == NULL && (rs = mmap(NULL, sizeof(*rs), PROT_READ|PROT_WRITE,
67 	    MAP_ANON, -1, 0)) == MAP_FAILED)
68 		abort();
69 	if (rs_buf == NULL && (rs_buf = mmap(NULL, RSBUFSZ, PROT_READ|PROT_WRITE,
70 	    MAP_ANON, -1, 0)) == MAP_FAILED)
71 		abort();
72 
73 	chacha_keysetup(rs, buf, KEYSZ * 8, 0);
74 	chacha_ivsetup(rs, buf + KEYSZ);
75 }
76 
77 static void
78 _rs_stir(void)
79 {
80 	u_char rnd[KEYSZ + IVSZ];
81 
82 	/* XXX */
83 	(void) getentropy(rnd, sizeof rnd);
84 
85 	if (!rs_initialized) {
86 		rs_initialized = 1;
87 		_rs_init(rnd, sizeof(rnd));
88 	} else
89 		_rs_rekey(rnd, sizeof(rnd));
90 	explicit_bzero(rnd, sizeof(rnd));
91 
92 	/* invalidate rs_buf */
93 	rs_have = 0;
94 	memset(rs_buf, 0, RSBUFSZ);
95 
96 	rs_count = 1600000;
97 }
98 
99 static inline void
100 _rs_stir_if_needed(size_t len)
101 {
102 	pid_t pid = getpid();
103 
104 	if (rs_count <= len || !rs_initialized || rs_stir_pid != pid) {
105 		rs_stir_pid = pid;
106 		_rs_stir();
107 	} else
108 		rs_count -= len;
109 }
110 
111 static inline void
112 _rs_rekey(u_char *dat, size_t datlen)
113 {
114 #ifndef KEYSTREAM_ONLY
115 	memset(rs_buf, 0,RSBUFSZ);
116 #endif
117 	/* fill rs_buf with the keystream */
118 	chacha_encrypt_bytes(rs, rs_buf, rs_buf, RSBUFSZ);
119 	/* mix in optional user provided data */
120 	if (dat) {
121 		size_t i, m;
122 
123 		m = MIN(datlen, KEYSZ + IVSZ);
124 		for (i = 0; i < m; i++)
125 			rs_buf[i] ^= dat[i];
126 	}
127 	/* immediately reinit for backtracking resistance */
128 	_rs_init(rs_buf, KEYSZ + IVSZ);
129 	memset(rs_buf, 0, KEYSZ + IVSZ);
130 	rs_have = RSBUFSZ - KEYSZ - IVSZ;
131 }
132 
133 static inline void
134 _rs_random_buf(void *_buf, size_t n)
135 {
136 	u_char *buf = (u_char *)_buf;
137 	size_t m;
138 
139 	_rs_stir_if_needed(n);
140 	while (n > 0) {
141 		if (rs_have > 0) {
142 			m = MIN(n, rs_have);
143 			memcpy(buf, rs_buf + RSBUFSZ - rs_have, m);
144 			memset(rs_buf + RSBUFSZ - rs_have, 0, m);
145 			buf += m;
146 			n -= m;
147 			rs_have -= m;
148 		}
149 		if (rs_have == 0)
150 			_rs_rekey(NULL, 0);
151 	}
152 }
153 
154 static inline void
155 _rs_random_u32(u_int32_t *val)
156 {
157 	_rs_stir_if_needed(sizeof(*val));
158 	if (rs_have < sizeof(*val))
159 		_rs_rekey(NULL, 0);
160 	memcpy(val, rs_buf + RSBUFSZ - rs_have, sizeof(*val));
161 	memset(rs_buf + RSBUFSZ - rs_have, 0, sizeof(*val));
162 	rs_have -= sizeof(*val);
163 }
164 
165 u_int32_t
166 arc4random(void)
167 {
168 	u_int32_t val;
169 
170 	_ARC4_LOCK();
171 	_rs_random_u32(&val);
172 	_ARC4_UNLOCK();
173 	return val;
174 }
175 
176 void
177 arc4random_buf(void *buf, size_t n)
178 {
179 	_ARC4_LOCK();
180 	_rs_random_buf(buf, n);
181 	_ARC4_UNLOCK();
182 }
183 
184 /*
185  * Calculate a uniformly distributed random number less than upper_bound
186  * avoiding "modulo bias".
187  *
188  * Uniformity is achieved by generating new random numbers until the one
189  * returned is outside the range [0, 2**32 % upper_bound).  This
190  * guarantees the selected random number will be inside
191  * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
192  * after reduction modulo upper_bound.
193  */
194 u_int32_t
195 arc4random_uniform(u_int32_t upper_bound)
196 {
197 	u_int32_t r, min;
198 
199 	if (upper_bound < 2)
200 		return 0;
201 
202 	/* 2**32 % x == (2**32 - x) % x */
203 	min = -upper_bound % upper_bound;
204 
205 	/*
206 	 * This could theoretically loop forever but each retry has
207 	 * p > 0.5 (worst case, usually far better) of selecting a
208 	 * number inside the range we need, so it should rarely need
209 	 * to re-roll.
210 	 */
211 	for (;;) {
212 		r = arc4random();
213 		if (r >= min)
214 			break;
215 	}
216 
217 	return r % upper_bound;
218 }
219