1// This file was extracted from the TCG Published
2// Trusted Platform Module Library
3// Part 4: Supporting Routines
4// Family "2.0"
5// Level 00 Revision 01.16
6// October 30, 2014
7
8#ifndef         GLOBAL_H
9#define         GLOBAL_H
10//#define SELF_TEST
11#include        "TpmBuildSwitches.h"
12#include        "Tpm.h"
13#include        "TPMB.h"
14#include        "CryptoEngine.h"
15#ifndef EMBEDDED_MODE
16#include        <setjmp.h>
17#endif
18//
19//
20//
21//          Defines and Types
22//
23//          Unreferenced Parameter
24//
25//     This define is used to eliminate the compiler warning about an unreferenced parameter. Basically, it tells
26//     the compiler that it is not an accident that the parameter is unreferenced.
27//
28#ifndef UNREFERENCED_PARAMETER
29#   define UNREFERENCED_PARAMETER(a)            (a)
30#endif
31#include    "bits.h"
32//
33//
34//          Crypto Self-Test Values
35//
36//     Define these values here if the AlgorithmTests() project is not used
37//
38#ifndef SELF_TEST
39extern ALGORITHM_VECTOR     g_implementedAlgorithms;
40extern ALGORITHM_VECTOR     g_toTest;
41#else
42LIB_IMPORT extern ALGORITHM_VECTOR     g_implementedAlgorithms;
43LIB_IMPORT extern ALGORITHM_VECTOR     g_toTest;
44#endif
45//
46//     These macros are used in CryptUtil() to invoke the incremental self test.
47//
48#define       TEST(alg) if(TEST_BIT(alg, g_toTest)) CryptTestAlgorithm(alg, NULL)
49//
50//     Use of TPM_ALG_NULL is reserved for RSAEP/RSADP testing. If someone is wanting to test a hash with
51//     that value, don't do it.
52//
53#define       TEST_HASH(alg)                                                                     \
54             if(     TEST_BIT(alg, g_toTest)                                                    \
55                 && (alg != ALG_NULL_VALUE))                                                    \
56                 CryptTestAlgorithm(alg, NULL)
57//
58//
59//          Hash and HMAC State Structures
60//
61//     These definitions are for the types that can be in a hash state structure. These types are used in the
62//     crypto utilities
63//
64typedef   BYTE    HASH_STATE_TYPE;
65#define   HASH_STATE_EMPTY         ((HASH_STATE_TYPE) 0)
66#define   HASH_STATE_HASH          ((HASH_STATE_TYPE) 1)
67#define   HASH_STATE_HMAC          ((HASH_STATE_TYPE) 2)
68//
69//     A HASH_STATE structure contains an opaque hash stack state. A caller would use this structure when
70//     performing incremental hash operations. The state is updated on each call. If type is an HMAC_STATE,
71//     or HMAC_STATE_SEQUENCE then state is followed by the HMAC key in oPad format.
72//
73typedef struct
74{
75   CPRI_HASH_STATE          state;                   // hash state
76   HASH_STATE_TYPE          type;                    // type of the context
77} HASH_STATE;
78//
79//
80//
81//
82//     An HMAC_STATE structure contains an opaque HMAC stack state. A caller would use this structure
83//     when performing incremental HMAC operations. This structure contains a hash state and an HMAC key
84//     and allows slightly better stack optimization than adding an HMAC key to each hash state.
85//
86typedef struct
87{
88   HASH_STATE                hashState;               // the hash state
89   TPM2B_HASH_BLOCK          hmacKey;                 // the HMAC key
90} HMAC_STATE;
91//
92//
93//          Other Types
94//
95//     An AUTH_VALUE is a BYTE array containing a digest (TPMU_HA)
96//
97typedef BYTE        AUTH_VALUE[sizeof(TPMU_HA)];
98//
99//     A TIME_INFO is a BYTE array that can contain a TPMS_TIME_INFO
100//
101typedef BYTE        TIME_INFO[sizeof(TPMS_TIME_INFO)];
102//
103//     A NAME is a BYTE array that can contain a TPMU_NAME
104//
105typedef BYTE        NAME[sizeof(TPMU_NAME)];
106//
107//
108//          Loaded Object Structures
109//
110//          Description
111//
112//     The structures in this section define the object layout as it exists in TPM memory.
113//     Two types of objects are defined: an ordinary object such as a key, and a sequence object that may be a
114//     hash, HMAC, or event.
115//
116//          OBJECT_ATTRIBUTES
117//
118//     An OBJECT_ATTRIBUTES structure contains the variable attributes of an object. These properties are
119//     not part of the public properties but are used by the TPM in managing the object. An
120//     OBJECT_ATTRIBUTES is used in the definition of the OBJECT data type.
121//
122typedef struct
123{
124   unsigned                  publicOnly      : 1;     //0)   SET if only the public portion of
125                                                      //     an object is loaded
126    unsigned                 epsHierarchy : 1;        //1)   SET if the object belongs to EPS
127                                                      //     Hierarchy
128    unsigned                 ppsHierarchy : 1;        //2)   SET if the object belongs to PPS
129                                                      //     Hierarchy
130    unsigned                 spsHierarchy : 1;        //3)   SET f the object belongs to SPS
131                                                      //     Hierarchy
132    unsigned                 evict           : 1;     //4)   SET if the object is a platform or
133                                                      //     owner evict object. Platform-
134                                                      //     evict object belongs to PPS
135                                                      //     hierarchy, owner-evict object
136                                                      //     belongs to SPS or EPS hierarchy.
137                                                      //     This bit is also used to mark a
138                                                      //     completed sequence object so it
139                                                      //     will be flush when the
140                                                      //     SequenceComplete command succeeds.
141    unsigned                 primary        : 1;      //5)   SET for a primary object
142   unsigned                 temporary      :   1;
143                                                    //6) SET for a temporary object
144   unsigned                 stClear        :   1;
145                                                    //7) SET for an stClear object
146   unsigned                 hmacSeq        :   1;
147                                                    //8) SET for an HMAC sequence object
148   unsigned                 hashSeq        :   1;
149                                                    //9) SET for a hash sequence object
150   unsigned                 eventSeq       :   1;
151                                                    //10) SET for an event sequence object
152   unsigned                 ticketSafe     :   1;
153                                                    //11) SET if a ticket is safe to create
154                                             //    for hash sequence object
155   unsigned            firstBlock : 1;       //12) SET if the first block of hash
156                                             //    data has been received. It
157                                             //    works with ticketSafe bit
158   unsigned            isParent     : 1;     //13) SET if the key has the proper
159                                             //    attributes to be a parent key
160   unsigned            privateExp : 1;       //14) SET when the private exponent
161                                             //    of an RSA key has been validated.
162   unsigned        reserved    : 1;      //15) reserved bits. unused.
163} OBJECT_ATTRIBUTES;
164//
165//
166//           OBJECT Structure
167//
168//      An OBJECT structure holds the object public, sensitive, and meta-data associated. This structure is
169//      implementation dependent. For this implementation, the structure is not optimized for space but rather for
170//      clarity of the reference implementation. Other implementations may choose to overlap portions of the
171//      structure that are not used simultaneously. These changes would necessitate changes to the source code
172//      but those changes would be compatible with the reference implementation.
173//
174typedef struct
175{
176   // The attributes field is required to be first followed by the publicArea.
177   // This allows the overlay of the object structure and a sequence structure
178   OBJECT_ATTRIBUTES   attributes;         // object attributes
179   TPMT_PUBLIC         publicArea;         // public area of an object
180   TPMT_SENSITIVE      sensitive;          // sensitive area of an object
181#ifdef TPM_ALG_RSA
182   TPM2B_PUBLIC_KEY_RSA privateExponent;             // Additional field for the private
183                                                     // exponent of an RSA key.
184#endif
185   TPM2B_NAME               qualifiedName;           //   object qualified name
186   TPMI_DH_OBJECT           evictHandle;             //   if the object is an evict object,
187                                                     //   the original handle is kept here.
188                                                     //   The 'working' handle will be the
189                                                     //   handle of an object slot.
190   TPM2B_NAME               name;                    // Name of the object name. Kept here
191                                                     // to avoid repeatedly computing it.
192} OBJECT;
193//
194//
195//           HASH_OBJECT Structure
196//
197//      This structure holds a hash sequence object or an event sequence object.
198//      The first four components of this structure are manually set to be the same as the first four components of
199//      the object structure. This prevents the object from being inadvertently misused as sequence objects
200//      occupy the same memory as a regular object. A debug check is present to make sure that the offsets are
201//      what they are supposed to be.
202//
203typedef struct
204{
205   OBJECT_ATTRIBUTES        attributes;              //   The attributes of the HASH object
206   TPMI_ALG_PUBLIC          type;                    //   algorithm
207   TPMI_ALG_HASH            nameAlg;                 //   name algorithm
208   TPMA_OBJECT              objectAttributes;        //   object attributes
209   // The data below is unique to a sequence object
210   TPM2B_AUTH          auth;               // auth for use of sequence
211   union
212   {
213       HASH_STATE      hashState[HASH_COUNT];
214       HMAC_STATE      hmacState;
215   }                   state;
216} HASH_OBJECT;
217//
218//
219//           ANY_OBJECT
220//
221//      This is the union for holding either a sequence object or a regular object.
222//
223typedef union
224{
225   OBJECT                    entity;
226   HASH_OBJECT               hash;
227} ANY_OBJECT;
228//
229//
230//           AUTH_DUP Types
231//
232//      These values are used in the authorization processing.
233//
234typedef   UINT32              AUTH_ROLE;
235#define   AUTH_NONE           ((AUTH_ROLE)(0))
236#define   AUTH_USER           ((AUTH_ROLE)(1))
237#define   AUTH_ADMIN          ((AUTH_ROLE)(2))
238#define   AUTH_DUP            ((AUTH_ROLE)(3))
239//
240//
241//           Active Session Context
242//
243//           Description
244//
245//      The structures in this section define the internal structure of a session context.
246//
247//           SESSION_ATTRIBUTES
248//
249//      The attributes in the SESSION_ATTRIBUTES structure track the various properties of the session. It
250//      maintains most of the tracking state information for the policy session. It is used within the SESSION
251//      structure.
252//
253typedef struct
254{
255   unsigned                  isPolicy : 1;       //1)        SET if the session may only
256                                                 //          be used for policy
257    unsigned                 isAudit : 1;        //2)        SET if the session is used
258                                                 //          for audit
259    unsigned                 isBound : 1;        //3)        SET if the session is bound to
260                                                 //          with an entity.
261                                                 //          This attribute will be CLEAR if
262                                                 //          either isPolicy or isAudit is SET.
263    unsigned                 iscpHashDefined : 1;//4)        SET if the cpHash has been defined
264                                                 //          This attribute is not SET unless
265                                                 //          'isPolicy' is SET.
266    unsigned                 isAuthValueNeeded : 1;
267                                                 //5)        SET if the authValue is required
268                                                 //          for computing the session HMAC.
269                                                 //          This attribute is not SET unless
270                                                   //   isPolicy is SET.
271   unsigned                    isPasswordNeeded : 1;
272                                                   //6) SET if a password authValue is
273                                                   //   required for authorization
274                                                   //   This attribute is not SET unless
275                                                   //   isPolicy is SET.
276   unsigned                    isPPRequired : 1;   //7) SET if physical presence is
277                                                   //   required to be asserted when the
278                                                   //   authorization is checked.
279                                                   //   This attribute is not SET unless
280                                                   //   isPolicy is SET.
281   unsigned                    isTrialPolicy : 1; //8) SET if the policy session is
282                                                   //   created for trial of the policy's
283                                                   //   policyHash generation.
284                                                   //   This attribute is not SET unless
285                                                   //   isPolicy is SET.
286   unsigned                    isDaBound : 1;      //9) SET if the bind entity had noDA
287                                                   //   CLEAR. If this is SET, then an
288                                                   //   auth failure using this session
289                                                   //   will count against lockout even
290                                                   //   if the object being authorized is
291                                                   //   exempt from DA.
292   unsigned                    isLockoutBound : 1; //10)SET if the session is bound to
293                                                   //   lockoutAuth.
294   unsigned                    requestWasBound : 1;//11) SET if the session is being used
295                                                   //    with the bind entity. If SET
296                                                   //    the authValue will not be use
297                                                   //    in the response HMAC computation.
298   unsigned                    checkNvWritten : 1; //12) SET if the TPMA_NV_WRITTEN
299                                                   //    attribute needs to be checked
300                                                   //    when the policy is used for
301                                                   //    authorization for NV access.
302                                                   //    If this is SET for any other
303                                                   //    type, the policy will fail.
304   unsigned                    nvWrittenState : 1; //13) SET if TPMA_NV_WRITTEN is
305                                                   //    required to be SET.
306} SESSION_ATTRIBUTES;
307//
308//
309//           SESSION Structure
310//
311//      The SESSION structure contains all the context of a session except for the associated contextID.
312//
313//      NOTE:           The contextID of a session is only relevant when the session context is stored off the TPM.
314//
315typedef struct
316{
317   TPM_ALG_ID                  authHashAlg;                   // session hash algorithm
318   TPM2B_NONCE                 nonceTPM;                      // last TPM-generated nonce for
319                                                              // this session
320   TPMT_SYM_DEF                symmetric;                     // session symmetric algorithm (if any)
321   TPM2B_AUTH                  sessionKey;                    // session secret value used for
322                                                              // generating HMAC and encryption keys
323   SESSION_ATTRIBUTES          attributes;                    //   session attributes
324   TPM_CC                      commandCode;                   //   command code (policy session)
325   TPMA_LOCALITY               commandLocality;               //   command locality (policy session)
326   UINT32                      pcrCounter;                    //   PCR counter value when PCR is
327                                                              //   included (policy session)
328                                                              //   If no PCR is included, this
329                                                              //   value is 0.
330   UINT64                      startTime;                     // value of TPMS_CLOCK_INFO.clock when
331                                                              // the session was started (policy
332//
333                                                    // session)
334   UINT64                    timeOut;               //   timeout relative to
335                                                    //   TPMS_CLOCK_INFO.clock
336                                                    //   There is no timeout if this value
337                                                    //   is 0.
338   union
339   {
340       TPM2B_NAME            boundEntity;            // value used to track the entity to
341                                                     // which the session is bound
342         TPM2B_DIGEST        cpHash;                 // the required cpHash value for the
343                                                     // command being authorized
344   } u1;                                             // 'boundEntity' and 'cpHash' may
345                                                     // share the same space to save memory
346   union
347   {
348       TPM2B_DIGEST          auditDigest;           // audit session digest
349       TPM2B_DIGEST          policyDigest;            // policyHash
350   } u2;                                            // audit log and policyHash may
351                                                    // share space to save memory
352} SESSION;
353//
354//
355//           PCR
356//
357//           PCR_SAVE Structure
358//
359//      The PCR_SAVE structure type contains the PCR data that are saved across power cycles. Only the static
360//      PCR are required to be saved across power cycles. The DRTM and resettable PCR are not saved. The
361//      number of static and resettable PCR is determined by the platform-specific specification to which the TPM
362//      is built.
363//
364typedef struct
365{
366#ifdef TPM_ALG_SHA1
367   BYTE                      sha1[NUM_STATIC_PCR][SHA1_DIGEST_SIZE];
368#endif
369#ifdef TPM_ALG_SHA256
370   BYTE                      sha256[NUM_STATIC_PCR][SHA256_DIGEST_SIZE];
371#endif
372#ifdef TPM_ALG_SHA384
373   BYTE                      sha384[NUM_STATIC_PCR][SHA384_DIGEST_SIZE];
374#endif
375#ifdef TPM_ALG_SHA512
376   BYTE                      sha512[NUM_STATIC_PCR][SHA512_DIGEST_SIZE];
377#endif
378#ifdef TPM_ALG_SM3_256
379   BYTE                      sm3_256[NUM_STATIC_PCR][SM3_256_DIGEST_SIZE];
380#endif
381   // This counter increments whenever the PCR are updated.
382   // NOTE: A platform-specific specification may designate
383   //       certain PCR changes as not causing this counter
384   //       to increment.
385   UINT32              pcrCounter;
386} PCR_SAVE;
387//
388//
389//
390//           PCR_POLICY
391//
392//      This structure holds the PCR policies, one for each group of PCR controlled by policy.
393//
394typedef struct
395{
396   TPMI_ALG_HASH               hashAlg[NUM_POLICY_PCR_GROUP];
397   TPM2B_DIGEST                a;
398   TPM2B_DIGEST                policy[NUM_POLICY_PCR_GROUP];
399} PCR_POLICY;
400//
401//
402//           PCR_AUTHVALUE
403//
404//      This structure holds the PCR policies, one for each group of PCR controlled by policy.
405//
406typedef struct
407{
408   TPM2B_DIGEST                auth[NUM_AUTHVALUE_PCR_GROUP];
409} PCR_AUTHVALUE;
410//
411//
412//           Startup
413//
414//           SHUTDOWN_NONE
415//
416//      Part 2 defines the two shutdown/startup types that may be used in TPM2_Shutdown() and
417//      TPM2_Starup(). This additional define is used by the TPM to indicate that no shutdown was received.
418//
419//      NOTE:           This is a reserved value.
420//
421#define SHUTDOWN_NONE           (TPM_SU)(0xFFFF)
422//
423//
424//           STARTUP_TYPE
425//
426//      This enumeration is the possible startup types. The type is determined by the combination of
427//      TPM2_ShutDown() and TPM2_Startup().
428//
429typedef enum
430{
431   SU_RESET,
432   SU_RESTART,
433   SU_RESUME
434} STARTUP_TYPE;
435//
436//
437//           NV
438//
439//           NV_RESERVE
440//
441//      This enumeration defines the master list of the elements of a reserved portion of NV. This list includes all
442//      the pre-defined data that takes space in NV, either as persistent data or as state save data. The
443//      enumerations are used as indexes into an array of offset values. The offset values then are used to index
444//      into NV. This is method provides an imperfect analog to an actual NV implementation.
445//
446typedef enum
447{
448// Entries below mirror the PERSISTENT_DATA structure. These values are written
449// to NV as individual items.
450   // hierarchy
451   NV_DISABLE_CLEAR,
452   NV_OWNER_ALG,
453   NV_ENDORSEMENT_ALG,
454   NV_LOCKOUT_ALG,
455   NV_OWNER_POLICY,
456   NV_ENDORSEMENT_POLICY,
457   NV_LOCKOUT_POLICY,
458   NV_OWNER_AUTH,
459   NV_ENDORSEMENT_AUTH,
460   NV_LOCKOUT_AUTH,
461   NV_EP_SEED,
462   NV_SP_SEED,
463   NV_PP_SEED,
464   NV_PH_PROOF,
465   NV_SH_PROOF,
466   NV_EH_PROOF,
467   // Time
468   NV_TOTAL_RESET_COUNT,
469   NV_RESET_COUNT,
470   // PCR
471   NV_PCR_POLICIES,
472   NV_PCR_ALLOCATED,
473   // Physical Presence
474   NV_PP_LIST,
475   // Dictionary Attack
476   NV_FAILED_TRIES,
477   NV_MAX_TRIES,
478   NV_RECOVERY_TIME,
479   NV_LOCKOUT_RECOVERY,
480   NV_LOCKOUT_AUTH_ENABLED,
481   // Orderly State flag
482   NV_ORDERLY,
483   // Command Audit
484   NV_AUDIT_COMMANDS,
485   NV_AUDIT_HASH_ALG,
486   NV_AUDIT_COUNTER,
487   // Algorithm Set
488   NV_ALGORITHM_SET,
489   NV_FIRMWARE_V1,
490   NV_FIRMWARE_V2,
491// The entries above are in PERSISTENT_DATA. The entries below represent
492// structures that are read and written as a unit.
493// ORDERLY_DATA data structure written on each orderly shutdown
494   NV_ORDERLY_DATA,
495// STATE_CLEAR_DATA structure written on each Shutdown(STATE)
496   NV_STATE_CLEAR,
497// STATE_RESET_DATA structure written on each Shutdown(STATE)
498   NV_STATE_RESET,
499   NV_RESERVE_LAST             // end of NV reserved data list
500} NV_RESERVE;
501//
502//           NV_INDEX
503//
504//      The NV_INDEX structure defines the internal format for an NV index. The indexData size varies
505//      according to the type of the index. In this implementation, all of the index is manipulated as a unit.
506//
507typedef struct
508{
509   TPMS_NV_PUBLIC           publicArea;
510   TPM2B_AUTH               authValue;
511} NV_INDEX;
512//
513//
514//           COMMIT_INDEX_MASK
515//
516//      This is the define for the mask value that is used when manipulating the bits in the commit bit array. The
517//      commit counter is a 64-bit value and the low order bits are used to index the commitArray. This mask
518//      value is applied to the commit counter to extract the bit number in the array.
519//
520#ifdef TPM_ALG_ECC
521#define COMMIT_INDEX_MASK ((UINT16)((sizeof(gr.commitArray)*8)-1))
522#endif
523//
524//
525//           RAM Global Values
526//
527//          Description
528//
529//      The values in this section are only extant in RAM. They are defined here and instanced in Global.c.
530//
531//          g_rcIndex
532//
533//      This array is used to contain the array of values that are added to a return code when it is a parameter-,
534//      handle-, or session-related error. This is an implementation choice and the same result can be achieved
535//      by using a macro.
536//
537extern const UINT16          g_rcIndex[15];
538//
539//
540//          g_exclusiveAuditSession
541//
542//      This location holds the session handle for the current exclusive audit session. If there is no exclusive
543//      audit session, the location is set to TPM_RH_UNASSIGNED.
544//
545extern TPM_HANDLE            g_exclusiveAuditSession;
546//
547//
548//          g_time
549//
550//      This value is the count of milliseconds since the TPM was powered up. This value is initialized at
551//      _TPM_Init().
552//
553extern     UINT64            g_time;
554//
555//
556//          g_phEnable
557//
558//      This is the platform hierarchy control and determines if the platform hierarchy is available. This value is
559//      SET on each TPM2_Startup(). The default value is SET.
560//
561extern BOOL                  g_phEnable;
562//          g_pceReConfig
563//
564//      This value is SET if a TPM2_PCR_Allocate() command successfully executed since the last
565//      TPM2_Startup(). If so, then the next shutdown is required to be Shutdown(CLEAR).
566//
567extern BOOL                   g_pcrReConfig;
568//
569//
570//          g_DRTMHandle
571//
572//      This location indicates the sequence object handle that holds the DRTM sequence data. When not used,
573//      it is set to TPM_RH_UNASSIGNED. A sequence DRTM sequence is started on either _TPM_Init() or
574//      _TPM_Hash_Start().
575//
576extern TPMI_DH_OBJECT         g_DRTMHandle;
577//
578//
579//          g_DrtmPreStartup
580//
581//      This value indicates that an H-CRTM occurred after _TPM_Init() but before TPM2_Startup(). The define
582//      for PRE_STARTUP_FLAG is used to add the g_DrtmPreStartup value to gp_orderlyState at shutdown.
583//      This hack is to avoid adding another NV variable.
584//
585extern BOOL              g_DrtmPreStartup;
586#define PRE_STARTUP_FLAG     0x8000
587//
588//
589//          g_StartupLocality3
590//
591//      This value indicates that a TPM2_Startup() occured at locality 3. Otherwise, it at locality 0. The define for
592//      STARTUP_LOCALITY_3 is to indicate that the startup was not at locality 0. This hack is to avoid adding
593//      another NV variable.
594//
595extern BOOL             g_StartupLocality3;
596#define STARTUP_LOCALITY_3       0x4000
597//
598//
599//       g_updateNV
600//
601//      This flag indicates if NV should be updated at the end of a command. This flag is set to FALSE at the
602//      beginning of each command in ExecuteCommand(). This flag is checked in ExecuteCommand() after the
603//      detailed actions of a command complete. If the command execution was successful and this flag is SET,
604//      any pending NV writes will be committed to NV.
605//
606extern BOOL                   g_updateNV;
607//
608//
609//       g_clearOrderly
610//
611//      This flag indicates if the execution of a command should cause the orderly state to be cleared. This flag
612//      is set to FALSE at the beginning of each command in ExecuteCommand() and is checked in
613//      ExecuteCommand() after the detailed actions of a command complete but before the check of
614//      g_updateNV. If this flag is TRUE, and the orderly state is not SHUTDOWN_NONE, then the orderly state
615//      in NV memory will be changed to SHUTDOWN_NONE.
616//
617extern BOOL                   g_clearOrderly;
618//
619//
620//
621//       g_prevOrderlyState
622//
623//      This location indicates how the TPM was shut down before the most recent TPM2_Startup(). This value,
624//      along with the startup type, determines if the TPM should do a TPM Reset, TPM Restart, or TPM
625//      Resume.
626//
627extern TPM_SU                 g_prevOrderlyState;
628//
629//
630//       g_nvOk
631//
632//      This value indicates if the NV integrity check was successful or not. If not and the failure was severe, then
633//      the TPM would have been put into failure mode after it had been re-manufactured. If the NV failure was in
634//      the area where the state-save data is kept, then this variable will have a value of FALSE indicating that a
635//      TPM2_Startup(CLEAR) is required.
636//
637extern BOOL                   g_nvOk;
638//
639//
640//       g_platformUnique
641//
642//      This location contains the unique value(s) used to identify the TPM. It is loaded on every
643//      _TPM2_Startup() The first value is used to seed the RNG. The second value is used as a vendor
644//      authValue. The value used by the RNG would be the value derived from the chip unique value (such as
645//      fused) with a dependency on the authorities of the code in the TPM boot path. The second would be
646//      derived from the chip unique value with a dependency on the details of the code in the boot path. That is,
647//      the first value depends on the various signers of the code and the second depends on what was signed.
648//      The TPM vendor should not be able to know the first value but they are expected to know the second.
649//
650extern TPM2B_AUTH             g_platformUniqueAuthorities; // Reserved for RNG
651extern TPM2B_AUTH             g_platformUniqueDetails;   // referenced by VENDOR_PERMANENT
652//
653//
654//           Persistent Global Values
655//
656//           Description
657//
658//      The values in this section are global values that are persistent across power events. The lifetime of the
659//      values determines the structure in which the value is placed.
660//
661//           PERSISTENT_DATA
662//
663//      This structure holds the persistent values that only change as a consequence of a specific Protected
664//      Capability and are not affected by TPM power events (TPM2_Startup() or TPM2_Shutdown().
665//
666typedef struct
667{
668//*********************************************************************************
669//          Hierarchy
670//*********************************************************************************
671// The values in this section are related to the hierarchies.
672    BOOL                     disableClear;            // TRUE if TPM2_Clear() using
673                                                      // lockoutAuth is disabled
674    // Hierarchy authPolicies
675    TPMI_ALG_HASH       ownerAlg;
676    TPMI_ALG_HASH       endorsementAlg;
677    TPMI_ALG_HASH       lockoutAlg;
678    TPM2B_DIGEST        ownerPolicy;
679    TPM2B_DIGEST             endorsementPolicy;
680    TPM2B_DIGEST             lockoutPolicy;
681    // Hierarchy authValues
682    TPM2B_AUTH          ownerAuth;
683    TPM2B_AUTH          endorsementAuth;
684    TPM2B_AUTH          lockoutAuth;
685    // Primary Seeds
686    TPM2B_SEED          EPSeed;
687    TPM2B_SEED          SPSeed;
688    TPM2B_SEED          PPSeed;
689    // Note there is a nullSeed in the state_reset memory.
690    // Hierarchy proofs
691    TPM2B_AUTH          phProof;
692    TPM2B_AUTH          shProof;
693    TPM2B_AUTH          ehProof;
694    // Note there is a nullProof in the state_reset memory.
695//*********************************************************************************
696//          Reset Events
697//*********************************************************************************
698// A count that increments at each TPM reset and never get reset during the life
699// time of TPM. The value of this counter is initialized to 1 during TPM
700// manufacture process.
701   UINT64               totalResetCount;
702// This counter increments on each TPM Reset. The counter is reset by
703// TPM2_Clear().
704   UINT32              resetCount;
705//*********************************************************************************
706//           PCR
707//*********************************************************************************
708// This structure hold the policies for those PCR that have an update policy.
709// This implementation only supports a single group of PCR controlled by
710// policy. If more are required, then this structure would be changed to
711// an array.
712   PCR_POLICY          pcrPolicies;
713//   This structure indicates the allocation of PCR. The structure contains a
714//   list of PCR allocations for each implemented algorithm. If no PCR are
715//   allocated for an algorithm, a list entry still exists but the bit map
716//   will contain no SET bits.
717     TPML_PCR_SELECTION pcrAllocated;
718//*********************************************************************************
719//          Physical Presence
720//*********************************************************************************
721// The PP_LIST type contains a bit map of the commands that require physical
722// to be asserted when the authorization is evaluated. Physical presence will be
723// checked if the corresponding bit in the array is SET and if the authorization
724// handle is TPM_RH_PLATFORM.
725//
726// These bits may be changed with TPM2_PP_Commands().
727   BYTE                ppList[((TPM_CC_PP_LAST - TPM_CC_PP_FIRST + 1) + 7)/8];
728//*********************************************************************************
729//          Dictionary attack values
730//*********************************************************************************
731// These values are used for dictionary attack tracking and control.
732   UINT32              failedTries;        // the current count of unexpired
733                                           // authorization failures
734    UINT32                   maxTries;            // number of unexpired authorization
735                                                  // failures before the TPM is in
736                                                  // lockout
737   UINT32                  recoveryTime;          // time between authorization failures
738                                                  // before failedTries is decremented
739   UINT32                  lockoutRecovery;       // time that must expire between
740                                                  // authorization failures associated
741                                                  // with lockoutAuth
742   BOOL                    lockOutAuthEnabled; // TRUE if use of lockoutAuth is
743                                               // allowed
744//*****************************************************************************
745//            Orderly State
746//*****************************************************************************
747// The orderly state for current cycle
748   TPM_SU              orderlyState;
749//*****************************************************************************
750//           Command audit values.
751//*****************************************************************************
752   BYTE                auditComands[((TPM_CC_LAST - TPM_CC_FIRST + 1) + 7) / 8];
753   TPMI_ALG_HASH       auditHashAlg;
754   UINT64              auditCounter;
755//*****************************************************************************
756//           Algorithm selection
757//*****************************************************************************
758//
759// The 'algorithmSet' value indicates the collection of algorithms that are
760// currently in used on the TPM. The interpretation of value is vendor dependent.
761   UINT32              algorithmSet;
762//*****************************************************************************
763//           Firmware version
764//*****************************************************************************
765// The firmwareV1 and firmwareV2 values are instanced in TimeStamp.c. This is
766// a scheme used in development to allow determination of the linker build time
767// of the TPM. An actual implementation would implement these values in a way that
768// is consistent with vendor needs. The values are maintained in RAM for simplified
769// access with a master version in NV. These values are modified in a
770// vendor-specific way.
771// g_firmwareV1 contains the more significant 32-bits of the vendor version number.
772// In the reference implementation, if this value is printed as a hex
773// value, it will have the format of yyyymmdd
774   UINT32              firmwareV1;
775// g_firmwareV1 contains the less significant 32-bits of the vendor version number.
776// In the reference implementation, if this value is printed as a hex
777// value, it will have the format of 00 hh mm ss
778   UINT32              firmwareV2;
779} PERSISTENT_DATA;
780extern PERSISTENT_DATA      gp;
781//
782//
783//         ORDERLY_DATA
784//
785//      The data in this structure is saved to NV on each TPM2_Shutdown().
786//
787typedef struct orderly_data
788{
789//
790//*****************************************************************************
791//           TIME
792//*****************************************************************************
793//   Clock has two parts. One is the state save part and one is the NV part. The
794//   state save version is updated on each command. When the clock rolls over, the
795//   NV version is updated. When the TPM starts up, if the TPM was shutdown in and
796//   orderly way, then the sClock value is used to initialize the clock. If the
797//   TPM shutdown was not orderly, then the persistent value is used and the safe
798//   attribute is clear.
799    UINT64                   clock;        // The orderly version of clock
800    TPMI_YES_NO              clockSafe;    // Indicates if the clock value is
801                                           // safe.
802//*********************************************************************************
803//          DRBG
804//*********************************************************************************
805#ifdef _DRBG_STATE_SAVE
806   // This is DRBG state data. This is saved each time the value of clock is
807   // updated.
808   DRBG_STATE          drbgState;
809#endif
810} ORDERLY_DATA;
811extern ORDERLY_DATA           go;
812//
813//
814//          STATE_CLEAR_DATA
815//
816//      This structure contains the data that is saved on Shutdown(STATE). and restored on Startup(STATE).
817//      The values are set to their default settings on any Startup(Clear). In other words the data is only
818//      persistent across TPM Resume.
819//      If the comments associated with a parameter indicate a default reset value, the value is applied on each
820//      Startup(CLEAR).
821//
822typedef struct state_clear_data
823{
824//*****************************************************************************
825//           Hierarchy Control
826//*****************************************************************************
827   BOOL                shEnable;           // default reset is SET
828   BOOL                ehEnable;           // default reset is SET
829   BOOL                phEnableNV;         // default reset is SET
830   TPMI_ALG_HASH       platformAlg;        // default reset is TPM_ALG_NULL
831   TPM2B_DIGEST        platformPolicy;     // default reset is an Empty Buffer
832   TPM2B_AUTH          platformAuth;       // default reset is an Empty Buffer
833//*****************************************************************************
834//           PCR
835//*****************************************************************************
836// The set of PCR to be saved on Shutdown(STATE)
837   PCR_SAVE            pcrSave;            // default reset is 0...0
838//   This structure hold the authorization values for those PCR that have an
839//   update authorization.
840//   This implementation only supports a single group of PCR controlled by
841//   authorization. If more are required, then this structure would be changed to
842//   an array.
843     PCR_AUTHVALUE        pcrAuthValues;
844} STATE_CLEAR_DATA;
845extern STATE_CLEAR_DATA gc;
846//
847//
848//
849//          State Reset Data
850//
851//      This structure contains data is that is saved on Shutdown(STATE) and restored on the subsequent
852//      Startup(ANY). That is, the data is preserved across TPM Resume and TPM Restart.
853//      If a default value is specified in the comments this value is applied on TPM Reset.
854//
855typedef struct state_reset_data
856{
857//*****************************************************************************
858//          Hierarchy Control
859//*****************************************************************************
860   TPM2B_AUTH          nullProof;          // The proof value associated with
861                                           // the TPM_RH_NULL hierarchy. The
862                                           // default reset value is from the RNG.
863   TPM2B_SEED               nullSeed;                // The seed value for the TPM_RN_NULL
864                                                     // hierarchy. The default reset value
865                                                     // is from the RNG.
866//*****************************************************************************
867//           Context
868//*****************************************************************************
869// The 'clearCount' counter is incremented each time the TPM successfully executes
870// a TPM Resume. The counter is included in each saved context that has 'stClear'
871// SET (including descendants of keys that have 'stClear' SET). This prevents these
872// objects from being loaded after a TPM Resume.
873// If 'clearCount' at its maximum value when the TPM receives a Shutdown(STATE),
874// the TPM will return TPM_RC_RANGE and the TPM will only accept Shutdown(CLEAR).
875   UINT32              clearCount;         // The default reset value is 0.
876   UINT64                   objectContextID;         // This is the context ID for a saved
877                                                     // object context. The default reset
878                                                     // value is 0.
879   CONTEXT_SLOT             contextArray[MAX_ACTIVE_SESSIONS];
880                                                // This is the value from which the
881                                                // 'contextID' is derived. The
882                                                // default reset value is {0}.
883   CONTEXT_COUNTER          contextCounter;          //   This array contains contains the
884                                                     //   values used to track the version
885                                                     //   numbers of saved contexts (see
886                                                     //   Session.c in for details). The
887                                                     //   default reset value is 0.
888//*****************************************************************************
889//           Command Audit
890//*****************************************************************************
891// When an audited command completes, ExecuteCommand() checks the return
892// value. If it is TPM_RC_SUCCESS, and the command is an audited command, the
893// TPM will extend the cpHash and rpHash for the command to this value. If this
894// digest was the Zero Digest before the cpHash was extended, the audit counter
895// is incremented.
896   TPM2B_DIGEST             commandAuditDigest; // This value is set to an Empty Digest
897                                                // by TPM2_GetCommandAuditDigest() or a
898                                                // TPM Reset.
899//*****************************************************************************
900//           Boot counter
901//*****************************************************************************
902   UINT32                   restartCount;            // This counter counts TPM Restarts.
903                                                     // The default reset value is 0.
904//
905//*********************************************************************************
906//            PCR
907//*********************************************************************************
908// This counter increments whenever the PCR are updated. This counter is preserved
909// across TPM Resume even though the PCR are not preserved. This is because
910// sessions remain active across TPM Restart and the count value in the session
911// is compared to this counter so this counter must have values that are unique
912// as long as the sessions are active.
913// NOTE: A platform-specific specification may designate that certain PCR changes
914//       do not increment this counter to increment.
915   UINT32              pcrCounter;         // The default reset value is 0.
916#ifdef TPM_ALG_ECC
917//*****************************************************************************
918//         ECDAA
919//*****************************************************************************
920   UINT64              commitCounter;      // This counter increments each time
921                                           // TPM2_Commit() returns
922                                           // TPM_RC_SUCCESS. The default reset
923                                           // value is 0.
924   TPM2B_NONCE               commitNonce;            // This random value is used to compute
925                                                     // the commit values. The default reset
926                                                     // value is from the RNG.
927// This implementation relies on the number of bits in g_commitArray being a
928// power of 2 (8, 16, 32, 64, etc.) and no greater than 64K.
929   BYTE                 commitArray[16];   // The default reset value is {0}.
930#endif //TPM_ALG_ECC
931} STATE_RESET_DATA;
932extern STATE_RESET_DATA gr;
933//
934//
935//         Global Macro Definitions
936//
937//      This macro is used to ensure that a handle, session, or parameter number is only added if the response
938//      code is FMT1.
939//
940#define RcSafeAddToResult(r, v) \
941   ((r) + (((r) & RC_FMT1) ? (v) : 0))
942//
943//      This macro is used when a parameter is not otherwise referenced in a function. This macro is normally
944//      not used by itself but is paired with a pAssert() within a #ifdef pAssert. If pAssert is not defined, then a
945//      parameter might not otherwise be referenced. This macro uses the parameter from the perspective of the
946//      compiler so it doesn't complain.
947//
948#define UNREFERENCED(a) ((void)(a))
949//
950//
951//         Private data
952//
953#if defined SESSION_PROCESS_C || defined GLOBAL_C || defined MANUFACTURE_C
954//
955//      From SessionProcess.c
956//      The following arrays are used to save command sessions information so that the command
957//      handle/session buffer does not have to be preserved for the duration of the command. These arrays are
958//      indexed by the session index in accordance with the order of sessions in the session area of the
959//      command.
960//
961//      Array of the authorization session handles
962//
963extern TPM_HANDLE             s_sessionHandles[MAX_SESSION_NUM];
964//
965//      Array of authorization session attributes
966//
967extern TPMA_SESSION           s_attributes[MAX_SESSION_NUM];
968//
969//      Array of handles authorized by the corresponding authorization sessions; and if none, then
970//      TPM_RH_UNASSIGNED value is used
971//
972extern TPM_HANDLE             s_associatedHandles[MAX_SESSION_NUM];
973//
974//      Array of nonces provided by the caller for the corresponding sessions
975//
976extern TPM2B_NONCE            s_nonceCaller[MAX_SESSION_NUM];
977//
978//      Array of authorization values (HMAC's or passwords) for the corresponding sessions
979//
980extern TPM2B_AUTH             s_inputAuthValues[MAX_SESSION_NUM];
981//
982//      Special value to indicate an undefined session index
983//
984#define                  UNDEFINED_INDEX        (0xFFFF)
985//
986//      Index of the session used for encryption of a response parameter
987//
988extern UINT32                 s_encryptSessionIndex;
989//
990//      Index of the session used for decryption of a command parameter
991//
992extern UINT32                 s_decryptSessionIndex;
993//
994//      Index of a session used for audit
995//
996extern UINT32                 s_auditSessionIndex;
997//
998//      The cpHash for an audit session
999//
1000extern TPM2B_DIGEST           s_cpHashForAudit;
1001//
1002//      The cpHash for command audit
1003//
1004#ifdef TPM_CC_GetCommandAuditDigest
1005extern TPM2B_DIGEST   s_cpHashForCommandAudit;
1006#endif
1007//
1008//      Number of authorization sessions present in the command
1009//
1010extern UINT32                 s_sessionNum;
1011//
1012//      Flag indicating if NV update is pending for the lockOutAuthEnabled or failedTries DA parameter
1013//
1014extern BOOL             s_DAPendingOnNV;
1015#endif // SESSION_PROCESS_C
1016#if defined DA_C || defined GLOBAL_C || defined MANUFACTURE_C
1017//
1018//      From DA.c
1019//
1020//      This variable holds the accumulated time since the last time that failedTries was decremented. This value
1021//      is in millisecond.
1022//
1023extern UINT64            s_selfHealTimer;
1024//
1025//      This variable holds the accumulated time that the lockoutAuth has been blocked.
1026//
1027extern UINT64       s_lockoutTimer;
1028#endif // DA_C
1029#if defined NV_C || defined GLOBAL_C
1030//
1031//      From NV.c
1032//      List of pre-defined address of reserved data
1033//
1034extern UINT32            s_reservedAddr[NV_RESERVE_LAST];
1035//
1036//      List of pre-defined reserved data size in byte
1037//
1038extern UINT32            s_reservedSize[NV_RESERVE_LAST];
1039//
1040//      Size of data in RAM index buffer
1041//
1042extern UINT32            s_ramIndexSize;
1043//
1044//      Reserved RAM space for frequently updated NV Index. The data layout in ram buffer is {NV_handle(),
1045//      size of data, data} for each NV index data stored in RAM
1046//
1047extern BYTE          s_ramIndex[RAM_INDEX_SPACE];
1048//
1049//      Address of size of RAM index space in NV
1050//
1051extern UINT32       s_ramIndexSizeAddr;
1052//
1053//      Address of NV copy of RAM index space
1054//
1055extern UINT32       s_ramIndexAddr;
1056//
1057//      Address of maximum counter value; an auxiliary variable to implement NV counters
1058//
1059extern UINT32       s_maxCountAddr;
1060//
1061//      Beginning of NV dynamic area; starts right after the s_maxCountAddr and s_evictHandleMapAddr
1062//      variables
1063//
1064extern UINT32       s_evictNvStart;
1065//
1066//      Beginning of NV dynamic area; also the beginning of the predefined reserved data area.
1067//
1068extern UINT32       s_evictNvEnd;
1069//
1070//      NV availability is sampled as the start of each command and stored here so that its value remains
1071//      consistent during the command execution
1072//
1073extern TPM_RC   s_NvStatus;
1074#endif
1075#if defined OBJECT_C || defined GLOBAL_C
1076//
1077//      From Object.c
1078//
1079//      This type is the container for an object.
1080//
1081typedef struct
1082{
1083   BOOL            occupied;
1084   ANY_OBJECT          object;
1085} OBJECT_SLOT;
1086//
1087//      This is the memory that holds the loaded objects.
1088//
1089extern OBJECT_SLOT     s_objects[MAX_LOADED_OBJECTS];
1090#endif // OBJECT_C
1091#if defined PCR_C || defined GLOBAL_C
1092//
1093//      From PCR.c
1094//
1095typedef struct
1096{
1097#ifdef TPM_ALG_SHA1
1098   // SHA1 PCR
1099   BYTE    sha1Pcr[SHA1_DIGEST_SIZE];
1100#endif
1101#ifdef TPM_ALG_SHA256
1102   // SHA256 PCR
1103   BYTE    sha256Pcr[SHA256_DIGEST_SIZE];
1104#endif
1105#ifdef TPM_ALG_SHA384
1106   // SHA384 PCR
1107   BYTE    sha384Pcr[SHA384_DIGEST_SIZE];
1108#endif
1109#ifdef TPM_ALG_SHA512
1110   // SHA512 PCR
1111   BYTE    sha512Pcr[SHA512_DIGEST_SIZE];
1112#endif
1113#ifdef TPM_ALG_SM3_256
1114   // SHA256 PCR
1115   BYTE    sm3_256Pcr[SM3_256_DIGEST_SIZE];
1116#endif
1117} PCR;
1118typedef struct
1119{
1120   unsigned int    stateSave : 1;                          //   if the PCR value should be
1121                                                           //   saved in state save
1122    unsigned int        resetLocality : 5;                 //   The locality that the PCR
1123                                                           //   can be reset
1124    unsigned int        extendLocality : 5;                //   The locality that the PCR
1125                                                           //   can be extend
1126} PCR_Attributes;
1127extern PCR          s_pcrs[IMPLEMENTATION_PCR];
1128#endif // PCR_C
1129#if defined SESSION_C || defined GLOBAL_C
1130//
1131//      From Session.c
1132//      Container for HMAC or policy session tracking information
1133//
1134typedef struct
1135{
1136   BOOL                      occupied;
1137   SESSION                   session;          // session structure
1138} SESSION_SLOT;
1139extern SESSION_SLOT           s_sessions[MAX_LOADED_SESSIONS];
1140//
1141//
1142//
1143//
1144//      The index in conextArray that has the value of the oldest saved session context. When no context is
1145//      saved, this will have a value that is greater than or equal to MAX_ACTIVE_SESSIONS.
1146//
1147extern UINT32                  s_oldestSavedSession;
1148//
1149//      The number of available session slot openings. When this is 1, a session can't be created or loaded if the
1150//      GAP is maxed out. The exception is that the oldest saved session context can always be loaded
1151//      (assuming that there is a space in memory to put it)
1152//
1153extern int                     s_freeSessionSlots;
1154#endif // SESSION_C
1155//
1156//      From Manufacture.c
1157//
1158extern BOOL              g_manufactured;
1159#if defined POWER_C || defined GLOBAL_C
1160//
1161//      From Power.c
1162//      This value indicates if a TPM2_Startup() commands has been receive since the power on event. This
1163//      flag is maintained in power simulation module because this is the only place that may reliably set this flag
1164//      to FALSE.
1165//
1166extern BOOL              s_initialized;
1167#endif // POWER_C
1168#if defined MEMORY_LIB_C || defined GLOBAL_C
1169//
1170//      The s_actionOutputBuffer should not be modifiable by the host system until the TPM has returned a
1171//      response code. The s_actionOutputBuffer should not be accessible until response parameter encryption,
1172//      if any, is complete.
1173//
1174extern   UINT32   s_actionInputBuffer[1024];          // action input buffer
1175extern   UINT32   s_actionOutputBuffer[1024];         // action output buffer
1176extern   BYTE     s_responseBuffer[MAX_RESPONSE_SIZE];// response buffer
1177#endif   // MEMORY_LIB_C
1178//
1179//      From TPMFail.c
1180//      This value holds the address of the string containing the name of the function in which the failure
1181//      occurred. This address value isn't useful for anything other than helping the vendor to know in which file
1182//      the failure occurred.
1183//
1184#ifndef EMBEDDED_MODE
1185extern jmp_buf   g_jumpBuffer;          //           the jump buffer
1186#endif
1187extern BOOL      g_inFailureMode;       //           Indicates that the TPM is in failure mode
1188extern BOOL      g_forceFailureMode;    //           flag to force failure mode during test
1189#if defined TPM_FAIL_C || defined GLOBAL_C           || 1
1190extern UINT32    s_failFunction;
1191extern UINT32    s_failLine;            //           the line in the file at which
1192                                       //           the error was signaled
1193extern UINT32    s_failCode;            //           the error code used
1194#endif // TPM_FAIL_C
1195#endif // GLOBAL_H
1196