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 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. */ 104static 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. */ 108static unsigned char *keypool; 109 110/* This is the offset into RNDPOOL where the next random bytes are to 111 be mixed in. */ 112static 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. */ 116static 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. */ 121static 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. */ 125static 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. */ 132static int did_initial_extra_seeding; 133 134/* This variable is used to estimated the amount of fresh entropy 135 available in RNDPOOL. */ 136static 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 other reasons. */ 141static 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. */ 146static char *seed_file_name; 147 148/* If a seed file has been registered and maybe updated on exit this 149 flag set. */ 150static int allow_seed_file_update; 151 152/* Option flag set at initialiation time to force allocation of the 153 pool in secure memory. */ 154static 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).*/ 160static 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 function 165 during initialization. If it is NULL, no such function is 166 available. */ 167static 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. */ 175static 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. */ 181static int faked_rng; 182 183/* This is the lock we use to protect all pool operations. */ 184static 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. */ 190static int pool_is_locked; 191 192/* This is the lock we use to protect the buffer used by the nonce 193 generation. */ 194static 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. */ 199static 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. */ 224static 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. */ 229static char *daemon_socket_name; 230 231#endif /*USE_RANDOM_DAEMON*/ 232 233 234 235/* --- Prototypes --- */ 236static void read_pool (byte *buffer, size_t length, int level ); 237static void add_randomness (const void *buffer, size_t length, 238 enum random_origins origin); 239static void random_poll (void); 240static void do_fast_random_poll (void); 241static int (*getfnc_gather_random (void))(void (*)(const void*, size_t, 242 enum random_origins), 243 enum random_origins, size_t, int); 244static void (*getfnc_fast_random_poll (void))(void (*)(const void*, size_t, 245 enum random_origins), 246 enum random_origins); 247static void read_random_source (enum random_origins origin, 248 size_t length, int level); 249static 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. */ 262static void 263initialize_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. */ 293static void 294lock_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. */ 305static void 306unlock_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. */ 318static void 319initialize(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. */ 363void 364_gcry_rngcsprng_initialize (int full) 365{ 366 if (!full) 367 initialize_basics (); 368 else 369 initialize (); 370} 371 372 373void 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 initialization of this module to place the random pools into secure 392 memory. */ 393void 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. */ 402void 403_gcry_rngcsprng_enable_quick_gen (void) 404{ 405 quick_test = 1; 406} 407 408 409void 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. */ 425int 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. */ 450int 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. */ 463gcry_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. */ 507void 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 */ 600static void 601mix_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 669void 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. */ 682static int 683lock_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 int backoff=0; 692 693 /* We take a lock on the entire file. */ 694 memset (&lck, 0, sizeof lck); 695 lck.l_type = for_write? F_WRLCK : F_RDLCK; 696 lck.l_whence = SEEK_SET; 697 698 while (fcntl (fd, F_SETLK, &lck) == -1) 699 { 700 if (errno != EAGAIN && errno != EACCES) 701 { 702 log_info (_("can't lock `%s': %s\n"), fname, strerror (errno)); 703 return -1; 704 } 705 706 if (backoff > 2) /* Show the first message after ~2.25 seconds. */ 707 log_info( _("waiting for lock on `%s'...\n"), fname); 708 709 tv.tv_sec = backoff; 710 tv.tv_usec = 250000; 711 select (0, NULL, NULL, NULL, &tv); 712 if (backoff < 10) 713 backoff++ ; 714 } 715#endif /*!LOCK_SEED_FILE*/ 716 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. */ 735static int 736read_seed_file (void) 737{ 738 int fd; 739 struct stat sb; 740 unsigned char buffer[POOLSIZE]; 741 int n; 742 743 gcry_assert (pool_is_locked); 744 745 if (!seed_file_name) 746 return 0; 747 748#ifdef HAVE_DOSISH_SYSTEM 749 fd = open( seed_file_name, O_RDONLY | O_BINARY ); 750#else 751 fd = open( seed_file_name, O_RDONLY ); 752#endif 753 if( fd == -1 && errno == ENOENT) 754 { 755 allow_seed_file_update = 1; 756 return 0; 757 } 758 759 if (fd == -1 ) 760 { 761 log_info(_("can't open `%s': %s\n"), seed_file_name, strerror(errno) ); 762 return 0; 763 } 764 if (lock_seed_file (fd, seed_file_name, 0)) 765 { 766 close (fd); 767 return 0; 768 } 769 if (fstat( fd, &sb ) ) 770 { 771 log_info(_("can't stat `%s': %s\n"), seed_file_name, strerror(errno) ); 772 close(fd); 773 return 0; 774 } 775 if (!S_ISREG(sb.st_mode) ) 776 { 777 log_info(_("`%s' is not a regular file - ignored\n"), seed_file_name ); 778 close(fd); 779 return 0; 780 } 781 if (!sb.st_size ) 782 { 783 log_info(_("note: random_seed file is empty\n") ); 784 close(fd); 785 allow_seed_file_update = 1; 786 return 0; 787 } 788 if (sb.st_size != POOLSIZE ) 789 { 790 log_info(_("warning: invalid size of random_seed file - not used\n") ); 791 close(fd); 792 return 0; 793 } 794 795 do 796 { 797 n = read( fd, buffer, POOLSIZE ); 798 } 799 while (n == -1 && errno == EINTR ); 800 801 if (n != POOLSIZE) 802 { 803 log_fatal(_("can't read `%s': %s\n"), seed_file_name,strerror(errno) ); 804 close(fd);/*NOTREACHED*/ 805 return 0; 806 } 807 808 close(fd); 809 810 add_randomness( buffer, POOLSIZE, RANDOM_ORIGIN_INIT ); 811 /* add some minor entropy to the pool now (this will also force a mixing) */ 812 { 813 pid_t x = getpid(); 814 add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT ); 815 } 816 { 817 time_t x = time(NULL); 818 add_randomness( &x, sizeof(x), RANDOM_ORIGIN_INIT ); 819 } 820 { 821 clock_t x = clock(); 822 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 read_random_source ( RANDOM_ORIGIN_INIT, 16, GCRY_WEAK_RANDOM ); 831 832 allow_seed_file_update = 1; 833 return 1; 834} 835 836 837void 838_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 initialize_basics (); 848 lock_pool (); 849 850 if ( !seed_file_name || !rndpool || !pool_filled ) 851 { 852 unlock_pool (); 853 return; 854 } 855 if ( !allow_seed_file_update ) 856 { 857 unlock_pool (); 858 log_info(_("note: random_seed file not updated\n")); 859 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 for (i=0,dp=(unsigned long*)keypool, sp=(unsigned long*)rndpool; 868 i < POOLWORDS; i++, dp++, sp++ ) 869 { 870 *dp = *sp + ADD_VALUE; 871 } 872 mix_pool(rndpool); rndstats.mixrnd++; 873 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 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 if (fd == -1 ) 887 log_info (_("can't create `%s': %s\n"), seed_file_name, strerror(errno) ); 888 else if (lock_seed_file (fd, seed_file_name, 1)) 889 { 890 close (fd); 891 } 892#if LOCK_SEED_FILE 893 else if (ftruncate (fd, 0)) 894 { 895 log_info(_("can't write `%s': %s\n"), seed_file_name, strerror(errno)); 896 close (fd); 897 } 898#endif /*LOCK_SEED_FILE*/ 899 else 900 { 901 do 902 { 903 i = write (fd, keypool, POOLSIZE ); 904 } 905 while (i == -1 && errno == EINTR); 906 if (i != POOLSIZE) 907 log_info (_("can't write `%s': %s\n"),seed_file_name, strerror(errno)); 908 if (close(fd)) 909 log_info (_("can't close `%s': %s\n"),seed_file_name, strerror(errno)); 910 } 911 912 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. */ 921static void 922read_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 gcry_assert (pool_is_locked); 935 936 retry: 937 /* Get our own pid, so that we can detect a fork. */ 938 my_pid2 = getpid (); 939 if (my_pid == (pid_t)(-1)) 940 my_pid = my_pid2; 941 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 my_pid = my_pid2; 948 x = my_pid; 949 add_randomness (&x, sizeof(x), RANDOM_ORIGIN_INIT); 950 just_mixed = 0; /* Make sure it will get mixed. */ 951 } 952 953 gcry_assert (pool_is_locked); 954 955 /* Our code does not allow to extract more than POOLSIZE. Better 956 check it here. */ 957 if (length > POOLSIZE) 958 { 959 log_bug("too many random bits requested\n"); 960 } 961 962 if (!pool_filled) 963 { 964 if (read_seed_file() ) 965 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 if (level == GCRY_VERY_STRONG_RANDOM && !did_initial_extra_seeding) 971 { 972 size_t needed; 973 974 pool_balance = 0; 975 needed = length - pool_balance; 976 if (needed < POOLSIZE/2) 977 needed = POOLSIZE/2; 978 else if( needed > POOLSIZE ) 979 BUG (); 980 read_random_source (RANDOM_ORIGIN_EXTRAPOLL, needed, 981 GCRY_VERY_STRONG_RANDOM); 982 pool_balance += needed; 983 did_initial_extra_seeding = 1; 984 } 985 986 /* For level 2 make sure that there is enough random in the pool. */ 987 if (level == GCRY_VERY_STRONG_RANDOM && pool_balance < length) 988 { 989 size_t needed; 990 991 if (pool_balance < 0) 992 pool_balance = 0; 993 needed = length - pool_balance; 994 if (needed > POOLSIZE) 995 BUG (); 996 read_random_source (RANDOM_ORIGIN_EXTRAPOLL, needed, 997 GCRY_VERY_STRONG_RANDOM); 998 pool_balance += needed; 999 } 1000 1001 /* Make sure the pool is filled. */ 1002 while (!pool_filled) 1003 random_poll(); 1004 1005 /* Always do a fast random poll (we have to use the unlocked version). */ 1006 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 pid_t apid = my_pid; 1012 add_randomness (&apid, sizeof (apid), RANDOM_ORIGIN_INIT); 1013 } 1014 1015 /* Mix the pool (if add_randomness() didn't it). */ 1016 if (!just_mixed) 1017 { 1018 mix_pool(rndpool); 1019 rndstats.mixrnd++; 1020 } 1021 1022 /* Create a new pool. */ 1023 for(i=0,dp=(unsigned long*)keypool, sp=(unsigned long*)rndpool; 1024 i < POOLWORDS; i++, dp++, sp++ ) 1025 *dp = *sp + ADD_VALUE; 1026 1027 /* Mix both pools. */ 1028 mix_pool(rndpool); rndstats.mixrnd++; 1029 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 while (length--) 1034 { 1035 *buffer++ = keypool[pool_readpos++]; 1036 if (pool_readpos >= POOLSIZE) 1037 pool_readpos = 0; 1038 pool_balance--; 1039 } 1040 1041 if (pool_balance < 0) 1042 pool_balance = 0; 1043 1044 /* Clear the keypool. */ 1045 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 if ( getpid () != my_pid2 ) 1054 { 1055 pid_t x = getpid(); 1056 add_randomness (&x, sizeof(x), RANDOM_ORIGIN_INIT); 1057 just_mixed = 0; /* Make sure it will get mixed. */ 1058 my_pid = x; /* Also update the static pid. */ 1059 goto retry; 1060 } 1061} 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. */ 1068static void 1069add_randomness (const void *buffer, size_t length, enum random_origins origin) 1070{ 1071 const unsigned char *p = buffer; 1072 size_t count = 0; 1073 1074 gcry_assert (pool_is_locked); 1075 1076 rndstats.addbytes += length; 1077 rndstats.naddbytes++; 1078 while (length-- ) 1079 { 1080 rndpool[pool_writepos++] ^= *p++; 1081 count++; 1082 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 if (origin >= RANDOM_ORIGIN_SLOWPOLL && !pool_filled) 1090 { 1091 pool_filled_counter += count; 1092 count = 0; 1093 if (pool_filled_counter >= POOLSIZE) 1094 pool_filled = 1; 1095 } 1096 pool_writepos = 0; 1097 mix_pool(rndpool); rndstats.mixrnd++; 1098 just_mixed = !length; 1099 } 1100 } 1101} 1102 1103 1104 1105static void 1106random_poll() 1107{ 1108 rndstats.slowpolls++; 1109 read_random_source (RANDOM_ORIGIN_SLOWPOLL, POOLSIZE/5, GCRY_STRONG_RANDOM); 1110} 1111 1112 1113/* Runtime determination of the slow entropy gathering module. */ 1114static int (* 1115getfnc_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 if ( !access (NAME_OF_DEV_RANDOM, R_OK) 1124 && !access (NAME_OF_DEV_URANDOM, R_OK)) 1125 { 1126 fnc = _gcry_rndlinux_gather_random; 1127 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 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.) */ 1161static void (* 1162getfnc_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 return NULL; 1173} 1174 1175 1176 1177static void 1178do_fast_random_poll (void) 1179{ 1180 gcry_assert (pool_is_locked); 1181 1182 rndstats.fastpolls++; 1183 1184 if (fast_gather_fnc) 1185 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 if( gettimeofday( &tv, NULL ) ) 1198 BUG(); 1199 add_randomness( &tv.tv_sec, sizeof(tv.tv_sec), RANDOM_ORIGIN_FASTPOLL ); 1200 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 getrusage (RUSAGE_SELF, &buf ); 1227 add_randomness( &buf, sizeof buf, RANDOM_ORIGIN_FASTPOLL ); 1228 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 time_t x = time(NULL); 1241 add_randomness( &x, sizeof(x), RANDOM_ORIGIN_FASTPOLL ); 1242 } 1243 { 1244 clock_t x = clock(); 1245 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 _gcry_rndhw_poll_fast (add_randomness, RANDOM_ORIGIN_FASTPOLL); 1251} 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. */ 1261void 1262_gcry_rngcsprng_fast_poll (void) 1263{ 1264 initialize_basics (); 1265 1266 lock_pool (); 1267 if (rndpool) 1268 { 1269 /* Yes, we are fully initialized. */ 1270 do_fast_random_poll (); 1271 } 1272 unlock_pool (); 1273} 1274 1275 1276 1277static void 1278read_random_source (enum random_origins orgin, size_t length, int level ) 1279{ 1280 if ( !slow_gather_fnc ) 1281 log_fatal ("Slow entropy gathering module not yet initialized\n"); 1282 1283 if ( slow_gather_fnc (add_randomness, orgin, length, level) < 0) 1284 log_fatal ("No way to gather entropy for the RNG\n"); 1285} 1286 1287 1288static int 1289gather_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 if ( !initialized ) 1300 { 1301 log_info(_("WARNING: using insecure random number generator!!\n")); 1302 initialized=1; 1303#ifdef HAVE_RAND 1304 srand( time(NULL)*getpid()); 1305#else 1306 srandom( time(NULL)*getpid()); 1307#endif 1308 } 1309 1310 p = buffer = gcry_xmalloc( length ); 1311 n = length; 1312#ifdef HAVE_RAND 1313 while ( n-- ) 1314 *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 add_randomness ( buffer, length, origin ); 1320 gcry_free (buffer); 1321 return 0; /* okay */ 1322} 1323 1324 1325/* Create an unpredicable nonce of LENGTH bytes in BUFFER. */ 1326void 1327_gcry_rngcsprng_create_nonce (void *buffer, size_t length) 1328{ 1329 static unsigned char nonce_buffer[20+8]; 1330 static int nonce_buffer_initialized = 0; 1331 static volatile pid_t my_pid; /* The volatile is there to make sure the 1332 compiler does not optimize the code away 1333 in case the getpid function is badly 1334 attributed. */ 1335 volatile pid_t apid; 1336 unsigned char *p; 1337 size_t n; 1338 int err; 1339 1340 /* Make sure we are initialized. */ 1341 initialize (); 1342 1343#ifdef USE_RANDOM_DAEMON 1344 if (allow_daemon 1345 && !_gcry_daemon_create_nonce (daemon_socket_name, buffer, length)) 1346 return; /* The daemon succeeded. */ 1347 allow_daemon = 0; /* Daemon failed - switch off. */ 1348#endif /*USE_RANDOM_DAEMON*/ 1349 1350 /* Acquire the nonce buffer lock. */ 1351 err = ath_mutex_lock (&nonce_buffer_lock); 1352 if (err) 1353 log_fatal ("failed to acquire the nonce buffer lock: %s\n", 1354 strerror (err)); 1355 1356 apid = getpid (); 1357 /* The first time initialize our buffer. */ 1358 if (!nonce_buffer_initialized) 1359 { 1360 time_t atime = time (NULL); 1361 pid_t xpid = apid; 1362 1363 my_pid = apid; 1364 1365 if ((sizeof apid + sizeof atime) > sizeof nonce_buffer) 1366 BUG (); 1367 1368 /* Initialize the first 20 bytes with a reasonable value so that 1369 a failure of gcry_randomize won't affect us too much. Don't 1370 care about the uninitialized remaining bytes. */ 1371 p = nonce_buffer; 1372 memcpy (p, &xpid, sizeof xpid); 1373 p += sizeof xpid; 1374 memcpy (p, &atime, sizeof atime); 1375 1376 /* Initialize the never changing private part of 64 bits. */ 1377 gcry_randomize (nonce_buffer+20, 8, GCRY_WEAK_RANDOM); 1378 1379 nonce_buffer_initialized = 1; 1380 } 1381 else if ( my_pid != apid ) 1382 { 1383 /* We forked. Need to reseed the buffer - doing this for the 1384 private part should be sufficient. */ 1385 gcry_randomize (nonce_buffer+20, 8, GCRY_WEAK_RANDOM); 1386 /* Update the pid so that we won't run into here again and 1387 again. */ 1388 my_pid = apid; 1389 } 1390 1391 /* Create the nonce by hashing the entire buffer, returning the hash 1392 and updating the first 20 bytes of the buffer with this hash. */ 1393 for (p = buffer; length > 0; length -= n, p += n) 1394 { 1395 _gcry_sha1_hash_buffer (nonce_buffer, 1396 nonce_buffer, sizeof nonce_buffer); 1397 n = length > 20? 20 : length; 1398 memcpy (p, nonce_buffer, n); 1399 } 1400 1401 1402 /* Release the nonce buffer lock. */ 1403 err = ath_mutex_unlock (&nonce_buffer_lock); 1404 if (err) 1405 log_fatal ("failed to release the nonce buffer lock: %s\n", 1406 strerror (err)); 1407 1408} 1409