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

« back to all changes in this revision

Viewing changes to random/random-csprng.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-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.
 
4
 *
 
5
 * This file is part of Libgcrypt.
 
6
 *
 
7
 * Libgcrypt is free software; you can redistribute it and/or modify
 
8
 * it under the terms of the GNU Lesser General Public License as
 
9
 * published by the Free Software Foundation; either version 2.1 of
 
10
 * the License, or (at your option) any later version.
 
11
 *
 
12
 * Libgcrypt is distributed in the hope that it will be useful,
 
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
15
 * GNU Lesser General Public License for more details.
 
16
 *
 
17
 * You should have received a copy of the GNU Lesser General Public
 
18
 * License along with this program; if not, see <http://www.gnu.org/licenses/>.
 
19
 */
 
20
 
 
21
/*
 
22
   This random number generator is modelled after the one described in
 
23
   Peter Gutmann's 1998 Usenix Security Symposium paper: "Software
 
24
   Generation of Practically Strong Random Numbers".  See also chapter
 
25
   6 in his book "Cryptographic Security Architecture", New York,
 
26
   2004, ISBN 0-387-95387-6.
 
27
 
 
28
   Note that the acronym CSPRNG stands for "Continuously Seeded
 
29
   PseudoRandom Number Generator" as used in Peter's implementation of
 
30
   the paper and not only for "Cryptographically Secure PseudoRandom
 
31
   Number Generator".
 
32
 */
 
33
 
 
34
 
 
35
#include <config.h>
 
36
#include <stdio.h>
 
37
#include <stdlib.h>
 
38
#include <errno.h>
 
39
#include <string.h>
 
40
#include <sys/time.h>
 
41
#include <sys/types.h>
 
42
#include <sys/stat.h>
 
43
#include <unistd.h>
 
44
#include <fcntl.h>
 
45
#include <time.h>
 
46
#ifdef  HAVE_GETHRTIME
 
47
#include <sys/times.h>
 
48
#endif
 
49
#ifdef HAVE_GETTIMEOFDAY
 
50
#include <sys/time.h>
 
51
#endif
 
52
#ifdef HAVE_GETRUSAGE
 
53
#include <sys/resource.h>
 
54
#endif
 
55
#ifdef __MINGW32__
 
56
#include <process.h>
 
57
#endif
 
58
#include "g10lib.h"
 
59
#include "../cipher/rmd.h"
 
60
#include "random.h"
 
61
#include "rand-internal.h"
 
62
#include "cipher.h" /* Required for the rmd160_hash_buffer() prototype.  */
 
63
#include "ath.h"
 
64
 
 
65
#ifndef RAND_MAX   /* For SunOS. */
 
66
#define RAND_MAX 32767
 
67
#endif
 
68
 
 
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
 
72
#else
 
73
#define LOCK_SEED_FILE 0
 
74
#endif
 
75
 
 
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
 
81
#else
 
82
#error weird size for an unsigned long
 
83
#endif
 
84
 
 
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.  */
 
89
#define POOLBLOCKS 30
 
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
 
92
   long.  */
 
93
#define POOLSIZE (POOLBLOCKS*DIGESTLEN)
 
94
#if (POOLSIZE % SIZEOF_UNSIGNED_LONG)
 
95
#error Please make sure that poolsize is a multiple of unsigned long
 
96
#endif
 
97
#define POOLWORDS (POOLSIZE / SIZEOF_UNSIGNED_LONG)
 
98
 
 
99
 
 
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
 
103
   initialized. */
 
104
static unsigned char *rndpool;  
 
105
 
 
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;  
 
109
 
 
110
/* This is the offset into RNDPOOL where the next random bytes are to
 
111
   be mixed in.  */
 
112
static size_t pool_writepos;
 
113
 
 
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;
 
117
 
 
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;
 
122
 
 
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;
 
126
 
 
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
 
131
   been done.  */
 
132
static int did_initial_extra_seeding;
 
133
 
 
134
/* This variable is used to estimated the amount of fresh entropy
 
135
   available in RNDPOOL.  */
 
136
static int pool_balance;
 
137
 
 
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
 
140
   otehr reasons.  */
 
141
static int just_mixed;
 
142
 
 
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;
 
147
 
 
148
/* If a seed file has been registered and maybe updated on exit this
 
149
   flag set. */
 
150
static int allow_seed_file_update;
 
151
 
 
152
/* Option flag set at initialiation time to force allocation of the
 
153
   pool in secure memory.  */
 
154
static int secure_alloc;
 
155
 
 
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);
 
163
 
 
164
/* This function is set to the actual fast entropy gathering fucntion
 
165
   during initialization.  If it is NULL, no such function is
 
166
   available. */
 
167
static void (*fast_gather_fnc)(void (*)(const void*, size_t,
 
168
                                        enum random_origins),
 
169
                               enum random_origins);
 
170
 
 
171
 
 
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;
 
176
 
 
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;
 
182
 
 
183
/* This is the lock we use to protect all pool operations.  */
 
184
static ath_mutex_t pool_lock = ATH_MUTEX_INITIALIZER;
 
185
 
 
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
 
189
   test suite.  */
 
190
static int pool_is_locked;
 
191
 
 
192
/* This is the lock we use to protect the buffer used by the nonce
 
193
   generation.  */
 
194
static ath_mutex_t nonce_buffer_lock = ATH_MUTEX_INITIALIZER;
 
195
 
 
196
 
 
197
/* We keep some counters in this structure for the sake of the
 
198
   _gcry_random_dump_stats () function.  */
 
199
static struct
 
200
{
 
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;
 
211
} rndstats;
 
212
 
 
213
 
 
214
 
 
215
/* --- Stuff pertaining to the random daemon support. --- */
 
216
#ifdef USE_RANDOM_DAEMON
 
217
 
 
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;       
 
225
 
 
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;
 
230
 
 
231
#endif /*USE_RANDOM_DAEMON*/
 
232
 
 
233
 
 
234
 
 
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 );
 
251
 
 
252
 
 
253
 
 
254
/* ---  Functions  --- */
 
255
 
 
256
 
 
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
 
261
   happens. */
 
262
static void
 
263
initialize_basics(void)
 
264
{
 
265
  static int initialized;
 
266
  int err;
 
267
 
 
268
  if (!initialized)
 
269
    {
 
270
      initialized = 1;
 
271
      err = ath_mutex_init (&pool_lock);
 
272
      if (err)
 
273
        log_fatal ("failed to create the pool lock: %s\n", strerror (err) );
 
274
      
 
275
      err = ath_mutex_init (&nonce_buffer_lock);
 
276
      if (err)
 
277
        log_fatal ("failed to create the nonce buffer lock: %s\n",
 
278
                   strerror (err) );
 
279
 
 
280
#ifdef USE_RANDOM_DAEMON
 
281
      _gcry_daemon_initialize_basics ();
 
282
#endif /*USE_RANDOM_DAEMON*/
 
283
 
 
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);
 
289
    }
 
290
}
 
291
 
 
292
/* Take the pool lock. */
 
293
static void
 
294
lock_pool (void)
 
295
{
 
296
  int err; 
 
297
 
 
298
  err = ath_mutex_lock (&pool_lock);
 
299
  if (err)
 
300
    log_fatal ("failed to acquire the pool lock: %s\n", strerror (err));
 
301
  pool_is_locked = 1;
 
302
}
 
303
 
 
304
/* Release the pool lock. */
 
305
static void
 
306
unlock_pool (void)
 
307
{
 
308
  int err; 
 
309
 
 
310
  pool_is_locked = 0;
 
311
  err = ath_mutex_unlock (&pool_lock);
 
312
  if (err)
 
313
    log_fatal ("failed to release the pool lock: %s\n", strerror (err));
 
314
}
 
315
 
 
316
 
 
317
/* Full initialization of this module. */
 
318
static void
 
319
initialize(void)
 
320
{
 
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 ();
 
324
 
 
325
  /* Now we can look the pool and complete the initialization if
 
326
     necessary.  */
 
327
  lock_pool ();
 
328
  if (!rndpool)
 
329
    {
 
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));
 
339
 
 
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)
 
344
        {
 
345
          faked_rng = 1;
 
346
          slow_gather_fnc = gather_faked;
 
347
        }
 
348
      
 
349
      /* Setup the fast entropy gathering function.  */
 
350
      fast_gather_fnc = getfnc_fast_random_poll ();
 
351
 
 
352
    }
 
353
  unlock_pool ();
 
354
}
 
355
 
 
356
 
 
357
 
 
358
 
 
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. */
 
363
void
 
364
_gcry_rngcsprng_initialize (int full)
 
365
{
 
366
  if (!full)
 
367
    initialize_basics ();
 
368
  else
 
369
    initialize ();
 
370
}
 
371
 
 
372
 
 
373
void
 
374
_gcry_rngcsprng_dump_stats (void)
 
375
{
 
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
 
378
     into problems.  */
 
379
 
 
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)":"");
 
387
}
 
388
 
 
389
 
 
390
/* This function should be called during initialization and before
 
391
   intialization of this module to place the random pools into secure
 
392
   memory.  */
 
393
void
 
394
_gcry_rngcsprng_secure_alloc (void)
 
395
{
 
396
  secure_alloc = 1;
 
397
}
 
398
 
 
399
 
 
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.  */
 
402
void
 
403
_gcry_rngcsprng_enable_quick_gen (void)
 
404
{
 
405
  quick_test = 1;
 
406
}
 
407
 
 
408
 
 
409
void
 
410
_gcry_rngcsprng_set_daemon_socket (const char *socketname)
 
411
{
 
412
#ifdef USE_RANDOM_DAEMON
 
413
  if (daemon_socket_name)
 
414
    BUG ();
 
415
 
 
416
  daemon_socket_name = gcry_xstrdup (socketname);
 
417
#else /*!USE_RANDOM_DAEMON*/
 
418
  (void)socketname;
 
419
#endif /*!USE_RANDOM_DAEMON*/
 
420
}
 
421
 
 
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. */
 
425
int
 
426
_gcry_rngcsprng_use_daemon (int onoff)
 
427
{
 
428
#ifdef USE_RANDOM_DAEMON
 
429
  int last;
 
430
  
 
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.  */
 
436
  last = allow_daemon;
 
437
  if (onoff != -1)
 
438
    allow_daemon = onoff;
 
439
 
 
440
  return last;
 
441
#else /*!USE_RANDOM_DAEMON*/
 
442
  (void)onoff;
 
443
  return 0;
 
444
#endif /*!USE_RANDOM_DAEMON*/
 
445
}
 
446
 
 
447
 
 
448
/* This function returns true if no real RNG is available or the
 
449
   quality of the RNG has been degraded for test purposes.  */
 
450
int
 
451
_gcry_rngcsprng_is_faked (void)
 
452
{
 
453
  /* We need to initialize due to the runtime determination of
 
454
     available entropy gather modules.  */
 
455
  initialize();
 
456
  return (faked_rng || quick_test);
 
457
}
 
458
 
 
459
 
 
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.  */
 
463
gcry_error_t
 
464
_gcry_rngcsprng_add_bytes (const void *buf, size_t buflen, int quality)
 
465
{
 
466
  size_t nbytes;
 
467
  const char *bufptr;
 
468
 
 
469
  if (quality == -1)
 
470
    quality = 35;
 
471
  else if (quality > 100)
 
472
    quality = 100;
 
473
  else if (quality < 0)
 
474
    quality = 0;
 
475
      
 
476
  if (!buf)
 
477
    return gpg_error (GPG_ERR_INV_ARG);
 
478
 
 
479
  if (!buflen || quality < 10)
 
480
    return 0; /* Take a shortcut. */
 
481
 
 
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 ();
 
487
  bufptr = buf;
 
488
  while (buflen)
 
489
    {
 
490
      nbytes = buflen > POOLSIZE? POOLSIZE : buflen;
 
491
      lock_pool ();
 
492
      if (rndpool)
 
493
        add_randomness (bufptr, nbytes, RANDOM_ORIGIN_EXTERNAL);
 
494
      unlock_pool ();
 
495
      bufptr += nbytes;
 
496
      buflen -= nbytes;
 
497
    }
 
498
  return 0;
 
499
}   
 
500
 
 
501
    
 
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
 
506
   may be very slow.  */
 
507
void
 
508
_gcry_rngcsprng_randomize (void *buffer, size_t length,
 
509
                           enum gcry_random_level level)
 
510
{
 
511
  unsigned char *p;
 
512
 
 
513
  /* Make sure we are initialized. */
 
514
  initialize ();
 
515
 
 
516
  /* Handle our hack used for regression tests of Libgcrypt. */
 
517
  if ( quick_test && level > GCRY_STRONG_RANDOM )
 
518
    level = GCRY_STRONG_RANDOM;
 
519
 
 
520
  /* Make sure the level is okay. */
 
521
  level &= 3;
 
522
 
 
523
#ifdef USE_RANDOM_DAEMON
 
524
  if (allow_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*/
 
529
 
 
530
  /* Acquire the pool lock. */
 
531
  lock_pool ();
 
532
 
 
533
  /* Update the statistics. */
 
534
  if (level >= GCRY_VERY_STRONG_RANDOM)
 
535
    {
 
536
      rndstats.getbytes2 += length;
 
537
      rndstats.ngetbytes2++;
 
538
    }
 
539
  else
 
540
    {
 
541
      rndstats.getbytes1 += length;
 
542
      rndstats.ngetbytes1++;
 
543
    }
 
544
 
 
545
  /* Read the random into the provided buffer. */
 
546
  for (p = buffer; length > 0;)
 
547
    {
 
548
      size_t n;
 
549
 
 
550
      n = length > POOLSIZE? POOLSIZE : length;
 
551
      read_pool (p, n, level);
 
552
      length -= n;
 
553
      p += n;
 
554
    }
 
555
 
 
556
  /* Release the pool lock. */
 
557
  unlock_pool ();
 
558
}
 
559
 
 
560
 
 
561
 
 
562
 
 
563
/*
 
564
   Mix the pool:
 
565
 
 
566
   |........blocks*20byte........|20byte|..44byte..|
 
567
   <..44byte..>           <20byte> 
 
568
        |                    |
 
569
        |                    +------+
 
570
        +---------------------------|----------+
 
571
                                    v          v
 
572
   |........blocks*20byte........|20byte|..44byte..|
 
573
                                 <.....64bytes.....>   
 
574
                                         |
 
575
      +----------------------------------+
 
576
     Hash
 
577
      v
 
578
   |.............................|20byte|..44byte..|
 
579
   <20byte><20byte><..44byte..>
 
580
      |                |
 
581
      |                +---------------------+
 
582
      +-----------------------------+        |
 
583
                                    v        v
 
584
   |.............................|20byte|..44byte..|
 
585
                                 <.....64byte......>
 
586
                                        |
 
587
              +-------------------------+
 
588
             Hash
 
589
              v
 
590
   |.............................|20byte|..44byte..|
 
591
   <20byte><20byte><..44byte..>
 
592
 
 
593
   and so on until we did this for all blocks. 
 
594
 
 
595
   To better protect against implementation errors in this code, we
 
596
   xor a digest of the entire pool into the pool before mixing.
 
597
 
 
598
   Note: this function must only be called with a locked pool.
 
599
 */
 
600
static void
 
601
mix_pool(unsigned char *pool)
 
602
{
 
603
  static unsigned char failsafe_digest[DIGESTLEN];
 
604
  static int failsafe_digest_valid;
 
605
 
 
606
  unsigned char *hashbuf = pool + POOLSIZE;
 
607
  unsigned char *p, *pend;
 
608
  int i, n;
 
609
  RMD160_CONTEXT md;
 
610
 
 
611
#if DIGESTLEN != 20
 
612
#error must have a digest length of 20 for ripe-md-160
 
613
#endif
 
614
 
 
615
  gcry_assert (pool_is_locked);
 
616
  _gcry_rmd160_init( &md );
 
617
 
 
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 );
 
624
 
 
625
  if (failsafe_digest_valid && pool == rndpool)
 
626
    {
 
627
      for (i=0; i < 20; i++)
 
628
        pool[i] ^= failsafe_digest[i];
 
629
    }
 
630
  
 
631
  p = pool;
 
632
  for (n=1; n < POOLBLOCKS; n++)
 
633
    {
 
634
      memcpy (hashbuf, p, DIGESTLEN);
 
635
 
 
636
      p += DIGESTLEN;
 
637
      if (p+DIGESTLEN+BLOCKLEN < pend)
 
638
        memcpy (hashbuf+DIGESTLEN, p+DIGESTLEN, BLOCKLEN-DIGESTLEN);
 
639
      else 
 
640
        {
 
641
          unsigned char *pp = p + DIGESTLEN;
 
642
          
 
643
          for (i=DIGESTLEN; i < BLOCKLEN; i++ )
 
644
            {
 
645
              if ( pp >= pend )
 
646
                pp = pool;
 
647
              hashbuf[i] = *pp++;
 
648
            }
 
649
        }
 
650
      
 
651
      _gcry_rmd160_mixblock ( &md, hashbuf);
 
652
      memcpy(p, hashbuf, 20 );
 
653
    }
 
654
 
 
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)
 
660
      {
 
661
        _gcry_rmd160_hash_buffer (failsafe_digest, pool, POOLSIZE);
 
662
        failsafe_digest_valid = 1;
 
663
      }
 
664
 
 
665
    _gcry_burn_stack (384); /* for the rmd160_mixblock(), rmd160_hash_buffer */
 
666
}
 
667
 
 
668
 
 
669
void
 
670
_gcry_rngcsprng_set_seed_file (const char *name)
 
671
{
 
672
  if (seed_file_name)
 
673
    BUG ();
 
674
  seed_file_name = gcry_xstrdup (name);
 
675
}
 
676
 
 
677
 
 
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. */
 
682
static int
 
683
lock_seed_file (int fd, const char *fname, int for_write)
 
684
{
 
685
#if LOCK_SEED_FILE
 
686
  struct flock lck;
 
687
  struct timeval tv;
 
688
  int backoff=0;
 
689
 
 
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;
 
694
 
 
695
  while (fcntl (fd, F_SETLK, &lck) == -1)
 
696
    {
 
697
      if (errno != EAGAIN && errno != EACCES)
 
698
        {
 
699
          log_info (_("can't lock `%s': %s\n"), fname, strerror (errno));
 
700
          return -1;
 
701
        }
 
702
 
 
703
      if (backoff > 2) /* Show the first message after ~2.25 seconds. */
 
704
        log_info( _("waiting for lock on `%s'...\n"), fname);
 
705
      
 
706
      tv.tv_sec = backoff;
 
707
      tv.tv_usec = 250000;
 
708
      select (0, NULL, NULL, NULL, &tv);
 
709
      if (backoff < 10)
 
710
        backoff++ ;
 
711
    }
 
712
#endif /*LOCK_SEED_FILE*/
 
713
  return 0;
 
714
}
 
715
 
 
716
 
 
717
/* Read in a seed from the random_seed file and return true if this
 
718
   was successful.
 
719
 
 
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.  */
 
732
static int
 
733
read_seed_file (void)
 
734
{
 
735
  int fd;
 
736
  struct stat sb;
 
737
  unsigned char buffer[POOLSIZE];
 
738
  int n;
 
739
 
 
740
  gcry_assert (pool_is_locked);
 
741
 
 
742
  if (!seed_file_name)
 
743
    return 0;
 
744
  
 
745
#ifdef HAVE_DOSISH_SYSTEM
 
746
  fd = open( seed_file_name, O_RDONLY | O_BINARY );
 
747
#else
 
748
  fd = open( seed_file_name, O_RDONLY );
 
749
#endif
 
750
  if( fd == -1 && errno == ENOENT)
 
751
    {
 
752
      allow_seed_file_update = 1;
 
753
      return 0;
 
754
    }
 
755
 
 
756
  if (fd == -1 )
 
757
    {
 
758
      log_info(_("can't open `%s': %s\n"), seed_file_name, strerror(errno) );
 
759
      return 0;
 
760
    }
 
761
  if (lock_seed_file (fd, seed_file_name, 0))
 
762
    {
 
763
      close (fd);
 
764
      return 0;
 
765
    }
 
766
  if (fstat( fd, &sb ) )
 
767
    {
 
768
      log_info(_("can't stat `%s': %s\n"), seed_file_name, strerror(errno) );
 
769
      close(fd);
 
770
      return 0;
 
771
    }
 
772
  if (!S_ISREG(sb.st_mode) )
 
773
    {
 
774
      log_info(_("`%s' is not a regular file - ignored\n"), seed_file_name );
 
775
      close(fd);
 
776
      return 0;
 
777
    }
 
778
  if (!sb.st_size )
 
779
    {
 
780
      log_info(_("note: random_seed file is empty\n") );
 
781
      close(fd);
 
782
      allow_seed_file_update = 1;
 
783
      return 0;
 
784
    }
 
785
  if (sb.st_size != POOLSIZE ) 
 
786
    {
 
787
      log_info(_("warning: invalid size of random_seed file - not used\n") );
 
788
      close(fd);
 
789
      return 0;
 
790
    }
 
791
 
 
792
  do
 
793
    {
 
794
      n = read( fd, buffer, POOLSIZE );
 
795
    } 
 
796
  while (n == -1 && errno == EINTR );
 
797
 
 
798
  if (n != POOLSIZE)
 
799
    {
 
800
      log_fatal(_("can't read `%s': %s\n"), seed_file_name,strerror(errno) );
 
801
      close(fd);/*NOTREACHED*/
 
802
      return 0;
 
803
    }
 
804
  
 
805
  close(fd);
 
806
 
 
807
  add_randomness( buffer, POOLSIZE, RANDOM_ORIGIN_INIT );
 
808
  /* add some minor entropy to the pool now (this will also force a mixing) */
 
809
  {     
 
810
    pid_t x = getpid();
 
811
    add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT );
 
812
  }
 
813
  {
 
814
    time_t x = time(NULL);
 
815
    add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT );
 
816
  }
 
817
  {     
 
818
    clock_t x = clock();
 
819
    add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT );
 
820
  }
 
821
 
 
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 );
 
828
 
 
829
  allow_seed_file_update = 1;
 
830
  return 1;
 
831
}
 
832
 
 
833
 
 
834
void
 
835
_gcry_rngcsprng_update_seed_file (void)
 
836
{
 
837
  unsigned long *sp, *dp;
 
838
  int fd, i;
 
839
 
 
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
 
843
     been initialized.  */
 
844
  initialize_basics ();
 
845
  lock_pool ();
 
846
 
 
847
  if ( !seed_file_name || !rndpool || !pool_filled )
 
848
    {
 
849
      unlock_pool ();
 
850
      return;
 
851
    }
 
852
  if ( !allow_seed_file_update )
 
853
    {
 
854
      unlock_pool ();
 
855
      log_info(_("note: random_seed file not updated\n"));
 
856
      return;
 
857
    }
 
858
 
 
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.  */
 
861
 
 
862
 
 
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++ ) 
 
866
    {
 
867
      *dp = *sp + ADD_VALUE;
 
868
    }
 
869
  mix_pool(rndpool); rndstats.mixrnd++;
 
870
  mix_pool(keypool); rndstats.mixkey++;
 
871
 
 
872
#if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
 
873
  fd = open (seed_file_name, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY,
 
874
             S_IRUSR|S_IWUSR );
 
875
#else
 
876
# if LOCK_SEED_FILE
 
877
    fd = open (seed_file_name, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR );
 
878
# else
 
879
    fd = open (seed_file_name, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR );
 
880
# endif
 
881
#endif
 
882
 
 
883
  if (fd == -1 )
 
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))
 
886
    {
 
887
      close (fd);
 
888
    }
 
889
#if LOCK_SEED_FILE
 
890
  else if (ftruncate (fd, 0))
 
891
    {
 
892
      log_info(_("can't write `%s': %s\n"), seed_file_name, strerror(errno));
 
893
      close (fd);
 
894
    }
 
895
#endif /*LOCK_SEED_FILE*/
 
896
  else 
 
897
    {
 
898
      do
 
899
        {
 
900
          i = write (fd, keypool, POOLSIZE );
 
901
        } 
 
902
      while (i == -1 && errno == EINTR);
 
903
      if (i != POOLSIZE) 
 
904
        log_info (_("can't write `%s': %s\n"),seed_file_name, strerror(errno));
 
905
      if (close(fd))
 
906
        log_info (_("can't close `%s': %s\n"),seed_file_name, strerror(errno));
 
907
    }
 
908
  
 
909
  unlock_pool ();
 
910
}
 
911
 
 
912
 
 
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
 
917
   locked.  */
 
918
static void
 
919
read_pool (byte *buffer, size_t length, int level)
 
920
{
 
921
  int i;
 
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;
 
930
 
 
931
  gcry_assert (pool_is_locked);
 
932
 
 
933
 retry:
 
934
  /* Get our own pid, so that we can detect a fork. */
 
935
  my_pid2 = getpid ();
 
936
  if (my_pid == (pid_t)(-1))                                
 
937
    my_pid = my_pid2;
 
938
  if ( my_pid != my_pid2 )
 
939
    {
 
940
      /* We detected a plain fork; i.e. we are now the child.  Update
 
941
         the static pid and add some randomness. */
 
942
      pid_t x;
 
943
 
 
944
      my_pid = my_pid2;
 
945
      x = my_pid;
 
946
      add_randomness (&x, sizeof(x), RANDOM_ORIGIN_INIT);
 
947
      just_mixed = 0; /* Make sure it will get mixed. */
 
948
    }
 
949
 
 
950
  gcry_assert (pool_is_locked);
 
951
 
 
952
  /* Our code does not allow to extract more than POOLSIZE.  Better
 
953
     check it here. */
 
954
  if (length > POOLSIZE)
 
955
    {
 
956
      log_bug("too many random bits requested\n");
 
957
    }
 
958
 
 
959
  if (!pool_filled)
 
960
    {
 
961
      if (read_seed_file() )
 
962
        pool_filled = 1;
 
963
    }
 
964
 
 
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)
 
968
    {
 
969
      size_t needed;
 
970
 
 
971
      pool_balance = 0;
 
972
      needed = length - pool_balance;
 
973
      if (needed < POOLSIZE/2)
 
974
        needed = POOLSIZE/2;
 
975
      else if( needed > POOLSIZE )
 
976
        BUG ();
 
977
      read_random_source (RANDOM_ORIGIN_EXTRAPOLL, needed,
 
978
                          GCRY_VERY_STRONG_RANDOM);
 
979
      pool_balance += needed;
 
980
      did_initial_extra_seeding = 1;
 
981
    }
 
982
 
 
983
  /* For level 2 make sure that there is enough random in the pool. */
 
984
  if (level == GCRY_VERY_STRONG_RANDOM && pool_balance < length)
 
985
    {
 
986
      size_t needed;
 
987
      
 
988
      if (pool_balance < 0)
 
989
        pool_balance = 0;
 
990
      needed = length - pool_balance;
 
991
      if (needed > POOLSIZE)
 
992
        BUG ();
 
993
      read_random_source (RANDOM_ORIGIN_EXTRAPOLL, needed,
 
994
                          GCRY_VERY_STRONG_RANDOM);
 
995
      pool_balance += needed;
 
996
    }
 
997
 
 
998
  /* Make sure the pool is filled. */
 
999
  while (!pool_filled)
 
1000
    random_poll();
 
1001
 
 
1002
  /* Always do a fast random poll (we have to use the unlocked version). */
 
1003
  do_fast_random_poll();
 
1004
  
 
1005
  /* Mix the pid in so that we for sure won't deliver the same random
 
1006
     after a fork. */
 
1007
  {
 
1008
    pid_t apid = my_pid;
 
1009
    add_randomness (&apid, sizeof (apid), RANDOM_ORIGIN_INIT);
 
1010
  }
 
1011
 
 
1012
  /* Mix the pool (if add_randomness() didn't it). */
 
1013
  if (!just_mixed)
 
1014
    {
 
1015
      mix_pool(rndpool);
 
1016
      rndstats.mixrnd++;
 
1017
    }
 
1018
 
 
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;
 
1023
 
 
1024
  /* Mix both pools. */
 
1025
  mix_pool(rndpool); rndstats.mixrnd++;
 
1026
  mix_pool(keypool); rndstats.mixkey++;
 
1027
 
 
1028
  /* Read the requested data.  We use a read pointer to read from a
 
1029
     different position each time.  */
 
1030
  while (length--)
 
1031
    {
 
1032
      *buffer++ = keypool[pool_readpos++];
 
1033
      if (pool_readpos >= POOLSIZE)
 
1034
        pool_readpos = 0;
 
1035
      pool_balance--;
 
1036
    }
 
1037
 
 
1038
  if (pool_balance < 0)
 
1039
    pool_balance = 0;
 
1040
 
 
1041
  /* Clear the keypool. */
 
1042
  memset (keypool, 0, POOLSIZE);
 
1043
 
 
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 )
 
1051
    {
 
1052
      pid_t x = getpid();
 
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. */
 
1056
      goto retry;
 
1057
    }
 
1058
}
 
1059
 
 
1060
 
 
1061
 
 
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. */
 
1065
static void
 
1066
add_randomness (const void *buffer, size_t length, enum random_origins origin)
 
1067
{
 
1068
  const unsigned char *p = buffer;
 
1069
  size_t count = 0;
 
1070
 
 
1071
  gcry_assert (pool_is_locked);
 
1072
 
 
1073
  rndstats.addbytes += length;
 
1074
  rndstats.naddbytes++;
 
1075
  while (length-- )
 
1076
    {
 
1077
      rndpool[pool_writepos++] ^= *p++;
 
1078
      count++;
 
1079
      if (pool_writepos >= POOLSIZE )
 
1080
        {
 
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)
 
1087
            {
 
1088
              pool_filled_counter += count;
 
1089
              count = 0;
 
1090
              if (pool_filled_counter >= POOLSIZE)
 
1091
                pool_filled = 1;
 
1092
            }
 
1093
          pool_writepos = 0;
 
1094
          mix_pool(rndpool); rndstats.mixrnd++;
 
1095
          just_mixed = !length;
 
1096
        }
 
1097
    }
 
1098
}
 
1099
 
 
1100
 
 
1101
 
 
1102
static void
 
1103
random_poll()
 
1104
{
 
1105
  rndstats.slowpolls++;
 
1106
  read_random_source (RANDOM_ORIGIN_SLOWPOLL, POOLSIZE/5, GCRY_STRONG_RANDOM);
 
1107
}
 
1108
 
 
1109
 
 
1110
/* Runtime determination of the slow entropy gathering module.  */
 
1111
static int (*
 
1112
getfnc_gather_random (void))(void (*)(const void*, size_t, 
 
1113
                                      enum random_origins), 
 
1114
                             enum random_origins, size_t, int)
 
1115
{
 
1116
  int (*fnc)(void (*)(const void*, size_t, enum random_origins), 
 
1117
             enum random_origins, size_t, int);
 
1118
  
 
1119
#if USE_RNDLINUX
 
1120
  if ( !access (NAME_OF_DEV_RANDOM, R_OK)
 
1121
       && !access (NAME_OF_DEV_URANDOM, R_OK))
 
1122
    {
 
1123
      fnc = _gcry_rndlinux_gather_random;
 
1124
      return fnc;
 
1125
    }
 
1126
#endif
 
1127
 
 
1128
#if USE_RNDEGD
 
1129
  if ( _gcry_rndegd_connect_socket (1) != -1 )
 
1130
    {
 
1131
      fnc = _gcry_rndegd_gather_random;
 
1132
      return fnc;
 
1133
    }
 
1134
#endif
 
1135
 
 
1136
#if USE_RNDUNIX
 
1137
  fnc = _gcry_rndunix_gather_random;
 
1138
  return fnc;
 
1139
#endif
 
1140
 
 
1141
#if USE_RNDW32
 
1142
  fnc = _gcry_rndw32_gather_random;
 
1143
  return fnc;
 
1144
#endif
 
1145
 
 
1146
  log_fatal (_("no entropy gathering module detected\n"));
 
1147
 
 
1148
  return NULL; /*NOTREACHED*/
 
1149
}
 
1150
 
 
1151
/* Runtime determination of the fast entropy gathering function.
 
1152
   (Currently a compile time method is used.)  */
 
1153
static void (*
 
1154
getfnc_fast_random_poll (void))( void (*)(const void*, size_t,
 
1155
                                          enum random_origins),
 
1156
                                 enum random_origins)
 
1157
{
 
1158
#if USE_RNDW32
 
1159
  return _gcry_rndw32_gather_random_fast;
 
1160
#endif
 
1161
  return NULL;
 
1162
}
 
1163
 
 
1164
 
 
1165
 
 
1166
static void
 
1167
do_fast_random_poll (void)
 
1168
{
 
1169
  gcry_assert (pool_is_locked);
 
1170
 
 
1171
  rndstats.fastpolls++;
 
1172
 
 
1173
  if (fast_gather_fnc)
 
1174
    fast_gather_fnc (add_randomness, RANDOM_ORIGIN_FASTPOLL);
 
1175
 
 
1176
  /* Continue with the generic functions. */
 
1177
#if HAVE_GETHRTIME
 
1178
  {     
 
1179
    hrtime_t tv;
 
1180
    tv = gethrtime();
 
1181
    add_randomness( &tv, sizeof(tv), RANDOM_ORIGIN_FASTPOLL );
 
1182
  }
 
1183
#elif HAVE_GETTIMEOFDAY
 
1184
  {     
 
1185
    struct timeval tv;
 
1186
    if( gettimeofday( &tv, NULL ) )
 
1187
      BUG();
 
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 );
 
1190
  }
 
1191
#elif HAVE_CLOCK_GETTIME
 
1192
  {     struct timespec tv;
 
1193
  if( clock_gettime( CLOCK_REALTIME, &tv ) == -1 )
 
1194
    BUG();
 
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 );
 
1197
  }
 
1198
#else /* use times */
 
1199
# ifndef HAVE_DOSISH_SYSTEM
 
1200
  {     struct tms buf;
 
1201
  times( &buf );
 
1202
  add_randomness( &buf, sizeof buf, RANDOM_ORIGIN_FASTPOLL );
 
1203
  }
 
1204
# endif
 
1205
#endif
 
1206
 
 
1207
#ifdef HAVE_GETRUSAGE
 
1208
# ifdef RUSAGE_SELF
 
1209
  {     
 
1210
    struct rusage buf;
 
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 );
 
1218
  }
 
1219
# else /*!RUSAGE_SELF*/
 
1220
#  ifdef __GCC__
 
1221
#   warning There is no RUSAGE_SELF on this system
 
1222
#  endif
 
1223
# endif /*!RUSAGE_SELF*/
 
1224
#endif /*HAVE_GETRUSAGE*/
 
1225
 
 
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.  */
 
1228
  {
 
1229
    time_t x = time(NULL);
 
1230
    add_randomness( &x, sizeof(x), RANDOM_ORIGIN_FASTPOLL );
 
1231
  }
 
1232
  {     
 
1233
    clock_t x = clock();
 
1234
    add_randomness( &x, sizeof(x), RANDOM_ORIGIN_FASTPOLL );
 
1235
  }
 
1236
 
 
1237
  /* If the system features a fast hardware RNG, read some bytes from
 
1238
     there.  */
 
1239
  _gcry_rndhw_poll_fast (add_randomness, RANDOM_ORIGIN_FASTPOLL);
 
1240
}
 
1241
 
 
1242
 
 
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. */
 
1250
void
 
1251
_gcry_rngcsprng_fast_poll (void)
 
1252
{
 
1253
  initialize_basics ();
 
1254
 
 
1255
  lock_pool ();
 
1256
  if (rndpool)
 
1257
    {
 
1258
      /* Yes, we are fully initialized. */
 
1259
      do_fast_random_poll ();
 
1260
    }
 
1261
  unlock_pool ();
 
1262
}
 
1263
 
 
1264
 
 
1265
 
 
1266
static void
 
1267
read_random_source (enum random_origins orgin, size_t length, int level )
 
1268
{
 
1269
  if ( !slow_gather_fnc )
 
1270
    log_fatal ("Slow entropy gathering module not yet initialized\n");
 
1271
 
 
1272
  if ( slow_gather_fnc (add_randomness, orgin, length, level) < 0)
 
1273
    log_fatal ("No way to gather entropy for the RNG\n");
 
1274
}
 
1275
 
 
1276
 
 
1277
static int
 
1278
gather_faked (void (*add)(const void*, size_t, enum random_origins),
 
1279
              enum random_origins origin, size_t length, int level )
 
1280
{
 
1281
  static int initialized=0;
 
1282
  size_t n;
 
1283
  char *buffer, *p;
 
1284
  
 
1285
  (void)add;
 
1286
  (void)level;
 
1287
  
 
1288
  if ( !initialized )
 
1289
    {
 
1290
      log_info(_("WARNING: using insecure random number generator!!\n"));
 
1291
      initialized=1;
 
1292
#ifdef HAVE_RAND
 
1293
      srand( time(NULL)*getpid());
 
1294
#else
 
1295
      srandom( time(NULL)*getpid());
 
1296
#endif
 
1297
    }
 
1298
 
 
1299
  p = buffer = gcry_xmalloc( length );
 
1300
  n = length;
 
1301
#ifdef HAVE_RAND
 
1302
  while ( n-- )
 
1303
    *p++ = ((unsigned)(1 + (int) (256.0*rand()/(RAND_MAX+1.0)))-1);
 
1304
#else
 
1305
  while ( n-- )
 
1306
    *p++ = ((unsigned)(1 + (int) (256.0*random()/(RAND_MAX+1.0)))-1);
 
1307
#endif
 
1308
  add_randomness ( buffer, length, origin );
 
1309
  gcry_free (buffer);
 
1310
  return 0; /* okay */
 
1311
}
 
1312
 
 
1313
 
 
1314
/* Create an unpredicable nonce of LENGTH bytes in BUFFER. */
 
1315
void
 
1316
_gcry_rngcsprng_create_nonce (void *buffer, size_t length)
 
1317
{
 
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
 
1323
                                   attributed. */
 
1324
  volatile pid_t apid;
 
1325
  unsigned char *p;
 
1326
  size_t n;
 
1327
  int err;
 
1328
 
 
1329
  /* Make sure we are initialized. */
 
1330
  initialize ();
 
1331
 
 
1332
#ifdef USE_RANDOM_DAEMON
 
1333
  if (allow_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*/
 
1338
 
 
1339
  /* Acquire the nonce buffer lock. */
 
1340
  err = ath_mutex_lock (&nonce_buffer_lock);
 
1341
  if (err)
 
1342
    log_fatal ("failed to acquire the nonce buffer lock: %s\n",
 
1343
               strerror (err));
 
1344
 
 
1345
  apid = getpid ();
 
1346
  /* The first time intialize our buffer. */
 
1347
  if (!nonce_buffer_initialized)
 
1348
    {
 
1349
      time_t atime = time (NULL);
 
1350
      pid_t xpid = apid;
 
1351
 
 
1352
      my_pid = apid;
 
1353
 
 
1354
      if ((sizeof apid + sizeof atime) > sizeof nonce_buffer)
 
1355
        BUG ();
 
1356
 
 
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. */
 
1360
      p = nonce_buffer;
 
1361
      memcpy (p, &xpid, sizeof xpid);
 
1362
      p += sizeof xpid;
 
1363
      memcpy (p, &atime, sizeof atime); 
 
1364
 
 
1365
      /* Initialize the never changing private part of 64 bits. */
 
1366
      gcry_randomize (nonce_buffer+20, 8, GCRY_WEAK_RANDOM);
 
1367
 
 
1368
      nonce_buffer_initialized = 1;
 
1369
    }
 
1370
  else if ( my_pid != apid )
 
1371
    {
 
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
 
1376
         again. */
 
1377
      my_pid = apid;
 
1378
    }
 
1379
 
 
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)
 
1383
    {
 
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);
 
1388
    }
 
1389
 
 
1390
 
 
1391
  /* Release the nonce buffer lock. */
 
1392
  err = ath_mutex_unlock (&nonce_buffer_lock);
 
1393
  if (err)
 
1394
    log_fatal ("failed to release the nonce buffer lock: %s\n",
 
1395
               strerror (err));
 
1396
 
 
1397
}