1 /* Portable arc4random.c based on arc4random.c from OpenBSD.
2 * Portable version by Chris Davis, adapted for Libevent by Nick Mathewson
3 * Copyright (c) 2010 Chris Davis, Niels Provos, and Nick Mathewson
4 * Copyright (c) 2010-2012 Niels Provos and Nick Mathewson
6 * Note that in Libevent, this file isn't compiled directly. Instead,
7 * it's included from evutil_rand.c
11 * Copyright (c) 1996, David Mazieres <dm@uun.org>
12 * Copyright (c) 2008, Damien Miller <djm@openbsd.org>
14 * Permission to use, copy, modify, and distribute this software for any
15 * purpose with or without fee is hereby granted, provided that the above
16 * copyright notice and this permission notice appear in all copies.
18 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
19 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
20 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
21 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
22 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
23 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
24 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
28 * Arc4 random number generator for OpenBSD.
30 * This code is derived from section 17.1 of Applied Cryptography,
31 * second edition, which describes a stream cipher allegedly
32 * compatible with RSA Labs "RC4" cipher (the actual description of
33 * which is a trade secret). The same algorithm is used as a stream
34 * cipher called "arcfour" in Tatu Ylonen's ssh package.
36 * Here the stream cipher has been modified always to include the time
37 * when initializing the state. That makes it impossible to
38 * regenerate the same random sequence twice, so this can't be used
39 * for encryption, but will generate good random numbers.
41 * RC4 is a registered trademark of RSA Laboratories.
44 #ifndef ARC4RANDOM_EXPORT
45 #define ARC4RANDOM_EXPORT
48 #ifndef ARC4RANDOM_UINT32
49 #define ARC4RANDOM_UINT32 uint32_t
52 #ifndef ARC4RANDOM_NO_INCLUDES
53 #include "evconfig-private.h"
61 #include <sys/param.h>
63 #ifdef EVENT__HAVE_SYS_SYSCTL_H
64 #include <sys/sysctl.h>
72 /* Add platform entropy 32 bytes (256 bits) at a time. */
73 #define ADD_ENTROPY 32
75 /* Re-seed from the platform RNG after generating this many bytes. */
76 #define BYTES_BEFORE_RESEED 1600000
85 #define getpid _getpid
89 static int rs_initialized;
90 static struct arc4_stream rs;
91 static pid_t arc4_stir_pid;
92 static int arc4_count;
94 static inline unsigned char arc4_getbyte(void);
101 for (n = 0; n < 256; n++)
108 arc4_addrandom(const unsigned char *dat, int datlen)
114 for (n = 0; n < 256; n++) {
117 rs.j = (rs.j + si + dat[n % datlen]);
118 rs.s[rs.i] = rs.s[rs.j];
126 read_all(int fd, unsigned char *buf, size_t count)
131 while (numread < count) {
132 result = read(fd, buf+numread, count-numread);
135 else if (result == 0)
140 return (ssize_t)numread;
145 #define TRY_SEED_WIN32
147 arc4_seed_win32(void)
149 /* This is adapted from Tor's crypto_seed_rng() */
150 static int provider_set = 0;
151 static HCRYPTPROV provider;
152 unsigned char buf[ADD_ENTROPY];
155 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
156 CRYPT_VERIFYCONTEXT)) {
157 if (GetLastError() != (DWORD)NTE_BAD_KEYSET)
162 if (!CryptGenRandom(provider, sizeof(buf), buf))
164 arc4_addrandom(buf, sizeof(buf));
165 evutil_memclear_(buf, sizeof(buf));
170 #if defined(EVENT__HAVE_SYS_SYSCTL_H) && defined(EVENT__HAVE_SYSCTL)
171 #if EVENT__HAVE_DECL_CTL_KERN && EVENT__HAVE_DECL_KERN_RANDOM && EVENT__HAVE_DECL_RANDOM_UUID
172 #define TRY_SEED_SYSCTL_LINUX
174 arc4_seed_sysctl_linux(void)
176 /* Based on code by William Ahern, this function tries to use the
177 * RANDOM_UUID sysctl to get entropy from the kernel. This can work
178 * even if /dev/urandom is inaccessible for some reason (e.g., we're
179 * running in a chroot). */
180 int mib[] = { CTL_KERN, KERN_RANDOM, RANDOM_UUID };
181 unsigned char buf[ADD_ENTROPY];
186 memset(buf, 0, sizeof(buf));
188 for (len = 0; len < sizeof(buf); len += n) {
189 n = sizeof(buf) - len;
191 if (0 != sysctl(mib, 3, &buf[len], &n, NULL, 0))
194 /* make sure that the buffer actually got set. */
195 for (i=0,any_set=0; i<sizeof(buf); ++i) {
201 arc4_addrandom(buf, sizeof(buf));
202 evutil_memclear_(buf, sizeof(buf));
207 #if EVENT__HAVE_DECL_CTL_KERN && EVENT__HAVE_DECL_KERN_ARND
208 #define TRY_SEED_SYSCTL_BSD
210 arc4_seed_sysctl_bsd(void)
212 /* Based on code from William Ahern and from OpenBSD, this function
213 * tries to use the KERN_ARND syscall to get entropy from the kernel.
214 * This can work even if /dev/urandom is inaccessible for some reason
215 * (e.g., we're running in a chroot). */
216 int mib[] = { CTL_KERN, KERN_ARND };
217 unsigned char buf[ADD_ENTROPY];
221 memset(buf, 0, sizeof(buf));
224 if (sysctl(mib, 2, buf, &len, NULL, 0) == -1) {
225 for (len = 0; len < sizeof(buf); len += sizeof(unsigned)) {
226 n = sizeof(unsigned);
227 if (n + len > sizeof(buf))
228 n = len - sizeof(buf);
229 if (sysctl(mib, 2, &buf[len], &n, NULL, 0) == -1)
233 /* make sure that the buffer actually got set. */
234 for (i=any_set=0; i<sizeof(buf); ++i) {
240 arc4_addrandom(buf, sizeof(buf));
241 evutil_memclear_(buf, sizeof(buf));
245 #endif /* defined(EVENT__HAVE_SYS_SYSCTL_H) */
248 #define TRY_SEED_PROC_SYS_KERNEL_RANDOM_UUID
250 arc4_seed_proc_sys_kernel_random_uuid(void)
252 /* Occasionally, somebody will make /proc/sys accessible in a chroot,
253 * but not /dev/urandom. Let's try /proc/sys/kernel/random/uuid.
254 * Its format is stupid, so we need to decode it from hex.
258 unsigned char entropy[64];
259 int bytes, n, i, nybbles;
260 for (bytes = 0; bytes<ADD_ENTROPY; ) {
261 fd = evutil_open_closeonexec_("/proc/sys/kernel/random/uuid", O_RDONLY, 0);
264 n = read(fd, buf, sizeof(buf));
268 memset(entropy, 0, sizeof(entropy));
269 for (i=nybbles=0; i<n; ++i) {
270 if (EVUTIL_ISXDIGIT_(buf[i])) {
271 int nyb = evutil_hex_char_to_int_(buf[i]);
273 entropy[nybbles/2] |= nyb;
275 entropy[nybbles/2] |= nyb<<4;
282 arc4_addrandom(entropy, nybbles/2);
285 evutil_memclear_(entropy, sizeof(entropy));
286 evutil_memclear_(buf, sizeof(buf));
292 #define TRY_SEED_URANDOM
293 static char *arc4random_urandom_filename = NULL;
295 static int arc4_seed_urandom_helper_(const char *fname)
297 unsigned char buf[ADD_ENTROPY];
301 fd = evutil_open_closeonexec_(fname, O_RDONLY, 0);
304 n = read_all(fd, buf, sizeof(buf));
306 if (n != sizeof(buf))
308 arc4_addrandom(buf, sizeof(buf));
309 evutil_memclear_(buf, sizeof(buf));
314 arc4_seed_urandom(void)
316 /* This is adapted from Tor's crypto_seed_rng() */
317 static const char *filenames[] = {
318 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
321 if (arc4random_urandom_filename)
322 return arc4_seed_urandom_helper_(arc4random_urandom_filename);
324 for (i = 0; filenames[i]; ++i) {
325 if (arc4_seed_urandom_helper_(filenames[i]) == 0) {
338 /* We try every method that might work, and don't give up even if one
339 * does seem to work. There's no real harm in over-seeding, and if
340 * one of these sources turns out to be broken, that would be bad. */
341 #ifdef TRY_SEED_WIN32
342 if (0 == arc4_seed_win32())
345 #ifdef TRY_SEED_URANDOM
346 if (0 == arc4_seed_urandom())
349 #ifdef TRY_SEED_PROC_SYS_KERNEL_RANDOM_UUID
350 if (arc4random_urandom_filename == NULL &&
351 0 == arc4_seed_proc_sys_kernel_random_uuid())
354 #ifdef TRY_SEED_SYSCTL_LINUX
355 /* Apparently Linux is deprecating sysctl, and spewing warning
356 * messages when you try to use it. */
357 if (!ok && 0 == arc4_seed_sysctl_linux())
360 #ifdef TRY_SEED_SYSCTL_BSD
361 if (0 == arc4_seed_sysctl_bsd())
372 if (!rs_initialized) {
377 if (0 != arc4_seed())
381 * Discard early keystream, as per recommendations in
382 * "Weaknesses in the Key Scheduling Algorithm of RC4" by
383 * Scott Fluhrer, Itsik Mantin, and Adi Shamir.
384 * http://www.wisdom.weizmann.ac.il/~itsik/RC4/Papers/Rc4_ksa.ps
386 * Ilya Mironov's "(Not So) Random Shuffles of RC4" suggests that
387 * we drop at least 2*256 bytes, with 12*256 as a conservative
390 * RFC4345 says to drop 6*256.
392 * At least some versions of this code drop 4*256, in a mistaken
393 * belief that "words" in the Fluhrer/Mantin/Shamir paper refers
394 * to processor words.
396 * We add another sect to the cargo cult, and choose 12*256.
398 for (i = 0; i < 12*256; i++)
399 (void)arc4_getbyte();
401 arc4_count = BYTES_BEFORE_RESEED;
408 arc4_stir_if_needed(void)
410 pid_t pid = getpid();
412 if (arc4_count <= 0 || !rs_initialized || arc4_stir_pid != pid)
419 static inline unsigned char
422 unsigned char si, sj;
430 return (rs.s[(si + sj) & 0xff]);
433 static inline unsigned int
438 val = arc4_getbyte() << 24;
439 val |= arc4_getbyte() << 16;
440 val |= arc4_getbyte() << 8;
441 val |= arc4_getbyte();
446 #ifndef ARC4RANDOM_NOSTIR
447 ARC4RANDOM_EXPORT int
448 arc4random_stir(void)
458 #ifndef ARC4RANDOM_NOADDRANDOM
459 ARC4RANDOM_EXPORT void
460 arc4random_addrandom(const unsigned char *dat, int datlen)
466 for (j = 0; j < datlen; j += 256) {
467 /* arc4_addrandom() ignores all but the first 256 bytes of
468 * its input. We want to make sure to look at ALL the
469 * data in 'dat', just in case the user is doing something
470 * crazy like passing us all the files in /var/log. */
471 arc4_addrandom(dat + j, datlen - j);
477 #ifndef ARC4RANDOM_NORANDOM
478 ARC4RANDOM_EXPORT ARC4RANDOM_UINT32
481 ARC4RANDOM_UINT32 val;
484 arc4_stir_if_needed();
485 val = arc4_getword();
491 ARC4RANDOM_EXPORT void
492 arc4random_buf(void *buf_, size_t n)
494 unsigned char *buf = buf_;
496 arc4_stir_if_needed();
498 if (--arc4_count <= 0)
500 buf[n] = arc4_getbyte();
505 #ifndef ARC4RANDOM_NOUNIFORM
507 * Calculate a uniformly distributed random number less than upper_bound
508 * avoiding "modulo bias".
510 * Uniformity is achieved by generating new random numbers until the one
511 * returned is outside the range [0, 2**32 % upper_bound). This
512 * guarantees the selected random number will be inside
513 * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
514 * after reduction modulo upper_bound.
516 ARC4RANDOM_EXPORT unsigned int
517 arc4random_uniform(unsigned int upper_bound)
519 ARC4RANDOM_UINT32 r, min;
524 #if (UINT_MAX > 0xffffffffUL)
525 min = 0x100000000UL % upper_bound;
527 /* Calculate (2**32 % upper_bound) avoiding 64-bit math */
528 if (upper_bound > 0x80000000)
529 min = 1 + ~upper_bound; /* 2**32 - upper_bound */
531 /* (2**32 - (x * 2)) % x == 2**32 % x when x <= 2**31 */
532 min = ((0xffffffff - (upper_bound * 2)) + 1) % upper_bound;
537 * This could theoretically loop forever but each retry has
538 * p > 0.5 (worst case, usually far better) of selecting a
539 * number inside the range we need, so it should rarely need
548 return r % upper_bound;