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