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"
60 #include <sys/param.h>
62 #ifdef EVENT__HAVE_SYS_SYSCTL_H
63 #include <sys/sysctl.h>
71 /* Add platform entropy 32 bytes (256 bits) at a time. */
72 #define ADD_ENTROPY 32
74 /* Re-seed from the platform RNG after generating this many bytes. */
75 #define BYTES_BEFORE_RESEED 1600000
84 #define getpid _getpid
88 static int rs_initialized;
89 static struct arc4_stream rs;
90 static pid_t arc4_stir_pid;
91 static int arc4_count;
93 static inline unsigned char arc4_getbyte(void);
100 for (n = 0; n < 256; n++)
107 arc4_addrandom(const unsigned char *dat, int datlen)
113 for (n = 0; n < 256; n++) {
116 rs.j = (rs.j + si + dat[n % datlen]);
117 rs.s[rs.i] = rs.s[rs.j];
125 read_all(int fd, unsigned char *buf, size_t count)
130 while (numread < count) {
131 result = read(fd, buf+numread, count-numread);
134 else if (result == 0)
139 return (ssize_t)numread;
144 #define TRY_SEED_WIN32
146 arc4_seed_win32(void)
148 /* This is adapted from Tor's crypto_seed_rng() */
149 static int provider_set = 0;
150 static HCRYPTPROV provider;
151 unsigned char buf[ADD_ENTROPY];
154 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
155 CRYPT_VERIFYCONTEXT)) {
156 if (GetLastError() != (DWORD)NTE_BAD_KEYSET)
161 if (!CryptGenRandom(provider, sizeof(buf), buf))
163 arc4_addrandom(buf, sizeof(buf));
164 evutil_memclear_(buf, sizeof(buf));
169 #if defined(EVENT__HAVE_SYS_SYSCTL_H) && defined(EVENT__HAVE_SYSCTL)
170 #if EVENT__HAVE_DECL_CTL_KERN && EVENT__HAVE_DECL_KERN_RANDOM && EVENT__HAVE_DECL_RANDOM_UUID
171 #define TRY_SEED_SYSCTL_LINUX
173 arc4_seed_sysctl_linux(void)
175 /* Based on code by William Ahern, this function tries to use the
176 * RANDOM_UUID sysctl to get entropy from the kernel. This can work
177 * even if /dev/urandom is inaccessible for some reason (e.g., we're
178 * running in a chroot). */
179 int mib[] = { CTL_KERN, KERN_RANDOM, RANDOM_UUID };
180 unsigned char buf[ADD_ENTROPY];
185 memset(buf, 0, sizeof(buf));
187 for (len = 0; len < sizeof(buf); len += n) {
188 n = sizeof(buf) - len;
190 if (0 != sysctl(mib, 3, &buf[len], &n, NULL, 0))
193 /* make sure that the buffer actually got set. */
194 for (i=0,any_set=0; i<sizeof(buf); ++i) {
200 arc4_addrandom(buf, sizeof(buf));
201 evutil_memclear_(buf, sizeof(buf));
206 #if EVENT__HAVE_DECL_CTL_KERN && EVENT__HAVE_DECL_KERN_ARND
207 #define TRY_SEED_SYSCTL_BSD
209 arc4_seed_sysctl_bsd(void)
211 /* Based on code from William Ahern and from OpenBSD, this function
212 * tries to use the KERN_ARND syscall to get entropy from the kernel.
213 * This can work even if /dev/urandom is inaccessible for some reason
214 * (e.g., we're running in a chroot). */
215 int mib[] = { CTL_KERN, KERN_ARND };
216 unsigned char buf[ADD_ENTROPY];
220 memset(buf, 0, sizeof(buf));
223 if (sysctl(mib, 2, buf, &len, NULL, 0) == -1) {
224 for (len = 0; len < sizeof(buf); len += sizeof(unsigned)) {
225 n = sizeof(unsigned);
226 if (n + len > sizeof(buf))
227 n = len - sizeof(buf);
228 if (sysctl(mib, 2, &buf[len], &n, NULL, 0) == -1)
232 /* make sure that the buffer actually got set. */
233 for (i=any_set=0; i<sizeof(buf); ++i) {
239 arc4_addrandom(buf, sizeof(buf));
240 evutil_memclear_(buf, sizeof(buf));
244 #endif /* defined(EVENT__HAVE_SYS_SYSCTL_H) */
247 #define TRY_SEED_PROC_SYS_KERNEL_RANDOM_UUID
249 arc4_seed_proc_sys_kernel_random_uuid(void)
251 /* Occasionally, somebody will make /proc/sys accessible in a chroot,
252 * but not /dev/urandom. Let's try /proc/sys/kernel/random/uuid.
253 * Its format is stupid, so we need to decode it from hex.
257 unsigned char entropy[64];
258 int bytes, n, i, nybbles;
259 for (bytes = 0; bytes<ADD_ENTROPY; ) {
260 fd = evutil_open_closeonexec_("/proc/sys/kernel/random/uuid", O_RDONLY, 0);
263 n = read(fd, buf, sizeof(buf));
267 memset(entropy, 0, sizeof(entropy));
268 for (i=nybbles=0; i<n; ++i) {
269 if (EVUTIL_ISXDIGIT_(buf[i])) {
270 int nyb = evutil_hex_char_to_int_(buf[i]);
272 entropy[nybbles/2] |= nyb;
274 entropy[nybbles/2] |= nyb<<4;
281 arc4_addrandom(entropy, nybbles/2);
284 evutil_memclear_(entropy, sizeof(entropy));
285 evutil_memclear_(buf, sizeof(buf));
291 #define TRY_SEED_URANDOM
292 static char *arc4random_urandom_filename = NULL;
294 static int arc4_seed_urandom_helper_(const char *fname)
296 unsigned char buf[ADD_ENTROPY];
300 fd = evutil_open_closeonexec_(fname, O_RDONLY, 0);
303 n = read_all(fd, buf, sizeof(buf));
305 if (n != sizeof(buf))
307 arc4_addrandom(buf, sizeof(buf));
308 evutil_memclear_(buf, sizeof(buf));
313 arc4_seed_urandom(void)
315 /* This is adapted from Tor's crypto_seed_rng() */
316 static const char *filenames[] = {
317 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
320 if (arc4random_urandom_filename)
321 return arc4_seed_urandom_helper_(arc4random_urandom_filename);
323 for (i = 0; filenames[i]; ++i) {
324 if (arc4_seed_urandom_helper_(filenames[i]) == 0) {
337 /* We try every method that might work, and don't give up even if one
338 * does seem to work. There's no real harm in over-seeding, and if
339 * one of these sources turns out to be broken, that would be bad. */
340 #ifdef TRY_SEED_WIN32
341 if (0 == arc4_seed_win32())
344 #ifdef TRY_SEED_URANDOM
345 if (0 == arc4_seed_urandom())
348 #ifdef TRY_SEED_PROC_SYS_KERNEL_RANDOM_UUID
349 if (arc4random_urandom_filename == NULL &&
350 0 == arc4_seed_proc_sys_kernel_random_uuid())
353 #ifdef TRY_SEED_SYSCTL_LINUX
354 /* Apparently Linux is deprecating sysctl, and spewing warning
355 * messages when you try to use it. */
356 if (!ok && 0 == arc4_seed_sysctl_linux())
359 #ifdef TRY_SEED_SYSCTL_BSD
360 if (0 == arc4_seed_sysctl_bsd())
371 if (!rs_initialized) {
376 if (0 != arc4_seed())
380 * Discard early keystream, as per recommendations in
381 * "Weaknesses in the Key Scheduling Algorithm of RC4" by
382 * Scott Fluhrer, Itsik Mantin, and Adi Shamir.
383 * http://www.wisdom.weizmann.ac.il/~itsik/RC4/Papers/Rc4_ksa.ps
385 * Ilya Mironov's "(Not So) Random Shuffles of RC4" suggests that
386 * we drop at least 2*256 bytes, with 12*256 as a conservative
389 * RFC4345 says to drop 6*256.
391 * At least some versions of this code drop 4*256, in a mistaken
392 * belief that "words" in the Fluhrer/Mantin/Shamir paper refers
393 * to processor words.
395 * We add another sect to the cargo cult, and choose 12*256.
397 for (i = 0; i < 12*256; i++)
398 (void)arc4_getbyte();
400 arc4_count = BYTES_BEFORE_RESEED;
407 arc4_stir_if_needed(void)
409 pid_t pid = getpid();
411 if (arc4_count <= 0 || !rs_initialized || arc4_stir_pid != pid)
418 static inline unsigned char
421 unsigned char si, sj;
429 return (rs.s[(si + sj) & 0xff]);
432 static inline unsigned int
437 val = arc4_getbyte() << 24;
438 val |= arc4_getbyte() << 16;
439 val |= arc4_getbyte() << 8;
440 val |= arc4_getbyte();
445 #ifndef ARC4RANDOM_NOSTIR
446 ARC4RANDOM_EXPORT int
447 arc4random_stir(void)
457 #ifndef ARC4RANDOM_NOADDRANDOM
458 ARC4RANDOM_EXPORT void
459 arc4random_addrandom(const unsigned char *dat, int datlen)
465 for (j = 0; j < datlen; j += 256) {
466 /* arc4_addrandom() ignores all but the first 256 bytes of
467 * its input. We want to make sure to look at ALL the
468 * data in 'dat', just in case the user is doing something
469 * crazy like passing us all the files in /var/log. */
470 arc4_addrandom(dat + j, datlen - j);
476 #ifndef ARC4RANDOM_NORANDOM
477 ARC4RANDOM_EXPORT ARC4RANDOM_UINT32
480 ARC4RANDOM_UINT32 val;
483 arc4_stir_if_needed();
484 val = arc4_getword();
490 ARC4RANDOM_EXPORT void
491 arc4random_buf(void *buf_, size_t n)
493 unsigned char *buf = buf_;
495 arc4_stir_if_needed();
497 if (--arc4_count <= 0)
499 buf[n] = arc4_getbyte();
504 #ifndef ARC4RANDOM_NOUNIFORM
506 * Calculate a uniformly distributed random number less than upper_bound
507 * avoiding "modulo bias".
509 * Uniformity is achieved by generating new random numbers until the one
510 * returned is outside the range [0, 2**32 % upper_bound). This
511 * guarantees the selected random number will be inside
512 * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
513 * after reduction modulo upper_bound.
515 ARC4RANDOM_EXPORT unsigned int
516 arc4random_uniform(unsigned int upper_bound)
518 ARC4RANDOM_UINT32 r, min;
523 #if (UINT_MAX > 0xffffffffUL)
524 min = 0x100000000UL % upper_bound;
526 /* Calculate (2**32 % upper_bound) avoiding 64-bit math */
527 if (upper_bound > 0x80000000)
528 min = 1 + ~upper_bound; /* 2**32 - upper_bound */
530 /* (2**32 - (x * 2)) % x == 2**32 % x when x <= 2**31 */
531 min = ((0xffffffff - (upper_bound * 2)) + 1) % upper_bound;
536 * This could theoretically loop forever but each retry has
537 * p > 0.5 (worst case, usually far better) of selecting a
538 * number inside the range we need, so it should rarely need
547 return r % upper_bound;