1
/* random-fips.c - FIPS style random number generator
2
* Copyright (C) 2008 Free Software Foundation, Inc.
4
* This file is part of Libgcrypt.
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.
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.
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/>.
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
27
There are 3 random context which map to the different levels of
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
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.
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.
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.
60
#include <sys/types.h>
62
#ifdef HAVE_GETTIMEOFDAY
68
#include "rand-internal.h"
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. */
75
static ath_mutex_t fips_rng_lock = ATH_MUTEX_INITIALIZER;
76
static int fips_rng_is_locked;
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.
85
This variable is also used to avoid duplicate initialization. */
86
#define TEMPVALUE_FOR_X931_AES_DRIVER_SIZE 48
87
static unsigned char *tempvalue_for_x931_aes_driver;
90
/* After having retrieved this number of blocks from the RNG, we want
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. */
100
static unsigned char *entropy_collect_buffer; /* Buffer. */
101
static size_t entropy_collect_buffer_len; /* Used length. */
102
static size_t entropy_collect_buffer_size; /* Allocated length. */
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
112
unsigned char guard_0[1];
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
117
gcry_cipher_hd_t cipher_hd;
119
/* If this flag is true, the SEED_V buffer below carries a valid
123
/* The very first block generated is used to compare the result
124
against the last result. This flag indicates that such a block
126
int compare_value_valid:1;
128
/* A counter used to trigger re-seeding. */
129
unsigned int use_counter;
131
unsigned char guard_1[1];
133
/* The buffer containing the seed value V. */
134
unsigned char seed_V[16];
136
unsigned char guard_2[1];
138
/* The last result from the x931_aes fucntion. Only valid if
139
compare_value_valid is set. */
140
unsigned char compare_value[16];
142
unsigned char guard_3[1];
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;
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. */
164
typedef struct rng_context *rng_context_t;
167
/* The random context used for the nonce generator. May only be used
168
while holding the FIPS_RNG_LOCK. */
169
static 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. */
172
static 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. */
175
static rng_context_t strong_rng_context;
178
/* --- Local prototypes --- */
179
static void x931_reseed (rng_context_t rng_ctx);
180
static void get_random (void *buffer, size_t length, rng_context_t rng_ctx);
185
/* --- Functions --- */
187
/* Basic initialization is required to initialize mutexes and
188
do a few checks on the implementation. */
190
basic_initialization (void)
192
static int initialized;
199
my_errno = ath_mutex_init (&fips_rng_lock);
201
log_fatal ("failed to create the RNG lock: %s\n", strerror (my_errno));
202
fips_rng_is_locked = 0;
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);
213
/* Acquire the fips_rng_lock. */
219
my_errno = ath_mutex_lock (&fips_rng_lock);
221
log_fatal ("failed to acquire the RNG lock: %s\n", strerror (my_errno));
222
fips_rng_is_locked = 1;
226
/* Release the fips_rng_lock. */
232
fips_rng_is_locked = 0;
233
my_errno = ath_mutex_unlock (&fips_rng_lock);
235
log_fatal ("failed to release the RNG lock: %s\n", strerror (my_errno));
239
setup_guards (rng_context_t rng_ctx)
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;
249
check_guards (rng_context_t rng_ctx)
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);
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:
264
Buffer: 00112233445566778899AABBCCDDEEFF
265
!--+---!!-+-!!+!!--+---!!--+---!
266
seconds ---------/ | | | |
267
microseconds -----------/ | | |
268
counter2 -------------------/ | |
269
counter1 ------------------------/ |
270
counter0 --------------------------------/
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. */
276
x931_get_dt (unsigned char *buffer, size_t length, rng_context_t rng_ctx)
278
gcry_assert (length == 16); /* This length is required for use with AES. */
279
gcry_assert (fips_rng_is_locked);
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)
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++;
299
#if HAVE_GETTIMEOFDAY
301
static u32 last_sec, last_usec;
302
static u32 counter1, counter0;
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 ();
320
if (gettimeofday (&tv, NULL))
321
log_fatal ("gettimeofday() failed: %s\n", strerror (errno));
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. */
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)
338
last_sec = tv.tv_sec;
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. */
364
log_fatal ("gettimeofday() not available on this system\n");
367
/* log_printhex ("x931_get_dt: ", buffer, 16); */
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. */
375
xor_buffer (unsigned char *r,
376
const unsigned char *a, const unsigned char *b, size_t length)
378
for ( ; length; length--, a++, b++, r++)
383
/* Encrypt LENGTH bytes of INPUT to OUTPUT using KEY. LENGTH
386
encrypt_aes (gcry_cipher_hd_t key,
387
unsigned char *output, const unsigned char *input, size_t length)
391
gcry_assert (length == 16);
393
err = gcry_cipher_encrypt (key, output, length, input, length);
395
log_fatal ("AES encryption in RNG failed: %s\n", gcry_strerror (err));
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.
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. */
409
x931_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])
414
/* Let ede*X(Y) represent the AES encryption of Y under the key *X.
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.
421
encrypt_aes (key, intermediate_I, datetime_DT, 16);
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);
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);
431
/* Zero out temporary values. */
432
wipememory (intermediate_I, 16);
433
wipememory (temp_xor, 16);
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. */
443
x931_aes_driver (unsigned char *output, size_t length, rng_context_t rng_ctx)
445
unsigned char datetime_DT[16];
446
unsigned char *intermediate_I, *temp_buffer, *result_buffer;
449
gcry_assert (fips_rng_is_locked);
450
gcry_assert (rng_ctx->cipher_hd);
451
gcry_assert (rng_ctx->is_seeded);
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;
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)
465
x931_reseed (rng_ctx);
466
rng_ctx->use_counter = 0;
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
474
nbytes = length < 16? length : 16;
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++;
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)
488
/* This is a test context which does not want the duplicate
493
/* Do a basic check on the output to avoid a stuck generator. */
494
if (!rng_ctx->compare_value_valid)
496
/* First time used, only save the result. */
497
memcpy (rng_ctx->compare_value, result_buffer, 16);
498
rng_ctx->compare_value_valid = 1;
501
if (!memcmp (rng_ctx->compare_value, result_buffer, 16))
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
507
fips_signal_error ("duplicate 128 bit block returned by RNG");
510
memcpy (rng_ctx->compare_value, result_buffer, 16);
513
/* Append to outbut. */
514
memcpy (output, result_buffer, nbytes);
515
wipememory (result_buffer, 16);
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
529
entropy_collect_cb (const void *buffer, size_t length,
530
enum random_origins origin)
532
const unsigned char *p = buffer;
536
gcry_assert (fips_rng_is_locked);
537
gcry_assert (entropy_collect_buffer);
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)
543
entropy_collect_buffer[entropy_collect_buffer_len++] ^= *p++;
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. */
552
get_entropy (size_t nbytes)
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;
563
rc = _gcry_rndlinux_gather_random (entropy_collect_cb, 0,
565
GCRY_VERY_STRONG_RANDOM);
569
rc = _gcry_rndw32_gather_random (entropy_collect_cb, 0,
571
GCRY_VERY_STRONG_RANDOM);
573
while (rc >= 0 && entropy_collect_buffer_len < entropy_collect_buffer_size);
578
if (rc < 0 || entropy_collect_buffer_len != entropy_collect_buffer_size)
580
gcry_free (entropy_collect_buffer);
581
entropy_collect_buffer = NULL;
582
log_fatal ("error getting entropy data\n");
584
result = entropy_collect_buffer;
585
entropy_collect_buffer = NULL;
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. */
594
static gcry_cipher_hd_t
595
x931_generate_key (int for_nonce)
601
gcry_assert (fips_rng_is_locked);
603
/* Allocate a cipher context. */
604
err = gcry_cipher_open (&hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB,
608
log_error ("error creating cipher context for RNG: %s\n",
609
gcry_strerror (err));
613
/* Get a key from the standard RNG or from the entropy source. */
616
buffer = gcry_xmalloc (X931_AES_KEYLEN);
617
get_random (buffer, X931_AES_KEYLEN, std_rng_context);
621
buffer = get_entropy (X931_AES_KEYLEN);
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);
631
log_error ("error creating key for RNG: %s\n", gcry_strerror (err));
632
gcry_cipher_close (hd);
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. */
643
x931_generate_seed (unsigned char *seed_buffer, size_t length)
647
gcry_assert (fips_rng_is_locked);
648
gcry_assert (length == 16);
650
buffer = get_entropy (X931_AES_KEYLEN);
652
memcpy (seed_buffer, buffer, X931_AES_KEYLEN);
653
wipememory (buffer, X931_AES_KEYLEN);
659
/* Reseed a generator. This is also used for the initial seeding. */
661
x931_reseed (rng_context_t rng_ctx)
663
gcry_assert (fips_rng_is_locked);
665
if (rng_ctx == nonce_context)
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 ();
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 ();
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
688
get_random (void *buffer, size_t length, rng_context_t rng_ctx)
690
gcry_assert (buffer);
691
gcry_assert (rng_ctx);
693
check_guards (rng_ctx);
695
/* Initialize the cipher handle and thus setup the key if needed. */
696
if (!rng_ctx->cipher_hd)
698
if (rng_ctx == nonce_context)
699
rng_ctx->cipher_hd = x931_generate_key (1);
701
rng_ctx->cipher_hd = x931_generate_key (0);
702
if (!rng_ctx->cipher_hd)
704
rng_ctx->key_init_pid = getpid ();
707
/* Initialize the seed value if needed. */
708
if (!rng_ctx->is_seeded)
709
x931_reseed (rng_ctx);
711
if (rng_ctx->key_init_pid != getpid ()
712
|| rng_ctx->seed_init_pid != getpid ())
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 "
723
if (x931_aes_driver (buffer, length, rng_ctx))
726
check_guards (rng_ctx);
730
log_fatal ("severe error getting random\n");
736
/* --- Public Functions --- */
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
744
_gcry_rngfips_initialize (int full)
746
basic_initialization ();
750
/* Allocate temporary buffers. If that buffer already exists we
751
know that we are already initialized. */
753
if (!tempvalue_for_x931_aes_driver)
755
tempvalue_for_x931_aes_driver
756
= gcry_xmalloc_secure (TEMPVALUE_FOR_X931_AES_DRIVER_SIZE);
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);
763
std_rng_context = gcry_xcalloc_secure (1, sizeof *std_rng_context);
764
setup_guards (std_rng_context);
766
strong_rng_context = gcry_xcalloc_secure (1, sizeof *strong_rng_context);
767
setup_guards (strong_rng_context);
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);
783
/* Print some statistics about the RNG. */
785
_gcry_rngfips_dump_stats (void)
787
/* Not yet implemented. */
791
/* This function returns true if no real RNG is available or the
792
quality of the RNG has been degraded for test purposes. */
794
_gcry_rngfips_is_faked (void)
796
return 0; /* Faked random is not allowed. */
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. */
804
_gcry_rngfips_add_bytes (const void *buf, size_t buflen, int quality)
809
return 0; /* Not implemented. */
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. */
819
_gcry_rngfips_randomize (void *buffer, size_t length,
820
enum gcry_random_level level)
822
_gcry_rngfips_initialize (1); /* Auto-initialize if needed. */
825
if (level == GCRY_VERY_STRONG_RANDOM)
826
get_random (buffer, length, strong_rng_context);
828
get_random (buffer, length, std_rng_context);
833
/* Create an unpredicable nonce of LENGTH bytes in BUFFER. */
835
_gcry_rngfips_create_nonce (void *buffer, size_t length)
837
_gcry_rngfips_initialize (1); /* Auto-initialize if needed. */
840
get_random (buffer, length, nonce_context);
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
850
static gcry_err_code_t
851
selftest_kat (selftest_report_func_t report)
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];
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 } } }
899
rng_context_t test_ctx;
901
const char *errtxt = NULL;
902
unsigned char result[16];
904
gcry_assert (tempvalue_for_x931_aes_driver);
906
test_ctx = gcry_xcalloc (1, sizeof *test_ctx);
907
setup_guards (test_ctx);
911
for (tvidx=0; tvidx < DIM (tv); tvidx++)
914
err = gcry_cipher_open (&test_ctx->cipher_hd,
915
GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB,
919
errtxt = "error creating cipher context for RNG";
923
err = gcry_cipher_setkey (test_ctx->cipher_hd, tv[tvidx].key, 16);
926
errtxt = "error setting key for RNG";
929
test_ctx->key_init_pid = getpid ();
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 ();
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]) );
943
/* Get and compare the first three results. */
944
for (ridx=0; ridx < 3; ridx++)
946
/* Compute the next value. */
947
if (x931_aes_driver (result, 16, test_ctx))
949
errtxt = "X9.31 RNG core function failed";
953
/* Compare it to the known value. */
954
if (memcmp (result, tv[tvidx].r[ridx], 16))
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";
963
/* This test is actual pretty pointless because we use a local test
965
if (test_ctx->key_init_pid != getpid ()
966
|| test_ctx->seed_init_pid != getpid ())
968
errtxt = "fork detection failed";
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);
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;
989
/* Run the self-tests. */
991
_gcry_rngfips_selftest (selftest_report_func_t report)
995
#if defined(USE_RNDLINUX) || defined(USE_RNDW32)
999
/* Do a simple test using the public interface. This will also
1000
enforce full intialization 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);
1006
ec = selftest_kat (report);
1008
#else /*!(USE_RNDLINUX||USE_RNDW32)*/
1009
report ("random", 0, "setup", "no entropy gathering module");
1010
ec = GPG_ERR_SELFTEST_FAILED;
1012
return gpg_error (ec);
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. */
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)
1026
rng_context_t test_ctx;
1028
_gcry_rngfips_initialize (1); /* Auto-initialize if needed. */
1031
|| !key || keylen != 16
1032
|| !seed || seedlen != 16
1033
|| !dt || dtlen != 16 )
1034
return GPG_ERR_INV_ARG;
1036
test_ctx = gcry_calloc (1, sizeof *test_ctx + dtlen);
1038
return gpg_err_code_from_syserror ();
1039
setup_guards (test_ctx);
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);
1048
err = gcry_cipher_setkey (test_ctx->cipher_hd, key, keylen);
1052
test_ctx->key_init_pid = getpid ();
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 ();
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]) );
1070
test_ctx->test_no_dup_check = 1;
1072
check_guards (test_ctx);
1079
gcry_cipher_close (test_ctx->cipher_hd);
1080
gcry_free (test_ctx);
1084
*r_context = test_ctx;
1085
return gcry_err_code (err);
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. */
1092
_gcry_rngfips_run_external_test (void *context, char *buffer, size_t buflen)
1094
rng_context_t test_ctx = context;
1096
if (!test_ctx || !buffer || buflen != 16)
1097
return GPG_ERR_INV_ARG;
1100
get_random (buffer, buflen, test_ctx);
1105
/* Release the test CONTEXT. */
1107
_gcry_rngfips_deinit_external_test (void *context)
1109
rng_context_t test_ctx = context;
1113
gcry_cipher_close (test_ctx->cipher_hd);
1114
gcry_free (test_ctx);