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 Free Software Foundation, Inc.
5
* This file is part of Libgcrypt.
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.
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.
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/>.
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.
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
41
#include <sys/types.h>
47
#include <sys/times.h>
49
#ifdef HAVE_GETTIMEOFDAY
53
#include <sys/resource.h>
59
#include "../cipher/rmd.h"
61
#include "rand-internal.h"
62
#include "cipher.h" /* Required for the rmd160_hash_buffer() prototype. */
65
#ifndef RAND_MAX /* For SunOS. */
66
#define RAND_MAX 32767
69
/* Check whether we can lock the seed file read write. */
70
#if defined(HAVE_FCNTL) && defined(HAVE_FTRUNCATE) && !defined(HAVE_W32_SYSTEM)
71
#define LOCK_SEED_FILE 1
73
#define LOCK_SEED_FILE 0
76
/* Define the constant we use for transforming the pool at read-out. */
77
#if SIZEOF_UNSIGNED_LONG == 8
78
#define ADD_VALUE 0xa5a5a5a5a5a5a5a5
79
#elif SIZEOF_UNSIGNED_LONG == 4
80
#define ADD_VALUE 0xa5a5a5a5
82
#error weird size for an unsigned long
85
/* Contstants pertaining to the hash pool. */
86
#define BLOCKLEN 64 /* Hash this amount of bytes... */
87
#define DIGESTLEN 20 /* ... into a digest of this length (rmd160). */
88
/* POOLBLOCKS is the number of digests which make up the pool. */
90
/* POOLSIZE must be a multiple of the digest length to make the AND
91
operations faster, the size should also be a multiple of unsigned
93
#define POOLSIZE (POOLBLOCKS*DIGESTLEN)
94
#if (POOLSIZE % SIZEOF_UNSIGNED_LONG)
95
#error Please make sure that poolsize is a multiple of unsigned long
97
#define POOLWORDS (POOLSIZE / SIZEOF_UNSIGNED_LONG)
100
/* RNDPOOL is the pool we use to collect the entropy and to stir it
101
up. Its allocated size is POOLSIZE+BLOCKLEN. Note that this is
102
also an indication on whether the module has been fully
104
static unsigned char *rndpool;
106
/* KEYPOOL is used as a scratch copy to read out random from RNDPOOL.
107
Its allocated size is also POOLSIZE+BLOCKLEN. */
108
static unsigned char *keypool;
110
/* This is the offset into RNDPOOL where the next random bytes are to
112
static size_t pool_writepos;
114
/* When reading data out of KEYPOOL, we start the read at different
115
positions. This variable keeps track on where to read next. */
116
static size_t pool_readpos;
118
/* This flag is set to true as soon as the pool has been completely
119
filled the first time. This may happen either by rereading a seed
120
file or by adding enough entropy. */
121
static int pool_filled;
123
/* This counter is used to track whether the initial seeding has been
124
done with enough bytes from a reliable entropy source. */
125
static size_t pool_filled_counter;
127
/* If random of level GCRY_VERY_STRONG_RANDOM has been requested we
128
have stricter requirements on what kind of entropy is in the pool.
129
In particular POOL_FILLED is not sufficient. Thus we add some
130
extra seeding and set this flag to true if the extra seeding has
132
static int did_initial_extra_seeding;
134
/* This variable is used to estimated the amount of fresh entropy
135
available in RNDPOOL. */
136
static int pool_balance;
138
/* After a mixing operation this variable will be set to true and
139
cleared if new entropy has been added or a remix is required for
141
static int just_mixed;
143
/* The name of the seed file or NULL if no seed file has been defined.
144
The seed file needs to be regsitered at initialiation time. We
145
keep a malloced copy here. */
146
static char *seed_file_name;
148
/* If a seed file has been registered and maybe updated on exit this
150
static int allow_seed_file_update;
152
/* Option flag set at initialiation time to force allocation of the
153
pool in secure memory. */
154
static int secure_alloc;
156
/* This function pointer is set to the actual entropy gathering
157
function during initailization. After initialization it is
158
guaranteed to point to function. (On systems without a random
159
gatherer module a dummy function is used).*/
160
static int (*slow_gather_fnc)(void (*)(const void*, size_t,
161
enum random_origins),
162
enum random_origins, size_t, int);
164
/* This function is set to the actual fast entropy gathering fucntion
165
during initialization. If it is NULL, no such function is
167
static void (*fast_gather_fnc)(void (*)(const void*, size_t,
168
enum random_origins),
169
enum random_origins);
172
/* Option flag useful for debugging and the test suite. If set
173
requests for very strong random are degraded to strong random. Not
174
used by regular applications. */
175
static int quick_test;
177
/* On systems without entropy gathering modules, this flag is set to
178
indicate that the random generator is not working properly. A
179
warning message is issued as well. This is useful only for
180
debugging and during development. */
181
static int faked_rng;
183
/* This is the lock we use to protect all pool operations. */
184
static ath_mutex_t pool_lock = ATH_MUTEX_INITIALIZER;
186
/* This is a helper for assert calls. These calls are used to assert
187
that functions are called in a locked state. It is not meant to be
188
thread-safe but as a method to get aware of missing locks in the
190
static int pool_is_locked;
192
/* This is the lock we use to protect the buffer used by the nonce
194
static ath_mutex_t nonce_buffer_lock = ATH_MUTEX_INITIALIZER;
197
/* We keep some counters in this structure for the sake of the
198
_gcry_random_dump_stats () function. */
201
unsigned long mixrnd;
202
unsigned long mixkey;
203
unsigned long slowpolls;
204
unsigned long fastpolls;
205
unsigned long getbytes1;
206
unsigned long ngetbytes1;
207
unsigned long getbytes2;
208
unsigned long ngetbytes2;
209
unsigned long addbytes;
210
unsigned long naddbytes;
215
/* --- Stuff pertaining to the random daemon support. --- */
216
#ifdef USE_RANDOM_DAEMON
218
/* If ALLOW_DAEMON is true, the module will try to use the random
219
daemon first. If the daemon has failed, this variable is set to
220
back to false and the code continues as normal. Note, we don't
221
test this flag in a locked state because a wrong value does not
222
harm and the trhead will find out itself that the daemon does not
223
work and set it (again) to false. */
224
static int allow_daemon;
226
/* During initialization, the user may set a non-default socket name
227
for accessing the random daemon. If this value is NULL, the
228
default name will be used. */
229
static char *daemon_socket_name;
231
#endif /*USE_RANDOM_DAEMON*/
235
/* --- Prototypes --- */
236
static void read_pool (byte *buffer, size_t length, int level );
237
static void add_randomness (const void *buffer, size_t length,
238
enum random_origins origin);
239
static void random_poll (void);
240
static void do_fast_random_poll (void);
241
static int (*getfnc_gather_random (void))(void (*)(const void*, size_t,
242
enum random_origins),
243
enum random_origins, size_t, int);
244
static void (*getfnc_fast_random_poll (void))(void (*)(const void*, size_t,
245
enum random_origins),
246
enum random_origins);
247
static void read_random_source (enum random_origins origin,
248
size_t length, int level);
249
static int gather_faked (void (*add)(const void*, size_t, enum random_origins),
250
enum random_origins, size_t length, int level );
254
/* --- Functions --- */
257
/* Basic initialization which is required to initialize mutexes and
258
such. It does not run a full initialization so that the filling of
259
the random pool can be delayed until it is actually needed. We
260
assume that this function is used before any concurrent access
263
initialize_basics(void)
265
static int initialized;
271
err = ath_mutex_init (&pool_lock);
273
log_fatal ("failed to create the pool lock: %s\n", strerror (err) );
275
err = ath_mutex_init (&nonce_buffer_lock);
277
log_fatal ("failed to create the nonce buffer lock: %s\n",
280
#ifdef USE_RANDOM_DAEMON
281
_gcry_daemon_initialize_basics ();
282
#endif /*USE_RANDOM_DAEMON*/
284
/* Make sure that we are still using the values we have
285
traditionally used for the random levels. */
286
gcry_assert (GCRY_WEAK_RANDOM == 0
287
&& GCRY_STRONG_RANDOM == 1
288
&& GCRY_VERY_STRONG_RANDOM == 2);
292
/* Take the pool lock. */
298
err = ath_mutex_lock (&pool_lock);
300
log_fatal ("failed to acquire the pool lock: %s\n", strerror (err));
304
/* Release the pool lock. */
311
err = ath_mutex_unlock (&pool_lock);
313
log_fatal ("failed to release the pool lock: %s\n", strerror (err));
317
/* Full initialization of this module. */
321
/* Although the basic initialization should have happened already,
322
we call it here to make sure that all prerequisites are met. */
323
initialize_basics ();
325
/* Now we can look the pool and complete the initialization if
330
/* The data buffer is allocated somewhat larger, so that we can
331
use this extra space (which is allocated in secure memory) as
332
a temporary hash buffer */
333
rndpool = (secure_alloc
334
? gcry_xcalloc_secure (1, POOLSIZE + BLOCKLEN)
335
: gcry_xcalloc (1, POOLSIZE + BLOCKLEN));
336
keypool = (secure_alloc
337
? gcry_xcalloc_secure (1, POOLSIZE + BLOCKLEN)
338
: gcry_xcalloc (1, POOLSIZE + BLOCKLEN));
340
/* Setup the slow entropy gathering function. The code requires
341
that this function exists. */
342
slow_gather_fnc = getfnc_gather_random ();
343
if (!slow_gather_fnc)
346
slow_gather_fnc = gather_faked;
349
/* Setup the fast entropy gathering function. */
350
fast_gather_fnc = getfnc_fast_random_poll ();
359
/* Initialize this random subsystem. If FULL is false, this function
360
merely calls the initialize and does not do anything more. Doing
361
this is not really required but when running in a threaded
362
environment we might get a race condition otherwise. */
364
_gcry_rngcsprng_initialize (int full)
367
initialize_basics ();
374
_gcry_rngcsprng_dump_stats (void)
376
/* In theory we would need to lock the stats here. However this
377
function is usually called during cleanup and then we _might_ run
380
log_info ("random usage: poolsize=%d mixed=%lu polls=%lu/%lu added=%lu/%lu\n"
381
" outmix=%lu getlvl1=%lu/%lu getlvl2=%lu/%lu%s\n",
382
POOLSIZE, rndstats.mixrnd, rndstats.slowpolls, rndstats.fastpolls,
383
rndstats.naddbytes, rndstats.addbytes,
384
rndstats.mixkey, rndstats.ngetbytes1, rndstats.getbytes1,
385
rndstats.ngetbytes2, rndstats.getbytes2,
386
_gcry_rndhw_failed_p()? " (hwrng failed)":"");
390
/* This function should be called during initialization and before
391
intialization of this module to place the random pools into secure
394
_gcry_rngcsprng_secure_alloc (void)
400
/* This may be called before full initialization to degrade the
401
quality of the RNG for the sake of a faster running test suite. */
403
_gcry_rngcsprng_enable_quick_gen (void)
410
_gcry_rngcsprng_set_daemon_socket (const char *socketname)
412
#ifdef USE_RANDOM_DAEMON
413
if (daemon_socket_name)
416
daemon_socket_name = gcry_xstrdup (socketname);
417
#else /*!USE_RANDOM_DAEMON*/
419
#endif /*!USE_RANDOM_DAEMON*/
422
/* With ONOFF set to 1, enable the use of the daemon. With ONOFF set
423
to 0, disable the use of the daemon. With ONOF set to -1, return
424
whether the daemon has been enabled. */
426
_gcry_rngcsprng_use_daemon (int onoff)
428
#ifdef USE_RANDOM_DAEMON
431
/* This is not really thread safe. However it is expected that this
432
function is being called during initialization and at that point
433
we are for other reasons not really thread safe. We do not want
434
to lock it because we might eventually decide that this function
435
may even be called prior to gcry_check_version. */
438
allow_daemon = onoff;
441
#else /*!USE_RANDOM_DAEMON*/
444
#endif /*!USE_RANDOM_DAEMON*/
448
/* This function returns true if no real RNG is available or the
449
quality of the RNG has been degraded for test purposes. */
451
_gcry_rngcsprng_is_faked (void)
453
/* We need to initialize due to the runtime determination of
454
available entropy gather modules. */
456
return (faked_rng || quick_test);
460
/* Add BUFLEN bytes from BUF to the internal random pool. QUALITY
461
should be in the range of 0..100 to indicate the goodness of the
462
entropy added, or -1 for goodness not known. */
464
_gcry_rngcsprng_add_bytes (const void *buf, size_t buflen, int quality)
471
else if (quality > 100)
473
else if (quality < 0)
477
return gpg_error (GPG_ERR_INV_ARG);
479
if (!buflen || quality < 10)
480
return 0; /* Take a shortcut. */
482
/* Because we don't increment the entropy estimation with FASTPOLL,
483
we don't need to take lock that estimation while adding from an
484
external source. This limited entropy estimation also means that
485
we can't take QUALITY into account. */
486
initialize_basics ();
490
nbytes = buflen > POOLSIZE? POOLSIZE : buflen;
493
add_randomness (bufptr, nbytes, RANDOM_ORIGIN_EXTERNAL);
502
/* Public function to fill the buffer with LENGTH bytes of
503
cryptographically strong random bytes. Level GCRY_WEAK_RANDOM is
504
not very strong, GCRY_STRONG_RANDOM is strong enough for most
505
usage, GCRY_VERY_STRONG_RANDOM is good for key generation stuff but
508
_gcry_rngcsprng_randomize (void *buffer, size_t length,
509
enum gcry_random_level level)
513
/* Make sure we are initialized. */
516
/* Handle our hack used for regression tests of Libgcrypt. */
517
if ( quick_test && level > GCRY_STRONG_RANDOM )
518
level = GCRY_STRONG_RANDOM;
520
/* Make sure the level is okay. */
523
#ifdef USE_RANDOM_DAEMON
525
&& !_gcry_daemon_randomize (daemon_socket_name, buffer, length, level))
526
return; /* The daemon succeeded. */
527
allow_daemon = 0; /* Daemon failed - switch off. */
528
#endif /*USE_RANDOM_DAEMON*/
530
/* Acquire the pool lock. */
533
/* Update the statistics. */
534
if (level >= GCRY_VERY_STRONG_RANDOM)
536
rndstats.getbytes2 += length;
537
rndstats.ngetbytes2++;
541
rndstats.getbytes1 += length;
542
rndstats.ngetbytes1++;
545
/* Read the random into the provided buffer. */
546
for (p = buffer; length > 0;)
550
n = length > POOLSIZE? POOLSIZE : length;
551
read_pool (p, n, level);
556
/* Release the pool lock. */
566
|........blocks*20byte........|20byte|..44byte..|
567
<..44byte..> <20byte>
570
+---------------------------|----------+
572
|........blocks*20byte........|20byte|..44byte..|
575
+----------------------------------+
578
|.............................|20byte|..44byte..|
579
<20byte><20byte><..44byte..>
581
| +---------------------+
582
+-----------------------------+ |
584
|.............................|20byte|..44byte..|
587
+-------------------------+
590
|.............................|20byte|..44byte..|
591
<20byte><20byte><..44byte..>
593
and so on until we did this for all blocks.
595
To better protect against implementation errors in this code, we
596
xor a digest of the entire pool into the pool before mixing.
598
Note: this function must only be called with a locked pool.
601
mix_pool(unsigned char *pool)
603
static unsigned char failsafe_digest[DIGESTLEN];
604
static int failsafe_digest_valid;
606
unsigned char *hashbuf = pool + POOLSIZE;
607
unsigned char *p, *pend;
612
#error must have a digest length of 20 for ripe-md-160
615
gcry_assert (pool_is_locked);
616
_gcry_rmd160_init( &md );
618
/* Loop over the pool. */
619
pend = pool + POOLSIZE;
620
memcpy(hashbuf, pend - DIGESTLEN, DIGESTLEN );
621
memcpy(hashbuf+DIGESTLEN, pool, BLOCKLEN-DIGESTLEN);
622
_gcry_rmd160_mixblock( &md, hashbuf);
623
memcpy(pool, hashbuf, 20 );
625
if (failsafe_digest_valid && pool == rndpool)
627
for (i=0; i < 20; i++)
628
pool[i] ^= failsafe_digest[i];
632
for (n=1; n < POOLBLOCKS; n++)
634
memcpy (hashbuf, p, DIGESTLEN);
637
if (p+DIGESTLEN+BLOCKLEN < pend)
638
memcpy (hashbuf+DIGESTLEN, p+DIGESTLEN, BLOCKLEN-DIGESTLEN);
641
unsigned char *pp = p + DIGESTLEN;
643
for (i=DIGESTLEN; i < BLOCKLEN; i++ )
651
_gcry_rmd160_mixblock ( &md, hashbuf);
652
memcpy(p, hashbuf, 20 );
655
/* Our hash implementation does only leave small parts (64 bytes)
656
of the pool on the stack, so it is okay not to require secure
657
memory here. Before we use this pool, it will be copied to the
658
help buffer anyway. */
659
if ( pool == rndpool)
661
_gcry_rmd160_hash_buffer (failsafe_digest, pool, POOLSIZE);
662
failsafe_digest_valid = 1;
665
_gcry_burn_stack (384); /* for the rmd160_mixblock(), rmd160_hash_buffer */
670
_gcry_rngcsprng_set_seed_file (const char *name)
674
seed_file_name = gcry_xstrdup (name);
678
/* Lock an open file identified by file descriptor FD and wait a
679
reasonable time to succeed. With FOR_WRITE set to true a write
680
lock will be taken. FNAME is used only for diagnostics. Returns 0
681
on success or -1 on error. */
683
lock_seed_file (int fd, const char *fname, int for_write)
690
/* We take a lock on the entire file. */
691
memset (&lck, 0, sizeof lck);
692
lck.l_type = for_write? F_WRLCK : F_RDLCK;
693
lck.l_whence = SEEK_SET;
695
while (fcntl (fd, F_SETLK, &lck) == -1)
697
if (errno != EAGAIN && errno != EACCES)
699
log_info (_("can't lock `%s': %s\n"), fname, strerror (errno));
703
if (backoff > 2) /* Show the first message after ~2.25 seconds. */
704
log_info( _("waiting for lock on `%s'...\n"), fname);
708
select (0, NULL, NULL, NULL, &tv);
712
#endif /*LOCK_SEED_FILE*/
717
/* Read in a seed from the random_seed file and return true if this
720
Note: Multiple instances of applications sharing the same random
721
seed file can be started in parallel, in which case they will read
722
out the same pool and then race for updating it (the last update
723
overwrites earlier updates). They will differentiate only by the
724
weak entropy that is added in read_seed_file based on the PID and
725
clock, and up to 16 bytes of weak random non-blockingly. The
726
consequence is that the output of these different instances is
727
correlated to some extent. In the perfect scenario, the attacker
728
can control (or at least guess) the PID and clock of the
729
application, and drain the system's entropy pool to reduce the "up
730
to 16 bytes" above to 0. Then the dependencies of the inital
731
states of the pools are completely known. */
733
read_seed_file (void)
737
unsigned char buffer[POOLSIZE];
740
gcry_assert (pool_is_locked);
745
#ifdef HAVE_DOSISH_SYSTEM
746
fd = open( seed_file_name, O_RDONLY | O_BINARY );
748
fd = open( seed_file_name, O_RDONLY );
750
if( fd == -1 && errno == ENOENT)
752
allow_seed_file_update = 1;
758
log_info(_("can't open `%s': %s\n"), seed_file_name, strerror(errno) );
761
if (lock_seed_file (fd, seed_file_name, 0))
766
if (fstat( fd, &sb ) )
768
log_info(_("can't stat `%s': %s\n"), seed_file_name, strerror(errno) );
772
if (!S_ISREG(sb.st_mode) )
774
log_info(_("`%s' is not a regular file - ignored\n"), seed_file_name );
780
log_info(_("note: random_seed file is empty\n") );
782
allow_seed_file_update = 1;
785
if (sb.st_size != POOLSIZE )
787
log_info(_("warning: invalid size of random_seed file - not used\n") );
794
n = read( fd, buffer, POOLSIZE );
796
while (n == -1 && errno == EINTR );
800
log_fatal(_("can't read `%s': %s\n"), seed_file_name,strerror(errno) );
801
close(fd);/*NOTREACHED*/
807
add_randomness( buffer, POOLSIZE, RANDOM_ORIGIN_INIT );
808
/* add some minor entropy to the pool now (this will also force a mixing) */
811
add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT );
814
time_t x = time(NULL);
815
add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT );
819
add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT );
822
/* And read a few bytes from our entropy source. By using a level
823
* of 0 this will not block and might not return anything with some
824
* entropy drivers, however the rndlinux driver will use
825
* /dev/urandom and return some stuff - Do not read too much as we
826
* want to be friendly to the scare system entropy resource. */
827
read_random_source ( RANDOM_ORIGIN_INIT, 16, GCRY_WEAK_RANDOM );
829
allow_seed_file_update = 1;
835
_gcry_rngcsprng_update_seed_file (void)
837
unsigned long *sp, *dp;
840
/* We do only a basic initialization so that we can lock the pool.
841
This is required to cope with the case that this function is
842
called by some cleanup code at a point where the RNG has never
844
initialize_basics ();
847
if ( !seed_file_name || !rndpool || !pool_filled )
852
if ( !allow_seed_file_update )
855
log_info(_("note: random_seed file not updated\n"));
859
/* At this point we know that there is something in the pool and
860
thus we can conclude that the pool has been fully initialized. */
863
/* Copy the entropy pool to a scratch pool and mix both of them. */
864
for (i=0,dp=(unsigned long*)keypool, sp=(unsigned long*)rndpool;
865
i < POOLWORDS; i++, dp++, sp++ )
867
*dp = *sp + ADD_VALUE;
869
mix_pool(rndpool); rndstats.mixrnd++;
870
mix_pool(keypool); rndstats.mixkey++;
872
#if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
873
fd = open (seed_file_name, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY,
877
fd = open (seed_file_name, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR );
879
fd = open (seed_file_name, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR );
884
log_info (_("can't create `%s': %s\n"), seed_file_name, strerror(errno) );
885
else if (lock_seed_file (fd, seed_file_name, 1))
890
else if (ftruncate (fd, 0))
892
log_info(_("can't write `%s': %s\n"), seed_file_name, strerror(errno));
895
#endif /*LOCK_SEED_FILE*/
900
i = write (fd, keypool, POOLSIZE );
902
while (i == -1 && errno == EINTR);
904
log_info (_("can't write `%s': %s\n"),seed_file_name, strerror(errno));
906
log_info (_("can't close `%s': %s\n"),seed_file_name, strerror(errno));
913
/* Read random out of the pool. This function is the core of the
914
public random functions. Note that Level GCRY_WEAK_RANDOM is not
915
anymore handled special and in fact is an alias in the API for
916
level GCRY_STRONG_RANDOM. Must be called with the pool already
919
read_pool (byte *buffer, size_t length, int level)
922
unsigned long *sp, *dp;
923
/* The volatile is there to make sure the compiler does not optimize
924
the code away in case the getpid function is badly attributed.
925
Note that we keep a pid in a static variable as well as in a
926
stack based one; the latter is to detect ill behaving thread
927
libraries, ignoring the pool mutexes. */
928
static volatile pid_t my_pid = (pid_t)(-1);
929
volatile pid_t my_pid2;
931
gcry_assert (pool_is_locked);
934
/* Get our own pid, so that we can detect a fork. */
936
if (my_pid == (pid_t)(-1))
938
if ( my_pid != my_pid2 )
940
/* We detected a plain fork; i.e. we are now the child. Update
941
the static pid and add some randomness. */
946
add_randomness (&x, sizeof(x), RANDOM_ORIGIN_INIT);
947
just_mixed = 0; /* Make sure it will get mixed. */
950
gcry_assert (pool_is_locked);
952
/* Our code does not allow to extract more than POOLSIZE. Better
954
if (length > POOLSIZE)
956
log_bug("too many random bits requested\n");
961
if (read_seed_file() )
965
/* For level 2 quality (key generation) we always make sure that the
966
pool has been seeded enough initially. */
967
if (level == GCRY_VERY_STRONG_RANDOM && !did_initial_extra_seeding)
972
needed = length - pool_balance;
973
if (needed < POOLSIZE/2)
975
else if( needed > POOLSIZE )
977
read_random_source (RANDOM_ORIGIN_EXTRAPOLL, needed,
978
GCRY_VERY_STRONG_RANDOM);
979
pool_balance += needed;
980
did_initial_extra_seeding = 1;
983
/* For level 2 make sure that there is enough random in the pool. */
984
if (level == GCRY_VERY_STRONG_RANDOM && pool_balance < length)
988
if (pool_balance < 0)
990
needed = length - pool_balance;
991
if (needed > POOLSIZE)
993
read_random_source (RANDOM_ORIGIN_EXTRAPOLL, needed,
994
GCRY_VERY_STRONG_RANDOM);
995
pool_balance += needed;
998
/* Make sure the pool is filled. */
1002
/* Always do a fast random poll (we have to use the unlocked version). */
1003
do_fast_random_poll();
1005
/* Mix the pid in so that we for sure won't deliver the same random
1008
pid_t apid = my_pid;
1009
add_randomness (&apid, sizeof (apid), RANDOM_ORIGIN_INIT);
1012
/* Mix the pool (if add_randomness() didn't it). */
1019
/* Create a new pool. */
1020
for(i=0,dp=(unsigned long*)keypool, sp=(unsigned long*)rndpool;
1021
i < POOLWORDS; i++, dp++, sp++ )
1022
*dp = *sp + ADD_VALUE;
1024
/* Mix both pools. */
1025
mix_pool(rndpool); rndstats.mixrnd++;
1026
mix_pool(keypool); rndstats.mixkey++;
1028
/* Read the requested data. We use a read pointer to read from a
1029
different position each time. */
1032
*buffer++ = keypool[pool_readpos++];
1033
if (pool_readpos >= POOLSIZE)
1038
if (pool_balance < 0)
1041
/* Clear the keypool. */
1042
memset (keypool, 0, POOLSIZE);
1044
/* We need to detect whether a fork has happened. A fork might have
1045
an identical pool and thus the child and the parent could emit
1046
the very same random number. This test here is to detect forks
1047
in a multi-threaded process. It does not work with all thread
1048
implementations in particular not with pthreads. However it is
1049
good enough for GNU Pth. */
1050
if ( getpid () != my_pid2 )
1053
add_randomness (&x, sizeof(x), RANDOM_ORIGIN_INIT);
1054
just_mixed = 0; /* Make sure it will get mixed. */
1055
my_pid = x; /* Also update the static pid. */
1062
/* Add LENGTH bytes of randomness from buffer to the pool. ORIGIN is
1063
used to specify the randomness origin. This is one of the
1064
RANDOM_ORIGIN_* values. */
1066
add_randomness (const void *buffer, size_t length, enum random_origins origin)
1068
const unsigned char *p = buffer;
1071
gcry_assert (pool_is_locked);
1073
rndstats.addbytes += length;
1074
rndstats.naddbytes++;
1077
rndpool[pool_writepos++] ^= *p++;
1079
if (pool_writepos >= POOLSIZE )
1081
/* It is possible that we are invoked before the pool is
1082
filled using an unreliable origin of entropy, for example
1083
the fast random poll. To avoid flagging the pool as
1084
filled in this case, we track the initial filling state
1085
separately. See also the remarks about the seed file. */
1086
if (origin >= RANDOM_ORIGIN_SLOWPOLL && !pool_filled)
1088
pool_filled_counter += count;
1090
if (pool_filled_counter >= POOLSIZE)
1094
mix_pool(rndpool); rndstats.mixrnd++;
1095
just_mixed = !length;
1105
rndstats.slowpolls++;
1106
read_random_source (RANDOM_ORIGIN_SLOWPOLL, POOLSIZE/5, GCRY_STRONG_RANDOM);
1110
/* Runtime determination of the slow entropy gathering module. */
1112
getfnc_gather_random (void))(void (*)(const void*, size_t,
1113
enum random_origins),
1114
enum random_origins, size_t, int)
1116
int (*fnc)(void (*)(const void*, size_t, enum random_origins),
1117
enum random_origins, size_t, int);
1120
if ( !access (NAME_OF_DEV_RANDOM, R_OK)
1121
&& !access (NAME_OF_DEV_URANDOM, R_OK))
1123
fnc = _gcry_rndlinux_gather_random;
1129
if ( _gcry_rndegd_connect_socket (1) != -1 )
1131
fnc = _gcry_rndegd_gather_random;
1137
fnc = _gcry_rndunix_gather_random;
1142
fnc = _gcry_rndw32_gather_random;
1146
log_fatal (_("no entropy gathering module detected\n"));
1148
return NULL; /*NOTREACHED*/
1151
/* Runtime determination of the fast entropy gathering function.
1152
(Currently a compile time method is used.) */
1154
getfnc_fast_random_poll (void))( void (*)(const void*, size_t,
1155
enum random_origins),
1156
enum random_origins)
1159
return _gcry_rndw32_gather_random_fast;
1167
do_fast_random_poll (void)
1169
gcry_assert (pool_is_locked);
1171
rndstats.fastpolls++;
1173
if (fast_gather_fnc)
1174
fast_gather_fnc (add_randomness, RANDOM_ORIGIN_FASTPOLL);
1176
/* Continue with the generic functions. */
1181
add_randomness( &tv, sizeof(tv), RANDOM_ORIGIN_FASTPOLL );
1183
#elif HAVE_GETTIMEOFDAY
1186
if( gettimeofday( &tv, NULL ) )
1188
add_randomness( &tv.tv_sec, sizeof(tv.tv_sec), RANDOM_ORIGIN_FASTPOLL );
1189
add_randomness( &tv.tv_usec, sizeof(tv.tv_usec), RANDOM_ORIGIN_FASTPOLL );
1191
#elif HAVE_CLOCK_GETTIME
1192
{ struct timespec tv;
1193
if( clock_gettime( CLOCK_REALTIME, &tv ) == -1 )
1195
add_randomness( &tv.tv_sec, sizeof(tv.tv_sec), RANDOM_ORIGIN_FASTPOLL );
1196
add_randomness( &tv.tv_nsec, sizeof(tv.tv_nsec), RANDOM_ORIGIN_FASTPOLL );
1198
#else /* use times */
1199
# ifndef HAVE_DOSISH_SYSTEM
1202
add_randomness( &buf, sizeof buf, RANDOM_ORIGIN_FASTPOLL );
1207
#ifdef HAVE_GETRUSAGE
1211
/* QNX/Neutrino does return ENOSYS - so we just ignore it and add
1212
whatever is in buf. In a chroot environment it might not work
1213
at all (i.e. because /proc/ is not accessible), so we better
1214
ignore all error codes and hope for the best. */
1215
getrusage (RUSAGE_SELF, &buf );
1216
add_randomness( &buf, sizeof buf, RANDOM_ORIGIN_FASTPOLL );
1217
memset( &buf, 0, sizeof buf );
1219
# else /*!RUSAGE_SELF*/
1221
# warning There is no RUSAGE_SELF on this system
1223
# endif /*!RUSAGE_SELF*/
1224
#endif /*HAVE_GETRUSAGE*/
1226
/* Time and clock are availabe on all systems - so we better do it
1227
just in case one of the above functions didn't work. */
1229
time_t x = time(NULL);
1230
add_randomness( &x, sizeof(x), RANDOM_ORIGIN_FASTPOLL );
1233
clock_t x = clock();
1234
add_randomness( &x, sizeof(x), RANDOM_ORIGIN_FASTPOLL );
1237
/* If the system features a fast hardware RNG, read some bytes from
1239
_gcry_rndhw_poll_fast (add_randomness, RANDOM_ORIGIN_FASTPOLL);
1243
/* The fast random pool function as called at some places in
1244
libgcrypt. This is merely a wrapper to make sure that this module
1245
is initalized and to look the pool. Note, that this function is a
1246
NOP unless a random function has been used or _gcry_initialize (1)
1247
has been used. We use this hack so that the internal use of this
1248
function in cipher_open and md_open won't start filling up the
1249
random pool, even if no random will be required by the process. */
1251
_gcry_rngcsprng_fast_poll (void)
1253
initialize_basics ();
1258
/* Yes, we are fully initialized. */
1259
do_fast_random_poll ();
1267
read_random_source (enum random_origins orgin, size_t length, int level )
1269
if ( !slow_gather_fnc )
1270
log_fatal ("Slow entropy gathering module not yet initialized\n");
1272
if ( slow_gather_fnc (add_randomness, orgin, length, level) < 0)
1273
log_fatal ("No way to gather entropy for the RNG\n");
1278
gather_faked (void (*add)(const void*, size_t, enum random_origins),
1279
enum random_origins origin, size_t length, int level )
1281
static int initialized=0;
1290
log_info(_("WARNING: using insecure random number generator!!\n"));
1293
srand( time(NULL)*getpid());
1295
srandom( time(NULL)*getpid());
1299
p = buffer = gcry_xmalloc( length );
1303
*p++ = ((unsigned)(1 + (int) (256.0*rand()/(RAND_MAX+1.0)))-1);
1306
*p++ = ((unsigned)(1 + (int) (256.0*random()/(RAND_MAX+1.0)))-1);
1308
add_randomness ( buffer, length, origin );
1310
return 0; /* okay */
1314
/* Create an unpredicable nonce of LENGTH bytes in BUFFER. */
1316
_gcry_rngcsprng_create_nonce (void *buffer, size_t length)
1318
static unsigned char nonce_buffer[20+8];
1319
static int nonce_buffer_initialized = 0;
1320
static volatile pid_t my_pid; /* The volatile is there to make sure the
1321
compiler does not optimize the code away
1322
in case the getpid function is badly
1324
volatile pid_t apid;
1329
/* Make sure we are initialized. */
1332
#ifdef USE_RANDOM_DAEMON
1334
&& !_gcry_daemon_create_nonce (daemon_socket_name, buffer, length))
1335
return; /* The daemon succeeded. */
1336
allow_daemon = 0; /* Daemon failed - switch off. */
1337
#endif /*USE_RANDOM_DAEMON*/
1339
/* Acquire the nonce buffer lock. */
1340
err = ath_mutex_lock (&nonce_buffer_lock);
1342
log_fatal ("failed to acquire the nonce buffer lock: %s\n",
1346
/* The first time intialize our buffer. */
1347
if (!nonce_buffer_initialized)
1349
time_t atime = time (NULL);
1354
if ((sizeof apid + sizeof atime) > sizeof nonce_buffer)
1357
/* Initialize the first 20 bytes with a reasonable value so that
1358
a failure of gcry_randomize won't affect us too much. Don't
1359
care about the uninitialized remaining bytes. */
1361
memcpy (p, &xpid, sizeof xpid);
1363
memcpy (p, &atime, sizeof atime);
1365
/* Initialize the never changing private part of 64 bits. */
1366
gcry_randomize (nonce_buffer+20, 8, GCRY_WEAK_RANDOM);
1368
nonce_buffer_initialized = 1;
1370
else if ( my_pid != apid )
1372
/* We forked. Need to reseed the buffer - doing this for the
1373
private part should be sufficient. */
1374
gcry_randomize (nonce_buffer+20, 8, GCRY_WEAK_RANDOM);
1375
/* Update the pid so that we won't run into here again and
1380
/* Create the nonce by hashing the entire buffer, returning the hash
1381
and updating the first 20 bytes of the buffer with this hash. */
1382
for (p = buffer; length > 0; length -= n, p += n)
1384
_gcry_sha1_hash_buffer (nonce_buffer,
1385
nonce_buffer, sizeof nonce_buffer);
1386
n = length > 20? 20 : length;
1387
memcpy (p, nonce_buffer, n);
1391
/* Release the nonce buffer lock. */
1392
err = ath_mutex_unlock (&nonce_buffer_lock);
1394
log_fatal ("failed to release the nonce buffer lock: %s\n",