xref: /libevent-2.1.12/arc4random.c (revision 66ec78fd)
1d4de062eSNick Mathewson /* Portable arc4random.c based on arc4random.c from OpenBSD.
2d4de062eSNick Mathewson  * Portable version by Chris Davis, adapted for Libevent by Nick Mathewson
371fc3eb0SNick Mathewson  * Copyright (c) 2010 Chris Davis, Niels Provos, and Nick Mathewson
4e49e2891SNick Mathewson  * Copyright (c) 2010-2012 Niels Provos and Nick Mathewson
5d4de062eSNick Mathewson  *
6d4de062eSNick Mathewson  * Note that in Libevent, this file isn't compiled directly.  Instead,
7d4de062eSNick Mathewson  * it's included from evutil_rand.c
8d4de062eSNick Mathewson  */
9d4de062eSNick Mathewson 
10d4de062eSNick Mathewson /*
11d4de062eSNick Mathewson  * Copyright (c) 1996, David Mazieres <[email protected]>
12d4de062eSNick Mathewson  * Copyright (c) 2008, Damien Miller <[email protected]>
13d4de062eSNick Mathewson  *
14d4de062eSNick Mathewson  * Permission to use, copy, modify, and distribute this software for any
15d4de062eSNick Mathewson  * purpose with or without fee is hereby granted, provided that the above
16d4de062eSNick Mathewson  * copyright notice and this permission notice appear in all copies.
17d4de062eSNick Mathewson  *
18d4de062eSNick Mathewson  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
19d4de062eSNick Mathewson  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
20d4de062eSNick Mathewson  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
21d4de062eSNick Mathewson  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
22d4de062eSNick Mathewson  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
23d4de062eSNick Mathewson  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
24d4de062eSNick Mathewson  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
25d4de062eSNick Mathewson  */
26d4de062eSNick Mathewson 
27d4de062eSNick Mathewson /*
28d4de062eSNick Mathewson  * Arc4 random number generator for OpenBSD.
29d4de062eSNick Mathewson  *
30d4de062eSNick Mathewson  * This code is derived from section 17.1 of Applied Cryptography,
31d4de062eSNick Mathewson  * second edition, which describes a stream cipher allegedly
32d4de062eSNick Mathewson  * compatible with RSA Labs "RC4" cipher (the actual description of
33d4de062eSNick Mathewson  * which is a trade secret).  The same algorithm is used as a stream
34d4de062eSNick Mathewson  * cipher called "arcfour" in Tatu Ylonen's ssh package.
35d4de062eSNick Mathewson  *
36d4de062eSNick Mathewson  * Here the stream cipher has been modified always to include the time
37d4de062eSNick Mathewson  * when initializing the state.  That makes it impossible to
38d4de062eSNick Mathewson  * regenerate the same random sequence twice, so this can't be used
39d4de062eSNick Mathewson  * for encryption, but will generate good random numbers.
40d4de062eSNick Mathewson  *
41d4de062eSNick Mathewson  * RC4 is a registered trademark of RSA Laboratories.
42d4de062eSNick Mathewson  */
43d4de062eSNick Mathewson 
44d4de062eSNick Mathewson #ifndef ARC4RANDOM_EXPORT
45d4de062eSNick Mathewson #define ARC4RANDOM_EXPORT
46d4de062eSNick Mathewson #endif
47d4de062eSNick Mathewson 
484ec8fea6SNick Mathewson #ifndef ARC4RANDOM_UINT32
494ec8fea6SNick Mathewson #define ARC4RANDOM_UINT32 uint32_t
504ec8fea6SNick Mathewson #endif
514ec8fea6SNick Mathewson 
52d4de062eSNick Mathewson #ifndef ARC4RANDOM_NO_INCLUDES
53ded0a090SKevin Bowling #include "evconfig-private.h"
549f560bfaSNick Mathewson #ifdef _WIN32
55d4de062eSNick Mathewson #include <wincrypt.h>
56ff2a134dSNick Mathewson #include <process.h>
579559349cSyuangongji #include <winerror.h>
58d4de062eSNick Mathewson #else
59d4de062eSNick Mathewson #include <fcntl.h>
60d4de062eSNick Mathewson #include <unistd.h>
61d4de062eSNick Mathewson #include <sys/param.h>
62d4de062eSNick Mathewson #include <sys/time.h>
6368120d9bSNick Mathewson #ifdef EVENT__HAVE_SYS_SYSCTL_H
6471fc3eb0SNick Mathewson #include <sys/sysctl.h>
65d4de062eSNick Mathewson #endif
66*66ec78fdSAzat Khuzhin #ifdef EVENT__HAVE_SYS_RANDOM_H
67*66ec78fdSAzat Khuzhin #include <sys/random.h>
68*66ec78fdSAzat Khuzhin #endif
69c44de06cSNick Mathewson #endif
70d4de062eSNick Mathewson #include <limits.h>
71d4de062eSNick Mathewson #include <stdlib.h>
72d4de062eSNick Mathewson #include <string.h>
73d4de062eSNick Mathewson #endif
74d4de062eSNick Mathewson 
75d4de062eSNick Mathewson /* Add platform entropy 32 bytes (256 bits) at a time. */
76d4de062eSNick Mathewson #define ADD_ENTROPY 32
77d4de062eSNick Mathewson 
78d4de062eSNick Mathewson /* Re-seed from the platform RNG after generating this many bytes. */
79d4de062eSNick Mathewson #define BYTES_BEFORE_RESEED 1600000
80d4de062eSNick Mathewson 
81d4de062eSNick Mathewson struct arc4_stream {
82d4de062eSNick Mathewson 	unsigned char i;
83d4de062eSNick Mathewson 	unsigned char j;
84d4de062eSNick Mathewson 	unsigned char s[256];
85d4de062eSNick Mathewson };
86d4de062eSNick Mathewson 
879f560bfaSNick Mathewson #ifdef _WIN32
8898edb891SNick Mathewson #define getpid _getpid
8998edb891SNick Mathewson #define pid_t int
9098edb891SNick Mathewson #endif
9198edb891SNick Mathewson 
92d4de062eSNick Mathewson static int rs_initialized;
93d4de062eSNick Mathewson static struct arc4_stream rs;
94d4de062eSNick Mathewson static pid_t arc4_stir_pid;
95d4de062eSNick Mathewson static int arc4_count;
96d4de062eSNick Mathewson 
97d4de062eSNick Mathewson static inline unsigned char arc4_getbyte(void);
98d4de062eSNick Mathewson 
99d4de062eSNick Mathewson static inline void
arc4_init(void)100d4de062eSNick Mathewson arc4_init(void)
101d4de062eSNick Mathewson {
102d4de062eSNick Mathewson 	int     n;
103d4de062eSNick Mathewson 
104d4de062eSNick Mathewson 	for (n = 0; n < 256; n++)
105d4de062eSNick Mathewson 		rs.s[n] = n;
106d4de062eSNick Mathewson 	rs.i = 0;
107d4de062eSNick Mathewson 	rs.j = 0;
108d4de062eSNick Mathewson }
109d4de062eSNick Mathewson 
110d4de062eSNick Mathewson static inline void
arc4_addrandom(const unsigned char * dat,int datlen)111d4de062eSNick Mathewson arc4_addrandom(const unsigned char *dat, int datlen)
112d4de062eSNick Mathewson {
113d4de062eSNick Mathewson 	int     n;
114d4de062eSNick Mathewson 	unsigned char si;
115d4de062eSNick Mathewson 
116d4de062eSNick Mathewson 	rs.i--;
117d4de062eSNick Mathewson 	for (n = 0; n < 256; n++) {
118d4de062eSNick Mathewson 		rs.i = (rs.i + 1);
119d4de062eSNick Mathewson 		si = rs.s[rs.i];
120d4de062eSNick Mathewson 		rs.j = (rs.j + si + dat[n % datlen]);
121d4de062eSNick Mathewson 		rs.s[rs.i] = rs.s[rs.j];
122d4de062eSNick Mathewson 		rs.s[rs.j] = si;
123d4de062eSNick Mathewson 	}
124d4de062eSNick Mathewson 	rs.j = rs.i;
125d4de062eSNick Mathewson }
126d4de062eSNick Mathewson 
1279f560bfaSNick Mathewson #ifndef _WIN32
128d4de062eSNick Mathewson static ssize_t
read_all(int fd,unsigned char * buf,size_t count)129d4de062eSNick Mathewson read_all(int fd, unsigned char *buf, size_t count)
130d4de062eSNick Mathewson {
131d4de062eSNick Mathewson 	size_t numread = 0;
132d4de062eSNick Mathewson 	ssize_t result;
133d4de062eSNick Mathewson 
134d4de062eSNick Mathewson 	while (numread < count) {
135d4de062eSNick Mathewson 		result = read(fd, buf+numread, count-numread);
136d4de062eSNick Mathewson 		if (result<0)
137d4de062eSNick Mathewson 			return -1;
138d4de062eSNick Mathewson 		else if (result == 0)
139d4de062eSNick Mathewson 			break;
140d4de062eSNick Mathewson 		numread += result;
141d4de062eSNick Mathewson 	}
142d4de062eSNick Mathewson 
143d4de062eSNick Mathewson 	return (ssize_t)numread;
144d4de062eSNick Mathewson }
145d4de062eSNick Mathewson #endif
146d4de062eSNick Mathewson 
1479f560bfaSNick Mathewson #ifdef _WIN32
14871fc3eb0SNick Mathewson #define TRY_SEED_WIN32
14971fc3eb0SNick Mathewson static int
arc4_seed_win32(void)15071fc3eb0SNick Mathewson arc4_seed_win32(void)
15171fc3eb0SNick Mathewson {
15271fc3eb0SNick Mathewson 	/* This is adapted from Tor's crypto_seed_rng() */
153d4de062eSNick Mathewson 	static int provider_set = 0;
154d4de062eSNick Mathewson 	static HCRYPTPROV provider;
15571fc3eb0SNick Mathewson 	unsigned char buf[ADD_ENTROPY];
156d4de062eSNick Mathewson 
157d4de062eSNick Mathewson 	if (!provider_set) {
158d4de062eSNick Mathewson 		if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
159d4de062eSNick Mathewson 		    CRYPT_VERIFYCONTEXT)) {
16071fc3eb0SNick Mathewson 			if (GetLastError() != (DWORD)NTE_BAD_KEYSET)
161d4de062eSNick Mathewson 				return -1;
162d4de062eSNick Mathewson 		}
163d4de062eSNick Mathewson 		provider_set = 1;
164d4de062eSNick Mathewson 	}
165d4de062eSNick Mathewson 	if (!CryptGenRandom(provider, sizeof(buf), buf))
166d4de062eSNick Mathewson 		return -1;
167d4de062eSNick Mathewson 	arc4_addrandom(buf, sizeof(buf));
168f5ced88cSNick Mathewson 	evutil_memclear_(buf, sizeof(buf));
169d4de062eSNick Mathewson 	return 0;
17071fc3eb0SNick Mathewson }
17171fc3eb0SNick Mathewson #endif
17271fc3eb0SNick Mathewson 
173*66ec78fdSAzat Khuzhin #if defined(EVENT__HAVE_GETRANDOM)
174*66ec78fdSAzat Khuzhin #define TRY_SEED_GETRANDOM
17571fc3eb0SNick Mathewson static int
arc4_seed_getrandom(void)176*66ec78fdSAzat Khuzhin arc4_seed_getrandom(void)
17771fc3eb0SNick Mathewson {
17871fc3eb0SNick Mathewson 	unsigned char buf[ADD_ENTROPY];
17971fc3eb0SNick Mathewson 	size_t len, n;
1809c8db0f8SNick Mathewson 	unsigned i;
1819c8db0f8SNick Mathewson 	int any_set;
18271fc3eb0SNick Mathewson 
18371fc3eb0SNick Mathewson 	memset(buf, 0, sizeof(buf));
18471fc3eb0SNick Mathewson 
18571fc3eb0SNick Mathewson 	for (len = 0; len < sizeof(buf); len += n) {
18671fc3eb0SNick Mathewson 		n = sizeof(buf) - len;
18771fc3eb0SNick Mathewson 
188*66ec78fdSAzat Khuzhin 		if (0 == getrandom(&buf[len], n, 0))
18971fc3eb0SNick Mathewson 			return -1;
19071fc3eb0SNick Mathewson 	}
19171fc3eb0SNick Mathewson 	/* make sure that the buffer actually got set. */
1929c8db0f8SNick Mathewson 	for (i=0,any_set=0; i<sizeof(buf); ++i) {
19371fc3eb0SNick Mathewson 		any_set |= buf[i];
19471fc3eb0SNick Mathewson 	}
19571fc3eb0SNick Mathewson 	if (!any_set)
19671fc3eb0SNick Mathewson 		return -1;
19771fc3eb0SNick Mathewson 
19871fc3eb0SNick Mathewson 	arc4_addrandom(buf, sizeof(buf));
199f5ced88cSNick Mathewson 	evutil_memclear_(buf, sizeof(buf));
20071fc3eb0SNick Mathewson 	return 0;
20171fc3eb0SNick Mathewson }
202*66ec78fdSAzat Khuzhin #endif /* EVENT__HAVE_GETRANDOM */
20371fc3eb0SNick Mathewson 
204*66ec78fdSAzat Khuzhin #if defined(EVENT__HAVE_SYS_SYSCTL_H) && defined(EVENT__HAVE_SYSCTL)
20568120d9bSNick Mathewson #if EVENT__HAVE_DECL_CTL_KERN && EVENT__HAVE_DECL_KERN_ARND
20690d42251SNick Mathewson #define TRY_SEED_SYSCTL_BSD
20790d42251SNick Mathewson static int
arc4_seed_sysctl_bsd(void)20890d42251SNick Mathewson arc4_seed_sysctl_bsd(void)
20990d42251SNick Mathewson {
21090d42251SNick Mathewson 	/* Based on code from William Ahern and from OpenBSD, this function
21190d42251SNick Mathewson 	 * tries to use the KERN_ARND syscall to get entropy from the kernel.
21290d42251SNick Mathewson 	 * This can work even if /dev/urandom is inaccessible for some reason
21390d42251SNick Mathewson 	 * (e.g., we're running in a chroot). */
21490d42251SNick Mathewson 	int mib[] = { CTL_KERN, KERN_ARND };
21590d42251SNick Mathewson 	unsigned char buf[ADD_ENTROPY];
21690d42251SNick Mathewson 	size_t len, n;
21790d42251SNick Mathewson 	int i, any_set;
21890d42251SNick Mathewson 
21990d42251SNick Mathewson 	memset(buf, 0, sizeof(buf));
22090d42251SNick Mathewson 
22190d42251SNick Mathewson 	len = sizeof(buf);
22290d42251SNick Mathewson 	if (sysctl(mib, 2, buf, &len, NULL, 0) == -1) {
22390d42251SNick Mathewson 		for (len = 0; len < sizeof(buf); len += sizeof(unsigned)) {
22490d42251SNick Mathewson 			n = sizeof(unsigned);
22590d42251SNick Mathewson 			if (n + len > sizeof(buf))
22690d42251SNick Mathewson 			    n = len - sizeof(buf);
22790d42251SNick Mathewson 			if (sysctl(mib, 2, &buf[len], &n, NULL, 0) == -1)
22890d42251SNick Mathewson 				return -1;
22990d42251SNick Mathewson 		}
23090d42251SNick Mathewson 	}
23190d42251SNick Mathewson 	/* make sure that the buffer actually got set. */
23290d42251SNick Mathewson 	for (i=any_set=0; i<sizeof(buf); ++i) {
23390d42251SNick Mathewson 		any_set |= buf[i];
23490d42251SNick Mathewson 	}
23590d42251SNick Mathewson 	if (!any_set)
23690d42251SNick Mathewson 		return -1;
23790d42251SNick Mathewson 
23890d42251SNick Mathewson 	arc4_addrandom(buf, sizeof(buf));
239f5ced88cSNick Mathewson 	evutil_memclear_(buf, sizeof(buf));
24090d42251SNick Mathewson 	return 0;
24190d42251SNick Mathewson }
24290d42251SNick Mathewson #endif
24368120d9bSNick Mathewson #endif /* defined(EVENT__HAVE_SYS_SYSCTL_H) */
24490d42251SNick Mathewson 
24520fda296SNick Mathewson #ifdef __linux__
24620fda296SNick Mathewson #define TRY_SEED_PROC_SYS_KERNEL_RANDOM_UUID
24720fda296SNick Mathewson static int
arc4_seed_proc_sys_kernel_random_uuid(void)24820fda296SNick Mathewson arc4_seed_proc_sys_kernel_random_uuid(void)
24920fda296SNick Mathewson {
25020fda296SNick Mathewson 	/* Occasionally, somebody will make /proc/sys accessible in a chroot,
25120fda296SNick Mathewson 	 * but not /dev/urandom.  Let's try /proc/sys/kernel/random/uuid.
25220fda296SNick Mathewson 	 * Its format is stupid, so we need to decode it from hex.
25320fda296SNick Mathewson 	 */
25420fda296SNick Mathewson 	int fd;
25520fda296SNick Mathewson 	char buf[128];
25620fda296SNick Mathewson 	unsigned char entropy[64];
25720fda296SNick Mathewson 	int bytes, n, i, nybbles;
25820fda296SNick Mathewson 	for (bytes = 0; bytes<ADD_ENTROPY; ) {
2598ac3c4c2SNick Mathewson 		fd = evutil_open_closeonexec_("/proc/sys/kernel/random/uuid", O_RDONLY, 0);
26020fda296SNick Mathewson 		if (fd < 0)
26120fda296SNick Mathewson 			return -1;
26220fda296SNick Mathewson 		n = read(fd, buf, sizeof(buf));
26320fda296SNick Mathewson 		close(fd);
26420fda296SNick Mathewson 		if (n<=0)
26520fda296SNick Mathewson 			return -1;
26620fda296SNick Mathewson 		memset(entropy, 0, sizeof(entropy));
26720fda296SNick Mathewson 		for (i=nybbles=0; i<n; ++i) {
2688ac3c4c2SNick Mathewson 			if (EVUTIL_ISXDIGIT_(buf[i])) {
2698ac3c4c2SNick Mathewson 				int nyb = evutil_hex_char_to_int_(buf[i]);
27020fda296SNick Mathewson 				if (nybbles & 1) {
27120fda296SNick Mathewson 					entropy[nybbles/2] |= nyb;
27220fda296SNick Mathewson 				} else {
27320fda296SNick Mathewson 					entropy[nybbles/2] |= nyb<<4;
27420fda296SNick Mathewson 				}
27520fda296SNick Mathewson 				++nybbles;
27620fda296SNick Mathewson 			}
27720fda296SNick Mathewson 		}
27820fda296SNick Mathewson 		if (nybbles < 2)
27920fda296SNick Mathewson 			return -1;
28020fda296SNick Mathewson 		arc4_addrandom(entropy, nybbles/2);
28120fda296SNick Mathewson 		bytes += nybbles/2;
28220fda296SNick Mathewson 	}
283f5ced88cSNick Mathewson 	evutil_memclear_(entropy, sizeof(entropy));
284f5ced88cSNick Mathewson 	evutil_memclear_(buf, sizeof(buf));
28520fda296SNick Mathewson 	return 0;
28620fda296SNick Mathewson }
28771fc3eb0SNick Mathewson #endif
28871fc3eb0SNick Mathewson 
2899f560bfaSNick Mathewson #ifndef _WIN32
29071fc3eb0SNick Mathewson #define TRY_SEED_URANDOM
2912bbb5d76SNick Mathewson static char *arc4random_urandom_filename = NULL;
2922bbb5d76SNick Mathewson 
arc4_seed_urandom_helper_(const char * fname)2932bbb5d76SNick Mathewson static int arc4_seed_urandom_helper_(const char *fname)
29471fc3eb0SNick Mathewson {
29571fc3eb0SNick Mathewson 	unsigned char buf[ADD_ENTROPY];
2962bbb5d76SNick Mathewson 	int fd;
29771fc3eb0SNick Mathewson 	size_t n;
29871fc3eb0SNick Mathewson 
299f391b003SNick Mathewson 	fd = evutil_open_closeonexec_(fname, O_RDONLY, 0);
300d4de062eSNick Mathewson 	if (fd<0)
3012bbb5d76SNick Mathewson 		return -1;
302d4de062eSNick Mathewson 	n = read_all(fd, buf, sizeof(buf));
303d4de062eSNick Mathewson 	close(fd);
304d4de062eSNick Mathewson 	if (n != sizeof(buf))
305d4de062eSNick Mathewson 		return -1;
306d4de062eSNick Mathewson 	arc4_addrandom(buf, sizeof(buf));
307f5ced88cSNick Mathewson 	evutil_memclear_(buf, sizeof(buf));
308d4de062eSNick Mathewson 	return 0;
309d4de062eSNick Mathewson }
310d4de062eSNick Mathewson 
3112bbb5d76SNick Mathewson static int
arc4_seed_urandom(void)3122bbb5d76SNick Mathewson arc4_seed_urandom(void)
3132bbb5d76SNick Mathewson {
3142bbb5d76SNick Mathewson 	/* This is adapted from Tor's crypto_seed_rng() */
3152bbb5d76SNick Mathewson 	static const char *filenames[] = {
3162bbb5d76SNick Mathewson 		"/dev/srandom", "/dev/urandom", "/dev/random", NULL
3172bbb5d76SNick Mathewson 	};
3182bbb5d76SNick Mathewson 	int i;
3192bbb5d76SNick Mathewson 	if (arc4random_urandom_filename)
3202bbb5d76SNick Mathewson 		return arc4_seed_urandom_helper_(arc4random_urandom_filename);
3212bbb5d76SNick Mathewson 
3222bbb5d76SNick Mathewson 	for (i = 0; filenames[i]; ++i) {
3239695e9c1SNick Mathewson 		if (arc4_seed_urandom_helper_(filenames[i]) == 0) {
3242bbb5d76SNick Mathewson 			return 0;
3252bbb5d76SNick Mathewson 		}
3269695e9c1SNick Mathewson 	}
3272bbb5d76SNick Mathewson 
328d4de062eSNick Mathewson 	return -1;
32971fc3eb0SNick Mathewson }
330d4de062eSNick Mathewson #endif
33171fc3eb0SNick Mathewson 
33271fc3eb0SNick Mathewson static int
arc4_seed(void)33371fc3eb0SNick Mathewson arc4_seed(void)
33471fc3eb0SNick Mathewson {
33571fc3eb0SNick Mathewson 	int ok = 0;
33671fc3eb0SNick Mathewson 	/* We try every method that might work, and don't give up even if one
33771fc3eb0SNick Mathewson 	 * does seem to work.  There's no real harm in over-seeding, and if
33871fc3eb0SNick Mathewson 	 * one of these sources turns out to be broken, that would be bad. */
33971fc3eb0SNick Mathewson #ifdef TRY_SEED_WIN32
34071fc3eb0SNick Mathewson 	if (0 == arc4_seed_win32())
34171fc3eb0SNick Mathewson 		ok = 1;
34271fc3eb0SNick Mathewson #endif
343*66ec78fdSAzat Khuzhin #ifdef TRY_SEED_GETRANDOM
344*66ec78fdSAzat Khuzhin 	if (0 == arc4_seed_getrandom())
345*66ec78fdSAzat Khuzhin 		ok = 1;
346*66ec78fdSAzat Khuzhin #endif
34720fda296SNick Mathewson #ifdef TRY_SEED_URANDOM
34820fda296SNick Mathewson 	if (0 == arc4_seed_urandom())
34920fda296SNick Mathewson 		ok = 1;
35020fda296SNick Mathewson #endif
35190d42251SNick Mathewson #ifdef TRY_SEED_PROC_SYS_KERNEL_RANDOM_UUID
3529695e9c1SNick Mathewson 	if (arc4random_urandom_filename == NULL &&
3539695e9c1SNick Mathewson 	    0 == arc4_seed_proc_sys_kernel_random_uuid())
35420fda296SNick Mathewson 		ok = 1;
35520fda296SNick Mathewson #endif
35671fc3eb0SNick Mathewson #ifdef TRY_SEED_SYSCTL_BSD
35771fc3eb0SNick Mathewson 	if (0 == arc4_seed_sysctl_bsd())
35871fc3eb0SNick Mathewson 		ok = 1;
35971fc3eb0SNick Mathewson #endif
36071fc3eb0SNick Mathewson 	return ok ? 0 : -1;
361d4de062eSNick Mathewson }
362d4de062eSNick Mathewson 
363f7361980SNick Mathewson static int
arc4_stir(void)364d4de062eSNick Mathewson arc4_stir(void)
365d4de062eSNick Mathewson {
366d4de062eSNick Mathewson 	int     i;
367d4de062eSNick Mathewson 
368d4de062eSNick Mathewson 	if (!rs_initialized) {
369d4de062eSNick Mathewson 		arc4_init();
370d4de062eSNick Mathewson 		rs_initialized = 1;
371d4de062eSNick Mathewson 	}
372d4de062eSNick Mathewson 
37391084140SNathan French 	if (0 != arc4_seed())
37491084140SNathan French 		return -1;
37591084140SNathan French 
376d4de062eSNick Mathewson 	/*
377d4de062eSNick Mathewson 	 * Discard early keystream, as per recommendations in
378d4de062eSNick Mathewson 	 * "Weaknesses in the Key Scheduling Algorithm of RC4" by
379d4de062eSNick Mathewson 	 * Scott Fluhrer, Itsik Mantin, and Adi Shamir.
380d4de062eSNick Mathewson 	 * http://www.wisdom.weizmann.ac.il/~itsik/RC4/Papers/Rc4_ksa.ps
381d4de062eSNick Mathewson 	 *
382d4de062eSNick Mathewson 	 * Ilya Mironov's "(Not So) Random Shuffles of RC4" suggests that
383d4de062eSNick Mathewson 	 * we drop at least 2*256 bytes, with 12*256 as a conservative
384d4de062eSNick Mathewson 	 * value.
385d4de062eSNick Mathewson 	 *
386d4de062eSNick Mathewson 	 * RFC4345 says to drop 6*256.
387d4de062eSNick Mathewson 	 *
388d4de062eSNick Mathewson 	 * At least some versions of this code drop 4*256, in a mistaken
389d4de062eSNick Mathewson 	 * belief that "words" in the Fluhrer/Mantin/Shamir paper refers
390d4de062eSNick Mathewson 	 * to processor words.
391d4de062eSNick Mathewson 	 *
392d4de062eSNick Mathewson 	 * We add another sect to the cargo cult, and choose 12*256.
393d4de062eSNick Mathewson 	 */
394d4de062eSNick Mathewson 	for (i = 0; i < 12*256; i++)
395d4de062eSNick Mathewson 		(void)arc4_getbyte();
396e35b5408SNick Mathewson 
397d4de062eSNick Mathewson 	arc4_count = BYTES_BEFORE_RESEED;
398f7361980SNick Mathewson 
399f7361980SNick Mathewson 	return 0;
400d4de062eSNick Mathewson }
401d4de062eSNick Mathewson 
402ff2a134dSNick Mathewson 
403d4de062eSNick Mathewson static void
arc4_stir_if_needed(void)404d4de062eSNick Mathewson arc4_stir_if_needed(void)
405d4de062eSNick Mathewson {
406d4de062eSNick Mathewson 	pid_t pid = getpid();
407d4de062eSNick Mathewson 
408d4de062eSNick Mathewson 	if (arc4_count <= 0 || !rs_initialized || arc4_stir_pid != pid)
409d4de062eSNick Mathewson 	{
410d4de062eSNick Mathewson 		arc4_stir_pid = pid;
411d4de062eSNick Mathewson 		arc4_stir();
412d4de062eSNick Mathewson 	}
413d4de062eSNick Mathewson }
414d4de062eSNick Mathewson 
415d4de062eSNick Mathewson static inline unsigned char
arc4_getbyte(void)416d4de062eSNick Mathewson arc4_getbyte(void)
417d4de062eSNick Mathewson {
418d4de062eSNick Mathewson 	unsigned char si, sj;
419d4de062eSNick Mathewson 
420d4de062eSNick Mathewson 	rs.i = (rs.i + 1);
421d4de062eSNick Mathewson 	si = rs.s[rs.i];
422d4de062eSNick Mathewson 	rs.j = (rs.j + si);
423d4de062eSNick Mathewson 	sj = rs.s[rs.j];
424d4de062eSNick Mathewson 	rs.s[rs.i] = sj;
425d4de062eSNick Mathewson 	rs.s[rs.j] = si;
426d4de062eSNick Mathewson 	return (rs.s[(si + sj) & 0xff]);
427d4de062eSNick Mathewson }
428d4de062eSNick Mathewson 
429d4de062eSNick Mathewson static inline unsigned int
arc4_getword(void)430d4de062eSNick Mathewson arc4_getword(void)
431d4de062eSNick Mathewson {
432d4de062eSNick Mathewson 	unsigned int val;
433d4de062eSNick Mathewson 
434d4de062eSNick Mathewson 	val = arc4_getbyte() << 24;
435d4de062eSNick Mathewson 	val |= arc4_getbyte() << 16;
436d4de062eSNick Mathewson 	val |= arc4_getbyte() << 8;
437d4de062eSNick Mathewson 	val |= arc4_getbyte();
438d4de062eSNick Mathewson 
439d4de062eSNick Mathewson 	return val;
440d4de062eSNick Mathewson }
441d4de062eSNick Mathewson 
442d4de062eSNick Mathewson #ifndef ARC4RANDOM_NOSTIR
443d4de062eSNick Mathewson ARC4RANDOM_EXPORT int
arc4random_stir(void)444d4de062eSNick Mathewson arc4random_stir(void)
445d4de062eSNick Mathewson {
446d4de062eSNick Mathewson 	int val;
447cb9da0bfSNick Mathewson 	ARC4_LOCK_();
448d4de062eSNick Mathewson 	val = arc4_stir();
449cb9da0bfSNick Mathewson 	ARC4_UNLOCK_();
450d4de062eSNick Mathewson 	return val;
451d4de062eSNick Mathewson }
452d4de062eSNick Mathewson #endif
453d4de062eSNick Mathewson 
454d4de062eSNick Mathewson #ifndef ARC4RANDOM_NOADDRANDOM
455d4de062eSNick Mathewson ARC4RANDOM_EXPORT void
arc4random_addrandom(const unsigned char * dat,int datlen)456d4de062eSNick Mathewson arc4random_addrandom(const unsigned char *dat, int datlen)
457d4de062eSNick Mathewson {
458d4de062eSNick Mathewson 	int j;
459cb9da0bfSNick Mathewson 	ARC4_LOCK_();
460d4de062eSNick Mathewson 	if (!rs_initialized)
461d4de062eSNick Mathewson 		arc4_stir();
462d4de062eSNick Mathewson 	for (j = 0; j < datlen; j += 256) {
463d4de062eSNick Mathewson 		/* arc4_addrandom() ignores all but the first 256 bytes of
464d4de062eSNick Mathewson 		 * its input.  We want to make sure to look at ALL the
465d4de062eSNick Mathewson 		 * data in 'dat', just in case the user is doing something
466d4de062eSNick Mathewson 		 * crazy like passing us all the files in /var/log. */
467d4de062eSNick Mathewson 		arc4_addrandom(dat + j, datlen - j);
468d4de062eSNick Mathewson 	}
469cb9da0bfSNick Mathewson 	ARC4_UNLOCK_();
470d4de062eSNick Mathewson }
471d4de062eSNick Mathewson #endif
472d4de062eSNick Mathewson 
473d4de062eSNick Mathewson #ifndef ARC4RANDOM_NORANDOM
4744ec8fea6SNick Mathewson ARC4RANDOM_EXPORT ARC4RANDOM_UINT32
arc4random(void)475d4de062eSNick Mathewson arc4random(void)
476d4de062eSNick Mathewson {
4774ec8fea6SNick Mathewson 	ARC4RANDOM_UINT32 val;
478cb9da0bfSNick Mathewson 	ARC4_LOCK_();
479d4de062eSNick Mathewson 	arc4_count -= 4;
480d4de062eSNick Mathewson 	arc4_stir_if_needed();
481d4de062eSNick Mathewson 	val = arc4_getword();
482cb9da0bfSNick Mathewson 	ARC4_UNLOCK_();
483d4de062eSNick Mathewson 	return val;
484d4de062eSNick Mathewson }
485d4de062eSNick Mathewson #endif
486d4de062eSNick Mathewson 
487d4de062eSNick Mathewson ARC4RANDOM_EXPORT void
arc4random_buf(void * buf_,size_t n)488946b5841SNick Mathewson arc4random_buf(void *buf_, size_t n)
489d4de062eSNick Mathewson {
490946b5841SNick Mathewson 	unsigned char *buf = buf_;
491cb9da0bfSNick Mathewson 	ARC4_LOCK_();
492d4de062eSNick Mathewson 	arc4_stir_if_needed();
493d4de062eSNick Mathewson 	while (n--) {
494d4de062eSNick Mathewson 		if (--arc4_count <= 0)
495d4de062eSNick Mathewson 			arc4_stir();
496d4de062eSNick Mathewson 		buf[n] = arc4_getbyte();
497d4de062eSNick Mathewson 	}
498cb9da0bfSNick Mathewson 	ARC4_UNLOCK_();
499d4de062eSNick Mathewson }
500d4de062eSNick Mathewson 
501d4de062eSNick Mathewson #ifndef ARC4RANDOM_NOUNIFORM
502d4de062eSNick Mathewson /*
503d4de062eSNick Mathewson  * Calculate a uniformly distributed random number less than upper_bound
504d4de062eSNick Mathewson  * avoiding "modulo bias".
505d4de062eSNick Mathewson  *
506d4de062eSNick Mathewson  * Uniformity is achieved by generating new random numbers until the one
507d4de062eSNick Mathewson  * returned is outside the range [0, 2**32 % upper_bound).  This
508d4de062eSNick Mathewson  * guarantees the selected random number will be inside
509d4de062eSNick Mathewson  * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
510d4de062eSNick Mathewson  * after reduction modulo upper_bound.
511d4de062eSNick Mathewson  */
512d4de062eSNick Mathewson ARC4RANDOM_EXPORT unsigned int
arc4random_uniform(unsigned int upper_bound)513d4de062eSNick Mathewson arc4random_uniform(unsigned int upper_bound)
514d4de062eSNick Mathewson {
5154ec8fea6SNick Mathewson 	ARC4RANDOM_UINT32 r, min;
516d4de062eSNick Mathewson 
517d4de062eSNick Mathewson 	if (upper_bound < 2)
518d4de062eSNick Mathewson 		return 0;
519d4de062eSNick Mathewson 
520d4de062eSNick Mathewson #if (UINT_MAX > 0xffffffffUL)
521d4de062eSNick Mathewson 	min = 0x100000000UL % upper_bound;
522d4de062eSNick Mathewson #else
523d4de062eSNick Mathewson 	/* Calculate (2**32 % upper_bound) avoiding 64-bit math */
524d4de062eSNick Mathewson 	if (upper_bound > 0x80000000)
525d4de062eSNick Mathewson 		min = 1 + ~upper_bound;		/* 2**32 - upper_bound */
526d4de062eSNick Mathewson 	else {
527d4de062eSNick Mathewson 		/* (2**32 - (x * 2)) % x == 2**32 % x when x <= 2**31 */
528d4de062eSNick Mathewson 		min = ((0xffffffff - (upper_bound * 2)) + 1) % upper_bound;
529d4de062eSNick Mathewson 	}
530d4de062eSNick Mathewson #endif
531d4de062eSNick Mathewson 
532d4de062eSNick Mathewson 	/*
533d4de062eSNick Mathewson 	 * This could theoretically loop forever but each retry has
534d4de062eSNick Mathewson 	 * p > 0.5 (worst case, usually far better) of selecting a
535d4de062eSNick Mathewson 	 * number inside the range we need, so it should rarely need
536d4de062eSNick Mathewson 	 * to re-roll.
537d4de062eSNick Mathewson 	 */
538d4de062eSNick Mathewson 	for (;;) {
539d4de062eSNick Mathewson 		r = arc4random();
540d4de062eSNick Mathewson 		if (r >= min)
541d4de062eSNick Mathewson 			break;
542d4de062eSNick Mathewson 	}
543d4de062eSNick Mathewson 
544d4de062eSNick Mathewson 	return r % upper_bound;
545d4de062eSNick Mathewson }
546d4de062eSNick Mathewson #endif
547