2 * Copyright (c) 1996, David Mazieres <dm@uun.org>
3 * Copyright (c) 2008, Damien Miller <djm@openbsd.org>
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 * Arc4 random number generator for OpenBSD.
21 * This code is derived from section 17.1 of Applied Cryptography,
22 * second edition, which describes a stream cipher allegedly
23 * compatible with RSA Labs "RC4" cipher (the actual description of
24 * which is a trade secret). The same algorithm is used as a stream
25 * cipher called "arcfour" in Tatu Ylonen's ssh package.
27 * RC4 is a registered trademark of RSA Laboratories.
29 * $OpenBSD: arc4random.c,v 1.24 2013/06/11 16:59:50 deraadt Exp $
30 * $FreeBSD: src/lib/libc/gen/arc4random.c,v 1.25 2008/09/09 09:46:36 ache Exp $
33 #include "namespace.h"
34 #include <sys/types.h>
36 #include <sys/sysctl.h>
42 #include "libc_private.h"
43 #include "un-namespace.h"
48 #define RANDOMDEV "/dev/random"
50 #define _ARC4_LOCK() \
53 _pthread_mutex_lock(&arc4random_mtx); \
56 #define _ARC4_UNLOCK() \
59 _pthread_mutex_unlock(&arc4random_mtx); \
65 u_int8_t s[KEYSIZE * 2];
68 static pthread_mutex_t arc4random_mtx = PTHREAD_MUTEX_INITIALIZER;
70 static struct arc4_stream rs;
71 static pid_t arc4_stir_pid;
72 static int rs_initialized;
74 static int arc4_count;
76 static u_int8_t arc4_getbyte(void);
77 static void arc4_stir(void);
84 for (n = 0; n < KEYSIZE * 2; n++)
91 arc4_addrandom(u_char *dat, size_t datlen)
97 for (n = 0; n < KEYSIZE * 2; n++) {
100 rs.j = (rs.j + si + dat[n % datlen]);
101 rs.s[rs.i] = rs.s[rs.j];
115 u_int8_t rnd[KEYSIZE*2];
120 * NOTE: Don't assume that the garbage on the stack is actually
124 fd = _open(RANDOMDEV, O_RDONLY | O_CLOEXEC, 0);
126 n = _read(fd, rnd, sizeof(rnd));
133 * Align for added entropy, sysctl back-off for chroots that might
134 * not have access to /dev/random.
136 n = n & ~15; /* align for added entropy */
137 if (n < sizeof(rnd)) {
138 size_t r = sizeof(rnd) - n;
139 if (sysctlbyname("kern.random", rnd + n, &r, NULL, 0) == 0)
144 * Pray if this code ever gets triggered.
147 if (n <= sizeof(rnd) - sizeof(struct pray)) {
148 struct pray *pray = (void *)(rnd + n);
149 gettimeofday(&pray->tv, NULL);
150 pray->pid = getpid();
151 n += sizeof(struct pray);
153 arc4_addrandom((u_char *)rnd, n);
156 * Discard early keystream, as per recommendations in:
157 * "(Not So) Random Shuffles of RC4" by Ilya Mironov.
159 for (n = 0; n < 3072; n++)
163 * Theoretically we can set arc4_count to 1600000. Realistically,
164 * it makes no sense to use a number that high. Use something
182 return (rs.s[(si + sj) & 0xff]);
190 val = arc4_getbyte() << 24;
191 val |= arc4_getbyte() << 16;
192 val |= arc4_getbyte() << 8;
193 val |= arc4_getbyte();
199 arc4_check_init(void)
201 if (!rs_initialized) {
208 arc4_check_stir(void)
210 pid_t pid = getpid(); /* optimized by upmap */
212 if (!rs_stired || arc4_count <= 0 || arc4_stir_pid != pid) {
220 arc4random_stir(void)
230 arc4random_addrandom(uint8_t *dat, size_t datlen)
235 arc4_addrandom(dat, datlen);
247 rnd = arc4_getword();
255 arc4random_buf(void *_buf, size_t n)
257 u_char *buf = (u_char *)_buf;
263 buf[n] = arc4_getbyte();
270 * Calculate a uniformly distributed random number less than upper_bound
271 * avoiding "modulo bias".
273 * Uniformity is achieved by generating new random numbers until the one
274 * returned is outside the range [0, 2**32 % upper_bound). This
275 * guarantees the selected random number will be inside
276 * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
277 * after reduction modulo upper_bound.
280 arc4random_uniform(u_int32_t upper_bound)
287 /* 2**32 % x == (2**32 - x) % x */
288 min = -upper_bound % upper_bound;
290 * This could theoretically loop forever but each retry has
291 * p > 0.5 (worst case, usually far better) of selecting a
292 * number inside the range we need, so it should rarely need
301 return (r % upper_bound);
305 /*-------- Test code for i386 --------*/
307 #include <machine/pctr.h>
309 main(int argc, char **argv)
311 const int iter = 1000000;
316 for (i = 0; i < iter; i++)
321 printf("%qd cycles\n", v);