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
5 * Note that in Libevent, this file isn't compiled directly. Instead,
6 * it's included from evutil_rand.c
10 * Copyright (c) 1996, David Mazieres <dm@uun.org>
11 * Copyright (c) 2008, Damien Miller <djm@openbsd.org>
13 * Permission to use, copy, modify, and distribute this software for any
14 * purpose with or without fee is hereby granted, provided that the above
15 * copyright notice and this permission notice appear in all copies.
17 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
18 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
19 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
20 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
21 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
22 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
23 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
27 * Arc4 random number generator for OpenBSD.
29 * This code is derived from section 17.1 of Applied Cryptography,
30 * second edition, which describes a stream cipher allegedly
31 * compatible with RSA Labs "RC4" cipher (the actual description of
32 * which is a trade secret). The same algorithm is used as a stream
33 * cipher called "arcfour" in Tatu Ylonen's ssh package.
35 * Here the stream cipher has been modified always to include the time
36 * when initializing the state. That makes it impossible to
37 * regenerate the same random sequence twice, so this can't be used
38 * for encryption, but will generate good random numbers.
40 * RC4 is a registered trademark of RSA Laboratories.
43 #ifndef ARC4RANDOM_EXPORT
44 #define ARC4RANDOM_EXPORT
47 #ifndef ARC4RANDOM_UINT32
48 #define ARC4RANDOM_UINT32 uint32_t
51 #ifndef ARC4RANDOM_NO_INCLUDES
58 #include <sys/param.h>
60 #ifdef _EVENT_HAVE_SYS_SYSCTL_H
61 #include <sys/sysctl.h>
69 /* Add platform entropy 32 bytes (256 bits) at a time. */
70 #define ADD_ENTROPY 32
72 /* Re-seed from the platform RNG after generating this many bytes. */
73 #define BYTES_BEFORE_RESEED 1600000
82 #define getpid _getpid
86 static int rs_initialized;
87 static struct arc4_stream rs;
88 static pid_t arc4_stir_pid;
89 static int arc4_count;
90 static int arc4_seeded_ok;
92 static inline unsigned char arc4_getbyte(void);
99 for (n = 0; n < 256; n++)
106 arc4_addrandom(const unsigned char *dat, int datlen)
112 for (n = 0; n < 256; n++) {
115 rs.j = (rs.j + si + dat[n % datlen]);
116 rs.s[rs.i] = rs.s[rs.j];
124 read_all(int fd, unsigned char *buf, size_t count)
129 while (numread < count) {
130 result = read(fd, buf+numread, count-numread);
133 else if (result == 0)
138 return (ssize_t)numread;
143 #define TRY_SEED_WIN32
145 arc4_seed_win32(void)
147 /* This is adapted from Tor's crypto_seed_rng() */
148 static int provider_set = 0;
149 static HCRYPTPROV provider;
150 unsigned char buf[ADD_ENTROPY];
153 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
154 CRYPT_VERIFYCONTEXT)) {
155 if (GetLastError() != (DWORD)NTE_BAD_KEYSET)
160 if (!CryptGenRandom(provider, sizeof(buf), buf))
162 arc4_addrandom(buf, sizeof(buf));
163 memset(buf, 0, sizeof(buf));
169 #if defined(_EVENT_HAVE_SYS_SYSCTL_H)
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 memset(buf, 0, 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 memset(buf, 0, sizeof(buf));
246 #endif /* defined(_EVENT_HAVE_SYS_SYSCTL_H) */
249 #define TRY_SEED_PROC_SYS_KERNEL_RANDOM_UUID
251 arc4_seed_proc_sys_kernel_random_uuid(void)
253 /* Occasionally, somebody will make /proc/sys accessible in a chroot,
254 * but not /dev/urandom. Let's try /proc/sys/kernel/random/uuid.
255 * Its format is stupid, so we need to decode it from hex.
259 unsigned char entropy[64];
260 int bytes, n, i, nybbles;
261 for (bytes = 0; bytes<ADD_ENTROPY; ) {
262 fd = open("/proc/sys/kernel/random/uuid", O_RDONLY, 0);
265 n = read(fd, buf, sizeof(buf));
269 memset(entropy, 0, sizeof(entropy));
270 for (i=nybbles=0; i<n; ++i) {
271 if (EVUTIL_ISXDIGIT(buf[i])) {
272 int nyb = evutil_hex_char_to_int(buf[i]);
274 entropy[nybbles/2] |= nyb;
276 entropy[nybbles/2] |= nyb<<4;
283 arc4_addrandom(entropy, nybbles/2);
286 memset(entropy, 0, sizeof(entropy));
287 memset(buf, 0, sizeof(buf));
293 #define TRY_SEED_URANDOM
295 arc4_seed_urandom(void)
297 /* This is adapted from Tor's crypto_seed_rng() */
298 static const char *filenames[] = {
299 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
301 unsigned char buf[ADD_ENTROPY];
305 for (i = 0; filenames[i]; ++i) {
306 fd = open(filenames[i], O_RDONLY, 0);
309 n = read_all(fd, buf, sizeof(buf));
311 if (n != sizeof(buf))
313 arc4_addrandom(buf, sizeof(buf));
314 memset(buf, 0, sizeof(buf));
327 /* We try every method that might work, and don't give up even if one
328 * does seem to work. There's no real harm in over-seeding, and if
329 * one of these sources turns out to be broken, that would be bad. */
330 #ifdef TRY_SEED_WIN32
331 if (0 == arc4_seed_win32())
334 #ifdef TRY_SEED_URANDOM
335 if (0 == arc4_seed_urandom())
338 #ifdef TRY_SEED_PROC_SYS_KERNEL_RANDOM_UUID
339 if (0 == arc4_seed_proc_sys_kernel_random_uuid())
342 #ifdef TRY_SEED_SYSCTL_LINUX
343 /* Apparently Linux is deprecating sysctl, and spewing warning
344 * messages when you try to use it. */
345 if (!ok && 0 == arc4_seed_sysctl_linux())
348 #ifdef TRY_SEED_SYSCTL_BSD
349 if (0 == arc4_seed_sysctl_bsd())
360 if (!rs_initialized) {
370 * Discard early keystream, as per recommendations in
371 * "Weaknesses in the Key Scheduling Algorithm of RC4" by
372 * Scott Fluhrer, Itsik Mantin, and Adi Shamir.
373 * http://www.wisdom.weizmann.ac.il/~itsik/RC4/Papers/Rc4_ksa.ps
375 * Ilya Mironov's "(Not So) Random Shuffles of RC4" suggests that
376 * we drop at least 2*256 bytes, with 12*256 as a conservative
379 * RFC4345 says to drop 6*256.
381 * At least some versions of this code drop 4*256, in a mistaken
382 * belief that "words" in the Fluhrer/Mantin/Shamir paper refers
383 * to processor words.
385 * We add another sect to the cargo cult, and choose 12*256.
387 for (i = 0; i < 12*256; i++)
388 (void)arc4_getbyte();
389 arc4_count = BYTES_BEFORE_RESEED;
396 arc4_stir_if_needed(void)
398 pid_t pid = getpid();
400 if (arc4_count <= 0 || !rs_initialized || arc4_stir_pid != pid)
407 static inline unsigned char
410 unsigned char si, sj;
418 return (rs.s[(si + sj) & 0xff]);
421 static inline unsigned int
426 val = arc4_getbyte() << 24;
427 val |= arc4_getbyte() << 16;
428 val |= arc4_getbyte() << 8;
429 val |= arc4_getbyte();
434 #ifndef ARC4RANDOM_NOSTIR
435 ARC4RANDOM_EXPORT int
436 arc4random_stir(void)
446 #ifndef ARC4RANDOM_NOADDRANDOM
447 ARC4RANDOM_EXPORT void
448 arc4random_addrandom(const unsigned char *dat, int datlen)
454 for (j = 0; j < datlen; j += 256) {
455 /* arc4_addrandom() ignores all but the first 256 bytes of
456 * its input. We want to make sure to look at ALL the
457 * data in 'dat', just in case the user is doing something
458 * crazy like passing us all the files in /var/log. */
459 arc4_addrandom(dat + j, datlen - j);
465 #ifndef ARC4RANDOM_NORANDOM
466 ARC4RANDOM_EXPORT ARC4RANDOM_UINT32
469 ARC4RANDOM_UINT32 val;
472 arc4_stir_if_needed();
473 val = arc4_getword();
479 ARC4RANDOM_EXPORT void
480 arc4random_buf(void *_buf, size_t n)
482 unsigned char *buf = _buf;
484 arc4_stir_if_needed();
486 if (--arc4_count <= 0)
488 buf[n] = arc4_getbyte();
493 #ifndef ARC4RANDOM_NOUNIFORM
495 * Calculate a uniformly distributed random number less than upper_bound
496 * avoiding "modulo bias".
498 * Uniformity is achieved by generating new random numbers until the one
499 * returned is outside the range [0, 2**32 % upper_bound). This
500 * guarantees the selected random number will be inside
501 * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
502 * after reduction modulo upper_bound.
504 ARC4RANDOM_EXPORT unsigned int
505 arc4random_uniform(unsigned int upper_bound)
507 ARC4RANDOM_UINT32 r, min;
512 #if (UINT_MAX > 0xffffffffUL)
513 min = 0x100000000UL % upper_bound;
515 /* Calculate (2**32 % upper_bound) avoiding 64-bit math */
516 if (upper_bound > 0x80000000)
517 min = 1 + ~upper_bound; /* 2**32 - upper_bound */
519 /* (2**32 - (x * 2)) % x == 2**32 % x when x <= 2**31 */
520 min = ((0xffffffff - (upper_bound * 2)) + 1) % upper_bound;
525 * This could theoretically loop forever but each retry has
526 * p > 0.5 (worst case, usually far better) of selecting a
527 * number inside the range we need, so it should rarely need
536 return r % upper_bound;