Debian Codegraph @

simulator/ms-tpm-20-ref/TPMCmd/tpm/src/crypt/CryptUtil.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 //
37 // This module contains the interfaces to the CryptoEngine and provides
38 // miscellaneous cryptographic functions in support of the TPM.
39 //
40
41 //** Includes
42 #include "Tpm.h"
43
44 //****************************************************************************/
45 //** Hash/HMAC Functions
46 //****************************************************************************/
47
48 //*** CryptHmacSign()
49 // Sign a digest using an HMAC key. This an HMAC of a digest, not an HMAC of a
50 // message.
51 // Return Type: TPM_RC
52 // TPM_RC_HASH not a valid hash
53 static TPM_RC
54 CryptHmacSign(
55 TPMT_SIGNATURE *signature, // OUT: signature
56 OBJECT *signKey, // IN: HMAC key sign the hash
57 TPM2B_DIGEST *hashData // IN: hash to be signed
58 )
59 {
60 HMAC_STATE hmacState;
61 UINT32 digestSize;
62
63 digestSize = CryptHmacStart2B(&hmacState, signature->signature.any.hashAlg,
64 &signKey->sensitive.sensitive.bits.b);
65 CryptDigestUpdate2B(&hmacState.hashState, &hashData->b);
66 CryptHmacEnd(&hmacState, digestSize,
67 (BYTE *)&signature->signature.hmac.digest);
68 return TPM_RC_SUCCESS;
69 }
70
71 //*** CryptHMACVerifySignature()
72 // This function will verify a signature signed by a HMAC key.
73 // Note that a caller needs to prepare 'signature' with the signature algorithm
74 // (TPM_ALG_HMAC) and the hash algorithm to use. This function then builds a
75 // signature of that type.
76 // Return Type: TPM_RC
77 // TPM_RC_SCHEME not the proper scheme for this key type
78 // TPM_RC_SIGNATURE if invalid input or signature is not genuine
79 static TPM_RC
80 CryptHMACVerifySignature(
81 OBJECT *signKey, // IN: HMAC key signed the hash
82 TPM2B_DIGEST *hashData, // IN: digest being verified
83 TPMT_SIGNATURE *signature // IN: signature to be verified
84 )
85 {
86 TPMT_SIGNATURE test;
87 TPMT_KEYEDHASH_SCHEME *keyScheme =
88 &signKey->publicArea.parameters.keyedHashDetail.scheme;
89 //
90 if((signature->sigAlg != ALG_HMAC_VALUE)
91 || (signature->signature.hmac.hashAlg == ALG_NULL_VALUE))
92 return TPM_RC_SCHEME;
93 // This check is not really needed for verification purposes. However, it does
94 // prevent someone from trying to validate a signature using a weaker hash
95 // algorithm than otherwise allowed by the key. That is, a key with a scheme
96 // other than TMP_ALG_NULL can only be used to validate signatures that have
97 // a matching scheme.
98 if((keyScheme->scheme != ALG_NULL_VALUE)
99 && ((keyScheme->scheme != signature->sigAlg)
100 || (keyScheme->details.hmac.hashAlg
101 != signature->signature.any.hashAlg)))
102 return TPM_RC_SIGNATURE;
103 test.sigAlg = signature->sigAlg;
104 test.signature.hmac.hashAlg = signature->signature.hmac.hashAlg;
105
106 CryptHmacSign(&test, signKey, hashData);
107
108 // Compare digest
109 if(!MemoryEqual(&test.signature.hmac.digest,
110 &signature->signature.hmac.digest,
111 CryptHashGetDigestSize(signature->signature.any.hashAlg)))
112 return TPM_RC_SIGNATURE;
113
114 return TPM_RC_SUCCESS;
115 }
116
117 //*** CryptGenerateKeyedHash()
118 // This function creates a keyedHash object.
119 // Return type: TPM_RC
120 // TPM_RC_NO_RESULT cannot get values from random number generator
121 // TPM_RC_SIZE sensitive data size is larger than allowed for
122 // the scheme
123 static TPM_RC
124 CryptGenerateKeyedHash(
125 TPMT_PUBLIC *publicArea, // IN/OUT: the public area template
126 // for the new key.
127 TPMT_SENSITIVE *sensitive, // OUT: sensitive area
128 TPMS_SENSITIVE_CREATE *sensitiveCreate, // IN: sensitive creation data
129 RAND_STATE *rand // IN: "entropy" source
130 )
131 {
132 TPMT_KEYEDHASH_SCHEME *scheme;
133 TPM_ALG_ID hashAlg;
134 UINT16 hashBlockSize;
135 UINT16 digestSize;
136
137 scheme = &publicArea->parameters.keyedHashDetail.scheme;
138
139 if(publicArea->type != ALG_KEYEDHASH_VALUE)
140 return TPM_RC_FAILURE;
141
142 // Pick the limiting hash algorithm
143 if(scheme->scheme == ALG_NULL_VALUE)
144 hashAlg = publicArea->nameAlg;
145 else if(scheme->scheme == ALG_XOR_VALUE)
146 hashAlg = scheme->details.xor.hashAlg;
147 else
148 hashAlg = scheme->details.hmac.hashAlg;
149 hashBlockSize = CryptHashGetBlockSize(hashAlg);
150 digestSize = CryptHashGetDigestSize(hashAlg);
151
152 // if this is a signing or a decryption key, then the limit
153 // for the data size is the block size of the hash. This limit
154 // is set because larger values have lower entropy because of the
155 // HMAC function. The lower limit is 1/2 the size of the digest
156 //
157 //If the user provided the key, check that it is a proper size
158 if(sensitiveCreate->data.t.size != 0)
159 {
160 if(IS_ATTRIBUTE(publicArea->objectAttributes, TPMA_OBJECT, decrypt)
161 || IS_ATTRIBUTE(publicArea->objectAttributes, TPMA_OBJECT, sign))
162 {
163 if(sensitiveCreate->data.t.size > hashBlockSize)
164 return TPM_RC_SIZE;
165 #if 0 // May make this a FIPS-mode requirement
166 if(sensitiveCreate->data.t.size < (digestSize / 2))
167 return TPM_RC_SIZE;
168 #endif
169 }
170 // If this is a data blob, then anything that will get past the unmarshaling
171 // is OK
172 MemoryCopy2B(&sensitive->sensitive.bits.b, &sensitiveCreate->data.b,
173 sizeof(sensitive->sensitive.bits.t.buffer));
174 }
175 else
176 {
177 // The TPM is going to generate the data so set the size to be the
178 // size of the digest of the algorithm
179 sensitive->sensitive.bits.t.size =
180 DRBG_Generate(rand, sensitive->sensitive.bits.t.buffer, digestSize);
181 if(sensitive->sensitive.bits.t.size == 0)
182 return (g_inFailureMode) ? TPM_RC_FAILURE : TPM_RC_NO_RESULT;
183 }
184 return TPM_RC_SUCCESS;
185 }
186
187 //*** CryptIsSchemeAnonymous()
188 // This function is used to test a scheme to see if it is an anonymous scheme
189 // The only anonymous scheme is ECDAA. ECDAA can be used to do things
190 // like U-Prove.
191 BOOL
192 CryptIsSchemeAnonymous(
193 TPM_ALG_ID scheme // IN: the scheme algorithm to test
194 )
195 {
196 return scheme == ALG_ECDAA_VALUE;
197 }
198
199 //**** ************************************************************************
200 //** Symmetric Functions
201 //**** ************************************************************************
202
203 //*** ParmDecryptSym()
204 // This function performs parameter decryption using symmetric block cipher.
205 /*(See Part 1 specification)
206 // Symmetric parameter decryption
207 // When parameter decryption uses a symmetric block cipher, a decryption
208 // key and IV will be generated from:
209 // KDFa(hash, sessionAuth, "CFB", nonceNewer, nonceOlder, bits) (24)
210 // Where:
211 // hash the hash function associated with the session
212 // sessionAuth the sessionAuth associated with the session
213 // nonceNewer nonceCaller for a command
214 // nonceOlder nonceTPM for a command
215 // bits the number of bits required for the symmetric key
216 // plus an IV
217 */
218 void
219 ParmDecryptSym(
220 TPM_ALG_ID symAlg, // IN: the symmetric algorithm
221 TPM_ALG_ID hash, // IN: hash algorithm for KDFa
222 UINT16 keySizeInBits, // IN: the key size in bits
223 TPM2B *key, // IN: KDF HMAC key
224 TPM2B *nonceCaller, // IN: nonce caller
225 TPM2B *nonceTpm, // IN: nonce TPM
226 UINT32 dataSize, // IN: size of parameter buffer
227 BYTE *data // OUT: buffer to be decrypted
228 )
229 {
230 // KDF output buffer
231 // It contains parameters for the CFB encryption
232 // From MSB to LSB, they are the key and iv
233 BYTE symParmString[MAX_SYM_KEY_BYTES + MAX_SYM_BLOCK_SIZE];
234 // Symmetric key size in byte
235 UINT16 keySize = (keySizeInBits + 7) / 8;
236 TPM2B_IV iv;
237
238 iv.t.size = CryptGetSymmetricBlockSize(symAlg, keySizeInBits);
239 // If there is decryption to do...
240 if(iv.t.size > 0)
241 {
242 // Generate key and iv
243 CryptKDFa(hash, key, CFB_KEY, nonceCaller, nonceTpm,
244 keySizeInBits + (iv.t.size * 8), symParmString, NULL, FALSE);
245 MemoryCopy(iv.t.buffer, &symParmString[keySize], iv.t.size);
246
247 CryptSymmetricDecrypt(data, symAlg, keySizeInBits, symParmString,
248 &iv, ALG_CFB_VALUE, dataSize, data);
249 }
250 return;
251 }
252
253 //*** ParmEncryptSym()
254 // This function performs parameter encryption using symmetric block cipher.
255 /*(See part 1 specification)
256 // When parameter decryption uses a symmetric block cipher, an encryption
257 // key and IV will be generated from:
258 // KDFa(hash, sessionAuth, "CFB", nonceNewer, nonceOlder, bits) (24)
259 // Where:
260 // hash the hash function associated with the session
261 // sessionAuth the sessionAuth associated with the session
262 // nonceNewer nonceTPM for a response
263 // nonceOlder nonceCaller for a response
264 // bits the number of bits required for the symmetric key
265 // plus an IV
266 */
267 void
268 ParmEncryptSym(
269 TPM_ALG_ID symAlg, // IN: symmetric algorithm
270 TPM_ALG_ID hash, // IN: hash algorithm for KDFa
271 UINT16 keySizeInBits, // IN: symmetric key size in bits
272 TPM2B *key, // IN: KDF HMAC key
273 TPM2B *nonceCaller, // IN: nonce caller
274 TPM2B *nonceTpm, // IN: nonce TPM
275 UINT32 dataSize, // IN: size of parameter buffer
276 BYTE *data // OUT: buffer to be encrypted
277 )
278 {
279 // KDF output buffer
280 // It contains parameters for the CFB encryption
281 BYTE symParmString[MAX_SYM_KEY_BYTES + MAX_SYM_BLOCK_SIZE];
282
283 // Symmetric key size in bytes
284 UINT16 keySize = (keySizeInBits + 7) / 8;
285
286 TPM2B_IV iv;
287
288 iv.t.size = CryptGetSymmetricBlockSize(symAlg, keySizeInBits);
289 // See if there is any encryption to do
290 if(iv.t.size > 0)
291 {
292 // Generate key and iv
293 CryptKDFa(hash, key, CFB_KEY, nonceTpm, nonceCaller,
294 keySizeInBits + (iv.t.size * 8), symParmString, NULL, FALSE);
295 MemoryCopy(iv.t.buffer, &symParmString[keySize], iv.t.size);
296
297 CryptSymmetricEncrypt(data, symAlg, keySizeInBits, symParmString, &iv,
298 ALG_CFB_VALUE, dataSize, data);
299 }
300 return;
301 }
302
303 //*** CryptGenerateKeySymmetric()
304 // This function generates a symmetric cipher key. The derivation process is
305 // determined by the type of the provided 'rand'
306 // Return type: TPM_RC
307 // TPM_RC_NO_RESULT cannot get a random value
308 // TPM_RC_KEY_SIZE key size in the public area does not match the size
309 // in the sensitive creation area
310 // TPM_RC_KEY provided key value is not allowed
311 static TPM_RC
312 CryptGenerateKeySymmetric(
313 TPMT_PUBLIC *publicArea, // IN/OUT: The public area template
314 // for the new key.
315 TPMT_SENSITIVE *sensitive, // OUT: sensitive area
316 TPMS_SENSITIVE_CREATE *sensitiveCreate, // IN: sensitive creation data
317 RAND_STATE *rand // IN: the "entropy" source for
318 )
319 {
320 UINT16 keyBits = publicArea->parameters.symDetail.sym.keyBits.sym;
321 TPM_RC result;
322 //
323 // only do multiples of RADIX_BITS
324 if((keyBits % RADIX_BITS) != 0)
325 return TPM_RC_KEY_SIZE;
326 // If this is not a new key, then the provided key data must be the right size
327 if(sensitiveCreate->data.t.size != 0)
328 {
329 result = CryptSymKeyValidate(&publicArea->parameters.symDetail.sym,
330 (TPM2B_SYM_KEY *)&sensitiveCreate->data);
331 if(result == TPM_RC_SUCCESS)
332 MemoryCopy2B(&sensitive->sensitive.sym.b, &sensitiveCreate->data.b,
333 sizeof(sensitive->sensitive.sym.t.buffer));
334 }
335 #if ALG_TDES
336 else if(publicArea->parameters.symDetail.sym.algorithm == ALG_TDES_VALUE)
337 {
338 result = CryptGenerateKeyDes(publicArea, sensitive, rand);
339 }
340 #endif
341 else
342 {
343 sensitive->sensitive.sym.t.size =
344 DRBG_Generate(rand, sensitive->sensitive.sym.t.buffer,
345 BITS_TO_BYTES(keyBits));
346 if(g_inFailureMode)
347 result = TPM_RC_FAILURE;
348 else if(sensitive->sensitive.sym.t.size == 0)
349 result = TPM_RC_NO_RESULT;
350 else
351 result = TPM_RC_SUCCESS;
352 }
353 return result;
354 }
355
356 //*** CryptXORObfuscation()
357 // This function implements XOR obfuscation. It should not be called if the
358 // hash algorithm is not implemented. The only return value from this function
359 // is TPM_RC_SUCCESS.
360 void
361 CryptXORObfuscation(
362 TPM_ALG_ID hash, // IN: hash algorithm for KDF
363 TPM2B *key, // IN: KDF key
364 TPM2B *contextU, // IN: contextU
365 TPM2B *contextV, // IN: contextV
366 UINT32 dataSize, // IN: size of data buffer
367 BYTE *data // IN/OUT: data to be XORed in place
368 )
369 {
370 BYTE mask[MAX_DIGEST_SIZE]; // Allocate a digest sized buffer
371 BYTE *pm;
372 UINT32 i;
373 UINT32 counter = 0;
374 UINT16 hLen = CryptHashGetDigestSize(hash);
375 UINT32 requestSize = dataSize * 8;
376 INT32 remainBytes = (INT32)dataSize;
377
378 pAssert((key != NULL) && (data != NULL) && (hLen != 0));
379
380 // Call KDFa to generate XOR mask
381 for(; remainBytes > 0; remainBytes -= hLen)
382 {
383 // Make a call to KDFa to get next iteration
384 CryptKDFa(hash, key, XOR_KEY, contextU, contextV,
385 requestSize, mask, &counter, TRUE);
386
387 // XOR next piece of the data
388 pm = mask;
389 for(i = hLen < remainBytes ? hLen : remainBytes; i > 0; i--)
390 *data++ ^= *pm++;
391 }
392 return;
393 }
394
395 //****************************************************************************
396 //** Initialization and shut down
397 //****************************************************************************
398
399 //*** CryptInit()
400 // This function is called when the TPM receives a _TPM_Init indication.
401 //
402 // NOTE: The hash algorithms do not have to be tested, they just need to be
403 // available. They have to be tested before the TPM can accept HMAC authorization
404 // or return any result that relies on a hash algorithm.
405 // Return Type: BOOL
406 // TRUE(1) initializations succeeded
407 // FALSE(0) initialization failed and caller should place the TPM into
408 // Failure Mode
409 BOOL
410 CryptInit(
411 void
412 )
413 {
414 BOOL ok;
415 // Initialize the vector of implemented algorithms
416 AlgorithmGetImplementedVector(&g_implementedAlgorithms);
417
418 // Indicate that all test are necessary
419 CryptInitializeToTest();
420
421 // Do any library initializations that are necessary. If any fails,
422 // the caller should go into failure mode;
423 ok = SupportLibInit();
424 ok = ok && CryptSymInit();
425 ok = ok && CryptRandInit();
426 ok = ok && CryptHashInit();
427 #if ALG_RSA
428 ok = ok && CryptRsaInit();
429 #endif // ALG_RSA
430 #if ALG_ECC
431 ok = ok && CryptEccInit();
432 #endif // ALG_ECC
433 return ok;
434 }
435
436 //*** CryptStartup()
437 // This function is called by TPM2_Startup() to initialize the functions in
438 // this cryptographic library and in the provided CryptoLibrary. This function
439 // and CryptUtilInit() are both provided so that the implementation may move the
440 // initialization around to get the best interaction.
441 // Return Type: BOOL
442 // TRUE(1) startup succeeded
443 // FALSE(0) startup failed and caller should place the TPM into
444 // Failure Mode
445 BOOL
446 CryptStartup(
447 STARTUP_TYPE type // IN: the startup type
448 )
449 {
450 BOOL OK;
451 NOT_REFERENCED(type);
452
453 OK = CryptSymStartup() && CryptRandStartup() && CryptHashStartup()
454 #if ALG_RSA
455 && CryptRsaStartup()
456 #endif // ALG_RSA
457 #if ALG_ECC
458 && CryptEccStartup()
459 #endif // ALG_ECC
460 ;
461 #if ALG_ECC
462 // Don't directly check for SU_RESET because that is the default
463 if(OK && (type != SU_RESTART) && (type != SU_RESUME))
464 {
465 // If the shutdown was orderly, then the values recovered from NV will
466 // be OK to use.
467 // Get a new random commit nonce
468 gr.commitNonce.t.size = sizeof(gr.commitNonce.t.buffer);
469 CryptRandomGenerate(gr.commitNonce.t.size, gr.commitNonce.t.buffer);
470 // Reset the counter and commit array
471 gr.commitCounter = 0;
472 MemorySet(gr.commitArray, 0, sizeof(gr.commitArray));
473 }
474 #endif // ALG_ECC
475 return OK;
476 }
477
478 //****************************************************************************
479 //** Algorithm-Independent Functions
480 //****************************************************************************
481 //*** Introduction
482 // These functions are used generically when a function of a general type
483 // (e.g., symmetric encryption) is required. The functions will modify the
484 // parameters as required to interface to the indicated algorithms.
485 //
486 //*** CryptIsAsymAlgorithm()
487 // This function indicates if an algorithm is an asymmetric algorithm.
488 // Return Type: BOOL
489 // TRUE(1) if it is an asymmetric algorithm
490 // FALSE(0) if it is not an asymmetric algorithm
491 BOOL
492 CryptIsAsymAlgorithm(
493 TPM_ALG_ID algID // IN: algorithm ID
494 )
495 {
496 switch(algID)
497 {
498 #if ALG_RSA
499 case ALG_RSA_VALUE:
500 #endif
501 #if ALG_ECC
502 case ALG_ECC_VALUE:
503 #endif
504 return TRUE;
505 break;
506 default:
507 break;
508 }
509 return FALSE;
510 }
511
512 //*** CryptSecretEncrypt()
513 // This function creates a secret value and its associated secret structure using
514 // an asymmetric algorithm.
515 //
516 // This function is used by TPM2_Rewrap() TPM2_MakeCredential(),
517 // and TPM2_Duplicate().
518 // Return Type: TPM_RC
519 // TPM_RC_ATTRIBUTES 'keyHandle' does not reference a valid decryption key
520 // TPM_RC_KEY invalid ECC key (public point is not on the curve)
521 // TPM_RC_SCHEME RSA key with an unsupported padding scheme
522 // TPM_RC_VALUE numeric value of the data to be decrypted is greater
523 // than the RSA key modulus
524 TPM_RC
525 CryptSecretEncrypt(
526 OBJECT *encryptKey, // IN: encryption key object
527 const TPM2B *label, // IN: a null-terminated string as L
528 TPM2B_DATA *data, // OUT: secret value
529 TPM2B_ENCRYPTED_SECRET *secret // OUT: secret structure
530 )
531 {
532 TPMT_RSA_DECRYPT scheme;
533 TPM_RC result = TPM_RC_SUCCESS;
534 //
535 if(data == NULL || secret == NULL)
536 return TPM_RC_FAILURE;
537
538 // The output secret value has the size of the digest produced by the nameAlg.
539 data->t.size = CryptHashGetDigestSize(encryptKey->publicArea.nameAlg);
540 // The encryption scheme is OAEP using the nameAlg of the encrypt key.
541 scheme.scheme = ALG_OAEP_VALUE;
542 scheme.details.anySig.hashAlg = encryptKey->publicArea.nameAlg;
543
544 if(!IS_ATTRIBUTE(encryptKey->publicArea.objectAttributes, TPMA_OBJECT, decrypt))
545 return TPM_RC_ATTRIBUTES;
546 switch(encryptKey->publicArea.type)
547 {
548 #if ALG_RSA
549 case ALG_RSA_VALUE:
550 {
551 // Create secret data from RNG
552 CryptRandomGenerate(data->t.size, data->t.buffer);
553
554 // Encrypt the data by RSA OAEP into encrypted secret
555 result = CryptRsaEncrypt((TPM2B_PUBLIC_KEY_RSA *)secret, &data->b,
556 encryptKey, &scheme, label, NULL);
557 }
558 break;
559 #endif // ALG_RSA
560
561 #if ALG_ECC
562 case ALG_ECC_VALUE:
563 {
564 TPMS_ECC_POINT eccPublic;
565 TPM2B_ECC_PARAMETER eccPrivate;
566 TPMS_ECC_POINT eccSecret;
567 BYTE *buffer = secret->t.secret;
568
569 // Need to make sure that the public point of the key is on the
570 // curve defined by the key.
571 if(!CryptEccIsPointOnCurve(
572 encryptKey->publicArea.parameters.eccDetail.curveID,
573 &encryptKey->publicArea.unique.ecc))
574 result = TPM_RC_KEY;
575 else
576 {
577 // Call crypto engine to create an auxiliary ECC key
578 // We assume crypt engine initialization should always success.
579 // Otherwise, TPM should go to failure mode.
580
581 CryptEccNewKeyPair(&eccPublic, &eccPrivate,
582 encryptKey->publicArea.parameters.eccDetail.curveID);
583 // Marshal ECC public to secret structure. This will be used by the
584 // recipient to decrypt the secret with their private key.
585 secret->t.size = TPMS_ECC_POINT_Marshal(&eccPublic, &buffer, NULL);
586
587 // Compute ECDH shared secret which is R = [d]Q where d is the
588 // private part of the ephemeral key and Q is the public part of a
589 // TPM key. TPM_RC_KEY error return from CryptComputeECDHSecret
590 // because the auxiliary ECC key is just created according to the
591 // parameters of input ECC encrypt key.
592 if(CryptEccPointMultiply(&eccSecret,
593 encryptKey->publicArea.parameters.eccDetail.curveID,
594 &encryptKey->publicArea.unique.ecc, &eccPrivate,
595 NULL, NULL)
596 != TPM_RC_SUCCESS)
597 result = TPM_RC_KEY;
598 else
599 {
600 // The secret value is computed from Z using KDFe as:
601 // secret := KDFe(HashID, Z, Use, PartyUInfo, PartyVInfo, bits)
602 // Where:
603 // HashID the nameAlg of the decrypt key
604 // Z the x coordinate (Px) of the product (P) of the point
605 // (Q) of the secret and the private x coordinate (de,V)
606 // of the decryption key
607 // Use a null-terminated string containing "SECRET"
608 // PartyUInfo the x coordinate of the point in the secret
609 // (Qe,U )
610 // PartyVInfo the x coordinate of the public key (Qs,V )
611 // bits the number of bits in the digest of HashID
612 // Retrieve seed from KDFe
613 CryptKDFe(encryptKey->publicArea.nameAlg, &eccSecret.x.b,
614 label, &eccPublic.x.b,
615 &encryptKey->publicArea.unique.ecc.x.b,
616 data->t.size * 8, data->t.buffer);
617 }
618 }
619 }
620 break;
621 #endif // ALG_ECC
622 default:
623 FAIL(FATAL_ERROR_INTERNAL);
624 break;
625 }
626 return result;
627 }
628
629 //*** CryptSecretDecrypt()
630 // Decrypt a secret value by asymmetric (or symmetric) algorithm
631 // This function is used for ActivateCredential and Import for asymmetric
632 // decryption, and StartAuthSession for both asymmetric and symmetric
633 // decryption process
634 //
635 // Return Type: TPM_RC
636 // TPM_RC_ATTRIBUTES RSA key is not a decryption key
637 // TPM_RC_BINDING Invalid RSA key (public and private parts are not
638 // cryptographically bound.
639 // TPM_RC_ECC_POINT ECC point in the secret is not on the curve
640 // TPM_RC_INSUFFICIENT failed to retrieve ECC point from the secret
641 // TPM_RC_NO_RESULT multiplication resulted in ECC point at infinity
642 // TPM_RC_SIZE data to decrypt is not of the same size as RSA key
643 // TPM_RC_VALUE For RSA key, numeric value of the encrypted data is
644 // greater than the modulus, or the recovered data is
645 // larger than the output buffer.
646 // For keyedHash or symmetric key, the secret is
647 // larger than the size of the digest produced by
648 // the name algorithm.
649 // TPM_RC_FAILURE internal error
650 TPM_RC
651 CryptSecretDecrypt(
652 OBJECT *decryptKey, // IN: decrypt key
653 TPM2B_NONCE *nonceCaller, // IN: nonceCaller. It is needed for
654 // symmetric decryption. For
655 // asymmetric decryption, this
656 // parameter is NULL
657 const TPM2B *label, // IN: a value for L
658 TPM2B_ENCRYPTED_SECRET *secret, // IN: input secret
659 TPM2B_DATA *data // OUT: decrypted secret value
660 )
661 {
662 TPM_RC result = TPM_RC_SUCCESS;
663
664 // Decryption for secret
665 switch(decryptKey->publicArea.type)
666 {
667 #if ALG_RSA
668 case ALG_RSA_VALUE:
669 {
670 TPMT_RSA_DECRYPT scheme;
671 TPMT_RSA_SCHEME *keyScheme
672 = &decryptKey->publicArea.parameters.rsaDetail.scheme;
673 UINT16 digestSize;
674
675 scheme = *(TPMT_RSA_DECRYPT *)keyScheme;
676 // If the key scheme is ALG_NULL_VALUE, set the scheme to OAEP and
677 // set the algorithm to the name algorithm.
678 if(scheme.scheme == ALG_NULL_VALUE)
679 {
680 // Use OAEP scheme
681 scheme.scheme = ALG_OAEP_VALUE;
682 scheme.details.oaep.hashAlg = decryptKey->publicArea.nameAlg;
683 }
684 // use the digestSize as an indicator of whether or not the scheme
685 // is using a supported hash algorithm.
686 // Note: depending on the scheme used for encryption, a hashAlg might
687 // not be needed. However, the return value has to have some upper
688 // limit on the size. In this case, it is the size of the digest of the
689 // hash algorithm. It is checked after the decryption is done but, there
690 // is no point in doing the decryption if the size is going to be
691 // 'wrong' anyway.
692 digestSize = CryptHashGetDigestSize(scheme.details.oaep.hashAlg);
693 if(scheme.scheme != ALG_OAEP_VALUE || digestSize == 0)
694 return TPM_RC_SCHEME;
695
696 // Set the output buffer capacity
697 data->t.size = sizeof(data->t.buffer);
698
699 // Decrypt seed by RSA OAEP
700 result = CryptRsaDecrypt(&data->b, &secret->b,
701 decryptKey, &scheme, label);
702 if((result == TPM_RC_SUCCESS) && (data->t.size > digestSize))
703 result = TPM_RC_VALUE;
704 }
705 break;
706 #endif // ALG_RSA
707 #if ALG_ECC
708 case ALG_ECC_VALUE:
709 {
710 TPMS_ECC_POINT eccPublic;
711 TPMS_ECC_POINT eccSecret;
712 BYTE *buffer = secret->t.secret;
713 INT32 size = secret->t.size;
714
715 // Retrieve ECC point from secret buffer
716 result = TPMS_ECC_POINT_Unmarshal(&eccPublic, &buffer, &size);
717 if(result == TPM_RC_SUCCESS)
718 {
719 result = CryptEccPointMultiply(&eccSecret,
720 decryptKey->publicArea.parameters.eccDetail.curveID,
721 &eccPublic, &decryptKey->sensitive.sensitive.ecc,
722 NULL, NULL);
723 if(result == TPM_RC_SUCCESS)
724 {
725 // Set the size of the "recovered" secret value to be the size
726 // of the digest produced by the nameAlg.
727 data->t.size =
728 CryptHashGetDigestSize(decryptKey->publicArea.nameAlg);
729
730 // The secret value is computed from Z using KDFe as:
731 // secret := KDFe(HashID, Z, Use, PartyUInfo, PartyVInfo, bits)
732 // Where:
733 // HashID -- the nameAlg of the decrypt key
734 // Z -- the x coordinate (Px) of the product (P) of the point
735 // (Q) of the secret and the private x coordinate (de,V)
736 // of the decryption key
737 // Use -- a null-terminated string containing "SECRET"
738 // PartyUInfo -- the x coordinate of the point in the secret
739 // (Qe,U )
740 // PartyVInfo -- the x coordinate of the public key (Qs,V )
741 // bits -- the number of bits in the digest of HashID
742 // Retrieve seed from KDFe
743 CryptKDFe(decryptKey->publicArea.nameAlg, &eccSecret.x.b, label,
744 &eccPublic.x.b,
745 &decryptKey->publicArea.unique.ecc.x.b,
746 data->t.size * 8, data->t.buffer);
747 }
748 }
749 }
750 break;
751 #endif // ALG_ECC
752 #if !ALG_KEYEDHASH
753 # error "KEYEDHASH support is required"
754 #endif
755 case ALG_KEYEDHASH_VALUE:
756 // The seed size can not be bigger than the digest size of nameAlg
757 if(secret->t.size >
758 CryptHashGetDigestSize(decryptKey->publicArea.nameAlg))
759 result = TPM_RC_VALUE;
760 else
761 {
762 // Retrieve seed by XOR Obfuscation:
763 // seed = XOR(secret, hash, key, nonceCaller, nullNonce)
764 // where:
765 // secret the secret parameter from the TPM2_StartAuthHMAC
766 // command that contains the seed value
767 // hash nameAlg of tpmKey
768 // key the key or data value in the object referenced by
769 // entityHandle in the TPM2_StartAuthHMAC command
770 // nonceCaller the parameter from the TPM2_StartAuthHMAC command
771 // nullNonce a zero-length nonce
772 // XOR Obfuscation in place
773 CryptXORObfuscation(decryptKey->publicArea.nameAlg,
774 &decryptKey->sensitive.sensitive.bits.b,
775 &nonceCaller->b, NULL,
776 secret->t.size, secret->t.secret);
777 // Copy decrypted seed
778 MemoryCopy2B(&data->b, &secret->b, sizeof(data->t.buffer));
779 }
780 break;
781 case ALG_SYMCIPHER_VALUE:
782 {
783 TPM2B_IV iv = {{0}};
784 TPMT_SYM_DEF_OBJECT *symDef;
785 // The seed size can not be bigger than the digest size of nameAlg
786 if(secret->t.size >
787 CryptHashGetDigestSize(decryptKey->publicArea.nameAlg))
788 result = TPM_RC_VALUE;
789 else
790 {
791 symDef = &decryptKey->publicArea.parameters.symDetail.sym;
792 iv.t.size = CryptGetSymmetricBlockSize(symDef->algorithm,
793 symDef->keyBits.sym);
794 if(iv.t.size == 0)
795 return TPM_RC_FAILURE;
796 if(nonceCaller->t.size >= iv.t.size)
797 {
798 MemoryCopy(iv.t.buffer, nonceCaller->t.buffer, iv.t.size);
799 }
800 else
801 {
802 if(nonceCaller->t.size > sizeof(iv.t.buffer))
803 return TPM_RC_FAILURE;
804 MemoryCopy(iv.b.buffer, nonceCaller->t.buffer,
805 nonceCaller->t.size);
806 }
807 // make sure secret will fit
808 if(secret->t.size > data->t.size)
809 return TPM_RC_FAILURE;
810 data->t.size = secret->t.size;
811 // CFB decrypt, using nonceCaller as iv
812 CryptSymmetricDecrypt(data->t.buffer, symDef->algorithm,
813 symDef->keyBits.sym,
814 decryptKey->sensitive.sensitive.sym.t.buffer,
815 &iv, ALG_CFB_VALUE, secret->t.size,
816 secret->t.secret);
817 }
818 }
819 break;
820 default:
821 FAIL(FATAL_ERROR_INTERNAL);
822 break;
823 }
824 return result;
825 }
826
827 //*** CryptParameterEncryption()
828 // This function does in-place encryption of a response parameter.
829 void
830 CryptParameterEncryption(
831 TPM_HANDLE handle, // IN: encrypt session handle
832 TPM2B *nonceCaller, // IN: nonce caller
833 UINT16 leadingSizeInByte, // IN: the size of the leading size field in
834 // bytes
835 TPM2B_AUTH *extraKey, // IN: additional key material other than
836 // sessionAuth
837 BYTE *buffer // IN/OUT: parameter buffer to be encrypted
838 )
839 {
840 SESSION *session = SessionGet(handle); // encrypt session
841 TPM2B_TYPE(TEMP_KEY, (sizeof(extraKey->t.buffer)
842 + sizeof(session->sessionKey.t.buffer)));
843 TPM2B_TEMP_KEY key; // encryption key
844 UINT32 cipherSize = 0; // size of cipher text
845 //
846 // Retrieve encrypted data size.
847 if(leadingSizeInByte == 2)
848 {
849 // Extract the first two bytes as the size field as the data size
850 // encrypt
851 cipherSize = (UINT32)BYTE_ARRAY_TO_UINT16(buffer);
852 // advance the buffer
853 buffer = &buffer[2];
854 }
855 #ifdef TPM4B
856 else if(leadingSizeInByte == 4)
857 {
858 // use the first four bytes to indicate the number of bytes to encrypt
859 cipherSize = BYTE_ARRAY_TO_UINT32(buffer);
860 //advance pointer
861 buffer = &buffer[4];
862 }
863 #endif
864 else
865 {
866 FAIL(FATAL_ERROR_INTERNAL);
867 }
868
869 // Compute encryption key by concatenating sessionKey with extra key
870 MemoryCopy2B(&key.b, &session->sessionKey.b, sizeof(key.t.buffer));
871 MemoryConcat2B(&key.b, &extraKey->b, sizeof(key.t.buffer));
872
873 if(session->symmetric.algorithm == ALG_XOR_VALUE)
874
875 // XOR parameter encryption formulation:
876 // XOR(parameter, hash, sessionAuth, nonceNewer, nonceOlder)
877 CryptXORObfuscation(session->authHashAlg, &(key.b),
878 &(session->nonceTPM.b),
879 nonceCaller, cipherSize, buffer);
880 else
881 ParmEncryptSym(session->symmetric.algorithm, session->authHashAlg,
882 session->symmetric.keyBits.aes, &(key.b),
883 nonceCaller, &(session->nonceTPM.b),
884 cipherSize, buffer);
885 return;
886 }
887
888 //*** CryptParameterDecryption()
889 // This function does in-place decryption of a command parameter.
890 // Return Type: TPM_RC
891 // TPM_RC_SIZE The number of bytes in the input buffer is less than
892 // the number of bytes to be decrypted.
893 TPM_RC
894 CryptParameterDecryption(
895 TPM_HANDLE handle, // IN: encrypted session handle
896 TPM2B *nonceCaller, // IN: nonce caller
897 UINT32 bufferSize, // IN: size of parameter buffer
898 UINT16 leadingSizeInByte, // IN: the size of the leading size field in
899 // byte
900 TPM2B_AUTH *extraKey, // IN: the authValue
901 BYTE *buffer // IN/OUT: parameter buffer to be decrypted
902 )
903 {
904 SESSION *session = SessionGet(handle); // encrypt session
905 // The HMAC key is going to be the concatenation of the session key and any
906 // additional key material (like the authValue). The size of both of these
907 // is the size of the buffer which can contain a TPMT_HA.
908 TPM2B_TYPE(HMAC_KEY, (sizeof(extraKey->t.buffer)
909 + sizeof(session->sessionKey.t.buffer)));
910 TPM2B_HMAC_KEY key; // decryption key
911 UINT32 cipherSize = 0; // size of cipher text
912 //
913 // Retrieve encrypted data size.
914 if(leadingSizeInByte == 2)
915 {
916 // The first two bytes of the buffer are the size of the
917 // data to be decrypted
918 cipherSize = (UINT32)BYTE_ARRAY_TO_UINT16(buffer);
919 buffer = &buffer[2]; // advance the buffer
920 }
921 #ifdef TPM4B
922 else if(leadingSizeInByte == 4)
923 {
924 // the leading size is four bytes so get the four byte size field
925 cipherSize = BYTE_ARRAY_TO_UINT32(buffer);
926 buffer = &buffer[4]; //advance pointer
927 }
928 #endif
929 else
930 {
931 FAIL(FATAL_ERROR_INTERNAL);
932 }
933 if(cipherSize > bufferSize)
934 return TPM_RC_SIZE;
935
936 // Compute decryption key by concatenating sessionAuth with extra input key
937 MemoryCopy2B(&key.b, &session->sessionKey.b, sizeof(key.t.buffer));
938 MemoryConcat2B(&key.b, &extraKey->b, sizeof(key.t.buffer));
939
940 if(session->symmetric.algorithm == ALG_XOR_VALUE)
941 // XOR parameter decryption formulation:
942 // XOR(parameter, hash, sessionAuth, nonceNewer, nonceOlder)
943 // Call XOR obfuscation function
944 CryptXORObfuscation(session->authHashAlg, &key.b, nonceCaller,
945 &(session->nonceTPM.b), cipherSize, buffer);
946 else
947 // Assume that it is one of the symmetric block ciphers.
948 ParmDecryptSym(session->symmetric.algorithm, session->authHashAlg,
949 session->symmetric.keyBits.sym,
950 &key.b, nonceCaller, &session->nonceTPM.b,
951 cipherSize, buffer);
952
953 return TPM_RC_SUCCESS;
954 }
955
956 //*** CryptComputeSymmetricUnique()
957 // This function computes the unique field in public area for symmetric objects.
958 void
959 CryptComputeSymmetricUnique(
960 TPMT_PUBLIC *publicArea, // IN: the object's public area
961 TPMT_SENSITIVE *sensitive, // IN: the associated sensitive area
962 TPM2B_DIGEST *unique // OUT: unique buffer
963 )
964 {
965 // For parents (symmetric and derivation), use an HMAC to compute
966 // the 'unique' field
967 if(IS_ATTRIBUTE(publicArea->objectAttributes, TPMA_OBJECT, restricted)
968 && IS_ATTRIBUTE(publicArea->objectAttributes, TPMA_OBJECT, decrypt))
969 {
970 // Unique field is HMAC(sensitive->seedValue, sensitive->sensitive)
971 HMAC_STATE hmacState;
972 unique->b.size = CryptHmacStart2B(&hmacState, publicArea->nameAlg,
973 &sensitive->seedValue.b);
974 CryptDigestUpdate2B(&hmacState.hashState,
975 &sensitive->sensitive.any.b);
976 CryptHmacEnd2B(&hmacState, &unique->b);
977 }
978 else
979 {
980 HASH_STATE hashState;
981 // Unique := Hash(sensitive->seedValue || sensitive->sensitive)
982 unique->t.size = CryptHashStart(&hashState, publicArea->nameAlg);
983 CryptDigestUpdate2B(&hashState, &sensitive->seedValue.b);
984 CryptDigestUpdate2B(&hashState, &sensitive->sensitive.any.b);
985 CryptHashEnd2B(&hashState, &unique->b);
986 }
987 return;
988 }
989
990 //*** CryptCreateObject()
991 // This function creates an object.
992 // For an asymmetric key, it will create a key pair and, for a parent key, a seed
993 // value for child protections.
994 //
995 // For an symmetric object, (TPM_ALG_SYMCIPHER or TPM_ALG_KEYEDHASH), it will
996 // create a secret key if the caller did not provide one. It will create a random
997 // secret seed value that is hashed with the secret value to create the public
998 // unique value.
999 //
1000 // 'publicArea', 'sensitive', and 'sensitiveCreate' are the only required parameters
1001 // and are the only ones that are used by TPM2_Create(). The other parameters
1002 // are optional and are used when the generated Object needs to be deterministic.
1003 // This is the case for both Primary Objects and Derived Objects.
1004 //
1005 // When a seed value is provided, a RAND_STATE will be populated and used for
1006 // all operations in the object generation that require a random number. In the
1007 // simplest case, TPM2_CreatePrimary() will use 'seed', 'label' and 'context' with
1008 // context being the hash of the template. If the Primary Object is in
1009 // the Endorsement hierarchy, it will also populate 'proof' with ehProof.
1010 //
1011 // For derived keys, 'seed' will be the secret value from the parent, 'label' and
1012 // 'context' will be set according to the parameters of TPM2_CreateLoaded() and
1013 // 'hashAlg' will be set which causes the RAND_STATE to be a KDF generator.
1014 //
1015 // Return Type: TPM_RC
1016 // TPM_RC_KEY a provided key is not an allowed value
1017 // TPM_RC_KEY_SIZE key size in the public area does not match the size
1018 // in the sensitive creation area for a symmetric key
1019 // TPM_RC_NO_RESULT unable to get random values (only in derivation)
1020 // TPM_RC_RANGE for an RSA key, the exponent is not supported
1021 // TPM_RC_SIZE sensitive data size is larger than allowed for the
1022 // scheme for a keyed hash object
1023 // TPM_RC_VALUE exponent is not prime or could not find a prime using
1024 // the provided parameters for an RSA key;
1025 // unsupported name algorithm for an ECC key
1026 TPM_RC
1027 CryptCreateObject(
1028 OBJECT *object, // IN: new object structure pointer
1029 TPMS_SENSITIVE_CREATE *sensitiveCreate, // IN: sensitive creation
1030 RAND_STATE *rand // IN: the random number generator
1031 // to use
1032 )
1033 {
1034 TPMT_PUBLIC *publicArea = &object->publicArea;
1035 TPMT_SENSITIVE *sensitive = &object->sensitive;
1036 TPM_RC result = TPM_RC_SUCCESS;
1037 //
1038 // Set the sensitive type for the object
1039 sensitive->sensitiveType = publicArea->type;
1040
1041 // For all objects, copy the initial authorization data
1042 sensitive->authValue = sensitiveCreate->userAuth;
1043
1044 // If the TPM is the source of the data, set the size of the provided data to
1045 // zero so that there's no confusion about what to do.
1046 if(IS_ATTRIBUTE(publicArea->objectAttributes,
1047 TPMA_OBJECT, sensitiveDataOrigin))
1048 sensitiveCreate->data.t.size = 0;
1049
1050 // Generate the key and unique fields for the asymmetric keys and just the
1051 // sensitive value for symmetric object
1052 switch(publicArea->type)
1053 {
1054 #if ALG_RSA
1055 // Create RSA key
1056 case ALG_RSA_VALUE:
1057 // RSA uses full object so that it has a place to put the private
1058 // exponent
1059 result = CryptRsaGenerateKey(publicArea, sensitive, rand);
1060 break;
1061 #endif // ALG_RSA
1062
1063 #if ALG_ECC
1064 // Create ECC key
1065 case ALG_ECC_VALUE:
1066 result = CryptEccGenerateKey(publicArea, sensitive, rand);
1067 break;
1068 #endif // ALG_ECC
1069 case ALG_SYMCIPHER_VALUE:
1070 result = CryptGenerateKeySymmetric(publicArea, sensitive,
1071 sensitiveCreate, rand);
1072 break;
1073 case ALG_KEYEDHASH_VALUE:
1074 result = CryptGenerateKeyedHash(publicArea, sensitive,
1075 sensitiveCreate, rand);
1076 break;
1077 default:
1078 FAIL(FATAL_ERROR_INTERNAL);
1079 break;
1080 }
1081 if(result != TPM_RC_SUCCESS)
1082 return result;
1083 // Create the sensitive seed value
1084 // If this is a primary key in the endorsement hierarchy, stir the DRBG state
1085 // This implementation uses both shProof and ehProof to make sure that there
1086 // is no leakage of either.
1087 if(object->attributes.primary && object->attributes.epsHierarchy)
1088 {
1089 DRBG_AdditionalData((DRBG_STATE *)rand, &gp.shProof.b);
1090 DRBG_AdditionalData((DRBG_STATE *)rand, &gp.ehProof.b);
1091 }
1092 // Generate a seedValue that is the size of the digest produced by nameAlg
1093 sensitive->seedValue.t.size =
1094 DRBG_Generate(rand, sensitive->seedValue.t.buffer,
1095 CryptHashGetDigestSize(publicArea->nameAlg));
1096 if(g_inFailureMode)
1097 return TPM_RC_FAILURE;
1098 else if(sensitive->seedValue.t.size == 0)
1099 return TPM_RC_NO_RESULT;
1100 // For symmetric objects, need to compute the unique value for the public area
1101 if(publicArea->type == ALG_SYMCIPHER_VALUE
1102 || publicArea->type == ALG_KEYEDHASH_VALUE)
1103 {
1104 CryptComputeSymmetricUnique(publicArea, sensitive, &publicArea->unique.sym);
1105 }
1106 else
1107 {
1108 // if this is an asymmetric key and it isn't a parent, then
1109 // get rid of the seed.
1110 if(IS_ATTRIBUTE(publicArea->objectAttributes, TPMA_OBJECT, sign)
1111 || !IS_ATTRIBUTE(publicArea->objectAttributes, TPMA_OBJECT, restricted))
1112 memset(&sensitive->seedValue, 0, sizeof(sensitive->seedValue));
1113 }
1114 // Compute the name
1115 PublicMarshalAndComputeName(publicArea, &object->name);
1116 return result;
1117 }
1118
1119 //*** CryptGetSignHashAlg()
1120 // Get the hash algorithm of signature from a TPMT_SIGNATURE structure.
1121 // It assumes the signature is not NULL
1122 // This is a function for easy access
1123 TPMI_ALG_HASH
1124 CryptGetSignHashAlg(
1125 TPMT_SIGNATURE *auth // IN: signature
1126 )
1127 {
1128 if(auth->sigAlg == ALG_NULL_VALUE)
1129 FAIL(FATAL_ERROR_INTERNAL);
1130
1131 // Get authHash algorithm based on signing scheme
1132 switch(auth->sigAlg)
1133 {
1134 #if ALG_RSA
1135 // If RSA is supported, both RSASSA and RSAPSS are required
1136 # if !defined ALG_RSASSA_VALUE || !defined ALG_RSAPSS_VALUE
1137 # error "RSASSA and RSAPSS are required for RSA"
1138 # endif
1139 case ALG_RSASSA_VALUE:
1140 return auth->signature.rsassa.hash;
1141 case ALG_RSAPSS_VALUE:
1142 return auth->signature.rsapss.hash;
1143 #endif // ALG_RSA
1144
1145 #if ALG_ECC
1146 // If ECC is defined, ECDSA is mandatory
1147 # if !ALG_ECDSA
1148 # error "ECDSA is requried for ECC"
1149 # endif
1150 case ALG_ECDSA_VALUE:
1151 // SM2 and ECSCHNORR are optional
1152
1153 # if ALG_SM2
1154 case ALG_SM2_VALUE:
1155 # endif
1156 # if ALG_ECSCHNORR
1157 case ALG_ECSCHNORR_VALUE:
1158 # endif
1159 //all ECC signatures look the same
1160 return auth->signature.ecdsa.hash;
1161
1162 # if ALG_ECDAA
1163 // Don't know how to verify an ECDAA signature
1164 case ALG_ECDAA_VALUE:
1165 break;
1166 # endif
1167
1168 #endif // ALG_ECC
1169
1170 case ALG_HMAC_VALUE:
1171 return auth->signature.hmac.hashAlg;
1172
1173 default:
1174 break;
1175 }
1176 return ALG_NULL_VALUE;
1177 }
1178
1179 //*** CryptIsSplitSign()
1180 // This function us used to determine if the signing operation is a split
1181 // signing operation that required a TPM2_Commit().
1182 //
1183 BOOL
1184 CryptIsSplitSign(
1185 TPM_ALG_ID scheme // IN: the algorithm selector
1186 )
1187 {
1188 switch(scheme)
1189 {
1190 # if ALG_ECDAA
1191 case ALG_ECDAA_VALUE:
1192 return TRUE;
1193 break;
1194 # endif // ALG_ECDAA
1195 default:
1196 return FALSE;
1197 break;
1198 }
1199 }
1200
1201 //*** CryptIsAsymSignScheme()
1202 // This function indicates if a scheme algorithm is a sign algorithm.
1203 BOOL
1204 CryptIsAsymSignScheme(
1205 TPMI_ALG_PUBLIC publicType, // IN: Type of the object
1206 TPMI_ALG_ASYM_SCHEME scheme // IN: the scheme
1207 )
1208 {
1209 BOOL isSignScheme = TRUE;
1210
1211 switch(publicType)
1212 {
1213 #if ALG_RSA
1214 case ALG_RSA_VALUE:
1215 switch(scheme)
1216 {
1217 # if !ALG_RSASSA || !ALG_RSAPSS
1218 # error "RSASSA and PSAPSS required if RSA used."
1219 # endif
1220 case ALG_RSASSA_VALUE:
1221 case ALG_RSAPSS_VALUE:
1222 break;
1223 default:
1224 isSignScheme = FALSE;
1225 break;
1226 }
1227 break;
1228 #endif // ALG_RSA
1229
1230 #if ALG_ECC
1231 // If ECC is implemented ECDSA is required
1232 case ALG_ECC_VALUE:
1233 switch(scheme)
1234 {
1235 // Support for ECDSA is required for ECC
1236 case ALG_ECDSA_VALUE:
1237 #if ALG_ECDAA // ECDAA is optional
1238 case ALG_ECDAA_VALUE:
1239 #endif
1240 #if ALG_ECSCHNORR // Schnorr is also optional
1241 case ALG_ECSCHNORR_VALUE:
1242 #endif
1243 #if ALG_SM2 // SM2 is optional
1244 case ALG_SM2_VALUE:
1245 #endif
1246 break;
1247 default:
1248 isSignScheme = FALSE;
1249 break;
1250 }
1251 break;
1252 #endif // ALG_ECC
1253 default:
1254 isSignScheme = FALSE;
1255 break;
1256 }
1257 return isSignScheme;
1258 }
1259
1260 //*** CryptIsAsymDecryptScheme()
1261 // This function indicate if a scheme algorithm is a decrypt algorithm.
1262 BOOL
1263 CryptIsAsymDecryptScheme(
1264 TPMI_ALG_PUBLIC publicType, // IN: Type of the object
1265 TPMI_ALG_ASYM_SCHEME scheme // IN: the scheme
1266 )
1267 {
1268 BOOL isDecryptScheme = TRUE;
1269
1270 switch(publicType)
1271 {
1272 #if ALG_RSA
1273 case ALG_RSA_VALUE:
1274 switch(scheme)
1275 {
1276 case ALG_RSAES_VALUE:
1277 case ALG_OAEP_VALUE:
1278 break;
1279 default:
1280 isDecryptScheme = FALSE;
1281 break;
1282 }
1283 break;
1284 #endif // ALG_RSA
1285
1286 #if ALG_ECC
1287 // If ECC is implemented ECDH is required
1288 case ALG_ECC_VALUE:
1289 switch(scheme)
1290 {
1291 #if !ALG_ECDH
1292 # error "ECDH is required for ECC"
1293 #endif
1294 case ALG_ECDH_VALUE:
1295 #if ALG_SM2
1296 case ALG_SM2_VALUE:
1297 #endif
1298 #if ALG_ECMQV
1299 case ALG_ECMQV_VALUE:
1300 #endif
1301 break;
1302 default:
1303 isDecryptScheme = FALSE;
1304 break;
1305 }
1306 break;
1307 #endif // ALG_ECC
1308 default:
1309 isDecryptScheme = FALSE;
1310 break;
1311 }
1312 return isDecryptScheme;
1313 }
1314
1315 //*** CryptSelectSignScheme()
1316 // This function is used by the attestation and signing commands. It implements
1317 // the rules for selecting the signature scheme to use in signing. This function
1318 // requires that the signing key either be TPM_RH_NULL or be loaded.
1319 //
1320 // If a default scheme is defined in object, the default scheme should be chosen,
1321 // otherwise, the input scheme should be chosen.
1322 // In the case that both object and input scheme has a non-NULL scheme
1323 // algorithm, if the schemes are compatible, the input scheme will be chosen.
1324 //
1325 // This function should not be called if 'signObject->publicArea.type' ==
1326 // ALG_SYMCIPHER.
1327 //
1328 // Return Type: BOOL
1329 // TRUE(1) scheme selected
1330 // FALSE(0) both 'scheme' and key's default scheme are empty; or
1331 // 'scheme' is empty while key's default scheme requires
1332 // explicit input scheme (split signing); or
1333 // non-empty default key scheme differs from 'scheme'
1334 BOOL
1335 CryptSelectSignScheme(
1336 OBJECT *signObject, // IN: signing key
1337 TPMT_SIG_SCHEME *scheme // IN/OUT: signing scheme
1338 )
1339 {
1340 TPMT_SIG_SCHEME *objectScheme;
1341 TPMT_PUBLIC *publicArea;
1342 BOOL OK;
1343
1344 // If the signHandle is TPM_RH_NULL, then the NULL scheme is used, regardless
1345 // of the setting of scheme
1346 if(signObject == NULL)
1347 {
1348 OK = TRUE;
1349 scheme->scheme = ALG_NULL_VALUE;
1350 scheme->details.any.hashAlg = ALG_NULL_VALUE;
1351 }
1352 else
1353 {
1354 // assignment to save typing.
1355 publicArea = &signObject->publicArea;
1356
1357 // A symmetric cipher can be used to encrypt and decrypt but it can't
1358 // be used for signing
1359 if(publicArea->type == ALG_SYMCIPHER_VALUE)
1360 return FALSE;
1361 // Point to the scheme object
1362 if(CryptIsAsymAlgorithm(publicArea->type))
1363 objectScheme =
1364 (TPMT_SIG_SCHEME *)&publicArea->parameters.asymDetail.scheme;
1365 else
1366 objectScheme =
1367 (TPMT_SIG_SCHEME *)&publicArea->parameters.keyedHashDetail.scheme;
1368
1369 // If the object doesn't have a default scheme, then use the
1370 // input scheme.
1371 if(objectScheme->scheme == ALG_NULL_VALUE)
1372 {
1373 // Input and default can't both be NULL
1374 OK = (scheme->scheme != ALG_NULL_VALUE);
1375 // Assume that the scheme is compatible with the key. If not,
1376 // an error will be generated in the signing operation.
1377 }
1378 else if(scheme->scheme == ALG_NULL_VALUE)
1379 {
1380 // input scheme is NULL so use default
1381
1382 // First, check to see if the default requires that the caller
1383 // provided scheme data
1384 OK = !CryptIsSplitSign(objectScheme->scheme);
1385 if(OK)
1386 {
1387 // The object has a scheme and the input is TPM_ALG_NULL so copy
1388 // the object scheme as the final scheme. It is better to use a
1389 // structure copy than a copy of the individual fields.
1390 *scheme = *objectScheme;
1391 }
1392 }
1393 else
1394 {
1395 // Both input and object have scheme selectors
1396 // If the scheme and the hash are not the same then...
1397 // NOTE: the reason that there is no copy here is that the input
1398 // might contain extra data for a split signing scheme and that
1399 // data is not in the object so, it has to be preserved.
1400 OK = (objectScheme->scheme == scheme->scheme)
1401 && (objectScheme->details.any.hashAlg
1402 == scheme->details.any.hashAlg);
1403 }
1404 }
1405 return OK;
1406 }
1407
1408 //*** CryptSign()
1409 // Sign a digest with asymmetric key or HMAC.
1410 // This function is called by attestation commands and the generic TPM2_Sign
1411 // command.
1412 // This function checks the key scheme and digest size. It does not
1413 // check if the sign operation is allowed for restricted key. It should be
1414 // checked before the function is called.
1415 // The function will assert if the key is not a signing key.
1416 //
1417 // Return Type: TPM_RC
1418 // TPM_RC_SCHEME 'signScheme' is not compatible with the signing key type
1419 // TPM_RC_VALUE 'digest' value is greater than the modulus of
1420 // 'signHandle' or size of 'hashData' does not match hash
1421 // algorithm in'signScheme' (for an RSA key);
1422 // invalid commit status or failed to generate "r" value
1423 // (for an ECC key)
1424 TPM_RC
1425 CryptSign(
1426 OBJECT *signKey, // IN: signing key
1427 TPMT_SIG_SCHEME *signScheme, // IN: sign scheme.
1428 TPM2B_DIGEST *digest, // IN: The digest being signed
1429 TPMT_SIGNATURE *signature // OUT: signature
1430 )
1431 {
1432 TPM_RC result = TPM_RC_SCHEME;
1433
1434 // Initialize signature scheme
1435 signature->sigAlg = signScheme->scheme;
1436
1437 // If the signature algorithm is TPM_ALG_NULL or the signing key is NULL,
1438 // then we are done
1439 if((signature->sigAlg == ALG_NULL_VALUE) || (signKey == NULL))
1440 return TPM_RC_SUCCESS;
1441
1442 // Initialize signature hash
1443 // Note: need to do the check for TPM_ALG_NULL first because the null scheme
1444 // doesn't have a hashAlg member.
1445 signature->signature.any.hashAlg = signScheme->details.any.hashAlg;
1446
1447 // perform sign operation based on different key type
1448 switch(signKey->publicArea.type)
1449 {
1450 #if ALG_RSA
1451 case ALG_RSA_VALUE:
1452 result = CryptRsaSign(signature, signKey, digest, NULL);
1453 break;
1454 #endif // ALG_RSA
1455 #if ALG_ECC
1456 case ALG_ECC_VALUE:
1457 // The reason that signScheme is passed to CryptEccSign but not to the
1458 // other signing methods is that the signing for ECC may be split and
1459 // need the 'r' value that is in the scheme but not in the signature.
1460 result = CryptEccSign(signature, signKey, digest,
1461 (TPMT_ECC_SCHEME *)signScheme, NULL);
1462 break;
1463 #endif // ALG_ECC
1464 case ALG_KEYEDHASH_VALUE:
1465 result = CryptHmacSign(signature, signKey, digest);
1466 break;
1467 default:
1468 FAIL(FATAL_ERROR_INTERNAL);
1469 break;
1470 }
1471 return result;
1472 }
1473
1474 //*** CryptValidateSignature()
1475 // This function is used to verify a signature. It is called by
1476 // TPM2_VerifySignature() and TPM2_PolicySigned.
1477 //
1478 // Since this operation only requires use of a public key, no consistency
1479 // checks are necessary for the key to signature type because a caller can load
1480 // any public key that they like with any scheme that they like. This routine
1481 // simply makes sure that the signature is correct, whatever the type.
1482 //
1483 // Return Type: TPM_RC
1484 // TPM_RC_SIGNATURE the signature is not genuine
1485 // TPM_RC_SCHEME the scheme is not supported
1486 // TPM_RC_HANDLE an HMAC key was selected but the
1487 // private part of the key is not loaded
1488 TPM_RC
1489 CryptValidateSignature(
1490 TPMI_DH_OBJECT keyHandle, // IN: The handle of sign key
1491 TPM2B_DIGEST *digest, // IN: The digest being validated
1492 TPMT_SIGNATURE *signature // IN: signature
1493 )
1494 {
1495 // NOTE: HandleToObject will either return a pointer to a loaded object or
1496 // will assert. It will never return a non-valid value. This makes it save
1497 // to initialize 'publicArea' with the return value from HandleToObject()
1498 // without checking it first.
1499 OBJECT *signObject = HandleToObject(keyHandle);
1500 TPMT_PUBLIC *publicArea = &signObject->publicArea;
1501 TPM_RC result = TPM_RC_SCHEME;
1502
1503 // The input unmarshaling should prevent any input signature from being
1504 // a NULL signature, but just in case
1505 if(signature->sigAlg == ALG_NULL_VALUE)
1506 return TPM_RC_SIGNATURE;
1507
1508 switch(publicArea->type)
1509 {
1510 #if ALG_RSA
1511 case ALG_RSA_VALUE:
1512 {
1513 //
1514 // Call RSA code to verify signature
1515 result = CryptRsaValidateSignature(signature, signObject, digest);
1516 break;
1517 }
1518 #endif // ALG_RSA
1519
1520 #if ALG_ECC
1521 case ALG_ECC_VALUE:
1522 result = CryptEccValidateSignature(signature, signObject, digest);
1523 break;
1524 #endif // ALG_ECC
1525
1526 case ALG_KEYEDHASH_VALUE:
1527 if(signObject->attributes.publicOnly)
1528 result = TPM_RCS_HANDLE;
1529 else
1530 result = CryptHMACVerifySignature(signObject, digest, signature);
1531 break;
1532 default:
1533 break;
1534 }
1535 return result;
1536 }
1537
1538 //*** CryptGetTestResult
1539 // This function returns the results of a self-test function.
1540 // Note: the behavior in this function is NOT the correct behavior for a real
1541 // TPM implementation. An artificial behavior is placed here due to the
1542 // limitation of a software simulation environment. For the correct behavior,
1543 // consult the part 3 specification for TPM2_GetTestResult().
1544 TPM_RC
1545 CryptGetTestResult(
1546 TPM2B_MAX_BUFFER *outData // OUT: test result data
1547 )
1548 {
1549 outData->t.size = 0;
1550 return TPM_RC_SUCCESS;
1551 }
1552
1553 //*** CryptValidateKeys()
1554 // This function is used to verify that the key material of and object is valid.
1555 // For a 'publicOnly' object, the key is verified for size and, if it is an ECC
1556 // key, it is verified to be on the specified curve. For a key with a sensitive
1557 // area, the binding between the public and private parts of the key are verified.
1558 // If the nameAlg of the key is TPM_ALG_NULL, then the size of the sensitive area
1559 // is verified but the public portion is not verified, unless the key is an RSA key.
1560 // For an RSA key, the reason for loading the sensitive area is to use it. The
1561 // only way to use a private RSA key is to compute the private exponent. To compute
1562 // the private exponent, the public modulus is used.
1563 // Return Type: TPM_RC
1564 // TPM_RC_BINDING the public and private parts are not cryptographically
1565 // bound
1566 // TPM_RC_HASH cannot have a publicOnly key with nameAlg of TPM_ALG_NULL
1567 // TPM_RC_KEY the public unique is not valid
1568 // TPM_RC_KEY_SIZE the private area key is not valid
1569 // TPM_RC_TYPE the types of the sensitive and private parts do not match
1570 TPM_RC
1571 CryptValidateKeys(
1572 TPMT_PUBLIC *publicArea,
1573 TPMT_SENSITIVE *sensitive,
1574 TPM_RC blamePublic,
1575 TPM_RC blameSensitive
1576 )
1577 {
1578 TPM_RC result;
1579 UINT16 keySizeInBytes;
1580 UINT16 digestSize = CryptHashGetDigestSize(publicArea->nameAlg);
1581 TPMU_PUBLIC_PARMS *params = &publicArea->parameters;
1582 TPMU_PUBLIC_ID *unique = &publicArea->unique;
1583
1584 if(sensitive != NULL)
1585 {
1586 // Make sure that the types of the public and sensitive are compatible
1587 if(publicArea->type != sensitive->sensitiveType)
1588 return TPM_RCS_TYPE + blameSensitive;
1589 // Make sure that the authValue is not bigger than allowed
1590 // If there is no name algorithm, then the size just needs to be less than
1591 // the maximum size of the buffer used for authorization. That size check
1592 // was made during unmarshaling of the sensitive area
1593 if((sensitive->authValue.t.size) > digestSize && (digestSize > 0))
1594 return TPM_RCS_SIZE + blameSensitive;
1595 }
1596 switch(publicArea->type)
1597 {
1598 #if ALG_RSA
1599 case ALG_RSA_VALUE:
1600 keySizeInBytes = BITS_TO_BYTES(params->rsaDetail.keyBits);
1601
1602 // Regardless of whether there is a sensitive area, the public modulus
1603 // needs to have the correct size. Otherwise, it can't be used for
1604 // any public key operation nor can it be used to compute the private
1605 // exponent.
1606 // NOTE: This implementation only supports key sizes that are multiples
1607 // of 1024 bits which means that the MSb of the 0th byte will always be
1608 // SET in any prime and in the public modulus.
1609 if((unique->rsa.t.size != keySizeInBytes)
1610 || (unique->rsa.t.buffer[0] < 0x80))
1611 return TPM_RCS_KEY + blamePublic;
1612 if(params->rsaDetail.exponent != 0
1613 && params->rsaDetail.exponent < 7)
1614 return TPM_RCS_VALUE + blamePublic;
1615 if(sensitive != NULL)
1616 {
1617 // If there is a sensitive area, it has to be the correct size
1618 // including having the correct high order bit SET.
1619 if(((sensitive->sensitive.rsa.t.size * 2) != keySizeInBytes)
1620 || (sensitive->sensitive.rsa.t.buffer[0] < 0x80))
1621 return TPM_RCS_KEY_SIZE + blameSensitive;
1622 }
1623 break;
1624 #endif
1625 #if ALG_ECC
1626 case ALG_ECC_VALUE:
1627 {
1628 TPMI_ECC_CURVE curveId;
1629 curveId = params->eccDetail.curveID;
1630 keySizeInBytes = BITS_TO_BYTES(CryptEccGetKeySizeForCurve(curveId));
1631 if(sensitive == NULL)
1632 {
1633 // Validate the public key size
1634 if(unique->ecc.x.t.size != keySizeInBytes
1635 || unique->ecc.y.t.size != keySizeInBytes)
1636 return TPM_RCS_KEY + blamePublic;
1637 if(publicArea->nameAlg != ALG_NULL_VALUE)
1638 {
1639 if(!CryptEccIsPointOnCurve(curveId, &unique->ecc))
1640 return TPM_RCS_ECC_POINT + blamePublic;
1641 }
1642 }
1643 else
1644 {
1645 // If the nameAlg is TPM_ALG_NULL, then only verify that the
1646 // private part of the key is OK.
1647 if(!CryptEccIsValidPrivateKey(&sensitive->sensitive.ecc,
1648 curveId))
1649 return TPM_RCS_KEY_SIZE;
1650 if(publicArea->nameAlg != ALG_NULL_VALUE)
1651 {
1652 // Full key load, verify that the public point belongs to the
1653 // private key.
1654 TPMS_ECC_POINT toCompare;
1655 result = CryptEccPointMultiply(&toCompare, curveId, NULL,
1656 &sensitive->sensitive.ecc,
1657 NULL, NULL);
1658 if(result != TPM_RC_SUCCESS)
1659 return TPM_RCS_BINDING;
1660 else
1661 {
1662 // Make sure that the private key generated the public key.
1663 // The input values and the values produced by the point
1664 // multiply may not be the same size so adjust the computed
1665 // value to match the size of the input value by adding or
1666 // removing zeros.
1667 AdjustNumberB(&toCompare.x.b, unique->ecc.x.t.size);
1668 AdjustNumberB(&toCompare.y.b, unique->ecc.y.t.size);
1669 if(!MemoryEqual2B(&unique->ecc.x.b, &toCompare.x.b)
1670 || !MemoryEqual2B(&unique->ecc.y.b, &toCompare.y.b))
1671 return TPM_RCS_BINDING;
1672 }
1673 }
1674 }
1675 break;
1676 }
1677 #endif
1678 default:
1679 // Checks for SYMCIPHER and KEYEDHASH are largely the same
1680 // If public area has a nameAlg, then validate the public area size
1681 // and if there is also a sensitive area, validate the binding
1682
1683 // For consistency, if the object is public-only just make sure that
1684 // the unique field is consistent with the name algorithm
1685 if(sensitive == NULL)
1686 {
1687 if(unique->sym.t.size != digestSize)
1688 return TPM_RCS_KEY + blamePublic;
1689 }
1690 else
1691 {
1692 // Make sure that the key size in the sensitive area is consistent.
1693 if(publicArea->type == ALG_SYMCIPHER_VALUE)
1694 {
1695 result = CryptSymKeyValidate(&params->symDetail.sym,
1696 &sensitive->sensitive.sym);
1697 if(result != TPM_RC_SUCCESS)
1698 return result + blameSensitive;
1699 }
1700 else
1701 {
1702 // For a keyed hash object, the key has to be less than the
1703 // smaller of the block size of the hash used in the scheme or
1704 // 128 bytes. The worst case value is limited by the
1705 // unmarshaling code so the only thing left to be checked is
1706 // that it does not exceed the block size of the hash.
1707 // by the hash algorithm of the scheme.
1708 TPMT_KEYEDHASH_SCHEME *scheme;
1709 UINT16 maxSize;
1710 scheme = &params->keyedHashDetail.scheme;
1711 if(scheme->scheme == ALG_XOR_VALUE)
1712 {
1713 maxSize = CryptHashGetBlockSize(scheme->details.xor.hashAlg);
1714 }
1715 else if(scheme->scheme == ALG_HMAC_VALUE)
1716 {
1717 maxSize = CryptHashGetBlockSize(scheme->details.hmac.hashAlg);
1718 }
1719 else if(scheme->scheme == ALG_NULL_VALUE)
1720 {
1721 // Not signing or xor so must be a data block
1722 maxSize = 128;
1723 }
1724 else
1725 return TPM_RCS_SCHEME + blamePublic;
1726 if(sensitive->sensitive.bits.t.size > maxSize)
1727 return TPM_RCS_KEY_SIZE + blameSensitive;
1728 }
1729 // If there is a nameAlg, check the binding
1730 if(publicArea->nameAlg != ALG_NULL_VALUE)
1731 {
1732 TPM2B_DIGEST compare;
1733 if(sensitive->seedValue.t.size != digestSize)
1734 return TPM_RCS_KEY_SIZE + blameSensitive;
1735
1736 CryptComputeSymmetricUnique(publicArea, sensitive, &compare);
1737 if(!MemoryEqual2B(&unique->sym.b, &compare.b))
1738 return TPM_RC_BINDING;
1739 }
1740 }
1741 break;
1742 }
1743 // For a parent, need to check that the seedValue is the correct size for
1744 // protections. It should be at least half the size of the nameAlg
1745 if(IS_ATTRIBUTE(publicArea->objectAttributes, TPMA_OBJECT, restricted)
1746 && IS_ATTRIBUTE(publicArea->objectAttributes, TPMA_OBJECT, decrypt)
1747 && sensitive != NULL
1748 && publicArea->nameAlg != ALG_NULL_VALUE)
1749 {
1750 if((sensitive->seedValue.t.size < (digestSize / 2))
1751 || (sensitive->seedValue.t.size > digestSize))
1752 return TPM_RCS_SIZE + blameSensitive;
1753 }
1754 return TPM_RC_SUCCESS;
1755 }
1756
1757 //*** CryptSelectMac()
1758 // This function is used to set the MAC scheme based on the key parameters and
1759 // the input scheme.
1760 // Return Type: TPM_RC
1761 // TPM_RC_SCHEME the scheme is not a valid mac scheme
1762 // TPM_RC_TYPE the input key is not a type that supports a mac
1763 // TPM_RC_VALUE the input scheme and the key scheme are not compatible
1764 TPM_RC
1765 CryptSelectMac(
1766 TPMT_PUBLIC *publicArea,
1767 TPMI_ALG_MAC_SCHEME *inMac
1768 )
1769 {
1770 TPM_ALG_ID macAlg = ALG_NULL_VALUE;
1771 switch(publicArea->type)
1772 {
1773 case ALG_KEYEDHASH_VALUE:
1774 {
1775 // Local value to keep lines from getting too long
1776 TPMT_KEYEDHASH_SCHEME *scheme;
1777 scheme = &publicArea->parameters.keyedHashDetail.scheme;
1778 // Expect that the scheme is either HMAC or NULL
1779 if(scheme->scheme != ALG_NULL_VALUE)
1780 macAlg = scheme->details.hmac.hashAlg;
1781 break;
1782 }
1783 case ALG_SYMCIPHER_VALUE:
1784 {
1785 TPMT_SYM_DEF_OBJECT *scheme;
1786 scheme = &publicArea->parameters.symDetail.sym;
1787 // Expect that the scheme is either valid symmetric cipher or NULL
1788 if(scheme->algorithm != ALG_NULL_VALUE)
1789 macAlg = scheme->mode.sym;
1790 break;
1791 }
1792 default:
1793 return TPM_RCS_TYPE;
1794 }
1795 // If the input value is not TPM_ALG_NULL ...
1796 if(*inMac != ALG_NULL_VALUE)
1797 {
1798 // ... then either the scheme in the key must be TPM_ALG_NULL or the input
1799 // value must match
1800 if((macAlg != ALG_NULL_VALUE) && (*inMac != macAlg))
1801 return TPM_RCS_VALUE;
1802 }
1803 else
1804 {
1805 // Since the input value is TPM_ALG_NULL, then the key value can't be
1806 // TPM_ALG_NULL
1807 if(macAlg == ALG_NULL_VALUE)
1808 return TPM_RCS_VALUE;
1809 *inMac = macAlg;
1810 }
1811 if(!CryptMacIsValidForKey(publicArea->type, *inMac, FALSE))
1812 return TPM_RCS_SCHEME;
1813 return TPM_RC_SUCCESS;
1814 }
1815
1816 //*** CryptMacIsValidForKey()
1817 // Check to see if the key type is compatible with the mac type
1818 BOOL
1819 CryptMacIsValidForKey(
1820 TPM_ALG_ID keyType,
1821 TPM_ALG_ID macAlg,
1822 BOOL flag
1823 )
1824 {
1825 switch(keyType)
1826 {
1827 case ALG_KEYEDHASH_VALUE:
1828 return CryptHashIsValidAlg(macAlg, flag);
1829 break;
1830 case ALG_SYMCIPHER_VALUE:
1831 return CryptSmacIsValidAlg(macAlg, flag);
1832 break;
1833 default:
1834 break;
1835 }
1836 return FALSE;
1837 }
1838
1839 //*** CryptSmacIsValidAlg()
1840 // This function is used to test if an algorithm is a supported SMAC algorithm. It
1841 // needs to be updated as new algorithms are added.
1842 BOOL
1843 CryptSmacIsValidAlg(
1844 TPM_ALG_ID alg,
1845 BOOL FLAG // IN: Indicates if TPM_ALG_NULL is valid
1846 )
1847 {
1848 switch (alg)
1849 {
1850 #if ALG_CMAC
1851 case ALG_CMAC_VALUE:
1852 return TRUE;
1853 break;
1854 #endif
1855 case ALG_NULL_VALUE:
1856 return FLAG;
1857 break;
1858 default:
1859 return FALSE;
1860 }
1861 }
1862
1863 //*** CryptSymModeIsValid()
1864 // Function checks to see if an algorithm ID is a valid, symmetric block cipher
1865 // mode for the TPM. If 'flag' is SET, them TPM_ALG_NULL is a valid mode.
1866 // not include the modes used for SMAC
1867 BOOL
1868 CryptSymModeIsValid(
1869 TPM_ALG_ID mode,
1870 BOOL flag
1871 )
1872 {
1873 switch(mode)
1874 {
1875 #if ALG_CTR
1876 case ALG_CTR_VALUE:
1877 #endif // ALG_CTR
1878 #if ALG_OFB
1879 case ALG_OFB_VALUE:
1880 #endif // ALG_OFB
1881 #if ALG_CBC
1882 case ALG_CBC_VALUE:
1883 #endif // ALG_CBC
1884 #if ALG_CFB
1885 case ALG_CFB_VALUE:
1886 #endif // ALG_CFB
1887 #if ALG_ECB
1888 case ALG_ECB_VALUE:
1889 #endif // ALG_ECB
1890 return TRUE;
1891 case ALG_NULL_VALUE:
1892 return flag;
1893 break;
1894 default:
1895 break;
1896 }
1897 return FALSE;
1898 }
1899
1900
1901