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
DfCompute(PDF_STATE dfState)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
DfStart(PDF_STATE dfState,uint32_t inputLength)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
DfUpdate(PDF_STATE dfState,int size,const BYTE * data)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 *
DfEnd(PDF_STATE dfState)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 *
DfBuffer(DRBG_SEED * output,int size,BYTE * buf)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 //
254 // Return Type: BOOL
255 // TRUE(1) requested entropy returned
256 // FALSE(0) entropy Failure
257 BOOL
DRBG_GetEntropy(UINT32 requiredEntropy,BYTE * entropy)258 DRBG_GetEntropy(
259 UINT32 requiredEntropy, // IN: requested number of bytes of full
260 // entropy
261 BYTE *entropy // OUT: buffer to return collected entropy
262 )
263 {
264 #if !USE_DEBUG_RNG
265
266 UINT32 obtainedEntropy;
267 INT32 returnedEntropy;
268
269 // If in debug mode, always use the self-test values for initialization
270 if(IsSelfTest())
271 {
272 #endif
273 // If doing simulated DRBG, then check to see if the
274 // entropyFailure condition is being tested
275 if(!IsEntropyBad())
276 {
277 // In self-test, the caller should be asking for exactly the seed
278 // size of entropy.
279 pAssert(requiredEntropy == sizeof(DRBG_NistTestVector_Entropy));
280 memcpy(entropy, DRBG_NistTestVector_Entropy,
281 sizeof(DRBG_NistTestVector_Entropy));
282 }
283 #if !USE_DEBUG_RNG
284 }
285 else if(!IsEntropyBad())
286 {
287 // Collect entropy
288 // Note: In debug mode, the only "entropy" value ever returned
289 // is the value of the self-test vector.
290 for(returnedEntropy = 1, obtainedEntropy = 0;
291 obtainedEntropy < requiredEntropy && !IsEntropyBad();
292 obtainedEntropy += returnedEntropy)
293 {
294 returnedEntropy = _plat__GetEntropy(&entropy[obtainedEntropy],
295 requiredEntropy - obtainedEntropy);
296 if(returnedEntropy <= 0)
297 SetEntropyBad();
298 }
299 }
300 #endif
301 return !IsEntropyBad();
302 }
303
304 //*** IncrementIv()
305 // This function increments the IV value by 1. It is used by EncryptDRBG().
306 void
IncrementIv(DRBG_IV * iv)307 IncrementIv(
308 DRBG_IV *iv
309 )
310 {
311 BYTE *ivP = ((BYTE *)iv) + DRBG_IV_SIZE_BYTES;
312 while((--ivP >= (BYTE *)iv) && ((*ivP = ((*ivP + 1) & 0xFF)) == 0));
313 }
314
315 //*** EncryptDRBG()
316 // This does the encryption operation for the DRBG. It will encrypt
317 // the input state counter (IV) using the state key. Into the output
318 // buffer for as many times as it takes to generate the required
319 // number of bytes.
320 static BOOL
EncryptDRBG(BYTE * dOut,UINT32 dOutBytes,DRBG_KEY_SCHEDULE * keySchedule,DRBG_IV * iv,UINT32 * lastValue)321 EncryptDRBG(
322 BYTE *dOut,
323 UINT32 dOutBytes,
324 DRBG_KEY_SCHEDULE *keySchedule,
325 DRBG_IV *iv,
326 UINT32 *lastValue // Points to the last output value
327 )
328 {
329 #if FIPS_COMPLIANT
330 // For FIPS compliance, the DRBG has to do a continuous self-test to make sure that
331 // no two consecutive values are the same. This overhead is not incurred if the TPM
332 // is not required to be FIPS compliant
333 //
334 UINT32 temp[DRBG_IV_SIZE_BYTES / sizeof(UINT32)];
335 int i;
336 BYTE *p;
337
338 for(; dOutBytes > 0;)
339 {
340 // Increment the IV before each encryption (this is what makes this
341 // different from normal counter-mode encryption
342 IncrementIv(iv);
343 DRBG_ENCRYPT(keySchedule, iv, temp);
344 // Expect a 16 byte block
345 #if DRBG_IV_SIZE_BITS != 128
346 #error "Unsuppored IV size in DRBG"
347 #endif
348 if((lastValue[0] == temp[0])
349 && (lastValue[1] == temp[1])
350 && (lastValue[2] == temp[2])
351 && (lastValue[3] == temp[3])
352 )
353 {
354 LOG_FAILURE(FATAL_ERROR_ENTROPY);
355 return FALSE;
356 }
357 lastValue[0] = temp[0];
358 lastValue[1] = temp[1];
359 lastValue[2] = temp[2];
360 lastValue[3] = temp[3];
361 i = MIN(dOutBytes, DRBG_IV_SIZE_BYTES);
362 dOutBytes -= i;
363 for(p = (BYTE *)temp; i > 0; i--)
364 *dOut++ = *p++;
365 }
366 #else // version without continuous self-test
367 NOT_REFERENCED(lastValue);
368 for(; dOutBytes >= DRBG_IV_SIZE_BYTES;
369 dOut = &dOut[DRBG_IV_SIZE_BYTES], dOutBytes -= DRBG_IV_SIZE_BYTES)
370 {
371 // Increment the IV
372 IncrementIv(iv);
373 DRBG_ENCRYPT(keySchedule, iv, dOut);
374 }
375 // If there is a partial, generate into a block-sized
376 // temp buffer and copy to the output.
377 if(dOutBytes != 0)
378 {
379 BYTE temp[DRBG_IV_SIZE_BYTES];
380 // Increment the IV
381 IncrementIv(iv);
382 DRBG_ENCRYPT(keySchedule, iv, temp);
383 memcpy(dOut, temp, dOutBytes);
384 }
385 #endif
386 return TRUE;
387 }
388
389 //*** DRBG_Update()
390 // This function performs the state update function.
391 // According to SP800-90A, a temp value is created by doing CTR mode
392 // encryption of 'providedData' and replacing the key and IV with
393 // these values. The one difference is that, with counter mode, the
394 // IV is incremented after each block is encrypted and in this
395 // operation, the counter is incremented before each block is
396 // encrypted. This function implements an 'optimized' version
397 // of the algorithm in that it does the update of the drbgState->seed
398 // in place and then 'providedData' is XORed into drbgState->seed
399 // to complete the encryption of 'providedData'. This works because
400 // the IV is the last thing that gets encrypted.
401 //
402 static BOOL
DRBG_Update(DRBG_STATE * drbgState,DRBG_KEY_SCHEDULE * keySchedule,DRBG_SEED * providedData)403 DRBG_Update(
404 DRBG_STATE *drbgState, // IN:OUT state to update
405 DRBG_KEY_SCHEDULE *keySchedule, // IN: the key schedule (optional)
406 DRBG_SEED *providedData // IN: additional data
407 )
408 {
409 UINT32 i;
410 BYTE *temp = (BYTE *)&drbgState->seed;
411 DRBG_KEY *key = pDRBG_KEY(&drbgState->seed);
412 DRBG_IV *iv = pDRBG_IV(&drbgState->seed);
413 DRBG_KEY_SCHEDULE localKeySchedule;
414 //
415 pAssert(drbgState->magic == DRBG_MAGIC);
416
417 // If an key schedule was not provided, make one
418 if(keySchedule == NULL)
419 {
420 if(DRBG_ENCRYPT_SETUP((BYTE *)key,
421 DRBG_KEY_SIZE_BITS, &localKeySchedule) != 0)
422 {
423 LOG_FAILURE(FATAL_ERROR_INTERNAL);
424 return FALSE;
425 }
426 keySchedule = &localKeySchedule;
427 }
428 // Encrypt the temp value
429
430 EncryptDRBG(temp, sizeof(DRBG_SEED), keySchedule, iv,
431 drbgState->lastValue);
432 if(providedData != NULL)
433 {
434 BYTE *pP = (BYTE *)providedData;
435 for(i = DRBG_SEED_SIZE_BYTES; i != 0; i--)
436 *temp++ ^= *pP++;
437 }
438 // Since temp points to the input key and IV, we are done and
439 // don't need to copy the resulting 'temp' to drbgState->seed
440 return TRUE;
441 }
442
443 //*** DRBG_Reseed()
444 // This function is used when reseeding of the DRBG is required. If
445 // entropy is provided, it is used in lieu of using hardware entropy.
446 // Note: the provided entropy must be the required size.
447 //
448 // Return Type: BOOL
449 // TRUE(1) reseed succeeded
450 // FALSE(0) reseed failed, probably due to the entropy generation
451 BOOL
DRBG_Reseed(DRBG_STATE * drbgState,DRBG_SEED * providedEntropy,DRBG_SEED * additionalData)452 DRBG_Reseed(
453 DRBG_STATE *drbgState, // IN: the state to update
454 DRBG_SEED *providedEntropy, // IN: entropy
455 DRBG_SEED *additionalData // IN:
456 )
457 {
458 DRBG_SEED seed;
459
460 pAssert((drbgState != NULL) && (drbgState->magic == DRBG_MAGIC));
461
462 if(providedEntropy == NULL)
463 {
464 providedEntropy = &seed;
465 if(!DRBG_GetEntropy(sizeof(DRBG_SEED), (BYTE *)providedEntropy))
466 return FALSE;
467 }
468 if(additionalData != NULL)
469 {
470 unsigned int i;
471
472 // XOR the provided data into the provided entropy
473 for(i = 0; i < sizeof(DRBG_SEED); i++)
474 ((BYTE *)providedEntropy)[i] ^= ((BYTE *)additionalData)[i];
475 }
476 DRBG_Update(drbgState, NULL, providedEntropy);
477
478 drbgState->reseedCounter = 1;
479
480 return TRUE;
481 }
482
483 //*** DRBG_SelfTest()
484 // This is run when the DRBG is instantiated and at startup.
485 //
486 // Return Type: BOOL
487 // TRUE(1) test OK
488 // FALSE(0) test failed
489 BOOL
DRBG_SelfTest(void)490 DRBG_SelfTest(
491 void
492 )
493 {
494 BYTE buf[sizeof(DRBG_NistTestVector_Generated)];
495 DRBG_SEED seed;
496 UINT32 i;
497 BYTE *p;
498 DRBG_STATE testState;
499 //
500 pAssert(!IsSelfTest());
501
502 SetSelfTest();
503 SetDrbgTested();
504 // Do an instantiate
505 if(!DRBG_Instantiate(&testState, 0, NULL))
506 return FALSE;
507 #if DRBG_DEBUG_PRINT
508 dbgDumpMemBlock(pDRBG_KEY(&testState), DRBG_KEY_SIZE_BYTES,
509 "Key after Instantiate");
510 dbgDumpMemBlock(pDRBG_IV(&testState), DRBG_IV_SIZE_BYTES,
511 "Value after Instantiate");
512 #endif
513 if(DRBG_Generate((RAND_STATE *)&testState, buf, sizeof(buf)) == 0)
514 return FALSE;
515 #if DRBG_DEBUG_PRINT
516 dbgDumpMemBlock(pDRBG_KEY(&testState.seed), DRBG_KEY_SIZE_BYTES,
517 "Key after 1st Generate");
518 dbgDumpMemBlock(pDRBG_IV(&testState.seed), DRBG_IV_SIZE_BYTES,
519 "Value after 1st Generate");
520 #endif
521 if(memcmp(buf, DRBG_NistTestVector_GeneratedInterm, sizeof(buf)) != 0)
522 return FALSE;
523 memcpy(seed.bytes, DRBG_NistTestVector_EntropyReseed, sizeof(seed));
524 DRBG_Reseed(&testState, &seed, NULL);
525 #if DRBG_DEBUG_PRINT
526 dbgDumpMemBlock((BYTE *)pDRBG_KEY(&testState.seed), DRBG_KEY_SIZE_BYTES,
527 "Key after 2nd Generate");
528 dbgDumpMemBlock((BYTE *)pDRBG_IV(&testState.seed), DRBG_IV_SIZE_BYTES,
529 "Value after 2nd Generate");
530 dbgDumpMemBlock(buf, sizeof(buf), "2nd Generated");
531 #endif
532 if(DRBG_Generate((RAND_STATE *)&testState, buf, sizeof(buf)) == 0)
533 return FALSE;
534 if(memcmp(buf, DRBG_NistTestVector_Generated, sizeof(buf)) != 0)
535 return FALSE;
536 ClearSelfTest();
537
538 DRBG_Uninstantiate(&testState);
539 for(p = (BYTE *)&testState, i = 0; i < sizeof(DRBG_STATE); i++)
540 {
541 if(*p++)
542 return FALSE;
543 }
544 // Simulate hardware failure to make sure that we get an error when
545 // trying to instantiate
546 SetEntropyBad();
547 if(DRBG_Instantiate(&testState, 0, NULL))
548 return FALSE;
549 ClearEntropyBad();
550
551 return TRUE;
552 }
553
554 //** Public Interface
555 //*** Description
556 // The functions in this section are the interface to the RNG. These
557 // are the functions that are used by TPM.lib.
558
559 //*** CryptRandomStir()
560 // This function is used to cause a reseed. A DRBG_SEED amount of entropy is
561 // collected from the hardware and then additional data is added.
562 //
563 // Return Type: TPM_RC
564 // TPM_RC_NO_RESULT failure of the entropy generator
565 LIB_EXPORT TPM_RC
CryptRandomStir(UINT16 additionalDataSize,BYTE * additionalData)566 CryptRandomStir(
567 UINT16 additionalDataSize,
568 BYTE *additionalData
569 )
570 {
571 #if !USE_DEBUG_RNG
572 DRBG_SEED tmpBuf;
573 DRBG_SEED dfResult;
574 //
575 // All reseed with outside data starts with a buffer full of entropy
576 if(!DRBG_GetEntropy(sizeof(tmpBuf), (BYTE *)&tmpBuf))
577 return TPM_RC_NO_RESULT;
578
579 DRBG_Reseed(&drbgDefault, &tmpBuf,
580 DfBuffer(&dfResult, additionalDataSize, additionalData));
581 drbgDefault.reseedCounter = 1;
582
583 return TPM_RC_SUCCESS;
584
585 #else
586 // If doing debug, use the input data as the initial setting for the RNG state
587 // so that the test can be reset at any time.
588 // Note: If this is called with a data size of 0 or less, nothing happens. The
589 // presumption is that, in a debug environment, the caller will have specific
590 // values for initialization, so this check is just a simple way to prevent
591 // inadvertent programming errors from screwing things up. This doesn't use an
592 // pAssert() because the non-debug version of this function will accept these
593 // parameters as meaning that there is no additionalData and only hardware
594 // entropy is used.
595 if((additionalDataSize > 0) && (additionalData != NULL))
596 {
597 memset(drbgDefault.seed.bytes, 0, sizeof(drbgDefault.seed.bytes));
598 memcpy(drbgDefault.seed.bytes, additionalData,
599 MIN(additionalDataSize, sizeof(drbgDefault.seed.bytes)));
600 }
601 drbgDefault.reseedCounter = 1;
602
603 return TPM_RC_SUCCESS;
604 #endif
605 }
606
607 //*** CryptRandomGenerate()
608 // Generate a 'randomSize' number or random bytes.
609 LIB_EXPORT UINT16
CryptRandomGenerate(UINT16 randomSize,BYTE * buffer)610 CryptRandomGenerate(
611 UINT16 randomSize,
612 BYTE *buffer
613 )
614 {
615 return DRBG_Generate((RAND_STATE *)&drbgDefault, buffer, randomSize);
616 }
617
618
619
620 //*** DRBG_InstantiateSeededKdf()
621 // This function is used to instantiate a KDF-based RNG. This is used for derivations.
622 // This function always returns TRUE.
623 LIB_EXPORT BOOL
DRBG_InstantiateSeededKdf(KDF_STATE * state,TPM_ALG_ID hashAlg,TPM_ALG_ID kdf,TPM2B * seed,const TPM2B * label,TPM2B * context,UINT32 limit)624 DRBG_InstantiateSeededKdf(
625 KDF_STATE *state, // OUT: buffer to hold the state
626 TPM_ALG_ID hashAlg, // IN: hash algorithm
627 TPM_ALG_ID kdf, // IN: the KDF to use
628 TPM2B *seed, // IN: the seed to use
629 const TPM2B *label, // IN: a label for the generation process.
630 TPM2B *context, // IN: the context value
631 UINT32 limit // IN: Maximum number of bits from the KDF
632 )
633 {
634 state->magic = KDF_MAGIC;
635 state->limit = limit;
636 state->seed = seed;
637 state->hash = hashAlg;
638 state->kdf = kdf;
639 state->label = label;
640 state->context = context;
641 state->digestSize = CryptHashGetDigestSize(hashAlg);
642 state->counter = 0;
643 state->residual.t.size = 0;
644 return TRUE;
645 }
646
647 //*** DRBG_AdditionalData()
648 // Function to reseed the DRBG with additional entropy. This is normally called
649 // before computing the protection value of a primary key in the Endorsement
650 // hierarchy.
651 LIB_EXPORT void
DRBG_AdditionalData(DRBG_STATE * drbgState,TPM2B * additionalData)652 DRBG_AdditionalData(
653 DRBG_STATE *drbgState, // IN:OUT state to update
654 TPM2B *additionalData // IN: value to incorporate
655 )
656 {
657 DRBG_SEED dfResult;
658 if(drbgState->magic == DRBG_MAGIC)
659 {
660 DfBuffer(&dfResult, additionalData->size, additionalData->buffer);
661 DRBG_Reseed(drbgState, &dfResult, NULL);
662 }
663 }
664
665
666 //*** DRBG_InstantiateSeeded()
667 // This function is used to instantiate a random number generator from seed values.
668 // The nominal use of this generator is to create sequences of pseudo-random
669 // numbers from a seed value.
670 //
671 // Return Type: TPM_RC
672 // TPM_RC_FAILURE DRBG self-test failure
673 LIB_EXPORT TPM_RC
DRBG_InstantiateSeeded(DRBG_STATE * drbgState,const TPM2B * seed,const TPM2B * purpose,const TPM2B * name,const TPM2B * additional)674 DRBG_InstantiateSeeded(
675 DRBG_STATE *drbgState, // IN/OUT: buffer to hold the state
676 const TPM2B *seed, // IN: the seed to use
677 const TPM2B *purpose, // IN: a label for the generation process.
678 const TPM2B *name, // IN: name of the object
679 const TPM2B *additional // IN: additional data
680 )
681 {
682 DF_STATE dfState;
683 int totalInputSize;
684 // DRBG should have been tested, but...
685 if(!IsDrbgTested() && !DRBG_SelfTest())
686 {
687 LOG_FAILURE(FATAL_ERROR_SELF_TEST);
688 return TPM_RC_FAILURE;
689 }
690 // Initialize the DRBG state
691 memset(drbgState, 0, sizeof(DRBG_STATE));
692 drbgState->magic = DRBG_MAGIC;
693
694 // Size all of the values
695 totalInputSize = (seed != NULL) ? seed->size : 0;
696 totalInputSize += (purpose != NULL) ? purpose->size : 0;
697 totalInputSize += (name != NULL) ? name->size : 0;
698 totalInputSize += (additional != NULL) ? additional->size : 0;
699
700 // Initialize the derivation
701 DfStart(&dfState, totalInputSize);
702
703 // Run all the input strings through the derivation function
704 if(seed != NULL)
705 DfUpdate(&dfState, seed->size, seed->buffer);
706 if(purpose != NULL)
707 DfUpdate(&dfState, purpose->size, purpose->buffer);
708 if(name != NULL)
709 DfUpdate(&dfState, name->size, name->buffer);
710 if(additional != NULL)
711 DfUpdate(&dfState, additional->size, additional->buffer);
712
713 // Used the derivation function output as the "entropy" input. This is not
714 // how it is described in SP800-90A but this is the equivalent function
715 DRBG_Reseed(((DRBG_STATE *)drbgState), DfEnd(&dfState), NULL);
716
717 return TPM_RC_SUCCESS;
718 }
719
720 //*** CryptRandStartup()
721 // This function is called when TPM_Startup is executed. This function always returns
722 // TRUE.
723 LIB_EXPORT BOOL
CryptRandStartup(void)724 CryptRandStartup(
725 void
726 )
727 {
728 #if ! _DRBG_STATE_SAVE
729 // If not saved in NV, re-instantiate on each startup
730 return DRBG_Instantiate(&drbgDefault, 0, NULL);
731 #else
732 // If the running state is saved in NV, NV has to be loaded before it can
733 // be updated
734 if(go.drbgState.magic == DRBG_MAGIC)
735 return DRBG_Reseed(&go.drbgState, NULL, NULL);
736 else
737 return DRBG_Instantiate(&go.drbgState, 0, NULL);
738 #endif
739 }
740
741 //*** CryptRandInit()
742 // This function is called when _TPM_Init is being processed.
743 //
744 // Return Type: BOOL
745 // TRUE(1) success
746 // FALSE(0) failure
747 LIB_EXPORT BOOL
CryptRandInit(void)748 CryptRandInit(
749 void
750 )
751 {
752 #if !USE_DEBUG_RNG
753 _plat__GetEntropy(NULL, 0);
754 #endif
755 return DRBG_SelfTest();
756 }
757
758 //*** DRBG_Generate()
759 // This function generates a random sequence according SP800-90A.
760 // If 'random' is not NULL, then 'randomSize' bytes of random values are generated.
761 // If 'random' is NULL or 'randomSize' is zero, then the function returns
762 // zero without generating any bits or updating the reseed counter.
763 // This function returns the number of bytes produced which could be less than the
764 // number requested if the request is too large ("too large" is implementation
765 // dependent.)
766 LIB_EXPORT UINT16
DRBG_Generate(RAND_STATE * state,BYTE * random,UINT16 randomSize)767 DRBG_Generate(
768 RAND_STATE *state,
769 BYTE *random, // OUT: buffer to receive the random values
770 UINT16 randomSize // IN: the number of bytes to generate
771 )
772 {
773 if(state == NULL)
774 state = (RAND_STATE *)&drbgDefault;
775 if(random == NULL)
776 return 0;
777
778 // If the caller used a KDF state, generate a sequence from the KDF not to
779 // exceed the limit.
780 if(state->kdf.magic == KDF_MAGIC)
781 {
782 KDF_STATE *kdf = (KDF_STATE *)state;
783 UINT32 counter = (UINT32)kdf->counter;
784 INT32 bytesLeft = randomSize;
785 //
786 // If the number of bytes to be returned would put the generator
787 // over the limit, then return 0
788 if((((kdf->counter * kdf->digestSize) + randomSize) * 8) > kdf->limit)
789 return 0;
790 // Process partial and full blocks until all requested bytes provided
791 while(bytesLeft > 0)
792 {
793 // If there is any residual data in the buffer, copy it to the output
794 // buffer
795 if(kdf->residual.t.size > 0)
796 {
797 INT32 size;
798 //
799 // Don't use more of the residual than will fit or more than are
800 // available
801 size = MIN(kdf->residual.t.size, bytesLeft);
802
803 // Copy some or all of the residual to the output. The residual is
804 // at the end of the buffer. The residual might be a full buffer.
805 MemoryCopy(random,
806 &kdf->residual.t.buffer
807 [kdf->digestSize - kdf->residual.t.size], size);
808
809 // Advance the buffer pointer
810 random += size;
811
812 // Reduce the number of bytes left to get
813 bytesLeft -= size;
814
815 // And reduce the residual size appropriately
816 kdf->residual.t.size -= (UINT16)size;
817 }
818 else
819 {
820 UINT16 blocks = (UINT16)(bytesLeft / kdf->digestSize);
821 //
822 // Get the number of required full blocks
823 if(blocks > 0)
824 {
825 UINT16 size = blocks * kdf->digestSize;
826 // Get some number of full blocks and put them in the return buffer
827 CryptKDFa(kdf->hash, kdf->seed, kdf->label, kdf->context, NULL,
828 kdf->limit, random, &counter, blocks);
829
830 // reduce the size remaining to be moved and advance the pointer
831 bytesLeft -= size;
832 random += size;
833 }
834 else
835 {
836 // Fill the residual buffer with a full block and then loop to
837 // top to get part of it copied to the output.
838 kdf->residual.t.size = CryptKDFa(kdf->hash, kdf->seed,
839 kdf->label, kdf->context, NULL,
840 kdf->limit,
841 kdf->residual.t.buffer,
842 &counter, 1);
843 }
844 }
845 }
846 kdf->counter = counter;
847 return randomSize;
848 }
849 else if(state->drbg.magic == DRBG_MAGIC)
850 {
851 DRBG_STATE *drbgState = (DRBG_STATE *)state;
852 DRBG_KEY_SCHEDULE keySchedule;
853 DRBG_SEED *seed = &drbgState->seed;
854
855 if(drbgState->reseedCounter >= CTR_DRBG_MAX_REQUESTS_PER_RESEED)
856 {
857 if(drbgState == &drbgDefault)
858 {
859 DRBG_Reseed(drbgState, NULL, NULL);
860 if(IsEntropyBad() && !IsSelfTest())
861 return 0;
862 }
863 else
864 {
865 // If this is a PRNG then the only way to get
866 // here is if the SW has run away.
867 LOG_FAILURE(FATAL_ERROR_INTERNAL);
868 return 0;
869 }
870 }
871 // if the allowed number of bytes in a request is larger than the
872 // less than the number of bytes that can be requested, then check
873 #if UINT16_MAX >= CTR_DRBG_MAX_BYTES_PER_REQUEST
874 if(randomSize > CTR_DRBG_MAX_BYTES_PER_REQUEST)
875 randomSize = CTR_DRBG_MAX_BYTES_PER_REQUEST;
876 #endif
877 // Create encryption schedule
878 if(DRBG_ENCRYPT_SETUP((BYTE *)pDRBG_KEY(seed),
879 DRBG_KEY_SIZE_BITS, &keySchedule) != 0)
880 {
881 LOG_FAILURE(FATAL_ERROR_INTERNAL);
882 return 0;
883 }
884 // Generate the random data
885 EncryptDRBG(random, randomSize, &keySchedule, pDRBG_IV(seed),
886 drbgState->lastValue);
887 // Do a key update
888 DRBG_Update(drbgState, &keySchedule, NULL);
889
890 // Increment the reseed counter
891 drbgState->reseedCounter += 1;
892 }
893 else
894 {
895 LOG_FAILURE(FATAL_ERROR_INTERNAL);
896 return FALSE;
897 }
898 return randomSize;
899 }
900
901 //*** DRBG_Instantiate()
902 // This is CTR_DRBG_Instantiate_algorithm() from [SP 800-90A 10.2.1.3.1].
903 // This is called when a the TPM DRBG is to be instantiated. This is
904 // called to instantiate a DRBG used by the TPM for normal
905 // operations.
906 //
907 // Return Type: BOOL
908 // TRUE(1) instantiation succeeded
909 // FALSE(0) instantiation failed
910 LIB_EXPORT BOOL
DRBG_Instantiate(DRBG_STATE * drbgState,UINT16 pSize,BYTE * personalization)911 DRBG_Instantiate(
912 DRBG_STATE *drbgState, // OUT: the instantiated value
913 UINT16 pSize, // IN: Size of personalization string
914 BYTE *personalization // IN: The personalization string
915 )
916 {
917 DRBG_SEED seed;
918 DRBG_SEED dfResult;
919 //
920 pAssert((pSize == 0) || (pSize <= sizeof(seed)) || (personalization != NULL));
921 // If the DRBG has not been tested, test when doing an instantiation. Since
922 // Instantiation is called during self test, make sure we don't get stuck in a
923 // loop.
924 if(!IsDrbgTested() && !IsSelfTest() && !DRBG_SelfTest())
925 return FALSE;
926 // If doing a self test, DRBG_GetEntropy will return the NIST
927 // test vector value.
928 if(!DRBG_GetEntropy(sizeof(seed), (BYTE *)&seed))
929 return FALSE;
930 // set everything to zero
931 memset(drbgState, 0, sizeof(DRBG_STATE));
932 drbgState->magic = DRBG_MAGIC;
933
934 // Steps 1, 2, 3, 6, 7 of SP 800-90A 10.2.1.3.1 are exactly what
935 // reseeding does. So, do a reduction on the personalization value (if any)
936 // and do a reseed.
937 DRBG_Reseed(drbgState, &seed, DfBuffer(&dfResult, pSize, personalization));
938
939 return TRUE;
940 }
941
942 //*** DRBG_Uninstantiate()
943 // This is Uninstantiate_function() from [SP 800-90A 9.4].
944 //
945 // Return Type: TPM_RC
946 // TPM_RC_VALUE not a valid state
947 LIB_EXPORT TPM_RC
DRBG_Uninstantiate(DRBG_STATE * drbgState)948 DRBG_Uninstantiate(
949 DRBG_STATE *drbgState // IN/OUT: working state to erase
950 )
951 {
952 if((drbgState == NULL) || (drbgState->magic != DRBG_MAGIC))
953 return TPM_RC_VALUE;
954 memset(drbgState, 0, sizeof(DRBG_STATE));
955 return TPM_RC_SUCCESS;
956 }
957