]> arthur.barton.de Git - netatalk.git/blob - libevent/arc4random.c
Add libevent
[netatalk.git] / libevent / arc4random.c
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  *
5  * Note that in Libevent, this file isn't compiled directly.  Instead,
6  * it's included from evutil_rand.c
7  */
8
9 /*
10  * Copyright (c) 1996, David Mazieres <dm@uun.org>
11  * Copyright (c) 2008, Damien Miller <djm@openbsd.org>
12  *
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.
16  *
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.
24  */
25
26 /*
27  * Arc4 random number generator for OpenBSD.
28  *
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.
34  *
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.
39  *
40  * RC4 is a registered trademark of RSA Laboratories.
41  */
42
43 #ifndef ARC4RANDOM_EXPORT
44 #define ARC4RANDOM_EXPORT
45 #endif
46
47 #ifndef ARC4RANDOM_UINT32
48 #define ARC4RANDOM_UINT32 uint32_t
49 #endif
50
51 #ifndef ARC4RANDOM_NO_INCLUDES
52 #ifdef WIN32
53 #include <wincrypt.h>
54 #include <process.h>
55 #else
56 #include <fcntl.h>
57 #include <unistd.h>
58 #include <sys/param.h>
59 #include <sys/time.h>
60 #ifdef _EVENT_HAVE_SYS_SYSCTL_H
61 #include <sys/sysctl.h>
62 #endif
63 #endif
64 #include <limits.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #endif
68
69 /* Add platform entropy 32 bytes (256 bits) at a time. */
70 #define ADD_ENTROPY 32
71
72 /* Re-seed from the platform RNG after generating this many bytes. */
73 #define BYTES_BEFORE_RESEED 1600000
74
75 struct arc4_stream {
76         unsigned char i;
77         unsigned char j;
78         unsigned char s[256];
79 };
80
81 #ifdef WIN32
82 #define getpid _getpid
83 #define pid_t int
84 #endif
85
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;
91
92 static inline unsigned char arc4_getbyte(void);
93
94 static inline void
95 arc4_init(void)
96 {
97         int     n;
98
99         for (n = 0; n < 256; n++)
100                 rs.s[n] = n;
101         rs.i = 0;
102         rs.j = 0;
103 }
104
105 static inline void
106 arc4_addrandom(const unsigned char *dat, int datlen)
107 {
108         int     n;
109         unsigned char si;
110
111         rs.i--;
112         for (n = 0; n < 256; n++) {
113                 rs.i = (rs.i + 1);
114                 si = rs.s[rs.i];
115                 rs.j = (rs.j + si + dat[n % datlen]);
116                 rs.s[rs.i] = rs.s[rs.j];
117                 rs.s[rs.j] = si;
118         }
119         rs.j = rs.i;
120 }
121
122 #ifndef WIN32
123 static ssize_t
124 read_all(int fd, unsigned char *buf, size_t count)
125 {
126         size_t numread = 0;
127         ssize_t result;
128
129         while (numread < count) {
130                 result = read(fd, buf+numread, count-numread);
131                 if (result<0)
132                         return -1;
133                 else if (result == 0)
134                         break;
135                 numread += result;
136         }
137
138         return (ssize_t)numread;
139 }
140 #endif
141
142 #ifdef WIN32
143 #define TRY_SEED_WIN32
144 static int
145 arc4_seed_win32(void)
146 {
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];
151
152         if (!provider_set) {
153                 if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
154                     CRYPT_VERIFYCONTEXT)) {
155                         if (GetLastError() != (DWORD)NTE_BAD_KEYSET)
156                                 return -1;
157                 }
158                 provider_set = 1;
159         }
160         if (!CryptGenRandom(provider, sizeof(buf), buf))
161                 return -1;
162         arc4_addrandom(buf, sizeof(buf));
163         memset(buf, 0, sizeof(buf));
164         arc4_seeded_ok = 1;
165         return 0;
166 }
167 #endif
168
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
172 static int
173 arc4_seed_sysctl_linux(void)
174 {
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];
181         size_t len, n;
182         unsigned i;
183         int any_set;
184
185         memset(buf, 0, sizeof(buf));
186
187         for (len = 0; len < sizeof(buf); len += n) {
188                 n = sizeof(buf) - len;
189
190                 if (0 != sysctl(mib, 3, &buf[len], &n, NULL, 0))
191                         return -1;
192         }
193         /* make sure that the buffer actually got set. */
194         for (i=0,any_set=0; i<sizeof(buf); ++i) {
195                 any_set |= buf[i];
196         }
197         if (!any_set)
198                 return -1;
199
200         arc4_addrandom(buf, sizeof(buf));
201         memset(buf, 0, sizeof(buf));
202         arc4_seeded_ok = 1;
203         return 0;
204 }
205 #endif
206
207 #if _EVENT_HAVE_DECL_CTL_KERN && _EVENT_HAVE_DECL_KERN_ARND
208 #define TRY_SEED_SYSCTL_BSD
209 static int
210 arc4_seed_sysctl_bsd(void)
211 {
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];
218         size_t len, n;
219         int i, any_set;
220
221         memset(buf, 0, sizeof(buf));
222
223         len = 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)
230                                 return -1;
231                 }
232         }
233         /* make sure that the buffer actually got set. */
234         for (i=any_set=0; i<sizeof(buf); ++i) {
235                 any_set |= buf[i];
236         }
237         if (!any_set)
238                 return -1;
239
240         arc4_addrandom(buf, sizeof(buf));
241         memset(buf, 0, sizeof(buf));
242         arc4_seeded_ok = 1;
243         return 0;
244 }
245 #endif
246 #endif /* defined(_EVENT_HAVE_SYS_SYSCTL_H) */
247
248 #ifdef __linux__
249 #define TRY_SEED_PROC_SYS_KERNEL_RANDOM_UUID
250 static int
251 arc4_seed_proc_sys_kernel_random_uuid(void)
252 {
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.
256          */
257         int fd;
258         char buf[128];
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);
263                 if (fd < 0)
264                         return -1;
265                 n = read(fd, buf, sizeof(buf));
266                 close(fd);
267                 if (n<=0)
268                         return -1;
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]);
273                                 if (nybbles & 1) {
274                                         entropy[nybbles/2] |= nyb;
275                                 } else {
276                                         entropy[nybbles/2] |= nyb<<4;
277                                 }
278                                 ++nybbles;
279                         }
280                 }
281                 if (nybbles < 2)
282                         return -1;
283                 arc4_addrandom(entropy, nybbles/2);
284                 bytes += nybbles/2;
285         }
286         memset(entropy, 0, sizeof(entropy));
287         memset(buf, 0, sizeof(buf));
288         return 0;
289 }
290 #endif
291
292 #ifndef WIN32
293 #define TRY_SEED_URANDOM
294 static int
295 arc4_seed_urandom(void)
296 {
297         /* This is adapted from Tor's crypto_seed_rng() */
298         static const char *filenames[] = {
299                 "/dev/srandom", "/dev/urandom", "/dev/random", NULL
300         };
301         unsigned char buf[ADD_ENTROPY];
302         int fd, i;
303         size_t n;
304
305         for (i = 0; filenames[i]; ++i) {
306                 fd = open(filenames[i], O_RDONLY, 0);
307                 if (fd<0)
308                         continue;
309                 n = read_all(fd, buf, sizeof(buf));
310                 close(fd);
311                 if (n != sizeof(buf))
312                         return -1;
313                 arc4_addrandom(buf, sizeof(buf));
314                 memset(buf, 0, sizeof(buf));
315                 arc4_seeded_ok = 1;
316                 return 0;
317         }
318
319         return -1;
320 }
321 #endif
322
323 static int
324 arc4_seed(void)
325 {
326         int ok = 0;
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())
332                 ok = 1;
333 #endif
334 #ifdef TRY_SEED_URANDOM
335         if (0 == arc4_seed_urandom())
336                 ok = 1;
337 #endif
338 #ifdef TRY_SEED_PROC_SYS_KERNEL_RANDOM_UUID
339         if (0 == arc4_seed_proc_sys_kernel_random_uuid())
340                 ok = 1;
341 #endif
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())
346                 ok = 1;
347 #endif
348 #ifdef TRY_SEED_SYSCTL_BSD
349         if (0 == arc4_seed_sysctl_bsd())
350                 ok = 1;
351 #endif
352         return ok ? 0 : -1;
353 }
354
355 static void
356 arc4_stir(void)
357 {
358         int     i;
359
360         if (!rs_initialized) {
361                 arc4_init();
362                 rs_initialized = 1;
363         }
364
365         arc4_seed();
366
367         /*
368          * Discard early keystream, as per recommendations in
369          * "Weaknesses in the Key Scheduling Algorithm of RC4" by
370          * Scott Fluhrer, Itsik Mantin, and Adi Shamir.
371          * http://www.wisdom.weizmann.ac.il/~itsik/RC4/Papers/Rc4_ksa.ps
372          *
373          * Ilya Mironov's "(Not So) Random Shuffles of RC4" suggests that
374          * we drop at least 2*256 bytes, with 12*256 as a conservative
375          * value.
376          *
377          * RFC4345 says to drop 6*256.
378          *
379          * At least some versions of this code drop 4*256, in a mistaken
380          * belief that "words" in the Fluhrer/Mantin/Shamir paper refers
381          * to processor words.
382          *
383          * We add another sect to the cargo cult, and choose 12*256.
384          */
385         for (i = 0; i < 12*256; i++)
386                 (void)arc4_getbyte();
387         arc4_count = BYTES_BEFORE_RESEED;
388 }
389
390
391 static void
392 arc4_stir_if_needed(void)
393 {
394         pid_t pid = getpid();
395
396         if (arc4_count <= 0 || !rs_initialized || arc4_stir_pid != pid)
397         {
398                 arc4_stir_pid = pid;
399                 arc4_stir();
400         }
401 }
402
403 static inline unsigned char
404 arc4_getbyte(void)
405 {
406         unsigned char si, sj;
407
408         rs.i = (rs.i + 1);
409         si = rs.s[rs.i];
410         rs.j = (rs.j + si);
411         sj = rs.s[rs.j];
412         rs.s[rs.i] = sj;
413         rs.s[rs.j] = si;
414         return (rs.s[(si + sj) & 0xff]);
415 }
416
417 static inline unsigned int
418 arc4_getword(void)
419 {
420         unsigned int val;
421
422         val = arc4_getbyte() << 24;
423         val |= arc4_getbyte() << 16;
424         val |= arc4_getbyte() << 8;
425         val |= arc4_getbyte();
426
427         return val;
428 }
429
430 #ifndef ARC4RANDOM_NOSTIR
431 ARC4RANDOM_EXPORT int
432 arc4random_stir(void)
433 {
434         int val;
435         _ARC4_LOCK();
436         val = arc4_stir();
437         _ARC4_UNLOCK();
438         return val;
439 }
440 #endif
441
442 #ifndef ARC4RANDOM_NOADDRANDOM
443 ARC4RANDOM_EXPORT void
444 arc4random_addrandom(const unsigned char *dat, int datlen)
445 {
446         int j;
447         _ARC4_LOCK();
448         if (!rs_initialized)
449                 arc4_stir();
450         for (j = 0; j < datlen; j += 256) {
451                 /* arc4_addrandom() ignores all but the first 256 bytes of
452                  * its input.  We want to make sure to look at ALL the
453                  * data in 'dat', just in case the user is doing something
454                  * crazy like passing us all the files in /var/log. */
455                 arc4_addrandom(dat + j, datlen - j);
456         }
457         _ARC4_UNLOCK();
458 }
459 #endif
460
461 #ifndef ARC4RANDOM_NORANDOM
462 ARC4RANDOM_EXPORT ARC4RANDOM_UINT32
463 arc4random(void)
464 {
465         ARC4RANDOM_UINT32 val;
466         _ARC4_LOCK();
467         arc4_count -= 4;
468         arc4_stir_if_needed();
469         val = arc4_getword();
470         _ARC4_UNLOCK();
471         return val;
472 }
473 #endif
474
475 ARC4RANDOM_EXPORT void
476 arc4random_buf(void *_buf, size_t n)
477 {
478         unsigned char *buf = _buf;
479         _ARC4_LOCK();
480         arc4_stir_if_needed();
481         while (n--) {
482                 if (--arc4_count <= 0)
483                         arc4_stir();
484                 buf[n] = arc4_getbyte();
485         }
486         _ARC4_UNLOCK();
487 }
488
489 #ifndef ARC4RANDOM_NOUNIFORM
490 /*
491  * Calculate a uniformly distributed random number less than upper_bound
492  * avoiding "modulo bias".
493  *
494  * Uniformity is achieved by generating new random numbers until the one
495  * returned is outside the range [0, 2**32 % upper_bound).  This
496  * guarantees the selected random number will be inside
497  * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
498  * after reduction modulo upper_bound.
499  */
500 ARC4RANDOM_EXPORT unsigned int
501 arc4random_uniform(unsigned int upper_bound)
502 {
503         ARC4RANDOM_UINT32 r, min;
504
505         if (upper_bound < 2)
506                 return 0;
507
508 #if (UINT_MAX > 0xffffffffUL)
509         min = 0x100000000UL % upper_bound;
510 #else
511         /* Calculate (2**32 % upper_bound) avoiding 64-bit math */
512         if (upper_bound > 0x80000000)
513                 min = 1 + ~upper_bound;         /* 2**32 - upper_bound */
514         else {
515                 /* (2**32 - (x * 2)) % x == 2**32 % x when x <= 2**31 */
516                 min = ((0xffffffff - (upper_bound * 2)) + 1) % upper_bound;
517         }
518 #endif
519
520         /*
521          * This could theoretically loop forever but each retry has
522          * p > 0.5 (worst case, usually far better) of selecting a
523          * number inside the range we need, so it should rarely need
524          * to re-roll.
525          */
526         for (;;) {
527                 r = arc4random();
528                 if (r >= min)
529                         break;
530         }
531
532         return r % upper_bound;
533 }
534 #endif