1
/* random.c - random number generator
2
* Copyright (C) 1998, 2000, 2001, 2002, 2003,
3
* 2004, 2005, 2006, 2007 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 paper: "Software Generation of Practically Strong
24
Random Numbers". See also chapter 6 in his book "Cryptographic
25
Security Architecture", New York, 2004, ISBN 0-387-95387-6.
36
#include <sys/types.h>
42
#include <sys/times.h>
44
#ifdef HAVE_GETTIMEOFDAY
48
#include <sys/resource.h>
56
#include "rand-internal.h"
57
#include "cipher.h" /* Required for the rmd160_hash_buffer() prototype. */
60
#ifndef RAND_MAX /* For SunOS. */
61
#define RAND_MAX 32767
64
/* Check whether we can lock the seed file read write. */
65
#if defined(HAVE_FCNTL) && defined(HAVE_FTRUNCATE) && !defined(HAVE_W32_SYSTEM)
66
#define LOCK_SEED_FILE 1
68
#define LOCK_SEED_FILE 0
71
/* Define the constant we use for transforming the pool at read-out. */
72
#if SIZEOF_UNSIGNED_LONG == 8
73
#define ADD_VALUE 0xa5a5a5a5a5a5a5a5
74
#elif SIZEOF_UNSIGNED_LONG == 4
75
#define ADD_VALUE 0xa5a5a5a5
77
#error weird size for an unsigned long
80
/* Contstants pertaining to the hash pool. */
81
#define BLOCKLEN 64 /* Hash this amount of bytes... */
82
#define DIGESTLEN 20 /* ... into a digest of this length (rmd160). */
83
/* POOLBLOCKS is the number of digests which make up the pool. */
85
/* POOLSIZE must be a multiple of the digest length to make the AND
86
operations faster, the size should also be a multiple of unsigned
88
#define POOLSIZE (POOLBLOCKS*DIGESTLEN)
89
#if (POOLSIZE % SIZEOF_UNSIGNED_LONG)
90
#error Please make sure that poolsize is a multiple of unsigned long
92
#define POOLWORDS (POOLSIZE / SIZEOF_UNSIGNED_LONG)
95
/* RNDPOOL is the pool we use to collect the entropy and to stir it
96
up. Its allocated size is POOLSIZE+BLOCKLEN. Note that this is
97
also an indication on whether the module has been fully
99
static unsigned char *rndpool;
101
/* KEYPOOL is used as a scratch copy to read out random from RNDPOOL.
102
Its allocated size is also POOLSIZE+BLOCKLEN. */
103
static unsigned char *keypool;
105
/* This is the offset into RNDPOOL where the next random bytes are to
107
static size_t pool_writepos;
109
/* When reading data out of KEYPOOL, we start the read at different
110
positions. This variable keeps track on where to read next. */
111
static size_t pool_readpos;
113
/* This flag is set to true as soon as the pool has been completely
114
filled the first time. This may happen either by rereading a seed
115
file or by adding enough entropy. */
116
static int pool_filled;
118
/* This counter is used to track whether the initial seeding has been
119
done with enough bytes from a reliable entropy source. */
120
static size_t pool_filled_counter;
122
/* If random of level GCRY_VERY_STRONG_RANDOM has been requested we
123
have stricter requirements on what kind of entropy is in the pool.
124
In particular POOL_FILLED is not sufficient. Thus we add some
125
extra seeding and set this flag to true if the extra seeding has
127
static int did_initial_extra_seeding;
129
/* This variable is used to estimated the amount of fresh entropy
130
available in RNDPOOL. */
131
static int pool_balance;
133
/* After a mixing operation this variable will be set to true and
134
cleared if new entropy has been added or a remix is required for
136
static int just_mixed;
138
/* The name of the seed file or NULL if no seed file has been defined.
139
The seed file needs to be regsitered at initialiation time. We
140
keep a malloced copy here. */
141
static char *seed_file_name;
143
/* If a seed file has been registered and maybe updated on exit this
145
static int allow_seed_file_update;
147
/* Option flag set at initialiation time to force allocation of the
148
pool in secure memory. */
149
static int secure_alloc;
151
/* This function pointer is set to the actual entropy gathering
152
function during initailization. After initialization it is
153
guaranteed to point to function. (On systems without a random
154
gatherer module a dummy function is used).*/
155
static int (*slow_gather_fnc)(void (*)(const void*, size_t,
156
enum random_origins),
157
enum random_origins, size_t, int);
159
/* This function is set to the actual fast entropy gathering fucntion
160
during initialization. If it is NULL, no such function is
162
static void (*fast_gather_fnc)(void (*)(const void*, size_t,
163
enum random_origins),
164
enum random_origins);
167
/* Option flag useful for debugging and the test suite. If set
168
requests for very strong random are degraded to strong random. Not
169
used by regular applications. */
170
static int quick_test;
172
/* On systems without entropy gathering modules, this flag is set to
173
indicate that the random generator is not working properly. A
174
warning message is issued as well. This is useful only for
175
debugging and during development. */
176
static int faked_rng;
178
/* This is the lock we use to protect all pool operations. */
179
static ath_mutex_t pool_lock = ATH_MUTEX_INITIALIZER;
181
/* This is a helper for assert calls. These calls are used to assert
182
that functions are called in a locked state. It is not meant to be
183
thread-safe but as a method to get aware of missing locks in the
185
static int pool_is_locked;
187
/* This is the lock we use to protect the buffer used by the nonce
189
static ath_mutex_t nonce_buffer_lock = ATH_MUTEX_INITIALIZER;
192
/* We keep some counters in this structure for the sake of the
193
_gcry_random_dump_stats () function. */
196
unsigned long mixrnd;
197
unsigned long mixkey;
198
unsigned long slowpolls;
199
unsigned long fastpolls;
200
unsigned long getbytes1;
201
unsigned long ngetbytes1;
202
unsigned long getbytes2;
203
unsigned long ngetbytes2;
204
unsigned long addbytes;
205
unsigned long naddbytes;
209
/* If not NULL a progress function called from certain places and the
210
opaque value passed along. Registred by
211
_gcry_register_random_progress (). */
212
static void (*progress_cb) (void *,const char*,int,int, int );
213
static void *progress_cb_data;
216
/* --- Stuff pertaining to the random daemon support. --- */
217
#ifdef USE_RANDOM_DAEMON
219
/* If ALLOW_DAEMON is true, the module will try to use the random
220
daemon first. If the daemon has failed, this variable is set to
221
back to false and the code continues as normal. Note, we don't
222
test this flag in a locked state because a wrong value does not
223
harm and the trhead will find out itself that the daemon does not
224
work and set it (again) to false. */
225
static int allow_daemon;
227
/* During initialization, the user may set a non-default socket name
228
for accessing the random daemon. If this value is NULL, the
229
default name will be used. */
230
static char *daemon_socket_name;
232
#endif /*USE_RANDOM_DAEMON*/
236
/* --- Prototypes --- */
237
static void read_pool (byte *buffer, size_t length, int level );
238
static void add_randomness (const void *buffer, size_t length,
239
enum random_origins origin);
240
static void random_poll (void);
241
static void do_fast_random_poll (void);
242
static int (*getfnc_gather_random (void))(void (*)(const void*, size_t,
243
enum random_origins),
244
enum random_origins, size_t, int);
245
static void (*getfnc_fast_random_poll (void))(void (*)(const void*, size_t,
246
enum random_origins),
247
enum random_origins);
248
static void read_random_source (enum random_origins origin,
249
size_t length, int level);
250
static int gather_faked (void (*add)(const void*, size_t, enum random_origins),
251
enum random_origins, size_t length, int level );
255
/* --- Functions --- */
258
/* Basic initialization which is required to initialize mutexes and
259
such. It does not run a full initialization so that the filling of
260
the random pool can be delayed until it is actually needed. We
261
assume that this function is used before any concurrent access
264
initialize_basics(void)
266
static int initialized;
272
err = ath_mutex_init (&pool_lock);
274
log_fatal ("failed to create the pool lock: %s\n", strerror (err) );
276
err = ath_mutex_init (&nonce_buffer_lock);
278
log_fatal ("failed to create the nonce buffer lock: %s\n",
281
#ifdef USE_RANDOM_DAEMON
282
_gcry_daemon_initialize_basics ();
283
#endif /*USE_RANDOM_DAEMON*/
285
/* Make sure that we are still using the values we have
286
traditionally used for the random levels. */
287
assert ( GCRY_WEAK_RANDOM == 0
288
&& GCRY_STRONG_RANDOM == 1
289
&& GCRY_VERY_STRONG_RANDOM == 2);
293
/* Take the pool lock. */
299
err = ath_mutex_lock (&pool_lock);
301
log_fatal ("failed to acquire the pool lock: %s\n", strerror (err));
305
/* Release the pool lock. */
312
err = ath_mutex_unlock (&pool_lock);
314
log_fatal ("failed to release the pool lock: %s\n", strerror (err));
318
/* Full initialization of this module. */
322
/* Although the basic initialization should have happened already,
323
we call it here to make sure that all prerequisites are met. */
324
initialize_basics ();
326
/* Now we can look the pool and complete the initialization if
331
/* The data buffer is allocated somewhat larger, so that we can
332
use this extra space (which is allocated in secure memory) as
333
a temporary hash buffer */
334
rndpool = (secure_alloc
335
? gcry_xcalloc_secure (1, POOLSIZE + BLOCKLEN)
336
: gcry_xcalloc (1, POOLSIZE + BLOCKLEN));
337
keypool = (secure_alloc
338
? gcry_xcalloc_secure (1, POOLSIZE + BLOCKLEN)
339
: gcry_xcalloc (1, POOLSIZE + BLOCKLEN));
341
/* Setup the slow entropy gathering function. The code requires
342
that this function exists. */
343
slow_gather_fnc = getfnc_gather_random ();
344
if (!slow_gather_fnc)
347
slow_gather_fnc = gather_faked;
350
/* Setup the fast entropy gathering function. */
351
fast_gather_fnc = getfnc_fast_random_poll ();
358
/* Used to register a progress callback. */
360
_gcry_register_random_progress (void (*cb)(void *,const char*,int,int,int),
364
progress_cb_data = cb_data;
368
/* This progress function is currently used by the random modules to give hint
369
on how much more entropy is required. */
371
_gcry_random_progress (const char *what, int printchar, int current, int total)
374
progress_cb (progress_cb_data, what, printchar, current, total);
378
/* Initialize this random subsystem. If FULL is false, this function
379
merely calls the initialize and does not do anything more. Doing
380
this is not really required but when running in a threaded
381
environment we might get a race condition otherwise. */
383
_gcry_random_initialize (int full)
386
initialize_basics ();
393
_gcry_random_dump_stats ()
395
/* FIXME: don't we need proper locking here? -mo.
396
Yes. However this is usually called during cleanup and thenwe _
397
might_ run into problems. Needs to be checked. -wk */
399
log_info ("random usage: poolsize=%d mixed=%lu polls=%lu/%lu added=%lu/%lu\n"
400
" outmix=%lu getlvl1=%lu/%lu getlvl2=%lu/%lu%s\n",
401
POOLSIZE, rndstats.mixrnd, rndstats.slowpolls, rndstats.fastpolls,
402
rndstats.naddbytes, rndstats.addbytes,
403
rndstats.mixkey, rndstats.ngetbytes1, rndstats.getbytes1,
404
rndstats.ngetbytes2, rndstats.getbytes2,
405
_gcry_rndhw_failed_p()? " (hwrng failed)":"");
409
/* This function should be called during initialization and beore
410
intialization of this module to palce the random pools into secure
413
_gcry_secure_random_alloc()
419
/* This may be called before full initialization to degrade the
420
quality of the RNG for the sake of a faster running test suite. */
422
_gcry_enable_quick_random_gen (void)
429
_gcry_set_random_daemon_socket (const char *socketname)
431
#ifdef USE_RANDOM_DAEMON
432
if (daemon_socket_name)
435
daemon_socket_name = gcry_xstrdup (socketname);
436
#else /*!USE_RANDOM_DAEMON*/
438
#endif /*!USE_RANDOM_DAEMON*/
441
/* With ONOFF set to 1, enable the use of the daemon. With ONOFF set
442
to 0, disable the use of the daemon. With ONOF set to -1, return
443
whether the daemon has been enabled. */
445
_gcry_use_random_daemon (int onoff)
447
#ifdef USE_RANDOM_DAEMON
450
/* FIXME: This is not really thread safe. */
453
allow_daemon = onoff;
456
#else /*!USE_RANDOM_DAEMON*/
459
#endif /*!USE_RANDOM_DAEMON*/
463
/* This function returns true if no real RNG is available or the
464
quality of the RNG has been degraded for test purposes. */
466
_gcry_random_is_faked()
468
/* We need to initialize due to the runtime determination of
469
available entropy gather modules. */
471
return (faked_rng || quick_test);
475
/* Add BUFLEN bytes from BUF to the internal random pool. QUALITY
476
should be in the range of 0..100 to indicate the goodness of the
477
entropy added, or -1 for goodness not known. */
479
gcry_random_add_bytes (const void *buf, size_t buflen, int quality)
486
else if (quality > 100)
488
else if (quality < 0)
492
return gpg_error (GPG_ERR_INV_ARG);
494
if (!buflen || quality < 10)
495
return 0; /* Take a shortcut. */
497
/* Because we don't increment the entropy estimation with FASTPOLL,
498
we don't need to take lock that estimation while adding from an
499
external source. This limited entropy estimation also means that
500
we can't take QUALITY into account. */
501
initialize_basics ();
505
nbytes = buflen > POOLSIZE? POOLSIZE : buflen;
508
add_randomness (bufptr, nbytes, RANDOM_ORIGIN_EXTERNAL);
517
/* The public function to return random data of the quality LEVEL.
518
Returns a pointer to a newly allocated and randomized buffer of
519
LEVEL and NBYTES length. Caller must free the buffer. */
521
gcry_random_bytes (size_t nbytes, enum gcry_random_level level)
527
buffer = gcry_xmalloc (nbytes);
528
gcry_randomize (buffer, nbytes, level);
534
/* The public function to return random data of the quality LEVEL;
535
this version of the function returns the random in a buffer allocated
536
in secure memory. Caller must free the buffer. */
538
gcry_random_bytes_secure( size_t nbytes, enum gcry_random_level level )
544
buffer = secure_alloc ? gcry_xmalloc_secure (nbytes)
545
: gcry_xmalloc (nbytes);
546
gcry_randomize (buffer, nbytes, level);
552
/* Public function to fill the buffer with LENGTH bytes of
553
cryptographically strong random bytes. Level GCRY_WEAK_RANDOM is
554
not very strong, GCRY_STRONG_RANDOM is strong enough for most
555
usage, GCRY_VERY_STRONG_RANDOM is good for key generation stuff but
558
gcry_randomize (void *buffer, size_t length, enum gcry_random_level level)
562
/* Make sure we are initialized. */
565
/* Handle our hack used for regression tests of Libgcrypt. */
566
if ( quick_test && level > GCRY_STRONG_RANDOM )
567
level = GCRY_STRONG_RANDOM;
569
/* Make sure the level is okay. */
572
#ifdef USE_RANDOM_DAEMON
574
&& !_gcry_daemon_randomize (daemon_socket_name, buffer, length, level))
575
return; /* The daemon succeeded. */
576
allow_daemon = 0; /* Daemon failed - switch off. */
577
#endif /*USE_RANDOM_DAEMON*/
579
/* Acquire the pool lock. */
582
/* Update the statistics. */
583
if (level >= GCRY_VERY_STRONG_RANDOM)
585
rndstats.getbytes2 += length;
586
rndstats.ngetbytes2++;
590
rndstats.getbytes1 += length;
591
rndstats.ngetbytes1++;
594
/* Read the random into the provided buffer. */
595
for (p = buffer; length > 0;)
599
n = length > POOLSIZE? POOLSIZE : length;
600
read_pool (p, n, level);
605
/* Release the pool lock. */
615
|........blocks*20byte........|20byte|..44byte..|
616
<..44byte..> <20byte>
619
+---------------------------|----------+
621
|........blocks*20byte........|20byte|..44byte..|
624
+----------------------------------+
627
|.............................|20byte|..44byte..|
628
<20byte><20byte><..44byte..>
630
| +---------------------+
631
+-----------------------------+ |
633
|.............................|20byte|..44byte..|
636
+-------------------------+
639
|.............................|20byte|..44byte..|
640
<20byte><20byte><..44byte..>
642
and so on until we did this for all blocks.
644
To better protect against implementation errors in this code, we
645
xor a digest of the entire pool into the pool before mixing.
647
Note: this function must only be called with a locked pool.
650
mix_pool(unsigned char *pool)
652
static unsigned char failsafe_digest[DIGESTLEN];
653
static int failsafe_digest_valid;
655
unsigned char *hashbuf = pool + POOLSIZE;
656
unsigned char *p, *pend;
661
#error must have a digest length of 20 for ripe-md-160
664
assert (pool_is_locked);
665
_gcry_rmd160_init( &md );
667
/* Loop over the pool. */
668
pend = pool + POOLSIZE;
669
memcpy(hashbuf, pend - DIGESTLEN, DIGESTLEN );
670
memcpy(hashbuf+DIGESTLEN, pool, BLOCKLEN-DIGESTLEN);
671
_gcry_rmd160_mixblock( &md, hashbuf);
672
memcpy(pool, hashbuf, 20 );
674
if (failsafe_digest_valid && pool == rndpool)
676
for (i=0; i < 20; i++)
677
pool[i] ^= failsafe_digest[i];
681
for (n=1; n < POOLBLOCKS; n++)
683
memcpy (hashbuf, p, DIGESTLEN);
686
if (p+DIGESTLEN+BLOCKLEN < pend)
687
memcpy (hashbuf+DIGESTLEN, p+DIGESTLEN, BLOCKLEN-DIGESTLEN);
690
unsigned char *pp = p + DIGESTLEN;
692
for (i=DIGESTLEN; i < BLOCKLEN; i++ )
700
_gcry_rmd160_mixblock ( &md, hashbuf);
701
memcpy(p, hashbuf, 20 );
704
/* Our hash implementation does only leave small parts (64 bytes)
705
of the pool on the stack, so it is okay not to require secure
706
memory here. Before we use this pool, it will be copied to the
707
help buffer anyway. */
708
if ( pool == rndpool)
710
_gcry_rmd160_hash_buffer (failsafe_digest, pool, POOLSIZE);
711
failsafe_digest_valid = 1;
714
_gcry_burn_stack (384); /* for the rmd160_mixblock(), rmd160_hash_buffer */
719
_gcry_set_random_seed_file( const char *name )
723
seed_file_name = gcry_xstrdup (name);
727
/* Lock an open file identified by file descriptor FD and wait a
728
reasonable time to succeed. With FOR_WRITE set to true a write
729
lock will be taken. FNAME is used only for diagnostics. Returns 0
730
on success or -1 on error. */
732
lock_seed_file (int fd, const char *fname, int for_write)
739
/* We take a lock on the entire file. */
740
memset (&lck, 0, sizeof lck);
741
lck.l_type = for_write? F_WRLCK : F_RDLCK;
742
lck.l_whence = SEEK_SET;
744
while (fcntl (fd, F_SETLK, &lck) == -1)
746
if (errno != EAGAIN && errno != EACCES)
748
log_info (_("can't lock `%s': %s\n"), fname, strerror (errno));
752
if (backoff > 2) /* Show the first message after ~2.25 seconds. */
753
log_info( _("waiting for lock on `%s'...\n"), fname);
757
select (0, NULL, NULL, NULL, &tv);
761
#endif /*LOCK_SEED_FILE*/
766
/* Read in a seed from the random_seed file and return true if this
769
Note: Multiple instances of applications sharing the same random
770
seed file can be started in parallel, in which case they will read
771
out the same pool and then race for updating it (the last update
772
overwrites earlier updates). They will differentiate only by the
773
weak entropy that is added in read_seed_file based on the PID and
774
clock, and up to 16 bytes of weak random non-blockingly. The
775
consequence is that the output of these different instances is
776
correlated to some extent. In the perfect scenario, the attacker
777
can control (or at least guess) the PID and clock of the
778
application, and drain the system's entropy pool to reduce the "up
779
to 16 bytes" above to 0. Then the dependencies of the inital
780
states of the pools are completely known. */
782
read_seed_file (void)
786
unsigned char buffer[POOLSIZE];
789
assert (pool_is_locked);
794
#ifdef HAVE_DOSISH_SYSTEM
795
fd = open( seed_file_name, O_RDONLY | O_BINARY );
797
fd = open( seed_file_name, O_RDONLY );
799
if( fd == -1 && errno == ENOENT)
801
allow_seed_file_update = 1;
807
log_info(_("can't open `%s': %s\n"), seed_file_name, strerror(errno) );
810
if (lock_seed_file (fd, seed_file_name, 0))
815
if (fstat( fd, &sb ) )
817
log_info(_("can't stat `%s': %s\n"), seed_file_name, strerror(errno) );
821
if (!S_ISREG(sb.st_mode) )
823
log_info(_("`%s' is not a regular file - ignored\n"), seed_file_name );
829
log_info(_("note: random_seed file is empty\n") );
831
allow_seed_file_update = 1;
834
if (sb.st_size != POOLSIZE )
836
log_info(_("warning: invalid size of random_seed file - not used\n") );
843
n = read( fd, buffer, POOLSIZE );
845
while (n == -1 && errno == EINTR );
849
log_fatal(_("can't read `%s': %s\n"), seed_file_name,strerror(errno) );
850
close(fd);/*NOTREACHED*/
856
add_randomness( buffer, POOLSIZE, RANDOM_ORIGIN_INIT );
857
/* add some minor entropy to the pool now (this will also force a mixing) */
860
add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT );
863
time_t x = time(NULL);
864
add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT );
868
add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT );
871
/* And read a few bytes from our entropy source. By using a level
872
* of 0 this will not block and might not return anything with some
873
* entropy drivers, however the rndlinux driver will use
874
* /dev/urandom and return some stuff - Do not read too much as we
875
* want to be friendly to the scare system entropy resource. */
876
read_random_source ( RANDOM_ORIGIN_INIT, 16, GCRY_WEAK_RANDOM );
878
allow_seed_file_update = 1;
884
_gcry_update_random_seed_file()
886
unsigned long *sp, *dp;
889
/* We do only a basic initialization so that we can lock the pool.
890
This is required to cope with the case that this function is
891
called by some cleanup code at a point where the RNG has never
893
initialize_basics ();
896
if ( !seed_file_name || !rndpool || !pool_filled )
901
if ( !allow_seed_file_update )
904
log_info(_("note: random_seed file not updated\n"));
908
/* At this point we know that there is something in the pool and
909
thus we can conclude that the pool has been fully initialized. */
912
/* Copy the entropy pool to a scratch pool and mix both of them. */
913
for (i=0,dp=(unsigned long*)keypool, sp=(unsigned long*)rndpool;
914
i < POOLWORDS; i++, dp++, sp++ )
916
*dp = *sp + ADD_VALUE;
918
mix_pool(rndpool); rndstats.mixrnd++;
919
mix_pool(keypool); rndstats.mixkey++;
921
#if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
922
fd = open (seed_file_name, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY,
926
fd = open (seed_file_name, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR );
928
fd = open (seed_file_name, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR );
933
log_info (_("can't create `%s': %s\n"), seed_file_name, strerror(errno) );
934
else if (lock_seed_file (fd, seed_file_name, 1))
939
else if (ftruncate (fd, 0))
941
log_info(_("can't write `%s': %s\n"), seed_file_name, strerror(errno));
944
#endif /*LOCK_SEED_FILE*/
949
i = write (fd, keypool, POOLSIZE );
951
while (i == -1 && errno == EINTR);
953
log_info (_("can't write `%s': %s\n"),seed_file_name, strerror(errno));
955
log_info (_("can't close `%s': %s\n"),seed_file_name, strerror(errno));
962
/* Read random out of the pool. This function is the core of the
963
public random functions. Note that Level GCRY_WEAK_RANDOM is not
964
anymore handled special and in fact is an alias in the API for
965
level GCRY_STRONG_RANDOM. Must be called with the pool already
968
read_pool (byte *buffer, size_t length, int level)
971
unsigned long *sp, *dp;
972
/* The volatile is there to make sure the compiler does not optimize
973
the code away in case the getpid function is badly attributed.
974
Note that we keep a pid in a static variable as well as in a
975
stack based one; the latter is to detect ill behaving thread
976
libraries, ignoring the pool mutexes. */
977
static volatile pid_t my_pid = (pid_t)(-1);
978
volatile pid_t my_pid2;
980
assert (pool_is_locked);
983
/* Get our own pid, so that we can detect a fork. */
985
if (my_pid == (pid_t)(-1))
987
if ( my_pid != my_pid2 )
989
/* We detected a plain fork; i.e. we are now the child. Update
990
the static pid and add some randomness. */
995
add_randomness (&x, sizeof(x), RANDOM_ORIGIN_INIT);
996
just_mixed = 0; /* Make sure it will get mixed. */
999
assert (pool_is_locked);
1001
/* Our code does not allow to extract more than POOLSIZE. Better
1003
if (length > POOLSIZE)
1005
log_bug("too many random bits requested\n");
1010
if (read_seed_file() )
1014
/* For level 2 quality (key generation) we always make sure that the
1015
pool has been seeded enough initially. */
1016
if (level == GCRY_VERY_STRONG_RANDOM && !did_initial_extra_seeding)
1021
needed = length - pool_balance;
1022
if (needed < POOLSIZE/2)
1023
needed = POOLSIZE/2;
1024
else if( needed > POOLSIZE )
1026
read_random_source (RANDOM_ORIGIN_EXTRAPOLL, needed,
1027
GCRY_VERY_STRONG_RANDOM);
1028
pool_balance += needed;
1029
did_initial_extra_seeding = 1;
1032
/* For level 2 make sure that there is enough random in the pool. */
1033
if (level == GCRY_VERY_STRONG_RANDOM && pool_balance < length)
1037
if (pool_balance < 0)
1039
needed = length - pool_balance;
1040
if (needed > POOLSIZE)
1042
read_random_source (RANDOM_ORIGIN_EXTRAPOLL, needed,
1043
GCRY_VERY_STRONG_RANDOM);
1044
pool_balance += needed;
1047
/* Make sure the pool is filled. */
1048
while (!pool_filled)
1051
/* Always do a fast random poll (we have to use the unlocked version). */
1052
do_fast_random_poll();
1054
/* Mix the pid in so that we for sure won't deliver the same random
1057
pid_t apid = my_pid;
1058
add_randomness (&apid, sizeof (apid), RANDOM_ORIGIN_INIT);
1061
/* Mix the pool (if add_randomness() didn't it). */
1068
/* Create a new pool. */
1069
for(i=0,dp=(unsigned long*)keypool, sp=(unsigned long*)rndpool;
1070
i < POOLWORDS; i++, dp++, sp++ )
1071
*dp = *sp + ADD_VALUE;
1073
/* Mix both pools. */
1074
mix_pool(rndpool); rndstats.mixrnd++;
1075
mix_pool(keypool); rndstats.mixkey++;
1077
/* Read the requested data. We use a read pointer to read from a
1078
different position each time. */
1081
*buffer++ = keypool[pool_readpos++];
1082
if (pool_readpos >= POOLSIZE)
1087
if (pool_balance < 0)
1090
/* Clear the keypool. */
1091
memset (keypool, 0, POOLSIZE);
1093
/* We need to detect whether a fork has happened. A fork might have
1094
an identical pool and thus the child and the parent could emit
1095
the very same random number. This test here is to detect forks
1096
in a multi-threaded process. It does not work with all thread
1097
implementations in particular not with pthreads. However it is
1098
good enough for GNU Pth. */
1099
if ( getpid () != my_pid2 )
1102
add_randomness (&x, sizeof(x), RANDOM_ORIGIN_INIT);
1103
just_mixed = 0; /* Make sure it will get mixed. */
1104
my_pid = x; /* Also update the static pid. */
1111
/* Add LENGTH bytes of randomness from buffer to the pool. ORIGIN is
1112
used to specify the randomness origin. This is one of the
1113
RANDOM_ORIGIN_* values. */
1115
add_randomness (const void *buffer, size_t length, enum random_origins origin)
1117
const unsigned char *p = buffer;
1120
assert (pool_is_locked);
1122
rndstats.addbytes += length;
1123
rndstats.naddbytes++;
1126
rndpool[pool_writepos++] ^= *p++;
1128
if (pool_writepos >= POOLSIZE )
1130
/* It is possible that we are invoked before the pool is
1131
filled using an unreliable origin of entropy, for example
1132
the fast random poll. To avoid flagging the pool as
1133
filled in this case, we track the initial filling state
1134
separately. See also the remarks about the seed file. */
1135
if (origin >= RANDOM_ORIGIN_SLOWPOLL && !pool_filled)
1137
pool_filled_counter += count;
1139
if (pool_filled_counter >= POOLSIZE)
1143
mix_pool(rndpool); rndstats.mixrnd++;
1144
just_mixed = !length;
1154
rndstats.slowpolls++;
1155
read_random_source (RANDOM_ORIGIN_SLOWPOLL, POOLSIZE/5, GCRY_STRONG_RANDOM);
1159
/* Runtime determination of the slow entropy gathering module. */
1161
getfnc_gather_random (void))(void (*)(const void*, size_t,
1162
enum random_origins),
1163
enum random_origins, size_t, int)
1165
int (*fnc)(void (*)(const void*, size_t, enum random_origins),
1166
enum random_origins, size_t, int);
1169
if ( !access (NAME_OF_DEV_RANDOM, R_OK)
1170
&& !access (NAME_OF_DEV_URANDOM, R_OK))
1172
fnc = _gcry_rndlinux_gather_random;
1178
if ( _gcry_rndegd_connect_socket (1) != -1 )
1180
fnc = _gcry_rndegd_gather_random;
1186
fnc = _gcry_rndunix_gather_random;
1191
fnc = _gcry_rndw32_gather_random;
1195
log_fatal (_("no entropy gathering module detected\n"));
1197
return NULL; /*NOTREACHED*/
1200
/* Runtime determination of the fast entropy gathering function.
1201
(Currently a compile time method is used.) */
1203
getfnc_fast_random_poll (void))( void (*)(const void*, size_t,
1204
enum random_origins),
1205
enum random_origins)
1208
return _gcry_rndw32_gather_random_fast;
1216
do_fast_random_poll (void)
1218
assert (pool_is_locked);
1220
rndstats.fastpolls++;
1222
if (fast_gather_fnc)
1223
fast_gather_fnc (add_randomness, RANDOM_ORIGIN_FASTPOLL);
1225
/* Continue with the generic functions. */
1230
add_randomness( &tv, sizeof(tv), RANDOM_ORIGIN_FASTPOLL );
1232
#elif HAVE_GETTIMEOFDAY
1235
if( gettimeofday( &tv, NULL ) )
1237
add_randomness( &tv.tv_sec, sizeof(tv.tv_sec), RANDOM_ORIGIN_FASTPOLL );
1238
add_randomness( &tv.tv_usec, sizeof(tv.tv_usec), RANDOM_ORIGIN_FASTPOLL );
1240
#elif HAVE_CLOCK_GETTIME
1241
{ struct timespec tv;
1242
if( clock_gettime( CLOCK_REALTIME, &tv ) == -1 )
1244
add_randomness( &tv.tv_sec, sizeof(tv.tv_sec), RANDOM_ORIGIN_FASTPOLL );
1245
add_randomness( &tv.tv_nsec, sizeof(tv.tv_nsec), RANDOM_ORIGIN_FASTPOLL );
1247
#else /* use times */
1248
# ifndef HAVE_DOSISH_SYSTEM
1251
add_randomness( &buf, sizeof buf, RANDOM_ORIGIN_FASTPOLL );
1256
#ifdef HAVE_GETRUSAGE
1260
/* QNX/Neutrino does return ENOSYS - so we just ignore it and add
1261
whatever is in buf. In a chroot environment it might not work
1262
at all (i.e. because /proc/ is not accessible), so we better
1263
ignore all error codes and hope for the best. */
1264
getrusage (RUSAGE_SELF, &buf );
1265
add_randomness( &buf, sizeof buf, RANDOM_ORIGIN_FASTPOLL );
1266
memset( &buf, 0, sizeof buf );
1268
# else /*!RUSAGE_SELF*/
1270
# warning There is no RUSAGE_SELF on this system
1272
# endif /*!RUSAGE_SELF*/
1273
#endif /*HAVE_GETRUSAGE*/
1275
/* Time and clock are availabe on all systems - so we better do it
1276
just in case one of the above functions didn't work. */
1278
time_t x = time(NULL);
1279
add_randomness( &x, sizeof(x), RANDOM_ORIGIN_FASTPOLL );
1282
clock_t x = clock();
1283
add_randomness( &x, sizeof(x), RANDOM_ORIGIN_FASTPOLL );
1286
/* If the system features a fast hardware RNG, read some bytes from
1288
_gcry_rndhw_poll_fast (add_randomness, RANDOM_ORIGIN_FASTPOLL);
1292
/* The fast random pool function as called at some places in
1293
libgcrypt. This is merely a wrapper to make sure that this module
1294
is initalized and to look the pool. Note, that this function is a
1295
NOP unless a random function has been used or _gcry_initialize (1)
1296
has been used. We use this hack so that the internal use of this
1297
function in cipher_open and md_open won't start filling up the
1298
random pool, even if no random will be required by the process. */
1300
_gcry_fast_random_poll (void)
1302
initialize_basics ();
1307
/* Yes, we are fully initialized. */
1308
do_fast_random_poll ();
1316
read_random_source (enum random_origins orgin, size_t length, int level )
1318
if ( !slow_gather_fnc )
1319
log_fatal ("Slow entropy gathering module not yet initialized\n");
1321
if ( slow_gather_fnc (add_randomness, orgin, length, level) < 0)
1322
log_fatal ("No way to gather entropy for the RNG\n");
1327
gather_faked (void (*add)(const void*, size_t, enum random_origins),
1328
enum random_origins origin, size_t length, int level )
1330
static int initialized=0;
1339
log_info(_("WARNING: using insecure random number generator!!\n"));
1342
srand( time(NULL)*getpid());
1344
srandom( time(NULL)*getpid());
1348
p = buffer = gcry_xmalloc( length );
1352
*p++ = ((unsigned)(1 + (int) (256.0*rand()/(RAND_MAX+1.0)))-1);
1355
*p++ = ((unsigned)(1 + (int) (256.0*random()/(RAND_MAX+1.0)))-1);
1357
add_randomness ( buffer, length, origin );
1359
return 0; /* okay */
1363
/* Create an unpredicable nonce of LENGTH bytes in BUFFER. */
1365
gcry_create_nonce (void *buffer, size_t length)
1367
static unsigned char nonce_buffer[20+8];
1368
static int nonce_buffer_initialized = 0;
1369
static volatile pid_t my_pid; /* The volatile is there to make sure the
1370
compiler does not optimize the code away
1371
in case the getpid function is badly
1373
volatile pid_t apid;
1378
/* Make sure we are initialized. */
1381
#ifdef USE_RANDOM_DAEMON
1383
&& !_gcry_daemon_create_nonce (daemon_socket_name, buffer, length))
1384
return; /* The daemon succeeded. */
1385
allow_daemon = 0; /* Daemon failed - switch off. */
1386
#endif /*USE_RANDOM_DAEMON*/
1388
/* Acquire the nonce buffer lock. */
1389
err = ath_mutex_lock (&nonce_buffer_lock);
1391
log_fatal ("failed to acquire the nonce buffer lock: %s\n",
1395
/* The first time intialize our buffer. */
1396
if (!nonce_buffer_initialized)
1398
time_t atime = time (NULL);
1403
if ((sizeof apid + sizeof atime) > sizeof nonce_buffer)
1406
/* Initialize the first 20 bytes with a reasonable value so that
1407
a failure of gcry_randomize won't affect us too much. Don't
1408
care about the uninitialized remaining bytes. */
1410
memcpy (p, &xpid, sizeof xpid);
1412
memcpy (p, &atime, sizeof atime);
1414
/* Initialize the never changing private part of 64 bits. */
1415
gcry_randomize (nonce_buffer+20, 8, GCRY_WEAK_RANDOM);
1417
nonce_buffer_initialized = 1;
1419
else if ( my_pid != apid )
1421
/* We forked. Need to reseed the buffer - doing this for the
1422
private part should be sufficient. */
1423
gcry_randomize (nonce_buffer+20, 8, GCRY_WEAK_RANDOM);
1424
/* Update the pid so that we won't run into here again and
1429
/* Create the nonce by hashing the entire buffer, returning the hash
1430
and updating the first 20 bytes of the buffer with this hash. */
1431
for (p = buffer; length > 0; length -= n, p += n)
1433
_gcry_sha1_hash_buffer (nonce_buffer,
1434
nonce_buffer, sizeof nonce_buffer);
1435
n = length > 20? 20 : length;
1436
memcpy (p, nonce_buffer, n);
1440
/* Release the nonce buffer lock. */
1441
err = ath_mutex_unlock (&nonce_buffer_lock);
1443
log_fatal ("failed to release the nonce buffer lock: %s\n",