arc4random.c revision 1.14 1 /* $NetBSD: arc4random.c,v 1.14 2012/07/29 14:44:13 dsl Exp $ */
2 /* $OpenBSD: arc4random.c,v 1.6 2001/06/05 05:05:38 pvalchev Exp $ */
3
4 /*
5 * Arc4 random number generator for OpenBSD.
6 * Copyright 1996 David Mazieres <dm (at) lcs.mit.edu>.
7 *
8 * Modification and redistribution in source and binary forms is
9 * permitted provided that due credit is given to the author and the
10 * OpenBSD project by leaving this copyright notice intact.
11 */
12
13 /*
14 * This code is derived from section 17.1 of Applied Cryptography,
15 * second edition, which describes a stream cipher allegedly
16 * compatible with RSA Labs "RC4" cipher (the actual description of
17 * which is a trade secret). The same algorithm is used as a stream
18 * cipher called "arcfour" in Tatu Ylonen's ssh package.
19 *
20 * Here the stream cipher has been modified always to include the time
21 * when initializing the state. That makes it impossible to
22 * regenerate the same random sequence twice, so this can't be used
23 * for encryption, but will generate good random numbers.
24 *
25 * RC4 is a registered trademark of RSA Laboratories.
26 */
27
28 #include <sys/cdefs.h>
29 #if defined(LIBC_SCCS) && !defined(lint)
30 __RCSID("$NetBSD: arc4random.c,v 1.14 2012/07/29 14:44:13 dsl Exp $");
31 #endif /* LIBC_SCCS and not lint */
32
33 #include "namespace.h"
34 #include "reentrant.h"
35 #include <fcntl.h>
36 #include <stdlib.h>
37 #include <unistd.h>
38 #include <sys/types.h>
39 #include <sys/param.h>
40 #include <sys/time.h>
41 #include <sys/sysctl.h>
42
43 #ifdef __weak_alias
44 __weak_alias(arc4random,_arc4random)
45 #endif
46
47 #define RSIZE 256
48 struct arc4_stream {
49 mutex_t mtx;
50 int initialized;
51 uint8_t i;
52 uint8_t j;
53 uint8_t s[RSIZE];
54 };
55
56 /* XXX lint explodes with an internal error if only mtx is initialized! */
57 static struct arc4_stream rs = { .i = 0, .mtx = MUTEX_INITIALIZER };
58
59 static inline void arc4_init(struct arc4_stream *);
60 static inline void arc4_addrandom(struct arc4_stream *, u_char *, int);
61 static void arc4_stir(struct arc4_stream *);
62 static inline uint8_t arc4_getbyte(struct arc4_stream *);
63 static inline uint32_t arc4_getword(struct arc4_stream *);
64
65 static inline void
66 arc4_init(struct arc4_stream *as)
67 {
68 int n;
69 for (n = 0; n < RSIZE; n++)
70 as->s[n] = n;
71 as->i = 0;
72 as->j = 0;
73
74 as->initialized = 1;
75 arc4_stir(as);
76 }
77
78 static inline void
79 arc4_addrandom(struct arc4_stream *as, u_char *dat, int datlen)
80 {
81 uint8_t si;
82 int n;
83
84 as->i--;
85 for (n = 0; n < RSIZE; n++) {
86 as->i = (as->i + 1);
87 si = as->s[as->i];
88 as->j = (as->j + si + dat[n % datlen]);
89 as->s[as->i] = as->s[as->j];
90 as->s[as->j] = si;
91 }
92 as->j = as->i;
93 }
94
95 static void
96 arc4_stir(struct arc4_stream *as)
97 {
98 int rdat[32];
99 int mib[] = { CTL_KERN, KERN_URND };
100 size_t len;
101 size_t i, j;
102
103 /*
104 * This code once opened and read /dev/urandom on each
105 * call. That causes repeated rekeying of the kernel stream
106 * generator, which is very wasteful. Because of application
107 * behavior, caching the fd doesn't really help. So we just
108 * fill up the tank from sysctl, which is a tiny bit slower
109 * for us but much friendlier to other entropy consumers.
110 */
111
112 for (i = 0; i < __arraycount(rdat); i++) {
113 len = sizeof(rdat[i]);
114 if (sysctl(mib, 2, &rdat[i], &len, NULL, 0) == -1)
115 abort();
116 }
117
118 arc4_addrandom(as, (void *) &rdat, (int)sizeof(rdat));
119
120 /*
121 * Throw away the first N words of output, as suggested in the
122 * paper "Weaknesses in the Key Scheduling Algorithm of RC4"
123 * by Fluher, Mantin, and Shamir. (N = 256 in our case.)
124 */
125 for (j = 0; j < RSIZE * 4; j++)
126 arc4_getbyte(as);
127 }
128
129 static inline uint8_t
130 arc4_getbyte(struct arc4_stream *as)
131 {
132 uint8_t si, sj;
133
134 as->i = (as->i + 1);
135 si = as->s[as->i];
136 as->j = (as->j + si);
137 sj = as->s[as->j];
138 as->s[as->i] = sj;
139 as->s[as->j] = si;
140 return (as->s[(si + sj) & 0xff]);
141 }
142
143 static inline uint32_t
144 arc4_getword(struct arc4_stream *as)
145 {
146 uint32_t val;
147 val = arc4_getbyte(as) << 24;
148 val |= arc4_getbyte(as) << 16;
149 val |= arc4_getbyte(as) << 8;
150 val |= arc4_getbyte(as);
151 return val;
152 }
153
154 static inline void
155 _arc4random_stir_unlocked(void)
156 {
157 if (__predict_false(!rs.initialized)) {
158 arc4_init(&rs); /* stirs */
159 } else {
160 arc4_stir(&rs);
161 }
162 }
163
164 void
165 arc4random_stir(void)
166 {
167 #ifdef _REENTRANT
168 if (__isthreaded) {
169 mutex_lock(&rs.mtx);
170 _arc4random_stir_unlocked();
171 mutex_unlock(&rs.mtx);
172 return;
173 }
174 #endif
175 _arc4random_stir_unlocked();
176 }
177
178 static inline void
179 _arc4random_addrandom_unlocked(u_char *dat, int datlen)
180 {
181 if (__predict_false(rs.initialized)) {
182 arc4_init(&rs);
183 }
184 arc4_addrandom(&rs, dat, datlen);
185 }
186
187 void
188 arc4random_addrandom(u_char *dat, int datlen)
189 {
190 #ifdef _REENTRANT
191 if (__isthreaded) {
192 mutex_lock(&rs.mtx);
193 _arc4random_addrandom_unlocked(dat, datlen);
194 mutex_unlock(&rs.mtx);
195 return;
196 }
197 #endif
198 _arc4random_addrandom_unlocked(dat, datlen);
199 }
200
201 static inline uint32_t
202 _arc4random_unlocked(void)
203 {
204 if (__predict_false(!rs.initialized)) {
205 arc4_init(&rs);
206 }
207 return arc4_getword(&rs);
208 }
209
210 uint32_t
211 arc4random(void)
212 {
213 uint32_t v;
214 #ifdef _REENTRANT
215 if (__isthreaded) {
216 mutex_lock(&rs.mtx);
217 v = _arc4random_unlocked();
218 mutex_unlock(&rs.mtx);
219 return v;
220 }
221 #endif
222 v = _arc4random_unlocked();
223 return v;
224 }
225
226 static void
227 _arc4random_buf_unlocked(void *buf, size_t len)
228 {
229 uint8_t *bp = buf;
230 uint8_t *ep = bp + len;
231
232 if (__predict_false(!rs.initialized)) {
233 arc4_init(&rs);
234 }
235
236 bp[0] = arc4_getbyte(&rs) % 3;
237 while (bp[0]--)
238 (void)arc4_getbyte(&rs);
239
240 while (bp < ep)
241 *bp++ = arc4_getbyte(&rs);
242 }
243
244 void
245 arc4random_buf(void *buf, size_t len)
246 {
247 #ifdef _REENTRANT
248 if (__isthreaded) {
249 mutex_lock(&rs.mtx);
250 _arc4random_buf_unlocked(buf, len);
251 mutex_unlock(&rs.mtx);
252 return;
253 } else
254 #endif
255 _arc4random_buf_unlocked(buf, len);
256 }
257
258 /*-
259 * Written by Damien Miller.
260 * With simplifications by Jinmei Tatuya.
261 */
262
263 /*
264 * Calculate a uniformly distributed random number less than
265 * upper_bound avoiding "modulo bias".
266 *
267 * Uniformity is achieved by generating new random numbers
268 * until the one returned is outside the range
269 * [0, 2^32 % upper_bound[. This guarantees the selected
270 * random number will be inside the range
271 * [2^32 % upper_bound, 2^32[ which maps back to
272 * [0, upper_bound[ after reduction modulo upper_bound.
273 */
274 static uint32_t
275 _arc4random_uniform_unlocked(uint32_t upper_bound)
276 {
277 uint32_t r, min;
278
279 if (upper_bound < 2)
280 return 0;
281
282 #if defined(ULONG_MAX) && (ULONG_MAX > 0xFFFFFFFFUL)
283 min = (uint32_t)(0x100000000U % upper_bound);
284 #else
285 /* calculate (2^32 % upper_bound) avoiding 64-bit math */
286 if (upper_bound > 0x80000000U)
287 /* 2^32 - upper_bound (only one "value area") */
288 min = 1 + ~upper_bound;
289 else
290 /* ((2^32 - x) % x) == (2^32 % x) when x <= 2^31 */
291 min = (0xFFFFFFFFU - upper_bound + 1) % upper_bound;
292 #endif
293
294 /*
295 * This could theoretically loop forever but each retry has
296 * p > 0.5 (worst case, usually far better) of selecting a
297 * number inside the range we need, so it should rarely need
298 * to re-roll (at all).
299 */
300 if (__predict_false(!rs.initialized)) {
301 arc4_init(&rs);
302 }
303 if (arc4_getbyte(&rs) & 1)
304 (void)arc4_getbyte(&rs);
305 do
306 r = arc4_getword(&rs);
307 while (r < min);
308
309 return r % upper_bound;
310 }
311
312 uint32_t
313 arc4random_uniform(uint32_t upper_bound)
314 {
315 uint32_t v;
316 #ifdef _REENTRANT
317 if (__isthreaded) {
318 mutex_lock(&rs.mtx);
319 v = _arc4random_uniform_unlocked(upper_bound);
320 mutex_unlock(&rs.mtx);
321 return v;
322 }
323 #endif
324 v = _arc4random_uniform_unlocked(upper_bound);
325 return v;
326 }
327