cryptlib  3.4.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros
random.c
Go to the documentation of this file.
1 /****************************************************************************
2 * *
3 * cryptlib Randomness Management Routines *
4 * Copyright Peter Gutmann 1995-2007 *
5 * *
6 ****************************************************************************/
7 
8 /* The random pool handling code in this module and the other modules in the
9  /random subdirectory represent the cryptlib continuously seeded
10  pseudorandom number generator (CSPRNG) as described in my 1998 Usenix
11  Security Symposium paper "The generation of practically strong random
12  numbers".
13 
14  The CSPRNG code is copyright Peter Gutmann (and various others) 1995-2004
15  all rights reserved. Redistribution of the CSPRNG modules and use in
16  source and binary forms, with or without modification, are permitted
17  provided that the following BSD-style license conditions are met:
18 
19  1. Redistributions of source code must retain the above copyright notice
20  and this permission notice in its entirety.
21 
22  2. Redistributions in binary form must reproduce the copyright notice in
23  the documentation and/or other materials provided with the distribution.
24 
25  3. A copy of any bugfixes or enhancements made must be provided to the
26  author, <[email protected]> to allow them to be added to the
27  baseline version of the code.
28 
29  ALTERNATIVELY, the code may be distributed under the terms of the GNU
30  General Public License, version 2 or any later version published by the
31  Free Software Foundation, in which case the provisions of the GNU GPL are
32  required INSTEAD OF the above restrictions.
33 
34  ALTERNATIVELY ALTERNATIVELY, the code may be distributed under the terms
35  of the GNU Library/Lesser General Public License, version 2 or any later
36  version published by the Free Software Foundation, in which case the
37  provisions of the GNU LGPL are required INSTEAD OF the above restrictions.
38 
39  Although not required under the terms of the GPL or LGPL, it would still
40  be nice if you could make any changes available to the author to allow a
41  consistent code base to be maintained */
42 
43 #if defined( INC_ALL )
44  #include "crypt.h"
45  #ifdef CONFIG_RANDSEED
46  #include "stream.h"
47  #endif /* CONFIG_RANDSEED */
48  #include "random_int.h"
49 #else
50  #include "crypt.h"
51  #ifdef CONFIG_RANDSEED
52  #include "io/stream.h"
53  #endif /* CONFIG_RANDSEED */
54  #include "random/random_int.h"
55 #endif /* Compiler-specific includes */
56 
57 /* If we don't have a defined randomness interface, complain */
58 
59 #if !( defined( __BEOS__ ) || defined( __ECOS__ ) || \
60  defined( __IBM4758__ ) || defined( __MAC__ ) || \
61  defined( __MSDOS__ ) || defined( __MVS__ ) || \
62  defined( __OS2__ ) || defined( __PALMOS__ ) || \
63  defined( __TANDEM_NSK__ ) || defined( __TANDEM_OSS__ ) || \
64  defined( __UNIX__ ) || defined( __VMCMS__ ) || \
65  defined( __WIN16__ ) || defined( __WIN32__ ) || \
66  defined( __WINCE__ ) || defined( __XMK__ ) )
67  #error You need to create OS-specific randomness-gathering functions in random/<os-name>.c
68 #endif /* Various OS-specific defines */
69 
70 /* If we're using stored seed data, make sure that the seed quality setting
71  is in order */
72 
73 #ifdef CONFIG_RANDSEED
74  #ifndef CONFIG_RANDSEED_QUALITY
75  /* If the user hasn't provided a quality estimate, default to 80 */
76  #define CONFIG_RANDSEED_QUALITY 80
77  #endif /* !CONFIG_RANDSEED_QUALITY */
78  #if ( CONFIG_RANDSEED_QUALITY < 10 ) || ( CONFIG_RANDSEED_QUALITY > 100 )
79  #error CONFIG_RANDSEED_QUALITY must be between 10 and 100
80  #endif /* CONFIG_RANDSEED_QUALITY check */
81 
82  /* Forward declaration for the add-data function */
83  STDC_NONNULL_ARG( ( 1 ) ) \
84  static void addStoredSeedData( INOUT RANDOM_INFO *randomInfo );
85 #endif /* CONFIG_RANDSEED */
86 
87 /* A custom form of REQUIRES()/ENSURES() that takes care of unlocking the
88  randomness mutex on the way out */
89 
90 #define REQUIRES_MUTEX( x ) \
91  if( !( x ) ) { krnlExitMutex( MUTEX_RANDOM ); retIntError(); }
92 #define ENSURES_MUTEX REQUIRES_MUTEX
93 
94 /****************************************************************************
95 * *
96 * Randomness Interface Definitions *
97 * *
98 ****************************************************************************/
99 
100 /* In order to avoid the pool startup problem (where initial pool data may
101  consist of minimally-mixed entropy samples) we require that the pool be
102  mixed at least the following number of times before we can draw data from
103  it. This usually happens automatically because a slow poll adds enough
104  data to cause many mixing iterations, however if this doesn't happen we
105  manually mix it the appropriate number of times to get it up to the
106  correct level */
107 
108 #define RANDOMPOOL_MIXES 10
109 
110 /****************************************************************************
111 * *
112 * Utility Functions *
113 * *
114 ****************************************************************************/
115 
116 /* Sanity-check the randomness state */
117 
119 static BOOLEAN sanityCheck( const RANDOM_INFO *randomInfo )
120  {
121  assert( isReadPtr( randomInfo, sizeof( RANDOM_INFO ) ) );
122 
123  /* Make sure that the pool index information is within bounds. The pool
124  index can briefly become the same as RANDOMPOOL_SIZE if we've filled
125  the pool and we've about to mix it */
126  if( randomInfo->randomPoolPos < 0 || \
127  randomInfo->randomPoolPos > RANDOMPOOL_SIZE )
128  return( FALSE );
129 
130  /* Make sure that the pool accounting information is within bounds */
131  if( randomInfo->randomQuality < 0 || randomInfo->randomQuality > 100 )
132  return( FALSE );
133  if( randomInfo->randomPoolMixes < 0 || \
134  randomInfo->randomPoolMixes > RANDOMPOOL_MIXES )
135  return( FALSE );
136 
137  return( TRUE );
138  }
139 
140 /****************************************************************************
141 * *
142 * Random Pool Management Routines *
143 * *
144 ****************************************************************************/
145 
146 /* Initialise and shut down the random pool */
147 
148 STDC_NONNULL_ARG( ( 1 ) ) \
149 void initRandomPool( INOUT RANDOM_INFO *randomInfo )
150  {
151  assert( isWritePtr( randomInfo, sizeof( RANDOM_INFO ) ) );
152 
153  memset( randomInfo, 0, sizeof( RANDOM_INFO ) );
154  }
155 
156 STDC_NONNULL_ARG( ( 1 ) ) \
157 void endRandomPool( INOUT RANDOM_INFO *randomInfo )
158  {
159  assert( isWritePtr( randomInfo, sizeof( RANDOM_INFO ) ) );
160 
161  zeroise( randomInfo, sizeof( RANDOM_INFO ) );
162  }
163 
164 /* Stir up the data in the random pool. Given a circular buffer of length n
165  bytes, a buffer position p, and a hash output size of h bytes, we hash
166  bytes from p - h...p - 1 (to provide chaining across previous hashes) and
167  p...p + 64 (to have as much surrounding data as possible affect the
168  current data). Then we move on to the next h bytes until all n bytes have
169  been mixed. See "Cryptographic Security Architecture Design and
170  Implementation" for the full details of the PRNG design */
171 
173 static int mixRandomPool( INOUT RANDOM_INFO *randomInfo )
174  {
175  HASHFUNCTION_ATOMIC hashFunctionAtomic;
176  BYTE dataBuffer[ CRYPT_MAX_HASHSIZE + 64 + 8 ];
177  int hashSize, hashIndex;
178  ORIGINAL_INT_VAR( randomPoolMixes, randomInfo->randomPoolMixes );
179 
180  assert( isWritePtr( randomInfo, sizeof( RANDOM_INFO ) ) );
181 
182  REQUIRES( sanityCheck( randomInfo ) );
183 
184  getHashAtomicParameters( CRYPT_ALGO_SHA1, 0, &hashFunctionAtomic,
185  &hashSize );
186 
187  /* Stir up the entire pool. We can't check the return value of the
188  hashing call because there isn't one, however the hashing code has
189  gone through a self-test when the randomness subsystem was
190  initialised */
191  for( hashIndex = 0; hashIndex < RANDOMPOOL_SIZE; hashIndex += hashSize )
192  {
193  int dataBufIndex, poolIndex;
194 
195  /* Precondition: We're processing hashSize bytes at a time */
196  REQUIRES( hashIndex % hashSize == 0 );
197 
198  /* If we're at the start of the pool then the first block that we hash
199  is at the end of the pool, otherwise it's the block immediately
200  preceding the current one */
201  poolIndex = ( hashIndex >= hashSize ) ? \
202  hashIndex - hashSize : RANDOMPOOL_SIZE - hashSize;
203  ENSURES( poolIndex >= 0 && poolIndex <= RANDOMPOOL_SIZE - hashSize );
204 
205  /* Copy hashSize bytes from position p - hashSize... p + 64 in the
206  circular pool into the hash data buffer:
207 
208  poolIndex
209  | hashIndex
210  v v
211  --------+---+-----------------------+---------
212  | 20| 64 | Pool
213  --------+---+-----------------------+---------
214  | |
215  +---------------------------+
216  | | Buffer
217  +---------------------------+
218  \ /
219  \ Hash ------------------
220  \ /
221  ------------+---+-----------------------------
222  | 20| Pool'
223  ------------+---+-----------------------------
224  ^ ^ ^
225  | | |
226  p-h p p+64 */
227  for( dataBufIndex = 0; dataBufIndex < hashSize + 64; dataBufIndex++ )
228  {
229  dataBuffer[ dataBufIndex ] = randomInfo->randomPool[ poolIndex ];
230  poolIndex = ( poolIndex + 1 ) % RANDOMPOOL_SIZE;
231  }
232 
233  /* Postconditions for the state data copy: We got hashSize + 64 bytes
234  surrounding the current pool position */
235  ENSURES( dataBufIndex == hashSize + 64 );
236 
237  /* Hash the data in the circular pool, depositing the result at position
238  p...p + hashSize */
239  hashFunctionAtomic( randomInfo->randomPool + hashIndex,
240  RANDOMPOOL_ALLOCSIZE - hashIndex,
241  dataBuffer, dataBufIndex );
242  }
243  zeroise( dataBuffer, CRYPT_MAX_HASHSIZE + 64 );
244 
245  /* Postconditions for the pool mixing: The entire pool was mixed and
246  temporary storage was cleared */
247  ENSURES( hashIndex >= RANDOMPOOL_SIZE );
248  FORALL( i, 0, CRYPT_MAX_HASHSIZE + 64,
249  dataBuffer[ i ] == 0 );
250 
251  /* Increment the mix count and move the write position back to the start
252  of the pool */
253  if( randomInfo->randomPoolMixes < RANDOMPOOL_MIXES )
254  randomInfo->randomPoolMixes++;
255  randomInfo->randomPoolPos = 0;
256 
257  /* Postconditions for the status update: We mixed the pool at least
258  once, and we're back at the start of the pool */
259  ENSURES( randomInfo->randomPoolMixes == RANDOMPOOL_MIXES || \
260  randomInfo->randomPoolMixes == \
261  ORIGINAL_VALUE( randomPoolMixes ) + 1 );
262  ENSURES( randomInfo->randomPoolPos == 0 );
263 
264  ENSURES( sanityCheck( randomInfo ) );
265 
266  return( CRYPT_OK );
267  }
268 
269 /****************************************************************************
270 * *
271 * Get Random Data *
272 * *
273 ****************************************************************************/
274 
275 /* Get a block of random data from the randomness pool in such a way that
276  compromise of the data doesn't compromise the pool and vice versa. This
277  is done by performing the (one-way) pool mixing operation on the pool and
278  on a transformed version of the pool that becomes the key. This
279  corresponds to the Barak-Halevi construction:
280 
281  r || s' = next( s );
282  s' = refresh( s ^ new_state );
283 
284  where 'r' is the generator output and 's' is the generator state (the RNG
285  design here predates Barak-Halevi by about 10 years but the principle is
286  the same).
287 
288  The transformed version of the pool from which the key data will be drawn
289  is then further processed by running each 64-bit block through the X9.17
290  generator. As an additional precaution the key data is folded in half to
291  ensure that not even a hashed or encrypted form of the previous contents
292  is available. No pool data ever leaves the pool.
293 
294  This function performs a more paranoid version of the FIPS 140 continuous
295  tests on both the main pool contents and the X9.17 generator output to
296  detect stuck-at faults and short cycles in the output. In addition the
297  higher-level message handler applies FIPS 140-like statistical tests to
298  the output and will retry the fetch if the output fails the tests. This
299  additional step is performed at a higher level because it's then applied
300  to all randomness sources used by cryptlib and not just the built-in one.
301 
302  Because the pool output is folded to mask the PRNG output, the output from
303  each round of mixing is only half the pool size, as defined below */
304 
305 #define RANDOM_OUTPUTSIZE ( RANDOMPOOL_SIZE / 2 )
306 
308 static int tryGetRandomOutput( INOUT RANDOM_INFO *randomInfo,
309  INOUT RANDOM_INFO *exportedRandomInfo )
310  {
311  const BYTE *samplePtr = randomInfo->randomPool;
312  const BYTE *x917SamplePtr = exportedRandomInfo->randomPool;
313  unsigned long sample;
314  int i, status;
315 
316  assert( isWritePtr( randomInfo, sizeof( RANDOM_INFO ) ) );
317  assert( isWritePtr( exportedRandomInfo, sizeof( RANDOM_INFO ) ) );
318 
319  /* Precondition: The pool is ready to go. This check isn't so much to
320  confirm that this really is the case (it's already been checked
321  elsewhere) but to ensure that the two pool parameters haven't been
322  reversed. The use of generic pools for all types of random output is
323  useful in terms of providing a nice abstraction, but less useful for
324  type safety */
325  REQUIRES( sanityCheck( randomInfo ) );
326  REQUIRES( randomInfo->randomQuality >= 100 && \
327  randomInfo->randomPoolMixes >= RANDOMPOOL_MIXES && \
328  randomInfo->x917Inited == TRUE );
329  REQUIRES( exportedRandomInfo->randomQuality == 0 && \
330  exportedRandomInfo->randomPoolMixes == 0 && \
331  exportedRandomInfo->x917Inited == FALSE );
332 
333  /* Copy the contents of the main pool across to the export pool,
334  transforming it as we go by flipping all of the bits */
335  for( i = 0; i < RANDOMPOOL_ALLOCSIZE; i++ )
336  exportedRandomInfo->randomPool[ i ] = randomInfo->randomPool[ i ] ^ 0xFF;
337 
338  /* Postcondition for the bit-flipping: The two pools differ, and the
339  difference is in the flipped bits */
340  ENSURES( memcmp( randomInfo->randomPool, exportedRandomInfo->randomPool,
341  RANDOMPOOL_ALLOCSIZE ) );
342  FORALL( i, 0, RANDOMPOOL_ALLOCSIZE, \
343  randomInfo->randomPool[ i ] == \
344  ( exportedRandomInfo->randomPool[ i ] ^ 0xFF ) );
345 
346  /* Mix the original and export pools so that neither can be recovered
347  from the other */
348  status = mixRandomPool( randomInfo );
349  if( cryptStatusOK( status ) )
350  status = mixRandomPool( exportedRandomInfo );
351  if( cryptStatusError( status ) )
352  return( status );
353 
354  /* Postcondition for the mixing: The two pools differ, and the difference
355  is more than just the bit flipping (this has a ~1e-14 chance of a false
356  positive, which should be safe) */
357  ENSURES( memcmp( randomInfo->randomPool, exportedRandomInfo->randomPool,
358  RANDOMPOOL_ALLOCSIZE ) );
359  ENSURES( randomInfo->randomPool[ 0 ] != \
360  ( exportedRandomInfo->randomPool[ 0 ] ^ 0xFF ) ||
361  randomInfo->randomPool[ 8 ] != \
362  ( exportedRandomInfo->randomPool[ 8 ] ^ 0xFF ) ||
363  randomInfo->randomPool[ 16 ] != \
364  ( exportedRandomInfo->randomPool[ 16 ] ^ 0xFF ) ||
365  randomInfo->randomPool[ 24 ] != \
366  ( exportedRandomInfo->randomPool[ 24 ] ^ 0xFF ) ||
367  randomInfo->randomPool[ 32 ] != \
368  ( exportedRandomInfo->randomPool[ 32 ] ^ 0xFF ) ||
369  randomInfo->randomPool[ 40 ] != \
370  ( exportedRandomInfo->randomPool[ 40 ] ^ 0xFF ) );
371 
372  /* Precondition for sampling the output: It's a sample from the start of
373  the pool */
374  ENSURES( samplePtr == randomInfo->randomPool && \
375  x917SamplePtr == exportedRandomInfo->randomPool );
376 
377  /* Check for stuck-at faults by comparing a short sample from the current
378  output with samples from the previous RANDOMPOOL_SAMPLES outputs */
379  sample = mgetLong( samplePtr );
380  for( i = 0; i < RANDOMPOOL_SAMPLES; i++ )
381  {
382  if( randomInfo->prevOutput[ i ] == sample )
383  {
384  /* We're repeating previous output, tell the caller to try
385  again */
386  return( OK_SPECIAL );
387  }
388  }
389 
390  /* Postcondition: There are no values seen during a previous run present
391  in the output */
392  FORALL( i, 0, RANDOMPOOL_SAMPLES, \
393  randomInfo->prevOutput[ i ] != sample );
394 
395  /* Process the exported pool with the X9.17 generator */
396  status = generateX917( randomInfo, exportedRandomInfo->randomPool,
397  RANDOMPOOL_ALLOCSIZE );
398  if( cryptStatusError( status ) )
399  return( status );
400 
401  /* Check for stuck-at faults in the X9.17 generator by comparing a short
402  sample from the current output with samples from the previous
403  RANDOMPOOL_SAMPLES outputs. If it's the most recent sample then FIPS
404  140 requires an absolute failure if there's a duplicate rather than
405  simply signalling a problem and letting the higher layer handle it.
406  Because this will lead to false positives even for a perfect
407  generator we provide a custom check in which if we get a match in the
408  first 32 bits then we perform a backup check on the full
409  RANDOMPOOL_SAMPLE_SIZE bytes and return a hard failure if all of the
410  bits match.
411 
412  There's an implied additional requirement in the sampling process in
413  which the zero'th iteration of the X9.17 generator doesn't have a
414  previous sample to compare to and therefore can't meet the
415  requirements for previous-sample checking, however this is handled by
416  having the generator cranked twice on init/reinit in
417  getRandomOutput(), which provides the necessary zero'th sample */
418  sample = mgetLong( x917SamplePtr );
419  for( i = 0; i < RANDOMPOOL_SAMPLES; i++ )
420  {
421  if( randomInfo->x917PrevOutput[ i ] == sample )
422  {
423  /* If we've failed on the first sample and the full match also
424  fails, return a hard error */
425  if( i == 0 && \
426  !memcmp( randomInfo->x917OuputSample,
427  exportedRandomInfo->randomPool,
429  {
430  retIntError();
431  }
432 
433  /* We're repeating previous output, tell the caller to try
434  again */
435  return( OK_SPECIAL );
436  }
437  }
438 
439  /* Postcondition: There are no values seen during a previous run present
440  in the output */
441  FORALL( i, 0, RANDOMPOOL_SAMPLES, \
442  randomInfo->x917PrevOutput[ i ] != sample );
443 
444  ENSURES( sanityCheck( randomInfo ) );
445 
446  return( CRYPT_OK );
447  }
448 
449 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
450 static int getRandomOutput( INOUT RANDOM_INFO *randomInfo,
452  IN_RANGE( 1, RANDOM_OUTPUTSIZE ) const int length )
453  {
454  RANDOM_INFO exportedRandomInfo;
455  BYTE *samplePtr;
456  int noRandomRetries, i, status;
457  ORIGINAL_INT_VAR( prevOutputIndex, randomInfo->prevOutputIndex );
458 
459  assert( isWritePtr( randomInfo, sizeof( RANDOM_INFO ) ) );
460  assert( isWritePtr( buffer, length ) );
461 
462  static_assert( RANDOM_OUTPUTSIZE == RANDOMPOOL_SIZE / 2, \
463  "Random pool size" );
464 
465  /* Precondition for output quantity: We're being asked for a valid output
466  length and we're not trying to use more than half the pool contents */
467  REQUIRES( sanityCheck( randomInfo ) );
468  REQUIRES( length > 0 && length <= RANDOM_OUTPUTSIZE && \
469  length <= RANDOMPOOL_SIZE / 2 );
470 
471  /* If the X9.17 generator cryptovariables haven't been initialised yet
472  or have reached their use-by date, set the generator key and seed from
473  the pool contents, then mix the pool and crank the generator twice to
474  obscure the data that was used. This also provides the zero'th sample
475  of output required by the FIPS 140 tests */
476  if( !randomInfo->x917Inited || \
477  randomInfo->x917Count >= X917_MAX_CYCLES )
478  {
479  status = mixRandomPool( randomInfo );
480  if( cryptStatusOK( status ) )
481  status = setKeyX917( randomInfo, randomInfo->randomPool,
482  randomInfo->randomPool + X917_KEYSIZE,
483  NULL );
484  if( cryptStatusOK( status ) )
485  status = mixRandomPool( randomInfo );
486  if( cryptStatusOK( status ) )
487  status = generateX917( randomInfo, randomInfo->randomPool,
489  if( cryptStatusOK( status ) )
490  status = mixRandomPool( randomInfo );
491  if( cryptStatusOK( status ) )
492  status = generateX917( randomInfo, randomInfo->randomPool,
494  if( cryptStatusError( status ) )
495  return( status );
496  memcpy( randomInfo->x917OuputSample, randomInfo->randomPool,
497  RANDOMPOOL_SAMPLE_SIZE ); /* Save zero'th output sample */
498  }
499 
500  /* Precondition for drawing output from the generator: The pool is
501  sufficiently mixed, there's enough entropy present, and the X9.17
502  post-processor is ready for use */
503  REQUIRES( randomInfo->randomPoolMixes == RANDOMPOOL_MIXES && \
504  randomInfo->randomQuality >= 100 && randomInfo->x917Inited );
505 
506  /* Initialise the pool to contain the exported random data */
507  initRandomPool( &exportedRandomInfo );
508 
509  /* Try to obtain random data from the pool. If the initial attempt to
510  get entropy fails, retry a fixed number of times */
511  status = tryGetRandomOutput( randomInfo, &exportedRandomInfo );
512  for( noRandomRetries = 1;
513  status == OK_SPECIAL && noRandomRetries < RANDOMPOOL_RETRIES;
514  noRandomRetries++ )
515  {
516  status = tryGetRandomOutput( randomInfo, &exportedRandomInfo );
517  }
518  if( cryptStatusError( status ) )
519  {
520  /* We ran out of retries so that we're repeating the same output
521  data or there was some other type of error, fail */
522  endRandomPool( &exportedRandomInfo );
523 
524  /* Postcondition: Nulla vestigia retrorsum */
525  FORALL( i, 0, RANDOMPOOL_ALLOCSIZE, \
526  exportedRandomInfo.randomPool[ i ] == 0 );
527 
528  /* We can't trust the pool data any more so we set its content
529  value to zero. Ideally we should flash lights and sound
530  klaxons as well, this is a catastrophic failure */
531  randomInfo->randomQuality = randomInfo->randomPoolMixes = 0;
532  randomInfo->x917Inited = FALSE;
533  retIntError();
534  }
535 
536  /* Save a short sample from the current output for future checks */
537  REQUIRES( randomInfo->prevOutputIndex >= 0 && \
538  randomInfo->prevOutputIndex < RANDOMPOOL_SAMPLES );
539  samplePtr = randomInfo->randomPool;
540  randomInfo->prevOutput[ randomInfo->prevOutputIndex ] = mgetLong( samplePtr );
541  samplePtr = exportedRandomInfo.randomPool;
542  randomInfo->x917PrevOutput[ randomInfo->prevOutputIndex ] = mgetLong( samplePtr );
543  randomInfo->prevOutputIndex = ( randomInfo->prevOutputIndex + 1 ) % \
545  memcpy( randomInfo->x917OuputSample, exportedRandomInfo.randomPool,
547  ENSURES( randomInfo->prevOutputIndex != ORIGINAL_VALUE( prevOutputIndex ) );
548  ENSURES( randomInfo->prevOutputIndex == 0 || \
549  randomInfo->prevOutputIndex == ORIGINAL_VALUE( prevOutputIndex ) + 1 );
550  ENSURES( randomInfo->prevOutputIndex >= 0 && \
551  randomInfo->prevOutputIndex < RANDOMPOOL_SAMPLES );
552 
553  /* Copy the transformed data to the output buffer, folding it in half as
554  we go to mask the original content */
555  for( i = 0; i < length; i++ )
556  {
557  buffer[ i ] = exportedRandomInfo.randomPool[ i ] ^ \
558  exportedRandomInfo.randomPool[ RANDOM_OUTPUTSIZE + i ];
559  }
560 
561  /* Postcondition: We drew at most half of the transformed output from the
562  export pool, and the output came from the export pool and not the main
563  pool */
564  ENSURES( i <= RANDOMPOOL_SIZE / 2 );
565  EXISTS( i, 0, RANDOMPOOL_SIZE / 2, \
566  buffer[ i ] != ( randomInfo->randomPool[ i ] ^ \
567  randomInfo->randomPool[ RANDOM_OUTPUTSIZE + i ] ) );
568 
569  /* Clean up */
570  endRandomPool( &exportedRandomInfo );
571 
572  /* Postcondition: Nulla vestigia retrorsum */
573  FORALL( i, 0, RANDOMPOOL_ALLOCSIZE, \
574  exportedRandomInfo.randomPool[ i ] == 0 );
575 
576  ENSURES( sanityCheck( randomInfo ) );
577 
578  return( CRYPT_OK );
579  }
580 
581 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
582 int getRandomData( INOUT TYPECAST( RANDOM_INFO * ) void *randomInfoPtr,
583  OUT_BUFFER_FIXED( length ) void *buffer,
584  IN_RANGE( 1, MAX_RANDOM_BYTES ) const int length )
585  {
586  RANDOM_INFO *randomInfo = ( RANDOM_INFO * ) randomInfoPtr;
587  BYTE *bufPtr = buffer;
588  int randomQuality, count, iterationCount, status;
589 
590  assert( isWritePtr( randomInfo, sizeof( RANDOM_INFO ) ) );
591  assert( isWritePtr( buffer, length ) );
592 
593  /* Precondition: We're not asking for more data than the maximum that
594  should be needed */
595  REQUIRES( length > 0 && length <= MAX_RANDOM_BYTES );
596 
597  /* Clear the return value and by extension make sure that we fail the
598  FIPS 140-like entropy tests on the output if there's a problem */
599  zeroise( buffer, length );
600 
601  status = krnlEnterMutex( MUTEX_RANDOM );
602  if( cryptStatusError( status ) )
603  return( status );
604  REQUIRES_MUTEX( sanityCheck( randomInfo ) );
605 
606  /* If we're using a stored random seed, add it to the entropy pool if
607  necessary. Note that we do this here rather than when we initialise
608  the randomness subsystem both because at that point the stream
609  subsystem may not be ready for use yet and because there may be a
610  requirement to periodically re-read the seed data if it's changed
611  by another process/task */
612 #ifdef CONFIG_RANDSEED
613  if( !randomInfo->seedProcessed )
614  addStoredSeedData( randomInfo );
615 #endif /* CONFIG_RANDSEED */
616 
617  /* Get the randomness quality before we release the randomness info
618  again */
619  randomQuality = randomInfo->randomQuality;
620 
622 
623  /* Perform a failsafe check to make sure that there's data available.
624  This should only ever be called once per application because after
625  the first blocking poll that occurs because the user has tried to
626  generate keying material without having first seeded the generator
627  the programmer of the calling application will make sure that
628  there's a slow poll done earlier on */
629  if( randomQuality < 100 )
630  slowPoll();
631 
632  /* Make sure that any background randomness-gathering process has
633  finished */
634  status = waitforRandomCompletion( FALSE );
635  if( cryptStatusError( status ) )
636  return( status );
637 
638  status = krnlEnterMutex( MUTEX_RANDOM );
639  if( cryptStatusError( status ) )
640  return( status );
641  REQUIRES_MUTEX( sanityCheck( randomInfo ) );
642 
643  /* If we still can't get any random information, let the user know */
644  if( randomInfo->randomQuality < 100 )
645  {
647  DEBUG_DIAG(( "No random data available" ));
648  assert( DEBUG_WARN );
649  return( CRYPT_ERROR_RANDOM );
650  }
651 
652  /* If the process has forked we need to restart the generator output
653  process but we can't determine this until after we've already
654  produced the output. If we do need to restart, we do it from this
655  point.
656 
657  There is one variant of this problem that we can't work around and
658  that's where we're running inside a VM with rollback support. Some
659  VMs can take periodic snapshots of the system state to allow rollback
660  to a known-good state if an error occurs. Since the VM's rollback is
661  transparent to the OS there's no way to detect that this has
662  occcurred (although getSysVars() can detect the presence of some
663  common VMs it can't detect whether a rollback has occurred). In this
664  case we'd roll back to a previous state of the RNG and continue from
665  there. OTOH it's hard to identify a situation in which this would
666  pose a serious threat. Consider for example SSL or SSH session key
667  setup/generation: If we haven't committed the data to the remote
668  system yet it's no problem and if we have then we're now out of sync
669  with the remote system and the handshake will fail. Similarly, if
670  we're generating a DSA signature then we'll end up generating the
671  same signature again but since it's over the same data there's no
672  threat involved. Being able to cause a change in the data being
673  signed after the random DSA k value is generated would be a problem,
674  but k is only generated after the data has already been hashed and
675  the signature is about to be generated.
676 
677  In general this type of attack would require cooperation between the
678  VM and a hostile external party to, for example, ignore the fact
679  that the VM has rolled back to an earlier point in the protocol so a
680  repeat of a previous handshake message will be seen. In other words
681  it more or less requires control over the VM by an external party, and
682  anyone faced with this level of attack has bigger things to worry
683  about than RNG state rollback */
684 restartPoint:
685 
686  /* Prepare to get data from the randomness pool. Before we do this we
687  perform a final quick poll of the system to get any last bit of
688  entropy, and mix the entire pool. If the pool hasn't been sufficiently
689  mixed, we iterate until we've reached the minimum mix count */
690  for( iterationCount = 0; iterationCount < FAILSAFE_ITERATIONS_LARGE;
691  iterationCount++ )
692  {
693  DECLARE_ORIGINAL_INT( randomPoolMixes );
694 
695  fastPoll();
696 
697  /* Mix the pool after the fast poll. The poll itself can result in
698  multiple sets of mixing, this final mix ensures that there's no
699  unmixed data left */
700  STORE_ORIGINAL_INT( randomPoolMixes, randomInfo->randomPoolMixes );
701  status = mixRandomPool( randomInfo );
702  if( cryptStatusError( status ) )
703  {
705  return( status );
706  }
707  ENSURES( randomInfo->randomPoolMixes == RANDOMPOOL_MIXES || \
708  randomInfo->randomPoolMixes == \
709  ORIGINAL_VALUE( randomPoolMixes ) + 1 );
710 
711  /* If the pool is sufficiently mixed, we're done */
712  if( randomInfo->randomPoolMixes >= RANDOMPOOL_MIXES )
713  break;
714  }
715  ENSURES_MUTEX( iterationCount < FAILSAFE_ITERATIONS_LARGE );
716 
717  /* Keep producing RANDOMPOOL_OUTPUTSIZE bytes of output until the request
718  is satisfied */
719  for( count = 0; count < length; count += RANDOM_OUTPUTSIZE )
720  {
721  const int outputBytes = min( length - count, RANDOM_OUTPUTSIZE );
722  ORIGINAL_PTR( bufPtr );
723 
724  /* Precondition for output quantity: Either we're on the last output
725  block or we're producing the maximum-size output quantity, and
726  we're never trying to use more than half the pool contents */
727  REQUIRES_MUTEX( length - count < RANDOM_OUTPUTSIZE || \
728  outputBytes == RANDOM_OUTPUTSIZE );
729  REQUIRES_MUTEX( outputBytes <= RANDOMPOOL_SIZE / 2 );
730 
731  status = getRandomOutput( randomInfo, bufPtr, outputBytes );
732  if( cryptStatusError( status ) )
733  {
735  return( status );
736  }
737  bufPtr += outputBytes;
738 
739  /* Postcondition: We're filling the output buffer and we wrote the
740  output to the correct portion of the output buffer */
741  ENSURES( ( bufPtr > ( BYTE * ) buffer ) && \
742  ( bufPtr <= ( BYTE * ) buffer + length ) );
743  ENSURES( bufPtr == ORIGINAL_VALUE( bufPtr ) + outputBytes );
744  }
745 
746  /* Postcondition: We filled the output buffer with the required amount
747  of output */
748  ENSURES_MUTEX( bufPtr == ( BYTE * ) buffer + length );
749 
750  /* Check whether the process forked while we were generating output. If
751  it did, force a complete remix of the pool and restart the output
752  generation process (the fast poll will ensure that the pools in the
753  parent and child differ) */
754  if( checkForked() )
755  {
756  randomInfo->randomPoolMixes = 0;
757  bufPtr = buffer;
758  goto restartPoint;
759  }
760 
762 
763  return( CRYPT_OK );
764  }
765 
766 /****************************************************************************
767 * *
768 * Init/Shutdown Routines *
769 * *
770 ****************************************************************************/
771 
772 /* Initialise the randomness subsystem */
773 
775 int initRandomInfo( OUT_OPT_PTR TYPECAST( RANDOM_INFO ** ) void **randomInfoPtrPtr )
776  {
777  RANDOM_INFO testRandomInfo, *randomInfoPtr;
778  BYTE buffer[ 16 + 8 ];
779  int status;
780 
781  assert( isWritePtr( randomInfoPtrPtr, sizeof( void * ) ) );
782 
783  /* Clear return value */
784  *randomInfoPtrPtr = NULL;
785 
786  /* Make sure that the crypto that we need is functioning as required */
787  status = randomAlgorithmSelfTest();
788  ENSURES( cryptStatusOK( status ) );
789 
790  /* The underlying crypto is OK, check that the cryptlib PRNG is working
791  correctly */
792  initRandomPool( &testRandomInfo );
793  status = mixRandomPool( &testRandomInfo );
794  if( cryptStatusOK( status ) && \
795  memcmp( testRandomInfo.randomPool,
796  "\xF6\x8F\x30\xEE\x52\x13\x3E\x40\x06\x06\xA6\xBE\x91\xD2\xD9\x82", 16 ) )
797  status = CRYPT_ERROR_FAILED;
798  if( cryptStatusOK( status ) )
799  status = mixRandomPool( &testRandomInfo );
800  if( cryptStatusOK( status ) && \
801  memcmp( testRandomInfo.randomPool,
802  "\xAE\x94\x3B\xF2\x86\x5F\xCF\x76\x36\x2B\x80\xD5\x73\x86\x9B\x69", 16 ) )
803  status = CRYPT_ERROR_FAILED;
804  if( cryptStatusOK( status ) )
805  status = mixRandomPool( &testRandomInfo );
806  if( cryptStatusOK( status ) && \
807  memcmp( testRandomInfo.randomPool,
808  "\xBC\x2D\xC1\x03\x8C\x78\x6D\x04\xA8\xBD\xD5\x51\x80\xCA\x42\xF4", 16 ) )
809  status = CRYPT_ERROR_FAILED;
810  if( cryptStatusError( status ) )
811  {
812  endRandomPool( &testRandomInfo );
813  retIntError();
814  }
815 
816  /* Check that the ANSI X9.17 PRNG is working correctly */
817  status = selfTestX917( &testRandomInfo, testRandomInfo.randomPool );
818  if( cryptStatusError( status ) )
819  {
820  endRandomPool( &testRandomInfo );
821  retIntError();
822  }
823 
824  /* The underlying PRNGs are OK, check the overall random number
825  generation system. Since we started with an all-zero seed we have
826  to fake the entropy-quality values for the artificial test pool */
827  testRandomInfo.randomQuality = 100;
828  testRandomInfo.randomPoolMixes = RANDOMPOOL_MIXES;
829  status = getRandomOutput( &testRandomInfo, buffer, 16 );
830  if( cryptStatusOK( status ) && \
831  memcmp( buffer, "\x6B\x59\x1D\xCD\xE1\xB3\xA8\x50\x32\x84\x8C\x8D\x93\xB0\x74\xD7", 16 ) )
832  status = CRYPT_ERROR_FAILED;
833  if( cryptStatusError( status ) )
834  {
835  endRandomPool( &testRandomInfo );
836  retIntError();
837  }
838  endRandomPool( &testRandomInfo );
839 
840  /* Check the ANSI X9.17 PRNG again, this time using FIPS test vectors */
841  status = fipsTestX917( &testRandomInfo );
842  if( cryptStatusError( status ) )
843  {
844  endRandomPool( &testRandomInfo );
845  retIntError();
846  }
847 
848  /* Allocate and initialise the random pool */
849  if( ( status = krnlMemalloc( ( void ** ) &randomInfoPtr, \
850  sizeof( RANDOM_INFO ) ) ) != CRYPT_OK )
851  return( status );
852  initRandomPool( randomInfoPtr );
853 
854  /* Initialise any helper routines that may be needed */
856 
857  *randomInfoPtrPtr = randomInfoPtr;
858  return( CRYPT_OK );
859  }
860 
861 /* Shut down the randomness subsystem. Exactly what to do if we can't
862  exit the polling thread or acquire the mutex is a bit complicated, this
863  is a shouldn't-occur exception condition condition so it's not even
864  possible to plan for this since it's uncertain under which conditions (if
865  ever) this situation would occur. We can't even perform a failsafe
866  zeroise of the pool data because it could lead to the other thread using
867  an all-zero key from the unexpectedly-cleared pool. For now we play it
868  by the book and don't do anything if we can't exit the thread or acquire
869  the mutex, which avoids a segfault from pulling the random data out from
870  underneath the other thread */
871 
872 STDC_NONNULL_ARG( ( 1 ) ) \
873 void endRandomInfo( INOUT TYPECAST( RANDOM_INFO ** ) void **randomInfoPtrPtr )
874  {
875  RANDOM_INFO *randomInfoPtr = *randomInfoPtrPtr;
876  int status;
877 
878  assert( isWritePtr( randomInfoPtrPtr, sizeof( void * ) ) );
879  assert( isWritePtr( *randomInfoPtrPtr, sizeof( RANDOM_INFO ) ) );
880 
881  /* Make sure that there are no background threads/processes still trying
882  to send us data */
883  status = waitforRandomCompletion( TRUE );
884  ENSURES_V( cryptStatusOK( status ) ); /* See comment above */
885 
886  /* Call any special-case shutdown functions */
888 
889  /* Shut down the random data pool. We acquire the randomness mutex
890  while we're doing this to ensure that any threads still using the
891  randomness info have exited before we destroy it */
892  status = krnlEnterMutex( MUTEX_RANDOM );
893  ENSURES_V( cryptStatusOK( status ) ); /* See comment above */
894  endRandomPool( randomInfoPtr );
896  status = krnlMemfree( randomInfoPtrPtr );
897  ENSURES_V( cryptStatusOK( status ) ); /* See comment above */
898  }
899 
900 /****************************************************************************
901 * *
902 * Add Random (Entropy) Data *
903 * *
904 ****************************************************************************/
905 
906 /* Add new entropy data and an entropy quality estimate to the random pool */
907 
908 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
909 int addEntropyData( INOUT TYPECAST( RANDOM_INFO * ) void *randomInfoPtr,
910  IN_BUFFER( length ) const void *buffer,
911  IN_LENGTH const int length )
912  {
913  RANDOM_INFO *randomInfo = ( RANDOM_INFO * ) randomInfoPtr;
914  const BYTE *bufPtr = ( BYTE * ) buffer;
915  int count, status;
916 #if 0 /* See comment in addEntropyQuality */
917  DECLARE_ORIGINAL_INT( entropyByteCount );
918 #endif /* 0 */
919 
920  assert( isWritePtr( randomInfo, sizeof( RANDOM_INFO ) ) );
921  assert( isReadPtr( buffer, length ) );
922 
923  REQUIRES( length > 0 && length < MAX_INTLENGTH );
924 
925  status = krnlEnterMutex( MUTEX_RANDOM );
926  if( cryptStatusError( status ) )
927  return( status );
928  REQUIRES_MUTEX( sanityCheck( randomInfo ) );
929 
930 #if 0 /* See comment in addEntropyQuality */
931  STORE_ORIGINAL_INT( entropyByteCount, randomInfo->entropyByteCount );
932 #endif /* 0 */
933 
934  /* Mix the incoming data into the pool. This operation is resistant to
935  chosen- and known-input attacks because the pool contents are unknown
936  to an attacker so XORing in known data won't help them. If an
937  attacker could determine pool contents by observing the generator
938  output (which is defeated by the postprocessing) we'd have to perform
939  an extra input mixing operation to defeat these attacks */
940  for( count = 0; count < length; count++ )
941  {
942  ORIGINAL_INT_VAR( bufVal, bufPtr[ count ] );
943  DECLARE_ORIGINAL_INT( poolVal );
944  DECLARE_ORIGINAL_INT( newPoolVal );
945  DECLARE_ORIGINAL_INT( poolPos );
946 
947  /* If the pool write position has reached the end of the pool, mix
948  the pool */
949  if( randomInfo->randomPoolPos >= RANDOMPOOL_SIZE )
950  {
951  status = mixRandomPool( randomInfo );
952  if( cryptStatusError( status ) )
953  {
955  return( status );
956  }
957  ENSURES_MUTEX( randomInfo->randomPoolPos == 0 );
958  }
959 
960  STORE_ORIGINAL_INT( poolVal,
961  randomInfo->randomPool[ randomInfo->randomPoolPos ] );
962  STORE_ORIGINAL_INT( poolPos, randomInfo->randomPoolPos );
963 
964  /* Precondition: We're adding data inside the pool */
965  REQUIRES_MUTEX( randomInfo->randomPoolPos >= 0 && \
966  randomInfo->randomPoolPos < RANDOMPOOL_SIZE );
967 
968  randomInfo->randomPool[ randomInfo->randomPoolPos++ ] ^= bufPtr[ count ];
969 
970  STORE_ORIGINAL_INT( newPoolVal,
971  randomInfo->randomPool[ randomInfo->randomPoolPos - 1 ] );
972 
973  /* Postcondition: We've updated the byte at the current pool
974  position, and the value really was XORed into the pool rather
975  than (for example) overwriting it as with PGP/xorbytes or
976  GPG/add_randomness. Note that in this case we can use a non-XOR
977  operation to check that the XOR succeeded, unlike the pool mixing
978  code which requires an XOR to check the original XOR */
979  ENSURES( randomInfo->randomPoolPos == \
980  ORIGINAL_VALUE( poolPos ) + 1 );
981  ENSURES( ( ( ORIGINAL_VALUE( newPoolVal ) == \
982  ORIGINAL_VALUE( bufVal ) ) && \
983  ( ORIGINAL_VALUE( poolVal ) == 0 ) ) || \
984  ( ORIGINAL_VALUE( newPoolVal ) != \
985  ORIGINAL_VALUE( bufVal ) ) );
986  }
987 
988 #if 0 /* See comment in addEntropyQuality */
989  /* Remember how many bytes of entropy we added on this update */
990  randomInfo->entropyByteCount += length;
991 #endif /* 0 */
992 
993  /* Postcondition: We processed all of the data */
994  ENSURES( count == length );
995 #if 0 /* See comment in addEntropyQuality */
996  ENSURES( randomInfo->entropyByteCount == \
997  ORIGINAL_VALUE( entropyByteCount ) + length );
998 #endif /* 0 */
999 
1000  ENSURES_MUTEX( sanityCheck( randomInfo ) );
1001 
1003 
1004  return( CRYPT_OK );
1005  }
1006 
1007 CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1008 int addEntropyQuality( INOUT TYPECAST( RANDOM_INFO * ) void *randomInfoPtr,
1009  IN_RANGE( 1, 100 ) const int quality )
1010  {
1011  RANDOM_INFO *randomInfo = ( RANDOM_INFO * ) randomInfoPtr;
1012  int status;
1013 
1014  assert( isWritePtr( randomInfo, sizeof( RANDOM_INFO ) ) );
1015 
1016  REQUIRES( quality > 0 && quality <= 100 );
1017 
1018  status = krnlEnterMutex( MUTEX_RANDOM );
1019  if( cryptStatusError( status ) )
1020  return( status );
1021  REQUIRES_MUTEX( sanityCheck( randomInfo ) );
1022 
1023  /* In theory we could check to ensure that the claimed entropy quality
1024  corresponds approximately to the amount of entropy data added,
1025  however in a multithreaded environment this doesn't work because the
1026  entropy addition is distinct from the entropy quality addition so
1027  that (for example) with entropy being added by three threads we could
1028  end up with the following:
1029 
1030  entropy1, entropy1,
1031  entropy2,
1032  entropy1,
1033  entropy3,
1034  entropy1,
1035  entropy3,
1036  entropy2,
1037  quality2, reset to 0
1038  quality1, fail since reset to 0
1039  quality3, fail since reset to 0
1040 
1041  This means that the first entropy quality measure added is applied
1042  to all of the previously added entropy after which the entropy byte
1043  count is reset, causing subsequent attempts to add entropy quality to
1044  fail. In addition the first quality value is applied to all of the
1045  entropy added until that point rather than just the specific entropy
1046  samples that it corresponds to. In theory this could be addressed by
1047  requiring the entropy source to treat entropy addition as a
1048  database-style BEGIN ... COMMIT transaction but this makes the
1049  interface excessively complex for both source and sink, and more
1050  prone to error than the small gain in entropy quality-checking is
1051  worth */
1052 #if 0
1053  if( randomInfo->entropyByteCount <= 0 || \
1054  quality / 2 > randomInfo->entropyByteCount )
1055  {
1056  /* If there's not enough entropy data present to justify the
1057  claimed entropy quality level, signal an error. We do however
1058  retain the existing entropy byte count for use the next time an
1059  entropy quality estimate is added, since it's still contributing
1060  to the total entropy quality */
1062  retIntError();
1063  }
1064  randomInfo->entropyByteCount = 0;
1065 #endif /* 0 */
1066 
1067  /* If we haven't reached the minimum quality level for generating keys
1068  yet, update the quality level */
1069  if( randomInfo->randomQuality < 100 )
1070  {
1071  /* Update the quality count, making sure that it stays within
1072  bounds */
1073  if( randomInfo->randomQuality + quality > 100 )
1074  randomInfo->randomQuality = 100;
1075  else
1076  randomInfo->randomQuality += quality;
1077  }
1078 
1079  ENSURES_MUTEX( sanityCheck( randomInfo ) );
1080 
1082 
1083  return( CRYPT_OK );
1084  }
1085 
1086 #ifdef CONFIG_RANDSEED
1087 
1088 /* Add entropy data from a stored seed value */
1089 
1090 STDC_NONNULL_ARG( ( 1 ) ) \
1091 static void addStoredSeedData( INOUT RANDOM_INFO *randomInfo )
1092  {
1093  STREAM stream;
1094  BYTE streamBuffer[ STREAM_BUFSIZE + 8 ], seedBuffer[ 1024 + 8 ];
1095  char seedFilePath[ MAX_PATH_LENGTH + 8 ];
1096  int seedFilePathLen, poolCount, length, status;
1097 
1098  assert( isWritePtr( randomInfo, sizeof( RANDOM_INFO ) ) );
1099 
1100  /* Try and access the stored seed data */
1101  status = fileBuildCryptlibPath( seedFilePath, MAX_PATH_LENGTH,
1102  &seedFilePathLen, NULL, 0,
1104  if( cryptStatusOK( status ) )
1105  {
1106  /* The file path functions are normally used with krnlSendMessage()
1107  which takes { data, length } parameters, since we've calling
1108  the low-level function sFileOpen() directly we have to null-
1109  terminate the string */
1110  seedFilePath[ seedFilePathLen ] = '\0';
1111  status = sFileOpen( &stream, seedFilePath, FILE_FLAG_READ );
1112  }
1113  if( cryptStatusError( status ) )
1114  {
1115  /* The seed data isn't present, don't try and access it again */
1116  randomInfo->seedProcessed = TRUE;
1117  DEBUG_DIAG(( "Error opening random seed file" ));
1118  assert( DEBUG_WARN );
1119  return;
1120  }
1121 
1122  /* Read up to 1K of data from the stored seed */
1123  sioctlSetString( &stream, STREAM_IOCTL_IOBUFFER, streamBuffer,
1124  STREAM_BUFSIZE );
1125  sioctlSet( &stream, STREAM_IOCTL_PARTIALREAD, TRUE );
1126  status = length = sread( &stream, seedBuffer, 1024 );
1127  sFileClose( &stream );
1128  zeroise( streamBuffer, STREAM_BUFSIZE );
1129  if( cryptStatusError( status ) || length <= 16 )
1130  {
1131  /* The seed data is present but we can't read it or there's not
1132  enough present to use, don't try and access it again */
1133  randomInfo->seedProcessed = TRUE;
1134  DEBUG_DIAG(( "Error reading random seed file" ));
1135  assert( DEBUG_WARN );
1136  return;
1137  }
1138  ENSURES_V( length >= 16 && length <= 1024 );
1139  randomInfo->seedSize = length;
1140 
1141  /* Precondition: We got at least some non-zero data */
1142  EXISTS( i, 0, length,
1143  seedBuffer[ i ] != 0 );
1144 
1145  /* Add the seed data to the entropy pool. Both because the entropy-
1146  management code gets suspicious about very small amounts of data with
1147  claimed high entropy and because it's a good idea to start with all
1148  of the pool set to the seed data (rather than most of it set at zero
1149  if the seed data is short), we add the seed data repeatedly until
1150  we've filled the pool */
1151  for( poolCount = RANDOMPOOL_SIZE; poolCount > 0; poolCount -= length )
1152  {
1153  status = addEntropyData( randomInfo, seedBuffer, length );
1154  assert( cryptStatusOK( status ) );
1155  }
1156 
1157  /* There were at least 128 bits of entropy present in the seed, set the
1158  entropy quality to the user-provided value */
1159  status = addEntropyQuality( randomInfo, CONFIG_RANDSEED_QUALITY );
1160  assert( cryptStatusOK( status ) );
1161 
1162  zeroise( seedBuffer, 1024 );
1163 
1164  /* Postcondition: Nulla vestigia retrorsum */
1165  FORALL( i, 0, 1024,
1166  seedBuffer[ i ] == 0 );
1167  }
1168 #endif /* CONFIG_RANDSEED */
1169 
1170 /****************************************************************************
1171 * *
1172 * Random Pool External Interface *
1173 * *
1174 ****************************************************************************/
1175 
1176 /* Convenience functions used by the system-specific randomness-polling
1177  routines to send data to the system device. These just accumulate as
1178  close to bufSize bytes of data as possible in a user-provided buffer and
1179  then forward them to the device object. Note that addRandomData()
1180  assumes that the quantity of data being added is small (a fixed-size
1181  struct or something similar), it shouldn't be used to add large buffers
1182  full of data since information at the end of the buffer will be lost */
1183 
1184 typedef struct {
1185  BUFFER( bufSize, bufPos ) \
1186  void *buffer; /* Entropy buffer */
1187  int bufPos, bufSize; /* Current buffer pos.and total size */
1188  int updateStatus; /* Error status if update failed */
1190 
1191 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
1192 int initRandomData( INOUT TYPECAST( RANDOM_STATE_INFO * ) void *statePtr,
1193  IN_BUFFER( maxSize ) void *buffer,
1194  IN_LENGTH_SHORT_MIN( 16 ) const int maxSize )
1195  {
1196  RANDOM_STATE_INFO *state = ( RANDOM_STATE_INFO * ) statePtr;
1197 
1198  assert( isWritePtr( state, sizeof( RANDOM_STATE_INFO ) ) );
1199  assert( isWritePtr( buffer, maxSize ) );
1200 
1201  static_assert( sizeof( RANDOM_STATE_INFO ) <= sizeof( RANDOM_STATE ),
1202  "Random pool state size" );
1203 
1204  REQUIRES( maxSize >= 16 && maxSize < MAX_INTLENGTH_SHORT );
1205 
1206  memset( state, 0, sizeof( RANDOM_STATE_INFO ) );
1207  state->buffer = buffer;
1208  state->bufSize = maxSize;
1209 
1210  return( CRYPT_OK );
1211  }
1212 
1213 RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
1214 int addRandomData( INOUT TYPECAST( RANDOM_STATE_INFO * ) void *statePtr,
1215  IN_BUFFER( valueLength ) const void *value,
1216  IN_LENGTH_SHORT const int valueLength )
1217  {
1218  RANDOM_STATE_INFO *state = ( RANDOM_STATE_INFO * ) statePtr;
1220  const BYTE *valuePtr = value;
1221  int bytesToCopy = min( valueLength, state->bufSize - state->bufPos );
1222  int totalLength = valueLength, status;
1223 
1224  assert( isWritePtr( state, sizeof( RANDOM_STATE_INFO ) ) );
1225  assert( isReadPtr( value, valueLength ) );
1226 
1227  REQUIRES( state->bufSize >= 16 && state->bufSize < MAX_INTLENGTH_SHORT );
1228  REQUIRES( state->bufPos >= 0 && state->bufPos <= state->bufSize );
1229  REQUIRES( valueLength > 0 && valueLength < MAX_INTLENGTH_SHORT );
1230 
1231  /* If we're in an error state, don't try and do anything */
1232  if( cryptStatusError( state->updateStatus ) )
1233  return( state->updateStatus );
1234 
1235  /* Copy as much of the input as we can into the accumulator */
1236  if( bytesToCopy > 0 )
1237  {
1238  ENSURES( state->bufPos + bytesToCopy <= state->bufSize );
1239 
1240  ANALYSER_HINT( bytesToCopy > 0 && bytesToCopy <= valueLength );
1241 
1242  memcpy( ( BYTE * ) state->buffer + state->bufPos, valuePtr, bytesToCopy );
1243  state->bufPos += bytesToCopy;
1244  valuePtr += bytesToCopy;
1245  totalLength -= bytesToCopy;
1246  }
1247  ENSURES( totalLength >= 0 && totalLength < MAX_INTLENGTH_SHORT );
1248 
1249  /* If everything went into the accumulator, we're done */
1250  if( state->bufPos < state->bufSize )
1251  return( CRYPT_OK );
1252 
1253  ENSURES( state->bufPos == state->bufSize );
1254 
1255  /* The accumulator is full, send the data through to the system device */
1256  setMessageData( &msgData, state->buffer, state->bufPos );
1258  &msgData, CRYPT_IATTRIBUTE_ENTROPY );
1259  if( cryptStatusError( status ) )
1260  {
1261  /* There was a problem moving the data through, make the error status
1262  persistent. Normally this is a should-never-occur error
1263  condition but if cryptlib has been shut down from another thread
1264  then the kernel will fail all non shutdown-related calls with a
1265  permission error. To avoid false alarms we mask out failures due
1266  to permission errors */
1267  state->updateStatus = status;
1268  assert( ( status == CRYPT_ERROR_PERMISSION ) || DEBUG_WARN );
1269  return( status );
1270  }
1271  state->bufPos = 0;
1272 
1273  /* If we've consumed all of the data, we're done */
1274  if( totalLength <= 0 )
1275  return( CRYPT_OK );
1276 
1277  /* There's uncopied data left, copy it in now. If there's more data
1278  present than can fit in the accumulator's buffer we discard it
1279  (although we warn in the debug build, which is why the code below
1280  has an assert() rather than a REQUIRES()), the caller should be
1281  sending quantities this large directly rather than using the
1282  addRandomData() interface */
1283  assert( totalLength < state->bufSize ); /* Debug warning only */
1284  bytesToCopy = min( totalLength, state->bufSize );
1285  memcpy( state->buffer, valuePtr, bytesToCopy );
1286  state->bufPos += bytesToCopy;
1287 
1288  return( CRYPT_OK );
1289  }
1290 
1291 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1292 int addRandomLong( INOUT void *statePtr, const long value )
1293  {
1294  return( addRandomData( statePtr, &value, sizeof( long ) ) );
1295  }
1296 
1297 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1298 int endRandomData( INOUT void *statePtr, \
1299  IN_RANGE( 0, 100 ) const int quality )
1300  {
1301  RANDOM_STATE_INFO *state = ( RANDOM_STATE_INFO * ) statePtr;
1302  int status = state->updateStatus;
1303 
1304  assert( isWritePtr( state, sizeof( RANDOM_STATE_INFO ) ) );
1305 
1306  REQUIRES( state->bufSize >= 16 && state->bufSize < MAX_INTLENGTH_SHORT );
1307  REQUIRES( state->bufPos >= 0 && state->bufPos <= state->bufSize );
1308  REQUIRES( quality >= 0 && quality <= 100 );
1309 
1310  /* If we're in an error state, don't try and do anything */
1311  if( cryptStatusError( state->updateStatus ) )
1312  return( state->updateStatus );
1313 
1314  /* If there's data still in the accumulator send it through to the
1315  system device. A failure at this point is a should-never-occur
1316  condition but if cryptlib has been shut down from another thread then
1317  the kernel will fail all non shutdown-related calls with a permission
1318  error. To avoid false alarms we mask out failures due to permission
1319  errors */
1320  if( state->bufPos > 0 )
1321  {
1323 
1324  setMessageData( &msgData, state->buffer, state->bufPos );
1326  IMESSAGE_SETATTRIBUTE_S, &msgData,
1327  CRYPT_IATTRIBUTE_ENTROPY );
1328  }
1329  assert( cryptStatusOK( status ) || ( status == CRYPT_ERROR_PERMISSION ) );
1330 
1331  /* If everything went OK, set the quality estimate for the data that
1332  we've added */
1333  if( cryptStatusOK( status ) && quality > 0 )
1334  {
1336  ( MESSAGE_CAST ) &quality,
1337  CRYPT_IATTRIBUTE_ENTROPY_QUALITY );
1338  }
1339  assert( cryptStatusOK( status ) || ( status == CRYPT_ERROR_PERMISSION ) );
1340 
1341  /* Clear the accumulator and exit */
1342  zeroise( state->buffer, state->bufSize );
1343  zeroise( state, sizeof( RANDOM_STATE_INFO ) );
1344  return( status );
1345  }