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

stefanberger / libtpms / 2735

pending completion
2735

cron

travis-ci-com

stefanberger
tpm2: rev164: Synchronize _TPM_Init() with upstream

Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>

1 of 1 new or added line in 1 file covered. (100.0%)

33726 of 44191 relevant lines covered (76.32%)

93553.55 hits per line

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

91.93
/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,452✔
78
             TPM_HANDLE       handle         // IN: entity handle
79
             )
80
{
81
    BOOL        result = FALSE;
6,452✔
82
    //
83
    switch(HandleGetType(handle))
6,452✔
84
        {
85
          case TPM_HT_PERMANENT:
3,964✔
86
            // All permanent handles, other than TPM_RH_LOCKOUT, are exempt from
87
            // DA protection.
88
            result = (handle != TPM_RH_LOCKOUT);
3,964✔
89
            break;
3,964✔
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,715✔
93
              {
94
                  TPMA_OBJECT     attributes = ObjectGetPublicAttributes(handle);
1,715✔
95
                  result = IS_ATTRIBUTE(attributes, TPMA_OBJECT, noDA);
1,715✔
96
                  break;
1,715✔
97
              }
98
          case TPM_HT_NV_INDEX:
488✔
99
              {
100
                  NV_INDEX            *nvIndex = NvGetIndexInfo(handle, NULL);
488✔
101
                  result = IS_ATTRIBUTE(nvIndex->publicArea.attributes, TPMA_NV, NO_DA);
488✔
102
                  break;
488✔
103
              }
104
          case TPM_HT_PCR:
285✔
105
            // PCRs are always exempted from DA.
106
            result = TRUE;
285✔
107
            break;
285✔
108
          default:
109
            break;
110
        }
111
    return result;
6,452✔
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(
66✔
119
                 UINT32           sessionIndex
120
                 )
121
{
122
    TPM_HANDLE       handle = s_associatedHandles[sessionIndex];
66✔
123
    TPM_HANDLE       sessionHandle = s_sessionHandles[sessionIndex];
66✔
124
    SESSION         *session = NULL;
66✔
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)
66✔
129
        {
130
            if(IsDAExempted(handle))
56✔
131
                return TPM_RC_BAD_AUTH;
132
        }
133
    else
134
        {
135
            session = SessionGet(sessionHandle);
10✔
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)
10✔
141
                handle = TPM_RH_LOCKOUT;
×
142
            if(session->attributes.isDaBound == CLEAR
10✔
143
               && (IsDAExempted(handle) || session->attributes.includeAuth == CLEAR))
10✔
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)
13✔
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)
9✔
168
                {
169
                    gp.failedTries++;
9✔
170
                    if(NV_IS_AVAILABLE)
9✔
171
                        // Record changes to NV. NvWrite will SET g_updateNV
172
                        NV_SYNC_PERSISTENT(failedTries);
9✔
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);
13✔
180
    return TPM_RC_AUTH_FAIL;
13✔
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(
690✔
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
690✔
194
    // If the session is not bound, return FALSE.
195
    if(session->attributes.isBound)
690✔
196
        {
197
            // Compute the bind value for the entity.
198
            SessionComputeBoundEntity(associatedHandle, &entity);
57✔
199
            // Compare to the bind value in the session.
200
            return MemoryEqual2B(&entity.b, &session->u1.boundEntity.b);
57✔
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,340✔
221
                        COMMAND_INDEX    commandIndex,  // IN: command index
222
                        UINT32           sessionIndex   // IN: session index
223
                        )
224
{
225
    AUTH_ROLE       role = CommandAuthRole(commandIndex, sessionIndex);
6,340✔
226
    TPM_HT          type = HandleGetType(s_associatedHandles[sessionIndex]);
6,340✔
227
    if(role == AUTH_DUP)
6,340✔
228
        return TRUE;
229
    if(role == AUTH_ADMIN)
6,340✔
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)
218✔
236
                {
237
                    OBJECT      *object = HandleToObject(s_associatedHandles[sessionIndex]);
207✔
238
                    if(!IS_ATTRIBUTE(object->publicArea.objectAttributes, TPMA_OBJECT,
207✔
239
                                     adminWithPolicy))
240
                        return FALSE;
241
                }
242
            return TRUE;
11✔
243
        }
244
    if(type == TPM_HT_PCR)
6,122✔
245
        {
246
            if(PCRPolicyIsAvailable(s_associatedHandles[sessionIndex]))
273✔
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,305✔
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,305✔
275
    //
276
    switch(HandleGetType(handle))
6,305✔
277
        {
278
          case TPM_HT_PERMANENT:
3,907✔
279
            switch(handle)
3,907✔
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,907✔
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,907✔
299
                    break;
3,907✔
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,706✔
314
            // A persistent object has already been loaded and the internal
315
            // handle changed.
316
              {
317
                  OBJECT          *object;
1,706✔
318
                  TPMA_OBJECT      attributes;
1,706✔
319
                  //
320
                  object = HandleToObject(handle);
1,706✔
321
                  attributes = object->publicArea.objectAttributes;
1,706✔
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,706✔
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,629✔
336
                     && (IS_ATTRIBUTE(attributes, TPMA_OBJECT, userWithAuth)
1,629✔
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:
419✔
343
            // NV Index.
344
              {
345
                  NV_REF           locator;
419✔
346
                  NV_INDEX        *nvIndex = NvGetIndexInfo(handle, &locator);
419✔
347
                  TPMA_NV          nvAttributes;
419✔
348
                  //
349
                  pAssert(nvIndex != 0);
419✔
350
                  nvAttributes = nvIndex->publicArea.attributes;
419✔
351
                  if(IsWriteOperation(commandIndex))
419✔
352
                      {
353
                          // AuthWrite can't be set for a PIN index
354
                          if(IS_ATTRIBUTE(nvAttributes, TPMA_NV, AUTHWRITE))
179✔
355
                              result = TRUE;
175✔
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)
240✔
363
                             || IsNvPinPassIndex(nvAttributes))
240✔
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))
208✔
375
                              result = TRUE;
204✔
376
                      }
377
              }
378
              break;
418✔
379
          case TPM_HT_PCR:
273✔
380
            // PCR handle.
381
            // authValue is always allowed for PCR
382
            result = TRUE;
273✔
383
            break;
273✔
384
          default:
385
            // Otherwise, authValue is not available
386
            break;
387
        }
388
    return result;
6,305✔
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(
192✔
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;
192✔
406
    //
407
    switch(HandleGetType(handle))
192✔
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:
152✔
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);
152✔
447
                  // Policy authorization is not available for an object with only
448
                  // public portion loaded.
449
                  if(object->attributes.publicOnly == CLEAR)
152✔
450
                      {
451
                          // Policy authorization is always available for an object but
452
                          // is never available for a sequence.
453
                          if(!ObjectIsSequence(object))
152✔
454
                              result = TRUE;
152✔
455
                      }
456
                  break;
457
              }
458
          case TPM_HT_NV_INDEX:
33✔
459
            // An NV Index.
460
              {
461
                  NV_INDEX         *nvIndex = NvGetIndexInfo(handle, NULL);
33✔
462
                  TPMA_NV           nvAttributes = nvIndex->publicArea.attributes;
33✔
463
                  //
464
                  // If the policy size is not zero, check if policy can be used.
465
                  if(nvIndex->publicArea.authPolicy.t.size != 0)
33✔
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))
33✔
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;
192✔
495
}
496
/* 6.4.4 Session Parsing Functions */
497
/* 6.4.4.1 ClearCpRpHashes() */
498

499
void
500
ClearCpRpHashes(
15,895✔
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)
15,895✔
510
#define CLEAR_RP_HASH(HASH, Hash)     command->Hash##RpHash.b.size = 0;
511
        FOR_EACH_HASH(CLEAR_RP_HASH)
15,895✔
512
}
15,895✔
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(
962✔
518
                 COMMAND         *command,
519
                 TPMI_ALG_HASH    hashAlg
520
                 )
521
{
522
    TPM2B_DIGEST     *retVal;
962✔
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)
962✔
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)
962✔
538
          default:
539
            retVal = NULL;
540
            break;
541
        }
542
    return retVal;
962✔
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(
943✔
549
                 COMMAND         *command,
550
                 TPMI_ALG_HASH    hashAlg
551
                 )
552
{
553
    TPM2B_DIGEST    *retVal;
943✔
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)
943✔
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)
943✔
569
          default:
570
            retVal = NULL;
571
            break;
572
        }
573
    return retVal;
943✔
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(
911✔
580
              COMMAND         *command,       // IN: command parsing structure
581
              TPMI_ALG_HASH    hashAlg        // IN: hash algorithm
582
              )
583
{
584
    UINT32               i;
911✔
585
    HASH_STATE           hashState;
911✔
586
    TPM2B_NAME           name;
911✔
587
    TPM2B_DIGEST        *cpHash;
911✔
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);
911✔
596
    if(cpHash->t.size == 0)
911✔
597
        {
598
            cpHash->t.size = CryptHashStart(&hashState, hashAlg);
636✔
599
            //  Add commandCode.
600
            CryptDigestUpdateInt(&hashState, sizeof(TPM_CC), command->code);
636✔
601
            //  Add authNames for each of the handles.
602
            for(i = 0; i < command->handleNum; i++)
2,222✔
603
                CryptDigestUpdate2B(&hashState, &EntityGetName(command->handles[i],
950✔
604
                                                               &name)->b);
605
            //  Add the parameters.
606
            CryptDigestUpdate(&hashState, command->parameterSize,
636✔
607
                              command->parameterBuffer);
636✔
608
            //  Complete the hash.
609
            CryptHashEnd2B(&hashState, &cpHash->b);
636✔
610
        }
611
    return cpHash;
911✔
612
}
613
/* 6.4.4.5 GetCpHash() */
614
/* This function is used to access a precomputed cpHash. */
615
static TPM2B_DIGEST *
616
GetCpHash(
51✔
617
          COMMAND         *command,
618
          TPMI_ALG_HASH    hashAlg
619
          )
620
{
621
    TPM2B_DIGEST        *cpHash = GetCpHashPointer(command, hashAlg);
51✔
622
    //
623
    pAssert(cpHash->t.size != 0);
51✔
624
    return cpHash;
51✔
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,601✔
705
                   UINT32           sessionIndex   // IN: index of session to be processed
706
                   )
707
{
708
    TPM2B_AUTH      authValue;
5,601✔
709
    TPM_HANDLE      associatedHandle = s_associatedHandles[sessionIndex];
5,601✔
710
    // Strip trailing zeros from the password.
711
    MemoryRemoveTrailingZeros(&s_inputAuthValues[sessionIndex]);
5,601✔
712
    // Get the authValue with trailing zeros removed
713
    EntityGetAuthValue(associatedHandle, &authValue);
5,601✔
714
    // Success if the values are identical.
715
    if(MemoryEqual2B(&s_inputAuthValues[sessionIndex].b, &authValue.b))
5,601✔
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);
57✔
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(
928✔
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));
928✔
735
    TPM2B_KEY        key;
928✔
736
    BYTE             marshalBuffer[sizeof(TPMA_SESSION)];
928✔
737
    BYTE            *buffer;
928✔
738
    UINT32           marshalSize;
928✔
739
    HMAC_STATE       hmacState;
928✔
740
    TPM2B_NONCE     *nonceDecrypt;
928✔
741
    TPM2B_NONCE     *nonceEncrypt;
928✔
742
    SESSION         *session;
928✔
743
    nonceDecrypt = NULL;
928✔
744
    nonceEncrypt = NULL;
928✔
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
928✔
750
       && s_associatedHandles[sessionIndex] != TPM_RH_UNASSIGNED)
688✔
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
677✔
755
               && s_decryptSessionIndex != sessionIndex)
156✔
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
677✔
764
               && s_encryptSessionIndex != sessionIndex
151✔
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]);
928✔
775
    // Generate HMAC key.
776
    MemoryCopy2B(&key.b, &session->sessionKey.b, sizeof(key.t.buffer));
928✔
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)
928✔
785
        {
786
            TPM2B_AUTH          authValue;
653✔
787
            // Get the entity authValue with trailing zeros removed
788
            EntityGetAuthValue(s_associatedHandles[sessionIndex], &authValue);
653✔
789
            // add the authValue to the HMAC key
790
            MemoryConcat2B(&key.b, &authValue.b, sizeof(key.t.buffer));
653✔
791
        }
792
    // if the HMAC key size is 0, a NULL string HMAC is allowed
793
    if(key.t.size == 0
928✔
794
       && s_inputAuthValues[sessionIndex].t.size == 0)
215✔
795
        {
796
            hmac->t.size = 0;
120✔
797
            return hmac;
120✔
798
        }
799
    // Start HMAC
800
    hmac->t.size = CryptHmacStart2B(&hmacState, session->authHashAlg, &key.b);
808✔
801
    //  Add cpHash
802
    CryptDigestUpdate2B(&hmacState.hashState,
1,616✔
803
                        &ComputeCpHash(command, session->authHashAlg)->b);
808✔
804
    //  Add nonces as required
805
    CryptDigestUpdate2B(&hmacState.hashState, &s_nonceCaller[sessionIndex].b);
808✔
806
    CryptDigestUpdate2B(&hmacState.hashState, &session->nonceTPM.b);
808✔
807
    if(nonceDecrypt != NULL)
808✔
808
        CryptDigestUpdate2B(&hmacState.hashState, &nonceDecrypt->b);
84✔
809
    if(nonceEncrypt != NULL)
808✔
810
        CryptDigestUpdate2B(&hmacState.hashState, &nonceEncrypt->b);
64✔
811
    //  Add sessionAttributes
812
    buffer = marshalBuffer;
808✔
813
    marshalSize = TPMA_SESSION_Marshal(&(s_attributes[sessionIndex]),
808✔
814
                                       &buffer, NULL);
815
    CryptDigestUpdate(&hmacState.hashState, marshalSize, marshalBuffer);
808✔
816
    // Complete the HMAC computation
817
    CryptHmacEnd2B(&hmacState, &hmac->b);
808✔
818
    return hmac;
808✔
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(
928✔
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
928✔
837
    // Compute authHMAC
838
   ComputeCommandHMAC(command, sessionIndex, &hmac);
928✔
839
    // Compare the input HMAC with the authHMAC computed above.
840
    if(!MemoryEqual2B(&s_inputAuthValues[sessionIndex].b, &hmac.b))
928✔
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);
9✔
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(
192✔
872
                       COMMAND         *command,       // IN: primary parsing structure
873
                       UINT32           sessionIndex   // IN: index of session to be processed
874
                       )
875
{
876
    SESSION             *session;
192✔
877
    TPM2B_DIGEST         authPolicy;
192✔
878
    TPMI_ALG_HASH        policyAlg;
192✔
879
    UINT8                locality;
192✔
880
    // Initialize pointer to the authorization session.
881
    session = SessionGet(s_sessionHandles[sessionIndex]);
192✔
882
    // If the command is TPM2_PolicySecret(), make sure that
883
    // either password or authValue is required
884
    if(command->code == TPM_CC_PolicySecret
192✔
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))
192✔
890
        return TPM_RC_PCR_CHANGED;
891
    // Get authPolicy.
892
    policyAlg = EntityGetAuthPolicy(s_associatedHandles[sessionIndex],
191✔
893
                                    &authPolicy);
894
    // Compare authPolicy.
895
    if(!MemoryEqual2B(&session->u2.policyDigest.b, &authPolicy.b))
191✔
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)
157✔
900
        return TPM_RC_POLICY_FAIL;
901
    // Compare timeout.
902
    if(session->timeout != 0)
157✔
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)
157✔
915
        {
916
            if(session->commandCode != command->code)
84✔
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);
73✔
924
            if(role == AUTH_ADMIN || role == AUTH_DUP)
73✔
925
                return TPM_RC_POLICY_FAIL;
926
        }
927
    // Check command locality.
928
    {
929
        BYTE         sessionLocality[sizeof(TPMA_LOCALITY)];
154✔
930
        BYTE        *buffer = sessionLocality;
154✔
931
        // Get existing locality setting in canonical form
932
        sessionLocality[0] = 0;
154✔
933
        TPMA_LOCALITY_Marshal(&session->commandLocality, &buffer, NULL);
154✔
934
        // See if the locality has been set
935
        if(sessionLocality[0] != 0)
154✔
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
154✔
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)
154✔
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)
153✔
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,307✔
1005
                    COMMAND         *command        // IN: main parsing structure for command
1006
                    )
1007
{
1008
    int              i;
6,307✔
1009
    TPM_RC           result;
6,307✔
1010
    SESSION         *session;
6,307✔
1011
    TPMA_SESSION     sessionAttributes;
6,307✔
1012
    TPM_HT           sessionType;
6,307✔
1013
    INT32            sessionIndex;
6,307✔
1014
    TPM_RC           errorIndex;
6,307✔
1015
    s_decryptSessionIndex = UNDEFINED_INDEX;
6,307✔
1016
    s_encryptSessionIndex = UNDEFINED_INDEX;
6,307✔
1017
    s_auditSessionIndex = UNDEFINED_INDEX;
6,307✔
1018
    for(sessionIndex = 0; command->authSize > 0; sessionIndex++)
13,003✔
1019
        {
1020
            errorIndex = TPM_RC_S + g_rcIndex[sessionIndex];
6,746✔
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,746✔
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,742✔
1029
            // First parameter: Session handle.
1030
            result = TPMI_SH_AUTH_SESSION_Unmarshal(
13,484✔
1031
                                                    &s_sessionHandles[sessionIndex],
6,742✔
1032
                                                    &command->parameterBuffer,
1033
                                                    &command->authSize, TRUE);
1034
            if(result != TPM_RC_SUCCESS)
6,742✔
1035
                return result + TPM_RC_S + g_rcIndex[sessionIndex];
16✔
1036
            // Second parameter: Nonce.
1037
            result = TPM2B_NONCE_Unmarshal(&s_nonceCaller[sessionIndex],
6,726✔
1038
                                           &command->parameterBuffer,
1039
                                           &command->authSize);
1040
            if(result != TPM_RC_SUCCESS)
6,726✔
1041
                return result + TPM_RC_S + g_rcIndex[sessionIndex];
8✔
1042
            // Third parameter: sessionAttributes.
1043
            result = TPMA_SESSION_Unmarshal(&s_attributes[sessionIndex],
6,718✔
1044
                                            &command->parameterBuffer,
1045
                                            &command->authSize);
1046
            if(result != TPM_RC_SUCCESS)
6,718✔
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,714✔
1050
                                          &command->parameterBuffer,
1051
                                          &command->authSize);
1052
            if(result != TPM_RC_SUCCESS)
6,714✔
1053
                return result + errorIndex;
4✔
1054
            sessionAttributes = s_attributes[sessionIndex];
6,710✔
1055
            if(s_sessionHandles[sessionIndex] == TPM_RS_PW)
6,710✔
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,727✔
1060
                       || IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, decrypt)
1061
                       || IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, audit)
5,727✔
1062
                       || IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, auditExclusive)
1063
                       || IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, auditReset))
5,723✔
1064
                        return TPM_RCS_ATTRIBUTES + errorIndex;
4✔
1065
                    //     The nonce size must be zero.
1066
                    if(s_nonceCaller[sessionIndex].t.size != 0)
5,723✔
1067
                        return TPM_RCS_NONCE + errorIndex;
4✔
1068
                    continue;
5,719✔
1069
                }
1070
            // For not password sessions...
1071
            // Find out if the session is loaded.
1072
            if(!SessionIsLoaded(s_sessionHandles[sessionIndex]))
983✔
1073
                return TPM_RC_REFERENCE_S0 + sessionIndex;
6✔
1074
            sessionType = HandleGetType(s_sessionHandles[sessionIndex]);
977✔
1075
            session = SessionGet(s_sessionHandles[sessionIndex]);
977✔
1076
            // Check if the session is an HMAC/policy session.
1077
            if((session->attributes.isPolicy == SET
977✔
1078
                && sessionType == TPM_HT_HMAC_SESSION)
192✔
1079
               || (session->attributes.isPolicy == CLEAR
977✔
1080
                   && sessionType == TPM_HT_POLICY_SESSION))
785✔
1081
                return TPM_RCS_HANDLE + errorIndex;
×
1082
            // Check that this handle has not previously been used.
1083
            for(i = 0; i < sessionIndex; i++)
1,302✔
1084
                {
1085
                    if(s_sessionHandles[i] == s_sessionHandles[sessionIndex])
325✔
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))
977✔
1092
                {
1093
                    // Check if the commandCode allows command parameter encryption.
1094
                    if(DecryptSize(command->index) == 0)
156✔
1095
                        return TPM_RCS_ATTRIBUTES + errorIndex;
×
1096
                    // Encrypt attribute can only appear in one session
1097
                    if(s_decryptSessionIndex != UNDEFINED_INDEX)
156✔
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)
156✔
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;
156✔
1105
                }
1106
            // Now process encrypt.
1107
            if(IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, encrypt))
977✔
1108
                {
1109
                    // Check if the commandCode allows response parameter encryption.
1110
                    if(EncryptSize(command->index) == 0)
151✔
1111
                        return TPM_RCS_ATTRIBUTES + errorIndex;
×
1112
                    // Encrypt attribute can only appear in one session.
1113
                    if(s_encryptSessionIndex != UNDEFINED_INDEX)
151✔
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)
151✔
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;
151✔
1121
                }
1122
            // At last process audit.
1123
            if(IS_ATTRIBUTE(sessionAttributes, TPMA_SESSION, audit))
977✔
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;
977✔
1149
        }
1150
    command->sessionNum = sessionIndex;
6,257✔
1151
    return TPM_RC_SUCCESS;
6,257✔
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(
153✔
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)
153✔
1171
        return g_NvStatus;
1172
    // Check if DA info needs to be updated in NV.
1173
    if(s_DAPendingOnNV)
153✔
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)
153✔
1185
        {
1186
            if(gp.lockOutAuthEnabled == FALSE)
75✔
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)
78✔
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)
40✔
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,559✔
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,559✔
1232
    SESSION         *session = NULL;
6,559✔
1233
    TPM_HANDLE       sessionHandle = s_sessionHandles[sessionIndex];
6,559✔
1234
    TPM_HANDLE       associatedHandle = s_associatedHandles[sessionIndex];
6,559✔
1235
    TPM_HT           sessionHandleType = HandleGetType(sessionHandle);
6,559✔
1236
    BOOL             authUsed;
6,559✔
1237

1238
    pAssert(sessionHandle != TPM_RH_UNASSIGNED);
6,559✔
1239
    
1240
    // Take care of physical presence
1241
    if(associatedHandle == TPM_RH_PLATFORM)
6,559✔
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)
854✔
1246
               && !_plat__PhysicalPresenceAsserted())
12✔
1247
                return TPM_RC_PP;
1248
        }
1249
    if(sessionHandle != TPM_RS_PW)
6,547✔
1250
        {
1251
            session = SessionGet(sessionHandle);
882✔
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)
882✔
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 =
192✔
1259
                        session->attributes.isAuthValueNeeded
1260
                        || session->attributes.isPasswordNeeded;
192✔
1261
                }
1262
            else
1263
                {
1264
                    // For an HMAC session, need to check unless the session
1265
                    // is bound.
1266
                    session->attributes.includeAuth =
1,380✔
1267
                        !IsSessionBindEntity(s_associatedHandles[sessionIndex], session);
690✔
1268
                }
1269
            authUsed = session->attributes.includeAuth;
882✔
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)
882✔
1277
        {
1278
            // See if entity is subject to lockout.
1279
            if(!IsDAExempted(associatedHandle))
6,327✔
1280
                {
1281
                    // See if in lockout
1282
                    result = CheckLockedOut(associatedHandle == TPM_RH_LOCKOUT);
153✔
1283
                    if(result != TPM_RC_SUCCESS)
153✔
1284
                        return result;
1285
                }
1286
        }
1287
    // Policy or HMAC+PW?
1288
    if(sessionHandleType != TPM_HT_POLICY_SESSION)
6,499✔
1289
        {
1290
            // for non-policy session make sure that a policy session is not required
1291
            if(IsPolicySessionRequired(command->index, sessionIndex))
6,307✔
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,305✔
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))
192✔
1305
                return TPM_RC_AUTH_UNAVAILABLE;
1306
            // ... and check the policy session.
1307
            result = CheckPolicyAuthSession(command, sessionIndex);
192✔
1308
            if(result != TPM_RC_SUCCESS)
192✔
1309
                return result;
1310
        }
1311
    // Check authorization according to the type
1312
    if((TPM_RS_PW == sessionHandle) || (session->attributes.isPasswordNeeded == SET))
6,434✔
1313
        result = CheckPWAuthSession(sessionIndex);
5,601✔
1314
    else
1315
        result = CheckSessionHMAC(command, sessionIndex);
833✔
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,434✔
1321
        {
1322
            NV_REF           locator;
401✔
1323
            NV_INDEX        *nvIndex = NvGetIndexInfo(associatedHandle, &locator);
401✔
1324
            NV_PIN           pinData;
401✔
1325
            TPMA_NV          nvAttributes;
401✔
1326
            
1327
            pAssert(nvIndex != NULL);
401✔
1328
            nvAttributes = nvIndex->publicArea.attributes;
401✔
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)
401✔
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)
388✔
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(
64✔
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
64✔
1376
       || GetCommandCode(command->index) == TPM_CC_GetCommandAuditDigest)
×
1377
        {
1378
            RETURN_IF_NV_IS_NOT_AVAILABLE;
64✔
1379
        }
1380
    // Make sure that the cpHash is computed for the algorithm
1381
    ComputeCpHash(command, gp.auditHashAlg);
64✔
1382
    return TPM_RC_SUCCESS;
64✔
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,307✔
1394
                   COMMAND         *command        // IN: the structure that contains
1395
                   )
1396
{
1397
    TPM_RC               result;
6,307✔
1398
    UINT32               i;
6,307✔
1399
    INT32                size = 0;
6,307✔
1400
    TPM2B_AUTH           extraKey;
6,307✔
1401
    UINT32               sessionIndex;
6,307✔
1402
    TPM_RC               errorIndex;
6,307✔
1403
    SESSION             *session = NULL;
6,307✔
1404
    // Check if a command allows any session in its session area.
1405
    if(!IsSessionAllowed(command->index))
6,307✔
1406
        return TPM_RC_AUTH_CONTEXT;
1407
    // Default-initialization.
1408
    command->sessionNum = 0;
6,307✔
1409
    result = RetrieveSessionData(command);
6,307✔
1410
    if(result != TPM_RC_SUCCESS)
6,307✔
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,257✔
1415
    // Associate the session with an authorization handle.
1416
    for(i = 0; i < command->handleNum; i++)
14,790✔
1417
        {
1418
            if(CommandAuthRole(command->index, i) != AUTH_NONE)
8,533✔
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(i > (command->sessionNum - 1))
6,565✔
1426
                        return TPM_RC_AUTH_MISSING;
1427
                    // Record the handle associated with the authorization session
1428
                    s_associatedHandles[i] = command->handles[i];
6,565✔
1429
                }
1430
        }
1431
    // Consistency checks are done first to avoid authorization failure when the
1432
    // command will not be executed anyway.
1433
    for(sessionIndex = 0; sessionIndex < command->sessionNum; sessionIndex++)
12,720✔
1434
        {
1435
            errorIndex = TPM_RC_S + g_rcIndex[sessionIndex];
6,666✔
1436
            // PW session must be an authorization session
1437
            if(s_sessionHandles[sessionIndex] == TPM_RS_PW)
6,666✔
1438
                {
1439
                    if(s_associatedHandles[sessionIndex] == TPM_RH_UNASSIGNED)
5,689✔
1440
                        return TPM_RCS_HANDLE + errorIndex;
12✔
1441
                    // a password session can't be audit, encrypt or decrypt
1442
                    if(IS_ATTRIBUTE(s_attributes[sessionIndex], TPMA_SESSION, audit)
5,677✔
1443
                       || IS_ATTRIBUTE(s_attributes[sessionIndex], TPMA_SESSION, encrypt)
1444
                       || IS_ATTRIBUTE(s_attributes[sessionIndex], TPMA_SESSION, decrypt))
5,677✔
1445
                        return TPM_RCS_ATTRIBUTES + errorIndex;
×
1446
                    session = NULL;
1447
                }
1448
            else
1449
                {
1450
                    session = SessionGet(s_sessionHandles[sessionIndex]);
977✔
1451
                    // A trial session can not appear in session area, because it cannot
1452
                    // be used for authorization, audit or encrypt/decrypt.
1453
                    if(session->attributes.isTrialPolicy == SET)
977✔
1454
                        return TPM_RCS_ATTRIBUTES + errorIndex;
×
1455
                    // See if the session is bound to a DA protected entity
1456
                    // NOTE: Since a policy session is never bound, a policy is still
1457
                    // usable even if the object is DA protected and the TPM is in
1458
                    // lockout.
1459
                    if(session->attributes.isDaBound == SET)
977✔
1460
                        {
1461
                            result = CheckLockedOut(session->attributes.isLockoutBound == SET);
×
1462
                            if(result != TPM_RC_SUCCESS)
×
1463
                                return result;
×
1464
                        }
1465
                    // If this session is for auditing, make sure the cpHash is computed.
1466
                    if(IS_ATTRIBUTE(s_attributes[sessionIndex], TPMA_SESSION, audit))
977✔
1467
                        ComputeCpHash(command, session->authHashAlg);
35✔
1468
                }
1469
            // if the session has an associated handle, check the authorization
1470
            if(s_associatedHandles[sessionIndex] != TPM_RH_UNASSIGNED)
6,654✔
1471
                {
1472
                    result = CheckAuthSession(command, sessionIndex);
6,559✔
1473
                    if(result != TPM_RC_SUCCESS)
6,559✔
1474
                        return RcSafeAddToResult(result, errorIndex);
191✔
1475
                }
1476
            else
1477
                {
1478
                    // a session that is not for authorization must either be encrypt,
1479
                    // decrypt, or audit
1480
                    if(!IS_ATTRIBUTE(s_attributes[sessionIndex], TPMA_SESSION, audit)
95✔
1481
                       &&  !IS_ATTRIBUTE(s_attributes[sessionIndex], TPMA_SESSION, encrypt)
1482
                       &&  !IS_ATTRIBUTE(s_attributes[sessionIndex], TPMA_SESSION, decrypt))
84✔
1483
                        return TPM_RCS_ATTRIBUTES + errorIndex;
×
1484
                    // no authValue included in any of the HMAC computations
1485
                    pAssert(session != NULL);
95✔
1486
                    session->attributes.includeAuth = CLEAR;
95✔
1487
                    // check HMAC for encrypt/decrypt/audit only sessions
1488
                    result = CheckSessionHMAC(command, sessionIndex);
95✔
1489
                    if(result != TPM_RC_SUCCESS)
95✔
1490
                        return RcSafeAddToResult(result, errorIndex);
×
1491
                }
1492
        }
1493
#if CC_GetCommandAuditDigest
1494
    // Check if the command should be audited. Need to do this before any parameter
1495
    // encryption so that the cpHash for the audit is correct
1496
    if(CommandAuditIsRequired(command->index))
6,054✔
1497
        {
1498
            result = CheckCommandAudit(command);
64✔
1499
            if(result != TPM_RC_SUCCESS)
64✔
1500
                return result;              // No session number to reference
1501
        }
1502
#endif
1503
    // Decrypt the first parameter if applicable. This should be the last operation
1504
    // in session processing.
1505
    // If the encrypt session is associated with a handle and the handle's
1506
    // authValue is available, then authValue is concatenated with sessionKey to
1507
    // generate encryption key, no matter if the handle is the session bound entity
1508
    // or not.
1509
    if(s_decryptSessionIndex != UNDEFINED_INDEX)
6,054✔
1510
        {
1511
            // If this is an authorization session, include the authValue in the
1512
            // generation of the decryption key
1513
            if(s_associatedHandles[s_decryptSessionIndex] != TPM_RH_UNASSIGNED)
154✔
1514
                {
1515
                    EntityGetAuthValue(s_associatedHandles[s_decryptSessionIndex],
106✔
1516
                                       &extraKey);
1517
                }
1518
            else
1519
                {
1520
                    extraKey.b.size = 0;
48✔
1521
                }
1522
            size = DecryptSize(command->index);
154✔
1523
            result = CryptParameterDecryption(s_sessionHandles[s_decryptSessionIndex],
308✔
1524
                                              &s_nonceCaller[s_decryptSessionIndex].b,
154✔
1525
                                              command->parameterSize, (UINT16)size,
1526
                                              &extraKey,
1527
                                              command->parameterBuffer);
1528
            if(result != TPM_RC_SUCCESS)
154✔
1529
                return RcSafeAddToResult(result,
2✔
1530
                                         TPM_RC_S + g_rcIndex[s_decryptSessionIndex]);
2✔
1531
        }
1532
    return TPM_RC_SUCCESS;
1533
}
1534
/* 6.4.4.17 CheckAuthNoSession() */
1535
/* Function to process a command with no session associated. The function makes sure all the handles
1536
   in the command require no authorization. */
1537
/* Error Returns Meaning */
1538
/* TPM_RC_AUTH_MISSING failure - one or more handles require authorization */
1539
TPM_RC
1540
CheckAuthNoSession(
9,560✔
1541
                   COMMAND         *command        // IN: command parsing structure
1542
                   )
1543
{
1544
    UINT32 i;
9,560✔
1545
    TPM_RC           result = TPM_RC_SUCCESS;
9,560✔
1546
    // Check if the command requires authorization
1547
    for(i = 0; i < command->handleNum; i++)
11,672✔
1548
        {
1549
            if(CommandAuthRole(command->index, i) != AUTH_NONE)
2,136✔
1550
                return TPM_RC_AUTH_MISSING;
1551
        }
1552
#if CC_GetCommandAuditDigest
1553
    // Check if the command should be audited.
1554
    if(CommandAuditIsRequired(command->index))
9,536✔
1555
        {
1556
            result = CheckCommandAudit(command);
×
1557
            if(result != TPM_RC_SUCCESS)
×
1558
                return result;
1559
        }
1560
#endif
1561
    // Initialize number of sessions to be 0
1562
    command->sessionNum = 0;
9,536✔
1563
    return TPM_RC_SUCCESS;
9,536✔
1564
}
1565
/* 6.4.5 Response Session Processing */
1566
/* 6.4.5.1 Introduction */
1567
/* The following functions build the session area in a response and handle the audit sessions (if
1568
   present). */
1569
/* 6.4.5.2 ComputeRpHash() */
1570
/* Function to compute rpHash (Response Parameter Hash). The rpHash is only computed if there is an
1571
   HMAC authorization session and the return code is TPM_RC_SUCCESS. */
1572
static TPM2B_DIGEST *
1573
ComputeRpHash(
943✔
1574
              COMMAND         *command,       // IN: command structure
1575
              TPM_ALG_ID       hashAlg        // IN: hash algorithm to compute rpHash
1576
              )
1577
{
1578
    TPM2B_DIGEST    *rpHash = GetRpHashPointer(command, hashAlg);
943✔
1579
    HASH_STATE       hashState;
943✔
1580
    if(rpHash->t.size == 0)
943✔
1581
        {
1582
            //   rpHash := hash(responseCode || commandCode || parameters)
1583
            // Initiate hash creation.
1584
            rpHash->t.size = CryptHashStart(&hashState, hashAlg);
668✔
1585
            // Add hash constituents.
1586
            CryptDigestUpdateInt(&hashState, sizeof(TPM_RC), TPM_RC_SUCCESS);
668✔
1587
            CryptDigestUpdateInt(&hashState, sizeof(TPM_CC), command->code);
668✔
1588
            CryptDigestUpdate(&hashState, command->parameterSize,
668✔
1589
                              command->parameterBuffer);
668✔
1590
            // Complete hash computation.
1591
            CryptHashEnd2B(&hashState, &rpHash->b);
668✔
1592
        }
1593
    return rpHash;
943✔
1594
}
1595
/* 6.4.5.3 InitAuditSession() */
1596
/* This function initializes the audit data in an audit session. */
1597
static void
1598
InitAuditSession(
21✔
1599
                 SESSION         *session        // session to be initialized
1600
                 )
1601
{
1602
    // Mark session as an audit session.
1603
    session->attributes.isAudit = SET;
21✔
1604
    // Audit session can not be bound.
1605
    session->attributes.isBound = CLEAR;
21✔
1606
    // Size of the audit log is the size of session hash algorithm digest.
1607
    session->u2.auditDigest.t.size = CryptHashGetDigestSize(session->authHashAlg);
21✔
1608
    // Set the original digest value to be 0.
1609
    MemorySet(&session->u2.auditDigest.t.buffer,
21✔
1610
              0,
1611
              session->u2.auditDigest.t.size);
1612
    return;
21✔
1613
}
1614
/* 6.4.5.4 UpdateAuditDigest */
1615
/* Function to update an audit digest */
1616
static void
1617
UpdateAuditDigest(
51✔
1618
                  COMMAND         *command,
1619
                  TPMI_ALG_HASH    hashAlg,
1620
                  TPM2B_DIGEST    *digest
1621
                  )
1622
{
1623
    HASH_STATE       hashState;
51✔
1624
    TPM2B_DIGEST    *cpHash = GetCpHash(command, hashAlg);
51✔
1625
    TPM2B_DIGEST    *rpHash = ComputeRpHash(command, hashAlg);
51✔
1626
    //
1627
    pAssert(cpHash != NULL);
51✔
1628
    // digestNew :=  hash (digestOld || cpHash || rpHash)
1629
    // Start hash computation.
1630
    digest->t.size = CryptHashStart(&hashState, hashAlg);
51✔
1631
    // Add old digest.
1632
    CryptDigestUpdate2B(&hashState, &digest->b);
51✔
1633
    // Add cpHash
1634
    CryptDigestUpdate2B(&hashState, &cpHash->b);
51✔
1635
    // Add rpHash
1636
    CryptDigestUpdate2B(&hashState, &rpHash->b);
51✔
1637
    // Finalize the hash.
1638
    CryptHashEnd2B(&hashState, &digest->b);
51✔
1639
}
51✔
1640
/* 6.4.5.5 Audit() */
1641
/* This function updates the audit digest in an audit session. */
1642
static void
1643
Audit(
35✔
1644
      COMMAND         *command,       // IN: primary control structure
1645
      SESSION         *auditSession   // IN: loaded audit session
1646
      )
1647
{
1648
    UpdateAuditDigest(command, auditSession->authHashAlg,
35✔
1649
                      &auditSession->u2.auditDigest);
1650
    return;
35✔
1651
}
1652
#if CC_GetCommandAuditDigest
1653
/* 6.4.5.6 CommandAudit() */
1654
/* This function updates the command audit digest. */
1655
static void
1656
CommandAudit(
16✔
1657
             COMMAND         *command        // IN:
1658
             )
1659
{
1660
    // If the digest.size is one, it indicates the special case of changing
1661
    // the audit hash algorithm. For this case, no audit is done on exit.
1662
    // NOTE: When the hash algorithm is changed, g_updateNV is set in order to
1663
    // force an update to the NV on exit so that the change in digest will
1664
    // be recorded. So, it is safe to exit here without setting any flags
1665
    // because the digest change will be written to NV when this code exits.
1666
    if(gr.commandAuditDigest.t.size == 1)
16✔
1667
        {
1668
            gr.commandAuditDigest.t.size = 0;
×
1669
            return;
×
1670
        }
1671
    // If the digest size is zero, need to start a new digest and increment
1672
    // the audit counter.
1673
    if(gr.commandAuditDigest.t.size == 0)
16✔
1674
        {
1675
            gr.commandAuditDigest.t.size = CryptHashGetDigestSize(gp.auditHashAlg);
16✔
1676
            MemorySet(gr.commandAuditDigest.t.buffer,
16✔
1677
                      0,
1678
                      gr.commandAuditDigest.t.size);
1679
            // Bump the counter and save its value to NV.
1680
            gp.auditCounter++;
16✔
1681
            NV_SYNC_PERSISTENT(auditCounter);
16✔
1682
        }
1683
    UpdateAuditDigest(command, gp.auditHashAlg, &gr.commandAuditDigest);
16✔
1684
    return;
16✔
1685
}
1686
#endif
1687
/* 6.4.5.7 UpdateAuditSessionStatus() */
1688
/* Function to update the internal audit related states of a session. It */
1689
/* a) initializes the session as audit session and sets it to be exclusive if this is the first time
1690
   it is used for audit or audit reset was requested; */
1691
/* b) reports exclusive audit session; */
1692
/* c) extends audit log; and */
1693
/* d) clears exclusive audit session if no audit session found in the command. */
1694
static void
1695
UpdateAuditSessionStatus(
13,738✔
1696
                         COMMAND         *command        // IN: primary control structure
1697
                         )
1698
{
1699
    UINT32           i;
13,738✔
1700
    TPM_HANDLE       auditSession = TPM_RH_UNASSIGNED;
13,738✔
1701
    // Iterate through sessions
1702
    for(i = 0; i < command->sessionNum; i++)
19,444✔
1703
        {
1704
            SESSION     *session;
5,706✔
1705
            // PW session do not have a loaded session and can not be an audit
1706
            // session either.  Skip it.
1707
            if(s_sessionHandles[i] == TPM_RS_PW)
5,706✔
1708
                continue;
4,811✔
1709
            session = SessionGet(s_sessionHandles[i]);
895✔
1710
            // If a session is used for audit
1711
            if(IS_ATTRIBUTE(s_attributes[i], TPMA_SESSION, audit))
895✔
1712
                {
1713
                    // An audit session has been found
1714
                    auditSession = s_sessionHandles[i];
35✔
1715
                    // If the session has not been an audit session yet, or
1716
                    // the auditSetting bits indicate a reset, initialize it and set
1717
                    // it to be the exclusive session
1718
                    if(session->attributes.isAudit == CLEAR
35✔
1719
                       || IS_ATTRIBUTE(s_attributes[i], TPMA_SESSION, auditReset))
14✔
1720
                        {
1721
                            InitAuditSession(session);
21✔
1722
                            g_exclusiveAuditSession = auditSession;
21✔
1723
                        }
1724
                    else
1725
                        {
1726
                            // Check if the audit session is the current exclusive audit
1727
                            // session and, if not, clear previous exclusive audit session.
1728
                            if(g_exclusiveAuditSession != auditSession)
14✔
1729
                                g_exclusiveAuditSession = TPM_RH_UNASSIGNED;
5✔
1730
                        }
1731
                    // Report audit session exclusivity.
1732
                    if(g_exclusiveAuditSession == auditSession)
35✔
1733
                        {
1734
                            SET_ATTRIBUTE(s_attributes[i], TPMA_SESSION, auditExclusive);
30✔
1735
                        }
1736
                    else
1737
                        {
1738
                            CLEAR_ATTRIBUTE(s_attributes[i], TPMA_SESSION, auditExclusive);
5✔
1739
                        }
1740
                    // Extend audit log.
1741
                    Audit(command, session);
5,741✔
1742
                }
1743
        }
1744
    // If no audit session is found in the command, and the command allows
1745
    // a session then, clear the current exclusive
1746
    // audit session.
1747
    if(auditSession == TPM_RH_UNASSIGNED && IsSessionAllowed(command->index))
13,738✔
1748
        {
1749
            g_exclusiveAuditSession = TPM_RH_UNASSIGNED;
8,747✔
1750
        }
1751
    return;
13,738✔
1752
}
1753
/* 6.4.5.8 ComputeResponseHMAC() */
1754
/* Function to compute HMAC for authorization session in a response. */
1755
static void
1756
ComputeResponseHMAC(
892✔
1757
                    COMMAND         *command,       // IN: command structure
1758
                    UINT32           sessionIndex,  // IN: session index to be processed
1759
                    SESSION         *session,       // IN: loaded session
1760
                    TPM2B_DIGEST    *hmac           // OUT: authHMAC
1761
                    )
1762
{
1763
    TPM2B_TYPE(KEY, (sizeof(AUTH_VALUE) * 2));
892✔
1764
    TPM2B_KEY        key;       // HMAC key
892✔
1765
    BYTE             marshalBuffer[sizeof(TPMA_SESSION)];
892✔
1766
    BYTE            *buffer;
892✔
1767
    UINT32           marshalSize;
892✔
1768
    HMAC_STATE       hmacState;
892✔
1769
    TPM2B_DIGEST    *rpHash = ComputeRpHash(command, session->authHashAlg);
892✔
1770
    // Generate HMAC key
1771
    MemoryCopy2B(&key.b, &session->sessionKey.b, sizeof(key.t.buffer));
892✔
1772
    // Add the object authValue if required
1773
    if(session->attributes.includeAuth == SET)
892✔
1774
        {
1775
            // Note: includeAuth may be SET for a policy that is used in
1776
            // UndefineSpaceSpecial(). At this point, the Index has been deleted
1777
            // so the includeAuth will have no meaning. However, the
1778
            // s_associatedHandles[] value for the session is now set to TPM_RH_NULL so
1779
            // this will return the authValue associated with TPM_RH_NULL and that is
1780
            // and empty buffer.
1781
            TPM2B_AUTH          authValue;
618✔
1782
            // Get the authValue with trailing zeros removed
1783
            EntityGetAuthValue(s_associatedHandles[sessionIndex], &authValue);
618✔
1784
            // Add it to the key
1785
            MemoryConcat2B(&key.b, &authValue.b, sizeof(key.t.buffer));
618✔
1786
        }
1787
    // if the HMAC key size is 0, the response HMAC is computed according to the
1788
    // input HMAC
1789
    if(key.t.size == 0
892✔
1790
       && s_inputAuthValues[sessionIndex].t.size == 0)
213✔
1791
        {
1792
            hmac->t.size = 0;
118✔
1793
            return;
118✔
1794
        }
1795
    // Start HMAC computation.
1796
    hmac->t.size = CryptHmacStart2B(&hmacState, session->authHashAlg, &key.b);
774✔
1797
    // Add hash components.
1798
    CryptDigestUpdate2B(&hmacState.hashState, &rpHash->b);
774✔
1799
    CryptDigestUpdate2B(&hmacState.hashState, &session->nonceTPM.b);
774✔
1800
    CryptDigestUpdate2B(&hmacState.hashState, &s_nonceCaller[sessionIndex].b);
774✔
1801
    // Add session attributes.
1802
    buffer = marshalBuffer;
774✔
1803
    marshalSize = TPMA_SESSION_Marshal(&s_attributes[sessionIndex], &buffer, NULL);
774✔
1804
    CryptDigestUpdate(&hmacState.hashState, marshalSize, marshalBuffer);
774✔
1805
    // Finalize HMAC.
1806
    CryptHmacEnd2B(&hmacState, &hmac->b);
774✔
1807
    return;
774✔
1808
}
1809
/* 6.4.5.9 UpdateInternalSession() */
1810
/* Updates internal sessions: */
1811
/* a) Restarts session time. */
1812
/* b) Clears a policy session since nonce is rolling. */
1813
static void
1814
UpdateInternalSession(
895✔
1815
                      SESSION         *session,       // IN: the session structure
1816
                      UINT32           i              // IN: session number
1817
                      )
1818
{
1819
    // If nonce is rolling in a policy session, the policy related data
1820
    // will be re-initialized.
1821
    if(HandleGetType(s_sessionHandles[i]) == TPM_HT_POLICY_SESSION
895✔
1822
       && IS_ATTRIBUTE(s_attributes[i], TPMA_SESSION, continueSession))
150✔
1823
        {
1824
            // When the nonce rolls it starts a new timing interval for the
1825
            // policy session.
1826
            SessionResetPolicyData(session);
113✔
1827
            SessionSetStartTime(session);
113✔
1828
        }
1829
    return;
895✔
1830
}
1831
/* 6.4.5.10 BuildSingleResponseAuth() */
1832
/* Function to compute response HMAC value for a policy or HMAC session. */
1833
static TPM2B_NONCE *
1834
BuildSingleResponseAuth(
895✔
1835
                        COMMAND         *command,       // IN: command structure
1836
                        UINT32           sessionIndex,  // IN: session index to be processed
1837
                        TPM2B_AUTH      *auth           // OUT: authHMAC
1838
                        )
1839
{
1840
    // Fill in policy/HMAC based session response.
1841
    SESSION     *session = SessionGet(s_sessionHandles[sessionIndex]);
895✔
1842
    // If the session is a policy session with isPasswordNeeded SET, the
1843
    // authorization field is empty.
1844
    if(HandleGetType(s_sessionHandles[sessionIndex]) == TPM_HT_POLICY_SESSION
895✔
1845
       && session->attributes.isPasswordNeeded == SET)
150✔
1846
        auth->t.size = 0;
3✔
1847
    else
1848
        // Compute response HMAC.
1849
        ComputeResponseHMAC(command, sessionIndex, session, auth);
892✔
1850
    UpdateInternalSession(session, sessionIndex);
895✔
1851
    return &session->nonceTPM;
895✔
1852
}
1853
/* 6.4.5.11 UpdateAllNonceTPM() */
1854
/* Updates TPM nonce for all sessions in command. */
1855
static void
1856
UpdateAllNonceTPM(
5,302✔
1857
                  COMMAND         *command        // IN: controlling structure
1858
                  )
1859
{
1860
    UINT32      i;
5,302✔
1861
    SESSION     *session;
5,302✔
1862
    for(i = 0; i < command->sessionNum; i++)
11,008✔
1863
        {
1864
            // If not a PW session, compute the new nonceTPM.
1865
            if(s_sessionHandles[i] != TPM_RS_PW)
5,706✔
1866
                {
1867
                    session = SessionGet(s_sessionHandles[i]);
895✔
1868
                    // Update nonceTPM in both internal session and response.
1869
                    CryptRandomGenerate(session->nonceTPM.t.size,
895✔
1870
                                        session->nonceTPM.t.buffer);
895✔
1871
                }
1872
        }
1873
    return;
5,302✔
1874
}
1875
/* 6.4.5.12 BuildResponseSession() */
1876
/* Function to build Session buffer in a response. The authorization data is added to the end of
1877
   command->responseBuffer. The size of the authorization area is accumulated in
1878
   command->authSize. When this is called, command->responseBuffer is pointing at the next location
1879
   in the response buffer to be filled. This is where the authorization sessions will go, if
1880
   any. command->parameterSize is the number of bytes that have been marshaled as parameters in the
1881
   output buffer. */
1882
TPM_RC
1883
BuildResponseSession(
13,738✔
1884
                     COMMAND         *command        // IN: structure that has relevant command
1885
                     //     information
1886
                     )
1887
{
1888
    TPM_RC result = TPM_RC_SUCCESS;
13,738✔
1889
    pAssert(command->authSize == 0);
13,738✔
1890
    // Reset the parameter buffer to point to the start of the parameters so that
1891
    // there is a starting point for any rpHash that might be generated and so there
1892
    // is a place where parameter encryption would start
1893
    command->parameterBuffer = command->responseBuffer - command->parameterSize;
13,738✔
1894
    // Session nonces should be updated before parameter encryption
1895
    if(command->tag == TPM_ST_SESSIONS)
13,738✔
1896
        {
1897
            UpdateAllNonceTPM(command);
5,302✔
1898
            // Encrypt first parameter if applicable. Parameter encryption should
1899
            // happen after nonce update and before any rpHash is computed.
1900
            // If the encrypt session is associated with a handle, the authValue of
1901
            // this handle will be concatenated with sessionKey to generate
1902
            // encryption key, no matter if the handle is the session bound entity
1903
            // or not. The authValue is added to sessionKey only when the authValue
1904
            // is available.
1905
            if(s_encryptSessionIndex != UNDEFINED_INDEX)
5,302✔
1906
                {
1907
                    UINT32          size;
149✔
1908
                    TPM2B_AUTH      extraKey;
149✔
1909
                    extraKey.b.size = 0;
149✔
1910
                    // If this is an authorization session, include the authValue in the
1911
                    // generation of the encryption key
1912
                    if(s_associatedHandles[s_encryptSessionIndex] != TPM_RH_UNASSIGNED)
149✔
1913
                        {
1914
                            EntityGetAuthValue(s_associatedHandles[s_encryptSessionIndex],
101✔
1915
                                               &extraKey);
1916
                        }
1917
                    size = EncryptSize(command->index);
149✔
1918
                    // This function operates on internally-generated data that is
1919
                    // expected to be well-formed for parameter encryption.
1920
                    // In the event that there is a bug elsewhere in the code and the
1921
                    // input data is not well-formed, CryptParameterEncryption will
1922
                    // put the TPM into failure mode instead of allowing the out-of-
1923
                    // band write.
1924
                    CryptParameterEncryption(s_sessionHandles[s_encryptSessionIndex],
149✔
1925
                                             &s_nonceCaller[s_encryptSessionIndex].b,
149✔
1926
                                             command->parameterSize,
1927
                                             (UINT16)size,
1928
                                             &extraKey,
1929
                                             command->parameterBuffer);
1930
                    if(g_inFailureMode)
149✔
1931
                        {
1932
                            result = TPM_RC_FAILURE;
×
1933
                            goto Cleanup;
×
1934
                        }
1935
                }
1936
        }
1937
    // Audit sessions should be processed regardless of the tag because
1938
    // a command with no session may cause a change of the exclusivity state.
1939
    UpdateAuditSessionStatus(command);
13,738✔
1940
#if CC_GetCommandAuditDigest
1941
    // Command Audit
1942
    if(CommandAuditIsRequired(command->index))
13,738✔
1943
        CommandAudit(command);
16✔
1944
#endif
1945
    // Process command with sessions.
1946
    if(command->tag == TPM_ST_SESSIONS)
13,738✔
1947
        {
1948
            UINT32           i;
5,302✔
1949
            pAssert(command->sessionNum > 0);
5,302✔
1950
            // Iterate over each session in the command session area, and create
1951
            // corresponding sessions for response.
1952
            for(i = 0; i < command->sessionNum; i++)
11,008✔
1953
                {
1954
                    TPM2B_NONCE     *nonceTPM;
5,706✔
1955
                    TPM2B_DIGEST     responseAuth;
5,706✔
1956
                    // Make sure that continueSession is SET on any Password session.
1957
                    // This makes it marginally easier for the management software
1958
                    // to keep track of the closed sessions.
1959
                    if(s_sessionHandles[i] == TPM_RS_PW)
5,706✔
1960
                        {
1961
                            SET_ATTRIBUTE(s_attributes[i], TPMA_SESSION, continueSession);
4,811✔
1962
                            responseAuth.t.size = 0;
4,811✔
1963
                            nonceTPM = (TPM2B_NONCE *)&responseAuth;
4,811✔
1964
                        }
1965
                    else
1966
                        {
1967
                            // Compute the response HMAC and get a pointer to the nonce used.
1968
                            // This function will also update the values if needed. Note, the
1969
                            nonceTPM = BuildSingleResponseAuth(command, i, &responseAuth);
895✔
1970
                        }
1971
                    command->authSize += TPM2B_NONCE_Marshal(nonceTPM,
5,706✔
1972
                                                             &command->responseBuffer,
1973
                                                             NULL);
1974
                    command->authSize += TPMA_SESSION_Marshal(&s_attributes[i],
5,706✔
1975
                                                              &command->responseBuffer,
1976
                                                              NULL);
1977
                    command->authSize += TPM2B_DIGEST_Marshal(&responseAuth,
5,706✔
1978
                                                              &command->responseBuffer,
1979
                                                              NULL);
1980
                    if(!IS_ATTRIBUTE(s_attributes[i], TPMA_SESSION, continueSession))
5,706✔
1981
                        SessionFlush(s_sessionHandles[i]);
80✔
1982
                }
1983
        }
1984
 Cleanup:
13,738✔
1985
    return result;
13,738✔
1986
}
1987
/* 6.4.5.13 SessionRemoveAssociationToHandle() */
1988
/* This function deals with the case where an entity associated with an authorization is deleted
1989
   during command processing. The primary use of this is to support UndefineSpaceSpecial(). */
1990
void
1991
SessionRemoveAssociationToHandle(
2✔
1992
                                 TPM_HANDLE       handle
1993
                                 )
1994
{
1995
    UINT32               i;
2✔
1996
    for(i = 0; i < MAX_SESSION_NUM; i++)
8✔
1997
        {
1998
            if(s_associatedHandles[i] == handle)
6✔
1999
                {
2000
                    s_associatedHandles[i] = TPM_RH_NULL;
2✔
2001
                }
2002
        }
2003
}
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