Debian Codegraph @

simulator/ms-tpm-20-ref/TPMCmd/tpm/src/crypt/CryptRand.c

raw
1 /* Microsoft Reference Implementation for TPM 2.0
2 *
3 * The copyright in this software is being made available under the BSD License,
4 * included below. This software may be subject to other third party and
5 * contributor rights, including patent rights, and no such rights are granted
6 * under this license.
7 *
8 * Copyright (c) Microsoft Corporation
9 *
10 * All rights reserved.
11 *
12 * BSD License
13 *
14 * Redistribution and use in source and binary forms, with or without modification,
15 * are permitted provided that the following conditions are met:
16 *
17 * Redistributions of source code must retain the above copyright notice, this list
18 * of conditions and the following disclaimer.
19 *
20 * Redistributions in binary form must reproduce the above copyright notice, this
21 * list of conditions and the following disclaimer in the documentation and/or
22 * other materials provided with the distribution.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS""
25 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
28 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
29 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
31 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 */
35 //** Introduction
36 // This file implements a DRBG with a behavior according to SP800-90A using
37 // a block cypher. This is also compliant to ISO/IEC 18031:2011(E) C.3.2.
38 //
39 // A state structure is created for use by TPM.lib and functions
40 // within the CryptoEngine my use their own state structures when they need to have
41 // deterministic values.
42 //
43 // A debug mode is available that allows the random numbers generated for TPM.lib
44 // to be repeated during runs of the simulator. The switch for it is in
45 // TpmBuildSwitches.h. It is USE_DEBUG_RNG.
46 //
47 //
48 // This is the implementation layer of CTR DRGB mechanism as defined in SP800-90A
49 // and the functions are organized as closely as practical to the organization in
50 // SP800-90A. It is intended to be compiled as a separate module that is linked
51 // with a secure application so that both reside inside the same boundary
52 // [SP 800-90A 8.5]. The secure application in particular manages the accesses
53 // protected storage for the state of the DRBG instantiations, and supplies the
54 // implementation functions here with a valid pointer to the working state of the
55 // given instantiations (as a DRBG_STATE structure).
56 //
57 // This DRBG mechanism implementation does not support prediction resistance. Thus
58 // 'prediction_resistance_flag' is omitted from Instantiate_function(),
59 // Reseed_function(), Generate_function() argument lists [SP 800-90A 9.1, 9.2,
60 // 9.3], as well as from the working state data structure DRBG_STATE [SP 800-90A
61 // 9.1].
62 //
63 // This DRBG mechanism implementation always uses the highest security strength of
64 // available in the block ciphers. Thus 'requested_security_strength' parameter is
65 // omitted from Instantiate_function() and Generate_function() argument lists
66 // [SP 800-90A 9.1, 9.2, 9.3], as well as from the working state data structure
67 // DRBG_STATE [SP 800-90A 9.1].
68 //
69 // Internal functions (ones without Crypt prefix) expect validated arguments and
70 // therefore use assertions instead of runtime parameter checks and mostly return
71 // void instead of a status value.
72
73 #include "Tpm.h"
74
75 // Pull in the test vector definitions and define the space
76 #include "PRNG_TestVectors.h"
77
78 const BYTE DRBG_NistTestVector_Entropy[] = {DRBG_TEST_INITIATE_ENTROPY};
79 const BYTE DRBG_NistTestVector_GeneratedInterm[] =
80 {DRBG_TEST_GENERATED_INTERM};
81
82 const BYTE DRBG_NistTestVector_EntropyReseed[] =
83 {DRBG_TEST_RESEED_ENTROPY};
84 const BYTE DRBG_NistTestVector_Generated[] = {DRBG_TEST_GENERATED};
85
86 //** Derivation Functions
87 //*** Description
88 // The functions in this section are used to reduce the personalization input values
89 // to make them usable as input for reseeding and instantiation. The overall
90 // behavior is intended to produce the same results as described in SP800-90A,
91 // section 10.4.2 "Derivation Function Using a Block Cipher Algorithm
92 // (Block_Cipher_df)." The code is broken into several subroutines to deal with the
93 // fact that the data used for personalization may come in several separate blocks
94 // such as a Template hash and a proof value and a primary seed.
95
96 //*** Derivation Function Defines and Structures
97
98 #define DF_COUNT (DRBG_KEY_SIZE_WORDS / DRBG_IV_SIZE_WORDS + 1)
99 #if DRBG_KEY_SIZE_BITS != 128 && DRBG_KEY_SIZE_BITS != 256
100 # error "CryptRand.c only written for AES with 128- or 256-bit keys."
101 #endif
102
103 typedef struct
104 {
105 DRBG_KEY_SCHEDULE keySchedule;
106 DRBG_IV iv[DF_COUNT];
107 DRBG_IV out1;
108 DRBG_IV buf;
109 int contents;
110 } DF_STATE, *PDF_STATE;
111
112 //*** DfCompute()
113 // This function does the incremental update of the derivation function state. It
114 // encrypts the 'iv' value and XOR's the results into each of the blocks of the
115 // output. This is equivalent to processing all of input data for each output block.
116 static void
117 DfCompute(
118 PDF_STATE dfState
119 )
120 {
121 int i;
122 int iv;
123 crypt_uword_t *pIv;
124 crypt_uword_t temp[DRBG_IV_SIZE_WORDS] = {0};
125 //
126 for(iv = 0; iv < DF_COUNT; iv++)
127 {
128 pIv = (crypt_uword_t *)&dfState->iv[iv].words[0];
129 for(i = 0; i < DRBG_IV_SIZE_WORDS; i++)
130 {
131 temp[i] ^= pIv[i] ^ dfState->buf.words[i];
132 }
133 DRBG_ENCRYPT(&dfState->keySchedule, &temp, pIv);
134 }
135 for(i = 0; i < DRBG_IV_SIZE_WORDS; i++)
136 dfState->buf.words[i] = 0;
137 dfState->contents = 0;
138 }
139
140 //*** DfStart()
141 // This initializes the output blocks with an encrypted counter value and
142 // initializes the key schedule.
143 static void
144 DfStart(
145 PDF_STATE dfState,
146 uint32_t inputLength
147 )
148 {
149 BYTE init[8];
150 int i;
151 UINT32 drbgSeedSize = sizeof(DRBG_SEED);
152
153 const BYTE dfKey[DRBG_KEY_SIZE_BYTES] = {
154 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
155 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
156 #if DRBG_KEY_SIZE_BYTES > 16
157 ,0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
158 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
159 #endif
160 };
161 memset(dfState, 0, sizeof(DF_STATE));
162 DRBG_ENCRYPT_SETUP(&dfKey[0], DRBG_KEY_SIZE_BITS, &dfState->keySchedule);
163 // Create the first chaining values
164 for(i = 0; i < DF_COUNT; i++)
165 ((BYTE *)&dfState->iv[i])[3] = (BYTE)i;
166 DfCompute(dfState);
167 // initialize the first 64 bits of the IV in a way that doesn't depend
168 // on the size of the words used.
169 UINT32_TO_BYTE_ARRAY(inputLength, init);
170 UINT32_TO_BYTE_ARRAY(drbgSeedSize, &init[4]);
171 memcpy(&dfState->iv[0], init, 8);
172 dfState->contents = 4;
173 }
174
175 //*** DfUpdate()
176 // This updates the state with the input data. A byte at a time is moved into the
177 // state buffer until it is full and then that block is encrypted by DfCompute().
178 static void
179 DfUpdate(
180 PDF_STATE dfState,
181 int size,
182 const BYTE *data
183 )
184 {
185 while(size > 0)
186 {
187 int toFill = DRBG_IV_SIZE_BYTES - dfState->contents;
188 if(size < toFill)
189 toFill = size;
190 // Copy as many bytes as there are or until the state buffer is full
191 memcpy(&dfState->buf.bytes[dfState->contents], data, toFill);
192 // Reduce the size left by the amount copied
193 size -= toFill;
194 // Advance the data pointer by the amount copied
195 data += toFill;
196 // increase the buffer contents count by the amount copied
197 dfState->contents += toFill;
198 pAssert(dfState->contents <= DRBG_IV_SIZE_BYTES);
199 // If we have a full buffer, do a computation pass.
200 if(dfState->contents == DRBG_IV_SIZE_BYTES)
201 DfCompute(dfState);
202 }
203 }
204
205 //*** DfEnd()
206 // This function is called to get the result of the derivation function computation.
207 // If the buffer is not full, it is padded with zeros. The output buffer is
208 // structured to be the same as a DRBG_SEED value so that the function can return
209 // a pointer to the DRBG_SEED value in the DF_STATE structure.
210 static DRBG_SEED *
211 DfEnd(
212 PDF_STATE dfState
213 )
214 {
215 // Since DfCompute is always called when a buffer is full, there is always
216 // space in the buffer for the terminator
217 dfState->buf.bytes[dfState->contents++] = 0x80;
218 // If the buffer is not full, pad with zeros
219 while(dfState->contents < DRBG_IV_SIZE_BYTES)
220 dfState->buf.bytes[dfState->contents++] = 0;
221 // Do a final state update
222 DfCompute(dfState);
223 return (DRBG_SEED *)&dfState->iv;
224 }
225
226 //*** DfBuffer()
227 // Function to take an input buffer and do the derivation function to produce a
228 // DRBG_SEED value that can be used in DRBG_Reseed();
229 static DRBG_SEED *
230 DfBuffer(
231 DRBG_SEED *output, // OUT: receives the result
232 int size, // IN: size of the buffer to add
233 BYTE *buf // IN: address of the buffer
234 )
235 {
236 DF_STATE dfState;
237 if(size == 0 || buf == NULL)
238 return NULL;
239 // Initialize the derivation function
240 DfStart(&dfState, size);
241 DfUpdate(&dfState, size, buf);
242 DfEnd(&dfState);
243 memcpy(output, &dfState.iv[0], sizeof(DRBG_SEED));
244 return output;
245 }
246
247 //*** DRBG_GetEntropy()
248 // Even though this implementation never fails, it may get blocked
249 // indefinitely long in the call to get entropy from the platform
250 // (DRBG_GetEntropy32()).
251 // This function is only used during instantiation of the DRBG for
252 // manufacturing and on each start-up after an non-orderly shutdown.
253 // Return Type: BOOL
254 // TRUE(1) requested entropy returned
255 // FALSE(0) entropy Failure
256 BOOL
257 DRBG_GetEntropy(
258 UINT32 requiredEntropy, // IN: requested number of bytes of full
259 // entropy
260 BYTE *entropy // OUT: buffer to return collected entropy
261 )
262 {
263 #if !USE_DEBUG_RNG
264
265 UINT32 obtainedEntropy;
266 INT32 returnedEntropy;
267
268 // If in debug mode, always use the self-test values for initialization
269 if(IsSelfTest())
270 {
271 #endif
272 // If doing simulated DRBG, then check to see if the
273 // entropyFailure condition is being tested
274 if(!IsEntropyBad())
275 {
276 // In self-test, the caller should be asking for exactly the seed
277 // size of entropy.
278 pAssert(requiredEntropy == sizeof(DRBG_NistTestVector_Entropy));
279 memcpy(entropy, DRBG_NistTestVector_Entropy,
280 sizeof(DRBG_NistTestVector_Entropy));
281 }
282 #if !USE_DEBUG_RNG
283 }
284 else if(!IsEntropyBad())
285 {
286 // Collect entropy
287 // Note: In debug mode, the only "entropy" value ever returned
288 // is the value of the self-test vector.
289 for(returnedEntropy = 1, obtainedEntropy = 0;
290 obtainedEntropy < requiredEntropy && !IsEntropyBad();
291 obtainedEntropy += returnedEntropy)
292 {
293 returnedEntropy = _plat__GetEntropy(&entropy[obtainedEntropy],
294 requiredEntropy - obtainedEntropy);
295 if(returnedEntropy <= 0)
296 SetEntropyBad();
297 }
298 }
299 #endif
300 return !IsEntropyBad();
301 }
302
303 //*** IncrementIv()
304 // This function increments the IV value by 1. It is used by EncryptDRBG().
305 void
306 IncrementIv(
307 DRBG_IV *iv
308 )
309 {
310 BYTE *ivP = ((BYTE *)iv) + DRBG_IV_SIZE_BYTES;
311 while((--ivP >= (BYTE *)iv) && ((*ivP = ((*ivP + 1) & 0xFF)) == 0));
312 }
313
314 //*** EncryptDRBG()
315 // This does the encryption operation for the DRBG. It will encrypt
316 // the input state counter (IV) using the state key. Into the output
317 // buffer for as many times as it takes to generate the required
318 // number of bytes.
319 static BOOL
320 EncryptDRBG(
321 BYTE *dOut,
322 UINT32 dOutBytes,
323 DRBG_KEY_SCHEDULE *keySchedule,
324 DRBG_IV *iv,
325 UINT32 *lastValue // Points to the last output value
326 )
327 {
328 #if FIPS_COMPLIANT
329 // For FIPS compliance, the DRBG has to do a continuous self-test to make sure that
330 // no two consecutive values are the same. This overhead is not incurred if the TPM
331 // is not required to be FIPS compliant
332 //
333 UINT32 temp[DRBG_IV_SIZE_BYTES / sizeof(UINT32)];
334 int i;
335 BYTE *p;
336
337 for(; dOutBytes > 0;)
338 {
339 // Increment the IV before each encryption (this is what makes this
340 // different from normal counter-mode encryption
341 IncrementIv(iv);
342 DRBG_ENCRYPT(keySchedule, iv, temp);
343 // Expect a 16 byte block
344 #if DRBG_IV_SIZE_BITS != 128
345 #error "Unsuppored IV size in DRBG"
346 #endif
347 if((lastValue[0] == temp[0])
348 && (lastValue[1] == temp[1])
349 && (lastValue[2] == temp[2])
350 && (lastValue[3] == temp[3])
351 )
352 {
353 LOG_FAILURE(FATAL_ERROR_ENTROPY);
354 return FALSE;
355 }
356 lastValue[0] = temp[0];
357 lastValue[1] = temp[1];
358 lastValue[2] = temp[2];
359 lastValue[3] = temp[3];
360 i = MIN(dOutBytes, DRBG_IV_SIZE_BYTES);
361 dOutBytes -= i;
362 for(p = (BYTE *)temp; i > 0; i--)
363 *dOut++ = *p++;
364 }
365 #else // version without continuous self-test
366 NOT_REFERENCED(lastValue);
367 for(; dOutBytes >= DRBG_IV_SIZE_BYTES;
368 dOut = &dOut[DRBG_IV_SIZE_BYTES], dOutBytes -= DRBG_IV_SIZE_BYTES)
369 {
370 // Increment the IV
371 IncrementIv(iv);
372 DRBG_ENCRYPT(keySchedule, iv, dOut);
373 }
374 // If there is a partial, generate into a block-sized
375 // temp buffer and copy to the output.
376 if(dOutBytes != 0)
377 {
378 BYTE temp[DRBG_IV_SIZE_BYTES];
379 // Increment the IV
380 IncrementIv(iv);
381 DRBG_ENCRYPT(keySchedule, iv, temp);
382 memcpy(dOut, temp, dOutBytes);
383 }
384 #endif
385 return TRUE;
386 }
387
388 //*** DRBG_Update()
389 // This function performs the state update function.
390 // According to SP800-90A, a temp value is created by doing CTR mode
391 // encryption of 'providedData' and replacing the key and IV with
392 // these values. The one difference is that, with counter mode, the
393 // IV is incremented after each block is encrypted and in this
394 // operation, the counter is incremented before each block is
395 // encrypted. This function implements an 'optimized' version
396 // of the algorithm in that it does the update of the drbgState->seed
397 // in place and then 'providedData' is XORed into drbgState->seed
398 // to complete the encryption of 'providedData'. This works because
399 // the IV is the last thing that gets encrypted.
400 //
401 static BOOL
402 DRBG_Update(
403 DRBG_STATE *drbgState, // IN:OUT state to update
404 DRBG_KEY_SCHEDULE *keySchedule, // IN: the key schedule (optional)
405 DRBG_SEED *providedData // IN: additional data
406 )
407 {
408 UINT32 i;
409 BYTE *temp = (BYTE *)&drbgState->seed;
410 DRBG_KEY *key = pDRBG_KEY(&drbgState->seed);
411 DRBG_IV *iv = pDRBG_IV(&drbgState->seed);
412 DRBG_KEY_SCHEDULE localKeySchedule;
413 //
414 pAssert(drbgState->magic == DRBG_MAGIC);
415
416 // If an key schedule was not provided, make one
417 if(keySchedule == NULL)
418 {
419 if(DRBG_ENCRYPT_SETUP((BYTE *)key,
420 DRBG_KEY_SIZE_BITS, &localKeySchedule) != 0)
421 {
422 LOG_FAILURE(FATAL_ERROR_INTERNAL);
423 return FALSE;
424 }
425 keySchedule = &localKeySchedule;
426 }
427 // Encrypt the temp value
428
429 EncryptDRBG(temp, sizeof(DRBG_SEED), keySchedule, iv,
430 drbgState->lastValue);
431 if(providedData != NULL)
432 {
433 BYTE *pP = (BYTE *)providedData;
434 for(i = DRBG_SEED_SIZE_BYTES; i != 0; i--)
435 *temp++ ^= *pP++;
436 }
437 // Since temp points to the input key and IV, we are done and
438 // don't need to copy the resulting 'temp' to drbgState->seed
439 return TRUE;
440 }
441
442 //*** DRBG_Reseed()
443 // This function is used when reseeding of the DRBG is required. If
444 // entropy is provided, it is used in lieu of using hardware entropy.
445 // Note: the provided entropy must be the required size.
446 // Return Type: BOOL
447 // TRUE(1) reseed succeeded
448 // FALSE(0) reseed failed, probably due to the entropy generation
449 BOOL
450 DRBG_Reseed(
451 DRBG_STATE *drbgState, // IN: the state to update
452 DRBG_SEED *providedEntropy, // IN: entropy
453 DRBG_SEED *additionalData // IN:
454 )
455 {
456 DRBG_SEED seed;
457
458 pAssert((drbgState != NULL) && (drbgState->magic == DRBG_MAGIC));
459
460 if(providedEntropy == NULL)
461 {
462 providedEntropy = &seed;
463 if(!DRBG_GetEntropy(sizeof(DRBG_SEED), (BYTE *)providedEntropy))
464 return FALSE;
465 }
466 if(additionalData != NULL)
467 {
468 unsigned int i;
469
470 // XOR the provided data into the provided entropy
471 for(i = 0; i < sizeof(DRBG_SEED); i++)
472 ((BYTE *)providedEntropy)[i] ^= ((BYTE *)additionalData)[i];
473 }
474 DRBG_Update(drbgState, NULL, providedEntropy);
475
476 drbgState->reseedCounter = 1;
477
478 return TRUE;
479 }
480
481 //*** DRBG_SelfTest()
482 // This is run when the DRBG is instantiated and at startup
483 // Return Type: BOOL
484 // TRUE(1) test OK
485 // FALSE(0) test failed
486 BOOL
487 DRBG_SelfTest(
488 void
489 )
490 {
491 BYTE buf[sizeof(DRBG_NistTestVector_Generated)];
492 DRBG_SEED seed;
493 UINT32 i;
494 BYTE *p;
495 DRBG_STATE testState;
496 //
497 pAssert(!IsSelfTest());
498
499 SetSelfTest();
500 SetDrbgTested();
501 // Do an instantiate
502 if(!DRBG_Instantiate(&testState, 0, NULL))
503 return FALSE;
504 #if DRBG_DEBUG_PRINT
505 dbgDumpMemBlock(pDRBG_KEY(&testState), DRBG_KEY_SIZE_BYTES,
506 "Key after Instantiate");
507 dbgDumpMemBlock(pDRBG_IV(&testState), DRBG_IV_SIZE_BYTES,
508 "Value after Instantiate");
509 #endif
510 if(DRBG_Generate((RAND_STATE *)&testState, buf, sizeof(buf)) == 0)
511 return FALSE;
512 #if DRBG_DEBUG_PRINT
513 dbgDumpMemBlock(pDRBG_KEY(&testState.seed), DRBG_KEY_SIZE_BYTES,
514 "Key after 1st Generate");
515 dbgDumpMemBlock(pDRBG_IV(&testState.seed), DRBG_IV_SIZE_BYTES,
516 "Value after 1st Generate");
517 #endif
518 if(memcmp(buf, DRBG_NistTestVector_GeneratedInterm, sizeof(buf)) != 0)
519 return FALSE;
520 memcpy(seed.bytes, DRBG_NistTestVector_EntropyReseed, sizeof(seed));
521 DRBG_Reseed(&testState, &seed, NULL);
522 #if DRBG_DEBUG_PRINT
523 dbgDumpMemBlock((BYTE *)pDRBG_KEY(&testState.seed), DRBG_KEY_SIZE_BYTES,
524 "Key after 2nd Generate");
525 dbgDumpMemBlock((BYTE *)pDRBG_IV(&testState.seed), DRBG_IV_SIZE_BYTES,
526 "Value after 2nd Generate");
527 dbgDumpMemBlock(buf, sizeof(buf), "2nd Generated");
528 #endif
529 if(DRBG_Generate((RAND_STATE *)&testState, buf, sizeof(buf)) == 0)
530 return FALSE;
531 if(memcmp(buf, DRBG_NistTestVector_Generated, sizeof(buf)) != 0)
532 return FALSE;
533 ClearSelfTest();
534
535 DRBG_Uninstantiate(&testState);
536 for(p = (BYTE *)&testState, i = 0; i < sizeof(DRBG_STATE); i++)
537 {
538 if(*p++)
539 return FALSE;
540 }
541 // Simulate hardware failure to make sure that we get an error when
542 // trying to instantiate
543 SetEntropyBad();
544 if(DRBG_Instantiate(&testState, 0, NULL))
545 return FALSE;
546 ClearEntropyBad();
547
548 return TRUE;
549 }
550
551 //** Public Interface
552 //*** Description
553 // The functions in this section are the interface to the RNG. These
554 // are the functions that are used by TPM.lib.
555
556 //*** CryptRandomStir()
557 // This function is used to cause a reseed. A DRBG_SEED amount of entropy is
558 // collected from the hardware and then additional data is added.
559 // Return Type: TPM_RC
560 // TPM_RC_NO_RESULT failure of the entropy generator
561 LIB_EXPORT TPM_RC
562 CryptRandomStir(
563 UINT16 additionalDataSize,
564 BYTE *additionalData
565 )
566 {
567 #if !USE_DEBUG_RNG
568 DRBG_SEED tmpBuf;
569 DRBG_SEED dfResult;
570 //
571 // All reseed with outside data starts with a buffer full of entropy
572 if(!DRBG_GetEntropy(sizeof(tmpBuf), (BYTE *)&tmpBuf))
573 return TPM_RC_NO_RESULT;
574
575 DRBG_Reseed(&drbgDefault, &tmpBuf,
576 DfBuffer(&dfResult, additionalDataSize, additionalData));
577 drbgDefault.reseedCounter = 1;
578
579 return TPM_RC_SUCCESS;
580
581 #else
582 // If doing debug, use the input data as the initial setting for the RNG state
583 // so that the test can be reset at any time.
584 // Note: If this is called with a data size of 0 or less, nothing happens. The
585 // presumption is that, in a debug environment, the caller will have specific
586 // values for initialization, so this check is just a simple way to prevent
587 // inadvertent programming errors from screwing things up. This doesn't use an
588 // pAssert() because the non-debug version of this function will accept these
589 // parameters as meaning that there is no additionalData and only hardware
590 // entropy is used.
591 if((additionalDataSize > 0) && (additionalData != NULL))
592 {
593 memset(drbgDefault.seed.bytes, 0, sizeof(drbgDefault.seed.bytes));
594 memcpy(drbgDefault.seed.bytes, additionalData,
595 MIN(additionalDataSize, sizeof(drbgDefault.seed.bytes)));
596 }
597 drbgDefault.reseedCounter = 1;
598
599 return TPM_RC_SUCCESS;
600 #endif
601 }
602
603 //*** CryptRandomGenerate()
604 // Generate a 'randomSize' number or random bytes.
605 LIB_EXPORT UINT16
606 CryptRandomGenerate(
607 UINT16 randomSize,
608 BYTE *buffer
609 )
610 {
611 return DRBG_Generate((RAND_STATE *)&drbgDefault, buffer, randomSize);
612 }
613
614
615
616 //*** DRBG_InstantiateSeededKdf()
617 // This function is used to instantiate a KDF-based RNG. This is used for derivations.
618 // This function always returns TRUE.
619 LIB_EXPORT BOOL
620 DRBG_InstantiateSeededKdf(
621 KDF_STATE *state, // OUT: buffer to hold the state
622 TPM_ALG_ID hashAlg, // IN: hash algorithm
623 TPM_ALG_ID kdf, // IN: the KDF to use
624 TPM2B *seed, // IN: the seed to use
625 const TPM2B *label, // IN: a label for the generation process.
626 TPM2B *context, // IN: the context value
627 UINT32 limit // IN: Maximum number of bits from the KDF
628 )
629 {
630 state->magic = KDF_MAGIC;
631 state->limit = limit;
632 state->seed = seed;
633 state->hash = hashAlg;
634 state->kdf = kdf;
635 state->label = label;
636 state->context = context;
637 state->digestSize = CryptHashGetDigestSize(hashAlg);
638 state->counter = 0;
639 state->residual.t.size = 0;
640 return TRUE;
641 }
642
643 //*** DRBG_AdditionalData()
644 // Function to reseed the DRBG with additional entropy. This is normally called
645 // before computing the protection value of a primary key in the Endorsement
646 // hierarchy.
647 LIB_EXPORT void
648 DRBG_AdditionalData(
649 DRBG_STATE *drbgState, // IN:OUT state to update
650 TPM2B *additionalData // IN: value to incorporate
651 )
652 {
653 DRBG_SEED dfResult;
654 if(drbgState->magic == DRBG_MAGIC)
655 {
656 DfBuffer(&dfResult, additionalData->size, additionalData->buffer);
657 DRBG_Reseed(drbgState, &dfResult, NULL);
658 }
659 }
660
661
662 //*** DRBG_InstantiateSeeded()
663 // This function is used to instantiate a random number generator from seed values.
664 // The nominal use of this generator is to create sequences of pseudo-random
665 // numbers from a seed value.
666 // Return Type: TPM_RC
667 // TPM_RC_FAILURE DRBG self-test failure
668 LIB_EXPORT TPM_RC
669 DRBG_InstantiateSeeded(
670 DRBG_STATE *drbgState, // IN/OUT: buffer to hold the state
671 const TPM2B *seed, // IN: the seed to use
672 const TPM2B *purpose, // IN: a label for the generation process.
673 const TPM2B *name, // IN: name of the object
674 const TPM2B *additional // IN: additional data
675 )
676 {
677 DF_STATE dfState;
678 int totalInputSize;
679 // DRBG should have been tested, but...
680 if(!IsDrbgTested() && !DRBG_SelfTest())
681 {
682 LOG_FAILURE(FATAL_ERROR_SELF_TEST);
683 return TPM_RC_FAILURE;
684 }
685 // Initialize the DRBG state
686 memset(drbgState, 0, sizeof(DRBG_STATE));
687 drbgState->magic = DRBG_MAGIC;
688
689 // Size all of the values
690 totalInputSize = (seed != NULL) ? seed->size : 0;
691 totalInputSize += (purpose != NULL) ? purpose->size : 0;
692 totalInputSize += (name != NULL) ? name->size : 0;
693 totalInputSize += (additional != NULL) ? additional->size : 0;
694
695 // Initialize the derivation
696 DfStart(&dfState, totalInputSize);
697
698 // Run all the input strings through the derivation function
699 if(seed != NULL)
700 DfUpdate(&dfState, seed->size, seed->buffer);
701 if(purpose != NULL)
702 DfUpdate(&dfState, purpose->size, purpose->buffer);
703 if(name != NULL)
704 DfUpdate(&dfState, name->size, name->buffer);
705 if(additional != NULL)
706 DfUpdate(&dfState, additional->size, additional->buffer);
707
708 // Used the derivation function output as the "entropy" input. This is not
709 // how it is described in SP800-90A but this is the equivalent function
710 DRBG_Reseed(((DRBG_STATE *)drbgState), DfEnd(&dfState), NULL);
711
712 return TPM_RC_SUCCESS;
713 }
714
715 //*** CryptRandStartup()
716 // This function is called when TPM_Startup is executed. This function always returns
717 // TRUE.
718 LIB_EXPORT BOOL
719 CryptRandStartup(
720 void
721 )
722 {
723 #if ! _DRBG_STATE_SAVE
724 // If not saved in NV, re-instantiate on each startup
725 DRBG_Instantiate(&drbgDefault, 0, NULL);
726 #else
727 // If the running state is saved in NV, NV has to be loaded before it can
728 // be updated
729 if(go.drbgState.magic == DRBG_MAGIC)
730 DRBG_Reseed(&go.drbgState, NULL, NULL);
731 else
732 DRBG_Instantiate(&go.drbgState, 0, NULL);
733 #endif
734 return TRUE;
735 }
736
737 //**** CryptRandInit()
738 // This function is called when _TPM_Init is being processed.
739 // Return Type: BOOL
740 // TRUE(1) success
741 // FALSE(0) failure
742 LIB_EXPORT BOOL
743 CryptRandInit(
744 void
745 )
746 {
747 #if !USE_DEBUG_RNG
748 _plat__GetEntropy(NULL, 0);
749 #endif
750 return DRBG_SelfTest();
751 }
752
753 //*** DRBG_Generate()
754 // This function generates a random sequence according SP800-90A.
755 // If 'random' is not NULL, then 'randomSize' bytes of random values are generated.
756 // If 'random' is NULL or 'randomSize' is zero, then the function returns
757 // zero without generating any bits or updating the reseed counter.
758 // This function returns the number of bytes produced which could be less than the
759 // number requested if the request is too large ("too large" is implementation
760 // dependent.)
761 LIB_EXPORT UINT16
762 DRBG_Generate(
763 RAND_STATE *state,
764 BYTE *random, // OUT: buffer to receive the random values
765 UINT16 randomSize // IN: the number of bytes to generate
766 )
767 {
768 if(state == NULL)
769 state = (RAND_STATE *)&drbgDefault;
770 if(random == NULL)
771 return 0;
772
773 // If the caller used a KDF state, generate a sequence from the KDF not to
774 // exceed the limit.
775 if(state->kdf.magic == KDF_MAGIC)
776 {
777 KDF_STATE *kdf = (KDF_STATE *)state;
778 UINT32 counter = (UINT32)kdf->counter;
779 INT32 bytesLeft = randomSize;
780 //
781 // If the number of bytes to be returned would put the generator
782 // over the limit, then return 0
783 if((((kdf->counter * kdf->digestSize) + randomSize) * 8) > kdf->limit)
784 return 0;
785 // Process partial and full blocks until all requested bytes provided
786 while(bytesLeft > 0)
787 {
788 // If there is any residual data in the buffer, copy it to the output
789 // buffer
790 if(kdf->residual.t.size > 0)
791 {
792 INT32 size;
793 //
794 // Don't use more of the residual than will fit or more than are
795 // available
796 size = MIN(kdf->residual.t.size, bytesLeft);
797
798 // Copy some or all of the residual to the output. The residual is
799 // at the end of the buffer. The residual might be a full buffer.
800 MemoryCopy(random,
801 &kdf->residual.t.buffer
802 [kdf->digestSize - kdf->residual.t.size], size);
803
804 // Advance the buffer pointer
805 random += size;
806
807 // Reduce the number of bytes left to get
808 bytesLeft -= size;
809
810 // And reduce the residual size appropriately
811 kdf->residual.t.size -= (UINT16)size;
812 }
813 else
814 {
815 UINT16 blocks = (UINT16)(bytesLeft / kdf->digestSize);
816 //
817 // Get the number of required full blocks
818 if(blocks > 0)
819 {
820 UINT16 size = blocks * kdf->digestSize;
821 // Get some number of full blocks and put them in the return buffer
822 CryptKDFa(kdf->hash, kdf->seed, kdf->label, kdf->context, NULL,
823 kdf->limit, random, &counter, blocks);
824
825 // reduce the size remaining to be moved and advance the pointer
826 bytesLeft -= size;
827 random += size;
828 }
829 else
830 {
831 // Fill the residual buffer with a full block and then loop to
832 // top to get part of it copied to the output.
833 kdf->residual.t.size = CryptKDFa(kdf->hash, kdf->seed,
834 kdf->label, kdf->context, NULL,
835 kdf->limit,
836 kdf->residual.t.buffer,
837 &counter, 1);
838 }
839 }
840 }
841 kdf->counter = counter;
842 return randomSize;
843 }
844 else if(state->drbg.magic == DRBG_MAGIC)
845 {
846 DRBG_STATE *drbgState = (DRBG_STATE *)state;
847 DRBG_KEY_SCHEDULE keySchedule;
848 DRBG_SEED *seed = &drbgState->seed;
849
850 if(drbgState->reseedCounter >= CTR_DRBG_MAX_REQUESTS_PER_RESEED)
851 {
852 if(drbgState == &drbgDefault)
853 {
854 DRBG_Reseed(drbgState, NULL, NULL);
855 if(IsEntropyBad() && !IsSelfTest())
856 return 0;
857 }
858 else
859 {
860 // If this is a PRNG then the only way to get
861 // here is if the SW has run away.
862 LOG_FAILURE(FATAL_ERROR_INTERNAL);
863 return 0;
864 }
865 }
866 // if the allowed number of bytes in a request is larger than the
867 // less than the number of bytes that can be requested, then check
868 #if UINT16_MAX >= CTR_DRBG_MAX_BYTES_PER_REQUEST
869 if(randomSize > CTR_DRBG_MAX_BYTES_PER_REQUEST)
870 randomSize = CTR_DRBG_MAX_BYTES_PER_REQUEST;
871 #endif
872 // Create encryption schedule
873 if(DRBG_ENCRYPT_SETUP((BYTE *)pDRBG_KEY(seed),
874 DRBG_KEY_SIZE_BITS, &keySchedule) != 0)
875 {
876 LOG_FAILURE(FATAL_ERROR_INTERNAL);
877 return 0;
878 }
879 // Generate the random data
880 EncryptDRBG(random, randomSize, &keySchedule, pDRBG_IV(seed),
881 drbgState->lastValue);
882 // Do a key update
883 DRBG_Update(drbgState, &keySchedule, NULL);
884
885 // Increment the reseed counter
886 drbgState->reseedCounter += 1;
887 }
888 else
889 {
890 LOG_FAILURE(FATAL_ERROR_INTERNAL);
891 return FALSE;
892 }
893 return randomSize;
894 }
895
896 //*** DRBG_Instantiate()
897 // This is CTR_DRBG_Instantiate_algorithm() from [SP 800-90A 10.2.1.3.1].
898 // This is called when a the TPM DRBG is to be instantiated. This is
899 // called to instantiate a DRBG used by the TPM for normal
900 // operations.
901 // Return Type: BOOL
902 // TRUE(1) instantiation succeeded
903 // FALSE(0) instantiation failed
904 LIB_EXPORT BOOL
905 DRBG_Instantiate(
906 DRBG_STATE *drbgState, // OUT: the instantiated value
907 UINT16 pSize, // IN: Size of personalization string
908 BYTE *personalization // IN: The personalization string
909 )
910 {
911 DRBG_SEED seed;
912 DRBG_SEED dfResult;
913 //
914 pAssert((pSize == 0) || (pSize <= sizeof(seed)) || (personalization != NULL));
915 // If the DRBG has not been tested, test when doing an instantiation. Since
916 // Instantiation is called during self test, make sure we don't get stuck in a
917 // loop.
918 if(!IsDrbgTested() && !IsSelfTest() && !DRBG_SelfTest())
919 return FALSE;
920 // If doing a self test, DRBG_GetEntropy will return the NIST
921 // test vector value.
922 if(!DRBG_GetEntropy(sizeof(seed), (BYTE *)&seed))
923 return FALSE;
924 // set everything to zero
925 memset(drbgState, 0, sizeof(DRBG_STATE));
926 drbgState->magic = DRBG_MAGIC;
927
928 // Steps 1, 2, 3, 6, 7 of SP 800-90A 10.2.1.3.1 are exactly what
929 // reseeding does. So, do a reduction on the personalization value (if any)
930 // and do a reseed.
931 DRBG_Reseed(drbgState, &seed, DfBuffer(&dfResult, pSize, personalization));
932
933 return TRUE;
934 }
935
936 //*** DRBG_Uninstantiate()
937 // This is Uninstantiate_function() from [SP 800-90A 9.4].
938 //
939 // Return Type: TPM_RC
940 // TPM_RC_VALUE not a valid state
941 LIB_EXPORT TPM_RC
942 DRBG_Uninstantiate(
943 DRBG_STATE *drbgState // IN/OUT: working state to erase
944 )
945 {
946 if((drbgState == NULL) || (drbgState->magic != DRBG_MAGIC))
947 return TPM_RC_VALUE;
948 memset(drbgState, 0, sizeof(DRBG_STATE));
949 return TPM_RC_SUCCESS;
950 }