LCOV - code coverage report
Current view: top level - random - random-csprng.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 177 363 48.8 %
Date: 2015-11-05 17:08:00 Functions: 17 28 60.7 %

          Line data    Source code
       1             : /* random-csprng.c - CSPRNG style random number generator (libgcrypt classic)
       2             :  * Copyright (C) 1998, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
       3             :  *               2007, 2008, 2010, 2012  Free Software Foundation, Inc.
       4             :  *
       5             :  * This file is part of Libgcrypt.
       6             :  *
       7             :  * Libgcrypt is free software; you can redistribute it and/or modify
       8             :  * it under the terms of the GNU Lesser General Public License as
       9             :  * published by the Free Software Foundation; either version 2.1 of
      10             :  * the License, or (at your option) any later version.
      11             :  *
      12             :  * Libgcrypt is distributed in the hope that it will be useful,
      13             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      14             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      15             :  * GNU Lesser General Public License for more details.
      16             :  *
      17             :  * You should have received a copy of the GNU Lesser General Public
      18             :  * License along with this program; if not, see <http://www.gnu.org/licenses/>.
      19             :  */
      20             : 
      21             : /*
      22             :    This random number generator is modelled after the one described in
      23             :    Peter Gutmann's 1998 Usenix Security Symposium paper: "Software
      24             :    Generation of Practically Strong Random Numbers".  See also chapter
      25             :    6 in his book "Cryptographic Security Architecture", New York,
      26             :    2004, ISBN 0-387-95387-6.
      27             : 
      28             :    Note that the acronym CSPRNG stands for "Continuously Seeded
      29             :    PseudoRandom Number Generator" as used in Peter's implementation of
      30             :    the paper and not only for "Cryptographically Secure PseudoRandom
      31             :    Number Generator".
      32             :  */
      33             : 
      34             : 
      35             : #include <config.h>
      36             : #include <stdio.h>
      37             : #include <stdlib.h>
      38             : #include <errno.h>
      39             : #include <string.h>
      40             : #include <sys/time.h>
      41             : #include <sys/types.h>
      42             : #include <sys/stat.h>
      43             : #include <unistd.h>
      44             : #include <fcntl.h>
      45             : #include <time.h>
      46             : #ifdef  HAVE_GETHRTIME
      47             : #include <sys/times.h>
      48             : #endif
      49             : #ifdef HAVE_GETTIMEOFDAY
      50             : #include <sys/time.h>
      51             : #endif
      52             : #ifdef HAVE_GETRUSAGE
      53             : #include <sys/resource.h>
      54             : #endif
      55             : #ifdef __MINGW32__
      56             : #include <process.h>
      57             : #endif
      58             : #include "g10lib.h"
      59             : #include "../cipher/rmd.h"
      60             : #include "random.h"
      61             : #include "rand-internal.h"
      62             : #include "cipher.h" /* Required for the rmd160_hash_buffer() prototype.  */
      63             : 
      64             : #ifndef RAND_MAX   /* For SunOS. */
      65             : #define RAND_MAX 32767
      66             : #endif
      67             : 
      68             : /* Check whether we can lock the seed file read write. */
      69             : #if defined(HAVE_FCNTL) && defined(HAVE_FTRUNCATE) && !defined(HAVE_W32_SYSTEM)
      70             : #define LOCK_SEED_FILE 1
      71             : #else
      72             : #define LOCK_SEED_FILE 0
      73             : #endif
      74             : 
      75             : /* Define the constant we use for transforming the pool at read-out. */
      76             : #if SIZEOF_UNSIGNED_LONG == 8
      77             : #define ADD_VALUE 0xa5a5a5a5a5a5a5a5
      78             : #elif SIZEOF_UNSIGNED_LONG == 4
      79             : #define ADD_VALUE 0xa5a5a5a5
      80             : #else
      81             : #error weird size for an unsigned long
      82             : #endif
      83             : 
      84             : /* Contstants pertaining to the hash pool. */
      85             : #define BLOCKLEN  64   /* Hash this amount of bytes... */
      86             : #define DIGESTLEN 20   /* ... into a digest of this length (rmd160). */
      87             : /* POOLBLOCKS is the number of digests which make up the pool.  */
      88             : #define POOLBLOCKS 30
      89             : /* POOLSIZE must be a multiple of the digest length to make the AND
      90             :    operations faster, the size should also be a multiple of unsigned
      91             :    long.  */
      92             : #define POOLSIZE (POOLBLOCKS*DIGESTLEN)
      93             : #if (POOLSIZE % SIZEOF_UNSIGNED_LONG)
      94             : #error Please make sure that poolsize is a multiple of unsigned long
      95             : #endif
      96             : #define POOLWORDS (POOLSIZE / SIZEOF_UNSIGNED_LONG)
      97             : 
      98             : 
      99             : /* RNDPOOL is the pool we use to collect the entropy and to stir it
     100             :    up.  Its allocated size is POOLSIZE+BLOCKLEN.  Note that this is
     101             :    also an indication on whether the module has been fully
     102             :    initialized. */
     103             : static unsigned char *rndpool;
     104             : 
     105             : /* KEYPOOL is used as a scratch copy to read out random from RNDPOOL.
     106             :    Its allocated size is also POOLSIZE+BLOCKLEN.  */
     107             : static unsigned char *keypool;
     108             : 
     109             : /* This is the offset into RNDPOOL where the next random bytes are to
     110             :    be mixed in.  */
     111             : static size_t pool_writepos;
     112             : 
     113             : /* When reading data out of KEYPOOL, we start the read at different
     114             :    positions.  This variable keeps track on where to read next.  */
     115             : static size_t pool_readpos;
     116             : 
     117             : /* This flag is set to true as soon as the pool has been completely
     118             :    filled the first time.  This may happen either by rereading a seed
     119             :    file or by adding enough entropy.  */
     120             : static int pool_filled;
     121             : 
     122             : /* This counter is used to track whether the initial seeding has been
     123             :    done with enough bytes from a reliable entropy source.  */
     124             : static size_t pool_filled_counter;
     125             : 
     126             : /* If random of level GCRY_VERY_STRONG_RANDOM has been requested we
     127             :    have stricter requirements on what kind of entropy is in the pool.
     128             :    In particular POOL_FILLED is not sufficient.  Thus we add some
     129             :    extra seeding and set this flag to true if the extra seeding has
     130             :    been done.  */
     131             : static int did_initial_extra_seeding;
     132             : 
     133             : /* This variable is used to estimated the amount of fresh entropy
     134             :    available in RNDPOOL.  */
     135             : static int pool_balance;
     136             : 
     137             : /* After a mixing operation this variable will be set to true and
     138             :    cleared if new entropy has been added or a remix is required for
     139             :    other reasons.  */
     140             : static int just_mixed;
     141             : 
     142             : /* The name of the seed file or NULL if no seed file has been defined.
     143             :    The seed file needs to be regsitered at initialiation time.  We
     144             :    keep a malloced copy here.  */
     145             : static char *seed_file_name;
     146             : 
     147             : /* If a seed file has been registered and maybe updated on exit this
     148             :    flag set. */
     149             : static int allow_seed_file_update;
     150             : 
     151             : /* Option flag set at initialiation time to force allocation of the
     152             :    pool in secure memory.  */
     153             : static int secure_alloc;
     154             : 
     155             : /* This function pointer is set to the actual entropy gathering
     156             :    function during initialization.  After initialization it is
     157             :    guaranteed to point to function.  (On systems without a random
     158             :    gatherer module a dummy function is used).*/
     159             : static int (*slow_gather_fnc)(void (*)(const void*, size_t,
     160             :                                        enum random_origins),
     161             :                               enum random_origins, size_t, int);
     162             : 
     163             : /* This function is set to the actual fast entropy gathering function
     164             :    during initialization.  If it is NULL, no such function is
     165             :    available. */
     166             : static void (*fast_gather_fnc)(void (*)(const void*, size_t,
     167             :                                         enum random_origins),
     168             :                                enum random_origins);
     169             : 
     170             : 
     171             : /* Option flag useful for debugging and the test suite.  If set
     172             :    requests for very strong random are degraded to strong random.  Not
     173             :    used by regular applications.  */
     174             : static int quick_test;
     175             : 
     176             : /* On systems without entropy gathering modules, this flag is set to
     177             :    indicate that the random generator is not working properly.  A
     178             :    warning message is issued as well.  This is useful only for
     179             :    debugging and during development.  */
     180             : static int faked_rng;
     181             : 
     182             : /* This is the lock we use to protect all pool operations.  */
     183             : GPGRT_LOCK_DEFINE (pool_lock);
     184             : 
     185             : /* This is a helper for assert calls.  These calls are used to assert
     186             :    that functions are called in a locked state.  It is not meant to be
     187             :    thread-safe but as a method to get aware of missing locks in the
     188             :    test suite.  */
     189             : static int pool_is_locked;
     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             : 
     210             : /* --- Stuff pertaining to the random daemon support. --- */
     211             : #ifdef USE_RANDOM_DAEMON
     212             : 
     213             : /* If ALLOW_DAEMON is true, the module will try to use the random
     214             :    daemon first.  If the daemon has failed, this variable is set to
     215             :    back to false and the code continues as normal.  Note, we don't
     216             :    test this flag in a locked state because a wrong value does not
     217             :    harm and the trhead will find out itself that the daemon does not
     218             :    work and set it (again) to false.  */
     219             : static int allow_daemon;
     220             : 
     221             : /* During initialization, the user may set a non-default socket name
     222             :    for accessing the random daemon.  If this value is NULL, the
     223             :    default name will be used. */
     224             : static char *daemon_socket_name;
     225             : 
     226             : #endif /*USE_RANDOM_DAEMON*/
     227             : 
     228             : 
     229             : 
     230             : /* ---  Prototypes  --- */
     231             : static void read_pool (byte *buffer, size_t length, int level );
     232             : static void add_randomness (const void *buffer, size_t length,
     233             :                             enum random_origins origin);
     234             : static void random_poll (void);
     235             : static void do_fast_random_poll (void);
     236             : static int (*getfnc_gather_random (void))(void (*)(const void*, size_t,
     237             :                                                    enum random_origins),
     238             :                                           enum random_origins, size_t, int);
     239             : static void (*getfnc_fast_random_poll (void))(void (*)(const void*, size_t,
     240             :                                                        enum random_origins),
     241             :                                               enum random_origins);
     242             : static void read_random_source (enum random_origins origin,
     243             :                                 size_t length, int level);
     244             : static int gather_faked (void (*add)(const void*, size_t, enum random_origins),
     245             :                          enum random_origins, size_t length, int level );
     246             : 
     247             : 
     248             : 
     249             : /* ---  Functions  --- */
     250             : 
     251             : 
     252             : /* Basic initialization which is required to initialize mutexes and
     253             :    such.  It does not run a full initialization so that the filling of
     254             :    the random pool can be delayed until it is actually needed.  We
     255             :    assume that this function is used before any concurrent access
     256             :    happens. */
     257             : static void
     258       36867 : initialize_basics(void)
     259             : {
     260             :   static int initialized;
     261             : 
     262       36867 :   if (!initialized)
     263             :     {
     264          29 :       initialized = 1;
     265             : 
     266             : #ifdef USE_RANDOM_DAEMON
     267             :       _gcry_daemon_initialize_basics ();
     268             : #endif /*USE_RANDOM_DAEMON*/
     269             : 
     270             :       /* Make sure that we are still using the values we have
     271             :          traditionally used for the random levels.  */
     272             :       gcry_assert (GCRY_WEAK_RANDOM == 0
     273             :                    && GCRY_STRONG_RANDOM == 1
     274             :                    && GCRY_VERY_STRONG_RANDOM == 2);
     275             :     }
     276       36867 : }
     277             : 
     278             : /* Take the pool lock. */
     279             : static void
     280       37542 : lock_pool (void)
     281             : {
     282             :   int err;
     283             : 
     284       37542 :   err = gpgrt_lock_lock (&pool_lock);
     285       37543 :   if (err)
     286           0 :     log_fatal ("failed to acquire the pool lock: %s\n", gpg_strerror (err));
     287       37543 :   pool_is_locked = 1;
     288       37543 : }
     289             : 
     290             : /* Release the pool lock. */
     291             : static void
     292       37543 : unlock_pool (void)
     293             : {
     294             :   int err;
     295             : 
     296       37543 :   pool_is_locked = 0;
     297       37543 :   err = gpgrt_lock_unlock (&pool_lock);
     298       37543 :   if (err)
     299           0 :     log_fatal ("failed to release the pool lock: %s\n", gpg_strerror (err));
     300       37543 : }
     301             : 
     302             : 
     303             : /* Full initialization of this module. */
     304             : static void
     305       15662 : initialize(void)
     306             : {
     307             :   /* Although the basic initialization should have happened already,
     308             :      we call it here to make sure that all prerequisites are met.  */
     309       15662 :   initialize_basics ();
     310             : 
     311             :   /* Now we can look the pool and complete the initialization if
     312             :      necessary.  */
     313       15662 :   lock_pool ();
     314       15663 :   if (!rndpool)
     315             :     {
     316             :       /* The data buffer is allocated somewhat larger, so that we can
     317             :          use this extra space (which is allocated in secure memory) as
     318             :          a temporary hash buffer */
     319          17 :       rndpool = (secure_alloc
     320          17 :                  ? xcalloc_secure (1, POOLSIZE + BLOCKLEN)
     321             :                  : xcalloc (1, POOLSIZE + BLOCKLEN));
     322          17 :       keypool = (secure_alloc
     323          17 :                  ? xcalloc_secure (1, POOLSIZE + BLOCKLEN)
     324             :                  : xcalloc (1, POOLSIZE + BLOCKLEN));
     325             : 
     326             :       /* Setup the slow entropy gathering function.  The code requires
     327             :          that this function exists. */
     328          17 :       slow_gather_fnc = getfnc_gather_random ();
     329          17 :       if (!slow_gather_fnc)
     330             :         {
     331           0 :           faked_rng = 1;
     332           0 :           slow_gather_fnc = gather_faked;
     333             :         }
     334             : 
     335             :       /* Setup the fast entropy gathering function.  */
     336          17 :       fast_gather_fnc = getfnc_fast_random_poll ();
     337             : 
     338             :     }
     339       15663 :   unlock_pool ();
     340       15663 : }
     341             : 
     342             : 
     343             : 
     344             : 
     345             : /* Initialize this random subsystem.  If FULL is false, this function
     346             :    merely calls the initialize and does not do anything more.  Doing
     347             :    this is not really required but when running in a threaded
     348             :    environment we might get a race condition otherwise. */
     349             : void
     350       14987 : _gcry_rngcsprng_initialize (int full)
     351             : {
     352       14987 :   if (!full)
     353          27 :     initialize_basics ();
     354             :   else
     355       14960 :     initialize ();
     356       14988 : }
     357             : 
     358             : 
     359             : /* Try to close the FDs of the random gather module.  This is
     360             :    currently only implemented for rndlinux. */
     361             : void
     362           0 : _gcry_rngcsprng_close_fds (void)
     363             : {
     364           0 :   lock_pool ();
     365             : #if USE_RNDLINUX
     366           0 :   _gcry_rndlinux_gather_random (NULL, 0, 0, 0);
     367           0 :   pool_filled = 0; /* Force re-open on next use.  */
     368             : #endif
     369           0 :   unlock_pool ();
     370           0 : }
     371             : 
     372             : 
     373             : void
     374           0 : _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           0 :   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           0 :             _gcry_rndhw_failed_p()? " (hwrng failed)":"");
     387           0 : }
     388             : 
     389             : 
     390             : /* This function should be called during initialization and before
     391             :    initialization of this module to place the random pools into secure
     392             :    memory.  */
     393             : void
     394           0 : _gcry_rngcsprng_secure_alloc (void)
     395             : {
     396           0 :   secure_alloc = 1;
     397           0 : }
     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          15 : _gcry_rngcsprng_enable_quick_gen (void)
     404             : {
     405          15 :   quick_test = 1;
     406          15 : }
     407             : 
     408             : 
     409             : void
     410           0 : _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           0 : }
     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           0 : _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           0 :   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           0 : _gcry_rngcsprng_is_faked (void)
     452             : {
     453             :   /* We need to initialize due to the runtime determination of
     454             :      available entropy gather modules.  */
     455           0 :   initialize();
     456           0 :   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           0 : _gcry_rngcsprng_add_bytes (const void *buf, size_t buflen, int quality)
     465             : {
     466             :   size_t nbytes;
     467             :   const char *bufptr;
     468             : 
     469           0 :   if (quality == -1)
     470           0 :     quality = 35;
     471           0 :   else if (quality > 100)
     472           0 :     quality = 100;
     473           0 :   else if (quality < 0)
     474           0 :     quality = 0;
     475             : 
     476           0 :   if (!buf)
     477           0 :     return gpg_error (GPG_ERR_INV_ARG);
     478             : 
     479           0 :   if (!buflen || quality < 10)
     480           0 :     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           0 :   initialize_basics ();
     487           0 :   bufptr = buf;
     488           0 :   while (buflen)
     489             :     {
     490           0 :       nbytes = buflen > POOLSIZE? POOLSIZE : buflen;
     491           0 :       lock_pool ();
     492           0 :       if (rndpool)
     493           0 :         add_randomness (bufptr, nbytes, RANDOM_ORIGIN_EXTERNAL);
     494           0 :       unlock_pool ();
     495           0 :       bufptr += nbytes;
     496           0 :       buflen -= nbytes;
     497             :     }
     498           0 :   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         702 : _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         702 :   initialize ();
     515             : 
     516             :   /* Handle our hack used for regression tests of Libgcrypt. */
     517         702 :   if ( quick_test && level > GCRY_STRONG_RANDOM )
     518          71 :     level = GCRY_STRONG_RANDOM;
     519             : 
     520             :   /* Make sure the level is okay. */
     521         702 :   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         702 :   lock_pool ();
     532             : 
     533             :   /* Update the statistics. */
     534         702 :   if (level >= GCRY_VERY_STRONG_RANDOM)
     535             :     {
     536           0 :       rndstats.getbytes2 += length;
     537           0 :       rndstats.ngetbytes2++;
     538             :     }
     539             :   else
     540             :     {
     541         702 :       rndstats.getbytes1 += length;
     542         702 :       rndstats.ngetbytes1++;
     543             :     }
     544             : 
     545             :   /* Read the random into the provided buffer. */
     546        2106 :   for (p = buffer; length > 0;)
     547             :     {
     548             :       size_t n;
     549             : 
     550         702 :       n = length > POOLSIZE? POOLSIZE : length;
     551         702 :       read_pool (p, n, level);
     552         702 :       length -= n;
     553         702 :       p += n;
     554             :     }
     555             : 
     556             :   /* Release the pool lock. */
     557         702 :   unlock_pool ();
     558         702 : }
     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        2471 : mix_pool(unsigned char *pool)
     602             : {
     603             :   static unsigned char failsafe_digest[DIGESTLEN];
     604             :   static int failsafe_digest_valid;
     605             : 
     606        2471 :   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        2471 :   gcry_assert (pool_is_locked);
     616        2471 :   _gcry_rmd160_init( &md );
     617             : 
     618             :   /* Loop over the pool.  */
     619        2471 :   pend = pool + POOLSIZE;
     620        2471 :   memcpy(hashbuf, pend - DIGESTLEN, DIGESTLEN );
     621        2471 :   memcpy(hashbuf+DIGESTLEN, pool, BLOCKLEN-DIGESTLEN);
     622        2471 :   _gcry_rmd160_mixblock( &md, hashbuf);
     623        2471 :   memcpy(pool, hashbuf, 20 );
     624             : 
     625        2471 :   if (failsafe_digest_valid && pool == rndpool)
     626             :     {
     627       36792 :       for (i=0; i < 20; i++)
     628       35040 :         pool[i] ^= failsafe_digest[i];
     629             :     }
     630             : 
     631        2471 :   p = pool;
     632       74130 :   for (n=1; n < POOLBLOCKS; n++)
     633             :     {
     634       71659 :       memcpy (hashbuf, p, DIGESTLEN);
     635             : 
     636       71659 :       p += DIGESTLEN;
     637       71659 :       if (p+DIGESTLEN+BLOCKLEN < pend)
     638       61775 :         memcpy (hashbuf+DIGESTLEN, p+DIGESTLEN, BLOCKLEN-DIGESTLEN);
     639             :       else
     640             :         {
     641        9884 :           unsigned char *pp = p + DIGESTLEN;
     642             : 
     643      444780 :           for (i=DIGESTLEN; i < BLOCKLEN; i++ )
     644             :             {
     645      434896 :               if ( pp >= pend )
     646        7413 :                 pp = pool;
     647      434896 :               hashbuf[i] = *pp++;
     648             :             }
     649             :         }
     650             : 
     651       71659 :       _gcry_rmd160_mixblock ( &md, hashbuf);
     652       71659 :       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        2471 :     if ( pool == rndpool)
     660             :       {
     661        1769 :         _gcry_rmd160_hash_buffer (failsafe_digest, pool, POOLSIZE);
     662        1769 :         failsafe_digest_valid = 1;
     663             :       }
     664             : 
     665        2471 :     _gcry_burn_stack (384); /* for the rmd160_mixblock(), rmd160_hash_buffer */
     666        2471 : }
     667             : 
     668             : 
     669             : void
     670           0 : _gcry_rngcsprng_set_seed_file (const char *name)
     671             : {
     672           0 :   if (seed_file_name)
     673           0 :     BUG ();
     674           0 :   seed_file_name = xstrdup (name);
     675           0 : }
     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           0 : lock_seed_file (int fd, const char *fname, int for_write)
     684             : {
     685             : #ifdef __GCC__
     686             : #warning Check whether we can lock on Windows.
     687             : #endif
     688             : #if LOCK_SEED_FILE
     689             :   struct flock lck;
     690             :   struct timeval tv;
     691           0 :   int backoff=0;
     692             : 
     693             :   /* We take a lock on the entire file. */
     694           0 :   memset (&lck, 0, sizeof lck);
     695           0 :   lck.l_type = for_write? F_WRLCK : F_RDLCK;
     696           0 :   lck.l_whence = SEEK_SET;
     697             : 
     698           0 :   while (fcntl (fd, F_SETLK, &lck) == -1)
     699             :     {
     700           0 :       if (errno != EAGAIN && errno != EACCES)
     701             :         {
     702           0 :           log_info (_("can't lock `%s': %s\n"), fname, strerror (errno));
     703           0 :           return -1;
     704             :         }
     705             : 
     706           0 :       if (backoff > 2) /* Show the first message after ~2.25 seconds. */
     707           0 :         log_info( _("waiting for lock on `%s'...\n"), fname);
     708             : 
     709           0 :       tv.tv_sec = backoff;
     710           0 :       tv.tv_usec = 250000;
     711           0 :       select (0, NULL, NULL, NULL, &tv);
     712           0 :       if (backoff < 10)
     713           0 :         backoff++ ;
     714             :     }
     715             : #endif /*!LOCK_SEED_FILE*/
     716           0 :   return 0;
     717             : }
     718             : 
     719             : 
     720             : /* Read in a seed from the random_seed file and return true if this
     721             :    was successful.
     722             : 
     723             :    Note: Multiple instances of applications sharing the same random
     724             :    seed file can be started in parallel, in which case they will read
     725             :    out the same pool and then race for updating it (the last update
     726             :    overwrites earlier updates).  They will differentiate only by the
     727             :    weak entropy that is added in read_seed_file based on the PID and
     728             :    clock, and up to 16 bytes of weak random non-blockingly.  The
     729             :    consequence is that the output of these different instances is
     730             :    correlated to some extent.  In the perfect scenario, the attacker
     731             :    can control (or at least guess) the PID and clock of the
     732             :    application, and drain the system's entropy pool to reduce the "up
     733             :    to 16 bytes" above to 0.  Then the dependencies of the initial
     734             :    states of the pools are completely known.  */
     735             : static int
     736          17 : read_seed_file (void)
     737             : {
     738             :   int fd;
     739             :   struct stat sb;
     740             :   unsigned char buffer[POOLSIZE];
     741             :   int n;
     742             : 
     743          17 :   gcry_assert (pool_is_locked);
     744             : 
     745          17 :   if (!seed_file_name)
     746          17 :     return 0;
     747             : 
     748             : #ifdef HAVE_DOSISH_SYSTEM
     749             :   fd = open( seed_file_name, O_RDONLY | O_BINARY );
     750             : #else
     751           0 :   fd = open( seed_file_name, O_RDONLY );
     752             : #endif
     753           0 :   if( fd == -1 && errno == ENOENT)
     754             :     {
     755           0 :       allow_seed_file_update = 1;
     756           0 :       return 0;
     757             :     }
     758             : 
     759           0 :   if (fd == -1 )
     760             :     {
     761           0 :       log_info(_("can't open `%s': %s\n"), seed_file_name, strerror(errno) );
     762           0 :       return 0;
     763             :     }
     764           0 :   if (lock_seed_file (fd, seed_file_name, 0))
     765             :     {
     766           0 :       close (fd);
     767           0 :       return 0;
     768             :     }
     769           0 :   if (fstat( fd, &sb ) )
     770             :     {
     771           0 :       log_info(_("can't stat `%s': %s\n"), seed_file_name, strerror(errno) );
     772           0 :       close(fd);
     773           0 :       return 0;
     774             :     }
     775           0 :   if (!S_ISREG(sb.st_mode) )
     776             :     {
     777           0 :       log_info(_("`%s' is not a regular file - ignored\n"), seed_file_name );
     778           0 :       close(fd);
     779           0 :       return 0;
     780             :     }
     781           0 :   if (!sb.st_size )
     782             :     {
     783           0 :       log_info(_("note: random_seed file is empty\n") );
     784           0 :       close(fd);
     785           0 :       allow_seed_file_update = 1;
     786           0 :       return 0;
     787             :     }
     788           0 :   if (sb.st_size != POOLSIZE )
     789             :     {
     790           0 :       log_info(_("warning: invalid size of random_seed file - not used\n") );
     791           0 :       close(fd);
     792           0 :       return 0;
     793             :     }
     794             : 
     795             :   do
     796             :     {
     797           0 :       n = read( fd, buffer, POOLSIZE );
     798             :     }
     799           0 :   while (n == -1 && errno == EINTR );
     800             : 
     801           0 :   if (n != POOLSIZE)
     802             :     {
     803           0 :       log_fatal(_("can't read `%s': %s\n"), seed_file_name,strerror(errno) );
     804             :       close(fd);/*NOTREACHED*/
     805             :       return 0;
     806             :     }
     807             : 
     808           0 :   close(fd);
     809             : 
     810           0 :   add_randomness( buffer, POOLSIZE, RANDOM_ORIGIN_INIT );
     811             :   /* add some minor entropy to the pool now (this will also force a mixing) */
     812             :   {
     813           0 :     pid_t x = getpid();
     814           0 :     add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT );
     815             :   }
     816             :   {
     817           0 :     time_t x = time(NULL);
     818           0 :     add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT );
     819             :   }
     820             :   {
     821           0 :     clock_t x = clock();
     822           0 :     add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT );
     823             :   }
     824             : 
     825             :   /* And read a few bytes from our entropy source.  By using a level
     826             :    * of 0 this will not block and might not return anything with some
     827             :    * entropy drivers, however the rndlinux driver will use
     828             :    * /dev/urandom and return some stuff - Do not read too much as we
     829             :    * want to be friendly to the scare system entropy resource. */
     830           0 :   read_random_source ( RANDOM_ORIGIN_INIT, 16, GCRY_WEAK_RANDOM );
     831             : 
     832           0 :   allow_seed_file_update = 1;
     833           0 :   return 1;
     834             : }
     835             : 
     836             : 
     837             : void
     838           0 : _gcry_rngcsprng_update_seed_file (void)
     839             : {
     840             :   unsigned long *sp, *dp;
     841             :   int fd, i;
     842             : 
     843             :   /* We do only a basic initialization so that we can lock the pool.
     844             :      This is required to cope with the case that this function is
     845             :      called by some cleanup code at a point where the RNG has never
     846             :      been initialized.  */
     847           0 :   initialize_basics ();
     848           0 :   lock_pool ();
     849             : 
     850           0 :   if ( !seed_file_name || !rndpool || !pool_filled )
     851             :     {
     852           0 :       unlock_pool ();
     853           0 :       return;
     854             :     }
     855           0 :   if ( !allow_seed_file_update )
     856             :     {
     857           0 :       unlock_pool ();
     858           0 :       log_info(_("note: random_seed file not updated\n"));
     859           0 :       return;
     860             :     }
     861             : 
     862             :   /* At this point we know that there is something in the pool and
     863             :      thus we can conclude that the pool has been fully initialized.  */
     864             : 
     865             : 
     866             :   /* Copy the entropy pool to a scratch pool and mix both of them. */
     867           0 :   for (i=0,dp=(unsigned long*)(void*)keypool, sp=(unsigned long*)(void*)rndpool;
     868           0 :        i < POOLWORDS; i++, dp++, sp++ )
     869             :     {
     870           0 :       *dp = *sp + ADD_VALUE;
     871             :     }
     872           0 :   mix_pool(rndpool); rndstats.mixrnd++;
     873           0 :   mix_pool(keypool); rndstats.mixkey++;
     874             : 
     875             : #if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
     876             :   fd = open (seed_file_name, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY,
     877             :              S_IRUSR|S_IWUSR );
     878             : #else
     879             : # if LOCK_SEED_FILE
     880           0 :     fd = open (seed_file_name, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR );
     881             : # else
     882             :     fd = open (seed_file_name, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR );
     883             : # endif
     884             : #endif
     885             : 
     886           0 :   if (fd == -1 )
     887           0 :     log_info (_("can't create `%s': %s\n"), seed_file_name, strerror(errno) );
     888           0 :   else if (lock_seed_file (fd, seed_file_name, 1))
     889             :     {
     890           0 :       close (fd);
     891             :     }
     892             : #if LOCK_SEED_FILE
     893           0 :   else if (ftruncate (fd, 0))
     894             :     {
     895           0 :       log_info(_("can't write `%s': %s\n"), seed_file_name, strerror(errno));
     896           0 :       close (fd);
     897             :     }
     898             : #endif /*LOCK_SEED_FILE*/
     899             :   else
     900             :     {
     901             :       do
     902             :         {
     903           0 :           i = write (fd, keypool, POOLSIZE );
     904             :         }
     905           0 :       while (i == -1 && errno == EINTR);
     906           0 :       if (i != POOLSIZE)
     907           0 :         log_info (_("can't write `%s': %s\n"),seed_file_name, strerror(errno));
     908           0 :       if (close(fd))
     909           0 :         log_info (_("can't close `%s': %s\n"),seed_file_name, strerror(errno));
     910             :     }
     911             : 
     912           0 :   unlock_pool ();
     913             : }
     914             : 
     915             : 
     916             : /* Read random out of the pool.  This function is the core of the
     917             :    public random functions.  Note that Level GCRY_WEAK_RANDOM is not
     918             :    anymore handled special and in fact is an alias in the API for
     919             :    level GCRY_STRONG_RANDOM.  Must be called with the pool already
     920             :    locked.  */
     921             : static void
     922         702 : read_pool (byte *buffer, size_t length, int level)
     923             : {
     924             :   int i;
     925             :   unsigned long *sp, *dp;
     926             :   /* The volatile is there to make sure the compiler does not optimize
     927             :      the code away in case the getpid function is badly attributed.
     928             :      Note that we keep a pid in a static variable as well as in a
     929             :      stack based one; the latter is to detect ill behaving thread
     930             :      libraries, ignoring the pool mutexes. */
     931             :   static volatile pid_t my_pid = (pid_t)(-1);
     932             :   volatile pid_t my_pid2;
     933             : 
     934         702 :   gcry_assert (pool_is_locked);
     935             : 
     936             :  retry:
     937             :   /* Get our own pid, so that we can detect a fork. */
     938         702 :   my_pid2 = getpid ();
     939         702 :   if (my_pid == (pid_t)(-1))
     940          17 :     my_pid = my_pid2;
     941         702 :   if ( my_pid != my_pid2 )
     942             :     {
     943             :       /* We detected a plain fork; i.e. we are now the child.  Update
     944             :          the static pid and add some randomness. */
     945             :       pid_t x;
     946             : 
     947           0 :       my_pid = my_pid2;
     948           0 :       x = my_pid;
     949           0 :       add_randomness (&x, sizeof(x), RANDOM_ORIGIN_INIT);
     950           0 :       just_mixed = 0; /* Make sure it will get mixed. */
     951             :     }
     952             : 
     953         702 :   gcry_assert (pool_is_locked);
     954             : 
     955             :   /* Our code does not allow to extract more than POOLSIZE.  Better
     956             :      check it here. */
     957         702 :   if (length > POOLSIZE)
     958             :     {
     959           0 :       log_bug("too many random bits requested\n");
     960             :     }
     961             : 
     962         702 :   if (!pool_filled)
     963             :     {
     964          17 :       if (read_seed_file() )
     965           0 :         pool_filled = 1;
     966             :     }
     967             : 
     968             :   /* For level 2 quality (key generation) we always make sure that the
     969             :      pool has been seeded enough initially. */
     970         702 :   if (level == GCRY_VERY_STRONG_RANDOM && !did_initial_extra_seeding)
     971             :     {
     972             :       size_t needed;
     973             : 
     974           0 :       pool_balance = 0;
     975           0 :       needed = length - pool_balance;
     976           0 :       if (needed < 16)  /* At least 128 bits.  */
     977           0 :         needed = 16;
     978           0 :       else if( needed > POOLSIZE )
     979           0 :         BUG ();
     980           0 :       read_random_source (RANDOM_ORIGIN_EXTRAPOLL, needed,
     981             :                           GCRY_VERY_STRONG_RANDOM);
     982           0 :       pool_balance += needed;
     983           0 :       did_initial_extra_seeding = 1;
     984             :     }
     985             : 
     986             :   /* For level 2 make sure that there is enough random in the pool. */
     987         702 :   if (level == GCRY_VERY_STRONG_RANDOM && pool_balance < length)
     988             :     {
     989             :       size_t needed;
     990             : 
     991           0 :       if (pool_balance < 0)
     992           0 :         pool_balance = 0;
     993           0 :       needed = length - pool_balance;
     994           0 :       if (needed > POOLSIZE)
     995           0 :         BUG ();
     996           0 :       read_random_source (RANDOM_ORIGIN_EXTRAPOLL, needed,
     997             :                           GCRY_VERY_STRONG_RANDOM);
     998           0 :       pool_balance += needed;
     999             :     }
    1000             : 
    1001             :   /* Make sure the pool is filled. */
    1002        1829 :   while (!pool_filled)
    1003         425 :     random_poll();
    1004             : 
    1005             :   /* Always do a fast random poll (we have to use the unlocked version). */
    1006         702 :   do_fast_random_poll();
    1007             : 
    1008             :   /* Mix the pid in so that we for sure won't deliver the same random
    1009             :      after a fork. */
    1010             :   {
    1011         702 :     pid_t apid = my_pid;
    1012         702 :     add_randomness (&apid, sizeof (apid), RANDOM_ORIGIN_INIT);
    1013             :   }
    1014             : 
    1015             :   /* Mix the pool (if add_randomness() didn't it). */
    1016         702 :   if (!just_mixed)
    1017             :     {
    1018         558 :       mix_pool(rndpool);
    1019         558 :       rndstats.mixrnd++;
    1020             :     }
    1021             : 
    1022             :   /* Create a new pool. */
    1023       54054 :   for(i=0,dp=(unsigned long*)(void*)keypool, sp=(unsigned long*)(void*)rndpool;
    1024       52650 :       i < POOLWORDS; i++, dp++, sp++ )
    1025       52650 :     *dp = *sp + ADD_VALUE;
    1026             : 
    1027             :   /* Mix both pools. */
    1028         702 :   mix_pool(rndpool); rndstats.mixrnd++;
    1029         702 :   mix_pool(keypool); rndstats.mixkey++;
    1030             : 
    1031             :   /* Read the requested data.  We use a read pointer to read from a
    1032             :      different position each time.  */
    1033       32384 :   while (length--)
    1034             :     {
    1035       30980 :       *buffer++ = keypool[pool_readpos++];
    1036       30980 :       if (pool_readpos >= POOLSIZE)
    1037          49 :         pool_readpos = 0;
    1038       30980 :       pool_balance--;
    1039             :     }
    1040             : 
    1041         702 :   if (pool_balance < 0)
    1042         702 :     pool_balance = 0;
    1043             : 
    1044             :   /* Clear the keypool. */
    1045         702 :   memset (keypool, 0, POOLSIZE);
    1046             : 
    1047             :   /* We need to detect whether a fork has happened.  A fork might have
    1048             :      an identical pool and thus the child and the parent could emit
    1049             :      the very same random number.  This test here is to detect forks
    1050             :      in a multi-threaded process.  It does not work with all thread
    1051             :      implementations in particular not with pthreads.  However it is
    1052             :      good enough for GNU Pth. */
    1053         702 :   if ( getpid () != my_pid2 )
    1054             :     {
    1055           0 :       pid_t x = getpid();
    1056           0 :       add_randomness (&x, sizeof(x), RANDOM_ORIGIN_INIT);
    1057           0 :       just_mixed = 0; /* Make sure it will get mixed. */
    1058           0 :       my_pid = x;     /* Also update the static pid. */
    1059           0 :       goto retry;
    1060             :     }
    1061         702 : }
    1062             : 
    1063             : 
    1064             : 
    1065             : /* Add LENGTH bytes of randomness from buffer to the pool.  ORIGIN is
    1066             :    used to specify the randomness origin.  This is one of the
    1067             :    RANDOM_ORIGIN_* values. */
    1068             : static void
    1069        8377 : add_randomness (const void *buffer, size_t length, enum random_origins origin)
    1070             : {
    1071        8377 :   const unsigned char *p = buffer;
    1072        8377 :   size_t count = 0;
    1073             : 
    1074        8377 :   gcry_assert (pool_is_locked);
    1075             : 
    1076        8377 :   rndstats.addbytes += length;
    1077        8377 :   rndstats.naddbytes++;
    1078      325762 :   while (length-- )
    1079             :     {
    1080      309008 :       rndpool[pool_writepos++] ^= *p++;
    1081      309008 :       count++;
    1082      309008 :       if (pool_writepos >= POOLSIZE )
    1083             :         {
    1084             :           /* It is possible that we are invoked before the pool is
    1085             :              filled using an unreliable origin of entropy, for example
    1086             :              the fast random poll.  To avoid flagging the pool as
    1087             :              filled in this case, we track the initial filling state
    1088             :              separately.  See also the remarks about the seed file. */
    1089         509 :           if (origin >= RANDOM_ORIGIN_SLOWPOLL && !pool_filled)
    1090             :             {
    1091          85 :               pool_filled_counter += count;
    1092          85 :               count = 0;
    1093          85 :               if (pool_filled_counter >= POOLSIZE)
    1094          17 :                 pool_filled = 1;
    1095             :             }
    1096         509 :           pool_writepos = 0;
    1097         509 :           mix_pool(rndpool); rndstats.mixrnd++;
    1098         509 :           just_mixed = !length;
    1099             :         }
    1100             :     }
    1101        8377 : }
    1102             : 
    1103             : 
    1104             : 
    1105             : static void
    1106         425 : random_poll()
    1107             : {
    1108         425 :   rndstats.slowpolls++;
    1109         425 :   read_random_source (RANDOM_ORIGIN_SLOWPOLL, POOLSIZE/5, GCRY_STRONG_RANDOM);
    1110         425 : }
    1111             : 
    1112             : 
    1113             : /* Runtime determination of the slow entropy gathering module.  */
    1114             : static int (*
    1115          17 : getfnc_gather_random (void))(void (*)(const void*, size_t,
    1116             :                                       enum random_origins),
    1117             :                              enum random_origins, size_t, int)
    1118             : {
    1119             :   int (*fnc)(void (*)(const void*, size_t, enum random_origins),
    1120             :              enum random_origins, size_t, int);
    1121             : 
    1122             : #if USE_RNDLINUX
    1123          17 :   if ( !access (NAME_OF_DEV_RANDOM, R_OK)
    1124          17 :        && !access (NAME_OF_DEV_URANDOM, R_OK))
    1125             :     {
    1126          17 :       fnc = _gcry_rndlinux_gather_random;
    1127          17 :       return fnc;
    1128             :     }
    1129             : #endif
    1130             : 
    1131             : #if USE_RNDEGD
    1132             :   if ( _gcry_rndegd_connect_socket (1) != -1 )
    1133             :     {
    1134             :       fnc = _gcry_rndegd_gather_random;
    1135             :       return fnc;
    1136             :     }
    1137             : #endif
    1138             : 
    1139             : #if USE_RNDUNIX
    1140             :   fnc = _gcry_rndunix_gather_random;
    1141             :   return fnc;
    1142             : #endif
    1143             : 
    1144             : #if USE_RNDW32
    1145             :   fnc = _gcry_rndw32_gather_random;
    1146             :   return fnc;
    1147             : #endif
    1148             : 
    1149             : #if USE_RNDW32CE
    1150             :   fnc = _gcry_rndw32ce_gather_random;
    1151             :   return fnc;
    1152             : #endif
    1153             : 
    1154           0 :   log_fatal (_("no entropy gathering module detected\n"));
    1155             : 
    1156             :   return NULL; /*NOTREACHED*/
    1157             : }
    1158             : 
    1159             : /* Runtime determination of the fast entropy gathering function.
    1160             :    (Currently a compile time method is used.)  */
    1161             : static void (*
    1162          17 : getfnc_fast_random_poll (void))( void (*)(const void*, size_t,
    1163             :                                           enum random_origins),
    1164             :                                  enum random_origins)
    1165             : {
    1166             : #if USE_RNDW32
    1167             :   return _gcry_rndw32_gather_random_fast;
    1168             : #endif
    1169             : #if USE_RNDW32CE
    1170             :   return _gcry_rndw32ce_gather_random_fast;
    1171             : #endif
    1172          17 :   return NULL;
    1173             : }
    1174             : 
    1175             : 
    1176             : 
    1177             : static void
    1178        1450 : do_fast_random_poll (void)
    1179             : {
    1180        1450 :   gcry_assert (pool_is_locked);
    1181             : 
    1182        1450 :   rndstats.fastpolls++;
    1183             : 
    1184        1450 :   if (fast_gather_fnc)
    1185           0 :     fast_gather_fnc (add_randomness, RANDOM_ORIGIN_FASTPOLL);
    1186             : 
    1187             :   /* Continue with the generic functions. */
    1188             : #if HAVE_GETHRTIME
    1189             :   {
    1190             :     hrtime_t tv;
    1191             :     tv = gethrtime();
    1192             :     add_randomness( &tv, sizeof(tv), RANDOM_ORIGIN_FASTPOLL );
    1193             :   }
    1194             : #elif HAVE_GETTIMEOFDAY
    1195             :   {
    1196             :     struct timeval tv;
    1197        1450 :     if( gettimeofday( &tv, NULL ) )
    1198           0 :       BUG();
    1199        1450 :     add_randomness( &tv.tv_sec, sizeof(tv.tv_sec), RANDOM_ORIGIN_FASTPOLL );
    1200        1450 :     add_randomness( &tv.tv_usec, sizeof(tv.tv_usec), RANDOM_ORIGIN_FASTPOLL );
    1201             :   }
    1202             : #elif HAVE_CLOCK_GETTIME
    1203             :   {     struct timespec tv;
    1204             :   if( clock_gettime( CLOCK_REALTIME, &tv ) == -1 )
    1205             :     BUG();
    1206             :   add_randomness( &tv.tv_sec, sizeof(tv.tv_sec), RANDOM_ORIGIN_FASTPOLL );
    1207             :   add_randomness( &tv.tv_nsec, sizeof(tv.tv_nsec), RANDOM_ORIGIN_FASTPOLL );
    1208             :   }
    1209             : #else /* use times */
    1210             : # ifndef HAVE_DOSISH_SYSTEM
    1211             :   {     struct tms buf;
    1212             :   times( &buf );
    1213             :   add_randomness( &buf, sizeof buf, RANDOM_ORIGIN_FASTPOLL );
    1214             :   }
    1215             : # endif
    1216             : #endif
    1217             : 
    1218             : #ifdef HAVE_GETRUSAGE
    1219             : # ifdef RUSAGE_SELF
    1220             :   {
    1221             :     struct rusage buf;
    1222             :     /* QNX/Neutrino does return ENOSYS - so we just ignore it and add
    1223             :        whatever is in buf.  In a chroot environment it might not work
    1224             :        at all (i.e. because /proc/ is not accessible), so we better
    1225             :        ignore all error codes and hope for the best. */
    1226        1450 :     getrusage (RUSAGE_SELF, &buf );
    1227        1450 :     add_randomness( &buf, sizeof buf, RANDOM_ORIGIN_FASTPOLL );
    1228        1450 :     memset( &buf, 0, sizeof buf );
    1229             :   }
    1230             : # else /*!RUSAGE_SELF*/
    1231             : #  ifdef __GCC__
    1232             : #   warning There is no RUSAGE_SELF on this system
    1233             : #  endif
    1234             : # endif /*!RUSAGE_SELF*/
    1235             : #endif /*HAVE_GETRUSAGE*/
    1236             : 
    1237             :   /* Time and clock are availabe on all systems - so we better do it
    1238             :      just in case one of the above functions didn't work.  */
    1239             :   {
    1240        1450 :     time_t x = time(NULL);
    1241        1450 :     add_randomness( &x, sizeof(x), RANDOM_ORIGIN_FASTPOLL );
    1242             :   }
    1243             :   {
    1244        1450 :     clock_t x = clock();
    1245        1450 :     add_randomness( &x, sizeof(x), RANDOM_ORIGIN_FASTPOLL );
    1246             :   }
    1247             : 
    1248             :   /* If the system features a fast hardware RNG, read some bytes from
    1249             :      there.  */
    1250        1450 :   _gcry_rndhw_poll_fast (add_randomness, RANDOM_ORIGIN_FASTPOLL);
    1251        1450 : }
    1252             : 
    1253             : 
    1254             : /* The fast random pool function as called at some places in
    1255             :    libgcrypt.  This is merely a wrapper to make sure that this module
    1256             :    is initialized and to lock the pool.  Note, that this function is a
    1257             :    NOP unless a random function has been used or _gcry_initialize (1)
    1258             :    has been used.  We use this hack so that the internal use of this
    1259             :    function in cipher_open and md_open won't start filling up the
    1260             :    random pool, even if no random will be required by the process. */
    1261             : void
    1262       21178 : _gcry_rngcsprng_fast_poll (void)
    1263             : {
    1264       21178 :   initialize_basics ();
    1265             : 
    1266       21178 :   lock_pool ();
    1267       21178 :   if (rndpool)
    1268             :     {
    1269             :       /* Yes, we are fully initialized. */
    1270         748 :       do_fast_random_poll ();
    1271             :     }
    1272       21178 :   unlock_pool ();
    1273       21178 : }
    1274             : 
    1275             : 
    1276             : 
    1277             : static void
    1278         425 : read_random_source (enum random_origins orgin, size_t length, int level )
    1279             : {
    1280         425 :   if ( !slow_gather_fnc )
    1281           0 :     log_fatal ("Slow entropy gathering module not yet initialized\n");
    1282             : 
    1283         425 :   if ( slow_gather_fnc (add_randomness, orgin, length, level) < 0)
    1284           0 :     log_fatal ("No way to gather entropy for the RNG\n");
    1285         425 : }
    1286             : 
    1287             : 
    1288             : static int
    1289           0 : gather_faked (void (*add)(const void*, size_t, enum random_origins),
    1290             :               enum random_origins origin, size_t length, int level )
    1291             : {
    1292             :   static int initialized=0;
    1293             :   size_t n;
    1294             :   char *buffer, *p;
    1295             : 
    1296             :   (void)add;
    1297             :   (void)level;
    1298             : 
    1299           0 :   if ( !initialized )
    1300             :     {
    1301           0 :       log_info(_("WARNING: using insecure random number generator!!\n"));
    1302           0 :       initialized=1;
    1303             : #ifdef HAVE_RAND
    1304           0 :       srand( time(NULL)*getpid());
    1305             : #else
    1306             :       srandom( time(NULL)*getpid());
    1307             : #endif
    1308             :     }
    1309             : 
    1310           0 :   p = buffer = xmalloc( length );
    1311           0 :   n = length;
    1312             : #ifdef HAVE_RAND
    1313           0 :   while ( n-- )
    1314           0 :     *p++ = ((unsigned)(1 + (int) (256.0*rand()/(RAND_MAX+1.0)))-1);
    1315             : #else
    1316             :   while ( n-- )
    1317             :     *p++ = ((unsigned)(1 + (int) (256.0*random()/(RAND_MAX+1.0)))-1);
    1318             : #endif
    1319           0 :   add_randomness ( buffer, length, origin );
    1320           0 :   xfree (buffer);
    1321           0 :   return 0; /* okay */
    1322             : }

Generated by: LCOV version 1.11