• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

stefanberger / libtpms / #2014

04 Aug 2025 07:21PM UTC coverage: 76.783% (-0.4%) from 77.225%
#2014

push

travis-ci

web-flow
Merge 24cf223e7 into 925b06ee4

33895 of 44144 relevant lines covered (76.78%)

93978.17 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

91.65
/src/tpm2/SessionProcess.c
1
/********************************************************************************/
2
/*                                                                                */
3
/*                Process the Authorization Sessions                                     */
4
/*                             Written by Ken Goldman                                */
5
/*                       IBM Thomas J. Watson Research Center                        */
6
/*                                                                                */
7
/*  Licenses and Notices                                                        */
8
/*                                                                                */
9
/*  1. Copyright Licenses:                                                        */
10
/*                                                                                */
11
/*  - Trusted Computing Group (TCG) grants to the user of the source code in        */
12
/*    this specification (the "Source Code") a worldwide, irrevocable,                 */
13
/*    nonexclusive, royalty free, copyright license to reproduce, create         */
14
/*    derivative works, distribute, display and perform the Source Code and        */
15
/*    derivative works thereof, and to grant others the rights granted herein.        */
16
/*                                                                                */
17
/*  - The TCG grants to the user of the other parts of the specification         */
18
/*    (other than the Source Code) the rights to reproduce, distribute,         */
19
/*    display, and perform the specification solely for the purpose of                 */
20
/*    developing products based on such documents.                                */
21
/*                                                                                */
22
/*  2. Source Code Distribution Conditions:                                        */
23
/*                                                                                */
24
/*  - Redistributions of Source Code must retain the above copyright licenses,         */
25
/*    this list of conditions and the following disclaimers.                        */
26
/*                                                                                */
27
/*  - Redistributions in binary form must reproduce the above copyright         */
28
/*    licenses, this list of conditions        and the following disclaimers in the         */
29
/*    documentation and/or other materials provided with the distribution.        */
30
/*                                                                                */
31
/*  3. Disclaimers:                                                                */
32
/*                                                                                */
33
/*  - THE COPYRIGHT LICENSES SET FORTH ABOVE DO NOT REPRESENT ANY FORM OF        */
34
/*  LICENSE OR WAIVER, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, WITH        */
35
/*  RESPECT TO PATENT RIGHTS HELD BY TCG MEMBERS (OR OTHER THIRD PARTIES)        */
36
/*  THAT MAY BE NECESSARY TO IMPLEMENT THIS SPECIFICATION OR OTHERWISE.                */
37
/*  Contact TCG Administration (admin@trustedcomputinggroup.org) for                 */
38
/*  information on specification licensing rights available through TCG         */
39
/*  membership agreements.                                                        */
40
/*                                                                                */
41
/*  - THIS SPECIFICATION IS PROVIDED "AS IS" WITH NO EXPRESS OR IMPLIED         */
42
/*    WARRANTIES WHATSOEVER, INCLUDING ANY WARRANTY OF MERCHANTABILITY OR         */
43
/*    FITNESS FOR A PARTICULAR PURPOSE, ACCURACY, COMPLETENESS, OR                 */
44
/*    NONINFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS, OR ANY WARRANTY                 */
45
/*    OTHERWISE ARISING OUT OF ANY PROPOSAL, SPECIFICATION OR SAMPLE.                */
46
/*                                                                                */
47
/*  - Without limitation, TCG and its members and licensors disclaim all         */
48
/*    liability, including liability for infringement of any proprietary         */
49
/*    rights, relating to use of information in this specification and to the        */
50
/*    implementation of this specification, and TCG disclaims all liability for        */
51
/*    cost of procurement of substitute goods or services, lost profits, loss         */
52
/*    of use, loss of data or any incidental, consequential, direct, indirect,         */
53
/*    or special damages, whether under contract, tort, warranty or otherwise,         */
54
/*    arising in any way out of use or reliance upon this specification or any         */
55
/*    information herein.                                                        */
56
/*                                                                                */
57
/*  (c) Copyright IBM Corp. and others, 2016 - 2023                                */
58
/*                                                                                */
59
/********************************************************************************/
60

61
/* 6.4 SessionProcess.c */
62
/* 6.4.1 Introduction */
63
/* This file contains the subsystem that process the authorization sessions including implementation
64
   of the Dictionary Attack logic. ExecCommand() uses ParseSessionBuffer() to process the
65
   authorization session area of a command and BuildResponseSession() to create the authorization
66
   session area of a response */
67
#define SESSION_PROCESS_C
68
#include "Tpm.h"
69
#include "ACT.h"
70
/* 6.4.3.1 IsDAExempted() */
71
/* This function indicates if a handle is exempted from DA logic. A handle is exempted if it is */
72
/* a) a primary seed handle, */
73
/* b) an object with noDA bit SET, */
74
/* c) an NV Index with TPMA_NV_NO_DA bit SET, or */
75
/* d)        a PCR handle. */
76
BOOL
77
IsDAExempted(
6,289✔
78
             TPM_HANDLE       handle         // IN: entity handle
79
             )
80
{
81
    BOOL        result = FALSE;
6,289✔
82
    //
83
    switch(HandleGetType(handle))
6,289✔
84
        {
85
          case TPM_HT_PERMANENT:
3,560✔
86
            // All permanent handles, other than TPM_RH_LOCKOUT, are exempt from
87
            // DA protection.
88
            result = (handle != TPM_RH_LOCKOUT);
3,560✔
89
            break;
3,560✔
90
            // When this function is called, a persistent object will have been loaded
91
            // into an object slot and assigned a transient handle.
92
          case TPM_HT_TRANSIENT:
1,861✔
93
              {
94
                  TPMA_OBJECT     attributes = ObjectGetPublicAttributes(handle);
1,861✔
95
                  result = IS_ATTRIBUTE(attributes, TPMA_OBJECT, noDA);
1,861✔
96
                  break;
1,861✔
97
              }
98
          case TPM_HT_NV_INDEX:
580✔
99
              {
100
                  NV_INDEX            *nvIndex = NvGetIndexInfo(handle, NULL);
580✔
101
                  result = IS_ATTRIBUTE(nvIndex->publicArea.attributes, TPMA_NV, NO_DA);
580✔
102
                  break;
580✔
103
              }
104
          case TPM_HT_PCR:
288✔
105
            // PCRs are always exempted from DA.
106
            result = TRUE;
288✔
107
            break;
288✔
108
          default:
109
            break;
110
        }
111
    return result;
6,289✔
112
}
113
/* 6.4.3.2 IncrementLockout() */
114
/* This function is called after an authorization failure that involves use of an authValue. If the
115
   entity referenced by the handle is not exempt from DA protection, then the failedTries counter
116
   will be incremented. */
117
static TPM_RC
118
IncrementLockout(
88✔
119
                 UINT32           sessionIndex
120
                 )
121
{
122
    TPM_HANDLE       handle = s_associatedHandles[sessionIndex];
88✔
123
    TPM_HANDLE       sessionHandle = s_sessionHandles[sessionIndex];
88✔
124
    SESSION         *session = NULL;
88✔
125
    //
126
    // Don't increment lockout unless the handle associated with the session
127
    // is DA protected or the session is bound to a DA protected entity.
128
    if(sessionHandle == TPM_RS_PW)
88✔
129
        {
130
            if(IsDAExempted(handle))
77✔
131
                return TPM_RC_BAD_AUTH;
132
        }
133
    else
134
        {
135
            session = SessionGet(sessionHandle);
11✔
136
            // If the session is bound to lockout, then use that as the relevant
137
            // handle. This means that an authorization failure with a bound session
138
            // bound to lockoutAuth will take precedence over any other
139
            // lockout check
140
            if(session->attributes.isLockoutBound == SET)
11✔
141
                handle = TPM_RH_LOCKOUT;
×
142
            if(session->attributes.isDaBound == CLEAR
11✔
143
               && (IsDAExempted(handle) || session->attributes.includeAuth == CLEAR))
11✔
144
                // If the handle was changed to TPM_RH_LOCKOUT, this will not return
145
                // TPM_RC_BAD_AUTH
146
                return TPM_RC_BAD_AUTH;
147
        }
148
    if(handle == TPM_RH_LOCKOUT)
19✔
149
        {
150
            pAssert(gp.lockOutAuthEnabled == TRUE);
4✔
151
            // lockout is no longer enabled
152
            gp.lockOutAuthEnabled = FALSE;
4✔
153
            // For TPM_RH_LOCKOUT, if lockoutRecovery is 0, no need to update NV since
154
            // the lockout authorization will be reset at startup.
155
            if(gp.lockoutRecovery != 0)
4✔
156
                {
157
                    if(NV_IS_AVAILABLE)
4✔
158
                        // Update NV.
159
                        NV_SYNC_PERSISTENT(lockOutAuthEnabled);
4✔
160
                    else
161
                        // No NV access for now. Put the TPM in pending mode.
162
                        s_DAPendingOnNV = TRUE;
×
163
                }
164
        }
165
    else
166
        {
167
            if(gp.recoveryTime != 0)
15✔
168
                {
169
                    gp.failedTries++;
15✔
170
                    if(NV_IS_AVAILABLE)
15✔
171
                        // Record changes to NV. NvWrite will SET g_updateNV
172
                        NV_SYNC_PERSISTENT(failedTries);
15✔
173
                    else
174
                        // No NV access for now.  Put the TPM in pending mode.
175
                        s_DAPendingOnNV = TRUE;
×
176
                }
177
        }
178
    // Register a DA failure and reset the timers.
179
    DARegisterFailure(handle);
19✔
180
    return TPM_RC_AUTH_FAIL;
19✔
181
}
182
/* 6.4.3.3 IsSessionBindEntity() */
183
/* This function indicates if the entity associated with the handle is the entity, to which this
184
   session is bound. The binding would occur by making the bind parameter in TPM2_StartAuthSession()
185
   not equal to TPM_RH_NULL. The binding only occurs if the session is an HMAC session. The bind
186
   value is a combination of the Name and the authValue of the entity. */
187
static BOOL
188
IsSessionBindEntity(
758✔
189
                    TPM_HANDLE       associatedHandle,  // IN: handle to be authorized
190
                    SESSION         *session            // IN: associated session
191
                    )
192
{
193
    TPM2B_NAME     entity;             // The bind value for the entity
758✔
194
    // If the session is not bound, return FALSE.
195
    if(session->attributes.isBound)
758✔
196
        {
197
            // Compute the bind value for the entity.
198
            SessionComputeBoundEntity(associatedHandle, &entity);
60✔
199
            // Compare to the bind value in the session.
200
            return MemoryEqual2B(&entity.b, &session->u1.boundEntity.b);
60✔
201
        }
202
    return FALSE;
203
}
204
/* 6.4.3.4 IsPolicySessionRequired() */
205
/* Checks if a policy session is required for a command. If a command requires DUP or ADMIN role
206
   authorization, then the handle that requires that role is the first handle in the command. This
207
   simplifies this checking. If a new command is created that requires multiple ADMIN role
208
   authorizations, then it will have to be special-cased in this function. A policy session is
209
   required if: */
210
/* a) the command requires the DUP role, */
211
/* b) the command requires the ADMIN role and the authorized entity is an object and its
212
   adminWithPolicy bit is SET, or */
213
/* c) the command requires the ADMIN role and the authorized entity is a permanent handle or an NV
214
   Index. */
215
/* d) The authorized entity is a PCR belonging to a policy group, and has its policy initialized */
216
/* Return Values Meaning */
217
/* TRUE policy session is required */
218
/* FALSE policy session is not required */
219
static BOOL
220
IsPolicySessionRequired(
6,153✔
221
                        COMMAND_INDEX    commandIndex,  // IN: command index
222
                        UINT32           sessionIndex   // IN: session index
223
                        )
224
{
225
    AUTH_ROLE       role = CommandAuthRole(commandIndex, sessionIndex);
6,153✔
226
    TPM_HT          type = HandleGetType(s_associatedHandles[sessionIndex]);
6,153✔
227
    if(role == AUTH_DUP)
6,153✔
228
        return TRUE;
229
    if(role == AUTH_ADMIN)
6,153✔
230
        {
231
            // We allow an exception for ADMIN role in a transient object. If the object
232
            // allows ADMIN role actions with authorization, then policy is not
233
            // required. For all other cases, there is no way to override the command
234
            // requirement that a policy be used
235
            if(type == TPM_HT_TRANSIENT)
250✔
236
                {
237
                    OBJECT      *object = HandleToObject(s_associatedHandles[sessionIndex]);
237✔
238
                    if(!IS_ATTRIBUTE(object->publicArea.objectAttributes, TPMA_OBJECT,
237✔
239
                                     adminWithPolicy))
240
                        return FALSE;
241
                }
242
            return TRUE;
13✔
243
        }
244
    if(type == TPM_HT_PCR)
5,903✔
245
        {
246
            if(PCRPolicyIsAvailable(s_associatedHandles[sessionIndex]))
276✔
247
                {
248
                    TPM2B_DIGEST        policy;
8✔
249
                    TPMI_ALG_HASH       policyAlg;
8✔
250
                    policyAlg = PCRGetAuthPolicy(s_associatedHandles[sessionIndex],
8✔
251
                                                 &policy);
252
                    if(policyAlg != TPM_ALG_NULL)
8✔
253
                        return TRUE;
×
254
                }
255
        }
256
    return FALSE;
257
}
258
/* 6.4.3.5 IsAuthValueAvailable() */
259
/* This function indicates if authValue is available and allowed for USER role authorization of an
260
   entity. */
261
/* This function is similar to IsAuthPolicyAvailable() except that it does not check the size of the
262
   authValue as IsAuthPolicyAvailable() does (a null authValue is a valid authorization, but a null
263
   policy is not a valid policy). */
264
/* This function does not check that the handle reference is valid or if the entity is in an
265
   enabled hierarchy. Those checks are assumed to have been performed during the handle
266
   unmarshaling. */
267
static BOOL
268
IsAuthValueAvailable(
6,116✔
269
                     TPM_HANDLE       handle,        // IN: handle of entity
270
                     COMMAND_INDEX    commandIndex,  // IN: command index
271
                     UINT32           sessionIndex   // IN: session index
272
                     )
273
{
274
    BOOL             result = FALSE;
6,116✔
275
    //
276
    switch(HandleGetType(handle))
6,116✔
277
        {
278
          case TPM_HT_PERMANENT:
3,487✔
279
            switch(handle)
3,487✔
280
                {
281
                    // At this point hierarchy availability has already been
282
                    // checked so primary seed handles are always available here
283
                  case TPM_RH_OWNER:
3,487✔
284
                  case TPM_RH_ENDORSEMENT:
285
                  case TPM_RH_PLATFORM:
286
#ifdef VENDOR_PERMANENT
287
                    // This vendor defined handle associated with the
288
                    // manufacturer's shared secret
289
                  case VENDOR_PERMANENT:
290
#endif
291
                    // The DA checking has been performed on LockoutAuth but we
292
                    // bypass the DA logic if we are using lockout policy. The
293
                    // policy would allow execution to continue an lockoutAuth
294
                    // could be used, even if direct use of lockoutAuth is disabled
295
                  case TPM_RH_LOCKOUT:
296
                    // NullAuth is always available.
297
                  case TPM_RH_NULL:
298
                    result = TRUE;
3,487✔
299
                    break;
3,487✔
300
#ifndef __ACT_DISABLED        // libtpms added begin
301
                    FOR_EACH_ACT(CASE_ACT_HANDLE)
302
                        {
303
                            // The ACT auth value is not available if the platform is disabled
304
                            result = g_phEnable == SET;
305
                            break;
306
                        }
307
#endif                        // libtpms added end
308
                  default:
309
                    // Otherwise authValue is not available.
310
                    break;
311
                }
312
            break;
313
          case TPM_HT_TRANSIENT:
1,850✔
314
            // A persistent object has already been loaded and the internal
315
            // handle changed.
316
              {
317
                  OBJECT          *object;
1,850✔
318
                  TPMA_OBJECT      attributes;
1,850✔
319
                  //
320
                  object = HandleToObject(handle);
1,850✔
321
                  attributes = object->publicArea.objectAttributes;
1,850✔
322
                  // authValue is always available for a sequence object.
323
                  // An alternative for this is to
324
                  // SET_ATTRIBUTE(object->publicArea, TPMA_OBJECT, userWithAuth) when the
325
                  // sequence is started.
326
                  if(ObjectIsSequence(object))
1,850✔
327
                      {
328
                          result = TRUE;
329
                          break;
330
                      }
331
                  // authValue is available for an object if it has its sensitive
332
                  // portion loaded and
333
                  //  1. userWithAuth bit is SET, or
334
                  //  2. ADMIN role is required
335
                  if(object->attributes.publicOnly == CLEAR
1,741✔
336
                     && (IS_ATTRIBUTE(attributes, TPMA_OBJECT, userWithAuth)
1,741✔
337
                         || (CommandAuthRole(commandIndex, sessionIndex) == AUTH_ADMIN
4✔
338
                             && !IS_ATTRIBUTE(attributes, TPMA_OBJECT, adminWithPolicy))))
×
339
                      result = TRUE;
340
              }
341
              break;
342
          case TPM_HT_NV_INDEX:
503✔
343
            // NV Index.
344
              {
345
                  NV_REF           locator;
503✔
346
                  NV_INDEX        *nvIndex = NvGetIndexInfo(handle, &locator);
503✔
347
                  TPMA_NV          nvAttributes;
503✔
348
                  //
349
                  pAssert(nvIndex != 0);
503✔
350
                  nvAttributes = nvIndex->publicArea.attributes;
503✔
351
                  if(IsWriteOperation(commandIndex))
503✔
352
                      {
353
                          // AuthWrite can't be set for a PIN index
354
                          if(IS_ATTRIBUTE(nvAttributes, TPMA_NV, AUTHWRITE))
221✔
355
                              result = TRUE;
217✔
356
                      }
357
                  else
358
                      {
359
                          // A "read" operation
360
                          // For a PIN Index, the authValue is available as long as the
361
                          // Index has been written and the pinCount is less than pinLimit
362
                          if(IsNvPinFailIndex(nvAttributes)
282✔
363
                             || IsNvPinPassIndex(nvAttributes))
282✔
364
                              {
365
                                  NV_PIN          pin;
32✔
366
                                  if(!IS_ATTRIBUTE(nvAttributes, TPMA_NV, WRITTEN))
32✔
367
                                      break; // return false
368
                                  // get the index values
369
                                  pin.intVal = NvGetUINT64Data(nvIndex, locator);
31✔
370
                                  if(pin.pin.pinCount < pin.pin.pinLimit)
31✔
371
                                      result = TRUE;
21✔
372
                              }
373
                          // For non-PIN Indexes, need to allow use of the authValue
374
                          else if(IS_ATTRIBUTE(nvAttributes, TPMA_NV, AUTHREAD))
250✔
375
                              result = TRUE;
246✔
376
                      }
377
              }
378
              break;
502✔
379
          case TPM_HT_PCR:
276✔
380
            // PCR handle.
381
            // authValue is always allowed for PCR
382
            result = TRUE;
276✔
383
            break;
276✔
384
          default:
385
            // Otherwise, authValue is not available
386
            break;
387
        }
388
    return result;
6,116✔
389
}
390

391
/* 6.4.3.6        IsAuthPolicyAvailable() */
392
/* This function indicates if an authPolicy is available and allowed. */
393
/* This function does not check that the handle reference is valid or if the entity is in an enabled
394
   hierarchy. Those checks are assumed to have been performed during the handle unmarshaling. */
395
/* Return Values Meaning */
396
/* TRUE authPolicy is available */
397
/* FALSE authPolicy is not available */
398
static BOOL
399
IsAuthPolicyAvailable(
204✔
400
                      TPM_HANDLE       handle,        // IN: handle of entity
401
                      COMMAND_INDEX    commandIndex,  // IN: command index
402
                      UINT32           sessionIndex   // IN: session index
403
                      )
404
{
405
    BOOL            result = FALSE;
204✔
406
    //
407
    switch(HandleGetType(handle))
204✔
408
        {
409
          case TPM_HT_PERMANENT:
7✔
410
            switch(handle)
7✔
411
                {
412
                    // At this point hierarchy availability has already been checked.
413
                  case TPM_RH_OWNER:
×
414
                    if(gp.ownerPolicy.t.size != 0)
×
415
                        result = TRUE;
×
416
                    break;
417
                  case TPM_RH_ENDORSEMENT:
×
418
                    if(gp.endorsementPolicy.t.size != 0)
×
419
                        result = TRUE;
×
420
                    break;
421
                  case TPM_RH_PLATFORM:
7✔
422
                    if(gc.platformPolicy.t.size != 0)
7✔
423
                        result = TRUE;
7✔
424
                    break;
425
#define ACT_GET_POLICY(N)                                                \
426
                    case TPM_RH_ACT_##N:                                \
427
                      if(go.ACT_##N.authPolicy.t.size != 0)                \
428
                          result = TRUE;                                \
429
                      break;
430
                    
431
                    FOR_EACH_ACT(ACT_GET_POLICY)
432
                        
433
                  case TPM_RH_LOCKOUT:
×
434
                    if(gp.lockoutPolicy.t.size != 0)
×
435
                        result = TRUE;
×
436
                    break;
437
                  default:
438
                    break;
439
                }
440
            break;
441
          case TPM_HT_TRANSIENT:
162✔
442
              {
443
                  // Object handle.
444
                  // An evict object would already have been loaded and given a
445
                  // transient object handle by this point.
446
                  OBJECT  *object = HandleToObject(handle);
162✔
447
                  // Policy authorization is not available for an object with only
448
                  // public portion loaded.
449
                  if(object->attributes.publicOnly == CLEAR)
162✔
450
                      {
451
                          // Policy authorization is always available for an object but
452
                          // is never available for a sequence.
453
                          if(!ObjectIsSequence(object))
162✔
454
                              result = TRUE;
162✔
455
                      }
456
                  break;
457
              }
458
          case TPM_HT_NV_INDEX:
35✔
459
            // An NV Index.
460
              {
461
                  NV_INDEX         *nvIndex = NvGetIndexInfo(handle, NULL);
35✔
462
                  TPMA_NV           nvAttributes = nvIndex->publicArea.attributes;
35✔
463
                  //
464
                  // If the policy size is not zero, check if policy can be used.
465
                  if(nvIndex->publicArea.authPolicy.t.size != 0)
35✔
466
                      {
467
                          // If policy session is required for this handle, always
468
                          // uses policy regardless of the attributes bit setting
469
                          if(IsPolicySessionRequired(commandIndex, sessionIndex))
35✔
470
                              result = TRUE;
471
                          // Otherwise, the presence of the policy depends on the NV
472
                          // attributes.
473
                          else if(IsWriteOperation(commandIndex))
24✔
474
                              {
475
                                  if(IS_ATTRIBUTE(nvAttributes, TPMA_NV, POLICYWRITE))
16✔
476
                                      result = TRUE;
16✔
477
                              }
478
                          else
479
                              {
480
                                  if(IS_ATTRIBUTE(nvAttributes, TPMA_NV, POLICYREAD))
8✔
481
                                      result = TRUE;
8✔
482
                              }
483
                      }
484
              }
485
              break;
486
          case TPM_HT_PCR:
×
487
            // PCR handle.
488
            if(PCRPolicyIsAvailable(handle))
×
489
                result = TRUE;
×
490
            break;
491
          default:
492
            break;
493
        }
494
    return result;
204✔
495
}
496
/* 6.4.4 Session Parsing Functions */
497
/* 6.4.4.1 ClearCpRpHashes() */
498

499
void
500
ClearCpRpHashes(
16,165✔
501
                COMMAND         *command
502
                )
503
{
504
    // The macros expand according to the implemented hash algorithms. An IDE may
505
    // complain that COMMAND does not contain SHA1CpHash or SHA1RpHash because of the
506
    // complexity of the macro expansion where the data space is defined; but, if SHA1
507
    // is implemented, it actually does  and the compiler is happy.
508
#define CLEAR_CP_HASH(HASH, Hash)     command->Hash##CpHash.b.size = 0;
509
    FOR_EACH_HASH(CLEAR_CP_HASH)
16,165✔
510
#define CLEAR_RP_HASH(HASH, Hash)     command->Hash##RpHash.b.size = 0;
511
        FOR_EACH_HASH(CLEAR_RP_HASH)
16,165✔
512
}
16,165✔
513

514
/* 6.4.4.2 GetCpHashPointer() */
515
/* Function to get a pointer to the cpHash of the command */
516
static TPM2B_DIGEST *
517
GetCpHashPointer(
1,043✔
518
                 COMMAND         *command,
519
                 TPMI_ALG_HASH    hashAlg
520
                 )
521
{
522
    TPM2B_DIGEST     *retVal;
1,043✔
523
    //
524
    // Define the macro that will expand for each implemented algorithm in the switch
525
    // statement below.
526
#define GET_CP_HASH_POINTER(HASH, Hash)                                        \
527
    case ALG_##HASH##_VALUE:                                                \
528
      retVal = (TPM2B_DIGEST *)&command->Hash##CpHash;                        \
529
      break;
530

531
    switch(hashAlg)
1,043✔
532
        {
533
            // For each implemented hash, this will expand as defined above
534
            // by GET_CP_HASH_POINTER. Your IDE may complain that
535
            // 'struct "COMMAND" has no field "SHA1CpHash"' but the compiler says
536
            // it does, so...
537
            FOR_EACH_HASH(GET_CP_HASH_POINTER)
1,043✔
538
          default:
539
            retVal = NULL;
540
            break;
541
        }
542
    return retVal;
1,043✔
543
}
544

545
/* 6.4.4.3 GetRpHashPointer() */
546
/* Function to get a pointer to the RpHash() of the command */
547
static TPM2B_DIGEST *
548
GetRpHashPointer(
1,011✔
549
                 COMMAND         *command,
550
                 TPMI_ALG_HASH    hashAlg
551
                 )
552
{
553
    TPM2B_DIGEST    *retVal;
1,011✔
554
    //
555
    // Define the macro that will expand for each implemented algorithm in the switch
556
    // statement below.
557
#define GET_RP_HASH_POINTER(HASH, Hash)                                        \
558
    case ALG_##HASH##_VALUE:                                                \
559
      retVal = (TPM2B_DIGEST *)&command->Hash##RpHash;                        \
560
      break;
561

562
    switch(hashAlg)
1,011✔
563
        {
564
            // For each implemented hash, this will expand as defined above
565
            // by GET_RP_HASH_POINTER. Your IDE may complain that
566
            // 'struct "COMMAND" has no field 'SHA1RpHash'" but the compiler says
567
            // it does, so...
568
            FOR_EACH_HASH(GET_RP_HASH_POINTER)
1,011✔
569
          default:
570
            retVal = NULL;
571
            break;
572
        }
573
    return retVal;
1,011✔
574
}
575

576
/* 6.4.4.4 ComputeCpHash() */
577
/* This function computes the cpHash as defined in Part 2 and described in Part 1. */
578
static TPM2B_DIGEST *
579
ComputeCpHash(
991✔
580
              COMMAND         *command,       // IN: command parsing structure
581
              TPMI_ALG_HASH    hashAlg        // IN: hash algorithm
582
              )
583
{
584
    UINT32               i;
991✔
585
    HASH_STATE           hashState;
991✔
586
    TPM2B_NAME           name;
991✔
587
    TPM2B_DIGEST        *cpHash;
991✔
588
    // cpHash = hash(commandCode [ || authName1
589
    //                           [ || authName2
590
    //                           [ || authName 3 ]]]
591
    //                           [ || parameters])
592
    // A cpHash can contain just a commandCode only if the lone session is
593
    // an audit session.
594
    // Get pointer to the hash value
595
    cpHash = GetCpHashPointer(command, hashAlg);
991✔
596
    if(cpHash->t.size == 0)
991✔
597
        {
598
            cpHash->t.size = CryptHashStart(&hashState, hashAlg);
714✔
599
            //  Add commandCode.
600
            CryptDigestUpdateInt(&hashState, sizeof(TPM_CC), command->code);
714✔
601
            //  Add authNames for each of the handles.
602
            for(i = 0; i < command->handleNum; i++)
2,517✔
603
                CryptDigestUpdate2B(&hashState, &EntityGetName(command->handles[i],
1,089✔
604
                                                               &name)->b);
605
            //  Add the parameters.
606
            CryptDigestUpdate(&hashState, command->parameterSize,
714✔
607
                              command->parameterBuffer);
714✔
608
            //  Complete the hash.
609
            CryptHashEnd2B(&hashState, &cpHash->b);
714✔
610
        }
611
    return cpHash;
991✔
612
}
613
/* 6.4.4.5 GetCpHash() */
614
/* This function is used to access a precomputed cpHash. */
615
static TPM2B_DIGEST *
616
GetCpHash(
52✔
617
          COMMAND         *command,
618
          TPMI_ALG_HASH    hashAlg
619
          )
620
{
621
    TPM2B_DIGEST        *cpHash = GetCpHashPointer(command, hashAlg);
52✔
622
    //
623
    pAssert(cpHash->t.size != 0);
52✔
624
    return cpHash;
52✔
625
}
626
/* 6.4.4.6 CompareTemplateHash() */
627
/* This function computes the template hash and compares it to the session templateHash. It is the
628
   hash of the second parameter assuming that the command is TPM2_Create(), TPM2_CreatePrimary(), or
629
   TPM2_CreateLoaded() */
630
static BOOL
631
CompareTemplateHash(
3✔
632
                    COMMAND         *command,       // IN: parsing structure
633
                    SESSION         *session        // IN: session data
634
                    )
635
{
636
    BYTE                *pBuffer = command->parameterBuffer;
3✔
637
    INT32                pSize = command->parameterSize;
3✔
638
    TPM2B_DIGEST         tHash;
3✔
639
    UINT16               size;
3✔
640
    //
641
    // Only try this for the three commands for which it is intended
642
    if(command->code != TPM_CC_Create
3✔
643
       && command->code != TPM_CC_CreatePrimary
3✔
644
#if CC_CreateLoaded
645
       && command->code != TPM_CC_CreateLoaded
1✔
646
#endif
647
       )
648
        return FALSE;
649
    // Assume that the first parameter is a TPM2B and unmarshal the size field
650
    // Note: this will not affect the parameter buffer and size in the calling
651
    // function.
652
    if(UINT16_Unmarshal(&size, &pBuffer, &pSize) != TPM_RC_SUCCESS)
3✔
653
        return FALSE;
654
    // reduce the space in the buffer.
655
    // NOTE: this could make pSize go negative if the parameters are not correct but
656
    // the unmarshaling code does not try to unmarshal if the remaining size is
657
    // negative.
658
    pSize -= size;
3✔
659
    // Advance the pointer
660
    pBuffer += size;
3✔
661
    // Get the size of what should be the template
662
    if(UINT16_Unmarshal(&size, &pBuffer, &pSize) != TPM_RC_SUCCESS)
3✔
663
        return FALSE;
664
    // See if this is reasonable
665
    if(size > pSize)
3✔
666
        return FALSE;
667
    // Hash the template data
668
    tHash.t.size = CryptHashBlock(session->authHashAlg, size, pBuffer,
3✔
669
                                  sizeof(tHash.t.buffer), tHash.t.buffer);
670
    return(MemoryEqual2B(&session->u1.templateHash.b, &tHash.b));
3✔
671
}
672
/* 6.4.4.7 CompareNameHash() */
673
/* This function computes the name hash and compares it to the nameHash in the session data. */
674
BOOL
675
CompareNameHash(
3✔
676
                COMMAND         *command,       // IN: main parsing structure
677
                SESSION         *session        // IN: session structure with nameHash
678
                )
679
{
680
    HASH_STATE           hashState;
3✔
681
    TPM2B_DIGEST         nameHash;
3✔
682
    UINT32               i;
3✔
683
    TPM2B_NAME           name;
3✔
684
    //
685
    nameHash.t.size = CryptHashStart(&hashState, session->authHashAlg);
3✔
686
    //  Add names.
687
    for(i = 0; i < command->handleNum; i++)
8✔
688
        CryptDigestUpdate2B(&hashState, &EntityGetName(command->handles[i],
5✔
689
                                                       &name)->b);
690
    //  Complete hash.
691
    CryptHashEnd2B(&hashState, &nameHash.b);
3✔
692
    // and compare
693
    return MemoryEqual(session->u1.nameHash.t.buffer, nameHash.t.buffer,
6✔
694
                       nameHash.t.size);
3✔
695
}
696
/* 6.4.4.8 CheckPWAuthSession() */
697
/* This function validates the authorization provided in a PWAP session. It compares the input value
698
   to authValue of the authorized entity. Argument sessionIndex is used to get handles handle of the
699
   referenced entities from s_inputAuthValues[] and s_associatedHandles[]. */
700
/* Error Returns Meaning */
701
/* TPM_RC_AUTH_FAIL authorization fails and increments DA failure count */
702
/* TPM_RC_BAD_AUTH authorization fails but DA does not apply */
703
static TPM_RC
704
CheckPWAuthSession(
5,345✔
705
                   UINT32           sessionIndex   // IN: index of session to be processed
706
                   )
707
{
708
    TPM2B_AUTH      authValue;
5,345✔
709
    TPM_HANDLE      associatedHandle = s_associatedHandles[sessionIndex];
5,345✔
710
    // Strip trailing zeros from the password.
711
    MemoryRemoveTrailingZeros(&s_inputAuthValues[sessionIndex]);
5,345✔
712
    // Get the authValue with trailing zeros removed
713
    EntityGetAuthValue(associatedHandle, &authValue);
5,345✔
714
    // Success if the values are identical.
715
    if(MemoryEqual2B(&s_inputAuthValues[sessionIndex].b, &authValue.b))
5,345✔
716
        {
717
            return TPM_RC_SUCCESS;
718
        }
719
    else                    // if the digests are not identical
720
        {
721
            // Invoke DA protection if applicable.
722
            return IncrementLockout(sessionIndex);
78✔
723
        }
724
}
725
/* 6.4.4.9 ComputeCommandHMAC() */
726
/* This function computes the HMAC for an authorization session in a command. */
727
static TPM2B_DIGEST *
728
ComputeCommandHMAC(
1,011✔
729
                   COMMAND         *command,       // IN: primary control structure
730
                   UINT32           sessionIndex,  // IN: index of session to be processed
731
                   TPM2B_DIGEST    *hmac           // OUT: authorization HMAC
732
                   )
733
{
734
    TPM2B_TYPE(KEY, (sizeof(AUTH_VALUE) * 2));
1,011✔
735
    TPM2B_KEY        key;
1,011✔
736
    BYTE             marshalBuffer[sizeof(TPMA_SESSION)];
1,011✔
737
    BYTE            *buffer;
1,011✔
738
    UINT32           marshalSize;
1,011✔
739
    HMAC_STATE       hmacState;
1,011✔
740
    TPM2B_NONCE     *nonceDecrypt;
1,011✔
741
    TPM2B_NONCE     *nonceEncrypt;
1,011✔
742
    SESSION         *session;
1,011✔
743
    nonceDecrypt = NULL;
1,011✔
744
    nonceEncrypt = NULL;
1,011✔
745
    // Determine if extra nonceTPM values are going to be required.
746
    // If this is the first session (sessionIndex = 0) and it is an authorization
747
    // session that uses an HMAC, then check if additional session nonces are to be
748
    // included.
749
    if(sessionIndex == 0
1,011✔
750
       && s_associatedHandles[sessionIndex] != TPM_RH_UNASSIGNED)
767✔
751
        {
752
            // If there is a decrypt session and if this is not the decrypt session,
753
            // then an extra nonce may be needed.
754
            if(s_decryptSessionIndex != UNDEFINED_INDEX
756✔
755
               && s_decryptSessionIndex != sessionIndex)
158✔
756
                {
757
                    // Will add the nonce for the decrypt session.
758
                    SESSION *decryptSession
84✔
759
                        = SessionGet(s_sessionHandles[s_decryptSessionIndex]);
84✔
760
                    nonceDecrypt = &decryptSession->nonceTPM;
84✔
761
                }
762
            // Now repeat for the encrypt session.
763
            if(s_encryptSessionIndex != UNDEFINED_INDEX
756✔
764
               && s_encryptSessionIndex != sessionIndex
152✔
765
               && s_encryptSessionIndex != s_decryptSessionIndex)
84✔
766
                {
767
                    // Have to have the nonce for the encrypt session.
768
                    SESSION *encryptSession
64✔
769
                        = SessionGet(s_sessionHandles[s_encryptSessionIndex]);
64✔
770
                    nonceEncrypt = &encryptSession->nonceTPM;
64✔
771
                }
772
        }
773
    // Continue with the HMAC processing.
774
    session = SessionGet(s_sessionHandles[sessionIndex]);
1,011✔
775
    // Generate HMAC key.
776
    MemoryCopy2B(&key.b, &session->sessionKey.b, sizeof(key.t.buffer));
1,011✔
777
    // Check if the session has an associated handle and if the associated entity
778
    // is the one to which the session is bound. If not, add the authValue of
779
    // this entity to the HMAC key.
780
    // If the session is bound to the object or the session is a policy session
781
    // with no authValue required, do not include the authValue in the HMAC key.
782
    // Note: For a policy session, its isBound attribute is CLEARED.
783
    // Include the entity authValue if it is needed
784
    if(session->attributes.includeAuth == SET)
1,011✔
785
        {
786
            TPM2B_AUTH          authValue;
721✔
787
            // Get the entity authValue with trailing zeros removed
788
            EntityGetAuthValue(s_associatedHandles[sessionIndex], &authValue);
721✔
789
            // add the authValue to the HMAC key
790
            MemoryConcat2B(&key.b, &authValue.b, sizeof(key.t.buffer));
721✔
791
        }
792
    // if the HMAC key size is 0, a NULL string HMAC is allowed
793
    if(key.t.size == 0
1,011✔
794
       && s_inputAuthValues[sessionIndex].t.size == 0)
240✔
795
        {
796
            hmac->t.size = 0;
124✔
797
            return hmac;
124✔
798
        }
799
    // Start HMAC
800
    hmac->t.size = CryptHmacStart2B(&hmacState, session->authHashAlg, &key.b);
887✔
801
    //  Add cpHash
802
    CryptDigestUpdate2B(&hmacState.hashState,
1,774✔
803
                        &ComputeCpHash(command, session->authHashAlg)->b);
887✔
804
    //  Add nonces as required
805
    CryptDigestUpdate2B(&hmacState.hashState, &s_nonceCaller[sessionIndex].b);
887✔
806
    CryptDigestUpdate2B(&hmacState.hashState, &session->nonceTPM.b);
887✔
807
    if(nonceDecrypt != NULL)
887✔
808
        CryptDigestUpdate2B(&hmacState.hashState, &nonceDecrypt->b);
84✔
809
    if(nonceEncrypt != NULL)
887✔
810
        CryptDigestUpdate2B(&hmacState.hashState, &nonceEncrypt->b);
64✔
811
    //  Add sessionAttributes
812
    buffer = marshalBuffer;
887✔
813
    marshalSize = TPMA_SESSION_Marshal(&(s_attributes[sessionIndex]),
887✔
814
                                       &buffer, NULL);
815
    CryptDigestUpdate(&hmacState.hashState, marshalSize, marshalBuffer);
887✔
816
    // Complete the HMAC computation
817
    CryptHmacEnd2B(&hmacState, &hmac->b);
887✔
818
    return hmac;
887✔
819
}
820
/* 6.4.4.10 CheckSessionHMAC() */
821
/* This function checks the HMAC of in a session. It uses ComputeCommandHMAC() to compute the
822
   expected HMAC value and then compares the result with the HMAC in the authorization session. The
823
   authorization is successful if they are the same. */
824
/* If the authorizations are not the same, IncrementLockout() is called. It will return
825
   TPM_RC_AUTH_FAIL if the failure caused the failureCount to increment. Otherwise, it will return
826
   TPM_RC_BAD_AUTH. */
827
/* Error Returns Meaning */
828
/* TPM_RC_AUTH_FAIL authorization failure caused failureCount increment */
829
/* TPM_RC_BAD_AUTH authorization failure did not cause failureCount increment */
830
static TPM_RC
831
CheckSessionHMAC(
1,011✔
832
                 COMMAND         *command,       // IN: primary control structure
833
                 UINT32           sessionIndex   // IN: index of session to be processed
834
                 )
835
{
836
    TPM2B_DIGEST        hmac;           // authHMAC for comparing
1,011✔
837
    // Compute authHMAC
838
   ComputeCommandHMAC(command, sessionIndex, &hmac);
1,011✔
839
    // Compare the input HMAC with the authHMAC computed above.
840
    if(!MemoryEqual2B(&s_inputAuthValues[sessionIndex].b, &hmac.b))
1,011✔
841
        {
842
            // If an HMAC session has a failure, invoke the anti-hammering
843
            // if it applies to the authorized entity or the session.
844
            // Otherwise, just indicate that the authorization is bad.
845
            return IncrementLockout(sessionIndex);
10✔
846
        }
847
    return TPM_RC_SUCCESS;
848
}
849
/* 6.4.4.11 CheckPolicyAuthSession() */
850
/* This function is used to validate the authorization in a policy session. This function performs
851
   the following comparisons to see if a policy authorization is properly provided. The check
852
   are: */
853
/* a) compare policyDigest in session with authPolicy associated with the entity to be
854
   authorized; */
855
/* b) compare timeout if applicable; */
856
/* c) compare commandCode if applicable; */
857
/* d) compare cpHash if applicable; and */
858
/* e) see if PCR values have changed since computed. */
859
/* If all the above checks succeed, the handle is authorized. The order of these comparisons is not
860
   important because any failure will result in the same error code. */
861
/* Error Returns Meaning */
862
/* TPM_RC_PCR_CHANGED PCR value is not current */
863
/* TPM_RC_POLICY_FAIL policy session fails */
864
/* TPM_RC_LOCALITY command locality is not allowed */
865
/* TPM_RC_POLICY_CC CC doesn't match */
866
/* TPM_RC_EXPIRED policy session has expired */
867
/* TPM_RC_PP PP is required but not asserted */
868
/* TPM_RC_NV_UNAVAILABLE NV is not available for write */
869
/* TPM_RC_NV_RATE NV is rate limiting */
870
static TPM_RC
871
CheckPolicyAuthSession(
204✔
872
                       COMMAND         *command,       // IN: primary parsing structure
873
                       UINT32           sessionIndex   // IN: index of session to be processed
874
                       )
875
{
876
    SESSION             *session;
204✔
877
    TPM2B_DIGEST         authPolicy;
204✔
878
    TPMI_ALG_HASH        policyAlg;
204✔
879
    UINT8                locality;
204✔
880
    // Initialize pointer to the authorization session.
881
    session = SessionGet(s_sessionHandles[sessionIndex]);
204✔
882
    // If the command is TPM2_PolicySecret(), make sure that
883
    // either password or authValue is required
884
    if(command->code == TPM_CC_PolicySecret
204✔
885
       &&  session->attributes.isPasswordNeeded == CLEAR
886
       &&  session->attributes.isAuthValueNeeded == CLEAR)
×
887
        return TPM_RC_MODE;
888
    // See if the PCR counter for the session is still valid.
889
    if(!SessionPCRValueIsCurrent(session))
204✔
890
        return TPM_RC_PCR_CHANGED;
891
    // Get authPolicy.
892
    policyAlg = EntityGetAuthPolicy(s_associatedHandles[sessionIndex],
203✔
893
                                    &authPolicy);
894
    // Compare authPolicy.
895
    if(!MemoryEqual2B(&session->u2.policyDigest.b, &authPolicy.b))
203✔
896
        return TPM_RC_POLICY_FAIL;
897
    // Policy is OK so check if the other factors are correct
898
    // Compare policy hash algorithm.
899
    if(policyAlg != session->authHashAlg)
169✔
900
        return TPM_RC_POLICY_FAIL;
901
    // Compare timeout.
902
    if(session->timeout != 0)
169✔
903
        {
904
            // Cannot compare time if clock stop advancing.  An TPM_RC_NV_UNAVAILABLE
905
            // or TPM_RC_NV_RATE error may be returned here. This doesn't mean that
906
            // a new nonce will be created just that, because TPM time can't advance
907
            // we can't do time-based operations.
908
            RETURN_IF_NV_IS_NOT_AVAILABLE;
11✔
909
            if((session->timeout < g_time)
11✔
910
               || (session->epoch != g_timeEpoch))
11✔
911
                return TPM_RC_EXPIRED;
912
        }
913
    // If command code is provided it must match
914
    if(session->commandCode != 0)
169✔
915
        {
916
            if(session->commandCode != command->code)
88✔
917
                return TPM_RC_POLICY_CC;
918
        }
919
    else
920
        {
921
            // If command requires a DUP or ADMIN authorization, the session must have
922
            // command code set.
923
            AUTH_ROLE   role = CommandAuthRole(command->index, sessionIndex);
81✔
924
            if(role == AUTH_ADMIN || role == AUTH_DUP)
81✔
925
                return TPM_RC_POLICY_FAIL;
926
        }
927
    // Check command locality.
928
    {
929
        BYTE         sessionLocality[sizeof(TPMA_LOCALITY)];
166✔
930
        BYTE        *buffer = sessionLocality;
166✔
931
        // Get existing locality setting in canonical form
932
        sessionLocality[0] = 0;
166✔
933
        TPMA_LOCALITY_Marshal(&session->commandLocality, &buffer, NULL);
166✔
934
        // See if the locality has been set
935
        if(sessionLocality[0] != 0)
166✔
936
            {
937
                // If so, get the current locality
938
                locality = _plat__LocalityGet();
×
939
                if(locality < 5)
×
940
                    {
941
                        if(((sessionLocality[0] & (1 << locality)) == 0)
×
942
                           || sessionLocality[0] > 31)
×
943
                            return TPM_RC_LOCALITY;
×
944
                    }
945
                else if(locality > 31)
×
946
                    {
947
                        if(sessionLocality[0] != locality)
×
948
                            return TPM_RC_LOCALITY;
949
                    }
950
                else
951
                    {
952
                        // Could throw an assert here but a locality error is just
953
                        // as good. It just means that, whatever the locality is, it isn't
954
                        // the locality requested so...
955
                        return TPM_RC_LOCALITY;
956
                    }
957
            }
958
    } // end of locality check
959
    // Check physical presence.
960
    if(session->attributes.isPPRequired == SET
166✔
961
       && !_plat__PhysicalPresenceAsserted())
×
962
        return TPM_RC_PP;
963
    // Compare cpHash/nameHash if defined, or if the command requires an ADMIN or
964
    // DUP role for this handle.
965
    if(session->u1.cpHash.b.size != 0)
166✔
966
        {
967
            BOOL        OK;
10✔
968
            if(session->attributes.isCpHashDefined)
10✔
969
                // Compare cpHash.
970
                OK = MemoryEqual2B(&session->u1.cpHash.b,
8✔
971
                                   &ComputeCpHash(command, session->authHashAlg)->b);
4✔
972
            else if(session->attributes.isTemplateSet)
6✔
973
                OK = CompareTemplateHash(command, session);
3✔
974
            else
975
                OK = CompareNameHash(command, session);
3✔
976
            if(!OK)
10✔
977
                return TPM_RCS_POLICY_FAIL;
978
        }
979
    if(session->attributes.checkNvWritten)
165✔
980
        {
981
            NV_REF           locator;
4✔
982
            NV_INDEX        *nvIndex;
4✔
983
            // If this is not an NV index, the policy makes no sense so fail it.
984
            if(HandleGetType(s_associatedHandles[sessionIndex]) != TPM_HT_NV_INDEX)
4✔
985
                return TPM_RC_POLICY_FAIL;
1✔
986
            // Get the index data
987
            nvIndex = NvGetIndexInfo(s_associatedHandles[sessionIndex], &locator);
4✔
988
            // Make sure that the TPMA_WRITTEN_ATTRIBUTE has the desired state
989
            if((IS_ATTRIBUTE(nvIndex->publicArea.attributes, TPMA_NV, WRITTEN))
4✔
990
               != (session->attributes.nvWrittenState == SET))
4✔
991
                return TPM_RC_POLICY_FAIL;
992
        }
993
    return TPM_RC_SUCCESS;
994
}
995
/* 6.4.4.12 RetrieveSessionData() */
996
/* This function will unmarshal the sessions in the session area of a command. The values are placed
997
   in the arrays that are defined at the beginning of this file. The normal unmarshaling errors are
998
   possible. */
999
/* Error Returns Meaning */
1000
/* TPM_RC_SUCCSS unmarshaled without error */
1001
/* TPM_RC_SIZE the number of bytes unmarshaled is not the same as the value for authorizationSize in
1002
   the command */
1003
static TPM_RC
1004
RetrieveSessionData(
6,068✔
1005
                    COMMAND         *command        // IN: main parsing structure for command
1006
                    )
1007
{
1008
    int              i;
6,068✔
1009
    TPM_RC           result;
6,068✔
1010
    SESSION         *session;
6,068✔
1011
    TPMA_SESSION     sessionAttributes;
6,068✔
1012
    TPM_HT           sessionType;
6,068✔
1013
    INT32            sessionIndex;
6,068✔
1014
    TPM_RC           errorIndex;
6,068✔
1015
    s_decryptSessionIndex = UNDEFINED_INDEX;
6,068✔
1016
    s_encryptSessionIndex = UNDEFINED_INDEX;
6,068✔
1017
    s_auditSessionIndex = UNDEFINED_INDEX;
6,068✔
1018
    for(sessionIndex = 0; command->authSize > 0; sessionIndex++)
12,591✔
1019
        {
1020
            errorIndex = TPM_RC_S + g_rcIndex[sessionIndex];
6,573✔
1021
            // If maximum allowed number of sessions has been parsed, return a size
1022
            // error with a session number that is larger than the number of allowed
1023
            // sessions
1024
            if(sessionIndex == MAX_SESSION_NUM)
6,573✔
1025
                return TPM_RCS_SIZE + errorIndex;
4✔
1026
            // make sure that the associated handle for each session starts out
1027
            // unassigned
1028
            s_associatedHandles[sessionIndex] = TPM_RH_UNASSIGNED;
6,569✔
1029
            // First parameter: Session handle.
1030
            result = TPMI_SH_AUTH_SESSION_Unmarshal(
13,138✔
1031
                                                    &s_sessionHandles[sessionIndex],
6,569✔
1032
                                                    &command->parameterBuffer,
1033
                                                    &command->authSize, TRUE);
1034
            if(result != TPM_RC_SUCCESS)
6,569✔
1035
                return result + TPM_RC_S + g_rcIndex[sessionIndex];
16✔
1036
            // Second parameter: Nonce.
1037
            result = TPM2B_NONCE_Unmarshal(&s_nonceCaller[sessionIndex],
6,553✔
1038
                                           &command->parameterBuffer,
1039
                                           &command->authSize);
1040
            if(result != TPM_RC_SUCCESS)
6,553✔
1041
                return result + TPM_RC_S + g_rcIndex[sessionIndex];
8✔
1042
            // Third parameter: sessionAttributes.
1043
            result = TPMA_SESSION_Unmarshal(&s_attributes[sessionIndex],
6,545✔
1044
                                            &command->parameterBuffer,
1045
                                            &command->authSize);
1046
            if(result != TPM_RC_SUCCESS)
6,545✔
1047
                return result + TPM_RC_S + g_rcIndex[sessionIndex];
4✔
1048
            // Fourth parameter: authValue (PW or HMAC).
1049
            result = TPM2B_AUTH_Unmarshal(&s_inputAuthValues[sessionIndex],
6,541✔
1050
                                          &command->parameterBuffer,
1051
                                          &command->authSize);
1052
            if(result != TPM_RC_SUCCESS)
6,541✔
1053
                return result + errorIndex;
4✔
1054
            sessionAttributes = s_attributes[sessionIndex];
6,537✔
1055
            if(s_sessionHandles[sessionIndex] == TPM_RS_PW)
6,537✔
1056
                {
1057
                    // A PWAP session needs additional processing.
1058
                    //     Can't have any attributes set other than continueSession bit
1059
                    if(IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, encrypt)
5,470✔
1060
                       || IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, decrypt)
1061
                       || IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, audit)
5,470✔
1062
                       || IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, auditExclusive)
1063
                       || IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, auditReset))
5,466✔
1064
                        return TPM_RCS_ATTRIBUTES + errorIndex;
4✔
1065
                    //     The nonce size must be zero.
1066
                    if(s_nonceCaller[sessionIndex].t.size != 0)
5,466✔
1067
                        return TPM_RCS_NONCE + errorIndex;
4✔
1068
                    continue;
5,462✔
1069
                }
1070
            // For not password sessions...
1071
            // Find out if the session is loaded.
1072
            if(!SessionIsLoaded(s_sessionHandles[sessionIndex]))
1,067✔
1073
                return TPM_RC_REFERENCE_S0 + sessionIndex;
6✔
1074
            sessionType = HandleGetType(s_sessionHandles[sessionIndex]);
1,061✔
1075
            session = SessionGet(s_sessionHandles[sessionIndex]);
1,061✔
1076
            // Check if the session is an HMAC/policy session.
1077
            if((session->attributes.isPolicy == SET
1,061✔
1078
                && sessionType == TPM_HT_HMAC_SESSION)
204✔
1079
               || (session->attributes.isPolicy == CLEAR
1,061✔
1080
                   && sessionType == TPM_HT_POLICY_SESSION))
857✔
1081
                return TPM_RCS_HANDLE + errorIndex;
×
1082
            // Check that this handle has not previously been used.
1083
            for(i = 0; i < sessionIndex; i++)
1,392✔
1084
                {
1085
                    if(s_sessionHandles[i] == s_sessionHandles[sessionIndex])
331✔
1086
                        return TPM_RCS_HANDLE + errorIndex;
×
1087
                }
1088
            // If the session is used for parameter encryption or audit as well, set
1089
            // the corresponding Indexes.
1090
            // First process decrypt.
1091
            if(IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, decrypt))
1,061✔
1092
                {
1093
                    // Check if the commandCode allows command parameter encryption.
1094
                    if(DecryptSize(command->index) == 0)
160✔
1095
                        return TPM_RCS_ATTRIBUTES + errorIndex;
×
1096
                    // Encrypt attribute can only appear in one session
1097
                    if(s_decryptSessionIndex != UNDEFINED_INDEX)
160✔
1098
                        return TPM_RCS_ATTRIBUTES + errorIndex;
×
1099
                    // Can't decrypt if the session's symmetric algorithm is TPM_ALG_NULL
1100
                    if(session->symmetric.algorithm == TPM_ALG_NULL)
160✔
1101
                        return TPM_RCS_SYMMETRIC + errorIndex;
×
1102
                    // All checks passed, so set the index for the session used to decrypt
1103
                    // a command parameter.
1104
                    s_decryptSessionIndex = sessionIndex;
160✔
1105
                }
1106
            // Now process encrypt.
1107
            if(IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, encrypt))
1,061✔
1108
                {
1109
                    // Check if the commandCode allows response parameter encryption.
1110
                    if(EncryptSize(command->index) == 0)
154✔
1111
                        return TPM_RCS_ATTRIBUTES + errorIndex;
×
1112
                    // Encrypt attribute can only appear in one session.
1113
                    if(s_encryptSessionIndex != UNDEFINED_INDEX)
154✔
1114
                        return TPM_RCS_ATTRIBUTES + errorIndex;
×
1115
                    // Can't encrypt if the session's symmetric algorithm is TPM_ALG_NULL
1116
                    if(session->symmetric.algorithm == TPM_ALG_NULL)
154✔
1117
                        return TPM_RCS_SYMMETRIC + errorIndex;
×
1118
                    // All checks passed, so set the index for the session used to encrypt
1119
                    // a response parameter.
1120
                    s_encryptSessionIndex = sessionIndex;
154✔
1121
                }
1122
            // At last process audit.
1123
            if(IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, audit))
1,061✔
1124
                {
1125
                    // Audit attribute can only appear in one session.
1126
                    if(s_auditSessionIndex != UNDEFINED_INDEX)
35✔
1127
                        return TPM_RCS_ATTRIBUTES + errorIndex;
×
1128
                    // An audit session can not be policy session.
1129
                    if(HandleGetType(s_sessionHandles[sessionIndex])
35✔
1130
                       == TPM_HT_POLICY_SESSION)
1131
                        return TPM_RCS_ATTRIBUTES + errorIndex;
×
1132
                    // If this is a reset of the audit session, or the first use
1133
                    // of the session as an audit session, it doesn't matter what
1134
                    // the exclusive state is. The session will become exclusive.
1135
                    if(!IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, auditReset)
35✔
1136
                       && session->attributes.isAudit == SET)
35✔
1137
                        {
1138
                            // Not first use or reset. If auditExlusive is SET, then this
1139
                            // session must be the current exclusive session.
1140
                            if(IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, auditExclusive)
14✔
1141
                               && g_exclusiveAuditSession != s_sessionHandles[sessionIndex])
×
1142
                                return TPM_RC_EXCLUSIVE;
1143
                        }
1144
                    s_auditSessionIndex = sessionIndex;
35✔
1145
                }
1146
            // Initialize associated handle as undefined. This will be changed when
1147
            // the handles are processed.
1148
            s_associatedHandles[sessionIndex] = TPM_RH_UNASSIGNED;
1,061✔
1149
        }
1150
    command->sessionNum = sessionIndex;
6,018✔
1151
    return TPM_RC_SUCCESS;
6,018✔
1152
}
1153
/* 6.4.4.13 CheckLockedOut() */
1154
/* This function checks to see if the TPM is in lockout. This function should only be called if the
1155
   entity being checked is subject to DA protection. The TPM is in lockout if the NV is not
1156
   available and a DA write is pending. Otherwise the TPM is locked out if checking for lockoutAuth
1157
   (lockoutAuthCheck == TRUE) and use of lockoutAuth is disabled, or failedTries >= maxTries */
1158
/* Error Returns Meaning */
1159
/* TPM_RC_NV_RATE NV is rate limiting */
1160
/* TPM_RC_NV_UNAVAILABLE NV is not available at this time */
1161
/* TPM_RC_LOCKOUT TPM is in lockout */
1162
static TPM_RC
1163
CheckLockedOut(
164✔
1164
               BOOL             lockoutAuthCheck   // IN: TRUE if checking is for lockoutAuth
1165
               )
1166
{
1167
    // If NV is unavailable, and current cycle state recorded in NV is not
1168
    // SU_NONE_VALUE, refuse to check any authorization because we would
1169
    // not be able to handle a DA failure.
1170
    if(!NV_IS_AVAILABLE && NV_IS_ORDERLY)
164✔
1171
        return g_NvStatus;
1172
    // Check if DA info needs to be updated in NV.
1173
    if(s_DAPendingOnNV)
164✔
1174
        {
1175
            // If NV is accessible,
1176
            RETURN_IF_NV_IS_NOT_AVAILABLE;
×
1177
            // ... write the pending DA data and proceed.
1178
            NV_SYNC_PERSISTENT(lockOutAuthEnabled);
×
1179
            NV_SYNC_PERSISTENT(failedTries);
×
1180
            s_DAPendingOnNV = FALSE;
×
1181
        }
1182
    // Lockout is in effect if checking for lockoutAuth and use of lockoutAuth
1183
    // is disabled...
1184
    if(lockoutAuthCheck)
164✔
1185
        {
1186
            if(gp.lockOutAuthEnabled == FALSE)
80✔
1187
                return TPM_RC_LOCKOUT;
×
1188
        }
1189
    else
1190
        {
1191
            // ... or if the number of failed tries has been maxed out.
1192
            if(gp.failedTries >= gp.maxTries)
84✔
1193
                return TPM_RC_LOCKOUT;
1194
#if USE_DA_USED
1195
            // If the daUsed flag is not SET, then no DA validation until the
1196
            // daUsed state is written to NV
1197
            if(!g_daUsed)
46✔
1198
                {
1199
                    RETURN_IF_NV_IS_NOT_AVAILABLE;
10✔
1200
                    g_daUsed = TRUE;
10✔
1201
                    gp.orderlyState = SU_DA_USED_VALUE;
10✔
1202
                    NV_SYNC_PERSISTENT(orderlyState);
10✔
1203
                    return TPM_RC_RETRY;
10✔
1204
                }
1205
#endif
1206
        }
1207
    return TPM_RC_SUCCESS;
1208
}
1209
/* 6.4.4.14 CheckAuthSession() */
1210
/* This function checks that the authorization session properly authorizes the use of the associated
1211
   handle. */
1212
/* Error Returns Meaning */
1213
/* TPM_RC_LOCKOUT entity is protected by DA and TPM is in lockout, or TPM is locked out on NV update
1214
   pending on DA parameters */
1215
/* TPM_RC_PP Physical Presence is required but not provided */
1216
/* TPM_RC_AUTH_FAIL HMAC or PW authorization failed with DA side-effects (can be a policy
1217
   session) */
1218
/* TPM_RC_BAD_AUTH HMAC or PW authorization failed without DA side-effects (can be a policy
1219
   session) */
1220
/* TPM_RC_POLICY_FAIL if policy session fails */
1221
/* TPM_RC_POLICY_CC command code of policy was wrong */
1222
/* TPM_RC_EXPIRED the policy session has expired */
1223
/* TPM_RC_PCR ??? */
1224
/* TPM_RC_AUTH_UNAVAILABLE authValue or authPolicy unavailable */
1225
static TPM_RC
1226
CheckAuthSession(
6,382✔
1227
                 COMMAND         *command,       // IN: primary parsing structure
1228
                 UINT32           sessionIndex   // IN: index of session to be processed
1229
                 )
1230
{
1231
    TPM_RC           result = TPM_RC_SUCCESS;
6,382✔
1232
    SESSION         *session = NULL;
6,382✔
1233
    TPM_HANDLE       sessionHandle = s_sessionHandles[sessionIndex];
6,382✔
1234
    TPM_HANDLE       associatedHandle = s_associatedHandles[sessionIndex];
6,382✔
1235
    TPM_HT           sessionHandleType = HandleGetType(sessionHandle);
6,382✔
1236
    BOOL             authUsed;
6,382✔
1237

1238
    pAssert(sessionHandle != TPM_RH_UNASSIGNED);
6,382✔
1239
    
1240
    // Take care of physical presence
1241
    if(associatedHandle == TPM_RH_PLATFORM)
6,382✔
1242
        {
1243
            // If the physical presence is required for this command, check for PP
1244
            // assertion. If it isn't asserted, no point going any further.
1245
            if(PhysicalPresenceIsRequired(command->index)
901✔
1246
               && !_plat__PhysicalPresenceAsserted())
12✔
1247
                return TPM_RC_PP;
1248
        }
1249
    if(sessionHandle != TPM_RS_PW)
6,370✔
1250
        {
1251
            session = SessionGet(sessionHandle);
962✔
1252
            // Set includeAuth to indicate if DA checking will be required and if the
1253
            // authValue will be included in any HMAC.
1254
            if(sessionHandleType == TPM_HT_POLICY_SESSION)
962✔
1255
                {
1256
                    // For a policy session, will check the DA status of the entity if either
1257
                    // isAuthValueNeeded or isPasswordNeeded is SET.
1258
                    session->attributes.includeAuth =
204✔
1259
                        session->attributes.isAuthValueNeeded
1260
                        || session->attributes.isPasswordNeeded;
204✔
1261
                }
1262
            else
1263
                {
1264
                    // For an HMAC session, need to check unless the session
1265
                    // is bound.
1266
                    session->attributes.includeAuth =
1,516✔
1267
                        !IsSessionBindEntity(s_associatedHandles[sessionIndex], session);
758✔
1268
                }
1269
            authUsed = session->attributes.includeAuth;
962✔
1270
        }
1271
    else
1272
        // Password session
1273
        authUsed = TRUE;
1274
    // If the authorization session is going to use an authValue, then make sure
1275
    // that access to that authValue isn't locked out.
1276
    if(authUsed)
962✔
1277
        {
1278
            // See if entity is subject to lockout.
1279
            if(!IsDAExempted(associatedHandle))
6,139✔
1280
                {
1281
                    // See if in lockout
1282
                    result = CheckLockedOut(associatedHandle == TPM_RH_LOCKOUT);
164✔
1283
                    if(result != TPM_RC_SUCCESS)
164✔
1284
                        return result;
1285
                }
1286
        }
1287
    // Policy or HMAC+PW?
1288
    if(sessionHandleType != TPM_HT_POLICY_SESSION)
6,322✔
1289
        {
1290
            // for non-policy session make sure that a policy session is not required
1291
            if(IsPolicySessionRequired(command->index, sessionIndex))
6,118✔
1292
                return TPM_RC_AUTH_TYPE;
1293
            // The authValue must be available.
1294
            // Note: The authValue is going to be "used" even if it is an EmptyAuth.
1295
            // and the session is bound.
1296
            if(!IsAuthValueAvailable(associatedHandle, command->index, sessionIndex))
6,116✔
1297
                return TPM_RC_AUTH_UNAVAILABLE;
1298
        }
1299
    else
1300
        {
1301
            // ... see if the entity has a policy, ...
1302
            // Note: IsAuthPolicyAvailable will return FALSE if the sensitive area of the
1303
            // object is not loaded
1304
            if(!IsAuthPolicyAvailable(associatedHandle, command->index, sessionIndex))
204✔
1305
                return TPM_RC_AUTH_UNAVAILABLE;
1306
            // ... and check the policy session.
1307
            result = CheckPolicyAuthSession(command, sessionIndex);
204✔
1308
            if(result != TPM_RC_SUCCESS)
204✔
1309
                return result;
1310
        }
1311
    // Check authorization according to the type
1312
    if((TPM_RS_PW == sessionHandle) || (session->attributes.isPasswordNeeded == SET))
6,257✔
1313
        result = CheckPWAuthSession(sessionIndex);
5,345✔
1314
    else
1315
        result = CheckSessionHMAC(command, sessionIndex);
912✔
1316
    // Do processing for PIN Indexes are only three possibilities for 'result' at
1317
    // this point: TPM_RC_SUCCESS, TPM_RC_AUTH_FAIL, TPM_RC_BAD_AUTH
1318
    // For all these cases, we would have to process a PIN index if the
1319
    // authValue of the index was used for authorization.
1320
    if((TPM_HT_NV_INDEX == HandleGetType(associatedHandle)) && authUsed)
6,257✔
1321
        {
1322
            NV_REF           locator;
485✔
1323
            NV_INDEX        *nvIndex = NvGetIndexInfo(associatedHandle, &locator);
485✔
1324
            NV_PIN           pinData;
485✔
1325
            TPMA_NV          nvAttributes;
485✔
1326
            
1327
            pAssert(nvIndex != NULL);
485✔
1328
            nvAttributes = nvIndex->publicArea.attributes;
485✔
1329
            // If this is a PIN FAIL index and the value has been written
1330
            // then we can update the counter (increment or clear)
1331
            if(IsNvPinFailIndex(nvAttributes)
485✔
1332
               && IS_ATTRIBUTE(nvAttributes, TPMA_NV, WRITTEN))
13✔
1333
                {
1334
                    pinData.intVal = NvGetUINT64Data(nvIndex, locator);
13✔
1335
                    if(result != TPM_RC_SUCCESS)
13✔
1336
                        pinData.pin.pinCount++;
6✔
1337
                    else
1338
                        pinData.pin.pinCount = 0;
7✔
1339
                    NvWriteUINT64Data(nvIndex, pinData.intVal);
13✔
1340
                }
1341
            // If this is a PIN PASS Index, increment if we have used the
1342
            // authorization value.
1343
            // NOTE: If the counter has already hit the limit, then we
1344
            // would not get here because the authorization value would not
1345
            // be available and the TPM would have returned before it gets here
1346
            else if(IsNvPinPassIndex(nvAttributes)
472✔
1347
                    && IS_ATTRIBUTE(nvAttributes, TPMA_NV, WRITTEN)
8✔
1348
                    && result == TPM_RC_SUCCESS)
8✔
1349
                {
1350
                    // If the access is valid, then increment the use counter
1351
                    pinData.intVal = NvGetUINT64Data(nvIndex, locator);
7✔
1352
                    pinData.pin.pinCount++;
7✔
1353
                    NvWriteUINT64Data(nvIndex, pinData.intVal);
7✔
1354
                }
1355
        }
1356
    return result;
1357
}
1358
#if CC_GetCommandAuditDigest
1359
/* 6.4.4.15 CheckCommandAudit() */
1360
/* This function is called before the command is processed if audit is enabled for the command. It
1361
   will check to see if the audit can be performed and will ensure that the cpHash is available for
1362
   the audit. */
1363
/* Error Returns Meaning */
1364
/* TPM_RC_NV_UNAVAILABLE NV is not available for write */
1365
/* TPM_RC_NV_RATE NV is rate limiting */
1366
static TPM_RC
1367
CheckCommandAudit(
65✔
1368
                  COMMAND         *command
1369
                  )
1370
{
1371
    // If the audit digest is clear and command audit is required, NV must be
1372
    // available so that TPM2_GetCommandAuditDigest() is able to increment
1373
    // audit counter. If NV is not available, the function bails out to prevent
1374
    // the TPM from attempting an operation that would fail anyway.
1375
    if(gr.commandAuditDigest.t.size == 0
65✔
1376
       || GetCommandCode(command->index) == TPM_CC_GetCommandAuditDigest)
×
1377
        {
1378
            RETURN_IF_NV_IS_NOT_AVAILABLE;
65✔
1379
        }
1380
    // Make sure that the cpHash is computed for the algorithm
1381
    ComputeCpHash(command, gp.auditHashAlg);
65✔
1382
    return TPM_RC_SUCCESS;
65✔
1383
}
1384
#endif
1385
/* 6.4.4.16 ParseSessionBuffer() */
1386
/* This function is the entry function for command session processing. It iterates sessions in
1387
   session area and reports if the required authorization has been properly provided. It also
1388
   processes audit session and passes the information of encryption sessions to parameter encryption
1389
   module. */
1390
/* Error Returns Meaning */
1391
/* various parsing failure or authorization failure */
1392
TPM_RC
1393
ParseSessionBuffer(
6,068✔
1394
                   COMMAND         *command        // IN: the structure that contains
1395
                   )
1396
{
1397
    TPM_RC               result;
6,068✔
1398
    UINT32               i;
6,068✔
1399
    INT32                size = 0;
6,068✔
1400
    TPM2B_AUTH           extraKey;
6,068✔
1401
    UINT32               sessionIndex;
6,068✔
1402
    TPM_RC               errorIndex;
6,068✔
1403
    SESSION             *session = NULL;
6,068✔
1404
    // Check if a command allows any session in its session area.
1405
    if(!IsSessionAllowed(command->index))
6,068✔
1406
        return TPM_RC_AUTH_CONTEXT;
1407
    // Default-initialization.
1408
    command->sessionNum = 0;
6,068✔
1409
    result = RetrieveSessionData(command);
6,068✔
1410
    if(result != TPM_RC_SUCCESS)
6,068✔
1411
        return result;
1412
    // There is no command in the TPM spec that has more handles than
1413
    // MAX_SESSION_NUM.
1414
    pAssert(command->handleNum <= MAX_SESSION_NUM);
6,018✔
1415
    // Associate the session with an authorization handle.
1416
    for(i = 0; i < command->handleNum; i++)
14,219✔
1417
        {
1418
            if(CommandAuthRole(command->index, i) != AUTH_NONE)
8,201✔
1419
                {
1420
                    // If the received session number is less than the number of handles
1421
                    // that requires authorization, an error should be returned.
1422
                    // Note: for all the TPM 2.0 commands, handles requiring
1423
                    // authorization come first in a command input and there are only ever
1424
                    // two values requiring authorization
1425
                    if(command->sessionNum == 0)                // libtpms added begin (Coverity 1550499)
6,388✔
1426
                        return TPM_RC_AUTH_MISSING;                // libtpms added end
1427
                    if(i > (command->sessionNum - 1))
6,388✔
1428
                        return TPM_RC_AUTH_MISSING;
1429
                    // Record the handle associated with the authorization session
1430
                    s_associatedHandles[i] = command->handles[i];
6,388✔
1431
                }
1432
        }
1433
    // Consistency checks are done first to avoid authorization failure when the
1434
    // command will not be executed anyway.
1435
    for(sessionIndex = 0; sessionIndex < command->sessionNum; sessionIndex++)
12,286✔
1436
        {
1437
            errorIndex = TPM_RC_S + g_rcIndex[sessionIndex];
6,493✔
1438
            // PW session must be an authorization session
1439
            if(s_sessionHandles[sessionIndex] == TPM_RS_PW)
6,493✔
1440
                {
1441
                    if(s_associatedHandles[sessionIndex] == TPM_RH_UNASSIGNED)
5,432✔
1442
                        return TPM_RCS_HANDLE + errorIndex;
12✔
1443
                    // a password session can't be audit, encrypt or decrypt
1444
                    if(IS_ATTRIBUTE(s_attributes[sessionIndex], TPMA_SESSION, audit)
5,420✔
1445
                       || IS_ATTRIBUTE(s_attributes[sessionIndex], TPMA_SESSION, encrypt)
1446
                       || IS_ATTRIBUTE(s_attributes[sessionIndex], TPMA_SESSION, decrypt))
5,420✔
1447
                        return TPM_RCS_ATTRIBUTES + errorIndex;
×
1448
                    session = NULL;
1449
                }
1450
            else
1451
                {
1452
                    session = SessionGet(s_sessionHandles[sessionIndex]);
1,061✔
1453
                    // A trial session can not appear in session area, because it cannot
1454
                    // be used for authorization, audit or encrypt/decrypt.
1455
                    if(session->attributes.isTrialPolicy == SET)
1,061✔
1456
                        return TPM_RCS_ATTRIBUTES + errorIndex;
×
1457
                    // See if the session is bound to a DA protected entity
1458
                    // NOTE: Since a policy session is never bound, a policy is still
1459
                    // usable even if the object is DA protected and the TPM is in
1460
                    // lockout.
1461
                    if(session->attributes.isDaBound == SET)
1,061✔
1462
                        {
1463
                            result = CheckLockedOut(session->attributes.isLockoutBound == SET);
×
1464
                            if(result != TPM_RC_SUCCESS)
×
1465
                                return result;
×
1466
                        }
1467
                    // If this session is for auditing, make sure the cpHash is computed.
1468
                    if(IS_ATTRIBUTE(s_attributes[sessionIndex], TPMA_SESSION, audit))
1,061✔
1469
                        ComputeCpHash(command, session->authHashAlg);
35✔
1470
                }
1471
            // if the session has an associated handle, check the authorization
1472
            if(s_associatedHandles[sessionIndex] != TPM_RH_UNASSIGNED)
6,481✔
1473
                {
1474
                    result = CheckAuthSession(command, sessionIndex);
6,382✔
1475
                    if(result != TPM_RC_SUCCESS)
6,382✔
1476
                        return RcSafeAddToResult(result, errorIndex);
213✔
1477
                }
1478
            else
1479
                {
1480
                    // a session that is not for authorization must either be encrypt,
1481
                    // decrypt, or audit
1482
                    if(!IS_ATTRIBUTE(s_attributes[sessionIndex], TPMA_SESSION, audit)
99✔
1483
                       &&  !IS_ATTRIBUTE(s_attributes[sessionIndex], TPMA_SESSION, encrypt)
1484
                       &&  !IS_ATTRIBUTE(s_attributes[sessionIndex], TPMA_SESSION, decrypt))
88✔
1485
                        return TPM_RCS_ATTRIBUTES + errorIndex;
×
1486
                    // no authValue included in any of the HMAC computations
1487
                    pAssert(session != NULL);
99✔
1488
                    session->attributes.includeAuth = CLEAR;
99✔
1489
                    // check HMAC for encrypt/decrypt/audit only sessions
1490
                    result = CheckSessionHMAC(command, sessionIndex);
99✔
1491
                    if(result != TPM_RC_SUCCESS)
99✔
1492
                        return RcSafeAddToResult(result, errorIndex);
×
1493
                }
1494
        }
1495
#if CC_GetCommandAuditDigest
1496
    // Check if the command should be audited. Need to do this before any parameter
1497
    // encryption so that the cpHash for the audit is correct
1498
    if(CommandAuditIsRequired(command->index))
5,793✔
1499
        {
1500
            result = CheckCommandAudit(command);
65✔
1501
            if(result != TPM_RC_SUCCESS)
65✔
1502
                return result;              // No session number to reference
1503
        }
1504
#endif
1505
    // Decrypt the first parameter if applicable. This should be the last operation
1506
    // in session processing.
1507
    // If the encrypt session is associated with a handle and the handle's
1508
    // authValue is available, then authValue is concatenated with sessionKey to
1509
    // generate encryption key, no matter if the handle is the session bound entity
1510
    // or not.
1511
    if(s_decryptSessionIndex != UNDEFINED_INDEX)
5,793✔
1512
        {
1513
            // If this is an authorization session, include the authValue in the
1514
            // generation of the decryption key
1515
            if(s_associatedHandles[s_decryptSessionIndex] != TPM_RH_UNASSIGNED)
158✔
1516
                {
1517
                    EntityGetAuthValue(s_associatedHandles[s_decryptSessionIndex],
108✔
1518
                                       &extraKey);
1519
                }
1520
            else
1521
                {
1522
                    extraKey.b.size = 0;
50✔
1523
                }
1524
            size = DecryptSize(command->index);
158✔
1525
            result = CryptParameterDecryption(s_sessionHandles[s_decryptSessionIndex],
316✔
1526
                                              &s_nonceCaller[s_decryptSessionIndex].b,
158✔
1527
                                              command->parameterSize, (UINT16)size,
1528
                                              &extraKey,
1529
                                              command->parameterBuffer);
1530
            if(result != TPM_RC_SUCCESS)
158✔
1531
                return RcSafeAddToResult(result,
×
1532
                                         TPM_RC_S + g_rcIndex[s_decryptSessionIndex]);
×
1533
        }
1534
    return TPM_RC_SUCCESS;
1535
}
1536
/* 6.4.4.17 CheckAuthNoSession() */
1537
/* Function to process a command with no session associated. The function makes sure all the handles
1538
   in the command require no authorization. */
1539
/* Error Returns Meaning */
1540
/* TPM_RC_AUTH_MISSING failure - one or more handles require authorization */
1541
TPM_RC
1542
CheckAuthNoSession(
10,069✔
1543
                   COMMAND         *command        // IN: command parsing structure
1544
                   )
1545
{
1546
    UINT32 i;
10,069✔
1547
    TPM_RC           result = TPM_RC_SUCCESS;
10,069✔
1548
    // Check if the command requires authorization
1549
    for(i = 0; i < command->handleNum; i++)
12,519✔
1550
        {
1551
            if(CommandAuthRole(command->index, i) != AUTH_NONE)
2,474✔
1552
                return TPM_RC_AUTH_MISSING;
1553
        }
1554
#if CC_GetCommandAuditDigest
1555
    // Check if the command should be audited.
1556
    if(CommandAuditIsRequired(command->index))
10,045✔
1557
        {
1558
            result = CheckCommandAudit(command);
×
1559
            if(result != TPM_RC_SUCCESS)
×
1560
                return result;
1561
        }
1562
#endif
1563
    // Initialize number of sessions to be 0
1564
    command->sessionNum = 0;
10,045✔
1565
    return TPM_RC_SUCCESS;
10,045✔
1566
}
1567
/* 6.4.5 Response Session Processing */
1568
/* 6.4.5.1 Introduction */
1569
/* The following functions build the session area in a response and handle the audit sessions (if
1570
   present). */
1571
/* 6.4.5.2 ComputeRpHash() */
1572
/* Function to compute rpHash (Response Parameter Hash). The rpHash is only computed if there is an
1573
   HMAC authorization session and the return code is TPM_RC_SUCCESS. */
1574
static TPM2B_DIGEST *
1575
ComputeRpHash(
1,011✔
1576
              COMMAND         *command,       // IN: command structure
1577
              TPM_ALG_ID       hashAlg        // IN: hash algorithm to compute rpHash
1578
              )
1579
{
1580
    TPM2B_DIGEST    *rpHash = GetRpHashPointer(command, hashAlg);
1,011✔
1581
    HASH_STATE       hashState;
1,011✔
1582
    if(rpHash->t.size == 0)
1,011✔
1583
        {
1584
            //   rpHash := hash(responseCode || commandCode || parameters)
1585
            // Initiate hash creation.
1586
            rpHash->t.size = CryptHashStart(&hashState, hashAlg);
734✔
1587
            // Add hash constituents.
1588
            CryptDigestUpdateInt(&hashState, sizeof(TPM_RC), TPM_RC_SUCCESS);
734✔
1589
            CryptDigestUpdateInt(&hashState, sizeof(TPM_CC), command->code);
734✔
1590
            CryptDigestUpdate(&hashState, command->parameterSize,
734✔
1591
                              command->parameterBuffer);
734✔
1592
            // Complete hash computation.
1593
            CryptHashEnd2B(&hashState, &rpHash->b);
734✔
1594
        }
1595
    return rpHash;
1,011✔
1596
}
1597
/* 6.4.5.3 InitAuditSession() */
1598
/* This function initializes the audit data in an audit session. */
1599
static void
1600
InitAuditSession(
21✔
1601
                 SESSION         *session        // session to be initialized
1602
                 )
1603
{
1604
    // Mark session as an audit session.
1605
    session->attributes.isAudit = SET;
21✔
1606
    // Audit session can not be bound.
1607
    session->attributes.isBound = CLEAR;
21✔
1608
    // Size of the audit log is the size of session hash algorithm digest.
1609
    session->u2.auditDigest.t.size = CryptHashGetDigestSize(session->authHashAlg);
21✔
1610
    // Set the original digest value to be 0.
1611
    MemorySet(&session->u2.auditDigest.t.buffer,
21✔
1612
              0,
1613
              session->u2.auditDigest.t.size);
1614
    return;
21✔
1615
}
1616
/* 6.4.5.4 UpdateAuditDigest */
1617
/* Function to update an audit digest */
1618
static void
1619
UpdateAuditDigest(
52✔
1620
                  COMMAND         *command,
1621
                  TPMI_ALG_HASH    hashAlg,
1622
                  TPM2B_DIGEST    *digest
1623
                  )
1624
{
1625
    HASH_STATE       hashState;
52✔
1626
    TPM2B_DIGEST    *cpHash = GetCpHash(command, hashAlg);
52✔
1627
    TPM2B_DIGEST    *rpHash = ComputeRpHash(command, hashAlg);
52✔
1628
    //
1629
    pAssert(cpHash != NULL);
52✔
1630
    // digestNew :=  hash (digestOld || cpHash || rpHash)
1631
    // Start hash computation.
1632
    digest->t.size = CryptHashStart(&hashState, hashAlg);
52✔
1633
    // Add old digest.
1634
    CryptDigestUpdate2B(&hashState, &digest->b);
52✔
1635
    // Add cpHash
1636
    CryptDigestUpdate2B(&hashState, &cpHash->b);
52✔
1637
    // Add rpHash
1638
    CryptDigestUpdate2B(&hashState, &rpHash->b);
52✔
1639
    // Finalize the hash.
1640
    CryptHashEnd2B(&hashState, &digest->b);
52✔
1641
}
52✔
1642
/* 6.4.5.5 Audit() */
1643
/* This function updates the audit digest in an audit session. */
1644
static void
1645
Audit(
35✔
1646
      COMMAND         *command,       // IN: primary control structure
1647
      SESSION         *auditSession   // IN: loaded audit session
1648
      )
1649
{
1650
    UpdateAuditDigest(command, auditSession->authHashAlg,
35✔
1651
                      &auditSession->u2.auditDigest);
1652
    return;
35✔
1653
}
1654
#if CC_GetCommandAuditDigest
1655
/* 6.4.5.6 CommandAudit() */
1656
/* This function updates the command audit digest. */
1657
static void
1658
CommandAudit(
17✔
1659
             COMMAND         *command        // IN:
1660
             )
1661
{
1662
    // If the digest.size is one, it indicates the special case of changing
1663
    // the audit hash algorithm. For this case, no audit is done on exit.
1664
    // NOTE: When the hash algorithm is changed, g_updateNV is set in order to
1665
    // force an update to the NV on exit so that the change in digest will
1666
    // be recorded. So, it is safe to exit here without setting any flags
1667
    // because the digest change will be written to NV when this code exits.
1668
    if(gr.commandAuditDigest.t.size == 1)
17✔
1669
        {
1670
            gr.commandAuditDigest.t.size = 0;
×
1671
            return;
×
1672
        }
1673
    // If the digest size is zero, need to start a new digest and increment
1674
    // the audit counter.
1675
    if(gr.commandAuditDigest.t.size == 0)
17✔
1676
        {
1677
            gr.commandAuditDigest.t.size = CryptHashGetDigestSize(gp.auditHashAlg);
17✔
1678
            MemorySet(gr.commandAuditDigest.t.buffer,
17✔
1679
                      0,
1680
                      gr.commandAuditDigest.t.size);
1681
            // Bump the counter and save its value to NV.
1682
            gp.auditCounter++;
17✔
1683
            NV_SYNC_PERSISTENT(auditCounter);
17✔
1684
        }
1685
    UpdateAuditDigest(command, gp.auditHashAlg, &gr.commandAuditDigest);
17✔
1686
    return;
17✔
1687
}
1688
#endif
1689
/* 6.4.5.7 UpdateAuditSessionStatus() */
1690
/* Function to update the internal audit related states of a session. It */
1691
/* a) initializes the session as audit session and sets it to be exclusive if this is the first time
1692
   it is used for audit or audit reset was requested; */
1693
/* b) reports exclusive audit session; */
1694
/* c) extends audit log; and */
1695
/* d) clears exclusive audit session if no audit session found in the command. */
1696
static void
1697
UpdateAuditSessionStatus(
13,916✔
1698
                         COMMAND         *command        // IN: primary control structure
1699
                         )
1700
{
1701
    UINT32           i;
13,916✔
1702
    TPM_HANDLE       auditSession = TPM_RH_UNASSIGNED;
13,916✔
1703
    // Iterate through sessions
1704
    for(i = 0; i < command->sessionNum; i++)
19,332✔
1705
        {
1706
            SESSION     *session;
5,416✔
1707
            // PW session do not have a loaded session and can not be an audit
1708
            // session either.  Skip it.
1709
            if(s_sessionHandles[i] == TPM_RS_PW)
5,416✔
1710
                continue;
4,453✔
1711
            session = SessionGet(s_sessionHandles[i]);
963✔
1712
            // If a session is used for audit
1713
            if(IS_ATTRIBUTE(s_attributes[i], TPMA_SESSION, audit))
963✔
1714
                {
1715
                    // An audit session has been found
1716
                    auditSession = s_sessionHandles[i];
35✔
1717
                    // If the session has not been an audit session yet, or
1718
                    // the auditSetting bits indicate a reset, initialize it and set
1719
                    // it to be the exclusive session
1720
                    if(session->attributes.isAudit == CLEAR
35✔
1721
                       || IS_ATTRIBUTE(s_attributes[i], TPMA_SESSION, auditReset))
14✔
1722
                        {
1723
                            InitAuditSession(session);
21✔
1724
                            g_exclusiveAuditSession = auditSession;
21✔
1725
                        }
1726
                    else
1727
                        {
1728
                            // Check if the audit session is the current exclusive audit
1729
                            // session and, if not, clear previous exclusive audit session.
1730
                            if(g_exclusiveAuditSession != auditSession)
14✔
1731
                                g_exclusiveAuditSession = TPM_RH_UNASSIGNED;
5✔
1732
                        }
1733
                    // Report audit session exclusivity.
1734
                    if(g_exclusiveAuditSession == auditSession)
35✔
1735
                        {
1736
                            SET_ATTRIBUTE(s_attributes[i], TPMA_SESSION, auditExclusive);
30✔
1737
                        }
1738
                    else
1739
                        {
1740
                            CLEAR_ATTRIBUTE(s_attributes[i], TPMA_SESSION, auditExclusive);
5✔
1741
                        }
1742
                    // Extend audit log.
1743
                    Audit(command, session);
5,451✔
1744
                }
1745
        }
1746
    // If no audit session is found in the command, and the command allows
1747
    // a session then, clear the current exclusive
1748
    // audit session.
1749
    if(auditSession == TPM_RH_UNASSIGNED && IsSessionAllowed(command->index))
13,916✔
1750
        {
1751
            g_exclusiveAuditSession = TPM_RH_UNASSIGNED;
8,765✔
1752
        }
1753
    return;
13,916✔
1754
}
1755
/* 6.4.5.8 ComputeResponseHMAC() */
1756
/* Function to compute HMAC for authorization session in a response. */
1757
static void
1758
ComputeResponseHMAC(
959✔
1759
                    COMMAND         *command,       // IN: command structure
1760
                    UINT32           sessionIndex,  // IN: session index to be processed
1761
                    SESSION         *session,       // IN: loaded session
1762
                    TPM2B_DIGEST    *hmac           // OUT: authHMAC
1763
                    )
1764
{
1765
    TPM2B_TYPE(KEY, (sizeof(AUTH_VALUE) * 2));
959✔
1766
    TPM2B_KEY        key;       // HMAC key
959✔
1767
    BYTE             marshalBuffer[sizeof(TPMA_SESSION)];
959✔
1768
    BYTE            *buffer;
959✔
1769
    UINT32           marshalSize;
959✔
1770
    HMAC_STATE       hmacState;
959✔
1771
    TPM2B_DIGEST    *rpHash = ComputeRpHash(command, session->authHashAlg);
959✔
1772
    // Generate HMAC key
1773
    MemoryCopy2B(&key.b, &session->sessionKey.b, sizeof(key.t.buffer));
959✔
1774
    // Add the object authValue if required
1775
    if(session->attributes.includeAuth == SET)
959✔
1776
        {
1777
            // Note: includeAuth may be SET for a policy that is used in
1778
            // UndefineSpaceSpecial(). At this point, the Index has been deleted
1779
            // so the includeAuth will have no meaning. However, the
1780
            // s_associatedHandles[] value for the session is now set to TPM_RH_NULL so
1781
            // this will return the authValue associated with TPM_RH_NULL and that is
1782
            // and empty buffer.
1783
            TPM2B_AUTH          authValue;
670✔
1784
            // Get the authValue with trailing zeros removed
1785
            EntityGetAuthValue(s_associatedHandles[sessionIndex], &authValue);
670✔
1786
            // Add it to the key
1787
            MemoryConcat2B(&key.b, &authValue.b, sizeof(key.t.buffer));
670✔
1788
        }
1789
    // if the HMAC key size is 0, the response HMAC is computed according to the
1790
    // input HMAC
1791
    if(key.t.size == 0
959✔
1792
       && s_inputAuthValues[sessionIndex].t.size == 0)
239✔
1793
        {
1794
            hmac->t.size = 0;
124✔
1795
            return;
124✔
1796
        }
1797
    // Start HMAC computation.
1798
    hmac->t.size = CryptHmacStart2B(&hmacState, session->authHashAlg, &key.b);
835✔
1799
    // Add hash components.
1800
    CryptDigestUpdate2B(&hmacState.hashState, &rpHash->b);
835✔
1801
    CryptDigestUpdate2B(&hmacState.hashState, &session->nonceTPM.b);
835✔
1802
    CryptDigestUpdate2B(&hmacState.hashState, &s_nonceCaller[sessionIndex].b);
835✔
1803
    // Add session attributes.
1804
    buffer = marshalBuffer;
835✔
1805
    marshalSize = TPMA_SESSION_Marshal(&s_attributes[sessionIndex], &buffer, NULL);
835✔
1806
    CryptDigestUpdate(&hmacState.hashState, marshalSize, marshalBuffer);
835✔
1807
    // Finalize HMAC.
1808
    CryptHmacEnd2B(&hmacState, &hmac->b);
835✔
1809
    return;
835✔
1810
}
1811
/* 6.4.5.9 UpdateInternalSession() */
1812
/* Updates internal sessions: */
1813
/* a) Restarts session time. */
1814
/* b) Clears a policy session since nonce is rolling. */
1815
static void
1816
UpdateInternalSession(
963✔
1817
                      SESSION         *session,       // IN: the session structure
1818
                      UINT32           i              // IN: session number
1819
                      )
1820
{
1821
    // If nonce is rolling in a policy session, the policy related data
1822
    // will be re-initialized.
1823
    if(HandleGetType(s_sessionHandles[i]) == TPM_HT_POLICY_SESSION
963✔
1824
       && IS_ATTRIBUTE(s_attributes[i], TPMA_SESSION, continueSession))
162✔
1825
        {
1826
            // When the nonce rolls it starts a new timing interval for the
1827
            // policy session.
1828
            SessionResetPolicyData(session);
121✔
1829
            SessionSetStartTime(session);
121✔
1830
        }
1831
    return;
963✔
1832
}
1833
/* 6.4.5.10 BuildSingleResponseAuth() */
1834
/* Function to compute response HMAC value for a policy or HMAC session. */
1835
static TPM2B_NONCE *
1836
BuildSingleResponseAuth(
963✔
1837
                        COMMAND         *command,       // IN: command structure
1838
                        UINT32           sessionIndex,  // IN: session index to be processed
1839
                        TPM2B_AUTH      *auth           // OUT: authHMAC
1840
                        )
1841
{
1842
    // Fill in policy/HMAC based session response.
1843
    SESSION     *session = SessionGet(s_sessionHandles[sessionIndex]);
963✔
1844
    // If the session is a policy session with isPasswordNeeded SET, the
1845
    // authorization field is empty.
1846
    if(HandleGetType(s_sessionHandles[sessionIndex]) == TPM_HT_POLICY_SESSION
963✔
1847
       && session->attributes.isPasswordNeeded == SET)
162✔
1848
        auth->t.size = 0;
4✔
1849
    else
1850
        // Compute response HMAC.
1851
        ComputeResponseHMAC(command, sessionIndex, session, auth);
959✔
1852
    UpdateInternalSession(session, sessionIndex);
963✔
1853
    return &session->nonceTPM;
963✔
1854
}
1855
/* 6.4.5.11 UpdateAllNonceTPM() */
1856
/* Updates TPM nonce for all sessions in command. */
1857
static void
1858
UpdateAllNonceTPM(
4,976✔
1859
                  COMMAND         *command        // IN: controlling structure
1860
                  )
1861
{
1862
    UINT32      i;
4,976✔
1863
    SESSION     *session;
4,976✔
1864
    for(i = 0; i < command->sessionNum; i++)
10,392✔
1865
        {
1866
            // If not a PW session, compute the new nonceTPM.
1867
            if(s_sessionHandles[i] != TPM_RS_PW)
5,416✔
1868
                {
1869
                    session = SessionGet(s_sessionHandles[i]);
963✔
1870
                    // Update nonceTPM in both internal session and response.
1871
                    CryptRandomGenerate(session->nonceTPM.t.size,
963✔
1872
                                        session->nonceTPM.t.buffer);
963✔
1873
                }
1874
        }
1875
    return;
4,976✔
1876
}
1877
/* 6.4.5.12 BuildResponseSession() */
1878
/* Function to build Session buffer in a response. The authorization data is added to the end of
1879
   command->responseBuffer. The size of the authorization area is accumulated in
1880
   command->authSize. When this is called, command->responseBuffer is pointing at the next location
1881
   in the response buffer to be filled. This is where the authorization sessions will go, if
1882
   any. command->parameterSize is the number of bytes that have been marshaled as parameters in the
1883
   output buffer. */
1884
TPM_RC
1885
BuildResponseSession(
13,916✔
1886
                     COMMAND         *command        // IN: structure that has relevant command
1887
                     //     information
1888
                     )
1889
{
1890
    TPM_RC result = TPM_RC_SUCCESS;
13,916✔
1891
    pAssert(command->authSize == 0);
13,916✔
1892
    // Reset the parameter buffer to point to the start of the parameters so that
1893
    // there is a starting point for any rpHash that might be generated and so there
1894
    // is a place where parameter encryption would start
1895
    command->parameterBuffer = command->responseBuffer - command->parameterSize;
13,916✔
1896
    // Session nonces should be updated before parameter encryption
1897
    if(command->tag == TPM_ST_SESSIONS)
13,916✔
1898
        {
1899
            UpdateAllNonceTPM(command);
4,976✔
1900
            // Encrypt first parameter if applicable. Parameter encryption should
1901
            // happen after nonce update and before any rpHash is computed.
1902
            // If the encrypt session is associated with a handle, the authValue of
1903
            // this handle will be concatenated with sessionKey to generate
1904
            // encryption key, no matter if the handle is the session bound entity
1905
            // or not. The authValue is added to sessionKey only when the authValue
1906
            // is available.
1907
            if(s_encryptSessionIndex != UNDEFINED_INDEX)
4,976✔
1908
                {
1909
                    UINT32          size;
152✔
1910
                    TPM2B_AUTH      extraKey;
152✔
1911
                    extraKey.b.size = 0;
152✔
1912
                    // If this is an authorization session, include the authValue in the
1913
                    // generation of the encryption key
1914
                    if(s_associatedHandles[s_encryptSessionIndex] != TPM_RH_UNASSIGNED)
152✔
1915
                        {
1916
                            EntityGetAuthValue(s_associatedHandles[s_encryptSessionIndex],
102✔
1917
                                               &extraKey);
1918
                        }
1919
                    size = EncryptSize(command->index);
152✔
1920
                    // This function operates on internally-generated data that is
1921
                    // expected to be well-formed for parameter encryption.
1922
                    // In the event that there is a bug elsewhere in the code and the
1923
                    // input data is not well-formed, CryptParameterEncryption will
1924
                    // put the TPM into failure mode instead of allowing the out-of-
1925
                    // band write.
1926
                    CryptParameterEncryption(s_sessionHandles[s_encryptSessionIndex],
152✔
1927
                                             &s_nonceCaller[s_encryptSessionIndex].b,
152✔
1928
                                             command->parameterSize,
1929
                                             (UINT16)size,
1930
                                             &extraKey,
1931
                                             command->parameterBuffer);
1932
                    if(g_inFailureMode)
152✔
1933
                        {
1934
                            result = TPM_RC_FAILURE;
×
1935
                            goto Cleanup;
×
1936
                        }
1937
                }
1938
        }
1939
    // Audit sessions should be processed regardless of the tag because
1940
    // a command with no session may cause a change of the exclusivity state.
1941
    UpdateAuditSessionStatus(command);
13,916✔
1942
#if CC_GetCommandAuditDigest
1943
    // Command Audit
1944
    if(CommandAuditIsRequired(command->index))
13,916✔
1945
        CommandAudit(command);
17✔
1946
#endif
1947
    // Process command with sessions.
1948
    if(command->tag == TPM_ST_SESSIONS)
13,916✔
1949
        {
1950
            UINT32           i;
4,976✔
1951
            pAssert(command->sessionNum > 0);
4,976✔
1952
            // Iterate over each session in the command session area, and create
1953
            // corresponding sessions for response.
1954
            for(i = 0; i < command->sessionNum; i++)
10,392✔
1955
                {
1956
                    TPM2B_NONCE     *nonceTPM;
5,416✔
1957
                    TPM2B_DIGEST     responseAuth;
5,416✔
1958
                    // Make sure that continueSession is SET on any Password session.
1959
                    // This makes it marginally easier for the management software
1960
                    // to keep track of the closed sessions.
1961
                    if(s_sessionHandles[i] == TPM_RS_PW)
5,416✔
1962
                        {
1963
                            SET_ATTRIBUTE(s_attributes[i], TPMA_SESSION, continueSession);
4,453✔
1964
                            responseAuth.t.size = 0;
4,453✔
1965
                            nonceTPM = (TPM2B_NONCE *)&responseAuth;
4,453✔
1966
                        }
1967
                    else
1968
                        {
1969
                            // Compute the response HMAC and get a pointer to the nonce used.
1970
                            // This function will also update the values if needed. Note, the
1971
                            nonceTPM = BuildSingleResponseAuth(command, i, &responseAuth);
963✔
1972
                        }
1973
                    command->authSize += TPM2B_NONCE_Marshal(nonceTPM,
5,416✔
1974
                                                             &command->responseBuffer,
1975
                                                             NULL);
1976
                    command->authSize += TPMA_SESSION_Marshal(&s_attributes[i],
5,416✔
1977
                                                              &command->responseBuffer,
1978
                                                              NULL);
1979
                    command->authSize += TPM2B_DIGEST_Marshal(&responseAuth,
5,416✔
1980
                                                              &command->responseBuffer,
1981
                                                              NULL);
1982
                    if(!IS_ATTRIBUTE(s_attributes[i], TPMA_SESSION, continueSession))
5,416✔
1983
                        SessionFlush(s_sessionHandles[i]);
86✔
1984
                }
1985
        }
1986
 Cleanup:
13,916✔
1987
    return result;
13,916✔
1988
}
1989
/* 6.4.5.13 SessionRemoveAssociationToHandle() */
1990
/* This function deals with the case where an entity associated with an authorization is deleted
1991
   during command processing. The primary use of this is to support UndefineSpaceSpecial(). */
1992
void
1993
SessionRemoveAssociationToHandle(
2✔
1994
                                 TPM_HANDLE       handle
1995
                                 )
1996
{
1997
    UINT32               i;
2✔
1998
    for(i = 0; i < MAX_SESSION_NUM; i++)
8✔
1999
        {
2000
            if(s_associatedHandles[i] == handle)
6✔
2001
                {
2002
                    s_associatedHandles[i] = TPM_RH_NULL;
2✔
2003
                }
2004
        }
2005
}
2✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc