xref: /netbsd-src/external/bsd/ntp/dist/sntp/libevent/arc4random.c (revision 6a493d6bc668897c91594964a732d38505b70cbb)
1 /*	$NetBSD: arc4random.c,v 1.1.1.1 2013/12/27 23:31:19 christos Exp $	*/
2 
3 /* Portable arc4random.c based on arc4random.c from OpenBSD.
4  * Portable version by Chris Davis, adapted for Libevent by Nick Mathewson
5  * Copyright (c) 2010 Chris Davis, Niels Provos, and Nick Mathewson
6  * Copyright (c) 2010-2012 Niels Provos and Nick Mathewson
7  *
8  * Note that in Libevent, this file isn't compiled directly.  Instead,
9  * it's included from evutil_rand.c
10  */
11 
12 /*
13  * Copyright (c) 1996, David Mazieres <dm@uun.org>
14  * Copyright (c) 2008, Damien Miller <djm@openbsd.org>
15  *
16  * Permission to use, copy, modify, and distribute this software for any
17  * purpose with or without fee is hereby granted, provided that the above
18  * copyright notice and this permission notice appear in all copies.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
21  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
22  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
23  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
24  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
25  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
26  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
27  */
28 
29 /*
30  * Arc4 random number generator for OpenBSD.
31  *
32  * This code is derived from section 17.1 of Applied Cryptography,
33  * second edition, which describes a stream cipher allegedly
34  * compatible with RSA Labs "RC4" cipher (the actual description of
35  * which is a trade secret).  The same algorithm is used as a stream
36  * cipher called "arcfour" in Tatu Ylonen's ssh package.
37  *
38  * Here the stream cipher has been modified always to include the time
39  * when initializing the state.  That makes it impossible to
40  * regenerate the same random sequence twice, so this can't be used
41  * for encryption, but will generate good random numbers.
42  *
43  * RC4 is a registered trademark of RSA Laboratories.
44  */
45 
46 #ifndef ARC4RANDOM_EXPORT
47 #define ARC4RANDOM_EXPORT
48 #endif
49 
50 #ifndef ARC4RANDOM_UINT32
51 #define ARC4RANDOM_UINT32 uint32_t
52 #endif
53 
54 #ifndef ARC4RANDOM_NO_INCLUDES
55 #include "evconfig-private.h"
56 #ifdef _WIN32
57 #include <wincrypt.h>
58 #include <process.h>
59 #else
60 #include <fcntl.h>
61 #include <unistd.h>
62 #include <sys/param.h>
63 #include <sys/time.h>
64 #ifdef EVENT__HAVE_SYS_SYSCTL_H
65 #include <sys/sysctl.h>
66 #endif
67 #endif
68 #include <limits.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #endif
72 
73 /* Add platform entropy 32 bytes (256 bits) at a time. */
74 #define ADD_ENTROPY 32
75 
76 /* Re-seed from the platform RNG after generating this many bytes. */
77 #define BYTES_BEFORE_RESEED 1600000
78 
79 struct arc4_stream {
80 	unsigned char i;
81 	unsigned char j;
82 	unsigned char s[256];
83 };
84 
85 #ifdef _WIN32
86 #define getpid _getpid
87 #define pid_t int
88 #endif
89 
90 static int rs_initialized;
91 static struct arc4_stream rs;
92 static pid_t arc4_stir_pid;
93 static int arc4_count;
94 static int arc4_seeded_ok;
95 
96 static inline unsigned char arc4_getbyte(void);
97 
98 static inline void
99 arc4_init(void)
100 {
101 	int     n;
102 
103 	for (n = 0; n < 256; n++)
104 		rs.s[n] = n;
105 	rs.i = 0;
106 	rs.j = 0;
107 }
108 
109 static inline void
110 arc4_addrandom(const unsigned char *dat, int datlen)
111 {
112 	int     n;
113 	unsigned char si;
114 
115 	rs.i--;
116 	for (n = 0; n < 256; n++) {
117 		rs.i = (rs.i + 1);
118 		si = rs.s[rs.i];
119 		rs.j = (rs.j + si + dat[n % datlen]);
120 		rs.s[rs.i] = rs.s[rs.j];
121 		rs.s[rs.j] = si;
122 	}
123 	rs.j = rs.i;
124 }
125 
126 #ifndef _WIN32
127 static ssize_t
128 read_all(int fd, unsigned char *buf, size_t count)
129 {
130 	size_t numread = 0;
131 	ssize_t result;
132 
133 	while (numread < count) {
134 		result = read(fd, buf+numread, count-numread);
135 		if (result<0)
136 			return -1;
137 		else if (result == 0)
138 			break;
139 		numread += result;
140 	}
141 
142 	return (ssize_t)numread;
143 }
144 #endif
145 
146 #ifdef _WIN32
147 #define TRY_SEED_WIN32
148 static int
149 arc4_seed_win32(void)
150 {
151 	/* This is adapted from Tor's crypto_seed_rng() */
152 	static int provider_set = 0;
153 	static HCRYPTPROV provider;
154 	unsigned char buf[ADD_ENTROPY];
155 
156 	if (!provider_set) {
157 		if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
158 		    CRYPT_VERIFYCONTEXT)) {
159 			if (GetLastError() != (DWORD)NTE_BAD_KEYSET)
160 				return -1;
161 		}
162 		provider_set = 1;
163 	}
164 	if (!CryptGenRandom(provider, sizeof(buf), buf))
165 		return -1;
166 	arc4_addrandom(buf, sizeof(buf));
167 	memset(buf, 0, sizeof(buf));
168 	arc4_seeded_ok = 1;
169 	return 0;
170 }
171 #endif
172 
173 #if defined(EVENT__HAVE_SYS_SYSCTL_H) && defined(EVENT__HAVE_SYSCTL)
174 #if EVENT__HAVE_DECL_CTL_KERN && EVENT__HAVE_DECL_KERN_RANDOM && EVENT__HAVE_DECL_RANDOM_UUID
175 #define TRY_SEED_SYSCTL_LINUX
176 static int
177 arc4_seed_sysctl_linux(void)
178 {
179 	/* Based on code by William Ahern, this function tries to use the
180 	 * RANDOM_UUID sysctl to get entropy from the kernel.  This can work
181 	 * even if /dev/urandom is inaccessible for some reason (e.g., we're
182 	 * running in a chroot). */
183 	int mib[] = { CTL_KERN, KERN_RANDOM, RANDOM_UUID };
184 	unsigned char buf[ADD_ENTROPY];
185 	size_t len, n;
186 	unsigned i;
187 	int any_set;
188 
189 	memset(buf, 0, sizeof(buf));
190 
191 	for (len = 0; len < sizeof(buf); len += n) {
192 		n = sizeof(buf) - len;
193 
194 		if (0 != sysctl(mib, 3, &buf[len], &n, NULL, 0))
195 			return -1;
196 	}
197 	/* make sure that the buffer actually got set. */
198 	for (i=0,any_set=0; i<sizeof(buf); ++i) {
199 		any_set |= buf[i];
200 	}
201 	if (!any_set)
202 		return -1;
203 
204 	arc4_addrandom(buf, sizeof(buf));
205 	memset(buf, 0, sizeof(buf));
206 	arc4_seeded_ok = 1;
207 	return 0;
208 }
209 #endif
210 
211 #if EVENT__HAVE_DECL_CTL_KERN && EVENT__HAVE_DECL_KERN_ARND
212 #define TRY_SEED_SYSCTL_BSD
213 static int
214 arc4_seed_sysctl_bsd(void)
215 {
216 	/* Based on code from William Ahern and from OpenBSD, this function
217 	 * tries to use the KERN_ARND syscall to get entropy from the kernel.
218 	 * This can work even if /dev/urandom is inaccessible for some reason
219 	 * (e.g., we're running in a chroot). */
220 	int mib[] = { CTL_KERN, KERN_ARND };
221 	unsigned char buf[ADD_ENTROPY];
222 	size_t len, n;
223 	int i, any_set;
224 
225 	memset(buf, 0, sizeof(buf));
226 
227 	len = sizeof(buf);
228 	if (sysctl(mib, 2, buf, &len, NULL, 0) == -1) {
229 		for (len = 0; len < sizeof(buf); len += sizeof(unsigned)) {
230 			n = sizeof(unsigned);
231 			if (n + len > sizeof(buf))
232 			    n = len - sizeof(buf);
233 			if (sysctl(mib, 2, &buf[len], &n, NULL, 0) == -1)
234 				return -1;
235 		}
236 	}
237 	/* make sure that the buffer actually got set. */
238 	for (i=any_set=0; i<sizeof(buf); ++i) {
239 		any_set |= buf[i];
240 	}
241 	if (!any_set)
242 		return -1;
243 
244 	arc4_addrandom(buf, sizeof(buf));
245 	memset(buf, 0, sizeof(buf));
246 	arc4_seeded_ok = 1;
247 	return 0;
248 }
249 #endif
250 #endif /* defined(EVENT__HAVE_SYS_SYSCTL_H) */
251 
252 #ifdef __linux__
253 #define TRY_SEED_PROC_SYS_KERNEL_RANDOM_UUID
254 static int
255 arc4_seed_proc_sys_kernel_random_uuid(void)
256 {
257 	/* Occasionally, somebody will make /proc/sys accessible in a chroot,
258 	 * but not /dev/urandom.  Let's try /proc/sys/kernel/random/uuid.
259 	 * Its format is stupid, so we need to decode it from hex.
260 	 */
261 	int fd;
262 	char buf[128];
263 	unsigned char entropy[64];
264 	int bytes, n, i, nybbles;
265 	for (bytes = 0; bytes<ADD_ENTROPY; ) {
266 		fd = evutil_open_closeonexec_("/proc/sys/kernel/random/uuid", O_RDONLY, 0);
267 		if (fd < 0)
268 			return -1;
269 		n = read(fd, buf, sizeof(buf));
270 		close(fd);
271 		if (n<=0)
272 			return -1;
273 		memset(entropy, 0, sizeof(entropy));
274 		for (i=nybbles=0; i<n; ++i) {
275 			if (EVUTIL_ISXDIGIT_(buf[i])) {
276 				int nyb = evutil_hex_char_to_int_(buf[i]);
277 				if (nybbles & 1) {
278 					entropy[nybbles/2] |= nyb;
279 				} else {
280 					entropy[nybbles/2] |= nyb<<4;
281 				}
282 				++nybbles;
283 			}
284 		}
285 		if (nybbles < 2)
286 			return -1;
287 		arc4_addrandom(entropy, nybbles/2);
288 		bytes += nybbles/2;
289 	}
290 	memset(entropy, 0, sizeof(entropy));
291 	memset(buf, 0, sizeof(buf));
292 	return 0;
293 }
294 #endif
295 
296 #ifndef _WIN32
297 #define TRY_SEED_URANDOM
298 static int
299 arc4_seed_urandom(void)
300 {
301 	/* This is adapted from Tor's crypto_seed_rng() */
302 	static const char *filenames[] = {
303 		"/dev/srandom", "/dev/urandom", "/dev/random", NULL
304 	};
305 	unsigned char buf[ADD_ENTROPY];
306 	int fd, i;
307 	size_t n;
308 
309 	for (i = 0; filenames[i]; ++i) {
310 		fd = evutil_open_closeonexec_(filenames[i], O_RDONLY, 0);
311 		if (fd<0)
312 			continue;
313 		n = read_all(fd, buf, sizeof(buf));
314 		close(fd);
315 		if (n != sizeof(buf))
316 			return -1;
317 		arc4_addrandom(buf, sizeof(buf));
318 		memset(buf, 0, sizeof(buf));
319 		arc4_seeded_ok = 1;
320 		return 0;
321 	}
322 
323 	return -1;
324 }
325 #endif
326 
327 static int
328 arc4_seed(void)
329 {
330 	int ok = 0;
331 	/* We try every method that might work, and don't give up even if one
332 	 * does seem to work.  There's no real harm in over-seeding, and if
333 	 * one of these sources turns out to be broken, that would be bad. */
334 #ifdef TRY_SEED_WIN32
335 	if (0 == arc4_seed_win32())
336 		ok = 1;
337 #endif
338 #ifdef TRY_SEED_URANDOM
339 	if (0 == arc4_seed_urandom())
340 		ok = 1;
341 #endif
342 #ifdef TRY_SEED_PROC_SYS_KERNEL_RANDOM_UUID
343 	if (0 == arc4_seed_proc_sys_kernel_random_uuid())
344 		ok = 1;
345 #endif
346 #ifdef TRY_SEED_SYSCTL_LINUX
347 	/* Apparently Linux is deprecating sysctl, and spewing warning
348 	 * messages when you try to use it. */
349 	if (!ok && 0 == arc4_seed_sysctl_linux())
350 		ok = 1;
351 #endif
352 #ifdef TRY_SEED_SYSCTL_BSD
353 	if (0 == arc4_seed_sysctl_bsd())
354 		ok = 1;
355 #endif
356 	return ok ? 0 : -1;
357 }
358 
359 static int
360 arc4_stir(void)
361 {
362 	int     i;
363 
364 	if (!rs_initialized) {
365 		arc4_init();
366 		rs_initialized = 1;
367 	}
368 
369 	arc4_seed();
370 	if (!arc4_seeded_ok)
371 		return -1;
372 
373 	/*
374 	 * Discard early keystream, as per recommendations in
375 	 * "Weaknesses in the Key Scheduling Algorithm of RC4" by
376 	 * Scott Fluhrer, Itsik Mantin, and Adi Shamir.
377 	 * http://www.wisdom.weizmann.ac.il/~itsik/RC4/Papers/Rc4_ksa.ps
378 	 *
379 	 * Ilya Mironov's "(Not So) Random Shuffles of RC4" suggests that
380 	 * we drop at least 2*256 bytes, with 12*256 as a conservative
381 	 * value.
382 	 *
383 	 * RFC4345 says to drop 6*256.
384 	 *
385 	 * At least some versions of this code drop 4*256, in a mistaken
386 	 * belief that "words" in the Fluhrer/Mantin/Shamir paper refers
387 	 * to processor words.
388 	 *
389 	 * We add another sect to the cargo cult, and choose 12*256.
390 	 */
391 	for (i = 0; i < 12*256; i++)
392 		(void)arc4_getbyte();
393 	arc4_count = BYTES_BEFORE_RESEED;
394 
395 	return 0;
396 }
397 
398 
399 static void
400 arc4_stir_if_needed(void)
401 {
402 	pid_t pid = getpid();
403 
404 	if (arc4_count <= 0 || !rs_initialized || arc4_stir_pid != pid)
405 	{
406 		arc4_stir_pid = pid;
407 		arc4_stir();
408 	}
409 }
410 
411 static inline unsigned char
412 arc4_getbyte(void)
413 {
414 	unsigned char si, sj;
415 
416 	rs.i = (rs.i + 1);
417 	si = rs.s[rs.i];
418 	rs.j = (rs.j + si);
419 	sj = rs.s[rs.j];
420 	rs.s[rs.i] = sj;
421 	rs.s[rs.j] = si;
422 	return (rs.s[(si + sj) & 0xff]);
423 }
424 
425 static inline unsigned int
426 arc4_getword(void)
427 {
428 	unsigned int val;
429 
430 	val = arc4_getbyte() << 24;
431 	val |= arc4_getbyte() << 16;
432 	val |= arc4_getbyte() << 8;
433 	val |= arc4_getbyte();
434 
435 	return val;
436 }
437 
438 #ifndef ARC4RANDOM_NOSTIR
439 ARC4RANDOM_EXPORT int
440 arc4random_stir(void)
441 {
442 	int val;
443 	ARC4_LOCK_();
444 	val = arc4_stir();
445 	ARC4_UNLOCK_();
446 	return val;
447 }
448 #endif
449 
450 #ifndef ARC4RANDOM_NOADDRANDOM
451 ARC4RANDOM_EXPORT void
452 arc4random_addrandom(const unsigned char *dat, int datlen)
453 {
454 	int j;
455 	ARC4_LOCK_();
456 	if (!rs_initialized)
457 		arc4_stir();
458 	for (j = 0; j < datlen; j += 256) {
459 		/* arc4_addrandom() ignores all but the first 256 bytes of
460 		 * its input.  We want to make sure to look at ALL the
461 		 * data in 'dat', just in case the user is doing something
462 		 * crazy like passing us all the files in /var/log. */
463 		arc4_addrandom(dat + j, datlen - j);
464 	}
465 	ARC4_UNLOCK_();
466 }
467 #endif
468 
469 #ifndef ARC4RANDOM_NORANDOM
470 ARC4RANDOM_EXPORT ARC4RANDOM_UINT32
471 arc4random(void)
472 {
473 	ARC4RANDOM_UINT32 val;
474 	ARC4_LOCK_();
475 	arc4_count -= 4;
476 	arc4_stir_if_needed();
477 	val = arc4_getword();
478 	ARC4_UNLOCK_();
479 	return val;
480 }
481 #endif
482 
483 ARC4RANDOM_EXPORT void
484 arc4random_buf(void *buf_, size_t n)
485 {
486 	unsigned char *buf = buf_;
487 	ARC4_LOCK_();
488 	arc4_stir_if_needed();
489 	while (n--) {
490 		if (--arc4_count <= 0)
491 			arc4_stir();
492 		buf[n] = arc4_getbyte();
493 	}
494 	ARC4_UNLOCK_();
495 }
496 
497 #ifndef ARC4RANDOM_NOUNIFORM
498 /*
499  * Calculate a uniformly distributed random number less than upper_bound
500  * avoiding "modulo bias".
501  *
502  * Uniformity is achieved by generating new random numbers until the one
503  * returned is outside the range [0, 2**32 % upper_bound).  This
504  * guarantees the selected random number will be inside
505  * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
506  * after reduction modulo upper_bound.
507  */
508 ARC4RANDOM_EXPORT unsigned int
509 arc4random_uniform(unsigned int upper_bound)
510 {
511 	ARC4RANDOM_UINT32 r, min;
512 
513 	if (upper_bound < 2)
514 		return 0;
515 
516 #if (UINT_MAX > 0xffffffffUL)
517 	min = 0x100000000UL % upper_bound;
518 #else
519 	/* Calculate (2**32 % upper_bound) avoiding 64-bit math */
520 	if (upper_bound > 0x80000000)
521 		min = 1 + ~upper_bound;		/* 2**32 - upper_bound */
522 	else {
523 		/* (2**32 - (x * 2)) % x == 2**32 % x when x <= 2**31 */
524 		min = ((0xffffffff - (upper_bound * 2)) + 1) % upper_bound;
525 	}
526 #endif
527 
528 	/*
529 	 * This could theoretically loop forever but each retry has
530 	 * p > 0.5 (worst case, usually far better) of selecting a
531 	 * number inside the range we need, so it should rarely need
532 	 * to re-roll.
533 	 */
534 	for (;;) {
535 		r = arc4random();
536 		if (r >= min)
537 			break;
538 	}
539 
540 	return r % upper_bound;
541 }
542 #endif
543