]> arthur.barton.de Git - netatalk.git/blob - libevent/arc4random.c
Update libevent to 2.0.12
[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 int
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         if (!arc4_seeded_ok)
367                 return -1;
368
369         /*
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
374          *
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
377          * value.
378          *
379          * RFC4345 says to drop 6*256.
380          *
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.
384          *
385          * We add another sect to the cargo cult, and choose 12*256.
386          */
387         for (i = 0; i < 12*256; i++)
388                 (void)arc4_getbyte();
389         arc4_count = BYTES_BEFORE_RESEED;
390
391         return 0;
392 }
393
394
395 static void
396 arc4_stir_if_needed(void)
397 {
398         pid_t pid = getpid();
399
400         if (arc4_count <= 0 || !rs_initialized || arc4_stir_pid != pid)
401         {
402                 arc4_stir_pid = pid;
403                 arc4_stir();
404         }
405 }
406
407 static inline unsigned char
408 arc4_getbyte(void)
409 {
410         unsigned char si, sj;
411
412         rs.i = (rs.i + 1);
413         si = rs.s[rs.i];
414         rs.j = (rs.j + si);
415         sj = rs.s[rs.j];
416         rs.s[rs.i] = sj;
417         rs.s[rs.j] = si;
418         return (rs.s[(si + sj) & 0xff]);
419 }
420
421 static inline unsigned int
422 arc4_getword(void)
423 {
424         unsigned int val;
425
426         val = arc4_getbyte() << 24;
427         val |= arc4_getbyte() << 16;
428         val |= arc4_getbyte() << 8;
429         val |= arc4_getbyte();
430
431         return val;
432 }
433
434 #ifndef ARC4RANDOM_NOSTIR
435 ARC4RANDOM_EXPORT int
436 arc4random_stir(void)
437 {
438         int val;
439         _ARC4_LOCK();
440         val = arc4_stir();
441         _ARC4_UNLOCK();
442         return val;
443 }
444 #endif
445
446 #ifndef ARC4RANDOM_NOADDRANDOM
447 ARC4RANDOM_EXPORT void
448 arc4random_addrandom(const unsigned char *dat, int datlen)
449 {
450         int j;
451         _ARC4_LOCK();
452         if (!rs_initialized)
453                 arc4_stir();
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);
460         }
461         _ARC4_UNLOCK();
462 }
463 #endif
464
465 #ifndef ARC4RANDOM_NORANDOM
466 ARC4RANDOM_EXPORT ARC4RANDOM_UINT32
467 arc4random(void)
468 {
469         ARC4RANDOM_UINT32 val;
470         _ARC4_LOCK();
471         arc4_count -= 4;
472         arc4_stir_if_needed();
473         val = arc4_getword();
474         _ARC4_UNLOCK();
475         return val;
476 }
477 #endif
478
479 ARC4RANDOM_EXPORT void
480 arc4random_buf(void *_buf, size_t n)
481 {
482         unsigned char *buf = _buf;
483         _ARC4_LOCK();
484         arc4_stir_if_needed();
485         while (n--) {
486                 if (--arc4_count <= 0)
487                         arc4_stir();
488                 buf[n] = arc4_getbyte();
489         }
490         _ARC4_UNLOCK();
491 }
492
493 #ifndef ARC4RANDOM_NOUNIFORM
494 /*
495  * Calculate a uniformly distributed random number less than upper_bound
496  * avoiding "modulo bias".
497  *
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.
503  */
504 ARC4RANDOM_EXPORT unsigned int
505 arc4random_uniform(unsigned int upper_bound)
506 {
507         ARC4RANDOM_UINT32 r, min;
508
509         if (upper_bound < 2)
510                 return 0;
511
512 #if (UINT_MAX > 0xffffffffUL)
513         min = 0x100000000UL % upper_bound;
514 #else
515         /* Calculate (2**32 % upper_bound) avoiding 64-bit math */
516         if (upper_bound > 0x80000000)
517                 min = 1 + ~upper_bound;         /* 2**32 - upper_bound */
518         else {
519                 /* (2**32 - (x * 2)) % x == 2**32 % x when x <= 2**31 */
520                 min = ((0xffffffff - (upper_bound * 2)) + 1) % upper_bound;
521         }
522 #endif
523
524         /*
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
528          * to re-roll.
529          */
530         for (;;) {
531                 r = arc4random();
532                 if (r >= min)
533                         break;
534         }
535
536         return r % upper_bound;
537 }
538 #endif