Debian Codegraph @

simulator/ms-tpm-20-ref/TPMCmd/tpm/src/main/SessionProcess.c

raw
1 /* Microsoft Reference Implementation for TPM 2.0
2 *
3 * The copyright in this software is being made available under the BSD License,
4 * included below. This software may be subject to other third party and
5 * contributor rights, including patent rights, and no such rights are granted
6 * under this license.
7 *
8 * Copyright (c) Microsoft Corporation
9 *
10 * All rights reserved.
11 *
12 * BSD License
13 *
14 * Redistribution and use in source and binary forms, with or without modification,
15 * are permitted provided that the following conditions are met:
16 *
17 * Redistributions of source code must retain the above copyright notice, this list
18 * of conditions and the following disclaimer.
19 *
20 * Redistributions in binary form must reproduce the above copyright notice, this
21 * list of conditions and the following disclaimer in the documentation and/or
22 * other materials provided with the distribution.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS""
25 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
28 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
29 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
31 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 */
35 //** Introduction
36 // This file contains the subsystem that process the authorization sessions
37 // including implementation of the Dictionary Attack logic. ExecCommand() uses
38 // ParseSessionBuffer() to process the authorization session area of a command and
39 // BuildResponseSession() to create the authorization session area of a response.
40
41 //** Includes and Data Definitions
42
43 #define SESSION_PROCESS_C
44
45 #include "Tpm.h"
46
47 //
48 //** Authorization Support Functions
49 //
50
51 //*** IsDAExempted()
52 // This function indicates if a handle is exempted from DA logic.
53 // A handle is exempted if it is
54 // 1. a primary seed handle,
55 // 2. an object with noDA bit SET,
56 // 3. an NV Index with TPMA_NV_NO_DA bit SET, or
57 // 4. a PCR handle.
58 //
59 // Return Type: BOOL
60 // TRUE(1) handle is exempted from DA logic
61 // FALSE(0) handle is not exempted from DA logic
62 BOOL
63 IsDAExempted(
64 TPM_HANDLE handle // IN: entity handle
65 )
66 {
67 BOOL result = FALSE;
68 //
69 switch(HandleGetType(handle))
70 {
71 case TPM_HT_PERMANENT:
72 // All permanent handles, other than TPM_RH_LOCKOUT, are exempt from
73 // DA protection.
74 result = (handle != TPM_RH_LOCKOUT);
75 break;
76 // When this function is called, a persistent object will have been loaded
77 // into an object slot and assigned a transient handle.
78 case TPM_HT_TRANSIENT:
79 {
80 TPMA_OBJECT attributes = ObjectGetPublicAttributes(handle);
81 result = IS_ATTRIBUTE(attributes, TPMA_OBJECT, noDA);
82 break;
83 }
84 case TPM_HT_NV_INDEX:
85 {
86 NV_INDEX *nvIndex = NvGetIndexInfo(handle, NULL);
87 result = IS_ATTRIBUTE(nvIndex->publicArea.attributes, TPMA_NV, NO_DA);
88 break;
89 }
90 case TPM_HT_PCR:
91 // PCRs are always exempted from DA.
92 result = TRUE;
93 break;
94 default:
95 break;
96 }
97 return result;
98 }
99
100 //*** IncrementLockout()
101 // This function is called after an authorization failure that involves use of
102 // an authValue. If the entity referenced by the handle is not exempt from DA
103 // protection, then the failedTries counter will be incremented.
104 //
105 // Return Type: TPM_RC
106 // TPM_RC_AUTH_FAIL authorization failure that caused DA lockout to increment
107 // TPM_RC_BAD_AUTH authorization failure did not cause DA lockout to
108 // increment
109 static TPM_RC
110 IncrementLockout(
111 UINT32 sessionIndex
112 )
113 {
114 TPM_HANDLE handle = s_associatedHandles[sessionIndex];
115 TPM_HANDLE sessionHandle = s_sessionHandles[sessionIndex];
116 SESSION *session = NULL;
117 //
118 // Don't increment lockout unless the handle associated with the session
119 // is DA protected or the session is bound to a DA protected entity.
120 if(sessionHandle == TPM_RS_PW)
121 {
122 if(IsDAExempted(handle))
123 return TPM_RC_BAD_AUTH;
124 }
125 else
126 {
127 session = SessionGet(sessionHandle);
128 // If the session is bound to lockout, then use that as the relevant
129 // handle. This means that an authorization failure with a bound session
130 // bound to lockoutAuth will take precedence over any other
131 // lockout check
132 if(session->attributes.isLockoutBound == SET)
133 handle = TPM_RH_LOCKOUT;
134 if(session->attributes.isDaBound == CLEAR
135 && (IsDAExempted(handle) || session->attributes.includeAuth == CLEAR))
136 // If the handle was changed to TPM_RH_LOCKOUT, this will not return
137 // TPM_RC_BAD_AUTH
138 return TPM_RC_BAD_AUTH;
139 }
140 if(handle == TPM_RH_LOCKOUT)
141 {
142 pAssert(gp.lockOutAuthEnabled == TRUE);
143
144 // lockout is no longer enabled
145 gp.lockOutAuthEnabled = FALSE;
146
147 // For TPM_RH_LOCKOUT, if lockoutRecovery is 0, no need to update NV since
148 // the lockout authorization will be reset at startup.
149 if(gp.lockoutRecovery != 0)
150 {
151 if(NV_IS_AVAILABLE)
152 // Update NV.
153 NV_SYNC_PERSISTENT(lockOutAuthEnabled);
154 else
155 // No NV access for now. Put the TPM in pending mode.
156 s_DAPendingOnNV = TRUE;
157 }
158 }
159 else
160 {
161 if(gp.recoveryTime != 0)
162 {
163 gp.failedTries++;
164 if(NV_IS_AVAILABLE)
165 // Record changes to NV. NvWrite will SET g_updateNV
166 NV_SYNC_PERSISTENT(failedTries);
167 else
168 // No NV access for now. Put the TPM in pending mode.
169 s_DAPendingOnNV = TRUE;
170 }
171 }
172 // Register a DA failure and reset the timers.
173 DARegisterFailure(handle);
174
175 return TPM_RC_AUTH_FAIL;
176 }
177
178 //*** IsSessionBindEntity()
179 // This function indicates if the entity associated with the handle is the entity,
180 // to which this session is bound. The binding would occur by making the "bind"
181 // parameter in TPM2_StartAuthSession() not equal to TPM_RH_NULL. The binding only
182 // occurs if the session is an HMAC session. The bind value is a combination of
183 // the Name and the authValue of the entity.
184 //
185 // Return Type: BOOL
186 // TRUE(1) handle points to the session start entity
187 // FALSE(0) handle does not point to the session start entity
188 static BOOL
189 IsSessionBindEntity(
190 TPM_HANDLE associatedHandle, // IN: handle to be authorized
191 SESSION *session // IN: associated session
192 )
193 {
194 TPM2B_NAME entity; // The bind value for the entity
195 //
196 // If the session is not bound, return FALSE.
197 if(session->attributes.isBound)
198 {
199 // Compute the bind value for the entity.
200 SessionComputeBoundEntity(associatedHandle, &entity);
201
202 // Compare to the bind value in the session.
203 return MemoryEqual2B(&entity.b, &session->u1.boundEntity.b);
204 }
205 return FALSE;
206 }
207
208 //*** IsPolicySessionRequired()
209 // Checks if a policy session is required for a command. If a command requires
210 // DUP or ADMIN role authorization, then the handle that requires that role is the
211 // first handle in the command. This simplifies this checking. If a new command
212 // is created that requires multiple ADMIN role authorizations, then it will
213 // have to be special-cased in this function.
214 // A policy session is required if:
215 // 1. the command requires the DUP role,
216 // 2. the command requires the ADMIN role and the authorized entity
217 // is an object and its adminWithPolicy bit is SET, or
218 // 3. the command requires the ADMIN role and the authorized entity
219 // is a permanent handle or an NV Index.
220 // 4. The authorized entity is a PCR belonging to a policy group, and
221 // has its policy initialized
222 // Return Type: BOOL
223 // TRUE(1) policy session is required
224 // FALSE(0) policy session is not required
225 static BOOL
226 IsPolicySessionRequired(
227 COMMAND_INDEX commandIndex, // IN: command index
228 UINT32 sessionIndex // IN: session index
229 )
230 {
231 AUTH_ROLE role = CommandAuthRole(commandIndex, sessionIndex);
232 TPM_HT type = HandleGetType(s_associatedHandles[sessionIndex]);
233 //
234 if(role == AUTH_DUP)
235 return TRUE;
236 if(role == AUTH_ADMIN)
237 {
238 // We allow an exception for ADMIN role in a transient object. If the object
239 // allows ADMIN role actions with authorization, then policy is not
240 // required. For all other cases, there is no way to override the command
241 // requirement that a policy be used
242 if(type == TPM_HT_TRANSIENT)
243 {
244 OBJECT *object = HandleToObject(s_associatedHandles[sessionIndex]);
245
246 if(!IS_ATTRIBUTE(object->publicArea.objectAttributes, TPMA_OBJECT,
247 adminWithPolicy))
248 return FALSE;
249 }
250 return TRUE;
251 }
252
253 if(type == TPM_HT_PCR)
254 {
255 if(PCRPolicyIsAvailable(s_associatedHandles[sessionIndex]))
256 {
257 TPM2B_DIGEST policy;
258 TPMI_ALG_HASH policyAlg;
259 policyAlg = PCRGetAuthPolicy(s_associatedHandles[sessionIndex],
260 &policy);
261 if(policyAlg != TPM_ALG_NULL)
262 return TRUE;
263 }
264 }
265 return FALSE;
266 }
267
268 //*** IsAuthValueAvailable()
269 // This function indicates if authValue is available and allowed for USER role
270 // authorization of an entity.
271 //
272 // This function is similar to IsAuthPolicyAvailable() except that it does not
273 // check the size of the authValue as IsAuthPolicyAvailable() does (a null
274 // authValue is a valid authorization, but a null policy is not a valid policy).
275 //
276 // This function does not check that the handle reference is valid or if the entity
277 // is in an enabled hierarchy. Those checks are assumed to have been performed
278 // during the handle unmarshaling.
279 //
280 // Return Type: BOOL
281 // TRUE(1) authValue is available
282 // FALSE(0) authValue is not available
283 static BOOL
284 IsAuthValueAvailable(
285 TPM_HANDLE handle, // IN: handle of entity
286 COMMAND_INDEX commandIndex, // IN: command index
287 UINT32 sessionIndex // IN: session index
288 )
289 {
290 BOOL result = FALSE;
291 //
292 switch(HandleGetType(handle))
293 {
294 case TPM_HT_PERMANENT:
295 switch(handle)
296 {
297 // At this point hierarchy availability has already been
298 // checked so primary seed handles are always available here
299 case TPM_RH_OWNER:
300 case TPM_RH_ENDORSEMENT:
301 case TPM_RH_PLATFORM:
302 #ifdef VENDOR_PERMANENT
303 // This vendor defined handle associated with the
304 // manufacturer's shared secret
305 case VENDOR_PERMANENT:
306 #endif
307 // The DA checking has been performed on LockoutAuth but we
308 // bypass the DA logic if we are using lockout policy. The
309 // policy would allow execution to continue an lockoutAuth
310 // could be used, even if direct use of lockoutAuth is disabled
311 case TPM_RH_LOCKOUT:
312 // NullAuth is always available.
313 case TPM_RH_NULL:
314 result = TRUE;
315 break;
316 default:
317 // Otherwise authValue is not available.
318 break;
319 }
320 break;
321 case TPM_HT_TRANSIENT:
322 // A persistent object has already been loaded and the internal
323 // handle changed.
324 {
325 OBJECT *object;
326 TPMA_OBJECT attributes;
327 //
328 object = HandleToObject(handle);
329 attributes = object->publicArea.objectAttributes;
330
331 // authValue is always available for a sequence object.
332 // An alternative for this is to
333 // SET_ATTRIBUTE(object->publicArea, TPMA_OBJECT, userWithAuth) when the
334 // sequence is started.
335 if(ObjectIsSequence(object))
336 {
337 result = TRUE;
338 break;
339 }
340 // authValue is available for an object if it has its sensitive
341 // portion loaded and
342 // 1. userWithAuth bit is SET, or
343 // 2. ADMIN role is required
344 if(object->attributes.publicOnly == CLEAR
345 && (IS_ATTRIBUTE(attributes, TPMA_OBJECT, userWithAuth)
346 || (CommandAuthRole(commandIndex, sessionIndex) == AUTH_ADMIN
347 && !IS_ATTRIBUTE(attributes, TPMA_OBJECT, adminWithPolicy))))
348 result = TRUE;
349 }
350 break;
351 case TPM_HT_NV_INDEX:
352 // NV Index.
353 {
354 NV_REF locator;
355 NV_INDEX *nvIndex = NvGetIndexInfo(handle, &locator);
356 TPMA_NV nvAttributes;
357 //
358 pAssert(nvIndex != 0);
359
360 nvAttributes = nvIndex->publicArea.attributes;
361
362 if(IsWriteOperation(commandIndex))
363 {
364 // AuthWrite can't be set for a PIN index
365 if(IS_ATTRIBUTE(nvAttributes, TPMA_NV, AUTHWRITE))
366 result = TRUE;
367 }
368 else
369 {
370 // A "read" operation
371 // For a PIN Index, the authValue is available as long as the
372 // Index has been written and the pinCount is less than pinLimit
373 if(IsNvPinFailIndex(nvAttributes)
374 || IsNvPinPassIndex(nvAttributes))
375 {
376 NV_PIN pin;
377 if(!IS_ATTRIBUTE(nvAttributes, TPMA_NV, WRITTEN))
378 break; // return false
379 // get the index values
380 pin.intVal = NvGetUINT64Data(nvIndex, locator);
381 if(pin.pin.pinCount < pin.pin.pinLimit)
382 result = TRUE;
383 }
384 // For non-PIN Indexes, need to allow use of the authValue
385 else if(IS_ATTRIBUTE(nvAttributes, TPMA_NV, AUTHREAD))
386 result = TRUE;
387 }
388 }
389 break;
390 case TPM_HT_PCR:
391 // PCR handle.
392 // authValue is always allowed for PCR
393 result = TRUE;
394 break;
395 default:
396 // Otherwise, authValue is not available
397 break;
398 }
399 return result;
400 }
401
402 //*** IsAuthPolicyAvailable()
403 // This function indicates if an authPolicy is available and allowed.
404 //
405 // This function does not check that the handle reference is valid or if the entity
406 // is in an enabled hierarchy. Those checks are assumed to have been performed
407 // during the handle unmarshaling.
408 //
409 // Return Type: BOOL
410 // TRUE(1) authPolicy is available
411 // FALSE(0) authPolicy is not available
412 static BOOL
413 IsAuthPolicyAvailable(
414 TPM_HANDLE handle, // IN: handle of entity
415 COMMAND_INDEX commandIndex, // IN: command index
416 UINT32 sessionIndex // IN: session index
417 )
418 {
419 BOOL result = FALSE;
420 //
421 switch(HandleGetType(handle))
422 {
423 case TPM_HT_PERMANENT:
424 switch(handle)
425 {
426 // At this point hierarchy availability has already been checked.
427 case TPM_RH_OWNER:
428 if(gp.ownerPolicy.t.size != 0)
429 result = TRUE;
430 break;
431 case TPM_RH_ENDORSEMENT:
432 if(gp.endorsementPolicy.t.size != 0)
433 result = TRUE;
434 break;
435 case TPM_RH_PLATFORM:
436 if(gc.platformPolicy.t.size != 0)
437 result = TRUE;
438 break;
439 case TPM_RH_LOCKOUT:
440 if(gp.lockoutPolicy.t.size != 0)
441 result = TRUE;
442 break;
443 default:
444 break;
445 }
446 break;
447 case TPM_HT_TRANSIENT:
448 {
449 // Object handle.
450 // An evict object would already have been loaded and given a
451 // transient object handle by this point.
452 OBJECT *object = HandleToObject(handle);
453 // Policy authorization is not available for an object with only
454 // public portion loaded.
455 if(object->attributes.publicOnly == CLEAR)
456 {
457 // Policy authorization is always available for an object but
458 // is never available for a sequence.
459 if(!ObjectIsSequence(object))
460 result = TRUE;
461 }
462 break;
463 }
464 case TPM_HT_NV_INDEX:
465 // An NV Index.
466 {
467 NV_INDEX *nvIndex = NvGetIndexInfo(handle, NULL);
468 TPMA_NV nvAttributes = nvIndex->publicArea.attributes;
469 //
470 // If the policy size is not zero, check if policy can be used.
471 if(nvIndex->publicArea.authPolicy.t.size != 0)
472 {
473 // If policy session is required for this handle, always
474 // uses policy regardless of the attributes bit setting
475 if(IsPolicySessionRequired(commandIndex, sessionIndex))
476 result = TRUE;
477 // Otherwise, the presence of the policy depends on the NV
478 // attributes.
479 else if(IsWriteOperation(commandIndex))
480 {
481 if(IS_ATTRIBUTE(nvAttributes, TPMA_NV, POLICYWRITE))
482 result = TRUE;
483 }
484 else
485 {
486 if(IS_ATTRIBUTE(nvAttributes, TPMA_NV, POLICYREAD))
487 result = TRUE;
488 }
489 }
490 }
491 break;
492 case TPM_HT_PCR:
493 // PCR handle.
494 if(PCRPolicyIsAvailable(handle))
495 result = TRUE;
496 break;
497 default:
498 break;
499 }
500 return result;
501 }
502
503 //** Session Parsing Functions
504
505 //*** ClearCpRpHashes()
506 void
507 ClearCpRpHashes(
508 COMMAND *command
509 )
510 {
511 #if ALG_SHA1
512 command->sha1CpHash.t.size = 0;
513 command->sha1RpHash.t.size = 0;
514 #endif
515 #if ALG_SHA256
516 command->sha256CpHash.t.size = 0;
517 command->sha256RpHash.t.size = 0;
518 #endif
519 #if ALG_SHA384
520 command->sha384CpHash.t.size = 0;
521 command->sha384RpHash.t.size = 0;
522 #endif
523 #if ALG_SHA512
524 command->sha512CpHash.t.size = 0;
525 command->sha512RpHash.t.size = 0;
526 #endif
527 #if ALG_SM3_256
528 command->sm3_256CpHash.t.size = 0;
529 command->sm3_256RpHash.t.size = 0;
530 #endif
531 }
532
533
534 //*** GetCpHashPointer()
535 // Function to get a pointer to the cpHash of the command
536 static TPM2B_DIGEST *
537 GetCpHashPointer(
538 COMMAND *command,
539 TPMI_ALG_HASH hashAlg
540 )
541 {
542 TPM2B_DIGEST *retVal;
543 //
544 switch(hashAlg)
545 {
546 #if ALG_SHA1
547 case ALG_SHA1_VALUE:
548 retVal = (TPM2B_DIGEST *)&command->sha1CpHash;
549 break;
550 #endif
551 #if ALG_SHA256
552 case ALG_SHA256_VALUE:
553 retVal = (TPM2B_DIGEST *)&command->sha256CpHash;
554 break;
555 #endif
556 #if ALG_SHA384
557 case ALG_SHA384_VALUE:
558 retVal = (TPM2B_DIGEST *)&command->sha384CpHash;
559 break;
560 #endif
561 #if ALG_SHA512
562 case ALG_SHA512_VALUE:
563 retVal = (TPM2B_DIGEST *)&command->sha512CpHash;
564 break;
565 #endif
566 #if ALG_SM3_256
567 case ALG_SM3_256_VALUE:
568 retVal = (TPM2B_DIGEST *)&command->sm3_256CpHash;
569 break;
570 #endif
571 default:
572 retVal = NULL;
573 break;
574 }
575 return retVal;
576 }
577
578 //*** GetRpHashPointer()
579 // Function to get a pointer to the RpHash of the command
580 static TPM2B_DIGEST *
581 GetRpHashPointer(
582 COMMAND *command,
583 TPMI_ALG_HASH hashAlg
584 )
585 {
586 TPM2B_DIGEST *retVal;
587 //
588 switch(hashAlg)
589 {
590 #if ALG_SHA1
591 case ALG_SHA1_VALUE:
592 retVal = (TPM2B_DIGEST *)&command->sha1RpHash;
593 break;
594 #endif
595 #if ALG_SHA256
596 case ALG_SHA256_VALUE:
597 retVal = (TPM2B_DIGEST *)&command->sha256RpHash;
598 break;
599 #endif
600 #if ALG_SHA384
601 case ALG_SHA384_VALUE:
602 retVal = (TPM2B_DIGEST *)&command->sha384RpHash;
603 break;
604 #endif
605 #if ALG_SHA512
606 case ALG_SHA512_VALUE:
607 retVal = (TPM2B_DIGEST *)&command->sha512RpHash;
608 break;
609 #endif
610 #if ALG_SM3_256
611 case ALG_SM3_256_VALUE:
612 retVal = (TPM2B_DIGEST *)&command->sm3_256RpHash;
613 break;
614 #endif
615 default:
616 retVal = NULL;
617 break;
618 }
619 return retVal;
620 }
621
622
623 //*** ComputeCpHash()
624 // This function computes the cpHash as defined in Part 2 and described in Part 1.
625 static TPM2B_DIGEST *
626 ComputeCpHash(
627 COMMAND *command, // IN: command parsing structure
628 TPMI_ALG_HASH hashAlg // IN: hash algorithm
629 )
630 {
631 UINT32 i;
632 HASH_STATE hashState;
633 TPM2B_NAME name;
634 TPM2B_DIGEST *cpHash;
635 //
636 // cpHash = hash(commandCode [ || authName1
637 // [ || authName2
638 // [ || authName 3 ]]]
639 // [ || parameters])
640 // A cpHash can contain just a commandCode only if the lone session is
641 // an audit session.
642 // Get pointer to the hash value
643 cpHash = GetCpHashPointer(command, hashAlg);
644 if(cpHash->t.size == 0)
645 {
646 cpHash->t.size = CryptHashStart(&hashState, hashAlg);
647 // Add commandCode.
648 CryptDigestUpdateInt(&hashState, sizeof(TPM_CC), command->code);
649 // Add authNames for each of the handles.
650 for(i = 0; i < command->handleNum; i++)
651 CryptDigestUpdate2B(&hashState, &EntityGetName(command->handles[i],
652 &name)->b);
653 // Add the parameters.
654 CryptDigestUpdate(&hashState, command->parameterSize,
655 command->parameterBuffer);
656 // Complete the hash.
657 CryptHashEnd2B(&hashState, &cpHash->b);
658 }
659 return cpHash;
660 }
661
662 //*** GetCpHash()
663 // This function is used to access a precomputed cpHash.
664 static TPM2B_DIGEST *
665 GetCpHash(
666 COMMAND *command,
667 TPMI_ALG_HASH hashAlg
668 )
669 {
670 TPM2B_DIGEST *cpHash = GetCpHashPointer(command, hashAlg);
671 //
672 pAssert(cpHash->t.size != 0);
673 return cpHash;
674 }
675
676 //*** CompareTemplateHash()
677 // This function computes the template hash and compares it to the session
678 // templateHash. It is the hash of the second parameter
679 // assuming that the command is TPM2_Create(), TPM2_CreatePrimary(), or
680 // TPM2_CreateLoaded()
681 // Return Type: BOOL
682 // TRUE(1) template hash equal to session->templateHash
683 // FALSE(0) template hash not equal to session->templateHash
684 static BOOL
685 CompareTemplateHash(
686 COMMAND *command, // IN: parsing structure
687 SESSION *session // IN: session data
688 )
689 {
690 BYTE *pBuffer = command->parameterBuffer;
691 INT32 pSize = command->parameterSize;
692 TPM2B_DIGEST tHash;
693 UINT16 size;
694 //
695 // Only try this for the three commands for which it is intended
696 if(command->code != TPM_CC_Create
697 && command->code != TPM_CC_CreatePrimary
698 #if CC_CreateLoaded
699 && command->code != TPM_CC_CreateLoaded
700 #endif
701 )
702 return FALSE;
703 // Assume that the first parameter is a TPM2B and unmarshal the size field
704 // Note: this will not affect the parameter buffer and size in the calling
705 // function.
706 if(UINT16_Unmarshal(&size, &pBuffer, &pSize) != TPM_RC_SUCCESS)
707 return FALSE;
708 // reduce the space in the buffer.
709 // NOTE: this could make pSize go negative if the parameters are not correct but
710 // the unmarshaling code does not try to unmarshal if the remaining size is
711 // negative.
712 pSize -= size;
713
714 // Advance the pointer
715 pBuffer += size;
716
717 // Get the size of what should be the template
718 if(UINT16_Unmarshal(&size, &pBuffer, &pSize) != TPM_RC_SUCCESS)
719 return FALSE;
720 // See if this is reasonable
721 if(size > pSize)
722 return FALSE;
723 // Hash the template data
724 tHash.t.size = CryptHashBlock(session->authHashAlg, size, pBuffer,
725 sizeof(tHash.t.buffer), tHash.t.buffer);
726 return(MemoryEqual2B(&session->u1.templateHash.b, &tHash.b));
727 }
728
729 //*** CompareNameHash()
730 // This function computes the name hash and compares it to the nameHash in the
731 // session data.
732 BOOL
733 CompareNameHash(
734 COMMAND *command, // IN: main parsing structure
735 SESSION *session // IN: session structure with nameHash
736 )
737 {
738 HASH_STATE hashState;
739 TPM2B_DIGEST nameHash;
740 UINT32 i;
741 TPM2B_NAME name;
742 //
743 nameHash.t.size = CryptHashStart(&hashState, session->authHashAlg);
744 // Add names.
745 for(i = 0; i < command->handleNum; i++)
746 CryptDigestUpdate2B(&hashState, &EntityGetName(command->handles[i],
747 &name)->b);
748 // Complete hash.
749 CryptHashEnd2B(&hashState, &nameHash.b);
750 // and compare
751 return MemoryEqual(session->u1.nameHash.t.buffer, nameHash.t.buffer,
752 nameHash.t.size);
753 }
754
755 //*** CheckPWAuthSession()
756 // This function validates the authorization provided in a PWAP session. It
757 // compares the input value to authValue of the authorized entity. Argument
758 // sessionIndex is used to get handles handle of the referenced entities from
759 // s_inputAuthValues[] and s_associatedHandles[].
760 //
761 // Return Type: TPM_RC
762 // TPM_RC_AUTH_FAIL authorization fails and increments DA failure
763 // count
764 // TPM_RC_BAD_AUTH authorization fails but DA does not apply
765 //
766 static TPM_RC
767 CheckPWAuthSession(
768 UINT32 sessionIndex // IN: index of session to be processed
769 )
770 {
771 TPM2B_AUTH authValue;
772 TPM_HANDLE associatedHandle = s_associatedHandles[sessionIndex];
773 //
774 // Strip trailing zeros from the password.
775 MemoryRemoveTrailingZeros(&s_inputAuthValues[sessionIndex]);
776
777 // Get the authValue with trailing zeros removed
778 EntityGetAuthValue(associatedHandle, &authValue);
779
780 // Success if the values are identical.
781 if(MemoryEqual2B(&s_inputAuthValues[sessionIndex].b, &authValue.b))
782 {
783 return TPM_RC_SUCCESS;
784 }
785 else // if the digests are not identical
786 {
787 // Invoke DA protection if applicable.
788 return IncrementLockout(sessionIndex);
789 }
790 }
791
792 //*** ComputeCommandHMAC()
793 // This function computes the HMAC for an authorization session in a command.
794 /*(See part 1 specification -- this tag keeps this comment from showing up in
795 // merged document which is probably good because this comment doesn't look right.
796 // The sessionAuth value
797 // authHMAC := HMACsHash((sessionKey | authValue),
798 // (pHash | nonceNewer | nonceOlder | nonceTPMencrypt-only
799 // | nonceTPMaudit | sessionAttributes))
800 // Where:
801 // HMACsHash() The HMAC algorithm using the hash algorithm specified
802 // when the session was started.
803 //
804 // sessionKey A value that is computed in a protocol-dependent way,
805 // using KDFa. When used in an HMAC or KDF, the size field
806 // for this value is not included.
807 //
808 // authValue A value that is found in the sensitive area of an entity.
809 // When used in an HMAC or KDF, the size field for this
810 // value is not included.
811 //
812 // pHash Hash of the command (cpHash) using the session hash.
813 // When using a pHash in an HMAC computation, only the
814 // digest is used.
815 //
816 // nonceNewer A value that is generated by the entity using the
817 // session. A new nonce is generated on each use of the
818 // session. For a command, this will be nonceCaller.
819 // When used in an HMAC or KDF, the size field is not used.
820 //
821 // nonceOlder A TPM2B_NONCE that was received the previous time the
822 // session was used. For a command, this is nonceTPM.
823 // When used in an HMAC or KDF, the size field is not used.
824 //
825 // nonceTPMdecrypt The nonceTPM of the decrypt session is included in
826 // the HMAC, but only in the command.
827 //
828 // nonceTPMencrypt The nonceTPM of the encrypt session is included in
829 // the HMAC but only in the command.
830 //
831 // sessionAttributes A byte indicating the attributes associated with the
832 // particular use of the session.
833 */
834 static TPM2B_DIGEST *
835 ComputeCommandHMAC(
836 COMMAND *command, // IN: primary control structure
837 UINT32 sessionIndex, // IN: index of session to be processed
838 TPM2B_DIGEST *hmac // OUT: authorization HMAC
839 )
840 {
841 TPM2B_TYPE(KEY, (sizeof(AUTH_VALUE) * 2));
842 TPM2B_KEY key;
843 BYTE marshalBuffer[sizeof(TPMA_SESSION)];
844 BYTE *buffer;
845 UINT32 marshalSize;
846 HMAC_STATE hmacState;
847 TPM2B_NONCE *nonceDecrypt;
848 TPM2B_NONCE *nonceEncrypt;
849 SESSION *session;
850 //
851 nonceDecrypt = NULL;
852 nonceEncrypt = NULL;
853
854 // Determine if extra nonceTPM values are going to be required.
855 // If this is the first session (sessionIndex = 0) and it is an authorization
856 // session that uses an HMAC, then check if additional session nonces are to be
857 // included.
858 if(sessionIndex == 0
859 && s_associatedHandles[sessionIndex] != TPM_RH_UNASSIGNED)
860 {
861 // If there is a decrypt session and if this is not the decrypt session,
862 // then an extra nonce may be needed.
863 if(s_decryptSessionIndex != UNDEFINED_INDEX
864 && s_decryptSessionIndex != sessionIndex)
865 {
866 // Will add the nonce for the decrypt session.
867 SESSION *decryptSession
868 = SessionGet(s_sessionHandles[s_decryptSessionIndex]);
869 nonceDecrypt = &decryptSession->nonceTPM;
870 }
871 // Now repeat for the encrypt session.
872 if(s_encryptSessionIndex != UNDEFINED_INDEX
873 && s_encryptSessionIndex != sessionIndex
874 && s_encryptSessionIndex != s_decryptSessionIndex)
875 {
876 // Have to have the nonce for the encrypt session.
877 SESSION *encryptSession
878 = SessionGet(s_sessionHandles[s_encryptSessionIndex]);
879 nonceEncrypt = &encryptSession->nonceTPM;
880 }
881 }
882
883 // Continue with the HMAC processing.
884 session = SessionGet(s_sessionHandles[sessionIndex]);
885
886 // Generate HMAC key.
887 MemoryCopy2B(&key.b, &session->sessionKey.b, sizeof(key.t.buffer));
888
889 // Check if the session has an associated handle and if the associated entity
890 // is the one to which the session is bound. If not, add the authValue of
891 // this entity to the HMAC key.
892 // If the session is bound to the object or the session is a policy session
893 // with no authValue required, do not include the authValue in the HMAC key.
894 // Note: For a policy session, its isBound attribute is CLEARED.
895 //
896 // Include the entity authValue if it is needed
897 if(session->attributes.includeAuth == SET)
898 {
899 TPM2B_AUTH authValue;
900 // Get the entity authValue with trailing zeros removed
901 EntityGetAuthValue(s_associatedHandles[sessionIndex], &authValue);
902 // add the authValue to the HMAC key
903 MemoryConcat2B(&key.b, &authValue.b, sizeof(key.t.buffer));
904 }
905 // if the HMAC key size is 0, a NULL string HMAC is allowed
906 if(key.t.size == 0
907 && s_inputAuthValues[sessionIndex].t.size == 0)
908 {
909 hmac->t.size = 0;
910 return hmac;
911 }
912 // Start HMAC
913 hmac->t.size = CryptHmacStart2B(&hmacState, session->authHashAlg, &key.b);
914
915 // Add cpHash
916 CryptDigestUpdate2B(&hmacState.hashState,
917 &ComputeCpHash(command, session->authHashAlg)->b);
918 // Add nonces as required
919 CryptDigestUpdate2B(&hmacState.hashState, &s_nonceCaller[sessionIndex].b);
920 CryptDigestUpdate2B(&hmacState.hashState, &session->nonceTPM.b);
921 if(nonceDecrypt != NULL)
922 CryptDigestUpdate2B(&hmacState.hashState, &nonceDecrypt->b);
923 if(nonceEncrypt != NULL)
924 CryptDigestUpdate2B(&hmacState.hashState, &nonceEncrypt->b);
925 // Add sessionAttributes
926 buffer = marshalBuffer;
927 marshalSize = TPMA_SESSION_Marshal(&(s_attributes[sessionIndex]),
928 &buffer, NULL);
929 CryptDigestUpdate(&hmacState.hashState, marshalSize, marshalBuffer);
930 // Complete the HMAC computation
931 CryptHmacEnd2B(&hmacState, &hmac->b);
932
933 return hmac;
934 }
935
936 //*** CheckSessionHMAC()
937 // This function checks the HMAC of in a session. It uses ComputeCommandHMAC()
938 // to compute the expected HMAC value and then compares the result with the
939 // HMAC in the authorization session. The authorization is successful if they
940 // are the same.
941 //
942 // If the authorizations are not the same, IncrementLockout() is called. It will
943 // return TPM_RC_AUTH_FAIL if the failure caused the failureCount to increment.
944 // Otherwise, it will return TPM_RC_BAD_AUTH.
945 //
946 // Return Type: TPM_RC
947 // TPM_RC_AUTH_FAIL authorization failure caused failureCount increment
948 // TPM_RC_BAD_AUTH authorization failure did not cause failureCount
949 // increment
950 //
951 static TPM_RC
952 CheckSessionHMAC(
953 COMMAND *command, // IN: primary control structure
954 UINT32 sessionIndex // IN: index of session to be processed
955 )
956 {
957 TPM2B_DIGEST hmac; // authHMAC for comparing
958 //
959 // Compute authHMAC
960 ComputeCommandHMAC(command, sessionIndex, &hmac);
961
962 // Compare the input HMAC with the authHMAC computed above.
963 if(!MemoryEqual2B(&s_inputAuthValues[sessionIndex].b, &hmac.b))
964 {
965 // If an HMAC session has a failure, invoke the anti-hammering
966 // if it applies to the authorized entity or the session.
967 // Otherwise, just indicate that the authorization is bad.
968 return IncrementLockout(sessionIndex);
969 }
970 return TPM_RC_SUCCESS;
971 }
972
973 //*** CheckPolicyAuthSession()
974 // This function is used to validate the authorization in a policy session.
975 // This function performs the following comparisons to see if a policy
976 // authorization is properly provided. The check are:
977 // 1. compare policyDigest in session with authPolicy associated with
978 // the entity to be authorized;
979 // 2. compare timeout if applicable;
980 // 3. compare commandCode if applicable;
981 // 4. compare cpHash if applicable; and
982 // 5. see if PCR values have changed since computed.
983 //
984 // If all the above checks succeed, the handle is authorized.
985 // The order of these comparisons is not important because any failure will
986 // result in the same error code.
987 //
988 // Return Type: TPM_RC
989 // TPM_RC_PCR_CHANGED PCR value is not current
990 // TPM_RC_POLICY_FAIL policy session fails
991 // TPM_RC_LOCALITY command locality is not allowed
992 // TPM_RC_POLICY_CC CC doesn't match
993 // TPM_RC_EXPIRED policy session has expired
994 // TPM_RC_PP PP is required but not asserted
995 // TPM_RC_NV_UNAVAILABLE NV is not available for write
996 // TPM_RC_NV_RATE NV is rate limiting
997 static TPM_RC
998 CheckPolicyAuthSession(
999 COMMAND *command, // IN: primary parsing structure
1000 UINT32 sessionIndex // IN: index of session to be processed
1001 )
1002 {
1003 SESSION *session;
1004 TPM2B_DIGEST authPolicy;
1005 TPMI_ALG_HASH policyAlg;
1006 UINT8 locality;
1007 //
1008 // Initialize pointer to the authorization session.
1009 session = SessionGet(s_sessionHandles[sessionIndex]);
1010
1011 // If the command is TPM2_PolicySecret(), make sure that
1012 // either password or authValue is required
1013 if(command->code == TPM_CC_PolicySecret
1014 && session->attributes.isPasswordNeeded == CLEAR
1015 && session->attributes.isAuthValueNeeded == CLEAR)
1016 return TPM_RC_MODE;
1017 // See if the PCR counter for the session is still valid.
1018 if(!SessionPCRValueIsCurrent(session))
1019 return TPM_RC_PCR_CHANGED;
1020 // Get authPolicy.
1021 policyAlg = EntityGetAuthPolicy(s_associatedHandles[sessionIndex],
1022 &authPolicy);
1023 // Compare authPolicy.
1024 if(!MemoryEqual2B(&session->u2.policyDigest.b, &authPolicy.b))
1025 return TPM_RC_POLICY_FAIL;
1026 // Policy is OK so check if the other factors are correct
1027
1028 // Compare policy hash algorithm.
1029 if(policyAlg != session->authHashAlg)
1030 return TPM_RC_POLICY_FAIL;
1031
1032 // Compare timeout.
1033 if(session->timeout != 0)
1034 {
1035 // Cannot compare time if clock stop advancing. An TPM_RC_NV_UNAVAILABLE
1036 // or TPM_RC_NV_RATE error may be returned here. This doesn't mean that
1037 // a new nonce will be created just that, because TPM time can't advance
1038 // we can't do time-based operations.
1039 RETURN_IF_NV_IS_NOT_AVAILABLE;
1040
1041 if((session->timeout < g_time)
1042 || (session->epoch != g_timeEpoch))
1043 return TPM_RC_EXPIRED;
1044 }
1045 // If command code is provided it must match
1046 if(session->commandCode != 0)
1047 {
1048 if(session->commandCode != command->code)
1049 return TPM_RC_POLICY_CC;
1050 }
1051 else
1052 {
1053 // If command requires a DUP or ADMIN authorization, the session must have
1054 // command code set.
1055 AUTH_ROLE role = CommandAuthRole(command->index, sessionIndex);
1056 if(role == AUTH_ADMIN || role == AUTH_DUP)
1057 return TPM_RC_POLICY_FAIL;
1058 }
1059 // Check command locality.
1060 {
1061 BYTE sessionLocality[sizeof(TPMA_LOCALITY)];
1062 BYTE *buffer = sessionLocality;
1063
1064 // Get existing locality setting in canonical form
1065 sessionLocality[0] = 0;
1066 TPMA_LOCALITY_Marshal(&session->commandLocality, &buffer, NULL);
1067
1068 // See if the locality has been set
1069 if(sessionLocality[0] != 0)
1070 {
1071 // If so, get the current locality
1072 locality = _plat__LocalityGet();
1073 if(locality < 5)
1074 {
1075 if(((sessionLocality[0] & (1 << locality)) == 0)
1076 || sessionLocality[0] > 31)
1077 return TPM_RC_LOCALITY;
1078 }
1079 else if(locality > 31)
1080 {
1081 if(sessionLocality[0] != locality)
1082 return TPM_RC_LOCALITY;
1083 }
1084 else
1085 {
1086 // Could throw an assert here but a locality error is just
1087 // as good. It just means that, whatever the locality is, it isn't
1088 // the locality requested so...
1089 return TPM_RC_LOCALITY;
1090 }
1091 }
1092 } // end of locality check
1093 // Check physical presence.
1094 if(session->attributes.isPPRequired == SET
1095 && !_plat__PhysicalPresenceAsserted())
1096 return TPM_RC_PP;
1097 // Compare cpHash/nameHash if defined, or if the command requires an ADMIN or
1098 // DUP role for this handle.
1099 if(session->u1.cpHash.b.size != 0)
1100 {
1101 BOOL OK;
1102 if(session->attributes.isCpHashDefined)
1103 // Compare cpHash.
1104 OK = MemoryEqual2B(&session->u1.cpHash.b,
1105 &ComputeCpHash(command, session->authHashAlg)->b);
1106 else if(session->attributes.isTemplateSet)
1107 OK = CompareTemplateHash(command, session);
1108 else
1109 OK = CompareNameHash(command, session);
1110 if(!OK)
1111 return TPM_RCS_POLICY_FAIL;
1112 }
1113 if(session->attributes.checkNvWritten)
1114 {
1115 NV_REF locator;
1116 NV_INDEX *nvIndex;
1117 //
1118 // If this is not an NV index, the policy makes no sense so fail it.
1119 if(HandleGetType(s_associatedHandles[sessionIndex]) != TPM_HT_NV_INDEX)
1120 return TPM_RC_POLICY_FAIL;
1121 // Get the index data
1122 nvIndex = NvGetIndexInfo(s_associatedHandles[sessionIndex], &locator);
1123
1124 // Make sure that the TPMA_WRITTEN_ATTRIBUTE has the desired state
1125 if((IS_ATTRIBUTE(nvIndex->publicArea.attributes, TPMA_NV, WRITTEN))
1126 != (session->attributes.nvWrittenState == SET))
1127 return TPM_RC_POLICY_FAIL;
1128 }
1129 return TPM_RC_SUCCESS;
1130 }
1131
1132 //*** RetrieveSessionData()
1133 // This function will unmarshal the sessions in the session area of a command. The
1134 // values are placed in the arrays that are defined at the beginning of this file.
1135 // The normal unmarshaling errors are possible.
1136 //
1137 // Return Type: TPM_RC
1138 // TPM_RC_SUCCSS unmarshaled without error
1139 // TPM_RC_SIZE the number of bytes unmarshaled is not the same
1140 // as the value for authorizationSize in the command
1141 //
1142 static TPM_RC
1143 RetrieveSessionData(
1144 COMMAND *command // IN: main parsing structure for command
1145 )
1146 {
1147 int i;
1148 TPM_RC result;
1149 SESSION *session;
1150 TPMA_SESSION sessionAttributes;
1151 TPM_HT sessionType;
1152 INT32 sessionIndex;
1153 TPM_RC errorIndex;
1154 //
1155 s_decryptSessionIndex = UNDEFINED_INDEX;
1156 s_encryptSessionIndex = UNDEFINED_INDEX;
1157 s_auditSessionIndex = UNDEFINED_INDEX;
1158
1159 for(sessionIndex = 0; command->authSize > 0; sessionIndex++)
1160 {
1161 errorIndex = TPM_RC_S + g_rcIndex[sessionIndex];
1162
1163 // If maximum allowed number of sessions has been parsed, return a size
1164 // error with a session number that is larger than the number of allowed
1165 // sessions
1166 if(sessionIndex == MAX_SESSION_NUM)
1167 return TPM_RCS_SIZE + errorIndex;
1168 // make sure that the associated handle for each session starts out
1169 // unassigned
1170 s_associatedHandles[sessionIndex] = TPM_RH_UNASSIGNED;
1171
1172 // First parameter: Session handle.
1173 result = TPMI_SH_AUTH_SESSION_Unmarshal(
1174 &s_sessionHandles[sessionIndex],
1175 &command->parameterBuffer,
1176 &command->authSize, TRUE);
1177 if(result != TPM_RC_SUCCESS)
1178 return result + TPM_RC_S + g_rcIndex[sessionIndex];
1179 // Second parameter: Nonce.
1180 result = TPM2B_NONCE_Unmarshal(&s_nonceCaller[sessionIndex],
1181 &command->parameterBuffer,
1182 &command->authSize);
1183 if(result != TPM_RC_SUCCESS)
1184 return result + TPM_RC_S + g_rcIndex[sessionIndex];
1185 // Third parameter: sessionAttributes.
1186 result = TPMA_SESSION_Unmarshal(&s_attributes[sessionIndex],
1187 &command->parameterBuffer,
1188 &command->authSize);
1189 if(result != TPM_RC_SUCCESS)
1190 return result + TPM_RC_S + g_rcIndex[sessionIndex];
1191 // Fourth parameter: authValue (PW or HMAC).
1192 result = TPM2B_AUTH_Unmarshal(&s_inputAuthValues[sessionIndex],
1193 &command->parameterBuffer,
1194 &command->authSize);
1195 if(result != TPM_RC_SUCCESS)
1196 return result + errorIndex;
1197
1198 sessionAttributes = s_attributes[sessionIndex];
1199 if(s_sessionHandles[sessionIndex] == TPM_RS_PW)
1200 {
1201 // A PWAP session needs additional processing.
1202 // Can't have any attributes set other than continueSession bit
1203 if(IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, encrypt)
1204 || IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, decrypt)
1205 || IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, audit)
1206 || IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, auditExclusive)
1207 || IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, auditReset))
1208 return TPM_RCS_ATTRIBUTES + errorIndex;
1209 // The nonce size must be zero.
1210 if(s_nonceCaller[sessionIndex].t.size != 0)
1211 return TPM_RCS_NONCE + errorIndex;
1212 continue;
1213 }
1214 // For not password sessions...
1215 // Find out if the session is loaded.
1216 if(!SessionIsLoaded(s_sessionHandles[sessionIndex]))
1217 return TPM_RC_REFERENCE_S0 + sessionIndex;
1218 sessionType = HandleGetType(s_sessionHandles[sessionIndex]);
1219 session = SessionGet(s_sessionHandles[sessionIndex]);
1220
1221 // Check if the session is an HMAC/policy session.
1222 if((session->attributes.isPolicy == SET
1223 && sessionType == TPM_HT_HMAC_SESSION)
1224 || (session->attributes.isPolicy == CLEAR
1225 && sessionType == TPM_HT_POLICY_SESSION))
1226 return TPM_RCS_HANDLE + errorIndex;
1227 // Check that this handle has not previously been used.
1228 for(i = 0; i < sessionIndex; i++)
1229 {
1230 if(s_sessionHandles[i] == s_sessionHandles[sessionIndex])
1231 return TPM_RCS_HANDLE + errorIndex;
1232 }
1233 // If the session is used for parameter encryption or audit as well, set
1234 // the corresponding Indexes.
1235
1236 // First process decrypt.
1237 if(IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, decrypt))
1238 {
1239 // Check if the commandCode allows command parameter encryption.
1240 if(DecryptSize(command->index) == 0)
1241 return TPM_RCS_ATTRIBUTES + errorIndex;
1242 // Encrypt attribute can only appear in one session
1243 if(s_decryptSessionIndex != UNDEFINED_INDEX)
1244 return TPM_RCS_ATTRIBUTES + errorIndex;
1245 // Can't decrypt if the session's symmetric algorithm is TPM_ALG_NULL
1246 if(session->symmetric.algorithm == TPM_ALG_NULL)
1247 return TPM_RCS_SYMMETRIC + errorIndex;
1248 // All checks passed, so set the index for the session used to decrypt
1249 // a command parameter.
1250 s_decryptSessionIndex = sessionIndex;
1251 }
1252 // Now process encrypt.
1253 if(IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, encrypt))
1254 {
1255 // Check if the commandCode allows response parameter encryption.
1256 if(EncryptSize(command->index) == 0)
1257 return TPM_RCS_ATTRIBUTES + errorIndex;
1258 // Encrypt attribute can only appear in one session.
1259 if(s_encryptSessionIndex != UNDEFINED_INDEX)
1260 return TPM_RCS_ATTRIBUTES + errorIndex;
1261 // Can't encrypt if the session's symmetric algorithm is TPM_ALG_NULL
1262 if(session->symmetric.algorithm == TPM_ALG_NULL)
1263 return TPM_RCS_SYMMETRIC + errorIndex;
1264 // All checks passed, so set the index for the session used to encrypt
1265 // a response parameter.
1266 s_encryptSessionIndex = sessionIndex;
1267 }
1268 // At last process audit.
1269 if(IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, audit))
1270 {
1271 // Audit attribute can only appear in one session.
1272 if(s_auditSessionIndex != UNDEFINED_INDEX)
1273 return TPM_RCS_ATTRIBUTES + errorIndex;
1274 // An audit session can not be policy session.
1275 if(HandleGetType(s_sessionHandles[sessionIndex])
1276 == TPM_HT_POLICY_SESSION)
1277 return TPM_RCS_ATTRIBUTES + errorIndex;
1278 // If this is a reset of the audit session, or the first use
1279 // of the session as an audit session, it doesn't matter what
1280 // the exclusive state is. The session will become exclusive.
1281 if(!IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, auditReset)
1282 && session->attributes.isAudit == SET)
1283 {
1284 // Not first use or reset. If auditExlusive is SET, then this
1285 // session must be the current exclusive session.
1286 if(IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, auditExclusive)
1287 && g_exclusiveAuditSession != s_sessionHandles[sessionIndex])
1288 return TPM_RC_EXCLUSIVE;
1289 }
1290 s_auditSessionIndex = sessionIndex;
1291 }
1292 // Initialize associated handle as undefined. This will be changed when
1293 // the handles are processed.
1294 s_associatedHandles[sessionIndex] = TPM_RH_UNASSIGNED;
1295 }
1296 command->sessionNum = sessionIndex;
1297 return TPM_RC_SUCCESS;
1298 }
1299
1300 //*** CheckLockedOut()
1301 // This function checks to see if the TPM is in lockout. This function should only
1302 // be called if the entity being checked is subject to DA protection. The TPM
1303 // is in lockout if the NV is not available and a DA write is pending. Otherwise
1304 // the TPM is locked out if checking for lockoutAuth ('lockoutAuthCheck' == TRUE)
1305 // and use of lockoutAuth is disabled, or 'failedTries' >= 'maxTries'
1306 // Return Type: TPM_RC
1307 // TPM_RC_NV_RATE NV is rate limiting
1308 // TPM_RC_NV_UNAVAILABLE NV is not available at this time
1309 // TPM_RC_LOCKOUT TPM is in lockout
1310 static TPM_RC
1311 CheckLockedOut(
1312 BOOL lockoutAuthCheck // IN: TRUE if checking is for lockoutAuth
1313 )
1314 {
1315 // If NV is unavailable, and current cycle state recorded in NV is not
1316 // SU_NONE_VALUE, refuse to check any authorization because we would
1317 // not be able to handle a DA failure.
1318 if(!NV_IS_AVAILABLE && NV_IS_ORDERLY)
1319 return g_NvStatus;
1320 // Check if DA info needs to be updated in NV.
1321 if(s_DAPendingOnNV)
1322 {
1323 // If NV is accessible,
1324 RETURN_IF_NV_IS_NOT_AVAILABLE;
1325
1326 // ... write the pending DA data and proceed.
1327 NV_SYNC_PERSISTENT(lockOutAuthEnabled);
1328 NV_SYNC_PERSISTENT(failedTries);
1329 s_DAPendingOnNV = FALSE;
1330 }
1331 // Lockout is in effect if checking for lockoutAuth and use of lockoutAuth
1332 // is disabled...
1333 if(lockoutAuthCheck)
1334 {
1335 if(gp.lockOutAuthEnabled == FALSE)
1336 return TPM_RC_LOCKOUT;
1337 }
1338 else
1339 {
1340 // ... or if the number of failed tries has been maxed out.
1341 if(gp.failedTries >= gp.maxTries)
1342 return TPM_RC_LOCKOUT;
1343 #if USE_DA_USED
1344 // If the daUsed flag is not SET, then no DA validation until the
1345 // daUsed state is written to NV
1346 if(!g_daUsed)
1347 {
1348 RETURN_IF_NV_IS_NOT_AVAILABLE;
1349 g_daUsed = TRUE;
1350 gp.orderlyState = SU_DA_USED_VALUE;
1351 NV_SYNC_PERSISTENT(orderlyState);
1352 return TPM_RC_RETRY;
1353 }
1354 #endif
1355 }
1356 return TPM_RC_SUCCESS;
1357 }
1358
1359 //*** CheckAuthSession()
1360 // This function checks that the authorization session properly authorizes the
1361 // use of the associated handle.
1362 //
1363 // Return Type: TPM_RC
1364 // TPM_RC_LOCKOUT entity is protected by DA and TPM is in
1365 // lockout, or TPM is locked out on NV update
1366 // pending on DA parameters
1367 //
1368 // TPM_RC_PP Physical Presence is required but not provided
1369 // TPM_RC_AUTH_FAIL HMAC or PW authorization failed
1370 // with DA side-effects (can be a policy session)
1371 //
1372 // TPM_RC_BAD_AUTH HMAC or PW authorization failed without DA
1373 // side-effects (can be a policy session)
1374 //
1375 // TPM_RC_POLICY_FAIL if policy session fails
1376 // TPM_RC_POLICY_CC command code of policy was wrong
1377 // TPM_RC_EXPIRED the policy session has expired
1378 // TPM_RC_PCR
1379 // TPM_RC_AUTH_UNAVAILABLE authValue or authPolicy unavailable
1380 static TPM_RC
1381 CheckAuthSession(
1382 COMMAND *command, // IN: primary parsing structure
1383 UINT32 sessionIndex // IN: index of session to be processed
1384 )
1385 {
1386 TPM_RC result = TPM_RC_SUCCESS;
1387 SESSION *session = NULL;
1388 TPM_HANDLE sessionHandle = s_sessionHandles[sessionIndex];
1389 TPM_HANDLE associatedHandle = s_associatedHandles[sessionIndex];
1390 TPM_HT sessionHandleType = HandleGetType(sessionHandle);
1391 //
1392 pAssert(sessionHandle != TPM_RH_UNASSIGNED);
1393
1394 // Take care of physical presence
1395 if(associatedHandle == TPM_RH_PLATFORM)
1396 {
1397 // If the physical presence is required for this command, check for PP
1398 // assertion. If it isn't asserted, no point going any further.
1399 if(PhysicalPresenceIsRequired(command->index)
1400 && !_plat__PhysicalPresenceAsserted())
1401 return TPM_RC_PP;
1402 }
1403 if(sessionHandle != TPM_RS_PW)
1404 {
1405 session = SessionGet(sessionHandle);
1406
1407 // Set includeAuth to indicate if DA checking will be required and if the
1408 // authValue will be included in any HMAC.
1409 if(sessionHandleType == TPM_HT_POLICY_SESSION)
1410 {
1411 // For a policy session, will check the DA status of the entity if either
1412 // isAuthValueNeeded or isPasswordNeeded is SET.
1413 session->attributes.includeAuth =
1414 session->attributes.isAuthValueNeeded
1415 || session->attributes.isPasswordNeeded;
1416 }
1417 else
1418 {
1419 // For an HMAC session, need to check unless the session
1420 // is bound.
1421 session->attributes.includeAuth =
1422 !IsSessionBindEntity(s_associatedHandles[sessionIndex], session);
1423 }
1424 }
1425 // If the authorization session is going to use an authValue, then make sure
1426 // that access to that authValue isn't locked out.
1427 // Note: session == NULL for a PW session.
1428 if(session == NULL || session->attributes.includeAuth)
1429 {
1430 // See if entity is subject to lockout.
1431 if(!IsDAExempted(associatedHandle))
1432 {
1433 // See if in lockout
1434 result = CheckLockedOut(associatedHandle == TPM_RH_LOCKOUT);
1435 if(result != TPM_RC_SUCCESS)
1436 return result;
1437 }
1438 }
1439 // Policy or HMAC+PW?
1440 if(sessionHandleType != TPM_HT_POLICY_SESSION)
1441 {
1442 // for non-policy session make sure that a policy session is not required
1443 if(IsPolicySessionRequired(command->index, sessionIndex))
1444 return TPM_RC_AUTH_TYPE;
1445 // The authValue must be available.
1446 // Note: The authValue is going to be "used" even if it is an EmptyAuth.
1447 // and the session is bound.
1448 if(!IsAuthValueAvailable(associatedHandle, command->index, sessionIndex))
1449 return TPM_RC_AUTH_UNAVAILABLE;
1450 }
1451 else
1452 {
1453 // ... see if the entity has a policy, ...
1454 // Note: IsAuthPolicyAvalable will return FALSE if the sensitive area of the
1455 // object is not loaded
1456 if(!IsAuthPolicyAvailable(associatedHandle, command->index, sessionIndex))
1457 return TPM_RC_AUTH_UNAVAILABLE;
1458 // ... and check the policy session.
1459 result = CheckPolicyAuthSession(command, sessionIndex);
1460 if(result != TPM_RC_SUCCESS)
1461 return result;
1462 }
1463 // Check authorization according to the type
1464 if(session == NULL || session->attributes.isPasswordNeeded == SET)
1465 result = CheckPWAuthSession(sessionIndex);
1466 else
1467 result = CheckSessionHMAC(command, sessionIndex);
1468 // Do processing for PIN Indexes are only three possibilities for 'result' at
1469 // this point: TPM_RC_SUCCESS, TPM_RC_AUTH_FAIL, and TPM_RC_BAD_AUTH.
1470 // For all these cases, we would have to process a PIN index if the
1471 // authValue of the index was used for authorization.
1472 // See if we need to do anything to a PIN index
1473 if(TPM_HT_NV_INDEX == HandleGetType(associatedHandle))
1474 {
1475 NV_REF locator;
1476 NV_INDEX *nvIndex = NvGetIndexInfo(associatedHandle, &locator);
1477 NV_PIN pinData;
1478 TPMA_NV nvAttributes;
1479 //
1480 pAssert(nvIndex != NULL);
1481 nvAttributes = nvIndex->publicArea.attributes;
1482 // If this is a PIN FAIL index and the value has been written
1483 // then we can update the counter (increment or clear)
1484 if(IsNvPinFailIndex(nvAttributes)
1485 && IS_ATTRIBUTE(nvAttributes, TPMA_NV, WRITTEN))
1486 {
1487 pinData.intVal = NvGetUINT64Data(nvIndex, locator);
1488 if(result != TPM_RC_SUCCESS)
1489 pinData.pin.pinCount++;
1490 else
1491 pinData.pin.pinCount = 0;
1492 NvWriteUINT64Data(nvIndex, pinData.intVal);
1493 }
1494 // If this is a PIN PASS Index, increment if we have used the
1495 // authorization value for anything other than NV_Read.
1496 // NOTE: If the counter has already hit the limit, then we
1497 // would not get here because the authorization value would not
1498 // be available and the TPM would have returned before it gets here
1499 else if(IsNvPinPassIndex(nvAttributes)
1500 && IS_ATTRIBUTE(nvAttributes, TPMA_NV, WRITTEN)
1501 && result == TPM_RC_SUCCESS)
1502 {
1503 // If the access is valid, then increment the use counter
1504 pinData.intVal = NvGetUINT64Data(nvIndex, locator);
1505 pinData.pin.pinCount++;
1506 NvWriteUINT64Data(nvIndex, pinData.intVal);
1507 }
1508 }
1509 return result;
1510 }
1511
1512 #ifdef TPM_CC_GetCommandAuditDigest
1513 //*** CheckCommandAudit()
1514 // This function is called before the command is processed if audit is enabled
1515 // for the command. It will check to see if the audit can be performed and
1516 // will ensure that the cpHash is available for the audit.
1517 // Return Type: TPM_RC
1518 // TPM_RC_NV_UNAVAILABLE NV is not available for write
1519 // TPM_RC_NV_RATE NV is rate limiting
1520 static TPM_RC
1521 CheckCommandAudit(
1522 COMMAND *command
1523 )
1524 {
1525 // If the audit digest is clear and command audit is required, NV must be
1526 // available so that TPM2_GetCommandAuditDigest() is able to increment
1527 // audit counter. If NV is not available, the function bails out to prevent
1528 // the TPM from attempting an operation that would fail anyway.
1529 if(gr.commandAuditDigest.t.size == 0
1530 || GetCommandCode(command->index) == TPM_CC_GetCommandAuditDigest)
1531 {
1532 RETURN_IF_NV_IS_NOT_AVAILABLE;
1533 }
1534 // Make sure that the cpHash is computed for the algorithm
1535 ComputeCpHash(command, gp.auditHashAlg);
1536 return TPM_RC_SUCCESS;
1537 }
1538 #endif
1539
1540 //*** ParseSessionBuffer()
1541 // This function is the entry function for command session processing.
1542 // It iterates sessions in session area and reports if the required authorization
1543 // has been properly provided. It also processes audit session and passes the
1544 // information of encryption sessions to parameter encryption module.
1545 //
1546 // Return Type: TPM_RC
1547 // various parsing failure or authorization failure
1548 //
1549 TPM_RC
1550 ParseSessionBuffer(
1551 COMMAND *command // IN: the structure that contains
1552 )
1553 {
1554 TPM_RC result;
1555 UINT32 i;
1556 INT32 size = 0;
1557 TPM2B_AUTH extraKey;
1558 UINT32 sessionIndex;
1559 TPM_RC errorIndex;
1560 SESSION *session = NULL;
1561 //
1562 // Check if a command allows any session in its session area.
1563 if(!IsSessionAllowed(command->index))
1564 return TPM_RC_AUTH_CONTEXT;
1565 // Default-initialization.
1566 command->sessionNum = 0;
1567
1568 result = RetrieveSessionData(command);
1569 if(result != TPM_RC_SUCCESS)
1570 return result;
1571 // There is no command in the TPM spec that has more handles than
1572 // MAX_SESSION_NUM.
1573 pAssert(command->handleNum <= MAX_SESSION_NUM);
1574
1575 // Associate the session with an authorization handle.
1576 for(i = 0; i < command->handleNum; i++)
1577 {
1578 if(CommandAuthRole(command->index, i) != AUTH_NONE)
1579 {
1580 // If the received session number is less than the number of handles
1581 // that requires authorization, an error should be returned.
1582 // Note: for all the TPM 2.0 commands, handles requiring
1583 // authorization come first in a command input and there are only ever
1584 // two values requiring authorization
1585 if(i > (command->sessionNum - 1))
1586 return TPM_RC_AUTH_MISSING;
1587 // Record the handle associated with the authorization session
1588 s_associatedHandles[i] = command->handles[i];
1589 }
1590 }
1591 // Consistency checks are done first to avoid authorization failure when the
1592 // command will not be executed anyway.
1593 for(sessionIndex = 0; sessionIndex < command->sessionNum; sessionIndex++)
1594 {
1595 errorIndex = TPM_RC_S + g_rcIndex[sessionIndex];
1596 // PW session must be an authorization session
1597 if(s_sessionHandles[sessionIndex] == TPM_RS_PW)
1598 {
1599 if(s_associatedHandles[sessionIndex] == TPM_RH_UNASSIGNED)
1600 return TPM_RCS_HANDLE + errorIndex;
1601 // a password session can't be audit, encrypt or decrypt
1602 if(IS_ATTRIBUTE(s_attributes[sessionIndex], TPMA_SESSION, audit)
1603 || IS_ATTRIBUTE(s_attributes[sessionIndex], TPMA_SESSION, encrypt)
1604 || IS_ATTRIBUTE(s_attributes[sessionIndex], TPMA_SESSION, decrypt))
1605 return TPM_RCS_ATTRIBUTES + errorIndex;
1606 session = NULL;
1607 }
1608 else
1609 {
1610 session = SessionGet(s_sessionHandles[sessionIndex]);
1611
1612 // A trial session can not appear in session area, because it cannot
1613 // be used for authorization, audit or encrypt/decrypt.
1614 if(session->attributes.isTrialPolicy == SET)
1615 return TPM_RCS_ATTRIBUTES + errorIndex;
1616
1617 // See if the session is bound to a DA protected entity
1618 // NOTE: Since a policy session is never bound, a policy is still
1619 // usable even if the object is DA protected and the TPM is in
1620 // lockout.
1621 if(session->attributes.isDaBound == SET)
1622 {
1623 result = CheckLockedOut(session->attributes.isLockoutBound == SET);
1624 if(result != TPM_RC_SUCCESS)
1625 return result;
1626 }
1627 // If this session is for auditing, make sure the cpHash is computed.
1628 if(IS_ATTRIBUTE(s_attributes[sessionIndex], TPMA_SESSION, audit))
1629 ComputeCpHash(command, session->authHashAlg);
1630 }
1631
1632 // if the session has an associated handle, check the authorization
1633 if(s_associatedHandles[sessionIndex] != TPM_RH_UNASSIGNED)
1634 {
1635 result = CheckAuthSession(command, sessionIndex);
1636 if(result != TPM_RC_SUCCESS)
1637 return RcSafeAddToResult(result, errorIndex);
1638 }
1639 else
1640 {
1641 // a session that is not for authorization must either be encrypt,
1642 // decrypt, or audit
1643 if(!IS_ATTRIBUTE(s_attributes[sessionIndex], TPMA_SESSION, audit)
1644 && !IS_ATTRIBUTE(s_attributes[sessionIndex], TPMA_SESSION, encrypt)
1645 && !IS_ATTRIBUTE(s_attributes[sessionIndex], TPMA_SESSION, decrypt))
1646 return TPM_RCS_ATTRIBUTES + errorIndex;
1647
1648 // no authValue included in any of the HMAC computations
1649 pAssert(session != NULL);
1650 session->attributes.includeAuth = CLEAR;
1651
1652 // check HMAC for encrypt/decrypt/audit only sessions
1653 result = CheckSessionHMAC(command, sessionIndex);
1654 if(result != TPM_RC_SUCCESS)
1655 return RcSafeAddToResult(result, errorIndex);
1656 }
1657 }
1658 #ifdef TPM_CC_GetCommandAuditDigest
1659 // Check if the command should be audited. Need to do this before any parameter
1660 // encryption so that the cpHash for the audit is correct
1661 if(CommandAuditIsRequired(command->index))
1662 {
1663 result = CheckCommandAudit(command);
1664 if(result != TPM_RC_SUCCESS)
1665 return result; // No session number to reference
1666 }
1667 #endif
1668 // Decrypt the first parameter if applicable. This should be the last operation
1669 // in session processing.
1670 // If the encrypt session is associated with a handle and the handle's
1671 // authValue is available, then authValue is concatenated with sessionKey to
1672 // generate encryption key, no matter if the handle is the session bound entity
1673 // or not.
1674 if(s_decryptSessionIndex != UNDEFINED_INDEX)
1675 {
1676 // If this is an authorization session, include the authValue in the
1677 // generation of the decryption key
1678 if(s_associatedHandles[s_decryptSessionIndex] != TPM_RH_UNASSIGNED)
1679 {
1680 EntityGetAuthValue(s_associatedHandles[s_decryptSessionIndex],
1681 &extraKey);
1682 }
1683 else
1684 {
1685 extraKey.b.size = 0;
1686 }
1687 size = DecryptSize(command->index);
1688 result = CryptParameterDecryption(s_sessionHandles[s_decryptSessionIndex],
1689 &s_nonceCaller[s_decryptSessionIndex].b,
1690 command->parameterSize, (UINT16)size,
1691 &extraKey,
1692 command->parameterBuffer);
1693 if(result != TPM_RC_SUCCESS)
1694 return RcSafeAddToResult(result,
1695 TPM_RC_S + g_rcIndex[s_decryptSessionIndex]);
1696 }
1697
1698 return TPM_RC_SUCCESS;
1699 }
1700
1701 //*** CheckAuthNoSession()
1702 // Function to process a command with no session associated.
1703 // The function makes sure all the handles in the command require no authorization.
1704 //
1705 // Return Type: TPM_RC
1706 // TPM_RC_AUTH_MISSING failure - one or more handles require
1707 // authorization
1708 TPM_RC
1709 CheckAuthNoSession(
1710 COMMAND *command // IN: command parsing structure
1711 )
1712 {
1713 UINT32 i;
1714 TPM_RC result = TPM_RC_SUCCESS;
1715 //
1716 // Check if the command requires authorization
1717 for(i = 0; i < command->handleNum; i++)
1718 {
1719 if(CommandAuthRole(command->index, i) != AUTH_NONE)
1720 return TPM_RC_AUTH_MISSING;
1721 }
1722 #ifdef TPM_CC_GetCommandAuditDigest
1723 // Check if the command should be audited.
1724 if(CommandAuditIsRequired(command->index))
1725 {
1726 result = CheckCommandAudit(command);
1727 if(result != TPM_RC_SUCCESS)
1728 return result;
1729 }
1730 #endif
1731 // Initialize number of sessions to be 0
1732 command->sessionNum = 0;
1733
1734 return TPM_RC_SUCCESS;
1735 }
1736
1737 //** Response Session Processing
1738 //*** Introduction
1739 //
1740 // The following functions build the session area in a response and handle
1741 // the audit sessions (if present).
1742 //
1743
1744 //*** ComputeRpHash()
1745 // Function to compute rpHash (Response Parameter Hash). The rpHash is only
1746 // computed if there is an HMAC authorization session and the return code is
1747 // TPM_RC_SUCCESS.
1748 static TPM2B_DIGEST *
1749 ComputeRpHash(
1750 COMMAND *command, // IN: command structure
1751 TPM_ALG_ID hashAlg // IN: hash algorithm to compute rpHash
1752 )
1753 {
1754 TPM2B_DIGEST *rpHash = GetRpHashPointer(command, hashAlg);
1755 HASH_STATE hashState;
1756 //
1757 if(rpHash->t.size == 0)
1758 {
1759 // rpHash := hash(responseCode || commandCode || parameters)
1760
1761 // Initiate hash creation.
1762 rpHash->t.size = CryptHashStart(&hashState, hashAlg);
1763
1764 // Add hash constituents.
1765 CryptDigestUpdateInt(&hashState, sizeof(TPM_RC), TPM_RC_SUCCESS);
1766 CryptDigestUpdateInt(&hashState, sizeof(TPM_CC), command->code);
1767 CryptDigestUpdate(&hashState, command->parameterSize,
1768 command->parameterBuffer);
1769 // Complete hash computation.
1770 CryptHashEnd2B(&hashState, &rpHash->b);
1771 }
1772 return rpHash;
1773 }
1774
1775 //*** InitAuditSession()
1776 // This function initializes the audit data in an audit session.
1777 static void
1778 InitAuditSession(
1779 SESSION *session // session to be initialized
1780 )
1781 {
1782 // Mark session as an audit session.
1783 session->attributes.isAudit = SET;
1784
1785 // Audit session can not be bound.
1786 session->attributes.isBound = CLEAR;
1787
1788 // Size of the audit log is the size of session hash algorithm digest.
1789 session->u2.auditDigest.t.size = CryptHashGetDigestSize(session->authHashAlg);
1790
1791 // Set the original digest value to be 0.
1792 MemorySet(&session->u2.auditDigest.t.buffer,
1793 0,
1794 session->u2.auditDigest.t.size);
1795 return;
1796 }
1797
1798 //*** UpdateAuditDigest
1799 // Function to update an audit digest
1800 static void
1801 UpdateAuditDigest(
1802 COMMAND *command,
1803 TPMI_ALG_HASH hashAlg,
1804 TPM2B_DIGEST *digest
1805 )
1806 {
1807 HASH_STATE hashState;
1808 TPM2B_DIGEST *cpHash = GetCpHash(command, hashAlg);
1809 TPM2B_DIGEST *rpHash = ComputeRpHash(command, hashAlg);
1810 //
1811 pAssert(cpHash != NULL);
1812
1813 // digestNew := hash (digestOld || cpHash || rpHash)
1814 // Start hash computation.
1815 digest->t.size = CryptHashStart(&hashState, hashAlg);
1816 // Add old digest.
1817 CryptDigestUpdate2B(&hashState, &digest->b);
1818 // Add cpHash
1819 CryptDigestUpdate2B(&hashState, &cpHash->b);
1820 // Add rpHash
1821 CryptDigestUpdate2B(&hashState, &rpHash->b);
1822 // Finalize the hash.
1823 CryptHashEnd2B(&hashState, &digest->b);
1824 }
1825
1826
1827 //*** Audit()
1828 //This function updates the audit digest in an audit session.
1829 static void
1830 Audit(
1831 COMMAND *command, // IN: primary control structure
1832 SESSION *auditSession // IN: loaded audit session
1833 )
1834 {
1835 UpdateAuditDigest(command, auditSession->authHashAlg,
1836 &auditSession->u2.auditDigest);
1837 return;
1838 }
1839
1840 #ifdef TPM_CC_GetCommandAuditDigest
1841 //*** CommandAudit()
1842 // This function updates the command audit digest.
1843 static void
1844 CommandAudit(
1845 COMMAND *command // IN:
1846 )
1847 {
1848 // If the digest.size is one, it indicates the special case of changing
1849 // the audit hash algorithm. For this case, no audit is done on exit.
1850 // NOTE: When the hash algorithm is changed, g_updateNV is set in order to
1851 // force an update to the NV on exit so that the change in digest will
1852 // be recorded. So, it is safe to exit here without setting any flags
1853 // because the digest change will be written to NV when this code exits.
1854 if(gr.commandAuditDigest.t.size == 1)
1855 {
1856 gr.commandAuditDigest.t.size = 0;
1857 return;
1858 }
1859 // If the digest size is zero, need to start a new digest and increment
1860 // the audit counter.
1861 if(gr.commandAuditDigest.t.size == 0)
1862 {
1863 gr.commandAuditDigest.t.size = CryptHashGetDigestSize(gp.auditHashAlg);
1864 MemorySet(gr.commandAuditDigest.t.buffer,
1865 0,
1866 gr.commandAuditDigest.t.size);
1867
1868 // Bump the counter and save its value to NV.
1869 gp.auditCounter++;
1870 NV_SYNC_PERSISTENT(auditCounter);
1871 }
1872 UpdateAuditDigest(command, gp.auditHashAlg, &gr.commandAuditDigest);
1873 return;
1874 }
1875 #endif
1876
1877 //*** UpdateAuditSessionStatus()
1878 // Function to update the internal audit related states of a session. It
1879 // 1. initializes the session as audit session and sets it to be exclusive if this
1880 // is the first time it is used for audit or audit reset was requested;
1881 // 2. reports exclusive audit session;
1882 // 3. extends audit log; and
1883 // 4. clears exclusive audit session if no audit session found in the command.
1884 static void
1885 UpdateAuditSessionStatus(
1886 COMMAND *command // IN: primary control structure
1887 )
1888 {
1889 UINT32 i;
1890 TPM_HANDLE auditSession = TPM_RH_UNASSIGNED;
1891 //
1892 // Iterate through sessions
1893 for(i = 0; i < command->sessionNum; i++)
1894 {
1895 SESSION *session;
1896 //
1897 // PW session do not have a loaded session and can not be an audit
1898 // session either. Skip it.
1899 if(s_sessionHandles[i] == TPM_RS_PW)
1900 continue;
1901 session = SessionGet(s_sessionHandles[i]);
1902
1903 // If a session is used for audit
1904 if(IS_ATTRIBUTE(s_attributes[i], TPMA_SESSION, audit))
1905 {
1906 // An audit session has been found
1907 auditSession = s_sessionHandles[i];
1908
1909 // If the session has not been an audit session yet, or
1910 // the auditSetting bits indicate a reset, initialize it and set
1911 // it to be the exclusive session
1912 if(session->attributes.isAudit == CLEAR
1913 || IS_ATTRIBUTE(s_attributes[i], TPMA_SESSION, auditReset))
1914 {
1915 InitAuditSession(session);
1916 g_exclusiveAuditSession = auditSession;
1917 }
1918 else
1919 {
1920 // Check if the audit session is the current exclusive audit
1921 // session and, if not, clear previous exclusive audit session.
1922 if(g_exclusiveAuditSession != auditSession)
1923 g_exclusiveAuditSession = TPM_RH_UNASSIGNED;
1924 }
1925 // Report audit session exclusivity.
1926 if(g_exclusiveAuditSession == auditSession)
1927 {
1928 SET_ATTRIBUTE(s_attributes[i], TPMA_SESSION, auditExclusive);
1929 }
1930 else
1931 {
1932 CLEAR_ATTRIBUTE(s_attributes[i], TPMA_SESSION, auditExclusive);
1933 }
1934 // Extend audit log.
1935 Audit(command, session);
1936 }
1937 }
1938 // If no audit session is found in the command, and the command allows
1939 // a session then, clear the current exclusive
1940 // audit session.
1941 if(auditSession == TPM_RH_UNASSIGNED && IsSessionAllowed(command->index))
1942 {
1943 g_exclusiveAuditSession = TPM_RH_UNASSIGNED;
1944 }
1945 return;
1946 }
1947
1948 //*** ComputeResponseHMAC()
1949 // Function to compute HMAC for authorization session in a response.
1950 /*(See part 1 specification)
1951 // Function: Compute HMAC for response sessions
1952 // The sessionAuth value
1953 // authHMAC := HMACsHASH((sessionAuth | authValue),
1954 // (pHash | nonceTPM | nonceCaller | sessionAttributes))
1955 // Where:
1956 // HMACsHASH() The HMAC algorithm using the hash algorithm specified when
1957 // the session was started.
1958 //
1959 // sessionAuth A TPMB_MEDIUM computed in a protocol-dependent way, using
1960 // KDFa. In an HMAC or KDF, only sessionAuth.buffer is used.
1961 //
1962 // authValue A TPM2B_AUTH that is found in the sensitive area of an
1963 // object. In an HMAC or KDF, only authValue.buffer is used
1964 // and all trailing zeros are removed.
1965 //
1966 // pHash Response parameters (rpHash) using the session hash. When
1967 // using a pHash in an HMAC computation, both the algorithm ID
1968 // and the digest are included.
1969 //
1970 // nonceTPM A TPM2B_NONCE that is generated by the entity using the
1971 // session. In an HMAC or KDF, only nonceTPM.buffer is used.
1972 //
1973 // nonceCaller a TPM2B_NONCE that was received the previous time the
1974 // session was used. In an HMAC or KDF, only
1975 // nonceCaller.buffer is used.
1976 //
1977 // sessionAttributes A TPMA_SESSION that indicates the attributes associated
1978 // with a particular use of the session.
1979 */
1980 static void
1981 ComputeResponseHMAC(
1982 COMMAND *command, // IN: command structure
1983 UINT32 sessionIndex, // IN: session index to be processed
1984 SESSION *session, // IN: loaded session
1985 TPM2B_DIGEST *hmac // OUT: authHMAC
1986 )
1987 {
1988 TPM2B_TYPE(KEY, (sizeof(AUTH_VALUE) * 2));
1989 TPM2B_KEY key; // HMAC key
1990 BYTE marshalBuffer[sizeof(TPMA_SESSION)];
1991 BYTE *buffer;
1992 UINT32 marshalSize;
1993 HMAC_STATE hmacState;
1994 TPM2B_DIGEST *rpHash = ComputeRpHash(command, session->authHashAlg);
1995 //
1996 // Generate HMAC key
1997 MemoryCopy2B(&key.b, &session->sessionKey.b, sizeof(key.t.buffer));
1998
1999 // Add the object authValue if required
2000 if(session->attributes.includeAuth == SET)
2001 {
2002 // Note: includeAuth may be SET for a policy that is used in
2003 // UndefineSpaceSpecial(). At this point, the Index has been deleted
2004 // so the includeAuth will have no meaning. However, the
2005 // s_associatedHandles[] value for the session is now set to TPM_RH_NULL so
2006 // this will return the authValue associated with TPM_RH_NULL and that is
2007 // and empty buffer.
2008 TPM2B_AUTH authValue;
2009 //
2010 // Get the authValue with trailing zeros removed
2011 EntityGetAuthValue(s_associatedHandles[sessionIndex], &authValue);
2012
2013 // Add it to the key
2014 MemoryConcat2B(&key.b, &authValue.b, sizeof(key.t.buffer));
2015 }
2016
2017 // if the HMAC key size is 0, the response HMAC is computed according to the
2018 // input HMAC
2019 if(key.t.size == 0
2020 && s_inputAuthValues[sessionIndex].t.size == 0)
2021 {
2022 hmac->t.size = 0;
2023 return;
2024 }
2025 // Start HMAC computation.
2026 hmac->t.size = CryptHmacStart2B(&hmacState, session->authHashAlg, &key.b);
2027
2028 // Add hash components.
2029 CryptDigestUpdate2B(&hmacState.hashState, &rpHash->b);
2030 CryptDigestUpdate2B(&hmacState.hashState, &session->nonceTPM.b);
2031 CryptDigestUpdate2B(&hmacState.hashState, &s_nonceCaller[sessionIndex].b);
2032
2033 // Add session attributes.
2034 buffer = marshalBuffer;
2035 marshalSize = TPMA_SESSION_Marshal(&s_attributes[sessionIndex], &buffer, NULL);
2036 CryptDigestUpdate(&hmacState.hashState, marshalSize, marshalBuffer);
2037
2038 // Finalize HMAC.
2039 CryptHmacEnd2B(&hmacState, &hmac->b);
2040
2041 return;
2042 }
2043
2044 //*** UpdateInternalSession()
2045 // Updates internal sessions:
2046 // 1. Restarts session time.
2047 // 2. Clears a policy session since nonce is rolling.
2048 static void
2049 UpdateInternalSession(
2050 SESSION *session, // IN: the session structure
2051 UINT32 i // IN: session number
2052 )
2053 {
2054 // If nonce is rolling in a policy session, the policy related data
2055 // will be re-initialized.
2056 if(HandleGetType(s_sessionHandles[i]) == TPM_HT_POLICY_SESSION
2057 && IS_ATTRIBUTE(s_attributes[i], TPMA_SESSION, continueSession))
2058 {
2059 // When the nonce rolls it starts a new timing interval for the
2060 // policy session.
2061 SessionResetPolicyData(session);
2062 SessionSetStartTime(session);
2063 }
2064 return;
2065 }
2066
2067 //*** BuildSingleResponseAuth()
2068 // Function to compute response HMAC value for a policy or HMAC session.
2069 static TPM2B_NONCE *
2070 BuildSingleResponseAuth(
2071 COMMAND *command, // IN: command structure
2072 UINT32 sessionIndex, // IN: session index to be processed
2073 TPM2B_AUTH *auth // OUT: authHMAC
2074 )
2075 {
2076 // Fill in policy/HMAC based session response.
2077 SESSION *session = SessionGet(s_sessionHandles[sessionIndex]);
2078 //
2079 // If the session is a policy session with isPasswordNeeded SET, the
2080 // authorization field is empty.
2081 if(HandleGetType(s_sessionHandles[sessionIndex]) == TPM_HT_POLICY_SESSION
2082 && session->attributes.isPasswordNeeded == SET)
2083 auth->t.size = 0;
2084 else
2085 // Compute response HMAC.
2086 ComputeResponseHMAC(command, sessionIndex, session, auth);
2087
2088 UpdateInternalSession(session, sessionIndex);
2089 return &session->nonceTPM;
2090 }
2091
2092 //*** UpdateAllNonceTPM()
2093 // Updates TPM nonce for all sessions in command.
2094 static void
2095 UpdateAllNonceTPM(
2096 COMMAND *command // IN: controlling structure
2097 )
2098 {
2099 UINT32 i;
2100 SESSION *session;
2101 //
2102 for(i = 0; i < command->sessionNum; i++)
2103 {
2104 // If not a PW session, compute the new nonceTPM.
2105 if(s_sessionHandles[i] != TPM_RS_PW)
2106 {
2107 session = SessionGet(s_sessionHandles[i]);
2108 // Update nonceTPM in both internal session and response.
2109 CryptRandomGenerate(session->nonceTPM.t.size,
2110 session->nonceTPM.t.buffer);
2111 }
2112 }
2113 return;
2114 }
2115
2116
2117
2118 //*** BuildResponseSession()
2119 // Function to build Session buffer in a response. The authorization data is added
2120 // to the end of command->responseBuffer. The size of the authorization area is
2121 // accumulated in command->authSize.
2122 // When this is called, command->responseBuffer is pointing at the next location
2123 // in the response buffer to be filled. This is where the authorization sessions
2124 // will go, if any. command->parameterSize is the number of bytes that have been
2125 // marshaled as parameters in the output buffer.
2126 void
2127 BuildResponseSession(
2128 COMMAND *command // IN: structure that has relevant command
2129 // information
2130 )
2131 {
2132 pAssert(command->authSize == 0);
2133
2134 // Reset the parameter buffer to point to the start of the parameters so that
2135 // there is a starting point for any rpHash that might be generated and so there
2136 // is a place where parameter encryption would start
2137 command->parameterBuffer = command->responseBuffer - command->parameterSize;
2138
2139 // Session nonces should be updated before parameter encryption
2140 if(command->tag == TPM_ST_SESSIONS)
2141 {
2142 UpdateAllNonceTPM(command);
2143
2144 // Encrypt first parameter if applicable. Parameter encryption should
2145 // happen after nonce update and before any rpHash is computed.
2146 // If the encrypt session is associated with a handle, the authValue of
2147 // this handle will be concatenated with sessionKey to generate
2148 // encryption key, no matter if the handle is the session bound entity
2149 // or not. The authValue is added to sessionKey only when the authValue
2150 // is available.
2151 if(s_encryptSessionIndex != UNDEFINED_INDEX)
2152 {
2153 UINT32 size;
2154 TPM2B_AUTH extraKey;
2155 //
2156 extraKey.b.size = 0;
2157 // If this is an authorization session, include the authValue in the
2158 // generation of the encryption key
2159 if(s_associatedHandles[s_encryptSessionIndex] != TPM_RH_UNASSIGNED)
2160 {
2161 EntityGetAuthValue(s_associatedHandles[s_encryptSessionIndex],
2162 &extraKey);
2163 }
2164 size = EncryptSize(command->index);
2165 CryptParameterEncryption(s_sessionHandles[s_encryptSessionIndex],
2166 &s_nonceCaller[s_encryptSessionIndex].b,
2167 (UINT16)size,
2168 &extraKey,
2169 command->parameterBuffer);
2170 }
2171 }
2172 // Audit sessions should be processed regardless of the tag because
2173 // a command with no session may cause a change of the exclusivity state.
2174 UpdateAuditSessionStatus(command);
2175 #if CC_GetCommandAuditDigest
2176 // Command Audit
2177 if(CommandAuditIsRequired(command->index))
2178 CommandAudit(command);
2179 #endif
2180 // Process command with sessions.
2181 if(command->tag == TPM_ST_SESSIONS)
2182 {
2183 UINT32 i;
2184 //
2185 pAssert(command->sessionNum > 0);
2186
2187 // Iterate over each session in the command session area, and create
2188 // corresponding sessions for response.
2189 for(i = 0; i < command->sessionNum; i++)
2190 {
2191 TPM2B_NONCE *nonceTPM;
2192 TPM2B_DIGEST responseAuth;
2193 // Make sure that continueSession is SET on any Password session.
2194 // This makes it marginally easier for the management software
2195 // to keep track of the closed sessions.
2196 if(s_sessionHandles[i] == TPM_RS_PW)
2197 {
2198 SET_ATTRIBUTE(s_attributes[i], TPMA_SESSION, continueSession);
2199 responseAuth.t.size = 0;
2200 nonceTPM = (TPM2B_NONCE *)&responseAuth;
2201 }
2202 else
2203 {
2204 // Compute the response HMAC and get a pointer to the nonce used.
2205 // This function will also update the values if needed. Note, the
2206 nonceTPM = BuildSingleResponseAuth(command, i, &responseAuth);
2207 }
2208 command->authSize += TPM2B_NONCE_Marshal(nonceTPM,
2209 &command->responseBuffer,
2210 NULL);
2211 command->authSize += TPMA_SESSION_Marshal(&s_attributes[i],
2212 &command->responseBuffer,
2213 NULL);
2214 command->authSize += TPM2B_DIGEST_Marshal(&responseAuth,
2215 &command->responseBuffer,
2216 NULL);
2217 if(!IS_ATTRIBUTE(s_attributes[i], TPMA_SESSION, continueSession))
2218 SessionFlush(s_sessionHandles[i]);
2219 }
2220 }
2221 return;
2222 }
2223
2224 //*** SessionRemoveAssociationToHandle()
2225 // This function deals with the case where an entity associated with an authorization
2226 // is deleted during command processing. The primary use of this is to support
2227 // UndefineSpaceSpecial().
2228 void
2229 SessionRemoveAssociationToHandle(
2230 TPM_HANDLE handle
2231 )
2232 {
2233 UINT32 i;
2234 //
2235 for(i = 0; i < MAX_SESSION_NUM; i++)
2236 {
2237 if(s_associatedHandles[i] == handle)
2238 {
2239 s_associatedHandles[i] = TPM_RH_NULL;
2240 }
2241 }
2242 }