1/* random-fips.c - FIPS style random number generator 2 * Copyright (C) 2008 Free Software Foundation, Inc. 3 * 4 * This file is part of Libgcrypt. 5 * 6 * Libgcrypt is free software; you can redistribute it and/or modify 7 * it under the terms of the GNU Lesser General Public License as 8 * published by the Free Software Foundation; either version 2.1 of 9 * the License, or (at your option) any later version. 10 * 11 * Libgcrypt is distributed in the hope that it will be useful, 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 * GNU Lesser General Public License for more details. 15 * 16 * You should have received a copy of the GNU Lesser General Public 17 * License along with this program; if not, see <http://www.gnu.org/licenses/>. 18 */ 19 20/* 21 The core of this deterministic random number generator is 22 implemented according to the document "NIST-Recommended Random 23 Number Generator Based on ANSI X9.31 Appendix A.2.4 Using the 3-Key 24 Triple DES and AES Algorithms" (2005-01-31). This implementation 25 uses the AES variant. 26 27 There are 3 random context which map to the different levels of 28 random quality: 29 30 Generator Seed and Key Kernel entropy (init/reseed) 31 ------------------------------------------------------------ 32 GCRY_VERY_STRONG_RANDOM /dev/random 256/128 bits 33 GCRY_STRONG_RANDOM /dev/random 256/128 bits 34 gcry_create_nonce GCRY_STRONG_RANDOM n/a 35 36 All random generators return their data in 128 bit blocks. If the 37 caller requested less bits, the extra bits are not used. The key 38 for each generator is only set once at the first time a generator 39 is used. The seed value is set with the key and again after 1000 40 (SEED_TTL) output blocks; the re-seeding is disabled in test mode. 41 42 The GCRY_VERY_STRONG_RANDOM and GCRY_STRONG_RANDOM generators are 43 keyed and seeded from the /dev/random device. Thus these 44 generators may block until the kernel has collected enough entropy. 45 46 The gcry_create_nonce generator is keyed and seeded from the 47 GCRY_STRONG_RANDOM generator. It may also block if the 48 GCRY_STRONG_RANDOM generator has not yet been used before and thus 49 gets initialized on the first use by gcry_create_nonce. This 50 special treatment is justified by the weaker requirements for a 51 nonce generator and to save precious kernel entropy for use by the 52 real random generators. 53 54 */ 55 56#include <config.h> 57#include <stdio.h> 58#include <stdlib.h> 59#include <errno.h> 60#include <sys/types.h> 61#include <unistd.h> 62#ifdef HAVE_GETTIMEOFDAY 63#include <sys/time.h> 64#endif 65 66#include "g10lib.h" 67#include "random.h" 68#include "rand-internal.h" 69#include "ath.h" 70 71/* This is the lock we use to serialize access to this RNG. The extra 72 integer variable is only used to check the locking state; that is, 73 it is not meant to be thread-safe but merely as a failsafe feature 74 to assert proper locking. */ 75static ath_mutex_t fips_rng_lock = ATH_MUTEX_INITIALIZER; 76static int fips_rng_is_locked; 77 78 79/* The required size for the temporary buffer of the x931_aes_driver 80 function and the buffer itself which will be allocated in secure 81 memory. This needs to be global variable for proper initialization 82 and to allow shutting down the RNG without leaking memory. May 83 only be used while holding the FIPS_RNG_LOCK. 84 85 This variable is also used to avoid duplicate initialization. */ 86#define TEMPVALUE_FOR_X931_AES_DRIVER_SIZE 48 87static unsigned char *tempvalue_for_x931_aes_driver; 88 89 90/* After having retrieved this number of blocks from the RNG, we want 91 to do a reseeding. */ 92#define SEED_TTL 1000 93 94 95/* The length of the key we use: 16 bytes (128 bit) for AES128. */ 96#define X931_AES_KEYLEN 16 97/* A global buffer used to communicate between the x931_generate_key 98 and x931_generate_seed functions and the entropy_collect_cb 99 function. It may only be used by these functions. */ 100static unsigned char *entropy_collect_buffer; /* Buffer. */ 101static size_t entropy_collect_buffer_len; /* Used length. */ 102static size_t entropy_collect_buffer_size; /* Allocated length. */ 103 104 105/* This random context type is used to track properties of one random 106 generator. Thee context are usually allocated in secure memory so 107 that the seed value is well protected. There are a couble of guard 108 fields to help detecting applications accidently overwriting parts 109 of the memory. */ 110struct rng_context 111{ 112 unsigned char guard_0[1]; 113 114 /* The handle of the cipher used by the RNG. If this one is not 115 NULL a cipher handle along with a random key has been 116 established. */ 117 gcry_cipher_hd_t cipher_hd; 118 119 /* If this flag is true, the SEED_V buffer below carries a valid 120 seed. */ 121 int is_seeded:1; 122 123 /* The very first block generated is used to compare the result 124 against the last result. This flag indicates that such a block 125 is available. */ 126 int compare_value_valid:1; 127 128 /* A counter used to trigger re-seeding. */ 129 unsigned int use_counter; 130 131 unsigned char guard_1[1]; 132 133 /* The buffer containing the seed value V. */ 134 unsigned char seed_V[16]; 135 136 unsigned char guard_2[1]; 137 138 /* The last result from the x931_aes function. Only valid if 139 compare_value_valid is set. */ 140 unsigned char compare_value[16]; 141 142 unsigned char guard_3[1]; 143 144 /* The external test may want to suppress the duplicate bock check. 145 This is done if the this flag is set. */ 146 unsigned char test_no_dup_check; 147 /* To implement a KAT we need to provide a know DT value. To 148 accomplish this the x931_get_dt function checks whether this 149 field is not NULL and then uses the 16 bytes at this address for 150 the DT value. However the last 4 bytes are replaced by the 151 value of field TEST_DT_COUNTER which will be incremented after 152 each invocation of x931_get_dt. We use a pointer and not a buffer 153 because there is no need to put this value into secure memory. */ 154 const unsigned char *test_dt_ptr; 155 u32 test_dt_counter; 156 157 /* We need to keep track of the process which did the initialization 158 so that we can detect a fork. The volatile modifier is required 159 so that the compiler does not optimize it away in case the getpid 160 function is badly attributed. */ 161 pid_t key_init_pid; 162 pid_t seed_init_pid; 163}; 164typedef struct rng_context *rng_context_t; 165 166 167/* The random context used for the nonce generator. May only be used 168 while holding the FIPS_RNG_LOCK. */ 169static rng_context_t nonce_context; 170/* The random context used for the standard random generator. May 171 only be used while holding the FIPS_RNG_LOCK. */ 172static rng_context_t std_rng_context; 173/* The random context used for the very strong random generator. May 174 only be used while holding the FIPS_RNG_LOCK. */ 175static rng_context_t strong_rng_context; 176 177 178/* --- Local prototypes --- */ 179static void x931_reseed (rng_context_t rng_ctx); 180static void get_random (void *buffer, size_t length, rng_context_t rng_ctx); 181 182 183 184 185/* --- Functions --- */ 186 187/* Basic initialization is required to initialize mutexes and 188 do a few checks on the implementation. */ 189static void 190basic_initialization (void) 191{ 192 static int initialized; 193 int my_errno; 194 195 if (!initialized) 196 return; 197 initialized = 1; 198 199 my_errno = ath_mutex_init (&fips_rng_lock); 200 if (my_errno) 201 log_fatal ("failed to create the RNG lock: %s\n", strerror (my_errno)); 202 fips_rng_is_locked = 0; 203 204 /* Make sure that we are still using the values we have 205 traditionally used for the random levels. */ 206 gcry_assert (GCRY_WEAK_RANDOM == 0 207 && GCRY_STRONG_RANDOM == 1 208 && GCRY_VERY_STRONG_RANDOM == 2); 209 210} 211 212 213/* Acquire the fips_rng_lock. */ 214static void 215lock_rng (void) 216{ 217 int my_errno; 218 219 my_errno = ath_mutex_lock (&fips_rng_lock); 220 if (my_errno) 221 log_fatal ("failed to acquire the RNG lock: %s\n", strerror (my_errno)); 222 fips_rng_is_locked = 1; 223} 224 225 226/* Release the fips_rng_lock. */ 227static void 228unlock_rng (void) 229{ 230 int my_errno; 231 232 fips_rng_is_locked = 0; 233 my_errno = ath_mutex_unlock (&fips_rng_lock); 234 if (my_errno) 235 log_fatal ("failed to release the RNG lock: %s\n", strerror (my_errno)); 236} 237 238static void 239setup_guards (rng_context_t rng_ctx) 240{ 241 /* Set the guards to some arbitrary values. */ 242 rng_ctx->guard_0[0] = 17; 243 rng_ctx->guard_1[0] = 42; 244 rng_ctx->guard_2[0] = 137; 245 rng_ctx->guard_3[0] = 252; 246} 247 248static void 249check_guards (rng_context_t rng_ctx) 250{ 251 if ( rng_ctx->guard_0[0] != 17 252 || rng_ctx->guard_1[0] != 42 253 || rng_ctx->guard_2[0] != 137 254 || rng_ctx->guard_3[0] != 252 ) 255 log_fatal ("memory corruption detected in RNG context %p\n", rng_ctx); 256} 257 258 259/* Get the DT vector for use with the core PRNG function. Buffer 260 needs to be provided by the caller with a size of at least LENGTH 261 bytes. RNG_CTX needs to be passed to allow for a KAT. The 16 byte 262 timestamp we construct is made up the real time and three counters: 263 264 Buffer: 00112233445566778899AABBCCDDEEFF 265 !--+---!!-+-!!+!!--+---!!--+---! 266 seconds ---------/ | | | | 267 microseconds -----------/ | | | 268 counter2 -------------------/ | | 269 counter1 ------------------------/ | 270 counter0 --------------------------------/ 271 272 Counter 2 is just 12 bits wide and used to track fractions of 273 milliseconds whereas counters 1 and 0 are combined to a free 274 running 64 bit counter. */ 275static void 276x931_get_dt (unsigned char *buffer, size_t length, rng_context_t rng_ctx) 277{ 278 gcry_assert (length == 16); /* This length is required for use with AES. */ 279 gcry_assert (fips_rng_is_locked); 280 281 /* If the random context indicates that a test DT should be used, 282 take the DT value from the context. For safety reasons we do 283 this only if the context is not one of the regular contexts. */ 284 if (rng_ctx->test_dt_ptr 285 && rng_ctx != nonce_context 286 && rng_ctx != std_rng_context 287 && rng_ctx != strong_rng_context) 288 { 289 memcpy (buffer, rng_ctx->test_dt_ptr, 16); 290 buffer[12] = (rng_ctx->test_dt_counter >> 24); 291 buffer[13] = (rng_ctx->test_dt_counter >> 16); 292 buffer[14] = (rng_ctx->test_dt_counter >> 8); 293 buffer[15] = rng_ctx->test_dt_counter; 294 rng_ctx->test_dt_counter++; 295 return; 296 } 297 298 299#if HAVE_GETTIMEOFDAY 300 { 301 static u32 last_sec, last_usec; 302 static u32 counter1, counter0; 303 static u16 counter2; 304 305 unsigned int usec; 306 struct timeval tv; 307 308 if (!last_sec) 309 { 310 /* This is the very first time we are called: Set the counters 311 to an not so easy predictable value to avoid always 312 starting at 0. Not really needed but it doesn't harm. */ 313 counter1 = (u32)getpid (); 314#ifndef HAVE_W32_SYSTEM 315 counter0 = (u32)getppid (); 316#endif 317 } 318 319 320 if (gettimeofday (&tv, NULL)) 321 log_fatal ("gettimeofday() failed: %s\n", strerror (errno)); 322 323 /* The microseconds part is always less than 1 millon (0x0f4240). 324 Thus we don't care about the MSB and in addition shift it to 325 the left by 4 bits. */ 326 usec = tv.tv_usec; 327 usec <<= 4; 328 /* If we got the same time as by the last invocation, bump up 329 counter2 and save the time for the next invocation. */ 330 if (tv.tv_sec == last_sec && usec == last_usec) 331 { 332 counter2++; 333 counter2 &= 0x0fff; 334 } 335 else 336 { 337 counter2 = 0; 338 last_sec = tv.tv_sec; 339 last_usec = usec; 340 } 341 /* Fill the buffer with the timestamp. */ 342 buffer[0] = ((tv.tv_sec >> 24) & 0xff); 343 buffer[1] = ((tv.tv_sec >> 16) & 0xff); 344 buffer[2] = ((tv.tv_sec >> 8) & 0xff); 345 buffer[3] = (tv.tv_sec & 0xff); 346 buffer[4] = ((usec >> 16) & 0xff); 347 buffer[5] = ((usec >> 8) & 0xff); 348 buffer[6] = ((usec & 0xf0) | ((counter2 >> 8) & 0x0f)); 349 buffer[7] = (counter2 & 0xff); 350 /* Add the free running counter. */ 351 buffer[8] = ((counter1 >> 24) & 0xff); 352 buffer[9] = ((counter1 >> 16) & 0xff); 353 buffer[10] = ((counter1 >> 8) & 0xff); 354 buffer[11] = ((counter1) & 0xff); 355 buffer[12] = ((counter0 >> 24) & 0xff); 356 buffer[13] = ((counter0 >> 16) & 0xff); 357 buffer[14] = ((counter0 >> 8) & 0xff); 358 buffer[15] = ((counter0) & 0xff); 359 /* Bump up that counter. */ 360 if (!++counter0) 361 ++counter1; 362 } 363#else 364 log_fatal ("gettimeofday() not available on this system\n"); 365#endif 366 367 /* log_printhex ("x931_get_dt: ", buffer, 16); */ 368} 369 370 371/* XOR the buffers A and B which are each of LENGTH bytes and store 372 the result at R. R needs to be provided by the caller with a size 373 of at least LENGTH bytes. */ 374static void 375xor_buffer (unsigned char *r, 376 const unsigned char *a, const unsigned char *b, size_t length) 377{ 378 for ( ; length; length--, a++, b++, r++) 379 *r = (*a ^ *b); 380} 381 382 383/* Encrypt LENGTH bytes of INPUT to OUTPUT using KEY. LENGTH 384 needs to be 16. */ 385static void 386encrypt_aes (gcry_cipher_hd_t key, 387 unsigned char *output, const unsigned char *input, size_t length) 388{ 389 gpg_error_t err; 390 391 gcry_assert (length == 16); 392 393 err = gcry_cipher_encrypt (key, output, length, input, length); 394 if (err) 395 log_fatal ("AES encryption in RNG failed: %s\n", gcry_strerror (err)); 396} 397 398 399/* The core ANSI X9.31, Appendix A.2.4 function using AES. The caller 400 needs to pass a 16 byte buffer for the result, the 16 byte 401 datetime_DT value and the 16 byte seed value V. The caller also 402 needs to pass an appropriate KEY and make sure to pass a valid 403 seed_V. The caller also needs to provide two 16 bytes buffer for 404 intermediate results, they may be reused by the caller later. 405 406 On return the result is stored at RESULT_R and the SEED_V is 407 updated. May only be used while holding the lock. */ 408static void 409x931_aes (unsigned char result_R[16], 410 unsigned char datetime_DT[16], unsigned char seed_V[16], 411 gcry_cipher_hd_t key, 412 unsigned char intermediate_I[16], unsigned char temp_xor[16]) 413{ 414 /* Let ede*X(Y) represent the AES encryption of Y under the key *X. 415 416 Let V be a 128-bit seed value which is also kept secret, and XOR 417 be the exclusive-or operator. Let DT be a date/time vector which 418 is updated on each iteration. I is a intermediate value. 419 420 I = ede*K(DT) */ 421 encrypt_aes (key, intermediate_I, datetime_DT, 16); 422 423 /* R = ede*K(I XOR V) */ 424 xor_buffer (temp_xor, intermediate_I, seed_V, 16); 425 encrypt_aes (key, result_R, temp_xor, 16); 426 427 /* V = ede*K(R XOR I). */ 428 xor_buffer (temp_xor, result_R, intermediate_I, 16); 429 encrypt_aes (key, seed_V, temp_xor, 16); 430 431 /* Zero out temporary values. */ 432 wipememory (intermediate_I, 16); 433 wipememory (temp_xor, 16); 434} 435 436 437/* The high level driver to x931_aes. This one does the required 438 tests and calls the core function until the entire buffer has been 439 filled. OUTPUT is a caller provided buffer of LENGTH bytes to 440 receive the random, RNG_CTX is the context of the RNG. The context 441 must be properly initialized. Returns 0 on success. */ 442static int 443x931_aes_driver (unsigned char *output, size_t length, rng_context_t rng_ctx) 444{ 445 unsigned char datetime_DT[16]; 446 unsigned char *intermediate_I, *temp_buffer, *result_buffer; 447 size_t nbytes; 448 449 gcry_assert (fips_rng_is_locked); 450 gcry_assert (rng_ctx->cipher_hd); 451 gcry_assert (rng_ctx->is_seeded); 452 453 gcry_assert (tempvalue_for_x931_aes_driver); 454 gcry_assert (TEMPVALUE_FOR_X931_AES_DRIVER_SIZE == 48); 455 intermediate_I = tempvalue_for_x931_aes_driver; 456 temp_buffer = tempvalue_for_x931_aes_driver + 16; 457 result_buffer = tempvalue_for_x931_aes_driver + 32; 458 459 while (length) 460 { 461 /* Unless we are running with a test context, we require a new 462 seed after some time. */ 463 if (!rng_ctx->test_dt_ptr && rng_ctx->use_counter > SEED_TTL) 464 { 465 x931_reseed (rng_ctx); 466 rng_ctx->use_counter = 0; 467 } 468 469 /* Due to the design of the RNG, we always receive 16 bytes (128 470 bit) of random even if we require less. The extra bytes 471 returned are not used. Intheory we could save them for the 472 next invocation, but that would make the control flow harder 473 to read. */ 474 nbytes = length < 16? length : 16; 475 476 x931_get_dt (datetime_DT, 16, rng_ctx); 477 x931_aes (result_buffer, 478 datetime_DT, rng_ctx->seed_V, rng_ctx->cipher_hd, 479 intermediate_I, temp_buffer); 480 rng_ctx->use_counter++; 481 482 if (rng_ctx->test_no_dup_check 483 && rng_ctx->test_dt_ptr 484 && rng_ctx != nonce_context 485 && rng_ctx != std_rng_context 486 && rng_ctx != strong_rng_context) 487 { 488 /* This is a test context which does not want the duplicate 489 block check. */ 490 } 491 else 492 { 493 /* Do a basic check on the output to avoid a stuck generator. */ 494 if (!rng_ctx->compare_value_valid) 495 { 496 /* First time used, only save the result. */ 497 memcpy (rng_ctx->compare_value, result_buffer, 16); 498 rng_ctx->compare_value_valid = 1; 499 continue; 500 } 501 if (!memcmp (rng_ctx->compare_value, result_buffer, 16)) 502 { 503 /* Ooops, we received the same 128 bit block - that should 504 in theory never happen. The FIPS requirement says that 505 we need to put ourself into the error state in such 506 case. */ 507 fips_signal_error ("duplicate 128 bit block returned by RNG"); 508 return -1; 509 } 510 memcpy (rng_ctx->compare_value, result_buffer, 16); 511 } 512 513 /* Append to outbut. */ 514 memcpy (output, result_buffer, nbytes); 515 wipememory (result_buffer, 16); 516 output += nbytes; 517 length -= nbytes; 518 } 519 520 return 0; 521} 522 523 524/* Callback for x931_generate_key. Note that this callback uses the 525 global ENTROPY_COLLECT_BUFFER which has been setup by get_entropy. 526 ORIGIN is not used but required due to the design of entropy 527 gathering module. */ 528static void 529entropy_collect_cb (const void *buffer, size_t length, 530 enum random_origins origin) 531{ 532 const unsigned char *p = buffer; 533 534 (void)origin; 535 536 gcry_assert (fips_rng_is_locked); 537 gcry_assert (entropy_collect_buffer); 538 539 /* Note that we need to protect against gatherers returning more 540 than the requested bytes (e.g. rndw32). */ 541 while (length-- && entropy_collect_buffer_len < entropy_collect_buffer_size) 542 { 543 entropy_collect_buffer[entropy_collect_buffer_len++] ^= *p++; 544 } 545} 546 547 548/* Get NBYTES of entropy from the kernel device. The callers needs to 549 free the returned buffer. The function either succeeds or 550 terminates the process in case of a fatal error. */ 551static void * 552get_entropy (size_t nbytes) 553{ 554 void *result; 555 int rc; 556 557 gcry_assert (!entropy_collect_buffer); 558 entropy_collect_buffer = gcry_xmalloc_secure (nbytes); 559 entropy_collect_buffer_size = nbytes; 560 entropy_collect_buffer_len = 0; 561 562#if USE_RNDLINUX 563 rc = _gcry_rndlinux_gather_random (entropy_collect_cb, 0, 564 X931_AES_KEYLEN, 565 GCRY_VERY_STRONG_RANDOM); 566#elif USE_RNDW32 567 do 568 { 569 rc = _gcry_rndw32_gather_random (entropy_collect_cb, 0, 570 X931_AES_KEYLEN, 571 GCRY_VERY_STRONG_RANDOM); 572 } 573 while (rc >= 0 && entropy_collect_buffer_len < entropy_collect_buffer_size); 574#else 575 rc = -1; 576#endif 577 578 if (rc < 0 || entropy_collect_buffer_len != entropy_collect_buffer_size) 579 { 580 gcry_free (entropy_collect_buffer); 581 entropy_collect_buffer = NULL; 582 log_fatal ("error getting entropy data\n"); 583 } 584 result = entropy_collect_buffer; 585 entropy_collect_buffer = NULL; 586 return result; 587} 588 589 590/* Generate a key for use with x931_aes. The function returns a 591 handle to the cipher context readily prepared for ECB encryption. 592 If FOR_NONCE is true, the key is retrieved by readong random from 593 the standard generator. On error NULL is returned. */ 594static gcry_cipher_hd_t 595x931_generate_key (int for_nonce) 596{ 597 gcry_cipher_hd_t hd; 598 gpg_error_t err; 599 void *buffer; 600 601 gcry_assert (fips_rng_is_locked); 602 603 /* Allocate a cipher context. */ 604 err = gcry_cipher_open (&hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB, 605 GCRY_CIPHER_SECURE); 606 if (err) 607 { 608 log_error ("error creating cipher context for RNG: %s\n", 609 gcry_strerror (err)); 610 return NULL; 611 } 612 613 /* Get a key from the standard RNG or from the entropy source. */ 614 if (for_nonce) 615 { 616 buffer = gcry_xmalloc (X931_AES_KEYLEN); 617 get_random (buffer, X931_AES_KEYLEN, std_rng_context); 618 } 619 else 620 { 621 buffer = get_entropy (X931_AES_KEYLEN); 622 } 623 624 /* Set the key and delete the buffer because the key is now part of 625 the cipher context. */ 626 err = gcry_cipher_setkey (hd, buffer, X931_AES_KEYLEN); 627 wipememory (buffer, X931_AES_KEYLEN); 628 gcry_free (buffer); 629 if (err) 630 { 631 log_error ("error creating key for RNG: %s\n", gcry_strerror (err)); 632 gcry_cipher_close (hd); 633 return NULL; 634 } 635 636 return hd; 637} 638 639 640/* Generate a key for use with x931_aes. The function copies a seed 641 of LENGTH bytes into SEED_BUFFER. LENGTH needs to by given as 16. */ 642static void 643x931_generate_seed (unsigned char *seed_buffer, size_t length) 644{ 645 void *buffer; 646 647 gcry_assert (fips_rng_is_locked); 648 gcry_assert (length == 16); 649 650 buffer = get_entropy (X931_AES_KEYLEN); 651 652 memcpy (seed_buffer, buffer, X931_AES_KEYLEN); 653 wipememory (buffer, X931_AES_KEYLEN); 654 gcry_free (buffer); 655} 656 657 658 659/* Reseed a generator. This is also used for the initial seeding. */ 660static void 661x931_reseed (rng_context_t rng_ctx) 662{ 663 gcry_assert (fips_rng_is_locked); 664 665 if (rng_ctx == nonce_context) 666 { 667 /* The nonce context is special. It will be seeded using the 668 standard random generator. */ 669 get_random (rng_ctx->seed_V, 16, std_rng_context); 670 rng_ctx->is_seeded = 1; 671 rng_ctx->seed_init_pid = getpid (); 672 } 673 else 674 { 675 /* The other two generators are seeded from /dev/random. */ 676 x931_generate_seed (rng_ctx->seed_V, 16); 677 rng_ctx->is_seeded = 1; 678 rng_ctx->seed_init_pid = getpid (); 679 } 680} 681 682 683/* Core random function. This is used for both nonce and random 684 generator. The actual RNG to be used depends on the random context 685 RNG_CTX passed. Note that this function is called with the RNG not 686 yet locked. */ 687static void 688get_random (void *buffer, size_t length, rng_context_t rng_ctx) 689{ 690 gcry_assert (buffer); 691 gcry_assert (rng_ctx); 692 693 check_guards (rng_ctx); 694 695 /* Initialize the cipher handle and thus setup the key if needed. */ 696 if (!rng_ctx->cipher_hd) 697 { 698 if (rng_ctx == nonce_context) 699 rng_ctx->cipher_hd = x931_generate_key (1); 700 else 701 rng_ctx->cipher_hd = x931_generate_key (0); 702 if (!rng_ctx->cipher_hd) 703 goto bailout; 704 rng_ctx->key_init_pid = getpid (); 705 } 706 707 /* Initialize the seed value if needed. */ 708 if (!rng_ctx->is_seeded) 709 x931_reseed (rng_ctx); 710 711 if (rng_ctx->key_init_pid != getpid () 712 || rng_ctx->seed_init_pid != getpid ()) 713 { 714 /* We are in a child of us. Because we have no way yet to do 715 proper re-initialization (including self-checks etc), the 716 only chance we have is to bail out. Obviusly a fork/exec 717 won't harm because the exec overwrites the old image. */ 718 fips_signal_error ("fork without proper re-initialization " 719 "detected in RNG"); 720 goto bailout; 721 } 722 723 if (x931_aes_driver (buffer, length, rng_ctx)) 724 goto bailout; 725 726 check_guards (rng_ctx); 727 return; 728 729 bailout: 730 log_fatal ("severe error getting random\n"); 731 /*NOTREACHED*/ 732} 733 734 735 736/* --- Public Functions --- */ 737 738/* Initialize this random subsystem. If FULL is false, this function 739 merely calls the basic initialization of the module and does not do 740 anything more. Doing this is not really required but when running 741 in a threaded environment we might get a race condition 742 otherwise. */ 743void 744_gcry_rngfips_initialize (int full) 745{ 746 basic_initialization (); 747 if (!full) 748 return; 749 750 /* Allocate temporary buffers. If that buffer already exists we 751 know that we are already initialized. */ 752 lock_rng (); 753 if (!tempvalue_for_x931_aes_driver) 754 { 755 tempvalue_for_x931_aes_driver 756 = gcry_xmalloc_secure (TEMPVALUE_FOR_X931_AES_DRIVER_SIZE); 757 758 /* Allocate the random contexts. Note that we do not need to use 759 secure memory for the nonce context. */ 760 nonce_context = gcry_xcalloc (1, sizeof *nonce_context); 761 setup_guards (nonce_context); 762 763 std_rng_context = gcry_xcalloc_secure (1, sizeof *std_rng_context); 764 setup_guards (std_rng_context); 765 766 strong_rng_context = gcry_xcalloc_secure (1, sizeof *strong_rng_context); 767 setup_guards (strong_rng_context); 768 } 769 else 770 { 771 /* Already initialized. Do some sanity checks. */ 772 gcry_assert (!nonce_context->test_dt_ptr); 773 gcry_assert (!std_rng_context->test_dt_ptr); 774 gcry_assert (!strong_rng_context->test_dt_ptr); 775 check_guards (nonce_context); 776 check_guards (std_rng_context); 777 check_guards (strong_rng_context); 778 } 779 unlock_rng (); 780} 781 782 783/* Print some statistics about the RNG. */ 784void 785_gcry_rngfips_dump_stats (void) 786{ 787 /* Not yet implemented. */ 788} 789 790 791/* This function returns true if no real RNG is available or the 792 quality of the RNG has been degraded for test purposes. */ 793int 794_gcry_rngfips_is_faked (void) 795{ 796 return 0; /* Faked random is not allowed. */ 797} 798 799 800/* Add BUFLEN bytes from BUF to the internal random pool. QUALITY 801 should be in the range of 0..100 to indicate the goodness of the 802 entropy added, or -1 for goodness not known. */ 803gcry_error_t 804_gcry_rngfips_add_bytes (const void *buf, size_t buflen, int quality) 805{ 806 (void)buf; 807 (void)buflen; 808 (void)quality; 809 return 0; /* Not implemented. */ 810} 811 812 813/* Public function to fill the buffer with LENGTH bytes of 814 cryptographically strong random bytes. Level GCRY_WEAK_RANDOM is 815 here mapped to GCRY_STRONG_RANDOM, GCRY_STRONG_RANDOM is strong 816 enough for most usage, GCRY_VERY_STRONG_RANDOM is good for key 817 generation stuff but may be very slow. */ 818void 819_gcry_rngfips_randomize (void *buffer, size_t length, 820 enum gcry_random_level level) 821{ 822 _gcry_rngfips_initialize (1); /* Auto-initialize if needed. */ 823 824 lock_rng (); 825 if (level == GCRY_VERY_STRONG_RANDOM) 826 get_random (buffer, length, strong_rng_context); 827 else 828 get_random (buffer, length, std_rng_context); 829 unlock_rng (); 830} 831 832 833/* Create an unpredicable nonce of LENGTH bytes in BUFFER. */ 834void 835_gcry_rngfips_create_nonce (void *buffer, size_t length) 836{ 837 _gcry_rngfips_initialize (1); /* Auto-initialize if needed. */ 838 839 lock_rng (); 840 get_random (buffer, length, nonce_context); 841 unlock_rng (); 842} 843 844 845/* Run a Know-Answer-Test using a dedicated test context. Note that 846 we can't use the samples from the NISR RNGVS document because they 847 don't take the requirement to throw away the first block and use 848 that for duplicate check in account. Thus we made up our own test 849 vectors. */ 850static gcry_err_code_t 851selftest_kat (selftest_report_func_t report) 852{ 853 static struct 854 { 855 const unsigned char key[16]; 856 const unsigned char dt[16]; 857 const unsigned char v[16]; 858 const unsigned char r[3][16]; 859 } tv[] = 860 { 861 { { 0xb9, 0xca, 0x7f, 0xd6, 0xa0, 0xf5, 0xd3, 0x42, 862 0x19, 0x6d, 0x84, 0x91, 0x76, 0x1c, 0x3b, 0xbe }, 863 { 0x48, 0xb2, 0x82, 0x98, 0x68, 0xc2, 0x80, 0x00, 864 0x00, 0x00, 0x28, 0x18, 0x00, 0x00, 0x25, 0x00 }, 865 { 0x52, 0x17, 0x8d, 0x29, 0xa2, 0xd5, 0x84, 0x12, 866 0x9d, 0x89, 0x9a, 0x45, 0x82, 0x02, 0xf7, 0x77 }, 867 { { 0x42, 0x9c, 0x08, 0x3d, 0x82, 0xf4, 0x8a, 0x40, 868 0x66, 0xb5, 0x49, 0x27, 0xab, 0x42, 0xc7, 0xc3 }, 869 { 0x0e, 0xb7, 0x61, 0x3c, 0xfe, 0xb0, 0xbe, 0x73, 870 0xf7, 0x6e, 0x6d, 0x6f, 0x1d, 0xa3, 0x14, 0xfa }, 871 { 0xbb, 0x4b, 0xc1, 0x0e, 0xc5, 0xfb, 0xcd, 0x46, 872 0xbe, 0x28, 0x61, 0xe7, 0x03, 0x2b, 0x37, 0x7d } } }, 873 { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 874 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, 875 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 876 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, 877 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 878 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, 879 { { 0xf7, 0x95, 0xbd, 0x4a, 0x52, 0xe2, 0x9e, 0xd7, 880 0x13, 0xd3, 0x13, 0xfa, 0x20, 0xe9, 0x8d, 0xbc }, 881 { 0xc8, 0xd1, 0xe5, 0x11, 0x59, 0x52, 0xf7, 0xfa, 882 0x37, 0x38, 0xb4, 0xc5, 0xce, 0xb2, 0xb0, 0x9a }, 883 { 0x0d, 0x9c, 0xc5, 0x0d, 0x16, 0xe1, 0xbc, 0xed, 884 0xcf, 0x60, 0x62, 0x09, 0x9d, 0x20, 0x83, 0x7e } } }, 885 { { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 886 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }, 887 { 0x80, 0x00, 0x81, 0x01, 0x82, 0x02, 0x83, 0x03, 888 0xa0, 0x20, 0xa1, 0x21, 0xa2, 0x22, 0xa3, 0x23 }, 889 { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 890 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, 891 { { 0x96, 0xed, 0xcc, 0xc3, 0xdd, 0x04, 0x7f, 0x75, 892 0x63, 0x19, 0x37, 0x6f, 0x15, 0x22, 0x57, 0x56 }, 893 { 0x7a, 0x14, 0x76, 0x77, 0x95, 0x17, 0x7e, 0xc8, 894 0x92, 0xe8, 0xdd, 0x15, 0xcb, 0x1f, 0xbc, 0xb1 }, 895 { 0x25, 0x3e, 0x2e, 0xa2, 0x41, 0x1b, 0xdd, 0xf5, 896 0x21, 0x48, 0x41, 0x71, 0xb3, 0x8d, 0x2f, 0x4c } } } 897 }; 898 int tvidx, ridx; 899 rng_context_t test_ctx; 900 gpg_error_t err; 901 const char *errtxt = NULL; 902 unsigned char result[16]; 903 904 gcry_assert (tempvalue_for_x931_aes_driver); 905 906 test_ctx = gcry_xcalloc (1, sizeof *test_ctx); 907 setup_guards (test_ctx); 908 909 lock_rng (); 910 911 for (tvidx=0; tvidx < DIM (tv); tvidx++) 912 { 913 /* Setup the key. */ 914 err = gcry_cipher_open (&test_ctx->cipher_hd, 915 GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB, 916 GCRY_CIPHER_SECURE); 917 if (err) 918 { 919 errtxt = "error creating cipher context for RNG"; 920 goto leave; 921 } 922 923 err = gcry_cipher_setkey (test_ctx->cipher_hd, tv[tvidx].key, 16); 924 if (err) 925 { 926 errtxt = "error setting key for RNG"; 927 goto leave; 928 } 929 test_ctx->key_init_pid = getpid (); 930 931 /* Setup the seed. */ 932 memcpy (test_ctx->seed_V, tv[tvidx].v, 16); 933 test_ctx->is_seeded = 1; 934 test_ctx->seed_init_pid = getpid (); 935 936 /* Setup a DT value. */ 937 test_ctx->test_dt_ptr = tv[tvidx].dt; 938 test_ctx->test_dt_counter = ( (tv[tvidx].dt[12] << 24) 939 |(tv[tvidx].dt[13] << 16) 940 |(tv[tvidx].dt[14] << 8) 941 |(tv[tvidx].dt[15]) ); 942 943 /* Get and compare the first three results. */ 944 for (ridx=0; ridx < 3; ridx++) 945 { 946 /* Compute the next value. */ 947 if (x931_aes_driver (result, 16, test_ctx)) 948 { 949 errtxt = "X9.31 RNG core function failed"; 950 goto leave; 951 } 952 953 /* Compare it to the known value. */ 954 if (memcmp (result, tv[tvidx].r[ridx], 16)) 955 { 956 /* log_printhex ("x931_aes got: ", result, 16); */ 957 /* log_printhex ("x931_aes exp: ", tv[tvidx].r[ridx], 16); */ 958 errtxt = "RNG output does not match known value"; 959 goto leave; 960 } 961 } 962 963 /* This test is actual pretty pointless because we use a local test 964 context. */ 965 if (test_ctx->key_init_pid != getpid () 966 || test_ctx->seed_init_pid != getpid ()) 967 { 968 errtxt = "fork detection failed"; 969 goto leave; 970 } 971 972 gcry_cipher_close (test_ctx->cipher_hd); 973 test_ctx->cipher_hd = NULL; 974 test_ctx->is_seeded = 0; 975 check_guards (test_ctx); 976 } 977 978 leave: 979 unlock_rng (); 980 gcry_cipher_close (test_ctx->cipher_hd); 981 check_guards (test_ctx); 982 gcry_free (test_ctx); 983 if (report && errtxt) 984 report ("random", 0, "KAT", errtxt); 985 return errtxt? GPG_ERR_SELFTEST_FAILED : 0; 986} 987 988 989/* Run the self-tests. */ 990gcry_error_t 991_gcry_rngfips_selftest (selftest_report_func_t report) 992{ 993 gcry_err_code_t ec; 994 995#if defined(USE_RNDLINUX) || defined(USE_RNDW32) 996 { 997 char buffer[8]; 998 999 /* Do a simple test using the public interface. This will also 1000 enforce full initialization of the RNG. We need to be fully 1001 initialized due to the global requirement of the 1002 tempvalue_for_x931_aes_driver stuff. */ 1003 gcry_randomize (buffer, sizeof buffer, GCRY_STRONG_RANDOM); 1004 } 1005 1006 ec = selftest_kat (report); 1007 1008#else /*!(USE_RNDLINUX||USE_RNDW32)*/ 1009 report ("random", 0, "setup", "no entropy gathering module"); 1010 ec = GPG_ERR_SELFTEST_FAILED; 1011#endif 1012 return gpg_error (ec); 1013} 1014 1015 1016/* Create a new test context for an external RNG test driver. On 1017 success the test context is stored at R_CONTEXT; on failure NULL is 1018 stored at R_CONTEXT and an error code is returned. */ 1019gcry_err_code_t 1020_gcry_rngfips_init_external_test (void **r_context, unsigned int flags, 1021 const void *key, size_t keylen, 1022 const void *seed, size_t seedlen, 1023 const void *dt, size_t dtlen) 1024{ 1025 gpg_error_t err; 1026 rng_context_t test_ctx; 1027 1028 _gcry_rngfips_initialize (1); /* Auto-initialize if needed. */ 1029 1030 if (!r_context 1031 || !key || keylen != 16 1032 || !seed || seedlen != 16 1033 || !dt || dtlen != 16 ) 1034 return GPG_ERR_INV_ARG; 1035 1036 test_ctx = gcry_calloc (1, sizeof *test_ctx + dtlen); 1037 if (!test_ctx) 1038 return gpg_err_code_from_syserror (); 1039 setup_guards (test_ctx); 1040 1041 /* Setup the key. */ 1042 err = gcry_cipher_open (&test_ctx->cipher_hd, 1043 GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB, 1044 GCRY_CIPHER_SECURE); 1045 if (err) 1046 goto leave; 1047 1048 err = gcry_cipher_setkey (test_ctx->cipher_hd, key, keylen); 1049 if (err) 1050 goto leave; 1051 1052 test_ctx->key_init_pid = getpid (); 1053 1054 /* Setup the seed. */ 1055 memcpy (test_ctx->seed_V, seed, seedlen); 1056 test_ctx->is_seeded = 1; 1057 test_ctx->seed_init_pid = getpid (); 1058 1059 /* Setup a DT value. Because our context structure only stores a 1060 pointer we copy the DT value to the extra space we allocated in 1061 the test_ctx and set the pointer to that address. */ 1062 memcpy ((unsigned char*)test_ctx + sizeof *test_ctx, dt, dtlen); 1063 test_ctx->test_dt_ptr = (unsigned char*)test_ctx + sizeof *test_ctx; 1064 test_ctx->test_dt_counter = ( (test_ctx->test_dt_ptr[12] << 24) 1065 |(test_ctx->test_dt_ptr[13] << 16) 1066 |(test_ctx->test_dt_ptr[14] << 8) 1067 |(test_ctx->test_dt_ptr[15]) ); 1068 1069 if ( (flags & 1) ) 1070 test_ctx->test_no_dup_check = 1; 1071 1072 check_guards (test_ctx); 1073 /* All fine. */ 1074 err = 0; 1075 1076 leave: 1077 if (err) 1078 { 1079 gcry_cipher_close (test_ctx->cipher_hd); 1080 gcry_free (test_ctx); 1081 *r_context = NULL; 1082 } 1083 else 1084 *r_context = test_ctx; 1085 return gcry_err_code (err); 1086} 1087 1088 1089/* Get BUFLEN bytes from the RNG using the test CONTEXT and store them 1090 at BUFFER. Return 0 on success or an error code. */ 1091gcry_err_code_t 1092_gcry_rngfips_run_external_test (void *context, char *buffer, size_t buflen) 1093{ 1094 rng_context_t test_ctx = context; 1095 1096 if (!test_ctx || !buffer || buflen != 16) 1097 return GPG_ERR_INV_ARG; 1098 1099 lock_rng (); 1100 get_random (buffer, buflen, test_ctx); 1101 unlock_rng (); 1102 return 0; 1103} 1104 1105/* Release the test CONTEXT. */ 1106void 1107_gcry_rngfips_deinit_external_test (void *context) 1108{ 1109 rng_context_t test_ctx = context; 1110 1111 if (test_ctx) 1112 { 1113 gcry_cipher_close (test_ctx->cipher_hd); 1114 gcry_free (test_ctx); 1115 } 1116} 1117