Debian Codegraph @

random/random-csprng.c

raw
1 /* random-csprng.c - CSPRNG style random number generator (libgcrypt classic)
2 * Copyright (C) 1998, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3 * 2007, 2008, 2010, 2012 Free Software Foundation, Inc.
4 *
5 * This file is part of Libgcrypt.
6 *
7 * Libgcrypt is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU Lesser General Public License as
9 * published by the Free Software Foundation; either version 2.1 of
10 * the License, or (at your option) any later version.
11 *
12 * Libgcrypt is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this program; if not, see <http://www.gnu.org/licenses/>.
19 */
20
21 /*
22 This random number generator is modelled after the one described in
23 Peter Gutmann's 1998 Usenix Security Symposium paper: "Software
24 Generation of Practically Strong Random Numbers". See also chapter
25 6 in his book "Cryptographic Security Architecture", New York,
26 2004, ISBN 0-387-95387-6.
27
28 Note that the acronym CSPRNG stands for "Continuously Seeded
29 PseudoRandom Number Generator" as used in Peter's implementation of
30 the paper and not only for "Cryptographically Secure PseudoRandom
31 Number Generator".
32 */
33
34
35 #include <config.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <errno.h>
39 #include <string.h>
40 #include <sys/time.h>
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #include <unistd.h>
44 #include <fcntl.h>
45 #include <time.h>
46 #ifdef HAVE_GETHRTIME
47 #include <sys/times.h>
48 #endif
49 #ifdef HAVE_GETTIMEOFDAY
50 #include <sys/time.h>
51 #endif
52 #ifdef HAVE_GETRUSAGE
53 #include <sys/resource.h>
54 #endif
55 #ifdef __MINGW32__
56 #include <process.h>
57 #endif
58 #ifdef HAVE_W32_SYSTEM
59 #include <windows.h>
60 #endif
61 #include "g10lib.h"
62 #include "random.h"
63 #include "rand-internal.h"
64 #include "cipher.h" /* _gcry_sha1_hash_buffer */
65 #include "../cipher/sha1.h" /* _gcry_sha1_mixblock */
66
67 #ifndef RAND_MAX /* For SunOS. */
68 #define RAND_MAX 32767
69 #endif
70
71 /* Check whether we can lock the seed file read write. */
72 #if defined(HAVE_FCNTL) && defined(HAVE_FTRUNCATE) && !defined(HAVE_W32_SYSTEM)
73 #define LOCK_SEED_FILE 1
74 #else
75 #define LOCK_SEED_FILE 0
76 #endif
77
78 /* Define the constant we use for transforming the pool at read-out. */
79 #if SIZEOF_UNSIGNED_LONG == 8
80 #define ADD_VALUE 0xa5a5a5a5a5a5a5a5
81 #elif SIZEOF_UNSIGNED_LONG == 4
82 #define ADD_VALUE 0xa5a5a5a5
83 #else
84 #error weird size for an unsigned long
85 #endif
86
87 /* Contstants pertaining to the hash pool. */
88 #define BLOCKLEN 64 /* Hash this amount of bytes... */
89 #define DIGESTLEN 20 /* ... into a digest of this length (sha-1). */
90 /* POOLBLOCKS is the number of digests which make up the pool. */
91 #define POOLBLOCKS 30
92 /* POOLSIZE must be a multiple of the digest length to make the AND
93 operations faster, the size should also be a multiple of unsigned
94 long. */
95 #define POOLSIZE (POOLBLOCKS*DIGESTLEN)
96 #if (POOLSIZE % SIZEOF_UNSIGNED_LONG)
97 #error Please make sure that poolsize is a multiple of unsigned long
98 #endif
99 #define POOLWORDS (POOLSIZE / SIZEOF_UNSIGNED_LONG)
100
101
102 /* RNDPOOL is the pool we use to collect the entropy and to stir it
103 up. Its allocated size is POOLSIZE+BLOCKLEN. Note that this is
104 also an indication on whether the module has been fully
105 initialized. */
106 static unsigned char *rndpool;
107
108 /* KEYPOOL is used as a scratch copy to read out random from RNDPOOL.
109 Its allocated size is also POOLSIZE+BLOCKLEN. */
110 static unsigned char *keypool;
111
112 /* This is the offset into RNDPOOL where the next random bytes are to
113 be mixed in. */
114 static size_t pool_writepos;
115
116 /* When reading data out of KEYPOOL, we start the read at different
117 positions. This variable keeps track on where to read next. */
118 static size_t pool_readpos;
119
120 /* This flag is set to true as soon as the pool has been completely
121 filled the first time. This may happen either by reading a seed
122 file or by adding enough entropy. */
123 static int pool_filled;
124
125 /* This counter is used to track whether the initial seeding has been
126 done with enough bytes from a reliable entropy source. */
127 static size_t pool_filled_counter;
128
129 /* If random of level GCRY_VERY_STRONG_RANDOM has been requested we
130 have stricter requirements on what kind of entropy is in the pool.
131 In particular POOL_FILLED is not sufficient. Thus we add some
132 extra seeding and set this flag to true if the extra seeding has
133 been done. */
134 static int did_initial_extra_seeding;
135
136 /* This variable is used to estimated the amount of fresh entropy
137 available in RNDPOOL. */
138 static int pool_balance;
139
140 /* After a mixing operation this variable will be set to true and
141 cleared if new entropy has been added or a remix is required for
142 other reasons. */
143 static int just_mixed;
144
145 /* The name of the seed file or NULL if no seed file has been defined.
146 The seed file needs to be registered at initialization time. We
147 keep a malloced copy here. */
148 static char *seed_file_name;
149
150 /* If a seed file has been registered and maybe updated on exit this
151 flag set. */
152 static int allow_seed_file_update;
153
154 /* Option flag set at initialiation time to force allocation of the
155 pool in secure memory. */
156 static int secure_alloc;
157
158 /* This function pointer is set to the actual entropy gathering
159 function during initialization. After initialization it is
160 guaranteed to point to function. (On systems without a random
161 gatherer module a dummy function is used).*/
162 static int (*slow_gather_fnc)(void (*)(const void*, size_t,
163 enum random_origins),
164 enum random_origins, size_t, int);
165
166 /* This function is set to the actual fast entropy gathering function
167 during initialization. If it is NULL, no such function is
168 available. */
169 static void (*fast_gather_fnc)(void (*)(const void*, size_t,
170 enum random_origins),
171 enum random_origins);
172
173
174 /* Option flag useful for debugging and the test suite. If set
175 requests for very strong random are degraded to strong random. Not
176 used by regular applications. */
177 static int quick_test;
178
179 /* This is the lock we use to protect all pool operations. */
180 GPGRT_LOCK_DEFINE (pool_lock);
181
182 /* This is a helper for assert calls. These calls are used to assert
183 that functions are called in a locked state. It is not meant to be
184 thread-safe but as a method to get aware of missing locks in the
185 test suite. */
186 static int pool_is_locked;
187
188
189 /* We keep some counters in this structure for the sake of the
190 _gcry_random_dump_stats () function. */
191 static struct
192 {
193 unsigned long mixrnd;
194 unsigned long mixkey;
195 unsigned long slowpolls;
196 unsigned long fastpolls;
197 unsigned long getbytes1;
198 unsigned long ngetbytes1;
199 unsigned long getbytes2;
200 unsigned long ngetbytes2;
201 unsigned long addbytes;
202 unsigned long naddbytes;
203 } rndstats;
204
205
206
207 /* --- Prototypes --- */
208 static void read_pool (byte *buffer, size_t length, int level );
209 static void add_randomness (const void *buffer, size_t length,
210 enum random_origins origin);
211 static void random_poll (void);
212 static void do_fast_random_poll (void);
213 static int (*getfnc_gather_random (void))(void (*)(const void*, size_t,
214 enum random_origins),
215 enum random_origins, size_t, int);
216 static void (*getfnc_fast_random_poll (void))(void (*)(const void*, size_t,
217 enum random_origins),
218 enum random_origins);
219 static void read_random_source (enum random_origins origin,
220 size_t length, int level);
221
222
223
224 /* --- Functions --- */
225
226
227 /* Basic initialization which is required to initialize mutexes and
228 such. It does not run a full initialization so that the filling of
229 the random pool can be delayed until it is actually needed. We
230 assume that this function is used before any concurrent access
231 happens. */
232 static void
233 initialize_basics(void)
234 {
235 static int initialized;
236
237 if (!initialized)
238 {
239 initialized = 1;
240
241 /* Make sure that we are still using the values we have
242 traditionally used for the random levels. */
243 gcry_assert (GCRY_WEAK_RANDOM == 0
244 && GCRY_STRONG_RANDOM == 1
245 && GCRY_VERY_STRONG_RANDOM == 2);
246 }
247 }
248
249 /* Take the pool lock. */
250 static void
251 lock_pool (void)
252 {
253 int err;
254
255 err = gpgrt_lock_lock (&pool_lock);
256 if (err)
257 log_fatal ("failed to acquire the pool lock: %s\n", gpg_strerror (err));
258 pool_is_locked = 1;
259 }
260
261 /* Release the pool lock. */
262 static void
263 unlock_pool (void)
264 {
265 int err;
266
267 pool_is_locked = 0;
268 err = gpgrt_lock_unlock (&pool_lock);
269 if (err)
270 log_fatal ("failed to release the pool lock: %s\n", gpg_strerror (err));
271 }
272
273
274 /* Full initialization of this module. */
275 static void
276 initialize(void)
277 {
278 /* Although the basic initialization should have happened already,
279 we call it here to make sure that all prerequisites are met. */
280 initialize_basics ();
281
282 /* Now we can look the pool and complete the initialization if
283 necessary. */
284 lock_pool ();
285 if (!rndpool)
286 {
287 /* The data buffer is allocated somewhat larger, so that we can
288 use this extra space (which is allocated in secure memory) as
289 a temporary hash buffer */
290 rndpool = (secure_alloc
291 ? xcalloc_secure (1, POOLSIZE + BLOCKLEN)
292 : xcalloc (1, POOLSIZE + BLOCKLEN));
293 keypool = (secure_alloc
294 ? xcalloc_secure (1, POOLSIZE + BLOCKLEN)
295 : xcalloc (1, POOLSIZE + BLOCKLEN));
296
297 /* Setup the slow entropy gathering function. The code requires
298 that this function exists. */
299 slow_gather_fnc = getfnc_gather_random ();
300
301 /* Setup the fast entropy gathering function. */
302 fast_gather_fnc = getfnc_fast_random_poll ();
303
304 }
305 unlock_pool ();
306 }
307
308
309
310
311 /* Initialize this random subsystem. If FULL is false, this function
312 merely calls the initialize and does not do anything more. Doing
313 this is not really required but when running in a threaded
314 environment we might get a race condition otherwise. */
315 void
316 _gcry_rngcsprng_initialize (int full)
317 {
318 if (!full)
319 initialize_basics ();
320 else
321 initialize ();
322 }
323
324
325 /* Try to close the FDs of the random gather module. This is
326 currently only implemented for rndgetentropy/rndoldlinux. */
327 void
328 _gcry_rngcsprng_close_fds (void)
329 {
330 lock_pool ();
331 #if USE_RNDGETENTROPY
332 _gcry_rndgetentropy_gather_random (NULL, 0, 0, 0);
333 #endif
334 #if USE_RNDOLDLINUX
335 _gcry_rndoldlinux_gather_random (NULL, 0, 0, 0);
336 #endif
337 pool_writepos = 0;
338 pool_readpos = 0;
339 pool_filled = 0;
340 pool_filled_counter = 0;
341 did_initial_extra_seeding = 0;
342 pool_balance = 0;
343 just_mixed = 0;
344 xfree (rndpool);
345 xfree (keypool);
346 rndpool = NULL;
347 keypool = NULL;
348 unlock_pool ();
349 }
350
351
352 void
353 _gcry_rngcsprng_dump_stats (void)
354 {
355 /* In theory we would need to lock the stats here. However this
356 function is usually called during cleanup and then we _might_ run
357 into problems. */
358
359 log_info ("random usage: poolsize=%d mixed=%lu polls=%lu/%lu added=%lu/%lu\n"
360 " outmix=%lu getlvl1=%lu/%lu getlvl2=%lu/%lu%s\n",
361 POOLSIZE, rndstats.mixrnd, rndstats.slowpolls, rndstats.fastpolls,
362 rndstats.naddbytes, rndstats.addbytes,
363 rndstats.mixkey, rndstats.ngetbytes1, rndstats.getbytes1,
364 rndstats.ngetbytes2, rndstats.getbytes2,
365 _gcry_rndhw_failed_p()? " (hwrng failed)":"");
366 }
367
368
369 /* This function should be called during initialization and before
370 initialization of this module to place the random pools into secure
371 memory. */
372 void
373 _gcry_rngcsprng_secure_alloc (void)
374 {
375 secure_alloc = 1;
376 }
377
378
379 /* This may be called before full initialization to degrade the
380 quality of the RNG for the sake of a faster running test suite. */
381 void
382 _gcry_rngcsprng_enable_quick_gen (void)
383 {
384 quick_test = 1;
385 }
386
387
388 /* This function returns true if no real RNG is available or the
389 quality of the RNG has been degraded for test purposes. */
390 int
391 _gcry_rngcsprng_is_faked (void)
392 {
393 /* We need to initialize due to the runtime determination of
394 available entropy gather modules. */
395 initialize();
396 return quick_test;
397 }
398
399
400 /* Add BUFLEN bytes from BUF to the internal random pool. QUALITY
401 should be in the range of 0..100 to indicate the goodness of the
402 entropy added, or -1 for goodness not known. */
403 gcry_error_t
404 _gcry_rngcsprng_add_bytes (const void *buf, size_t buflen, int quality)
405 {
406 size_t nbytes;
407 const char *bufptr;
408
409 if (quality == -1)
410 quality = 35;
411 else if (quality > 100)
412 quality = 100;
413 else if (quality < 0)
414 quality = 0;
415
416 if (!buf)
417 return gpg_error (GPG_ERR_INV_ARG);
418
419 if (!buflen || quality < 10)
420 return 0; /* Take a shortcut. */
421
422 /* Because we don't increment the entropy estimation with FASTPOLL,
423 we don't need to take lock that estimation while adding from an
424 external source. This limited entropy estimation also means that
425 we can't take QUALITY into account. */
426 initialize_basics ();
427 bufptr = buf;
428 while (buflen)
429 {
430 nbytes = buflen > POOLSIZE? POOLSIZE : buflen;
431 lock_pool ();
432 if (rndpool)
433 add_randomness (bufptr, nbytes, RANDOM_ORIGIN_EXTERNAL);
434 unlock_pool ();
435 bufptr += nbytes;
436 buflen -= nbytes;
437 }
438 return 0;
439 }
440
441
442 /* Public function to fill the buffer with LENGTH bytes of
443 cryptographically strong random bytes. Level GCRY_WEAK_RANDOM is
444 not very strong, GCRY_STRONG_RANDOM is strong enough for most
445 usage, GCRY_VERY_STRONG_RANDOM is good for key generation stuff but
446 may be very slow. */
447 void
448 _gcry_rngcsprng_randomize (void *buffer, size_t length,
449 enum gcry_random_level level)
450 {
451 unsigned char *p;
452
453 /* Make sure we are initialized. */
454 initialize ();
455
456 /* Handle our hack used for regression tests of Libgcrypt. */
457 if ( quick_test && level > GCRY_STRONG_RANDOM )
458 level = GCRY_STRONG_RANDOM;
459
460 /* Make sure the level is okay. */
461 level &= 3;
462
463 /* Acquire the pool lock. */
464 lock_pool ();
465
466 /* Update the statistics. */
467 if (level >= GCRY_VERY_STRONG_RANDOM)
468 {
469 rndstats.getbytes2 += length;
470 rndstats.ngetbytes2++;
471 }
472 else
473 {
474 rndstats.getbytes1 += length;
475 rndstats.ngetbytes1++;
476 }
477
478 /* Read the random into the provided buffer. */
479 for (p = buffer; length > 0;)
480 {
481 size_t n;
482
483 n = length > POOLSIZE? POOLSIZE : length;
484 read_pool (p, n, level);
485 length -= n;
486 p += n;
487 }
488
489 /* Release the pool lock. */
490 unlock_pool ();
491 }
492
493
494
495
496 /*
497 * Mix the 600 byte pool. Note that the 64 byte scratch area directly
498 * follows the pool. The numbers in the diagram give the number of
499 * bytes.
500 * <................600...............> <.64.>
501 * pool |------------------------------------| |------|
502 * <20><.24.> <20>
503 * | | +-----+
504 * +-----|-------------------------------|-+
505 * +-------------------------------|-|-+
506 * v v v
507 * |------|
508 * <hash>
509 * +---------------------------------------+
510 * v
511 * <20>
512 * pool' |------------------------------------|
513 * <20><20><.24.>
514 * +---|-----|---------------------------+
515 * +-----|---------------------------|-+
516 * +---------------------------|-|-+
517 * v v v
518 * |------|
519 * <hash>
520 * |
521 * +-----------------------------------+
522 * v
523 * <20>
524 * pool'' |------------------------------------|
525 * <20><20><20><.24.>
526 * +---|-----|-----------------------+
527 * +-----|-----------------------|-+
528 * +-----------------------|-|-+
529 * v v v
530 *
531 * and so on until we did this for all 30 blocks.
532 *
533 * To better protect against implementation errors in this code, we
534 * xor a digest of the entire pool into the pool before mixing.
535 *
536 * Note: this function must only be called with a locked pool.
537 */
538 static void
539 mix_pool(unsigned char *pool)
540 {
541 static unsigned char failsafe_digest[DIGESTLEN];
542 static int failsafe_digest_valid;
543
544 unsigned char *hashbuf = pool + POOLSIZE;
545 unsigned char *p, *pend;
546 int i, n;
547 SHA1_CONTEXT md;
548 unsigned int nburn;
549
550 #if DIGESTLEN != 20
551 #error must have a digest length of 20 for SHA-1
552 #endif
553
554 gcry_assert (pool_is_locked);
555 _gcry_sha1_mixblock_init (&md);
556
557 /* pool_0 -> pool'. */
558 pend = pool + POOLSIZE;
559 memcpy (hashbuf, pend - DIGESTLEN, DIGESTLEN);
560 memcpy (hashbuf+DIGESTLEN, pool, BLOCKLEN-DIGESTLEN);
561 nburn = _gcry_sha1_mixblock (&md, hashbuf);
562 memcpy (pool, hashbuf, DIGESTLEN);
563
564 if (failsafe_digest_valid && pool == rndpool)
565 {
566 for (i=0; i < DIGESTLEN; i++)
567 pool[i] ^= failsafe_digest[i];
568 }
569
570 /* Loop for the remaining iterations. */
571 p = pool;
572 for (n=1; n < POOLBLOCKS; n++)
573 {
574 if (p + BLOCKLEN < pend)
575 memcpy (hashbuf, p, BLOCKLEN);
576 else
577 {
578 unsigned char *pp = p;
579
580 for (i=0; i < BLOCKLEN; i++ )
581 {
582 if ( pp >= pend )
583 pp = pool;
584 hashbuf[i] = *pp++;
585 }
586 }
587
588 _gcry_sha1_mixblock (&md, hashbuf);
589 p += DIGESTLEN;
590 memcpy (p, hashbuf, DIGESTLEN);
591 }
592
593 /* Our hash implementation does only leave small parts (64 bytes)
594 of the pool on the stack, so it is okay not to require secure
595 memory here. Before we use this pool, it will be copied to the
596 help buffer anyway. */
597 if ( pool == rndpool)
598 {
599 _gcry_sha1_hash_buffer (failsafe_digest, pool, POOLSIZE);
600 failsafe_digest_valid = 1;
601 }
602
603 _gcry_burn_stack (nburn);
604 }
605
606
607 void
608 _gcry_rngcsprng_set_seed_file (const char *name)
609 {
610 if (seed_file_name)
611 BUG ();
612 seed_file_name = xstrdup (name);
613 }
614
615
616
617 /* Helper for my_open.
618 * Return a malloced wide char string from an UTF-8 encoded input
619 * string STRING. Caller must free this value. Returns NULL and sets
620 * ERRNO on failure. Calling this function with STRING set to NULL is
621 * not defined. */
622 #ifdef HAVE_W32_SYSTEM
623 static wchar_t *
624 utf8_to_wchar (const char *string)
625 {
626 int n;
627 size_t nbytes;
628 wchar_t *result;
629
630 n = MultiByteToWideChar (CP_UTF8, 0, string, -1, NULL, 0);
631 if (n < 0)
632 {
633 gpg_err_set_errno (EINVAL);
634 return NULL;
635 }
636
637 nbytes = (size_t)(n+1) * sizeof(*result);
638 if (nbytes / sizeof(*result) != (n+1))
639 {
640 gpg_err_set_errno (ENOMEM);
641 return NULL;
642 }
643 result = xtrymalloc (nbytes);
644 if (!result)
645 return NULL;
646
647 n = MultiByteToWideChar (CP_UTF8, 0, string, -1, result, n);
648 if (n < 0)
649 {
650 xfree (result);
651 gpg_err_set_errno (EINVAL);
652 result = NULL;
653 }
654 return result;
655 }
656 #endif /*HAVE_W32_SYSTEM*/
657
658
659 /* Helper for my_open. */
660 #ifdef HAVE_W32_SYSTEM
661 static int
662 any8bitchar (const char *string)
663 {
664 if (string)
665 for ( ; *string; string++)
666 if ((*string & 0x80))
667 return 1;
668 return 0;
669 }
670 #endif /*HAVE_W32_SYSTEM*/
671
672
673 /* A wrapper around open to handle Unicode file names under Windows. */
674 static int
675 my_open (const char *name, int flags, unsigned int mode)
676 {
677 #ifdef HAVE_W32_SYSTEM
678 if (any8bitchar (name))
679 {
680 wchar_t *wname;
681 int ret;
682
683 wname = utf8_to_wchar (name);
684 if (!wname)
685 return -1;
686 ret = _wopen (wname, flags, mode);
687 xfree (wname);
688 return ret;
689 }
690 else
691 return open (name, flags, mode);
692 #else
693 return open (name, flags, mode);
694 #endif
695 }
696
697
698 /* Lock an open file identified by file descriptor FD and wait a
699 reasonable time to succeed. With FOR_WRITE set to true a write
700 lock will be taken. FNAME is used only for diagnostics. Returns 0
701 on success or -1 on error. */
702 static int
703 lock_seed_file (int fd, const char *fname, int for_write)
704 {
705 #ifdef __GCC__
706 #warning Check whether we can lock on Windows.
707 #endif
708 #if LOCK_SEED_FILE
709 struct flock lck;
710 struct timeval tv;
711 int backoff=0;
712
713 /* We take a lock on the entire file. */
714 memset (&lck, 0, sizeof lck);
715 lck.l_type = for_write? F_WRLCK : F_RDLCK;
716 lck.l_whence = SEEK_SET;
717
718 while (fcntl (fd, F_SETLK, &lck) == -1)
719 {
720 if (errno != EAGAIN && errno != EACCES)
721 {
722 log_info (_("can't lock `%s': %s\n"), fname, strerror (errno));
723 return -1;
724 }
725
726 if (backoff > 2) /* Show the first message after ~2.25 seconds. */
727 log_info( _("waiting for lock on `%s'...\n"), fname);
728
729 tv.tv_sec = backoff;
730 tv.tv_usec = 250000;
731 select (0, NULL, NULL, NULL, &tv);
732 if (backoff < 10)
733 backoff++ ;
734 }
735 #else
736 (void)fd;
737 (void)fname;
738 (void)for_write;
739 #endif /*!LOCK_SEED_FILE*/
740 return 0;
741 }
742
743
744 /* Read in a seed from the random_seed file and return true if this
745 was successful.
746
747 Note: Multiple instances of applications sharing the same random
748 seed file can be started in parallel, in which case they will read
749 out the same pool and then race for updating it (the last update
750 overwrites earlier updates). They will differentiate only by the
751 weak entropy that is added in read_seed_file based on the PID and
752 clock, and up to 32 bytes from a non-blocking entropy source. The
753 consequence is that the output of these different instances is
754 correlated to some extent. In the perfect scenario, the attacker
755 can control (or at least guess) the PID and clock of the
756 application, and drain the system's entropy pool to reduce the "up
757 to 32 bytes" above to 0. Then the dependencies of the initial
758 states of the pools are completely known. */
759 static int
760 read_seed_file (void)
761 {
762 int fd;
763 struct stat sb;
764 unsigned char buffer[POOLSIZE];
765 int n;
766
767 gcry_assert (pool_is_locked);
768
769 if (!seed_file_name)
770 return 0;
771
772 #ifdef HAVE_DOSISH_SYSTEM
773 fd = my_open (seed_file_name, O_RDONLY | O_BINARY, 0);
774 #else
775 fd = my_open (seed_file_name, O_RDONLY, 0);
776 #endif
777 if( fd == -1 && errno == ENOENT)
778 {
779 allow_seed_file_update = 1;
780 return 0;
781 }
782
783 if (fd == -1 )
784 {
785 log_info(_("can't open `%s': %s\n"), seed_file_name, strerror(errno) );
786 return 0;
787 }
788 if (lock_seed_file (fd, seed_file_name, 0))
789 {
790 close (fd);
791 return 0;
792 }
793 if (fstat( fd, &sb ) )
794 {
795 log_info(_("can't stat `%s': %s\n"), seed_file_name, strerror(errno) );
796 close(fd);
797 return 0;
798 }
799 if (!S_ISREG(sb.st_mode) )
800 {
801 log_info(_("`%s' is not a regular file - ignored\n"), seed_file_name );
802 close(fd);
803 return 0;
804 }
805 if (!sb.st_size )
806 {
807 log_info(_("note: random_seed file is empty\n") );
808 close(fd);
809 allow_seed_file_update = 1;
810 return 0;
811 }
812 if (sb.st_size != POOLSIZE )
813 {
814 log_info(_("warning: invalid size of random_seed file - not used\n") );
815 close(fd);
816 return 0;
817 }
818
819 do
820 {
821 n = read( fd, buffer, POOLSIZE );
822 }
823 while (n == -1 && errno == EINTR );
824
825 if (n != POOLSIZE)
826 {
827 log_fatal(_("can't read `%s': %s\n"), seed_file_name,strerror(errno) );
828 close(fd);/*NOTREACHED*/
829 return 0;
830 }
831
832 close(fd);
833
834 add_randomness( buffer, POOLSIZE, RANDOM_ORIGIN_INIT );
835 /* add some minor entropy to the pool now (this will also force a mixing) */
836 {
837 pid_t x = getpid();
838 add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT );
839 }
840 {
841 time_t x = time(NULL);
842 add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT );
843 }
844 {
845 clock_t x = clock();
846 add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT );
847 }
848
849 /* And read a few bytes from our entropy source. If we have the
850 * Jitter RNG we can fast get a lot of entropy. Thus we read 1024
851 * bits from that source.
852 *
853 * Without the Jitter RNG we keep the old method of reading only a
854 * few bytes usually from /dev/urandom which won't block. */
855 if (_gcry_rndjent_get_version (NULL))
856 read_random_source (RANDOM_ORIGIN_INIT, 128, GCRY_STRONG_RANDOM);
857 else
858 read_random_source (RANDOM_ORIGIN_INIT, 32, GCRY_STRONG_RANDOM);
859
860 allow_seed_file_update = 1;
861 return 1;
862 }
863
864
865 void
866 _gcry_rngcsprng_update_seed_file (void)
867 {
868 unsigned long *sp, *dp;
869 int fd, i;
870
871 /* We do only a basic initialization so that we can lock the pool.
872 This is required to cope with the case that this function is
873 called by some cleanup code at a point where the RNG has never
874 been initialized. */
875 initialize_basics ();
876 lock_pool ();
877
878 if ( !seed_file_name || !rndpool || !pool_filled )
879 {
880 unlock_pool ();
881 return;
882 }
883 if ( !allow_seed_file_update )
884 {
885 unlock_pool ();
886 log_info(_("note: random_seed file not updated\n"));
887 return;
888 }
889
890 /* At this point we know that there is something in the pool and
891 thus we can conclude that the pool has been fully initialized. */
892
893
894 /* Copy the entropy pool to a scratch pool and mix both of them. */
895 for (i=0,dp=(unsigned long*)(void*)keypool, sp=(unsigned long*)(void*)rndpool;
896 i < POOLWORDS; i++, dp++, sp++ )
897 {
898 *dp = *sp + ADD_VALUE;
899 }
900 mix_pool(rndpool); rndstats.mixrnd++;
901 mix_pool(keypool); rndstats.mixkey++;
902
903 #if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
904 fd = my_open (seed_file_name, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY,
905 S_IRUSR|S_IWUSR );
906 #else
907 # if LOCK_SEED_FILE
908 fd = my_open (seed_file_name, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR );
909 # else
910 fd = my_open (seed_file_name, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR );
911 # endif
912 #endif
913
914 if (fd == -1 )
915 log_info (_("can't create `%s': %s\n"), seed_file_name, strerror(errno) );
916 else if (lock_seed_file (fd, seed_file_name, 1))
917 {
918 close (fd);
919 }
920 #if LOCK_SEED_FILE
921 else if (ftruncate (fd, 0))
922 {
923 log_info(_("can't write `%s': %s\n"), seed_file_name, strerror(errno));
924 close (fd);
925 }
926 #endif /*LOCK_SEED_FILE*/
927 else
928 {
929 do
930 {
931 i = write (fd, keypool, POOLSIZE );
932 }
933 while (i == -1 && errno == EINTR);
934 if (i != POOLSIZE)
935 log_info (_("can't write `%s': %s\n"),seed_file_name, strerror(errno));
936 if (close(fd))
937 log_info (_("can't close `%s': %s\n"),seed_file_name, strerror(errno));
938 }
939
940 unlock_pool ();
941 }
942
943
944 /* Read random out of the pool. This function is the core of the
945 public random functions. Note that Level GCRY_WEAK_RANDOM is not
946 anymore handled special and in fact is an alias in the API for
947 level GCRY_STRONG_RANDOM. Must be called with the pool already
948 locked. */
949 static void
950 read_pool (byte *buffer, size_t length, int level)
951 {
952 int i;
953 unsigned long *sp, *dp;
954 /* The volatile is there to make sure the compiler does not optimize
955 the code away in case the getpid function is badly attributed.
956 Note that we keep a pid in a static variable as well as in a
957 stack based one; the latter is to detect ill behaving thread
958 libraries, ignoring the pool mutexes. */
959 static volatile pid_t my_pid = (pid_t)(-1);
960 volatile pid_t my_pid2;
961
962 gcry_assert (pool_is_locked);
963
964 retry:
965 /* Get our own pid, so that we can detect a fork. */
966 my_pid2 = getpid ();
967 if (my_pid == (pid_t)(-1))
968 my_pid = my_pid2;
969 if ( my_pid != my_pid2 )
970 {
971 /* We detected a plain fork; i.e. we are now the child. Update
972 the static pid and add some randomness. */
973 pid_t x;
974
975 my_pid = my_pid2;
976 x = my_pid;
977 add_randomness (&x, sizeof(x), RANDOM_ORIGIN_INIT);
978 just_mixed = 0; /* Make sure it will get mixed. */
979 }
980
981 gcry_assert (pool_is_locked);
982
983 /* Our code does not allow extracting more than POOLSIZE. Better
984 check it here. */
985 if (length > POOLSIZE)
986 {
987 log_bug("too many random bits requested\n");
988 }
989
990 if (!pool_filled)
991 {
992 if (read_seed_file() )
993 pool_filled = 1;
994 }
995
996 /* For level 2 quality (key generation) we always make sure that the
997 pool has been seeded enough initially. */
998 if (level == GCRY_VERY_STRONG_RANDOM && !did_initial_extra_seeding)
999 {
1000 size_t needed;
1001
1002 pool_balance = 0;
1003 needed = length - pool_balance;
1004 if (needed < 16) /* At least 128 bits. */
1005 needed = 16;
1006 else if( needed > POOLSIZE )
1007 BUG ();
1008 read_random_source (RANDOM_ORIGIN_EXTRAPOLL, needed,
1009 GCRY_VERY_STRONG_RANDOM);
1010 pool_balance += needed;
1011 did_initial_extra_seeding = 1;
1012 }
1013
1014 /* For level 2 make sure that there is enough random in the pool. */
1015 if (level == GCRY_VERY_STRONG_RANDOM && pool_balance < length)
1016 {
1017 size_t needed;
1018
1019 if (pool_balance < 0)
1020 pool_balance = 0;
1021 needed = length - pool_balance;
1022 if (needed > POOLSIZE)
1023 BUG ();
1024 read_random_source (RANDOM_ORIGIN_EXTRAPOLL, needed,
1025 GCRY_VERY_STRONG_RANDOM);
1026 pool_balance += needed;
1027 }
1028
1029 /* Make sure the pool is filled. */
1030 while (!pool_filled)
1031 random_poll();
1032
1033 /* Always do a fast random poll (we have to use the unlocked version). */
1034 do_fast_random_poll();
1035
1036 /* Mix the pid in so that we for sure won't deliver the same random
1037 after a fork. */
1038 {
1039 pid_t apid = my_pid;
1040 add_randomness (&apid, sizeof (apid), RANDOM_ORIGIN_INIT);
1041 }
1042
1043 /* Mix the pool (if add_randomness() didn't it). */
1044 if (!just_mixed)
1045 {
1046 mix_pool(rndpool);
1047 rndstats.mixrnd++;
1048 }
1049
1050 /* Create a new pool. */
1051 for(i=0,dp=(unsigned long*)(void*)keypool, sp=(unsigned long*)(void*)rndpool;
1052 i < POOLWORDS; i++, dp++, sp++ )
1053 *dp = *sp + ADD_VALUE;
1054
1055 /* Mix both pools. */
1056 mix_pool(rndpool); rndstats.mixrnd++;
1057 mix_pool(keypool); rndstats.mixkey++;
1058
1059 /* Read the requested data. We use a read pointer to read from a
1060 different position each time. */
1061 while (length--)
1062 {
1063 *buffer++ = keypool[pool_readpos++];
1064 if (pool_readpos >= POOLSIZE)
1065 pool_readpos = 0;
1066 pool_balance--;
1067 }
1068
1069 if (pool_balance < 0)
1070 pool_balance = 0;
1071
1072 /* Clear the keypool. */
1073 memset (keypool, 0, POOLSIZE);
1074
1075 /* We need to detect whether a fork has happened. A fork might have
1076 an identical pool and thus the child and the parent could emit
1077 the very same random number. This test here is to detect forks
1078 in a multi-threaded process. It does not work with all thread
1079 implementations in particular not with pthreads. However it is
1080 good enough for GNU Pth. */
1081 if ( getpid () != my_pid2 )
1082 {
1083 pid_t x = getpid();
1084 add_randomness (&x, sizeof(x), RANDOM_ORIGIN_INIT);
1085 just_mixed = 0; /* Make sure it will get mixed. */
1086 my_pid = x; /* Also update the static pid. */
1087 goto retry;
1088 }
1089 }
1090
1091
1092
1093 /* Add LENGTH bytes of randomness from buffer to the pool. ORIGIN is
1094 used to specify the randomness origin. This is one of the
1095 RANDOM_ORIGIN_* values. */
1096 static void
1097 add_randomness (const void *buffer, size_t length, enum random_origins origin)
1098 {
1099 const unsigned char *p = buffer;
1100 size_t count = 0;
1101
1102 gcry_assert (pool_is_locked);
1103
1104 rndstats.addbytes += length;
1105 rndstats.naddbytes++;
1106 while (length-- )
1107 {
1108 rndpool[pool_writepos++] ^= *p++;
1109 count++;
1110 if (pool_writepos >= POOLSIZE )
1111 {
1112 /* It is possible that we are invoked before the pool is
1113 filled using an unreliable origin of entropy, for example
1114 the fast random poll. To avoid flagging the pool as
1115 filled in this case, we track the initial filling state
1116 separately. See also the remarks about the seed file. */
1117 if (origin >= RANDOM_ORIGIN_SLOWPOLL && !pool_filled)
1118 {
1119 pool_filled_counter += count;
1120 count = 0;
1121 if (pool_filled_counter >= POOLSIZE)
1122 pool_filled = 1;
1123 }
1124 pool_writepos = 0;
1125 mix_pool(rndpool); rndstats.mixrnd++;
1126 just_mixed = !length;
1127 }
1128 }
1129 }
1130
1131
1132
1133 static void
1134 random_poll (void)
1135 {
1136 rndstats.slowpolls++;
1137 read_random_source (RANDOM_ORIGIN_SLOWPOLL, POOLSIZE/5, GCRY_STRONG_RANDOM);
1138 }
1139
1140
1141 /* Runtime determination of the slow entropy gathering module. */
1142 static int (*
1143 getfnc_gather_random (void))(void (*)(const void*, size_t,
1144 enum random_origins),
1145 enum random_origins, size_t, int)
1146 {
1147 int (*fnc)(void (*)(const void*, size_t, enum random_origins),
1148 enum random_origins, size_t, int);
1149
1150 #if USE_RNDGETENTROPY
1151 fnc = _gcry_rndgetentropy_gather_random;
1152 return fnc;
1153 #endif
1154
1155 #if USE_RNDOLDLINUX
1156 if ( !access (NAME_OF_DEV_RANDOM, R_OK)
1157 && !access (NAME_OF_DEV_URANDOM, R_OK))
1158 {
1159 fnc = _gcry_rndoldlinux_gather_random;
1160 return fnc;
1161 }
1162 #endif
1163
1164 #if USE_RNDEGD
1165 if ( _gcry_rndegd_connect_socket (1) != -1 )
1166 {
1167 fnc = _gcry_rndegd_gather_random;
1168 return fnc;
1169 }
1170 #endif
1171
1172 #if USE_RNDUNIX
1173 fnc = _gcry_rndunix_gather_random;
1174 return fnc;
1175 #endif
1176
1177 #if USE_RNDW32
1178 fnc = _gcry_rndw32_gather_random;
1179 return fnc;
1180 #endif
1181
1182 log_fatal (_("no entropy gathering module detected\n"));
1183
1184 return NULL; /*NOTREACHED*/
1185 }
1186
1187 /* Runtime determination of the fast entropy gathering function.
1188 (Currently a compile time method is used.) */
1189 static void (*
1190 getfnc_fast_random_poll (void))( void (*)(const void*, size_t,
1191 enum random_origins),
1192 enum random_origins)
1193 {
1194 #if USE_RNDW32
1195 return _gcry_rndw32_gather_random_fast;
1196 #endif
1197 return NULL;
1198 }
1199
1200
1201
1202 static void
1203 do_fast_random_poll (void)
1204 {
1205 gcry_assert (pool_is_locked);
1206
1207 rndstats.fastpolls++;
1208
1209 if (fast_gather_fnc)
1210 fast_gather_fnc (add_randomness, RANDOM_ORIGIN_FASTPOLL);
1211
1212 /* Continue with the generic functions. */
1213 #if HAVE_GETHRTIME
1214 {
1215 hrtime_t tv;
1216 tv = gethrtime();
1217 add_randomness( &tv, sizeof(tv), RANDOM_ORIGIN_FASTPOLL );
1218 }
1219 #elif HAVE_GETTIMEOFDAY
1220 {
1221 struct timeval tv;
1222 if( gettimeofday( &tv, NULL ) )
1223 BUG();
1224 add_randomness( &tv.tv_sec, sizeof(tv.tv_sec), RANDOM_ORIGIN_FASTPOLL );
1225 add_randomness( &tv.tv_usec, sizeof(tv.tv_usec), RANDOM_ORIGIN_FASTPOLL );
1226 }
1227 #elif HAVE_CLOCK_GETTIME
1228 { struct timespec tv;
1229 if( clock_gettime( CLOCK_REALTIME, &tv ) == -1 )
1230 BUG();
1231 add_randomness( &tv.tv_sec, sizeof(tv.tv_sec), RANDOM_ORIGIN_FASTPOLL );
1232 add_randomness( &tv.tv_nsec, sizeof(tv.tv_nsec), RANDOM_ORIGIN_FASTPOLL );
1233 }
1234 #else /* use times */
1235 # ifndef HAVE_DOSISH_SYSTEM
1236 { struct tms buf;
1237 times( &buf );
1238 add_randomness( &buf, sizeof buf, RANDOM_ORIGIN_FASTPOLL );
1239 }
1240 # endif
1241 #endif
1242
1243 #ifdef HAVE_GETRUSAGE
1244 # ifdef RUSAGE_SELF
1245 {
1246 struct rusage buf;
1247 /* QNX/Neutrino does return ENOSYS - so we just ignore it and add
1248 whatever is in buf. In a chroot environment it might not work
1249 at all (i.e. because /proc/ is not accessible), so we better
1250 ignore all error codes and hope for the best. */
1251 getrusage (RUSAGE_SELF, &buf );
1252 add_randomness( &buf, sizeof buf, RANDOM_ORIGIN_FASTPOLL );
1253 memset( &buf, 0, sizeof buf );
1254 }
1255 # else /*!RUSAGE_SELF*/
1256 # ifdef __GCC__
1257 # warning There is no RUSAGE_SELF on this system
1258 # endif
1259 # endif /*!RUSAGE_SELF*/
1260 #endif /*HAVE_GETRUSAGE*/
1261
1262 /* Time and clock are available on all systems - so we better do it
1263 just in case one of the above functions didn't work. */
1264 {
1265 time_t x = time(NULL);
1266 add_randomness( &x, sizeof(x), RANDOM_ORIGIN_FASTPOLL );
1267 }
1268 {
1269 clock_t x = clock();
1270 add_randomness( &x, sizeof(x), RANDOM_ORIGIN_FASTPOLL );
1271 }
1272
1273 /* If the system features a fast hardware RNG, read some bytes from
1274 there. */
1275 _gcry_rndhw_poll_fast (add_randomness, RANDOM_ORIGIN_FASTPOLL);
1276 }
1277
1278
1279 /* The fast random pool function as called at some places in
1280 libgcrypt. This is merely a wrapper to make sure that this module
1281 is initialized and to lock the pool. Note, that this function is a
1282 NOP unless a random function has been used or _gcry_initialize (1)
1283 has been used. We use this hack so that the internal use of this
1284 function in cipher_open and md_open won't start filling up the
1285 random pool, even if no random will be required by the process. */
1286 void
1287 _gcry_rngcsprng_fast_poll (void)
1288 {
1289 initialize_basics ();
1290
1291 lock_pool ();
1292 if (rndpool)
1293 {
1294 /* Yes, we are fully initialized. */
1295 do_fast_random_poll ();
1296 }
1297 unlock_pool ();
1298 }
1299
1300
1301
1302 static void
1303 read_random_source (enum random_origins origin, size_t length, int level)
1304 {
1305 if ( !slow_gather_fnc )
1306 log_fatal ("Slow entropy gathering module not yet initialized\n");
1307
1308 if (slow_gather_fnc (add_randomness, origin, length, level) < 0)
1309 log_fatal ("No way to gather entropy for the RNG\n");
1310 }