~ubuntu-branches/ubuntu/natty/libgcrypt11/natty-proposed

« back to all changes in this revision

Viewing changes to cipher/random.c

  • Committer: Bazaar Package Importer
  • Author(s): Andreas Metzler
  • Date: 2009-02-21 13:46:58 UTC
  • mto: (1.1.6 upstream) (2.1.3 squeeze)
  • mto: This revision was merged to the branch mainline in revision 18.
  • Revision ID: james.westby@ubuntu.com-20090221134658-855twvcr4ezk2ron
ImportĀ upstreamĀ versionĀ 1.4.4

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/* random.c  -  random number generator
2
 
 * Copyright (C) 1998, 2000, 2001, 2002, 2003,
3
 
 *               2004, 2005, 2006, 2007  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 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.
26
 
 */
27
 
 
28
 
 
29
 
#include <config.h>
30
 
#include <stdio.h>
31
 
#include <stdlib.h>
32
 
#include <assert.h>
33
 
#include <errno.h>
34
 
#include <string.h>
35
 
#include <sys/time.h>
36
 
#include <sys/types.h>
37
 
#include <sys/stat.h>
38
 
#include <unistd.h>
39
 
#include <fcntl.h>
40
 
#include <time.h>
41
 
#ifdef  HAVE_GETHRTIME
42
 
#include <sys/times.h>
43
 
#endif
44
 
#ifdef HAVE_GETTIMEOFDAY
45
 
#include <sys/time.h>
46
 
#endif
47
 
#ifdef HAVE_GETRUSAGE
48
 
#include <sys/resource.h>
49
 
#endif
50
 
#ifdef __MINGW32__
51
 
#include <process.h>
52
 
#endif
53
 
#include "g10lib.h"
54
 
#include "rmd.h"
55
 
#include "random.h"
56
 
#include "rand-internal.h"
57
 
#include "cipher.h" /* Required for the rmd160_hash_buffer() prototype.  */
58
 
#include "ath.h"
59
 
 
60
 
#ifndef RAND_MAX   /* For SunOS. */
61
 
#define RAND_MAX 32767
62
 
#endif
63
 
 
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
67
 
#else
68
 
#define LOCK_SEED_FILE 0
69
 
#endif
70
 
 
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
76
 
#else
77
 
#error weird size for an unsigned long
78
 
#endif
79
 
 
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.  */
84
 
#define POOLBLOCKS 30
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
87
 
   long.  */
88
 
#define POOLSIZE (POOLBLOCKS*DIGESTLEN)
89
 
#if (POOLSIZE % SIZEOF_UNSIGNED_LONG)
90
 
#error Please make sure that poolsize is a multiple of unsigned long
91
 
#endif
92
 
#define POOLWORDS (POOLSIZE / SIZEOF_UNSIGNED_LONG)
93
 
 
94
 
 
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
98
 
   initialized. */
99
 
static unsigned char *rndpool;  
100
 
 
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;  
104
 
 
105
 
/* This is the offset into RNDPOOL where the next random bytes are to
106
 
   be mixed in.  */
107
 
static size_t pool_writepos;
108
 
 
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;
112
 
 
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;
117
 
 
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;
121
 
 
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
126
 
   been done.  */
127
 
static int did_initial_extra_seeding;
128
 
 
129
 
/* This variable is used to estimated the amount of fresh entropy
130
 
   available in RNDPOOL.  */
131
 
static int pool_balance;
132
 
 
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
135
 
   otehr reasons.  */
136
 
static int just_mixed;
137
 
 
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;
142
 
 
143
 
/* If a seed file has been registered and maybe updated on exit this
144
 
   flag set. */
145
 
static int allow_seed_file_update;
146
 
 
147
 
/* Option flag set at initialiation time to force allocation of the
148
 
   pool in secure memory.  */
149
 
static int secure_alloc;
150
 
 
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);
158
 
 
159
 
/* This function is set to the actual fast entropy gathering fucntion
160
 
   during initialization.  If it is NULL, no such function is
161
 
   available. */
162
 
static void (*fast_gather_fnc)(void (*)(const void*, size_t,
163
 
                                        enum random_origins),
164
 
                               enum random_origins);
165
 
 
166
 
 
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;
171
 
 
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;
177
 
 
178
 
/* This is the lock we use to protect all pool operations.  */
179
 
static ath_mutex_t pool_lock = ATH_MUTEX_INITIALIZER;
180
 
 
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
184
 
   test suite.  */
185
 
static int pool_is_locked;
186
 
 
187
 
/* This is the lock we use to protect the buffer used by the nonce
188
 
   generation.  */
189
 
static ath_mutex_t nonce_buffer_lock = ATH_MUTEX_INITIALIZER;
190
 
 
191
 
 
192
 
/* We keep some counters in this structure for the sake of the
193
 
   _gcry_random_dump_stats () function.  */
194
 
static struct
195
 
{
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;
206
 
} rndstats;
207
 
 
208
 
 
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;
214
 
 
215
 
 
216
 
/* --- Stuff pertaining to the random daemon support. --- */
217
 
#ifdef USE_RANDOM_DAEMON
218
 
 
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;       
226
 
 
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;
231
 
 
232
 
#endif /*USE_RANDOM_DAEMON*/
233
 
 
234
 
 
235
 
 
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 );
252
 
 
253
 
 
254
 
 
255
 
/* ---  Functions  --- */
256
 
 
257
 
 
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
262
 
   happens. */
263
 
static void
264
 
initialize_basics(void)
265
 
{
266
 
  static int initialized;
267
 
  int err;
268
 
 
269
 
  if (!initialized)
270
 
    {
271
 
      initialized = 1;
272
 
      err = ath_mutex_init (&pool_lock);
273
 
      if (err)
274
 
        log_fatal ("failed to create the pool lock: %s\n", strerror (err) );
275
 
      
276
 
      err = ath_mutex_init (&nonce_buffer_lock);
277
 
      if (err)
278
 
        log_fatal ("failed to create the nonce buffer lock: %s\n",
279
 
                   strerror (err) );
280
 
 
281
 
#ifdef USE_RANDOM_DAEMON
282
 
      _gcry_daemon_initialize_basics ();
283
 
#endif /*USE_RANDOM_DAEMON*/
284
 
 
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);
290
 
    }
291
 
}
292
 
 
293
 
/* Take the pool lock. */
294
 
static void
295
 
lock_pool (void)
296
 
{
297
 
  int err; 
298
 
 
299
 
  err = ath_mutex_lock (&pool_lock);
300
 
  if (err)
301
 
    log_fatal ("failed to acquire the pool lock: %s\n", strerror (err));
302
 
  pool_is_locked = 1;
303
 
}
304
 
 
305
 
/* Release the pool lock. */
306
 
static void
307
 
unlock_pool (void)
308
 
{
309
 
  int err; 
310
 
 
311
 
  pool_is_locked = 0;
312
 
  err = ath_mutex_unlock (&pool_lock);
313
 
  if (err)
314
 
    log_fatal ("failed to release the pool lock: %s\n", strerror (err));
315
 
}
316
 
 
317
 
 
318
 
/* Full initialization of this module. */
319
 
static void
320
 
initialize(void)
321
 
{
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 ();
325
 
 
326
 
  /* Now we can look the pool and complete the initialization if
327
 
     necessary.  */
328
 
  lock_pool ();
329
 
  if (!rndpool)
330
 
    {
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));
340
 
 
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)
345
 
        {
346
 
          faked_rng = 1;
347
 
          slow_gather_fnc = gather_faked;
348
 
        }
349
 
      
350
 
      /* Setup the fast entropy gathering function.  */
351
 
      fast_gather_fnc = getfnc_fast_random_poll ();
352
 
 
353
 
    }
354
 
  unlock_pool ();
355
 
}
356
 
 
357
 
 
358
 
/* Used to register a progress callback. */
359
 
void
360
 
_gcry_register_random_progress (void (*cb)(void *,const char*,int,int,int),
361
 
                                void *cb_data )
362
 
{
363
 
  progress_cb = cb;
364
 
  progress_cb_data = cb_data;
365
 
}
366
 
 
367
 
 
368
 
/* This progress function is currently used by the random modules to give hint
369
 
   on how much more entropy is required. */
370
 
void
371
 
_gcry_random_progress (const char *what, int printchar, int current, int total)
372
 
{
373
 
  if (progress_cb)
374
 
    progress_cb (progress_cb_data, what, printchar, current, total);
375
 
}
376
 
 
377
 
 
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. */
382
 
void
383
 
_gcry_random_initialize (int full)
384
 
{
385
 
  if (!full)
386
 
    initialize_basics ();
387
 
  else
388
 
    initialize ();
389
 
}
390
 
 
391
 
 
392
 
void
393
 
_gcry_random_dump_stats ()
394
 
{
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 */
398
 
 
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)":"");
406
 
}
407
 
 
408
 
 
409
 
/* This function should be called during initialization and beore
410
 
   intialization of this module to palce the random pools into secure
411
 
   memory.  */
412
 
void
413
 
_gcry_secure_random_alloc()
414
 
{
415
 
  secure_alloc = 1;
416
 
}
417
 
 
418
 
 
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.  */
421
 
void
422
 
_gcry_enable_quick_random_gen (void)
423
 
{
424
 
  quick_test = 1;
425
 
}
426
 
 
427
 
 
428
 
void
429
 
_gcry_set_random_daemon_socket (const char *socketname)
430
 
{
431
 
#ifdef USE_RANDOM_DAEMON
432
 
  if (daemon_socket_name)
433
 
    BUG ();
434
 
 
435
 
  daemon_socket_name = gcry_xstrdup (socketname);
436
 
#else /*!USE_RANDOM_DAEMON*/
437
 
  (void)socketname;
438
 
#endif /*!USE_RANDOM_DAEMON*/
439
 
}
440
 
 
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. */
444
 
int
445
 
_gcry_use_random_daemon (int onoff)
446
 
{
447
 
#ifdef USE_RANDOM_DAEMON
448
 
  int last;
449
 
  
450
 
  /* FIXME: This is not really thread safe. */
451
 
  last = allow_daemon;
452
 
  if (onoff != -1)
453
 
    allow_daemon = onoff;
454
 
 
455
 
  return last;
456
 
#else /*!USE_RANDOM_DAEMON*/
457
 
  (void)onoff;
458
 
  return 0;
459
 
#endif /*!USE_RANDOM_DAEMON*/
460
 
}
461
 
 
462
 
 
463
 
/* This function returns true if no real RNG is available or the
464
 
   quality of the RNG has been degraded for test purposes.  */
465
 
int
466
 
_gcry_random_is_faked()
467
 
{
468
 
  /* We need to initialize due to the runtime determination of
469
 
     available entropy gather modules.  */
470
 
  initialize();
471
 
  return (faked_rng || quick_test);
472
 
}
473
 
 
474
 
 
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.  */
478
 
gcry_error_t
479
 
gcry_random_add_bytes (const void *buf, size_t buflen, int quality)
480
 
{
481
 
  size_t nbytes;
482
 
  const char *bufptr;
483
 
 
484
 
  if (quality == -1)
485
 
    quality = 35;
486
 
  else if (quality > 100)
487
 
    quality = 100;
488
 
  else if (quality < 0)
489
 
    quality = 0;
490
 
      
491
 
  if (!buf)
492
 
    return gpg_error (GPG_ERR_INV_ARG);
493
 
 
494
 
  if (!buflen || quality < 10)
495
 
    return 0; /* Take a shortcut. */
496
 
 
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 ();
502
 
  bufptr = buf;
503
 
  while (buflen)
504
 
    {
505
 
      nbytes = buflen > POOLSIZE? POOLSIZE : buflen;
506
 
      lock_pool ();
507
 
      if (rndpool)
508
 
        add_randomness (bufptr, nbytes, RANDOM_ORIGIN_EXTERNAL);
509
 
      unlock_pool ();
510
 
      bufptr += nbytes;
511
 
      buflen -= nbytes;
512
 
    }
513
 
  return 0;
514
 
}   
515
 
 
516
 
    
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.  */
520
 
void *
521
 
gcry_random_bytes (size_t nbytes, enum gcry_random_level level)
522
 
{
523
 
  void *buffer;
524
 
 
525
 
  initialize();
526
 
 
527
 
  buffer = gcry_xmalloc (nbytes);
528
 
  gcry_randomize (buffer, nbytes, level);
529
 
 
530
 
  return buffer;
531
 
}
532
 
 
533
 
 
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. */
537
 
void *
538
 
gcry_random_bytes_secure( size_t nbytes, enum gcry_random_level level )
539
 
{
540
 
  void *buffer;
541
 
 
542
 
  initialize();
543
 
 
544
 
  buffer = secure_alloc ? gcry_xmalloc_secure (nbytes)
545
 
                        : gcry_xmalloc (nbytes);
546
 
  gcry_randomize (buffer, nbytes, level);
547
 
 
548
 
  return buffer;
549
 
}
550
 
 
551
 
 
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
556
 
   may be very slow.  */
557
 
void
558
 
gcry_randomize (void *buffer, size_t length, enum gcry_random_level level)
559
 
{
560
 
  unsigned char *p;
561
 
 
562
 
  /* Make sure we are initialized. */
563
 
  initialize ();
564
 
 
565
 
  /* Handle our hack used for regression tests of Libgcrypt. */
566
 
  if ( quick_test && level > GCRY_STRONG_RANDOM )
567
 
    level = GCRY_STRONG_RANDOM;
568
 
 
569
 
  /* Make sure the level is okay. */
570
 
  level &= 3;
571
 
 
572
 
#ifdef USE_RANDOM_DAEMON
573
 
  if (allow_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*/
578
 
 
579
 
  /* Acquire the pool lock. */
580
 
  lock_pool ();
581
 
 
582
 
  /* Update the statistics. */
583
 
  if (level >= GCRY_VERY_STRONG_RANDOM)
584
 
    {
585
 
      rndstats.getbytes2 += length;
586
 
      rndstats.ngetbytes2++;
587
 
    }
588
 
  else
589
 
    {
590
 
      rndstats.getbytes1 += length;
591
 
      rndstats.ngetbytes1++;
592
 
    }
593
 
 
594
 
  /* Read the random into the provided buffer. */
595
 
  for (p = buffer; length > 0;)
596
 
    {
597
 
      size_t n;
598
 
 
599
 
      n = length > POOLSIZE? POOLSIZE : length;
600
 
      read_pool (p, n, level);
601
 
      length -= n;
602
 
      p += n;
603
 
    }
604
 
 
605
 
  /* Release the pool lock. */
606
 
  unlock_pool ();
607
 
}
608
 
 
609
 
 
610
 
 
611
 
 
612
 
/*
613
 
   Mix the pool:
614
 
 
615
 
   |........blocks*20byte........|20byte|..44byte..|
616
 
   <..44byte..>           <20byte> 
617
 
        |                    |
618
 
        |                    +------+
619
 
        +---------------------------|----------+
620
 
                                    v          v
621
 
   |........blocks*20byte........|20byte|..44byte..|
622
 
                                 <.....64bytes.....>   
623
 
                                         |
624
 
      +----------------------------------+
625
 
     Hash
626
 
      v
627
 
   |.............................|20byte|..44byte..|
628
 
   <20byte><20byte><..44byte..>
629
 
      |                |
630
 
      |                +---------------------+
631
 
      +-----------------------------+        |
632
 
                                    v        v
633
 
   |.............................|20byte|..44byte..|
634
 
                                 <.....64byte......>
635
 
                                        |
636
 
              +-------------------------+
637
 
             Hash
638
 
              v
639
 
   |.............................|20byte|..44byte..|
640
 
   <20byte><20byte><..44byte..>
641
 
 
642
 
   and so on until we did this for all blocks. 
643
 
 
644
 
   To better protect against implementation errors in this code, we
645
 
   xor a digest of the entire pool into the pool before mixing.
646
 
 
647
 
   Note: this function must only be called with a locked pool.
648
 
 */
649
 
static void
650
 
mix_pool(unsigned char *pool)
651
 
{
652
 
  static unsigned char failsafe_digest[DIGESTLEN];
653
 
  static int failsafe_digest_valid;
654
 
 
655
 
  unsigned char *hashbuf = pool + POOLSIZE;
656
 
  unsigned char *p, *pend;
657
 
  int i, n;
658
 
  RMD160_CONTEXT md;
659
 
 
660
 
#if DIGESTLEN != 20
661
 
#error must have a digest length of 20 for ripe-md-160
662
 
#endif
663
 
 
664
 
  assert (pool_is_locked);
665
 
  _gcry_rmd160_init( &md );
666
 
 
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 );
673
 
 
674
 
  if (failsafe_digest_valid && pool == rndpool)
675
 
    {
676
 
      for (i=0; i < 20; i++)
677
 
        pool[i] ^= failsafe_digest[i];
678
 
    }
679
 
  
680
 
  p = pool;
681
 
  for (n=1; n < POOLBLOCKS; n++)
682
 
    {
683
 
      memcpy (hashbuf, p, DIGESTLEN);
684
 
 
685
 
      p += DIGESTLEN;
686
 
      if (p+DIGESTLEN+BLOCKLEN < pend)
687
 
        memcpy (hashbuf+DIGESTLEN, p+DIGESTLEN, BLOCKLEN-DIGESTLEN);
688
 
      else 
689
 
        {
690
 
          unsigned char *pp = p + DIGESTLEN;
691
 
          
692
 
          for (i=DIGESTLEN; i < BLOCKLEN; i++ )
693
 
            {
694
 
              if ( pp >= pend )
695
 
                pp = pool;
696
 
              hashbuf[i] = *pp++;
697
 
            }
698
 
        }
699
 
      
700
 
      _gcry_rmd160_mixblock ( &md, hashbuf);
701
 
      memcpy(p, hashbuf, 20 );
702
 
    }
703
 
 
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)
709
 
      {
710
 
        _gcry_rmd160_hash_buffer (failsafe_digest, pool, POOLSIZE);
711
 
        failsafe_digest_valid = 1;
712
 
      }
713
 
 
714
 
    _gcry_burn_stack (384); /* for the rmd160_mixblock(), rmd160_hash_buffer */
715
 
}
716
 
 
717
 
 
718
 
void
719
 
_gcry_set_random_seed_file( const char *name )
720
 
{
721
 
  if (seed_file_name)
722
 
    BUG ();
723
 
  seed_file_name = gcry_xstrdup (name);
724
 
}
725
 
 
726
 
 
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. */
731
 
static int
732
 
lock_seed_file (int fd, const char *fname, int for_write)
733
 
{
734
 
#if LOCK_SEED_FILE
735
 
  struct flock lck;
736
 
  struct timeval tv;
737
 
  int backoff=0;
738
 
 
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;
743
 
 
744
 
  while (fcntl (fd, F_SETLK, &lck) == -1)
745
 
    {
746
 
      if (errno != EAGAIN && errno != EACCES)
747
 
        {
748
 
          log_info (_("can't lock `%s': %s\n"), fname, strerror (errno));
749
 
          return -1;
750
 
        }
751
 
 
752
 
      if (backoff > 2) /* Show the first message after ~2.25 seconds. */
753
 
        log_info( _("waiting for lock on `%s'...\n"), fname);
754
 
      
755
 
      tv.tv_sec = backoff;
756
 
      tv.tv_usec = 250000;
757
 
      select (0, NULL, NULL, NULL, &tv);
758
 
      if (backoff < 10)
759
 
        backoff++ ;
760
 
    }
761
 
#endif /*LOCK_SEED_FILE*/
762
 
  return 0;
763
 
}
764
 
 
765
 
 
766
 
/* Read in a seed from the random_seed file and return true if this
767
 
   was successful.
768
 
 
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.  */
781
 
static int
782
 
read_seed_file (void)
783
 
{
784
 
  int fd;
785
 
  struct stat sb;
786
 
  unsigned char buffer[POOLSIZE];
787
 
  int n;
788
 
 
789
 
  assert (pool_is_locked);
790
 
 
791
 
  if (!seed_file_name)
792
 
    return 0;
793
 
  
794
 
#ifdef HAVE_DOSISH_SYSTEM
795
 
  fd = open( seed_file_name, O_RDONLY | O_BINARY );
796
 
#else
797
 
  fd = open( seed_file_name, O_RDONLY );
798
 
#endif
799
 
  if( fd == -1 && errno == ENOENT)
800
 
    {
801
 
      allow_seed_file_update = 1;
802
 
      return 0;
803
 
    }
804
 
 
805
 
  if (fd == -1 )
806
 
    {
807
 
      log_info(_("can't open `%s': %s\n"), seed_file_name, strerror(errno) );
808
 
      return 0;
809
 
    }
810
 
  if (lock_seed_file (fd, seed_file_name, 0))
811
 
    {
812
 
      close (fd);
813
 
      return 0;
814
 
    }
815
 
  if (fstat( fd, &sb ) )
816
 
    {
817
 
      log_info(_("can't stat `%s': %s\n"), seed_file_name, strerror(errno) );
818
 
      close(fd);
819
 
      return 0;
820
 
    }
821
 
  if (!S_ISREG(sb.st_mode) )
822
 
    {
823
 
      log_info(_("`%s' is not a regular file - ignored\n"), seed_file_name );
824
 
      close(fd);
825
 
      return 0;
826
 
    }
827
 
  if (!sb.st_size )
828
 
    {
829
 
      log_info(_("note: random_seed file is empty\n") );
830
 
      close(fd);
831
 
      allow_seed_file_update = 1;
832
 
      return 0;
833
 
    }
834
 
  if (sb.st_size != POOLSIZE ) 
835
 
    {
836
 
      log_info(_("warning: invalid size of random_seed file - not used\n") );
837
 
      close(fd);
838
 
      return 0;
839
 
    }
840
 
 
841
 
  do
842
 
    {
843
 
      n = read( fd, buffer, POOLSIZE );
844
 
    } 
845
 
  while (n == -1 && errno == EINTR );
846
 
 
847
 
  if (n != POOLSIZE)
848
 
    {
849
 
      log_fatal(_("can't read `%s': %s\n"), seed_file_name,strerror(errno) );
850
 
      close(fd);/*NOTREACHED*/
851
 
      return 0;
852
 
    }
853
 
  
854
 
  close(fd);
855
 
 
856
 
  add_randomness( buffer, POOLSIZE, RANDOM_ORIGIN_INIT );
857
 
  /* add some minor entropy to the pool now (this will also force a mixing) */
858
 
  {     
859
 
    pid_t x = getpid();
860
 
    add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT );
861
 
  }
862
 
  {
863
 
    time_t x = time(NULL);
864
 
    add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT );
865
 
  }
866
 
  {     
867
 
    clock_t x = clock();
868
 
    add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT );
869
 
  }
870
 
 
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 );
877
 
 
878
 
  allow_seed_file_update = 1;
879
 
  return 1;
880
 
}
881
 
 
882
 
 
883
 
void
884
 
_gcry_update_random_seed_file()
885
 
{
886
 
  unsigned long *sp, *dp;
887
 
  int fd, i;
888
 
 
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
892
 
     been initialized.  */
893
 
  initialize_basics ();
894
 
  lock_pool ();
895
 
 
896
 
  if ( !seed_file_name || !rndpool || !pool_filled )
897
 
    {
898
 
      unlock_pool ();
899
 
      return;
900
 
    }
901
 
  if ( !allow_seed_file_update )
902
 
    {
903
 
      unlock_pool ();
904
 
      log_info(_("note: random_seed file not updated\n"));
905
 
      return;
906
 
    }
907
 
 
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.  */
910
 
 
911
 
 
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++ ) 
915
 
    {
916
 
      *dp = *sp + ADD_VALUE;
917
 
    }
918
 
  mix_pool(rndpool); rndstats.mixrnd++;
919
 
  mix_pool(keypool); rndstats.mixkey++;
920
 
 
921
 
#if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
922
 
  fd = open (seed_file_name, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY,
923
 
             S_IRUSR|S_IWUSR );
924
 
#else
925
 
# if LOCK_SEED_FILE
926
 
    fd = open (seed_file_name, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR );
927
 
# else
928
 
    fd = open (seed_file_name, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR );
929
 
# endif
930
 
#endif
931
 
 
932
 
  if (fd == -1 )
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))
935
 
    {
936
 
      close (fd);
937
 
    }
938
 
#if LOCK_SEED_FILE
939
 
  else if (ftruncate (fd, 0))
940
 
    {
941
 
      log_info(_("can't write `%s': %s\n"), seed_file_name, strerror(errno));
942
 
      close (fd);
943
 
    }
944
 
#endif /*LOCK_SEED_FILE*/
945
 
  else 
946
 
    {
947
 
      do
948
 
        {
949
 
          i = write (fd, keypool, POOLSIZE );
950
 
        } 
951
 
      while (i == -1 && errno == EINTR);
952
 
      if (i != POOLSIZE) 
953
 
        log_info (_("can't write `%s': %s\n"),seed_file_name, strerror(errno));
954
 
      if (close(fd))
955
 
        log_info (_("can't close `%s': %s\n"),seed_file_name, strerror(errno));
956
 
    }
957
 
  
958
 
  unlock_pool ();
959
 
}
960
 
 
961
 
 
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
966
 
   locked.  */
967
 
static void
968
 
read_pool (byte *buffer, size_t length, int level)
969
 
{
970
 
  int i;
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;
979
 
 
980
 
  assert (pool_is_locked);
981
 
 
982
 
 retry:
983
 
  /* Get our own pid, so that we can detect a fork. */
984
 
  my_pid2 = getpid ();
985
 
  if (my_pid == (pid_t)(-1))                                
986
 
    my_pid = my_pid2;
987
 
  if ( my_pid != my_pid2 )
988
 
    {
989
 
      /* We detected a plain fork; i.e. we are now the child.  Update
990
 
         the static pid and add some randomness. */
991
 
      pid_t x;
992
 
 
993
 
      my_pid = my_pid2;
994
 
      x = my_pid;
995
 
      add_randomness (&x, sizeof(x), RANDOM_ORIGIN_INIT);
996
 
      just_mixed = 0; /* Make sure it will get mixed. */
997
 
    }
998
 
 
999
 
  assert (pool_is_locked);
1000
 
 
1001
 
  /* Our code does not allow to extract more than POOLSIZE.  Better
1002
 
     check it here. */
1003
 
  if (length > POOLSIZE)
1004
 
    {
1005
 
      log_bug("too many random bits requested\n");
1006
 
    }
1007
 
 
1008
 
  if (!pool_filled)
1009
 
    {
1010
 
      if (read_seed_file() )
1011
 
        pool_filled = 1;
1012
 
    }
1013
 
 
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)
1017
 
    {
1018
 
      size_t needed;
1019
 
 
1020
 
      pool_balance = 0;
1021
 
      needed = length - pool_balance;
1022
 
      if (needed < POOLSIZE/2)
1023
 
        needed = POOLSIZE/2;
1024
 
      else if( needed > POOLSIZE )
1025
 
        BUG ();
1026
 
      read_random_source (RANDOM_ORIGIN_EXTRAPOLL, needed,
1027
 
                          GCRY_VERY_STRONG_RANDOM);
1028
 
      pool_balance += needed;
1029
 
      did_initial_extra_seeding = 1;
1030
 
    }
1031
 
 
1032
 
  /* For level 2 make sure that there is enough random in the pool. */
1033
 
  if (level == GCRY_VERY_STRONG_RANDOM && pool_balance < length)
1034
 
    {
1035
 
      size_t needed;
1036
 
      
1037
 
      if (pool_balance < 0)
1038
 
        pool_balance = 0;
1039
 
      needed = length - pool_balance;
1040
 
      if (needed > POOLSIZE)
1041
 
        BUG ();
1042
 
      read_random_source (RANDOM_ORIGIN_EXTRAPOLL, needed,
1043
 
                          GCRY_VERY_STRONG_RANDOM);
1044
 
      pool_balance += needed;
1045
 
    }
1046
 
 
1047
 
  /* Make sure the pool is filled. */
1048
 
  while (!pool_filled)
1049
 
    random_poll();
1050
 
 
1051
 
  /* Always do a fast random poll (we have to use the unlocked version). */
1052
 
  do_fast_random_poll();
1053
 
  
1054
 
  /* Mix the pid in so that we for sure won't deliver the same random
1055
 
     after a fork. */
1056
 
  {
1057
 
    pid_t apid = my_pid;
1058
 
    add_randomness (&apid, sizeof (apid), RANDOM_ORIGIN_INIT);
1059
 
  }
1060
 
 
1061
 
  /* Mix the pool (if add_randomness() didn't it). */
1062
 
  if (!just_mixed)
1063
 
    {
1064
 
      mix_pool(rndpool);
1065
 
      rndstats.mixrnd++;
1066
 
    }
1067
 
 
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;
1072
 
 
1073
 
  /* Mix both pools. */
1074
 
  mix_pool(rndpool); rndstats.mixrnd++;
1075
 
  mix_pool(keypool); rndstats.mixkey++;
1076
 
 
1077
 
  /* Read the requested data.  We use a read pointer to read from a
1078
 
     different position each time.  */
1079
 
  while (length--)
1080
 
    {
1081
 
      *buffer++ = keypool[pool_readpos++];
1082
 
      if (pool_readpos >= POOLSIZE)
1083
 
        pool_readpos = 0;
1084
 
      pool_balance--;
1085
 
    }
1086
 
 
1087
 
  if (pool_balance < 0)
1088
 
    pool_balance = 0;
1089
 
 
1090
 
  /* Clear the keypool. */
1091
 
  memset (keypool, 0, POOLSIZE);
1092
 
 
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 )
1100
 
    {
1101
 
      pid_t x = getpid();
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. */
1105
 
      goto retry;
1106
 
    }
1107
 
}
1108
 
 
1109
 
 
1110
 
 
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. */
1114
 
static void
1115
 
add_randomness (const void *buffer, size_t length, enum random_origins origin)
1116
 
{
1117
 
  const unsigned char *p = buffer;
1118
 
  size_t count = 0;
1119
 
 
1120
 
  assert (pool_is_locked);
1121
 
 
1122
 
  rndstats.addbytes += length;
1123
 
  rndstats.naddbytes++;
1124
 
  while (length-- )
1125
 
    {
1126
 
      rndpool[pool_writepos++] ^= *p++;
1127
 
      count++;
1128
 
      if (pool_writepos >= POOLSIZE )
1129
 
        {
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)
1136
 
            {
1137
 
              pool_filled_counter += count;
1138
 
              count = 0;
1139
 
              if (pool_filled_counter >= POOLSIZE)
1140
 
                pool_filled = 1;
1141
 
            }
1142
 
          pool_writepos = 0;
1143
 
          mix_pool(rndpool); rndstats.mixrnd++;
1144
 
          just_mixed = !length;
1145
 
        }
1146
 
    }
1147
 
}
1148
 
 
1149
 
 
1150
 
 
1151
 
static void
1152
 
random_poll()
1153
 
{
1154
 
  rndstats.slowpolls++;
1155
 
  read_random_source (RANDOM_ORIGIN_SLOWPOLL, POOLSIZE/5, GCRY_STRONG_RANDOM);
1156
 
}
1157
 
 
1158
 
 
1159
 
/* Runtime determination of the slow entropy gathering module.  */
1160
 
static int (*
1161
 
getfnc_gather_random (void))(void (*)(const void*, size_t, 
1162
 
                                      enum random_origins), 
1163
 
                             enum random_origins, size_t, int)
1164
 
{
1165
 
  int (*fnc)(void (*)(const void*, size_t, enum random_origins), 
1166
 
             enum random_origins, size_t, int);
1167
 
  
1168
 
#if USE_RNDLINUX
1169
 
  if ( !access (NAME_OF_DEV_RANDOM, R_OK)
1170
 
       && !access (NAME_OF_DEV_URANDOM, R_OK))
1171
 
    {
1172
 
      fnc = _gcry_rndlinux_gather_random;
1173
 
      return fnc;
1174
 
    }
1175
 
#endif
1176
 
 
1177
 
#if USE_RNDEGD
1178
 
  if ( _gcry_rndegd_connect_socket (1) != -1 )
1179
 
    {
1180
 
      fnc = _gcry_rndegd_gather_random;
1181
 
      return fnc;
1182
 
    }
1183
 
#endif
1184
 
 
1185
 
#if USE_RNDUNIX
1186
 
  fnc = _gcry_rndunix_gather_random;
1187
 
  return fnc;
1188
 
#endif
1189
 
 
1190
 
#if USE_RNDW32
1191
 
  fnc = _gcry_rndw32_gather_random;
1192
 
  return fnc;
1193
 
#endif
1194
 
 
1195
 
  log_fatal (_("no entropy gathering module detected\n"));
1196
 
 
1197
 
  return NULL; /*NOTREACHED*/
1198
 
}
1199
 
 
1200
 
/* Runtime determination of the fast entropy gathering function.
1201
 
   (Currently a compile time method is used.)  */
1202
 
static void (*
1203
 
getfnc_fast_random_poll (void))( void (*)(const void*, size_t,
1204
 
                                          enum random_origins),
1205
 
                                 enum random_origins)
1206
 
{
1207
 
#if USE_RNDW32
1208
 
  return _gcry_rndw32_gather_random_fast;
1209
 
#endif
1210
 
  return NULL;
1211
 
}
1212
 
 
1213
 
 
1214
 
 
1215
 
static void
1216
 
do_fast_random_poll (void)
1217
 
{
1218
 
  assert (pool_is_locked);
1219
 
 
1220
 
  rndstats.fastpolls++;
1221
 
 
1222
 
  if (fast_gather_fnc)
1223
 
    fast_gather_fnc (add_randomness, RANDOM_ORIGIN_FASTPOLL);
1224
 
 
1225
 
  /* Continue with the generic functions. */
1226
 
#if HAVE_GETHRTIME
1227
 
  {     
1228
 
    hrtime_t tv;
1229
 
    tv = gethrtime();
1230
 
    add_randomness( &tv, sizeof(tv), RANDOM_ORIGIN_FASTPOLL );
1231
 
  }
1232
 
#elif HAVE_GETTIMEOFDAY
1233
 
  {     
1234
 
    struct timeval tv;
1235
 
    if( gettimeofday( &tv, NULL ) )
1236
 
      BUG();
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 );
1239
 
  }
1240
 
#elif HAVE_CLOCK_GETTIME
1241
 
  {     struct timespec tv;
1242
 
  if( clock_gettime( CLOCK_REALTIME, &tv ) == -1 )
1243
 
    BUG();
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 );
1246
 
  }
1247
 
#else /* use times */
1248
 
# ifndef HAVE_DOSISH_SYSTEM
1249
 
  {     struct tms buf;
1250
 
  times( &buf );
1251
 
  add_randomness( &buf, sizeof buf, RANDOM_ORIGIN_FASTPOLL );
1252
 
  }
1253
 
# endif
1254
 
#endif
1255
 
 
1256
 
#ifdef HAVE_GETRUSAGE
1257
 
# ifdef RUSAGE_SELF
1258
 
  {     
1259
 
    struct rusage buf;
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 );
1267
 
  }
1268
 
# else /*!RUSAGE_SELF*/
1269
 
#  ifdef __GCC__
1270
 
#   warning There is no RUSAGE_SELF on this system
1271
 
#  endif
1272
 
# endif /*!RUSAGE_SELF*/
1273
 
#endif /*HAVE_GETRUSAGE*/
1274
 
 
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.  */
1277
 
  {
1278
 
    time_t x = time(NULL);
1279
 
    add_randomness( &x, sizeof(x), RANDOM_ORIGIN_FASTPOLL );
1280
 
  }
1281
 
  {     
1282
 
    clock_t x = clock();
1283
 
    add_randomness( &x, sizeof(x), RANDOM_ORIGIN_FASTPOLL );
1284
 
  }
1285
 
 
1286
 
  /* If the system features a fast hardware RNG, read some bytes from
1287
 
     there.  */
1288
 
  _gcry_rndhw_poll_fast (add_randomness, RANDOM_ORIGIN_FASTPOLL);
1289
 
}
1290
 
 
1291
 
 
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. */
1299
 
void
1300
 
_gcry_fast_random_poll (void)
1301
 
{
1302
 
  initialize_basics ();
1303
 
 
1304
 
  lock_pool ();
1305
 
  if (rndpool)
1306
 
    {
1307
 
      /* Yes, we are fully initialized. */
1308
 
      do_fast_random_poll ();
1309
 
    }
1310
 
  unlock_pool ();
1311
 
}
1312
 
 
1313
 
 
1314
 
 
1315
 
static void
1316
 
read_random_source (enum random_origins orgin, size_t length, int level )
1317
 
{
1318
 
  if ( !slow_gather_fnc )
1319
 
    log_fatal ("Slow entropy gathering module not yet initialized\n");
1320
 
 
1321
 
  if ( slow_gather_fnc (add_randomness, orgin, length, level) < 0)
1322
 
    log_fatal ("No way to gather entropy for the RNG\n");
1323
 
}
1324
 
 
1325
 
 
1326
 
static int
1327
 
gather_faked (void (*add)(const void*, size_t, enum random_origins),
1328
 
              enum random_origins origin, size_t length, int level )
1329
 
{
1330
 
  static int initialized=0;
1331
 
  size_t n;
1332
 
  char *buffer, *p;
1333
 
  
1334
 
  (void)add;
1335
 
  (void)level;
1336
 
  
1337
 
  if ( !initialized )
1338
 
    {
1339
 
      log_info(_("WARNING: using insecure random number generator!!\n"));
1340
 
      initialized=1;
1341
 
#ifdef HAVE_RAND
1342
 
      srand( time(NULL)*getpid());
1343
 
#else
1344
 
      srandom( time(NULL)*getpid());
1345
 
#endif
1346
 
    }
1347
 
 
1348
 
  p = buffer = gcry_xmalloc( length );
1349
 
  n = length;
1350
 
#ifdef HAVE_RAND
1351
 
  while ( n-- )
1352
 
    *p++ = ((unsigned)(1 + (int) (256.0*rand()/(RAND_MAX+1.0)))-1);
1353
 
#else
1354
 
  while ( n-- )
1355
 
    *p++ = ((unsigned)(1 + (int) (256.0*random()/(RAND_MAX+1.0)))-1);
1356
 
#endif
1357
 
  add_randomness ( buffer, length, origin );
1358
 
  gcry_free (buffer);
1359
 
  return 0; /* okay */
1360
 
}
1361
 
 
1362
 
 
1363
 
/* Create an unpredicable nonce of LENGTH bytes in BUFFER. */
1364
 
void
1365
 
gcry_create_nonce (void *buffer, size_t length)
1366
 
{
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
1372
 
                                   attributed. */
1373
 
  volatile pid_t apid;
1374
 
  unsigned char *p;
1375
 
  size_t n;
1376
 
  int err;
1377
 
 
1378
 
  /* Make sure we are initialized. */
1379
 
  initialize ();
1380
 
 
1381
 
#ifdef USE_RANDOM_DAEMON
1382
 
  if (allow_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*/
1387
 
 
1388
 
  /* Acquire the nonce buffer lock. */
1389
 
  err = ath_mutex_lock (&nonce_buffer_lock);
1390
 
  if (err)
1391
 
    log_fatal ("failed to acquire the nonce buffer lock: %s\n",
1392
 
               strerror (err));
1393
 
 
1394
 
  apid = getpid ();
1395
 
  /* The first time intialize our buffer. */
1396
 
  if (!nonce_buffer_initialized)
1397
 
    {
1398
 
      time_t atime = time (NULL);
1399
 
      pid_t xpid = apid;
1400
 
 
1401
 
      my_pid = apid;
1402
 
 
1403
 
      if ((sizeof apid + sizeof atime) > sizeof nonce_buffer)
1404
 
        BUG ();
1405
 
 
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. */
1409
 
      p = nonce_buffer;
1410
 
      memcpy (p, &xpid, sizeof xpid);
1411
 
      p += sizeof xpid;
1412
 
      memcpy (p, &atime, sizeof atime); 
1413
 
 
1414
 
      /* Initialize the never changing private part of 64 bits. */
1415
 
      gcry_randomize (nonce_buffer+20, 8, GCRY_WEAK_RANDOM);
1416
 
 
1417
 
      nonce_buffer_initialized = 1;
1418
 
    }
1419
 
  else if ( my_pid != apid )
1420
 
    {
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
1425
 
         again. */
1426
 
      my_pid = apid;
1427
 
    }
1428
 
 
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)
1432
 
    {
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);
1437
 
    }
1438
 
 
1439
 
 
1440
 
  /* Release the nonce buffer lock. */
1441
 
  err = ath_mutex_unlock (&nonce_buffer_lock);
1442
 
  if (err)
1443
 
    log_fatal ("failed to release the nonce buffer lock: %s\n",
1444
 
               strerror (err));
1445
 
 
1446
 
}