• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Microsoft Reference Implementation for TPM 2.0
2  *
3  *  The copyright in this software is being made available under the BSD License,
4  *  included below. This software may be subject to other third party and
5  *  contributor rights, including patent rights, and no such rights are granted
6  *  under this license.
7  *
8  *  Copyright (c) Microsoft Corporation
9  *
10  *  All rights reserved.
11  *
12  *  BSD License
13  *
14  *  Redistribution and use in source and binary forms, with or without modification,
15  *  are permitted provided that the following conditions are met:
16  *
17  *  Redistributions of source code must retain the above copyright notice, this list
18  *  of conditions and the following disclaimer.
19  *
20  *  Redistributions in binary form must reproduce the above copyright notice, this
21  *  list of conditions and the following disclaimer in the documentation and/or
22  *  other materials provided with the distribution.
23  *
24  *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS""
25  *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27  *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
28  *  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
29  *  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30  *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
31  *  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32  *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 //** Description
37 
38 // This file contains internal global type definitions and data declarations that
39 // are need between subsystems. The instantiation of global data is in Global.c.
40 // The initialization of global data is in the subsystem that is the primary owner
41 // of the data.
42 //
43 // The first part of this file has the 'typedefs' for structures and other defines
44 // used in many portions of the code. After the 'typedef' section, is a section that
45 // defines global values that are only present in RAM. The next three sections
46 // define the structures for the NV data areas: persistent, orderly, and state
47 // save. Additional sections define the data that is used in specific modules. That
48 // data is private to the module but is collected here to simplify the management
49 // of the instance data.
50 //
51 // All the data is instanced in Global.c.
52 #if !defined _TPM_H_
53 #error "Should only be instanced in TPM.h"
54 #endif
55 
56 
57 //** Includes
58 
59 #ifndef         GLOBAL_H
60 #define         GLOBAL_H
61 
62 _REDUCE_WARNING_LEVEL_(2)
63 #include <string.h>
64 #include <stddef.h>
65 _NORMAL_WARNING_LEVEL_
66 
67 #include "Capabilities.h"
68 #include "TpmTypes.h"
69 #include "CommandAttributes.h"
70 #include "CryptTest.h"
71 #include "BnValues.h"
72 #include "CryptHash.h"
73 #include "CryptSym.h"
74 #include "CryptRand.h"
75 #include "CryptEcc.h"
76 #include "CryptRsa.h"
77 #include "CryptTest.h"
78 #include "TpmError.h"
79 #include "NV.h"
80 #include "ACT.h"
81 
82 //** Defines and Types
83 
84 //*** Size Types
85 // These types are used to differentiate the two different size values used.
86 //
87 // NUMBYTES is used when a size is a number of bytes (usually a TPM2B)
88 typedef UINT16  NUMBYTES;
89 
90 //*** Other Types
91 // An AUTH_VALUE is a BYTE array containing a digest (TPMU_HA)
92 typedef BYTE    AUTH_VALUE[sizeof(TPMU_HA)];
93 
94 // A TIME_INFO is a BYTE array that can contain a TPMS_TIME_INFO
95 typedef BYTE    TIME_INFO[sizeof(TPMS_TIME_INFO)];
96 
97 // A NAME is a BYTE array that can contain a TPMU_NAME
98 typedef BYTE    NAME[sizeof(TPMU_NAME)];
99 
100 // Definition for a PROOF value
101 TPM2B_TYPE(PROOF, PROOF_SIZE);
102 
103 // Definition for a Primary Seed value
104 TPM2B_TYPE(SEED, PRIMARY_SEED_SIZE);
105 
106 
107 // A CLOCK_NONCE is used to tag the time value in the authorization session and
108 // in the ticket computation so that the ticket expires when there is a time
109 // discontinuity. When the clock stops during normal operation, the nonce is
110 // 64-bit value kept in RAM but it is a 32-bit counter when the clock only stops
111 // during power events.
112 #if CLOCK_STOPS
113 typedef UINT64          CLOCK_NONCE;
114 #else
115 typedef UINT32          CLOCK_NONCE;
116 #endif
117 
118 //** Loaded Object Structures
119 //*** Description
120 // The structures in this section define the object layout as it exists in TPM
121 // memory.
122 //
123 // Two types of objects are defined: an ordinary object such as a key, and a
124 // sequence object that may be a hash, HMAC, or event.
125 //
126 //*** OBJECT_ATTRIBUTES
127 // An OBJECT_ATTRIBUTES structure contains the variable attributes of an object.
128 // These properties are not part of the public properties but are used by the
129 // TPM in managing the object. An OBJECT_ATTRIBUTES is used in the definition of
130 // the OBJECT data type.
131 
132 typedef struct
133 {
134     unsigned            publicOnly : 1;     //0) SET if only the public portion of
135                                             //   an object is loaded
136     unsigned            epsHierarchy : 1;   //1) SET if the object belongs to EPS
137                                             //   Hierarchy
138     unsigned            ppsHierarchy : 1;   //2) SET if the object belongs to PPS
139                                             //   Hierarchy
140     unsigned            spsHierarchy : 1;   //3) SET f the object belongs to SPS
141                                             //   Hierarchy
142     unsigned            evict : 1;          //4) SET if the object is a platform or
143                                             //   owner evict object.  Platform-
144                                             //   evict object belongs to PPS
145                                             //   hierarchy, owner-evict object
146                                             //   belongs to SPS or EPS hierarchy.
147                                             //   This bit is also used to mark a
148                                             //   completed sequence object so it
149                                             //   will be flush when the
150                                             //   SequenceComplete command succeeds.
151     unsigned            primary : 1;        //5) SET for a primary object
152     unsigned            temporary : 1;      //6) SET for a temporary object
153     unsigned            stClear : 1;        //7) SET for an stClear object
154     unsigned            hmacSeq : 1;        //8) SET for an HMAC or MAC sequence
155                                             //   object
156     unsigned            hashSeq : 1;        //9) SET for a hash sequence object
157     unsigned            eventSeq : 1;       //10) SET for an event sequence object
158     unsigned            ticketSafe : 1;     //11) SET if a ticket is safe to create
159                                             //    for hash sequence object
160     unsigned            firstBlock : 1;     //12) SET if the first block of hash
161                                             //    data has been received.  It
162                                             //    works with ticketSafe bit
163     unsigned            isParent : 1;       //13) SET if the key has the proper
164                                             //    attributes to be a parent key
165 //   unsigned            privateExp : 1;    //14) SET when the private exponent
166 //                                          //    of an RSA key has been validated.
167     unsigned            not_used_14 : 1;
168     unsigned            occupied : 1;       //15) SET when the slot is occupied.
169     unsigned            derivation : 1;     //16) SET when the key is a derivation
170                                             //        parent
171     unsigned            external : 1;       //17) SET when the object is loaded with
172                                             //    TPM2_LoadExternal();
173 } OBJECT_ATTRIBUTES;
174 
175 #if ALG_RSA
176 // There is an overload of the sensitive.rsa.t.size field of a TPMT_SENSITIVE when an
177 // RSA key is loaded. When the sensitive->sensitive contains an RSA key with all of
178 // the CRT values, then the MSB of the size field will be set to indicate that the
179 // buffer contains all 5 of the CRT private key values.
180 #define     RSA_prime_flag      0x8000
181 #endif
182 
183 
184 //*** OBJECT Structure
185 // An OBJECT structure holds the object public, sensitive, and meta-data
186 // associated. This structure is implementation dependent. For this
187 // implementation, the structure is not optimized for space but rather
188 // for clarity of the reference implementation. Other implementations
189 // may choose to overlap portions of the structure that are not used
190 // simultaneously. These changes would necessitate changes to the source
191 // code but those changes would be compatible with the reference
192 // implementation.
193 
194 typedef struct OBJECT
195 {
196     // The attributes field is required to be first followed by the publicArea.
197     // This allows the overlay of the object structure and a sequence structure
198     OBJECT_ATTRIBUTES   attributes;         // object attributes
199     TPMT_PUBLIC         publicArea;         // public area of an object
200     TPMT_SENSITIVE      sensitive;          // sensitive area of an object
201     TPM2B_NAME          qualifiedName;      // object qualified name
202     TPMI_DH_OBJECT      evictHandle;        // if the object is an evict object,
203                                             // the original handle is kept here.
204                                             // The 'working' handle will be the
205                                             // handle of an object slot.
206     TPM2B_NAME          name;               // Name of the object name. Kept here
207                                             // to avoid repeatedly computing it.
208 } OBJECT;
209 
210 //*** HASH_OBJECT Structure
211 // This structure holds a hash sequence object or an event sequence object.
212 //
213 // The first four components of this structure are manually set to be the same as
214 // the first four components of the object structure. This prevents the object
215 // from being inadvertently misused as sequence objects occupy the same memory as
216 // a regular object. A debug check is present to make sure that the offsets are
217 // what they are supposed to be.
218 // NOTE: In a future version, this will probably be renamed as SEQUENCE_OBJECT
219 typedef struct HASH_OBJECT
220 {
221     OBJECT_ATTRIBUTES   attributes;         // The attributes of the HASH object
222     TPMI_ALG_PUBLIC     type;               // algorithm
223     TPMI_ALG_HASH       nameAlg;            // name algorithm
224     TPMA_OBJECT         objectAttributes;   // object attributes
225 
226     // The data below is unique to a sequence object
227     TPM2B_AUTH          auth;               // authorization for use of sequence
228     union
229     {
230         HASH_STATE      hashState[HASH_COUNT];
231         HMAC_STATE      hmacState;
232     }                   state;
233 } HASH_OBJECT;
234 
235 typedef BYTE  HASH_OBJECT_BUFFER[sizeof(HASH_OBJECT)];
236 
237 //*** ANY_OBJECT
238 // This is the union for holding either a sequence object or a regular object
239 // for ContextSave and ContextLoad.
240 typedef union ANY_OBJECT
241 {
242     OBJECT              entity;
243     HASH_OBJECT         hash;
244 } ANY_OBJECT;
245 
246 typedef BYTE    ANY_OBJECT_BUFFER[sizeof(ANY_OBJECT)];
247 
248 //**AUTH_DUP Types
249 // These values are used in the authorization processing.
250 
251 typedef UINT32          AUTH_ROLE;
252 #define AUTH_NONE       ((AUTH_ROLE)(0))
253 #define AUTH_USER       ((AUTH_ROLE)(1))
254 #define AUTH_ADMIN      ((AUTH_ROLE)(2))
255 #define AUTH_DUP        ((AUTH_ROLE)(3))
256 
257 //** Active Session Context
258 //*** Description
259 // The structures in this section define the internal structure of a session
260 // context.
261 //
262 //*** SESSION_ATTRIBUTES
263 // The attributes in the SESSION_ATTRIBUTES structure track the various properties
264 // of the session. It maintains most of the tracking state information for the
265 // policy session. It is used within the SESSION structure.
266 
267 typedef struct SESSION_ATTRIBUTES
268 {
269     unsigned    isPolicy : 1;           //1) SET if the session may only be used
270                                         //   for policy
271     unsigned    isAudit : 1;            //2) SET if the session is used for audit
272     unsigned    isBound : 1;            //3) SET if the session is bound to with an
273                                         //   entity. This attribute will be CLEAR
274                                         //   if either isPolicy or isAudit is SET.
275     unsigned    isCpHashDefined : 1;    //4) SET if the cpHash has been defined
276                                         //   This attribute is not SET unless
277                                         //   'isPolicy' is SET.
278     unsigned    isAuthValueNeeded : 1;  //5) SET if the authValue is required for
279                                         //   computing the session HMAC. This
280                                         //   attribute is not SET unless 'isPolicy'
281                                         //   is SET.
282     unsigned    isPasswordNeeded : 1;   //6) SET if a password authValue is required
283                                         //   for authorization This attribute is not
284                                         //   SET unless 'isPolicy' is SET.
285     unsigned    isPPRequired : 1;       //7) SET if physical presence is required to
286                                         //   be asserted when the authorization is
287                                         //   checked. This attribute is not SET
288                                         //   unless 'isPolicy' is SET.
289     unsigned    isTrialPolicy : 1;      //8) SET if the policy session is created
290                                         //   for trial of the policy's policyHash
291                                         //   generation. This attribute is not SET
292                                         //   unless 'isPolicy' is SET.
293     unsigned    isDaBound : 1;          //9) SET if the bind entity had noDA CLEAR.
294                                         //   If this is SET, then an authorization
295                                         //   failure using this session will count
296                                         //   against lockout even if the object
297                                         //   being authorized is exempt from DA.
298     unsigned    isLockoutBound : 1;     //10) SET if the session is bound to
299                                         //    lockoutAuth.
300     unsigned    includeAuth : 1;        //11) This attribute is SET when the
301                                         //    authValue of an object is to be
302                                         //    included in the computation of the
303                                         //    HMAC key for the command and response
304                                         //    computations. (was 'requestWasBound')
305     unsigned    checkNvWritten : 1;     //12) SET if the TPMA_NV_WRITTEN attribute
306                                         //    needs to be checked when the policy is
307                                         //    used for authorization for NV access.
308                                         //    If this is SET for any other type, the
309                                         //    policy will fail.
310     unsigned    nvWrittenState : 1;     //13) SET if TPMA_NV_WRITTEN is required to
311                                         //    be SET. Used when 'checkNvWritten' is
312                                         //    SET
313     unsigned    isTemplateSet : 1;      //14) SET if the templateHash needs to be
314                                         //    checked for Create, CreatePrimary, or
315                                         //    CreateLoaded.
316 } SESSION_ATTRIBUTES;
317 
318 //*** SESSION Structure
319 // The SESSION structure contains all the context of a session except for the
320 // associated contextID.
321 //
322 // Note: The contextID of a session is only relevant when the session context
323 // is stored off the TPM.
324 
325 typedef struct SESSION
326 {
327     SESSION_ATTRIBUTES  attributes;         // session attributes
328     UINT32              pcrCounter;         // PCR counter value when PCR is
329                                             // included (policy session)
330                                             // If no PCR is included, this
331                                             // value is 0.
332     UINT64              startTime;          // The value in g_time when the session
333                                             // was started (policy session)
334     UINT64              timeout;            // The timeout relative to g_time
335                                             // There is no timeout if this value
336                                             // is 0.
337     CLOCK_NONCE         epoch;              // The g_clockEpoch value when the
338                                             // session was started. If g_clockEpoch
339                                             // does not match this value when the
340                                             // timeout is used, then
341                                             // then the command will fail.
342     TPM_CC              commandCode;        // command code (policy session)
343     TPM_ALG_ID          authHashAlg;        // session hash algorithm
344     TPMA_LOCALITY       commandLocality;    // command locality (policy session)
345     TPMT_SYM_DEF        symmetric;          // session symmetric algorithm (if any)
346     TPM2B_AUTH          sessionKey;         // session secret value used for
347                                             // this session
348     TPM2B_NONCE         nonceTPM;           // last TPM-generated nonce for
349                                             // generating HMAC and encryption keys
350    union
351     {
352         TPM2B_NAME      boundEntity;        // value used to track the entity to
353                                             // which the session is bound
354 
355         TPM2B_DIGEST    cpHash;             // the required cpHash value for the
356                                             // command being authorized
357         TPM2B_DIGEST    nameHash;           // the required nameHash
358         TPM2B_DIGEST    templateHash;       // the required template for creation
359     } u1;
360 
361     union
362     {
363         TPM2B_DIGEST    auditDigest;        // audit session digest
364         TPM2B_DIGEST    policyDigest;       // policyHash
365     } u2;                                   // audit log and policyHash may
366                                             // share space to save memory
367 } SESSION;
368 
369 #define     EXPIRES_ON_RESET    INT32_MIN
370 #define     TIMEOUT_ON_RESET    UINT64_MAX
371 #define     EXPIRES_ON_RESTART  (INT32_MIN + 1)
372 #define     TIMEOUT_ON_RESTART  (UINT64_MAX - 1)
373 
374 typedef BYTE        SESSION_BUF[sizeof(SESSION)];
375 
376 //*********************************************************************************
377 //** PCR
378 //*********************************************************************************
379 //***PCR_SAVE Structure
380 // The PCR_SAVE structure type contains the PCR data that are saved across power
381 // cycles. Only the static PCR are required to be saved across power cycles. The
382 // DRTM and resettable PCR are not saved. The number of static and resettable PCR
383 // is determined by the platform-specific specification to which the TPM is built.
384 
385 #define PCR_SAVE_SPACE(HASH, Hash)  BYTE Hash[NUM_STATIC_PCR][HASH##_DIGEST_SIZE];
386 
387 typedef struct PCR_SAVE
388 {
389     FOR_EACH_HASH(PCR_SAVE_SPACE)
390 
391     // This counter increments whenever the PCR are updated.
392     // NOTE: A platform-specific specification may designate
393     //       certain PCR changes as not causing this counter
394     //       to increment.
395     UINT32              pcrCounter;
396 } PCR_SAVE;
397 
398 //***PCR_POLICY
399 #if defined NUM_POLICY_PCR_GROUP && NUM_POLICY_PCR_GROUP > 0
400 // This structure holds the PCR policies, one for each group of PCR controlled
401 // by policy.
402 typedef struct PCR_POLICY
403 {
404     TPMI_ALG_HASH       hashAlg[NUM_POLICY_PCR_GROUP];
405     TPM2B_DIGEST        a;
406     TPM2B_DIGEST        policy[NUM_POLICY_PCR_GROUP];
407 } PCR_POLICY;
408 #endif
409 
410 //***PCR_AUTHVALUE
411 // This structure holds the PCR policies, one for each group of PCR controlled
412 // by policy.
413 typedef struct PCR_AUTH_VALUE
414 {
415     TPM2B_DIGEST        auth[NUM_AUTHVALUE_PCR_GROUP];
416 } PCR_AUTHVALUE;
417 
418 
419 
420 //**STARTUP_TYPE
421 // This enumeration is the possible startup types. The type is determined
422 // by the combination of TPM2_ShutDown and TPM2_Startup.
423 typedef enum
424 {
425     SU_RESET,
426     SU_RESTART,
427     SU_RESUME
428 } STARTUP_TYPE;
429 
430 //**NV
431 
432 //***NV_INDEX
433 // The NV_INDEX structure defines the internal format for an NV index.
434 // The 'indexData' size varies according to the type of the index.
435 // In this implementation, all of the index is manipulated as a unit.
436 typedef struct NV_INDEX
437 {
438     TPMS_NV_PUBLIC      publicArea;
439     TPM2B_AUTH          authValue;
440 } NV_INDEX;
441 
442 //*** NV_REF
443 // An NV_REF is an opaque value returned by the NV subsystem. It is used to
444 // reference and NV Index in a relatively efficient way. Rather than having to
445 // continually search for an Index, its reference value may be used. In this
446 // implementation, an NV_REF is a byte pointer that points to the copy of the
447 // NV memory that is kept in RAM.
448 typedef UINT32           NV_REF;
449 
450 typedef BYTE            *NV_RAM_REF;
451 //***NV_PIN
452 // This structure deals with the possible endianess differences between the
453 // canonical form of the TPMS_NV_PIN_COUNTER_PARAMETERS structure and the internal
454 // value. The structures allow the data in a PIN index to be read as an 8-octet
455 // value using NvReadUINT64Data(). That function will byte swap all the values on a
456 // little endian system. This will put the bytes with the 4-octet values in the
457 // correct order but will swap the pinLimit and pinCount values. When written, the
458 // PIN index is simply handled as a normal index with the octets in canonical order.
459 #if BIG_ENDIAN_TPM
460 typedef struct
461 {
462     UINT32      pinCount;
463     UINT32      pinLimit;
464 } PIN_DATA;
465 #else
466 typedef struct
467 {
468     UINT32      pinLimit;
469     UINT32      pinCount;
470 } PIN_DATA;
471 #endif
472 
473 typedef union
474 {
475     UINT64     intVal;
476     PIN_DATA   pin;
477 } NV_PIN;
478 
479 //**COMMIT_INDEX_MASK
480 // This is the define for the mask value that is used when manipulating
481 // the bits in the commit bit array. The commit counter is a 64-bit
482 // value and the low order bits are used to index the commitArray.
483 // This mask value is applied to the commit counter to extract the
484 // bit number in the array.
485 #if     ALG_ECC
486 
487 #define COMMIT_INDEX_MASK ((UINT16)((sizeof(gr.commitArray)*8)-1))
488 
489 #endif
490 
491 //*****************************************************************************
492 //*****************************************************************************
493 //** RAM Global Values
494 //*****************************************************************************
495 //*****************************************************************************
496 //*** Description
497 // The values in this section are only extant in RAM or ROM as constant values.
498 
499 //*** Crypto Self-Test Values
500 EXTERN ALGORITHM_VECTOR     g_implementedAlgorithms;
501 EXTERN ALGORITHM_VECTOR     g_toTest;
502 
503 //*** g_rcIndex[]
504 // This array is used to contain the array of values that are added to a return
505 // code when it is a parameter-, handle-, or session-related error.
506 // This is an implementation choice and the same result can be achieved by using
507 // a macro.
508 #define g_rcIndexInitializer {  TPM_RC_1, TPM_RC_2, TPM_RC_3, TPM_RC_4,             \
509                                 TPM_RC_5, TPM_RC_6, TPM_RC_7, TPM_RC_8,             \
510                                 TPM_RC_9, TPM_RC_A, TPM_RC_B, TPM_RC_C,             \
511                                 TPM_RC_D, TPM_RC_E, TPM_RC_F }
512 EXTERN const UINT16     g_rcIndex[15] INITIALIZER(g_rcIndexInitializer);
513 
514 //*** g_exclusiveAuditSession
515 // This location holds the session handle for the current exclusive audit
516 // session. If there is no exclusive audit session, the location is set to
517 // TPM_RH_UNASSIGNED.
518 EXTERN TPM_HANDLE       g_exclusiveAuditSession;
519 
520 //*** g_time
521 // This is the value in which we keep the current command time. This is initialized
522 // at the start of each command. The time is the accumulated time since the last
523 // time that the TPM's timer was last powered up. Clock is the accumulated time
524 // since the last time that the TPM was cleared. g_time is in mS.
525 EXTERN  UINT64          g_time;
526 
527 //*** g_timeEpoch
528 // This value contains the current clock Epoch. It changes when there is a clock
529 // discontinuity. It may be necessary to place this in NV should the timer be able
530 // to run across a power down of the TPM but not in all cases (e.g. dead battery).
531 // If the nonce is placed in NV, it should go in gp because it should be changing
532 // slowly.
533 #if CLOCK_STOPS
534 EXTERN CLOCK_NONCE       g_timeEpoch;
535 #else
536 #define g_timeEpoch      gp.timeEpoch
537 #endif
538 
539 //*** g_phEnable
540 // This is the platform hierarchy control and determines if the platform hierarchy
541 // is available. This value is SET on each TPM2_Startup(). The default value is
542 // SET.
543 EXTERN BOOL             g_phEnable;
544 
545 //*** g_pcrReConfig
546 // This value is SET if a TPM2_PCR_Allocate command successfully executed since
547 // the last TPM2_Startup(). If so, then the next shutdown is required to be
548 // Shutdown(CLEAR).
549 EXTERN BOOL             g_pcrReConfig;
550 
551 //*** g_DRTMHandle
552 // This location indicates the sequence object handle that holds the DRTM
553 // sequence data. When not used, it is set to TPM_RH_UNASSIGNED. A sequence
554 // DRTM sequence is started on either _TPM_Init or _TPM_Hash_Start.
555 EXTERN TPMI_DH_OBJECT   g_DRTMHandle;
556 
557 //*** g_DrtmPreStartup
558 // This value indicates that an H-CRTM occurred after _TPM_Init but before
559 // TPM2_Startup(). The define for PRE_STARTUP_FLAG is used to add the
560 // g_DrtmPreStartup value to gp_orderlyState at shutdown. This hack is to avoid
561 // adding another NV variable.
562 EXTERN  BOOL            g_DrtmPreStartup;
563 
564 //*** g_StartupLocality3
565 // This value indicates that a TPM2_Startup() occurred at locality 3. Otherwise, it
566 // at locality 0. The define for STARTUP_LOCALITY_3 is to
567 // indicate that the startup was not at locality 0. This hack is to avoid
568 // adding another NV variable.
569 EXTERN  BOOL            g_StartupLocality3;
570 
571 //***TPM_SU_NONE
572 // Part 2 defines the two shutdown/startup types that may be used in
573 // TPM2_Shutdown() and TPM2_Starup(). This additional define is
574 // used by the TPM to indicate that no shutdown was received.
575 // NOTE: This is a reserved value.
576 #define SU_NONE_VALUE           (0xFFFF)
577 #define TPM_SU_NONE             (TPM_SU)(SU_NONE_VALUE)
578 
579 //*** TPM_SU_DA_USED
580 // As with TPM_SU_NONE, this value is added to allow indication that the shutdown
581 // was not orderly and that a DA=protected object was reference during the previous
582 // cycle.
583 #define SU_DA_USED_VALUE    (SU_NONE_VALUE - 1)
584 #define TPM_SU_DA_USED      (TPM_SU)(SU_DA_USED_VALUE)
585 
586 
587 
588 //*** Startup Flags
589 // These flags are included in gp.orderlyState. These are hacks and are being
590 // used to avoid having to change the layout of gp. The PRE_STARTUP_FLAG indicates
591 // that a _TPM_Hash_Start/_Data/_End sequence was received after _TPM_Init but
592 // before TPM2_StartUp(). STARTUP_LOCALITY_3 indicates that the last TPM2_Startup()
593 // was received at locality 3. These flags are only  relevant if after a
594 // TPM2_Shutdown(STATE).
595 #define PRE_STARTUP_FLAG     0x8000
596 #define STARTUP_LOCALITY_3   0x4000
597 
598 #if USE_DA_USED
599 //*** g_daUsed
600 // This location indicates if a DA-protected value is accessed during a boot
601 // cycle. If none has, then there is no need to increment 'failedTries' on the
602 // next non-orderly startup. This bit is merged with gp.orderlyState when
603 // gp.orderly is set to SU_NONE_VALUE
604 EXTERN  BOOL                 g_daUsed;
605 #endif
606 
607 //*** g_updateNV
608 // This flag indicates if NV should be updated at the end of a command.
609 // This flag is set to UT_NONE at the beginning of each command in ExecuteCommand().
610 // This flag is checked in ExecuteCommand() after the detailed actions of a command
611 // complete. If the command execution was successful and this flag is not UT_NONE,
612 // any pending NV writes will be committed to NV.
613 // UT_ORDERLY causes any RAM data to be written to the orderly space for staging
614 // the write to NV.
615 typedef BYTE        UPDATE_TYPE;
616 #define UT_NONE     (UPDATE_TYPE)0
617 #define UT_NV       (UPDATE_TYPE)1
618 #define UT_ORDERLY  (UPDATE_TYPE)(UT_NV + 2)
619 EXTERN UPDATE_TYPE          g_updateNV;
620 
621 //*** g_powerWasLost
622 // This flag is used to indicate if the power was lost. It is SET in _TPM__Init.
623 // This flag is cleared by TPM2_Startup() after all power-lost activities are
624 // completed.
625 // Note: When power is applied, this value can come up as anything. However,
626 // _plat__WasPowerLost() will provide the proper indication in that case. So, when
627 // power is actually lost, we get the correct answer. When power was not lost, but
628 // the power-lost processing has not been completed before the next _TPM_Init(),
629 // then the TPM still does the correct thing.
630 EXTERN BOOL             g_powerWasLost;
631 
632 //*** g_clearOrderly
633 // This flag indicates if the execution of a command should cause the orderly
634 // state to be cleared.  This flag is set to FALSE at the beginning of each
635 // command in ExecuteCommand() and is checked in ExecuteCommand() after the
636 // detailed actions of a command complete but before the check of
637 // 'g_updateNV'. If this flag is TRUE, and the orderly state is not
638 // SU_NONE_VALUE, then the orderly state in NV memory will be changed to
639 // SU_NONE_VALUE or SU_DA_USED_VALUE.
640 EXTERN BOOL             g_clearOrderly;
641 
642 //*** g_prevOrderlyState
643 // This location indicates how the TPM was shut down before the most recent
644 // TPM2_Startup(). This value, along with the startup type, determines if
645 // the TPM should do a TPM Reset, TPM Restart, or TPM Resume.
646 EXTERN TPM_SU           g_prevOrderlyState;
647 
648 //*** g_nvOk
649 // This value indicates if the NV integrity check was successful or not. If not and
650 // the failure was severe, then the TPM would have been put into failure mode after
651 // it had been re-manufactured. If the NV failure was in the area where the state-save
652 // data is kept, then this variable will have a value of FALSE indicating that
653 // a TPM2_Startup(CLEAR) is required.
654 EXTERN BOOL             g_nvOk;
655 // NV availability is sampled as the start of each command and stored here
656 // so that its value remains consistent during the command execution
657 EXTERN TPM_RC           g_NvStatus;
658 
659 //*** g_platformUnique
660 // This location contains the unique value(s) used to identify the TPM. It is
661 // loaded on every _TPM2_Startup()
662 // The first value is used to seed the RNG. The second value is used as a vendor
663 // authValue. The value used by the RNG would be the value derived from the
664 // chip unique value (such as fused) with a dependency on the authorities of the
665 // code in the TPM boot path. The second would be derived from the chip unique value
666 // with a dependency on the details of the code in the boot path. That is, the
667 // first value depends on the various signers of the code and the second depends on
668 // what was signed. The TPM vendor should not be able to know the first value but
669 // they are expected to know the second.
670 EXTERN TPM2B_AUTH       g_platformUniqueAuthorities; // Reserved for RNG
671 
672 EXTERN TPM2B_AUTH       g_platformUniqueDetails;   // referenced by VENDOR_PERMANENT
673 
674 //*********************************************************************************
675 //*********************************************************************************
676 //** Persistent Global Values
677 //*********************************************************************************
678 //*********************************************************************************
679 //*** Description
680 // The values in this section are global values that are persistent across power
681 // events. The lifetime of the values determines the structure in which the value
682 // is placed.
683 
684 //*********************************************************************************
685 //*** PERSISTENT_DATA
686 //*********************************************************************************
687 // This structure holds the persistent values that only change as a consequence
688 // of a specific Protected Capability and are not affected by TPM power events
689 // (TPM2_Startup() or TPM2_Shutdown().
690 typedef struct
691 {
692 //*********************************************************************************
693 //          Hierarchy
694 //*********************************************************************************
695 // The values in this section are related to the hierarchies.
696 
697     BOOL                disableClear;       // TRUE if TPM2_Clear() using
698                                             // lockoutAuth is disabled
699 
700     // Hierarchy authPolicies
701     TPMI_ALG_HASH       ownerAlg;
702     TPMI_ALG_HASH       endorsementAlg;
703     TPMI_ALG_HASH       lockoutAlg;
704     TPM2B_DIGEST        ownerPolicy;
705     TPM2B_DIGEST        endorsementPolicy;
706     TPM2B_DIGEST        lockoutPolicy;
707 
708     // Hierarchy authValues
709     TPM2B_AUTH          ownerAuth;
710     TPM2B_AUTH          endorsementAuth;
711     TPM2B_AUTH          lockoutAuth;
712 
713     // Primary Seeds
714     TPM2B_SEED          EPSeed;
715     TPM2B_SEED          SPSeed;
716     TPM2B_SEED          PPSeed;
717     // Note there is a nullSeed in the state_reset memory.
718 
719     // Hierarchy proofs
720     TPM2B_PROOF          phProof;
721     TPM2B_PROOF          shProof;
722     TPM2B_PROOF          ehProof;
723     // Note there is a nullProof in the state_reset memory.
724 
725 //*********************************************************************************
726 //          Reset Events
727 //*********************************************************************************
728 // A count that increments at each TPM reset and never get reset during the life
729 // time of TPM.  The value of this counter is initialized to 1 during TPM
730 // manufacture process. It is used to invalidate all saved contexts after a TPM
731 // Reset.
732     UINT64              totalResetCount;
733 
734 // This counter increments on each TPM Reset. The counter is reset by
735 // TPM2_Clear().
736     UINT32              resetCount;
737 
738 //*********************************************************************************
739 //          PCR
740 //*********************************************************************************
741 // This structure hold the policies for those PCR that have an update policy.
742 // This implementation only supports a single group of PCR controlled by
743 // policy. If more are required, then this structure would be changed to
744 // an array.
745 #if defined NUM_POLICY_PCR_GROUP && NUM_POLICY_PCR_GROUP > 0
746     PCR_POLICY          pcrPolicies;
747 #endif
748 
749 // This structure indicates the allocation of PCR. The structure contains a
750 // list of PCR allocations for each implemented algorithm. If no PCR are
751 // allocated for an algorithm, a list entry still exists but the bit map
752 // will contain no SET bits.
753     TPML_PCR_SELECTION  pcrAllocated;
754 
755 //*********************************************************************************
756 //          Physical Presence
757 //*********************************************************************************
758 // The PP_LIST type contains a bit map of the commands that require physical
759 // to be asserted when the authorization is evaluated. Physical presence will be
760 // checked if the corresponding bit in the array is SET and if the authorization
761 // handle is TPM_RH_PLATFORM.
762 //
763 // These bits may be changed with TPM2_PP_Commands().
764     BYTE                ppList[(COMMAND_COUNT + 7) / 8];
765 
766 //*********************************************************************************
767 //          Dictionary attack values
768 //*********************************************************************************
769 // These values are used for dictionary attack tracking and control.
770     UINT32              failedTries;        // the current count of unexpired
771                                             // authorization failures
772 
773     UINT32              maxTries;           // number of unexpired authorization
774                                             // failures before the TPM is in
775                                             // lockout
776 
777     UINT32              recoveryTime;       // time between authorization failures
778                                             // before failedTries is decremented
779 
780     UINT32              lockoutRecovery;    // time that must expire between
781                                             // authorization failures associated
782                                             // with lockoutAuth
783 
784     BOOL                lockOutAuthEnabled; // TRUE if use of lockoutAuth is
785                                             // allowed
786 
787 //*****************************************************************************
788 //            Orderly State
789 //*****************************************************************************
790 // The orderly state for current cycle
791     TPM_SU              orderlyState;
792 
793 //*****************************************************************************
794 //           Command audit values.
795 //*****************************************************************************
796     BYTE                auditCommands[((COMMAND_COUNT + 1) + 7) / 8];
797     TPMI_ALG_HASH       auditHashAlg;
798     UINT64              auditCounter;
799 
800 //*****************************************************************************
801 //           Algorithm selection
802 //*****************************************************************************
803 //
804 // The 'algorithmSet' value indicates the collection of algorithms that are
805 // currently in used on the TPM.  The interpretation of value is vendor dependent.
806     UINT32              algorithmSet;
807 
808 //*****************************************************************************
809 //           Firmware version
810 //*****************************************************************************
811 // The firmwareV1 and firmwareV2 values are instanced in TimeStamp.c. This is
812 // a scheme used in development to allow determination of the linker build time
813 // of the TPM. An actual implementation would implement these values in a way that
814 // is consistent with vendor needs. The values are maintained in RAM for simplified
815 // access with a master version in NV.  These values are modified in a
816 // vendor-specific way.
817 
818 // g_firmwareV1 contains the more significant 32-bits of the vendor version number.
819 // In the reference implementation, if this value is printed as a hex
820 // value, it will have the format of YYYYMMDD
821     UINT32              firmwareV1;
822 
823 // g_firmwareV1 contains the less significant 32-bits of the vendor version number.
824 // In the reference implementation, if this value is printed as a hex
825 // value, it will have the format of 00 HH MM SS
826     UINT32              firmwareV2;
827 //*****************************************************************************
828 //           Timer Epoch
829 //*****************************************************************************
830 // timeEpoch contains a nonce that has a vendor=specific size (should not be
831 // less than 8 bytes. This nonce changes when the clock epoch changes. The clock
832 // epoch changes when there is a discontinuity in the timing of the TPM.
833 #if !CLOCK_STOPS
834     CLOCK_NONCE         timeEpoch;
835 #endif
836 
837 } PERSISTENT_DATA;
838 
839 EXTERN PERSISTENT_DATA  gp;
840 
841 //*********************************************************************************
842 //*********************************************************************************
843 //*** ORDERLY_DATA
844 //*********************************************************************************
845 //*********************************************************************************
846 // The data in this structure is saved to NV on each TPM2_Shutdown().
847 typedef struct orderly_data
848 {
849 //*****************************************************************************
850 //           TIME
851 //*****************************************************************************
852 
853 // Clock has two parts. One is the state save part and one is the NV part. The
854 // state save version is updated on each command. When the clock rolls over, the
855 // NV version is updated. When the TPM starts up, if the TPM was shutdown in and
856 // orderly way, then the sClock value is used to initialize the clock. If the
857 // TPM shutdown was not orderly, then the persistent value is used and the safe
858 // attribute is clear.
859 
860     UINT64              clock;              // The orderly version of clock
861     TPMI_YES_NO         clockSafe;          // Indicates if the clock value is
862                                             // safe.
863 
864     // In many implementations, the quality of the entropy available is not that
865     // high. To compensate, the current value of the drbgState can be saved and
866     // restored on each power cycle. This prevents the internal state from reverting
867     // to the initial state on each power cycle and starting with a limited amount
868     // of entropy. By keeping the old state and adding entropy, the entropy will
869     // accumulate.
870     DRBG_STATE          drbgState;
871 
872 // These values allow the accumulation of self-healing time across orderly shutdown
873 // of the TPM.
874 #if ACCUMULATE_SELF_HEAL_TIMER
875     UINT64              selfHealTimer;  // current value of s_selfHealTimer
876     UINT64              lockoutTimer;   // current value of s_lockoutTimer
877     UINT64              time;           // current value of g_time at shutdown
878 #endif // ACCUMULATE_SELF_HEAL_TIMER
879 
880 // These are the ACT Timeout values. They are saved with the other timers
881 #define DefineActData(N)  ACT_STATE      ACT_##N;
882     FOR_EACH_ACT(DefineActData)
883 
884  // this is the 'signaled' attribute data for all the ACT. It is done this way so
885  // that they can be manipulated by ACT number rather than having to access a
886  // structure.
887     UINT16              signaledACT;
888     UINT16              preservedSignaled;
889 } ORDERLY_DATA;
890 
891 #if ACCUMULATE_SELF_HEAL_TIMER
892 #define     s_selfHealTimer     go.selfHealTimer
893 #define     s_lockoutTimer      go.lockoutTimer
894 #endif  // ACCUMULATE_SELF_HEAL_TIMER
895 
896 #  define drbgDefault go.drbgState
897 
898 EXTERN ORDERLY_DATA     go;
899 
900 //*********************************************************************************
901 //*********************************************************************************
902 //*** STATE_CLEAR_DATA
903 //*********************************************************************************
904 //*********************************************************************************
905 // This structure contains the data that is saved on Shutdown(STATE)
906 // and restored on Startup(STATE).  The values are set to their default
907 // settings on any Startup(Clear). In other words, the data is only persistent
908 // across TPM Resume.
909 //
910 // If the comments associated with a parameter indicate a default reset value, the
911 // value is applied on each Startup(CLEAR).
912 
913 typedef struct state_clear_data
914 {
915 //*****************************************************************************
916 //           Hierarchy Control
917 //*****************************************************************************
918     BOOL                shEnable;           // default reset is SET
919     BOOL                ehEnable;           // default reset is SET
920     BOOL                phEnableNV;         // default reset is SET
921     TPMI_ALG_HASH       platformAlg;        // default reset is TPM_ALG_NULL
922     TPM2B_DIGEST        platformPolicy;     // default reset is an Empty Buffer
923     TPM2B_AUTH          platformAuth;       // default reset is an Empty Buffer
924 
925 //*****************************************************************************
926 //           PCR
927 //*****************************************************************************
928 // The set of PCR to be saved on Shutdown(STATE)
929     PCR_SAVE            pcrSave;            // default reset is 0...0
930 
931 // This structure hold the authorization values for those PCR that have an
932 // update authorization.
933 // This implementation only supports a single group of PCR controlled by
934 // authorization. If more are required, then this structure would be changed to
935 // an array.
936     PCR_AUTHVALUE       pcrAuthValues;
937 
938 //*****************************************************************************
939 //           ACT
940 //*****************************************************************************
941 #define DefineActPolicySpace(N)     TPMT_HA     act_##N;
942     FOR_EACH_ACT(DefineActPolicySpace)
943 
944 } STATE_CLEAR_DATA;
945 
946 EXTERN STATE_CLEAR_DATA gc;
947 
948 //*********************************************************************************
949 //*********************************************************************************
950 //***  State Reset Data
951 //*********************************************************************************
952 //*********************************************************************************
953 // This structure contains data is that is saved on Shutdown(STATE) and restored on
954 // the subsequent Startup(ANY). That is, the data is preserved across TPM Resume
955 // and TPM Restart.
956 //
957 // If a default value is specified in the comments this value is applied on
958 // TPM Reset.
959 
960 typedef struct state_reset_data
961 {
962 //*****************************************************************************
963 //          Hierarchy Control
964 //*****************************************************************************
965     TPM2B_PROOF         nullProof;          // The proof value associated with
966                                             // the TPM_RH_NULL hierarchy. The
967                                             // default reset value is from the RNG.
968 
969     TPM2B_SEED          nullSeed;           // The seed value for the TPM_RN_NULL
970                                             // hierarchy. The default reset value
971                                             // is from the RNG.
972 
973 //*****************************************************************************
974 //           Context
975 //*****************************************************************************
976 // The 'clearCount' counter is incremented each time the TPM successfully executes
977 // a TPM Resume. The counter is included in each saved context that has 'stClear'
978 // SET (including descendants of keys that have 'stClear' SET). This prevents these
979 // objects from being loaded after a TPM Resume.
980 // If 'clearCount' is at its maximum value when the TPM receives a Shutdown(STATE),
981 // the TPM will return TPM_RC_RANGE and the TPM will only accept Shutdown(CLEAR).
982     UINT32              clearCount;         // The default reset value is 0.
983 
984     UINT64              objectContextID;    // This is the context ID for a saved
985                                             //  object context. The default reset
986                                             //  value is 0.
987     CONTEXT_SLOT        contextArray[MAX_ACTIVE_SESSIONS];    // This array contains
988                                             // contains the values used to track
989                                             // the version numbers of saved
990                                             // contexts (see
991                                             // Session.c in for details). The
992                                             // default reset value is {0}.
993 
994     CONTEXT_COUNTER     contextCounter;     // This is the value from which the
995                                             // 'contextID' is derived. The
996                                             // default reset value is {0}.
997 
998 //*****************************************************************************
999 //           Command Audit
1000 //*****************************************************************************
1001 // When an audited command completes, ExecuteCommand() checks the return
1002 // value.  If it is TPM_RC_SUCCESS, and the command is an audited command, the
1003 // TPM will extend the cpHash and rpHash for the command to this value. If this
1004 // digest was the Zero Digest before the cpHash was extended, the audit counter
1005 // is incremented.
1006 
1007     TPM2B_DIGEST        commandAuditDigest; // This value is set to an Empty Digest
1008                                             // by TPM2_GetCommandAuditDigest() or a
1009                                             // TPM Reset.
1010 
1011 //*****************************************************************************
1012 //           Boot counter
1013 //*****************************************************************************
1014 
1015     UINT32              restartCount;       // This counter counts TPM Restarts.
1016                                             // The default reset value is 0.
1017 
1018 //*********************************************************************************
1019 //            PCR
1020 //*********************************************************************************
1021 // This counter increments whenever the PCR are updated. This counter is preserved
1022 // across TPM Resume even though the PCR are not preserved. This is because
1023 // sessions remain active across TPM Restart and the count value in the session
1024 // is compared to this counter so this counter must have values that are unique
1025 // as long as the sessions are active.
1026 // NOTE: A platform-specific specification may designate that certain PCR changes
1027 //       do not increment this counter to increment.
1028     UINT32              pcrCounter;         // The default reset value is 0.
1029 
1030 #if     ALG_ECC
1031 
1032 //*****************************************************************************
1033 //         ECDAA
1034 //*****************************************************************************
1035     UINT64              commitCounter;      // This counter increments each time
1036                                             // TPM2_Commit() returns
1037                                             // TPM_RC_SUCCESS. The default reset
1038                                             // value is 0.
1039 
1040     TPM2B_NONCE         commitNonce;        // This random value is used to compute
1041                                             // the commit values. The default reset
1042                                             // value is from the RNG.
1043 
1044 // This implementation relies on the number of bits in g_commitArray being a
1045 // power of 2 (8, 16, 32, 64, etc.) and no greater than 64K.
1046     BYTE                 commitArray[16];   // The default reset value is {0}.
1047 
1048 #endif // ALG_ECC
1049 } STATE_RESET_DATA;
1050 
1051 EXTERN STATE_RESET_DATA gr;
1052 
1053 //** NV Layout
1054 // The NV data organization is
1055 // 1) a PERSISTENT_DATA structure
1056 // 2) a STATE_RESET_DATA structure
1057 // 3) a STATE_CLEAR_DATA structure
1058 // 4) an ORDERLY_DATA structure
1059 // 5) the user defined NV index space
1060 #define NV_PERSISTENT_DATA  (0)
1061 #define NV_STATE_RESET_DATA (NV_PERSISTENT_DATA + sizeof(PERSISTENT_DATA))
1062 #define NV_STATE_CLEAR_DATA (NV_STATE_RESET_DATA + sizeof(STATE_RESET_DATA))
1063 #define NV_ORDERLY_DATA     (NV_STATE_CLEAR_DATA + sizeof(STATE_CLEAR_DATA))
1064 #define NV_INDEX_RAM_DATA   (NV_ORDERLY_DATA + sizeof(ORDERLY_DATA))
1065 #define NV_USER_DYNAMIC     (NV_INDEX_RAM_DATA + sizeof(s_indexOrderlyRam))
1066 #define NV_USER_DYNAMIC_END     NV_MEMORY_SIZE
1067 
1068 //** Global Macro Definitions
1069 // The NV_READ_PERSISTENT and NV_WRITE_PERSISTENT macros are used to access members
1070 // of the PERSISTENT_DATA structure in NV.
1071 #define NV_READ_PERSISTENT(to, from)                \
1072             NvRead(&to, offsetof(PERSISTENT_DATA, from), sizeof(to))
1073 
1074 #define NV_WRITE_PERSISTENT(to, from)               \
1075             NvWrite(offsetof(PERSISTENT_DATA, to), sizeof(gp.to), &from)
1076 
1077 #define CLEAR_PERSISTENT(item)                      \
1078             NvClearPersistent(offsetof(PERSISTENT_DATA, item), sizeof(gp.item))
1079 
1080 #define NV_SYNC_PERSISTENT(item) NV_WRITE_PERSISTENT(item, gp.item)
1081 
1082 // At the start of command processing, the index of the command is determined. This
1083 // index value is used to access the various data tables that contain per-command
1084 // information. There are multiple options for how the per-command tables can be
1085 // implemented. This is resolved in GetClosestCommandIndex().
1086 typedef UINT16      COMMAND_INDEX;
1087 #define UNIMPLEMENTED_COMMAND_INDEX     ((COMMAND_INDEX)(~0))
1088 
1089 typedef struct _COMMAND_FLAGS_
1090 {
1091     unsigned    trialPolicy : 1;    //1) If SET, one of the handles references a
1092                                     //   trial policy and authorization may be
1093                                     //   skipped. This is only allowed for a policy
1094                                     //   command.
1095 } COMMAND_FLAGS;
1096 
1097 // This structure is used to avoid having to manage a large number of
1098 // parameters being passed through various levels of the command input processing.
1099 //
1100 
1101 // The following macros are used to define the space for the CP and RP hashes. Space,
1102 // is provided for each implemented hash algorithm because it is not known what the
1103 // caller may use.
1104 #define CP_HASH(HASH, Hash)           TPM2B_##HASH##_DIGEST   Hash##CpHash;
1105 #define RP_HASH(HASH, Hash)           TPM2B_##HASH##_DIGEST   Hash##RpHash;
1106 
1107 typedef struct COMMAND
1108 {
1109     TPM_ST           tag;               // the parsed command tag
1110     TPM_CC           code;              // the parsed command code
1111     COMMAND_INDEX    index;             // the computed command index
1112     UINT32           handleNum;         // the number of entity handles in the
1113                                         //   handle area of the command
1114     TPM_HANDLE       handles[MAX_HANDLE_NUM]; // the parsed handle values
1115     UINT32           sessionNum;        // the number of sessions found
1116     INT32            parameterSize;     // starts out with the parsed command size
1117                                         // and is reduced and values are
1118                                         // unmarshaled. Just before calling the
1119                                         // command actions, this should be zero.
1120                                         // After the command actions, this number
1121                                         // should grow as values are marshaled
1122                                         // in to the response buffer.
1123     INT32            authSize;          // this is initialized with the parsed size
1124                                         // of authorizationSize field and should
1125                                         // be zero when the authorizations are
1126                                         // parsed.
1127     BYTE            *parameterBuffer;   // input to ExecuteCommand
1128     BYTE            *responseBuffer;    // input to ExecuteCommand
1129     FOR_EACH_HASH(CP_HASH)              // space for the CP hashes
1130     FOR_EACH_HASH(RP_HASH)              // space for the RP hashes
1131 } COMMAND;
1132 
1133 // Global string constants for consistency in KDF function calls.
1134 // These string constants are shared across functions to make sure that they
1135 // are all using consistent string values.
1136 
1137 #define STRING_INITIALIZER(value)   {{sizeof(value), {value}}}
1138 #define TPM2B_STRING(name, value)                                                   \
1139 typedef union name##_ {                                                             \
1140         struct  {                                                                   \
1141             UINT16  size;                                                           \
1142             BYTE    buffer[sizeof(value)];                                          \
1143         } t;                                                                        \
1144         TPM2B   b;                                                                  \
1145     } TPM2B_##name##_;                                                              \
1146 EXTERN  const TPM2B_##name##_      name##_ INITIALIZER(STRING_INITIALIZER(value));  \
1147 EXTERN  const TPM2B               *name INITIALIZER(&name##_.b)
1148 
1149 TPM2B_STRING(PRIMARY_OBJECT_CREATION, "Primary Object Creation");
1150 TPM2B_STRING(CFB_KEY, "CFB");
1151 TPM2B_STRING(CONTEXT_KEY, "CONTEXT");
1152 TPM2B_STRING(INTEGRITY_KEY, "INTEGRITY");
1153 TPM2B_STRING(SECRET_KEY, "SECRET");
1154 TPM2B_STRING(SESSION_KEY, "ATH");
1155 TPM2B_STRING(STORAGE_KEY, "STORAGE");
1156 TPM2B_STRING(XOR_KEY, "XOR");
1157 TPM2B_STRING(COMMIT_STRING, "ECDAA Commit");
1158 TPM2B_STRING(DUPLICATE_STRING, "DUPLICATE");
1159 TPM2B_STRING(IDENTITY_STRING, "IDENTITY");
1160 TPM2B_STRING(OBFUSCATE_STRING, "OBFUSCATE");
1161 #if SELF_TEST
1162 TPM2B_STRING(OAEP_TEST_STRING, "OAEP Test Value");
1163 #endif // SELF_TEST
1164 
1165 //*****************************************************************************
1166 //** From CryptTest.c
1167 //*****************************************************************************
1168 // This structure contains the self-test state values for the cryptographic modules.
1169 EXTERN CRYPTO_SELF_TEST_STATE   g_cryptoSelfTestState;
1170 
1171 //*****************************************************************************
1172 //** From Manufacture.c
1173 //*****************************************************************************
1174 EXTERN BOOL              g_manufactured INITIALIZER(FALSE);
1175 
1176 // This value indicates if a TPM2_Startup commands has been
1177 // receive since the power on event.  This flag is maintained in power
1178 // simulation module because this is the only place that may reliably set this
1179 // flag to FALSE.
1180 EXTERN BOOL              g_initialized;
1181 
1182 //** Private data
1183 
1184 //*****************************************************************************
1185 //*** From SessionProcess.c
1186 //*****************************************************************************
1187 #if defined SESSION_PROCESS_C || defined GLOBAL_C || defined MANUFACTURE_C
1188 // The following arrays are used to save command sessions information so that the
1189 // command handle/session buffer does not have to be preserved for the duration of
1190 // the command. These arrays are indexed by the session index in accordance with
1191 // the order of sessions in the session area of the command.
1192 //
1193 // Array of the authorization session handles
1194 EXTERN TPM_HANDLE       s_sessionHandles[MAX_SESSION_NUM];
1195 
1196 // Array of authorization session attributes
1197 EXTERN TPMA_SESSION     s_attributes[MAX_SESSION_NUM];
1198 
1199 // Array of handles authorized by the corresponding authorization sessions;
1200 // and if none, then TPM_RH_UNASSIGNED value is used
1201 EXTERN TPM_HANDLE       s_associatedHandles[MAX_SESSION_NUM];
1202 
1203 // Array of nonces provided by the caller for the corresponding sessions
1204 EXTERN TPM2B_NONCE      s_nonceCaller[MAX_SESSION_NUM];
1205 
1206 // Array of authorization values (HMAC's or passwords) for the corresponding
1207 // sessions
1208 EXTERN TPM2B_AUTH       s_inputAuthValues[MAX_SESSION_NUM];
1209 
1210 // Array of pointers to the SESSION structures for the sessions in a command
1211 EXTERN SESSION          *s_usedSessions[MAX_SESSION_NUM];
1212 
1213 // Special value to indicate an undefined session index
1214 #define             UNDEFINED_INDEX     (0xFFFF)
1215 
1216 // Index of the session used for encryption of a response parameter
1217 EXTERN UINT32           s_encryptSessionIndex;
1218 
1219 // Index of the session used for decryption of a command parameter
1220 EXTERN UINT32           s_decryptSessionIndex;
1221 
1222 // Index of a session used for audit
1223 EXTERN UINT32           s_auditSessionIndex;
1224 
1225 // The cpHash for command audit
1226 #ifdef  TPM_CC_GetCommandAuditDigest
1227 EXTERN TPM2B_DIGEST    s_cpHashForCommandAudit;
1228 #endif
1229 
1230 // Flag indicating if NV update is pending for the lockOutAuthEnabled or
1231 // failedTries DA parameter
1232 EXTERN BOOL             s_DAPendingOnNV;
1233 
1234 #endif // SESSION_PROCESS_C
1235 
1236 //*****************************************************************************
1237 //*** From DA.c
1238 //*****************************************************************************
1239 #if defined DA_C || defined GLOBAL_C || defined MANUFACTURE_C
1240 // This variable holds the accumulated time since the last time
1241 // that 'failedTries' was decremented. This value is in millisecond.
1242 #if !ACCUMULATE_SELF_HEAL_TIMER
1243 EXTERN UINT64       s_selfHealTimer;
1244 
1245 // This variable holds the accumulated time that the lockoutAuth has been
1246 // blocked.
1247 EXTERN UINT64       s_lockoutTimer;
1248 #endif // ACCUMULATE_SELF_HEAL_TIMER
1249 
1250 #endif // DA_C
1251 
1252 //*****************************************************************************
1253 //*** From NV.c
1254 //*****************************************************************************
1255 #if defined NV_C || defined GLOBAL_C
1256 // This marks the end of the NV area. This is a run-time variable as it might
1257 // not be compile-time constant.
1258 EXTERN NV_REF   s_evictNvEnd;
1259 
1260 // This space is used to hold the index data for an orderly Index. It also contains
1261 // the attributes for the index.
1262 EXTERN BYTE      s_indexOrderlyRam[RAM_INDEX_SPACE];   // The orderly NV Index data
1263 
1264 // This value contains the current max counter value. It is written to the end of
1265 // allocatable NV space each time an index is deleted or added. This value is
1266 // initialized on Startup. The indices are searched and the maximum of all the
1267 // current counter indices and this value is the initial value for this.
1268 EXTERN UINT64    s_maxCounter;
1269 
1270 // This is space used for the NV Index cache. As with a persistent object, the
1271 // contents of a referenced index are copied into the cache so that the
1272 // NV Index memory scanning and data copying can be reduced.
1273 // Only code that operates on NV Index data should use this cache directly. When
1274 // that action code runs, s_lastNvIndex will contain the index header information.
1275 // It will have been loaded when the handles were verified.
1276 // NOTE: An NV index handle can appear in many commands that do not operate on the
1277 // NV data (e.g. TPM2_StartAuthSession). However, only one NV Index at a time is
1278 // ever directly referenced by any command. If that changes, then the NV Index
1279 // caching needs to be changed to accommodate that. Currently, the code will verify
1280 // that only one NV Index is referenced by the handles of the command.
1281 EXTERN      NV_INDEX         s_cachedNvIndex;
1282 EXTERN      NV_REF           s_cachedNvRef;
1283 EXTERN      BYTE            *s_cachedNvRamRef;
1284 
1285 // Initial NV Index/evict object iterator value
1286 #define     NV_REF_INIT     (NV_REF)0xFFFFFFFF
1287 
1288 #endif
1289 
1290 //*****************************************************************************
1291 //*** From Object.c
1292 //*****************************************************************************
1293 #if defined OBJECT_C || defined GLOBAL_C
1294 // This type is the container for an object.
1295 
1296 EXTERN OBJECT           s_objects[MAX_LOADED_OBJECTS];
1297 
1298 #endif // OBJECT_C
1299 
1300 //*****************************************************************************
1301 //*** From PCR.c
1302 //*****************************************************************************
1303 #if defined PCR_C || defined GLOBAL_C
1304 // The following macro is used to define the per-implemented-hash space. This
1305 // implementation reserves space for all implemented hashes.
1306 #define PCR_ALL_HASH(HASH, Hash)    BYTE    Hash##Pcr[HASH##_DIGEST_SIZE];
1307 
1308 typedef struct
1309 {
1310     FOR_EACH_HASH(PCR_ALL_HASH)
1311 } PCR;
1312 
1313 typedef struct
1314 {
1315     unsigned int    stateSave : 1;              // if the PCR value should be
1316                                                 // saved in state save
1317     unsigned int    resetLocality : 5;          // The locality that the PCR
1318                                                 // can be reset
1319     unsigned int    extendLocality : 5;         // The locality that the PCR
1320                                                 // can be extend
1321 } PCR_Attributes;
1322 
1323 EXTERN PCR          s_pcrs[IMPLEMENTATION_PCR];
1324 
1325 #endif // PCR_C
1326 
1327 //*****************************************************************************
1328 //*** From Session.c
1329 //*****************************************************************************
1330 #if defined SESSION_C || defined GLOBAL_C
1331 // Container for HMAC or policy session tracking information
1332 typedef struct
1333 {
1334     BOOL                occupied;
1335     SESSION             session;        // session structure
1336 } SESSION_SLOT;
1337 
1338 EXTERN SESSION_SLOT     s_sessions[MAX_LOADED_SESSIONS];
1339 
1340 //  The index in contextArray that has the value of the oldest saved session
1341 //  context. When no context is saved, this will have a value that is greater
1342 //  than or equal to MAX_ACTIVE_SESSIONS.
1343 EXTERN UINT32            s_oldestSavedSession;
1344 
1345 // The number of available session slot openings.  When this is 1,
1346 // a session can't be created or loaded if the GAP is maxed out.
1347 // The exception is that the oldest saved session context can always
1348 // be loaded (assuming that there is a space in memory to put it)
1349 EXTERN int               s_freeSessionSlots;
1350 
1351 #endif // SESSION_C
1352 
1353 //*****************************************************************************
1354 //*** From IoBuffers.c
1355 //*****************************************************************************
1356 #if defined IO_BUFFER_C || defined GLOBAL_C
1357 // Each command function is allowed a structure for the inputs to the function and
1358 // a structure for the outputs. The command dispatch code unmarshals the input butter
1359 // to the command action input structure starting at the first byte of
1360 // s_actionIoBuffer. The value of s_actionIoAllocation is the number of UINT64 values
1361 // allocated. It is used to set the pointer for the response structure. The command
1362 // dispatch code will marshal the response values into the final output buffer.
1363 EXTERN UINT64   s_actionIoBuffer[768];      // action I/O buffer
1364 EXTERN UINT32   s_actionIoAllocation;       // number of UIN64 allocated for the
1365                                             // action input structure
1366 #endif // IO_BUFFER_C
1367 
1368 //*****************************************************************************
1369 //*** From TPMFail.c
1370 //*****************************************************************************
1371 // This value holds the address of the string containing the name of the function
1372 // in which the failure occurred. This address value is not useful for anything
1373 // other than helping the vendor to know in which file the failure  occurred.
1374 EXTERN BOOL      g_inFailureMode;       // Indicates that the TPM is in failure mode
1375 #if SIMULATION
1376 EXTERN BOOL      g_forceFailureMode;    // flag to force failure mode during test
1377 #endif
1378 
1379 typedef void(FailFunction)(const char *function, int line, int code);
1380 
1381 #if defined TPM_FAIL_C || defined GLOBAL_C
1382 EXTERN UINT32    s_failFunction;
1383 EXTERN UINT32    s_failLine;            // the line in the file at which
1384                                         // the error was signaled
1385 EXTERN UINT32    s_failCode;            // the error code used
1386 
1387 EXTERN FailFunction    *LibFailCallback;
1388 
1389 #endif // TPM_FAIL_C
1390 
1391 //*****************************************************************************
1392 //*** From ACT_spt.c
1393 //*****************************************************************************
1394 // This value is used to indicate if an ACT has been updated since the last
1395 // TPM2_Startup() (one bit for each ACT). If the ACT is not updated
1396 // (TPM2_ACT_SetTimeout()) after a startup, then on each TPM2_Shutdown() the TPM will
1397 // save 1/2 of the current timer value. This prevents an attack on the ACT by saving
1398 // the counter and then running for a long period of time before doing a TPM Restart.
1399 // A quick TPM2_Shutdown() after each
1400 EXTERN UINT16                       s_ActUpdated;
1401 
1402 //*****************************************************************************
1403 //*** From CommandCodeAttributes.c
1404 //*****************************************************************************
1405 // This array is instanced in CommandCodeAttributes.c when it includes
1406 // CommandCodeAttributes.h. Don't change the extern to EXTERN.
1407 extern  const  TPMA_CC               s_ccAttr[];
1408 extern  const  COMMAND_ATTRIBUTES    s_commandAttributes[];
1409 
1410 #endif // GLOBAL_H
1411