Home | History | Annotate | Download | only in tpm2
      1       Trusted Platform Module Library
      2       Part 3: Commands
      3 
      4       Family 2.0
      5 
      6       Level 00 Revision 01.16
      7 
      8       October 30, 2014
      9 
     10 
     11 
     12 
     13       Contact: admin (a] trustedcomputinggroup.org
     14 
     15 
     16 
     17 
     18       TCG Published
     19       Copyright  TCG 2006-2014
     20 
     21 
     22 
     23 
     24 TCG
     25 Part 3: Commands                                                               Trusted Platform Module Library
     27 
     28 
     29 Licenses and Notices
     30 
     31 1. Copyright Licenses:
     32          Trusted Computing Group (TCG) grants to the user of the source code in this specification (the
     33           Source Code) a worldwide, irrevocable, nonexclusive, royalty free, copyright license to
     34           reproduce, create derivative works, distribute, display and perform the Source Code and
     35           derivative works thereof, and to grant others the rights granted herein.
     36          The TCG grants to the user of the other parts of the specification (other than the Source Code)
     37           the rights to reproduce, distribute, display, and perform the specification solely for the purpose of
     38           developing products based on such documents.
     39 2. Source Code Distribution Conditions:
     40          Redistributions of Source Code must retain the above copyright licenses, this list of conditions
     41           and the following disclaimers.
     42          Redistributions in binary form must reproduce the above copyright licenses, this list of conditions
     43           and the following disclaimers in the documentation and/or other materials provided with the
     44           distribution.
     45 3. Disclaimers:
     46          THE COPYRIGHT LICENSES SET FORTH ABOVE DO NOT REPRESENT ANY FORM OF
     47           LICENSE OR WAIVER, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, WITH
     48           RESPECT TO PATENT RIGHTS HELD BY TCG MEMBERS (OR OTHER THIRD PARTIES)
     49           THAT MAY BE NECESSARY TO IMPLEMENT THIS SPECIFICATION OR OTHERWISE.
     50           Contact TCG Administration (admin (a] trustedcomputinggroup.org) for information on specification
     51           licensing rights available through TCG membership agreements.
     52          THIS SPECIFICATION IS PROVIDED "AS IS" WITH NO EXPRESS OR IMPLIED WARRANTIES
     53           WHATSOEVER, INCLUDING ANY WARRANTY OF MERCHANTABILITY OR FITNESS FOR A
     54           PARTICULAR PURPOSE, ACCURACY, COMPLETENESS, OR NONINFRINGEMENT OF
     55           INTELLECTUAL PROPERTY RIGHTS, OR ANY WARRANTY OTHERWISE ARISING OUT OF
     56           ANY PROPOSAL, SPECIFICATION OR SAMPLE.
     57          Without limitation, TCG and its members and licensors disclaim all liability, including liability for
     58           infringement of any proprietary rights, relating to use of information in this specification and to the
     59           implementation of this specification, and TCG disclaims all liability for cost of procurement of
     60           substitute goods or services, lost profits, loss of use, loss of data or any incidental, consequential,
     61           direct, indirect, or special damages, whether under contract, tort, warranty or otherwise, arising in
     62           any way out of use or reliance upon this specification or any information herein.
     63 Any marks and brands contained herein are the property of their respective owner.
     64 
     65 
     66 
     67 
     68 Page ii                                         TCG Published                                      Family 2.0
     69 October 30, 2014                        Copyright  TCG 2006-2014                    Level 00 Revision 01.16
     70 Trusted Platform Module Library                                                                                                      Part 3: Commands
     72 
     73 
     74                                                                     CONTENTS
     75 
     76 1     Scope .................................................................................................................................................... 1
     77 2     Terms and Definitions ........................................................................................................................... 1
     78 3     Symbols and abbreviated terms ............................................................................................................ 1
     79 4     Notation ................................................................................................................................................. 1
     80     4.1     Introduction ..................................................................................................................................... 1
     81     4.2     Table Decorations ........................................................................................................................... 1
     82     4.3     Handle and Parameter Demarcation .............................................................................................. 3
     83     4.4     AuthorizationSize and ParameterSize ............................................................................................ 3
     84 5     Command Processing ........................................................................................................................... 4
     85     5.1     Introduction ..................................................................................................................................... 4
     86     5.2     Command Header Validation .......................................................................................................... 4
     87     5.3     Mode Checks .................................................................................................................................. 4
     88     5.4     Handle Area Validation ................................................................................................................... 5
     89     5.5     Session Area Validation .................................................................................................................. 6
     90     5.6     Authorization Checks ...................................................................................................................... 7
     91     5.7     Parameter Decryption ..................................................................................................................... 8
     92     5.8     Parameter Unmarshaling ................................................................................................................ 8
     93     5.9     Command Post Processing .......................................................................................................... 10
     94 6     Response Values ................................................................................................................................ 12
     95     6.1     Tag ................................................................................................................................................ 12
     96     6.2     Response Codes .......................................................................................................................... 12
     97 7     Implementation Dependent ................................................................................................................. 15
     98 8     Detailed Actions Assumptions ............................................................................................................. 16
     99     8.1     Introduction ................................................................................................................................... 16
    100     8.2     Pre-processing .............................................................................................................................. 16
    101     8.3     Post Processing ............................................................................................................................ 16
    102 9     Start-up ................................................................................................................................................ 17
    103     9.1     Introduction ................................................................................................................................... 17
    104     9.2     _TPM_Init...................................................................................................................................... 17
    105     9.3     TPM2_Startup ............................................................................................................................... 19
    106     9.4     TPM2_Shutdown .......................................................................................................................... 26
    107 10    Testing ................................................................................................................................................. 30
    108     10.1    Introduction ................................................................................................................................... 30
    109     10.2    TPM2_SelfTest ............................................................................................................................. 31
    110     10.3    TPM2_IncrementalSelfTest .......................................................................................................... 34
    111     10.4    TPM2_GetTestResult ................................................................................................................... 37
    112 11    Session Commands ............................................................................................................................ 40
    113     11.1    TPM2_StartAuthSession .............................................................................................................. 40
    114     11.2    TPM2_PolicyRestart ..................................................................................................................... 45
    115 12    Object Commands............................................................................................................................... 48
    116     12.1    TPM2_Create................................................................................................................................ 48
    117     12.2    TPM2_Load .................................................................................................................................. 54
    118 
    119 Family 2.0                                                      TCG Published                                                                       Page iii
    120 Level 00 Revision 01.16                                Copyright  TCG 2006-2014                                                     October 30, 2014
    121 Part 3: Commands                                                                                            Trusted Platform Module Library
    123 
    124 
    125  12.3     TPM2_LoadExternal ..................................................................................................................... 58
    126  12.4     TPM2_ReadPublic ........................................................................................................................ 63
    127  12.5     TPM2_ActivateCredential ............................................................................................................. 66
    128  12.6     TPM2_MakeCredential ................................................................................................................. 70
    129  12.7     TPM2_Unseal ............................................................................................................................... 73
    130  12.8     TPM2_ObjectChangeAuth ............................................................................................................ 76
    131 13   Duplication Commands ....................................................................................................................... 80
    132  13.1     TPM2_Duplicate ........................................................................................................................... 80
    133  13.2     TPM2_Rewrap .............................................................................................................................. 84
    134  13.3     TPM2_Import ................................................................................................................................ 88
    135 14   Asymmetric Primitives ......................................................................................................................... 94
    136  14.1     Introduction ................................................................................................................................... 94
    137  14.2     TPM2_RSA_Encrypt ..................................................................................................................... 94
    138  14.3     TPM2_RSA_Decrypt .................................................................................................................... 99
    139  14.4     TPM2_ECDH_KeyGen ............................................................................................................... 103
    140  14.5     TPM2_ECDH_ZGen ................................................................................................................... 107
    141  14.6     TPM2_ECC_Parameters ............................................................................................................ 110
    142  14.7     TPM2_ZGen_2Phase ................................................................................................................. 112
    143 15   Symmetric Primitives ......................................................................................................................... 116
    144  15.1     Introduction ................................................................................................................................. 116
    145  15.2     TPM2_EncryptDecrypt ................................................................................................................ 118
    146  15.3     TPM2_Hash ................................................................................................................................ 122
    147  15.4     TPM2_HMAC .............................................................................................................................. 125
    148 16   Random Number Generator .............................................................................................................. 129
    149  16.1     TPM2_GetRandom ..................................................................................................................... 129
    150  16.2     TPM2_StirRandom ..................................................................................................................... 132
    151 17   Hash/HMAC/Event Sequences ......................................................................................................... 135
    152  17.1     Introduction ................................................................................................................................. 135
    153  17.2     TPM2_HMAC_Start .................................................................................................................... 135
    154  17.3     TPM2_HashSequenceStart ........................................................................................................ 139
    155  17.4     TPM2_SequenceUpdate ............................................................................................................ 142
    156  17.5     TPM2_SequenceComplete......................................................................................................... 146
    157  17.6     TPM2_EventSequenceComplete ............................................................................................... 150
    158 18   Attestation Commands ...................................................................................................................... 154
    159  18.1     Introduction ................................................................................................................................. 154
    160  18.2     TPM2_Certify .............................................................................................................................. 156
    161  18.3     TPM2_CertifyCreation ................................................................................................................ 160
    162  18.4     TPM2_Quote............................................................................................................................... 164
    163  18.5     TPM2_GetSessionAuditDigest ................................................................................................... 168
    164  18.6     TPM2_GetCommandAuditDigest ............................................................................................... 172
    165  18.7     TPM2_GetTime........................................................................................................................... 176
    166 19   Ephemeral EC Keys .......................................................................................................................... 180
    167  19.1     Introduction ................................................................................................................................. 180
    168  19.2     TPM2_Commit ............................................................................................................................ 181
    169 
    170 
    171 Page iv                                                        TCG Published                                                             Family 2.0
    172 October 30, 2014                                    Copyright  TCG 2006-2014                                        Level 00 Revision 01.16
    173 Trusted Platform Module Library                                                                                                Part 3: Commands
    175 
    176 
    177   19.3    TPM2_EC_Ephemeral ................................................................................................................ 186
    178 20   Signing and Signature Verification .................................................................................................... 189
    179   20.1    TPM2_VerifySignature ................................................................................................................ 189
    180   20.2    TPM2_Sign ................................................................................................................................. 193
    181 21   Command Audit ................................................................................................................................. 197
    182   21.1    Introduction ................................................................................................................................. 197
    183   21.2    TPM2_SetCommandCodeAuditStatus ....................................................................................... 198
    184 22   Integrity Collection (PCR) .................................................................................................................. 202
    185   22.1    Introduction ................................................................................................................................. 202
    186   22.2    TPM2_PCR_Extend ................................................................................................................... 203
    187   22.3    TPM2_PCR_Event ..................................................................................................................... 206
    188   22.4    TPM2_PCR_Read ...................................................................................................................... 209
    189   22.5    TPM2_PCR_Allocate .................................................................................................................. 212
    190   22.6    TPM2_PCR_SetAuthPolicy ........................................................................................................ 215
    191   22.7    TPM2_PCR_SetAuthValue ......................................................................................................... 218
    192   22.8    TPM2_PCR_Reset ..................................................................................................................... 221
    193   22.9    _TPM_Hash_Start ...................................................................................................................... 224
    194   22.10   _TPM_Hash_Data ...................................................................................................................... 226
    195   22.11   _TPM_Hash_End ....................................................................................................................... 228
    196 23   Enhanced Authorization (EA) Commands ........................................................................................ 231
    197   23.1    Introduction ................................................................................................................................. 231
    198   23.2    Signed Authorization Actions ...................................................................................................... 232
    199   23.3    TPM2_PolicySigned ................................................................................................................... 236
    200   23.4    TPM2_PolicySecret .................................................................................................................... 242
    201   23.5    TPM2_PolicyTicket ..................................................................................................................... 246
    202   23.6    TPM2_PolicyOR ......................................................................................................................... 250
    203   23.7    TPM2_PolicyPCR ....................................................................................................................... 254
    204   23.8    TPM2_PolicyLocality .................................................................................................................. 259
    205   23.9    TPM2_PolicyNV .......................................................................................................................... 263
    206   23.10   TPM2_PolicyCounterTimer......................................................................................................... 268
    207   23.11   TPM2_PolicyCommandCode ..................................................................................................... 273
    208   23.12   TPM2_PolicyPhysicalPresence .................................................................................................. 276
    209   23.13   TPM2_PolicyCpHash .................................................................................................................. 279
    210   23.14   TPM2_PolicyNameHash ............................................................................................................. 283
    211   23.15   TPM2_PolicyDuplicationSelect ................................................................................................... 287
    212   23.16   TPM2_PolicyAuthorize ............................................................................................................... 291
    213   23.17   TPM2_PolicyAuthValue .............................................................................................................. 295
    214   23.18   TPM2_PolicyPassword ............................................................................................................... 298
    215   23.19   TPM2_PolicyGetDigest ............................................................................................................... 301
    216   23.20   TPM2_PolicyNvWritten ............................................................................................................... 304
    217 24   Hierarchy Commands........................................................................................................................ 308
    218   24.1    TPM2_CreatePrimary ................................................................................................................. 308
    219   24.2    TPM2_HierarchyControl ............................................................................................................. 312
    220   24.3    TPM2_SetPrimaryPolicy ............................................................................................................. 316
    221   24.4    TPM2_ChangePPS .................................................................................................................... 320
    222   24.5    TPM2_ChangeEPS .................................................................................................................... 323
    223 
    224 Family 2.0                                                   TCG Published                                                                    Page v
    225 Level 00 Revision 01.16                             Copyright  TCG 2006-2014                                                  October 30, 2014
    226 Part 3: Commands                                                                                            Trusted Platform Module Library
    228 
    229 
    230  24.6      TPM2_Clear ................................................................................................................................ 326
    231  24.7      TPM2_ClearControl .................................................................................................................... 330
    232  24.8      TPM2_HierarchyChangeAuth ..................................................................................................... 333
    233 25   Dictionary Attack Functions ............................................................................................................... 336
    234  25.1      Introduction ................................................................................................................................. 336
    235  25.2      TPM2_DictionaryAttackLockReset ............................................................................................. 336
    236  25.3      TPM2_DictionaryAttackParameters............................................................................................ 339
    237 26   Miscellaneous Management Functions ............................................................................................. 342
    238  26.1      Introduction ................................................................................................................................. 342
    239  26.2      TPM2_PP_Commands ............................................................................................................... 342
    240  26.3      TPM2_SetAlgorithmSet .............................................................................................................. 345
    241 27   Field Upgrade .................................................................................................................................... 348
    242  27.1      Introduction ................................................................................................................................. 348
    243  27.2      TPM2_FieldUpgradeStart ........................................................................................................... 350
    244  27.3      TPM2_FieldUpgradeData ........................................................................................................... 353
    245  27.4      TPM2_FirmwareRead ................................................................................................................. 356
    246 28   Context Management ........................................................................................................................ 359
    247  28.1      Introduction ................................................................................................................................. 359
    248  28.2      TPM2_ContextSave .................................................................................................................... 359
    249  28.3      TPM2_ContextLoad .................................................................................................................... 364
    250  28.4      TPM2_FlushContext ................................................................................................................... 369
    251  28.5      TPM2_EvictControl ..................................................................................................................... 372
    252 29   Clocks and Timers............................................................................................................................. 377
    253  29.1      TPM2_ReadClock ....................................................................................................................... 377
    254  29.2      TPM2_ClockSet .......................................................................................................................... 380
    255  29.3      TPM2_ClockRateAdjust .............................................................................................................. 383
    256 30   Capability Commands ....................................................................................................................... 386
    257  30.1      Introduction ................................................................................................................................. 386
    258  30.2      TPM2_GetCapability ................................................................................................................... 386
    259  30.3      TPM2_TestParms ....................................................................................................................... 394
    260 31   Non-volatile Storage .......................................................................................................................... 397
    261  31.1      Introduction ................................................................................................................................. 397
    262  31.2      NV Counters ............................................................................................................................... 398
    263  31.3      TPM2_NV_DefineSpace ............................................................................................................. 399
    264  31.4      TPM2_NV_UndefineSpace ......................................................................................................... 405
    265  31.5      TPM2_NV_UndefineSpaceSpecial ............................................................................................. 408
    266  31.6      TPM2_NV_ReadPublic ............................................................................................................... 411
    267  31.7      TPM2_NV_Write ......................................................................................................................... 414
    268  31.8      TPM2_NV_Increment ................................................................................................................. 418
    269  31.9      TPM2_NV_Extend ...................................................................................................................... 422
    270  31.10     TPM2_NV_SetBits ...................................................................................................................... 426
    271  31.11     TPM2_NV_WriteLock ................................................................................................................. 430
    272  31.12     TPM2_NV_GlobalWriteLock ....................................................................................................... 434
    273  31.13     TPM2_NV_Read ......................................................................................................................... 437
    274 
    275 
    276 Page vi                                                         TCG Published                                                            Family 2.0
    277 October 30, 2014                                     Copyright  TCG 2006-2014                                       Level 00 Revision 01.16
    278 Trusted Platform Module Library                                                                                         Part 3: Commands
    280 
    281 
    282   31.14 TPM2_NV_ReadLock ................................................................................................................. 440
    283   31.15 TPM2_NV_ChangeAuth ............................................................................................................. 444
    284   31.16 TPM2_NV_Certify ....................................................................................................................... 447
    285 
    286 
    287 
    288 
    289 Family 2.0                                                TCG Published                                                             Page vii
    290 Level 00 Revision 01.16                           Copyright  TCG 2006-2014                                             October 30, 2014
    291 Part 3: Commands                                                                                           Trusted Platform Module Library
    293 
    294 Tables
    295 Table 1  Command Modifiers and Decoration ........................................................................................... 2
    296 Table 2  Separators ................................................................................................................................... 3
    297 Table 3  Unmarshaling Errors ................................................................................................................. 10
    298 Table 4  Command-Independent Response Codes ................................................................................ 13
    299 Table 5  TPM2_Startup Command .......................................................................................................... 22
    300 Table 6  TPM2_Startup Response .......................................................................................................... 22
    301 Table 7  TPM2_Shutdown Command ..................................................................................................... 27
    302 Table 8  TPM2_Shutdown Response ...................................................................................................... 27
    303 Table 9  TPM2_SelfTest Command ........................................................................................................ 32
    304 Table 10  TPM2_SelfTest Response ...................................................................................................... 32
    305 Table 11  TPM2_IncrementalSelfTest Command ................................................................................... 35
    306 Table 12  TPM2_IncrementalSelfTest Response ................................................................................... 35
    307 Table 13  TPM2_GetTestResult Command ............................................................................................ 38
    308 Table 14  TPM2_GetTestResult Response............................................................................................. 38
    309 Table 15  TPM2_StartAuthSession Command ....................................................................................... 42
    310 Table 16  TPM2_StartAuthSession Response ........................................................................................ 42
    311 Table 17  TPM2_PolicyRestart Command .............................................................................................. 46
    312 Table 18  TPM2_PolicyRestart Response .............................................................................................. 46
    313 Table 19  TPM2_Create Command ........................................................................................................ 51
    314 Table 20  TPM2_Create Response ......................................................................................................... 51
    315 Table 21  TPM2_Load Command ........................................................................................................... 55
    316 Table 22  TPM2_Load Response ............................................................................................................ 55
    317 Table 23  TPM2_LoadExternal Command .............................................................................................. 60
    318 Table 24  TPM2_LoadExternal Response .............................................................................................. 60
    319 Table 25  TPM2_ReadPublic Command ................................................................................................. 64
    320 Table 26  TPM2_ReadPublic Response ................................................................................................. 64
    321 Table 27  TPM2_ActivateCredential Command ...................................................................................... 67
    322 Table 28  TPM2_ActivateCredential Response ...................................................................................... 67
    323 Table 29  TPM2_MakeCredential Command .......................................................................................... 71
    324 Table 30  TPM2_MakeCredential Response .......................................................................................... 71
    325 Table 31  TPM2_Unseal Command ........................................................................................................ 74
    326 Table 32  TPM2_Unseal Response ........................................................................................................ 74
    327 Table 33  TPM2_ObjectChangeAuth Command ..................................................................................... 77
    328 Table 34  TPM2_ObjectChangeAuth Response ..................................................................................... 77
    329 Table 35  TPM2_Duplicate Command .................................................................................................... 81
    330 Table 36  TPM2_Duplicate Response ..................................................................................................... 81
    331 Table 37  TPM2_Rewrap Command ....................................................................................................... 85
    332 Table 38  TPM2_Rewrap Response ....................................................................................................... 85
    333 
    334 Page viii                                                       TCG Published                                                          Family 2.0
    335 October 30, 2014                                     Copyright  TCG 2006-2014                                     Level 00 Revision 01.16
    336 Trusted Platform Module Library                                                                                       Part 3: Commands
    338 
    339 Table 39  TPM2_Import Command ......................................................................................................... 90
    340 Table 40  TPM2_Import Response ......................................................................................................... 90
    341 Table 41  Padding Scheme Selection ..................................................................................................... 94
    342 Table 42  Message Size Limits Based on Padding ................................................................................. 95
    343 Table 43  TPM2_RSA_Encrypt Command.............................................................................................. 96
    344 Table 44  TPM2_RSA_Encrypt Response .............................................................................................. 96
    345 Table 45  TPM2_RSA_Decrypt Command ........................................................................................... 100
    346 Table 46  TPM2_RSA_Decrypt Response ............................................................................................ 100
    347 Table 47  TPM2_ECDH_KeyGen Command ........................................................................................ 104
    348 Table 48  TPM2_ECDH_KeyGen Response ........................................................................................ 104
    349 Table 49  TPM2_ECDH_ZGen Command ............................................................................................ 108
    350 Table 50  TPM2_ECDH_ZGen Response ............................................................................................ 108
    351 Table 51  TPM2_ECC_Parameters Command ..................................................................................... 110
    352 Table 52  TPM2_ECC_Parameters Response ..................................................................................... 110
    353 Table 53  TPM2_ZGen_2Phase Command .......................................................................................... 113
    354 Table 54  TPM2_ZGen_2Phase Response .......................................................................................... 113
    355 Table 55  Symmetric Chaining Process ................................................................................................ 117
    356 Table 56  TPM2_EncryptDecrypt Command......................................................................................... 119
    357 Table 57  TPM2_EncryptDecrypt Response ......................................................................................... 119
    358 Table 58  TPM2_Hash Command ......................................................................................................... 123
    359 Table 59  TPM2_Hash Response ......................................................................................................... 123
    360 Table 60  TPM2_HMAC Command ....................................................................................................... 126
    361 Table 61  TPM2_HMAC Response ....................................................................................................... 126
    362 Table 62  TPM2_GetRandom Command .............................................................................................. 130
    363 Table 63  TPM2_GetRandom Response .............................................................................................. 130
    364 Table 64  TPM2_StirRandom Command .............................................................................................. 133
    365 Table 65  TPM2_StirRandom Response ............................................................................................... 133
    366 Table 66  Hash Selection Matrix ........................................................................................................... 135
    367 Table 67  TPM2_HMAC_Start Command ............................................................................................. 136
    368 Table 68  TPM2_HMAC_Start Response ............................................................................................. 136
    369 Table 69  TPM2_HashSequenceStart Command ................................................................................. 140
    370 Table 70  TPM2_HashSequenceStart Response ................................................................................. 140
    371 Table 71  TPM2_SequenceUpdate Command ..................................................................................... 143
    372 Table 72  TPM2_SequenceUpdate Response ...................................................................................... 143
    373 Table 73  TPM2_SequenceComplete Command ................................................................................. 147
    374 Table 74  TPM2_SequenceComplete Response .................................................................................. 147
    375 Table 75  TPM2_EventSequenceComplete Command ........................................................................ 151
    376 Table 76  TPM2_EventSequenceComplete Response ......................................................................... 151
    377 Table 77  TPM2_Certify Command ....................................................................................................... 157
    378 Family 2.0                                                TCG Published                                                           Page ix
    379 Level 00 Revision 01.16                           Copyright  TCG 2006-2014                                           October 30, 2014
    380 Part 3: Commands                                                                                 Trusted Platform Module Library
    382 
    383 Table 78  TPM2_Certify Response ....................................................................................................... 157
    384 Table 79  TPM2_CertifyCreation Command ......................................................................................... 161
    385 Table 80  TPM2_CertifyCreation Response .......................................................................................... 161
    386 Table 81  TPM2_Quote Command ....................................................................................................... 165
    387 Table 82  TPM2_Quote Response ........................................................................................................ 165
    388 Table 83  TPM2_GetSessionAuditDigest Command ............................................................................ 169
    389 Table 84  TPM2_GetSessionAuditDigest Response ............................................................................ 169
    390 Table 85  TPM2_GetCommandAuditDigest Command ........................................................................ 173
    391 Table 86  TPM2_GetCommandAuditDigest Response ......................................................................... 173
    392 Table 87  TPM2_GetTime Command ................................................................................................... 177
    393 Table 88  TPM2_GetTime Response .................................................................................................... 177
    394 Table 89  TPM2_Commit Command ..................................................................................................... 182
    395 Table 90  TPM2_Commit Response ..................................................................................................... 182
    396 Table 91  TPM2_EC_Ephemeral Command ......................................................................................... 187
    397 Table 92  TPM2_EC_Ephemeral Response ......................................................................................... 187
    398 Table 93  TPM2_VerifySignature Command......................................................................................... 190
    399 Table 94  TPM2_VerifySignature Response ......................................................................................... 190
    400 Table 95  TPM2_Sign Command .......................................................................................................... 194
    401 Table 96  TPM2_Sign Response .......................................................................................................... 194
    402 Table 97  TPM2_SetCommandCodeAuditStatus Command ................................................................ 199
    403 Table 98  TPM2_SetCommandCodeAuditStatus Response ................................................................ 199
    404 Table 99  TPM2_PCR_Extend Command ............................................................................................ 204
    405 Table 100  TPM2_PCR_Extend Response ........................................................................................... 204
    406 Table 101  TPM2_PCR_Event Command ............................................................................................ 207
    407 Table 102  TPM2_PCR_Event Response ............................................................................................. 207
    408 Table 103  TPM2_PCR_Read Command ............................................................................................. 210
    409 Table 104  TPM2_PCR_Read Response ............................................................................................. 210
    410 Table 105  TPM2_PCR_Allocate Command ......................................................................................... 213
    411 Table 106  TPM2_PCR_Allocate Response ......................................................................................... 213
    412 Table 107  TPM2_PCR_SetAuthPolicy Command ............................................................................... 216
    413 Table 108  TPM2_PCR_SetAuthPolicy Response ............................................................................... 216
    414 Table 109  TPM2_PCR_SetAuthValue Command ............................................................................... 219
    415 Table 110  TPM2_PCR_SetAuthValue Response ................................................................................ 219
    416 Table 111  TPM2_PCR_Reset Command ............................................................................................ 222
    417 Table 112  TPM2_PCR_Reset Response ............................................................................................. 222
    418 Table 113  TPM2_PolicySigned Command .......................................................................................... 238
    419 Table 114  TPM2_PolicySigned Response ........................................................................................... 238
    420 Table 115  TPM2_PolicySecret Command ........................................................................................... 243
    421 Table 116  TPM2_PolicySecret Response ............................................................................................ 243
    422 Page x                                                    TCG Published                                                   Family 2.0
    423 October 30, 2014                                Copyright  TCG 2006-2014                                Level 00 Revision 01.16
    424 Trusted Platform Module Library                                                                                Part 3: Commands
    426 
    427 Table 117  TPM2_PolicyTicket Command ............................................................................................ 247
    428 Table 118  TPM2_PolicyTicket Response ............................................................................................ 247
    429 Table 119  TPM2_PolicyOR Command ................................................................................................ 251
    430 Table 120  TPM2_PolicyOR Response ................................................................................................. 251
    431 Table 121  TPM2_PolicyPCR Command .............................................................................................. 256
    432 Table 122  TPM2_PolicyPCR Response .............................................................................................. 256
    433 Table 123  TPM2_PolicyLocality Command ......................................................................................... 260
    434 Table 124  TPM2_PolicyLocality Response .......................................................................................... 260
    435 Table 125  TPM2_PolicyNV Command ................................................................................................. 264
    436 Table 126  TPM2_PolicyNV Response ................................................................................................. 264
    437 Table 127  TPM2_PolicyCounterTimer Command ............................................................................... 269
    438 Table 128  TPM2_PolicyCounterTimer Response ................................................................................ 269
    439 Table 129  TPM2_PolicyCommandCode Command ............................................................................ 274
    440 Table 130  TPM2_PolicyCommandCode Response ............................................................................. 274
    441 Table 131  TPM2_PolicyPhysicalPresence Command ......................................................................... 277
    442 Table 132  TPM2_PolicyPhysicalPresence Response ......................................................................... 277
    443 Table 133  TPM2_PolicyCpHash Command......................................................................................... 280
    444 Table 134  TPM2_PolicyCpHash Response ......................................................................................... 280
    445 Table 135  TPM2_PolicyNameHash Command.................................................................................... 284
    446 Table 136  TPM2_PolicyNameHash Response .................................................................................... 284
    447 Table 137  TPM2_PolicyDuplicationSelect Command .......................................................................... 288
    448 Table 138  TPM2_PolicyDuplicationSelect Response .......................................................................... 288
    449 Table 139  TPM2_PolicyAuthorize Command ...................................................................................... 292
    450 Table 140  TPM2_PolicyAuthorize Response ....................................................................................... 292
    451 Table 141  TPM2_PolicyAuthValue Command ..................................................................................... 296
    452 Table 142  TPM2_PolicyAuthValue Response ..................................................................................... 296
    453 Table 143  TPM2_PolicyPassword Command ...................................................................................... 299
    454 Table 144  TPM2_PolicyPassword Response ...................................................................................... 299
    455 Table 145  TPM2_PolicyGetDigest Command...................................................................................... 302
    456 Table 146  TPM2_PolicyGetDigest Response ...................................................................................... 302
    457 Table 147  TPM2_PolicyNvWritten Command ...................................................................................... 305
    458 Table 148  TPM2_PolicyNvWritten Response ...................................................................................... 305
    459 Table 149  TPM2_CreatePrimary Command ........................................................................................ 309
    460 Table 150  TPM2_CreatePrimary Response ........................................................................................ 309
    461 Table 151  TPM2_HierarchyControl Command .................................................................................... 313
    462 Table 152  TPM2_HierarchyControl Response .................................................................................... 313
    463 Table 153  TPM2_SetPrimaryPolicy Command .................................................................................... 317
    464 Table 154  TPM2_SetPrimaryPolicy Response .................................................................................... 317
    465 Table 155  TPM2_ChangePPS Command ........................................................................................... 321
    466 Family 2.0                                            TCG Published                                                        Page xi
    467 Level 00 Revision 01.16                        Copyright  TCG 2006-2014                                       October 30, 2014
    468 Part 3: Commands                                                                                Trusted Platform Module Library
    470 
    471 Table 156  TPM2_ChangePPS Response ............................................................................................ 321
    472 Table 157  TPM2_ChangeEPS Command ........................................................................................... 324
    473 Table 158  TPM2_ChangeEPS Response ............................................................................................ 324
    474 Table 159  TPM2_Clear Command ....................................................................................................... 327
    475 Table 160  TPM2_Clear Response ....................................................................................................... 327
    476 Table 161  TPM2_ClearControl Command ........................................................................................... 331
    477 Table 162  TPM2_ClearControl Response ........................................................................................... 331
    478 Table 163  TPM2_HierarchyChangeAuth Command ............................................................................ 334
    479 Table 164  TPM2_HierarchyChangeAuth Response ............................................................................ 334
    480 Table 165  TPM2_DictionaryAttackLockReset Command .................................................................... 337
    481 Table 166  TPM2_DictionaryAttackLockReset Response .................................................................... 337
    482 Table 167  TPM2_DictionaryAttackParameters Command .................................................................. 340
    483 Table 168  TPM2_DictionaryAttackParameters Response ................................................................... 340
    484 Table 169  TPM2_PP_Commands Command ...................................................................................... 343
    485 Table 170  TPM2_PP_Commands Response ...................................................................................... 343
    486 Table 171  TPM2_SetAlgorithmSet Command ..................................................................................... 346
    487 Table 172  TPM2_SetAlgorithmSet Response...................................................................................... 346
    488 Table 173  TPM2_FieldUpgradeStart Command .................................................................................. 351
    489 Table 174  TPM2_FieldUpgradeStart Response .................................................................................. 351
    490 Table 175  TPM2_FieldUpgradeData Command .................................................................................. 354
    491 Table 176  TPM2_FieldUpgradeData Response .................................................................................. 354
    492 Table 177  TPM2_FirmwareRead Command........................................................................................ 357
    493 Table 178  TPM2_FirmwareRead Response ........................................................................................ 357
    494 Table 179  TPM2_ContextSave Command........................................................................................... 360
    495 Table 180  TPM2_ContextSave Response ........................................................................................... 360
    496 Table 181  TPM2_ContextLoad Command ........................................................................................... 365
    497 Table 182  TPM2_ContextLoad Response ........................................................................................... 365
    498 Table 183  TPM2_FlushContext Command .......................................................................................... 370
    499 Table 184  TPM2_FlushContext Response .......................................................................................... 370
    500 Table 185  TPM2_EvictControl Command ............................................................................................ 374
    501 Table 186  TPM2_EvictControl Response ............................................................................................ 374
    502 Table 187  TPM2_ReadClock Command.............................................................................................. 378
    503 Table 188  TPM2_ReadClock Response .............................................................................................. 378
    504 Table 189  TPM2_ClockSet Command ................................................................................................. 381
    505 Table 190  TPM2_ClockSet Response ................................................................................................. 381
    506 Table 191  TPM2_ClockRateAdjust Command..................................................................................... 384
    507 Table 192  TPM2_ClockRateAdjust Response ..................................................................................... 384
    508 Table 193  TPM2_GetCapability Command.......................................................................................... 390
    509 Table 194  TPM2_GetCapability Response .......................................................................................... 390
    510 Page xii                                                  TCG Published                                                  Family 2.0
    511 October 30, 2014                                Copyright  TCG 2006-2014                               Level 00 Revision 01.16
    512 Trusted Platform Module Library                                                                               Part 3: Commands
    514 
    515 Table 195  TPM2_TestParms Command .............................................................................................. 395
    516 Table 196  TPM2_TestParms Response .............................................................................................. 395
    517 Table 197  TPM2_NV_DefineSpace Command ................................................................................... 401
    518 Table 198  TPM2_NV_DefineSpace Response .................................................................................... 401
    519 Table 199  TPM2_NV_UndefineSpace Command ............................................................................... 406
    520 Table 200  TPM2_NV_UndefineSpace Response ................................................................................ 406
    521 Table 201  TPM2_NV_UndefineSpaceSpecial Command .................................................................... 409
    522 Table 202  TPM2_NV_UndefineSpaceSpecial Response .................................................................... 409
    523 Table 203  TPM2_NV_ReadPublic Command ...................................................................................... 412
    524 Table 204  TPM2_NV_ReadPublic Response ...................................................................................... 412
    525 Table 205  TPM2_NV_Write Command ................................................................................................ 415
    526 Table 206  TPM2_NV_Write Response ................................................................................................ 415
    527 Table 207  TPM2_NV_Increment Command ........................................................................................ 419
    528 Table 208  TPM2_NV_Increment Response......................................................................................... 419
    529 Table 209  TPM2_NV_Extend Command ............................................................................................. 423
    530 Table 210  TPM2_NV_Extend Response ............................................................................................. 423
    531 Table 211  TPM2_NV_SetBits Command ............................................................................................. 427
    532 Table 212  TPM2_NV_SetBits Response ............................................................................................. 427
    533 Table 213  TPM2_NV_WriteLock Command ........................................................................................ 431
    534 Table 214  TPM2_NV_WriteLock Response......................................................................................... 431
    535 Table 215  TPM2_NV_GlobalWriteLock Command .............................................................................. 435
    536 Table 216  TPM2_NV_GlobalWriteLock Response .............................................................................. 435
    537 Table 217  TPM2_NV_Read Command................................................................................................ 438
    538 Table 218  TPM2_NV_Read Response ................................................................................................ 438
    539 Table 219  TPM2_NV_ReadLock Command ........................................................................................ 441
    540 Table 220  TPM2_NV_ReadLock Response ........................................................................................ 441
    541 Table 221  TPM2_NV_ChangeAuth Command .................................................................................... 445
    542 Table 222  TPM2_NV_ChangeAuth Response .................................................................................... 445
    543 Table 223  TPM2_NV_Certify Command .............................................................................................. 448
    544 Table 224  TPM2_NV_Certify Response .............................................................................................. 448
    545 
    546 
    547 
    548 
    549 Family 2.0                                            TCG Published                                                      Page xiii
    550 Level 00 Revision 01.16                        Copyright  TCG 2006-2014                                      October 30, 2014
    551 Trusted Platform Module Library                                                       Part 3: Commands
    554 
    555 
    556                               Trusted Platform Module Library
    557                                      Part 3: Commands
    558 
    559 1     Scope
    560 
    561 This TPM 2.0 Part 3 of the Trusted Platform Module Library specification contains the definitions of the
    562 TPM commands. These commands make use of the constants, flags, structures, and union definitions
    563 defined in TPM 2.0 Part 2.
    564 The detailed description of the operation of the commands is written in the C language with extensive
    565 comments. The behavior of the C code in this TPM 2.0 Part 3 is normative but does not fully describe the
    566 behavior of a TPM. The combination of this TPM 2.0 Part 3 and TPM 2.0 Part 4 is sufficient to fully
    567 describe the required behavior of a TPM.
    568 The code in parts 3 and 4 is written to define the behavior of a compliant TPM. In some cases (e.g.,
    569 firmware update), it is not possible to provide a compliant implementation. In those cases, any
    570 implementation provided by the vendor that meets the general description of the function provided in TPM
    571 2.0 Part 3 would be compliant.
    572 The code in parts 3 and 4 is not written to meet any particular level of conformance nor does this
    573 specification require that a TPM meet any particular level of conformance.
    574 
    575 
    576 2     Terms and Definitions
    577 
    578 For the purposes of this document, the terms and definitions given in TPM 2.0 Part 1 apply.
    579 
    580 
    581 3     Symbols and abbreviated terms
    582 
    583 For the purposes of this document, the symbols and abbreviated terms given in TPM 2.0 Part 1 apply.
    584 
    585 
    586 4     Notation
    587 
    588 4.1 Introduction
    589 
    590 For the purposes of this document, the notation given in TPM 2.0 Part 1 applies.
    591 Command and response tables use various decorations to indicate the fields of the command and the
    592 allowed types. These decorations are described in this clause.
    593 
    594 4.2    Table Decorations
    595 
    596 The symbols and terms in the Notation column of Table 1 are used in the tables for the command
    597 schematics. These values indicate various qualifiers for the parameters or descriptions with which they
    598 are associated.
    599 
    600 
    601 
    602 
    603 Family 2.0                                TCG Published                                       Page 1
    604 Level 00 Revision 01.16             Copyright  TCG 2006-2014                         October 30, 2014
    605 Part 3: Commands                                                                      Trusted Platform Module Library
    607 
    608                              Table 1  Command Modifiers and Decoration
    609   Notation     Meaning
    610 
    611      +         A Type decoration  When appended to a value in the Type column of a command, this symbol
    612                indicates that the parameter is allowed to use the null value of the data type (see "Conditional
    613                Types" in TPM 2.0 Part 2). The null value is usually TPM_RH_NULL for a handle or
    614                TPM_ALG_NULL for an algorithm selector.
    615      @         A Name decoration  When this symbol precedes a handle parameter in the Name column, it
    616                indicates that an authorization session is required for use of the entity associated with the handle.
    617                If a handle does not have this symbol, then an authorization session is not allowed.
    618     +PP        A Description modifier  This modifier may follow TPM_RH_PLATFORM in the Description
    619                column to indicate that Physical Presence is required when platformAuth/platformPolicy is
    620                provided.
    621     +{PP}      A Description modifier  This modifier may follow TPM_RH_PLATFORM to indicate that Physical
    622                Presence may be required when platformAuth/platformPolicy is provided. The commands with this
    623                notation may be in the setList or clearList of TPM2_PP_Commands().
    624     {NV}       A Description modifier  This modifier may follow the commandCode in the Description column
    625                to indicate that the command may result in an update of NV memory and be subject to rate
    626                throttling by the TPM. If the command code does not have this notation, then a write to NV
    627                memory does not occur as part of the command actions.
    628                NOTE        Any command that uses authorization may cause a write to NV if there is an authorization failure.
    629                            A TPM may use the occasion of command execution to update the NV copy of clock.
    630 
    631      {F}       A Description modifier  This modifier indicates that the flushed attribute will be SET in the
    632                TPMA_CC for the command. The modifier may follow the commandCode in the Description
    633                column to indicate that any transient handle context used by the command will be flushed from the
    634                TPM when the command completes. This may be combined with the {NV} modifier but not with the
    635                {E} modifier.
    636                EXAMPLE 1       {NV F}
    637                EXAMPLE 2       TPM2_SequenceComplete() will flush the context associated with the sequenceHandle.
    638 
    639      {E}       A Description modifier  This modifier indicates that the extensive attribute will be SET in the
    640                TPMA_CC for the command. This modifier may follow the commandCode in the Description
    641                column to indicate that the command may flush many objects and re-enumeration of the loaded
    642                context likely will be required. This may be combined with the {NV} modifier but not with the {F}
    643                modifier.
    644                EXAMPLE 1       {NV E}
    645                EXAMPLE 2       TPM2_Clear() will flush all contexts associated with the Storage hierarchy and the
    646                                Endorsement hierarchy.
    647 
    648  Auth Index:   A Description modifier  When a handle has a @ decoration, the Description column will
    649                contain an Auth Index: entry for the handle. This entry indicates the number of the authorization
    650                session. The authorization sessions associated with handles will occur in the session area in the
    651                order of the handles with the @ modifier. Sessions used only for encryption/decryption or only for
    652                audit will follow the handles used for authorization.
    653 
    654 
    655 
    656 
    657 Page 2                                           TCG Published                                                Family 2.0
    658 October 30, 2014                        Copyright  TCG 2006-2014                            Level 00 Revision 01.16
    659 Trusted Platform Module Library                                                                       Part 3: Commands
    661 
    662 
    663   Notation      Meaning
    664 
    665   Auth Role:    A Description modifier  This will be in the Description column of a handle with the @
    666                 decoration. It may have a value of USER, ADMIN or DUP.
    667                 If the handle has the Auth Role of USER and the handle is an Object, the type of authorization is
    668                 determined by the setting of userWithAuth in the Object's attributes. If the handle is
    669                 TPM_RH_OWNER, TPM_RH_ENDORSEMENT, or TPM_RH_PLATFORM, operation is as if
    670                 userWithAuth is SET. If the handle references an NV Index, then the allowed authorizations are
    671                 determined by the settings of the attributes of the NV Index as described in TPM 2.0 Part 2,
    672                 "TPMA_NV (NV Index Attributes)."
    673                 If the Auth Role is ADMIN and the handle is an Object, the type of authorization is determined by
    674                 the setting of adminWithPolicy in the Object's attributes. If the handle is TPM_RH_OWNER,
    675                 TPM_RH_ENDORSEMENT, or TPM_RH_PLATFORM, operation is as if adminWithPolicy is SET.
    676                 If the handle is an NV index, operation is as if adminWithPolicy is SET (see 5.6 e)2)).
    677                 If the DUP role is selected, authorization may only be with a policy session (DUP role only applies
    678                 to Objects).
    679                 When either ADMIN or DUP role is selected, a policy command that selects the command being
    680                 authorized is required to be part of the policy.
    681                 EXAMPLE    TPM2_Certify requires the ADMIN role for the first handle (objectHandle). The policy authorization
    682                            for objectHandle is required to contain TPM2_PolicyCommandCode(commandCode ==
    683                            TPM_CC_Certify). This sets the state of the policy so that it can be used for ADMIN role
    684                            authorization in TPM2_Certify().
    685 
    686 
    687 
    688 
    689 4.3    Handle and Parameter Demarcation
    690 
    691 The demarcations between the header, handle, and parameter parts are indicated by:
    692 
    693                                              Table 2  Separators
    694                Separator            Meaning
    695                                     the values immediately following are in the handle area
    696 
    697                                     the values immediately following are in the parameter area
    698 
    699 
    700 4.4    AuthorizationSize and ParameterSize
    701 
    702 Authorization sessions are not shown in the command or response schematics. When the tag of a
    703 command or response is TPM_ST_SESSIONS, then a 32-bit value will be present in the
    704 command/response buffer to indicate the size of the authorization field or the parameter field. This value
    705 shall immediately follow the handle area (which may contain no handles). For a command, this value
    706 (authorizationSize) indicates the size of the Authorization Area and shall have a value of 9 or more. For a
    707 response, this value (parameterSize) indicates the size of the parameter area and may have a value of
    708 zero.
    709 If the authorizationSize field is present in the command, parameterSize will be present in the response,
    710 but only if the responseCode is TPM_RC_SUCCESS.
    711 When authorization is required to use the TPM entity associated with a handle, then at least one session
    712 will be present. To indicate this, the command tag Description field contains TPM_ST_SESSIONS.
    713 Addional sessions for audit, encrypt, and decrypt may be present.
    714 When the command tag Description field contains TPM_ST_NO_SESSIONS, then no sessions are
    715 allowed and the authorizationSize field is not present.
    716 When a command allows use of sessions when not required, the command tag Description field will
    717 indicate the types of sessions that may be used with the command.
    718 
    719 
    720 Family 2.0                                     TCG Published                                                      Page 3
    721 Level 00 Revision 01.16                 Copyright  TCG 2006-2014                                     October 30, 2014
    722 Part 3: Commands                                                               Trusted Platform Module Library
    724 
    725 
    726 5     Command Processing
    727 
    728 5.1     Introduction
    729 
    730 This clause defines the command validations that are required of any implementation and the response
    731 code returned if the indicated check fails. Unless stated otherwise, the order of the checks is not
    732 normative and different TPM may give different responses when a command has multiple errors.
    733 In the description below, some statements that describe a check may be followed by a response code in
    734 parentheses. This is the normative response code should the indicated check fail. A normative response
    735 code may also be included in the statement.
    736 
    737 5.2     Command Header Validation
    738 
    739 Before a TPM may begin the actions associated with a command, a set of command format and
    740 consistency checks shall be performed. These checks are listed below and should be performed in the
    741 indicated order.
    742 a) The TPM shall successfully unmarshal a TPMI_ST_COMMAND_TAG and verify that it is either
    743    TPM_ST_SESSIONS or TPM_ST_NO_SESSIONS (TPM_RC_BAD_TAG).
    744 b) The TPM shall successfully unmarshal a UINT32 as the commandSize. If the TPM has an interface
    745    buffer that is loaded by some hardware process, the number of octets in the input buffer for the
    746    command reported by the hardware process shall exactly match the value in commandSize
    747    (TPM_RC_COMMAND_SIZE).
    748 
    749       NOTE          A TPM may have direct access to system memory and unmarshal direc tly from that memory.
    750 
    751 c) The TPM shall successfully unmarshal a TPM_CC and verify that the command is implemented
    752    (TPM_RC_COMMAND_CODE).
    753 
    754 5.3     Mode Checks
    755 
    756 The following mode checks shall be performed in the order listed:
    757 a) If the TPM is in Failure mode, then the commandCode is TPM_CC_GetTestResult or
    758    TPM_CC_GetCapability (TPM_RC_FAILURE) and the command tag is TPM_ST_NO_SESSIONS
    759    (TPM_RC_FAILURE).
    760 
    761       NOTE 1        In Failure mode, the TPM has no cryptographic capability and processing of sessions is not
    762                     supported.
    763 
    764 b) The TPM is in Field Upgrade mode (FUM), the commandCode is TPM_CC_FieldUpgradeData
    765    (TPM_RC_UPGRADE).
    766 c) If the TPM has not been initialized (TPM2_Startup()), then the commandCode is TPM_CC_Startup
    767    (TPM_RC_INITIALIZE).
    768 
    769       NOTE 2        The TPM may enter Failure mode during _TPM_Init processing, before TPM2_Startup(). Since
    770                     the platform firmware cannot know that the TPM is in Failure mode without accessing it, and
    771                     since the first command is required to be TPM2_Startup(), the expected sequence will be that
    772                     platform firmware (the CRTM) will issue TPM2_Startup() and receive TPM_RC_FAILURE
    773                     indicating that the TPM is in Failure mode.
    774 
    775                     There may be failures where a TPM cannot record that it received TPM2_Startup(). In those
    776                     cases, a TPM in failure mode may process TPM2_GetTestResult(), TPM2_GetCapability(), or
    777                     the field upgrade commands. As a side effect, that TPM may process TPM2_GetTestResult(),
    778                     TPM2_GetCapability() or the field upgrade commands before TPM2_Startup().
    779 
    780                     This is a corner case exception to the rule that TPM2_Startup() must be the first command.
    781 
    782 Page 4                                        TCG Published                                         Family 2.0
    783 October 30, 2014                      Copyright  TCG 2006-2014                       Level 00 Revision 01.16
    784 Trusted Platform Module Library                                                                      Part 3: Commands
    786 
    787 The mode checks may be performed before or after the command header validation.
    788 
    789 5.4 Handle Area Validation
    790 
    791 After successfully unmarshaling and validating the command header, the TPM shall perform the following
    792 checks on the handles and sessions. These checks may be performed in any order.
    793 
    794 NOTE 1             A TPM is required to perform the handle area validation before the authorization checks because an
    795                    authorization cannot be performed unless the authorization values and attributes for the referenc ed
    796                    entity are known by the TPM. For them to be known, the referenced entity must be in the TPM and
    797                    accessible.
    798 
    799 a) The TPM shall successfully unmarshal the number of handles required by the command and validate
    800    that the value of the handle is consistent with the command syntax. If not, the TPM shall return
    801    TPM_RC_VALUE.
    802 
    803     NOTE 2              The TPM may unmarshal a handle and validate that it references an entity on the TPM before
    804                         unmarshaling a subsequent handle.
    805 
    806     NOTE 3              If the submitted command contains fewer handles than re quired by the syntax of the command,
    807                         the TPM may continue to read into the next area and attempt to interpret the data as a handle.
    808 
    809 b) For all handles in the handle area of the command, the TPM will validate that the referenced entity is
    810    present in the TPM.
    811     1) If the handle references a transient object, the handle shall reference a loaded object
    812        (TPM_RC_REFERENCE_H0 + N where N is the number of the handle in the command).
    813 
    814          NOTE 3             If the hierarchy for a transient object is disabled, then the transient objects will be flushed
    815                             so this check will fail.
    816 
    817     2) If the handle references a persistent object, then
    818          i)    the hierarchy associated with the object (platform or storage, based on the handle value) is
    819                enabled (TPM_RC_HANDLE);
    820          ii)   the handle shall reference a persistent object that is currently in TPM non-volatile memory
    821                (TPM_RC_HANDLE);
    822          iii) if the handle references a persistent object that is associated with the endorsement hierarchy,
    823               that the endorsement hierarchy is not disabled (TPM_RC_HANDLE); and
    824 
    825                NOTE 4           The reference implementation keeps an internal attribute, passed down from a primary
    826                                 key to its descendents, indicating the object's hierarchy.
    827 
    828          iv) if the TPM implementation moves a persistent object to RAM for command processing then
    829              sufficient RAM space is available (TPM_RC_OBJECT_MEMORY).
    830     3) If the handle references an NV Index, then
    831          i)    an Index exists that corresponds to the handle (TPM_RC_HANDLE); and
    832          ii)   the hierarchy associated with the existing NV Index is not disabled (TPM_RC_HANDLE).
    833          iii) If the command requires write access to the index data then TPMA_NV_WRITELOCKED is
    834               not SET (TPM_RC_LOCKED)
    835          iv) If the command requires read access to the index data then TPMA_NV_READLOCKED is
    836              not SET (TPM_RC_LOCKED)
    837     4) If the handle references a session, then the session context shall be present in TPM memory
    838        (TPM_RC_REFERENCE_S0 + N).
    839 
    840 
    841 
    842 Family 2.0                                       TCG Published                                                  Page 5
    843 Level 00 Revision 01.16                   Copyright  TCG 2006-2014                                  October 30, 2014
    844 Part 3: Commands                                                                Trusted Platform Module Library
    846 
    847       5) If the handle references a primary seed for a hierarchy (TPM_RH_ENDORSEMENT,
    848          TPM_RH_OWNER, or TPM_RH_PLATFORM) then the enable for the hierarchy is SET
    849          (TPM_RC_HIERARCHY).
    850       6) If the handle references a PCR, then the value is within the range of PCR supported by the TPM
    851          (TPM_RC_VALUE)
    852 
    853           NOTE 5           In the reference implementation, this TPM_RC_VALUE is returned by the unmarshaling
    854                            code for a TPMI_DH_PCR.
    855 
    856 
    857 5.5      Session Area Validation
    858 
    859 a) If the tag is TPM_ST_SESSIONS and the command requires TPM_ST_NO_SESSIONS, the TPM will
    860    return TPM_RC_AUTH_CONTEXT.
    861 b) If the tag is TPM_ST_NO_SESSIONS and the command requires TPM_ST_SESSIONS, the TPM will
    862    return TPM_RC_AUTH_MISSING.
    863 c) If the tag is TPM_ST_SESSIONS, the TPM will attempt to unmarshal an authorizationSize and return
    864    TPM_RC_AUTHSIZE if the value is not within an acceptable range.
    865       1) The minimum value is (sizeof(TPM_HANDLE) + sizeof(UINT16) + sizeof(TPMA_SESSION) +
    866          sizeof(UINT16)).
    867       2) The maximum value of authorizationSize is equal to commandSize  (sizeof(TPM_ST) +
    868          sizeof(UINT32) + sizeof(TPM_CC) + (N * sizeof(TPM_HANDLE)) + sizeof(UINT32)) where N is
    869          the number of handles associated with the commandCode and may be zero.
    870 
    871           NOTE 1           (sizeof(TPM_ST) + sizeof(UINT32) + sizeof(TPM_CC)) is the size of a command header.
    872                            The last UINT32 contains the authorizationSize octets, which are not counted as being in
    873                            the authorization session area.
    874 
    875 d) The TPM will unmarshal the authorization sessions and perform the following validations:
    876       1) If the session handle is not a handle for an HMAC session, a handle for a policy session, or,
    877          TPM_RS_PW then the TPM shall return TPM_RC_HANDLE.
    878       2) If the session is not loaded, the TPM will return the warning TPM_RC_REFERENCE_S0 + N
    879          where N is the number of the session. The first session is session zero, N = 0.
    880 
    881           NOTE 2           If the HMAC and policy session contexts use the same memory, the type of the context
    882                            must match the type of the handle.
    883 
    884       3) If the maximum allowed number of sessions have been unmarshaled and fewer octets than
    885          indicated in authorizationSize were unmarshaled (that is, authorizationSize is too large), the TPM
    886          shall return TPM_RC_AUTHSIZE.
    887       4) The consistency of the authorization session attributes is checked.
    888           i)   Only one session is allowed for:
    889                (a) session auditing (TPM_RC_ATTRIBUTES)  this session may be used for encrypt or
    890                    decrypt but may not be a session that is also used for authorization;
    891                (b) decrypting a command parameter (TPM_RC_ATTRIBUTES)  this may be any of the
    892                    authorization sessions, or the audit session, or a session may be added for the single
    893                    purpose of decrypting a command parameter, as long as the total number of sessions
    894                    does not exceed three; and
    895                (c) encrypting a response parameter (TPM_RC_ATTRIBUTES)  this may be any of the
    896                    authorization sessions, or the audit session if present, ora session may be added for the
    897                    single purpose of encrypting a response parameter, as long as the total number of
    898                    sessions does not exceed three.
    899 
    900 Page 6                                            TCG Published                                      Family 2.0
    901 October 30, 2014                        Copyright  TCG 2006-2014                     Level 00 Revision 01.16
    902 Trusted Platform Module Library                                                                    Part 3: Commands
    904 
    905                     NOTE 3            A session used for decrypting a command parameter may also be used for
    906                                       encrypting a response parameter.
    907 
    908           ii)   If a session is not being used for authorization, at least one of decrypt, encrypt, or audit must
    909                 be SET. (TPM_RC_ATTRIBUTES).
    910 
    911 
    912       5) An authorization session is present for each of the handles with the @ decoration
    913          (TPM_RC_AUTH_MISSING).
    914 
    915 
    916 
    917 5.6      Authorization Checks
    918 
    919 After unmarshaling and validating the handles and the consistency of the authorization sessions, the
    920 authorizations shall be checked. Authorization checks only apply to handles if the handle in the command
    921 schematic has the @ decoration.
    922 a) The public and sensitive portions                   of   the     object   shall   be     present      on     the   TPM
    923    (TPM_RC_AUTH_UNAVAILABLE).
    924 b) If the associated handle is TPM_RH_PLATFORM, and the command requires confirmation with
    925    physical presence, then physical presence is asserted (TPM_RC_PP).
    926 c) If the object or NV Index is subject to DA protection, and the authorization is with an HMAC or
    927    password, then the TPM is not in lockout (TPM_RC_LOCKOUT).
    928 
    929       NOTE 1            An object is subject to DA protection if its noDA attribute is CLEAR. An NV Index is subject to
    930                         DA protection if its TPMA_NV_NO_DA attribute is CLEAR.
    931 
    932       NOTE 2            An HMAC or password is required in a policy               session   when   the    policy   contains
    933                         TPM2_PolicyAuthValue() or TPM2_PolicyPassword().
    934 
    935 d) If the command requires a handle to have DUP role authorization, then the associated authorization
    936    session is a policy session (TPM_RC_POLICY_FAIL).
    937 e) If the command requires a handle to have ADMIN role authorization:
    938       1) If the entity being authorized is an object and its adminWithPolicy attribute is SET, or a hierarchy,
    939          then the authorization session is a policy session (TPM_RC_POLICY_FAIL).
    940 
    941           NOTE 3             If adminWithPolicy is CLEAR, then any type of authorization session is allowed .
    942 
    943       2) If the entity being authorized is an NV Index, then the associated authorization session is a policy
    944          session.
    945 
    946           NOTE 4             The only commands that are currently defined that require use of ADMIN role authorization
    947                              are commands that operate on objects and NV Indices.
    948 
    949 f)    If the command requires a handle to have USER role authorization:
    950       1) If the entity being authorized is an object and its userWithAuth attribute is CLEAR, then the
    951          associated authorization session is a policy session (TPM_RC_POLICY_FAIL).
    952 
    953           NOTE 5             There is no check for a hierarchy, because a hierarchy operates as if userWithAuth is SET.
    954 
    955       2) If the entity being authorized is an NV Index;
    956           i)    if the authorization session is a policy session;
    957                 (a) the TPMA_NV_POLICYWRITE attribute of the NV Index is SET if the command modifies
    958                     the NV Index data (TPM_RC_AUTH_UNAVAILABLE);
    959 
    960 Family 2.0                                       TCG Published                                                   Page 7
    961 Level 00 Revision 01.16                    Copyright  TCG 2006-2014                               October 30, 2014
    962 Part 3: Commands                                                               Trusted Platform Module Library
    964 
    965                (b) the TPMA_NV_POLICYREAD attribute of the NV Index is SET if the command reads the
    966                    NV Index data (TPM_RC_AUTH_UNAVAILABLE);
    967          ii)   if the authorization is an HMAC session or a password;
    968                (a) the TPMA_NV_AUTHWRITE attribute of the NV Index is SET if the command modifies
    969                    the NV Index data (TPM_RC_AUTH_UNAVAILABLE);
    970                (b) the TPMA_NV_AUTHREAD attribute of the NV Index is SET if the command reads the
    971                    NV Index data (TPM_RC_AUTH_UNAVAILABLE).
    972 g) If the authorization is provided by a policy session, then:
    973       1) if policySessiontimeOut          has     been    set,   the   session   shall     not   have     expired
    974          (TPM_RC_EXPIRED);
    975       2) if policySessioncpHash has been set, it shall match the cpHash of the command
    976          (TPM_RC_POLICY_FAIL);
    977       3) if policySessioncommandCode has been set, then commandCode of the command shall match
    978          (TPM_RC_POLICY_CC);
    979       4) policySessionpolicyDigest       shall    match    the   authPolicy   associated     with   the   handle
    980          (TPM_RC_POLICY_FAIL);
    981       5) if policySessionpcrUpdateCounter has been set, then it shall match the value of
    982          pcrUpdateCounter (TPM_RC_PCR_CHANGED);
    983       6) if policySession->commandLocality has been set, it shall match the locality of the command
    984          (TPM_RC_LOCALITY), and
    985 h) if the authorization uses an HMAC, then the HMAC is properly constructed using the authValue
    986    associated with the handle and/or the session secret (TPM_RC_AUTH_FAIL or
    987    TPM_RC_BAD_AUTH).
    988 
    989          NOTE 6            A policy session may require proof of knowledge of the authValue of the object being
    990                            authorized.
    991 
    992 i)    if the authorization uses a password, then the password matches the authValue associated with the
    993       handle (TPM_RC_AUTH_FAIL or TPM_RC_BAD_AUTH).
    994 If the TPM returns an error other than TPM_RC_AUTH_FAIL then the TPM shall not alter any TPM state.
    995 If the TPM return TPM_RC_AUTH_FAIL, then the TPM shall not alter any TPM state other than
    996 lockoutCount.
    997 
    998 NOTE 7             The TPM may decrease failedTries regardless of any other processing performed by the TPM. That
    999                    is, the TPM may exit Lockout mode, regardless of the return code.
   1000 
   1001 
   1002 5.7      Parameter Decryption
   1003 
   1004 If an authorization session has the TPMA_SESSION.decrypt attribute SET, and the command does not
   1005 allow a command parameter to be encrypted, then the TPM will return TPM_RC_ATTRIBUTES.
   1006 Otherwise, the TPM will decrypt the parameter using the values associated with the session before
   1007 parsing parameters.
   1008 
   1009 5.8      Parameter Unmarshaling
   1010 
   1011 5.8.1    Introduction
   1012 
   1013 The detailed actions for each command assume that the input parameters of the command have been
   1014 unmarshaled into a command-specific structure with the structure defined by the command schematic.
   1015 
   1016 
   1017 Page 8                                            TCG Published                                      Family 2.0
   1018 October 30, 2014                        Copyright  TCG 2006-2014                    Level 00 Revision 01.16
   1019 Trusted Platform Module Library                                                             Part 3: Commands
   1021 
   1022 Additionally, a response-specific output structure is assumed which will receive the values produced by
   1023 the detailed actions.
   1024 
   1025 NOTE            An implementation is not required to process parameters in this manner or to separate the
   1026                 parameter parsing from the command actions. This method was chosen for the specification so that
   1027                 the normative behavior described by the detailed actions would be clear and unencumbered.
   1028 
   1029 Unmarshaling is the process of processing the parameters in the input buffer and preparing the
   1030 parameters for use by the command-specific action code. No data movement need take place but it is
   1031 required that the TPM validate that the parameters meet the requirements of the expected data type as
   1032 defined in TPM 2.0 Part 2.
   1033 
   1034 5.8.2   Unmarshaling Errors
   1035 
   1036 When an error is encountered while unmarshaling a command parameter, an error response code is
   1037 returned and no command processing occurs. A table defining a data type may have response codes
   1038 embedded in the table to indicate the error returned when the input value does not match the parameters
   1039 of the table.
   1040 
   1041 NOTE            In the reference implementation, a parameter number is added to the response code so that the
   1042                 offending parameter can be isolated. This is optional.
   1043 
   1044 In many cases, the table contains no specific response code value and the return code will be determined
   1045 as defined in Table 3.
   1046 
   1047 
   1048 
   1049 
   1050 Family 2.0                                  TCG Published                                             Page 9
   1051 Level 00 Revision 01.16               Copyright  TCG 2006-2014                            October 30, 2014
   1052 Part 3: Commands                                                               Trusted Platform Module Library
   1054 
   1055                                     Table 3  Unmarshaling Errors
   1056  Response Code                 Meaning
   1057 
   1058  TPM_RC_ASYMMETRIC             a parameter that should be an asymmetric algorithm selection does not have a
   1059                                value that is supported by the TPM
   1060  TPM_RC_BAD_TAG                a parameter that should be a command tag selection has a value that is not
   1061                                supported by the TPM
   1062  TPM_RC_COMMAND_CODE           a parameter that should be a command code does not have a value that is
   1063                                supported by the TPM
   1064  TPM_RC_HASH                   a parameter that should be a hash algorithm selection does not have a value that
   1065                                is supported by the TPM
   1066  TPM_RC_INSUFFICIENT           the input buffer did not contain enough octets to allow unmarshaling of the
   1067                                expected data type;
   1068  TPM_RC_KDF                    a parameter that should be a key derivation scheme (KDF) selection does not
   1069                                have a value that is supported by the TPM
   1070  TPM_RC_KEY_SIZE               a parameter that is a key size has a value that is not supported by the TPM
   1071  TPM_RC_MODE                   a parameter that should be a symmetric encryption mode selection does not have
   1072                                a value that is supported by the TPM
   1073  TPM_RC_RESERVED               a non-zero value was found in a reserved field of an attribute structure (TPMA_)
   1074  TPM_RC_SCHEME                 a parameter that should be signing or encryption scheme selection does not have
   1075                                a value that is supported by the TPM
   1076  TPM_RC_SIZE                   the value of a size parameter is larger or smaller than allowed
   1077  TPM_RC_SYMMETRIC              a parameter that should be a symmetric algorithm selection does not have a
   1078                                value that is supported by the TPM
   1079  TPM_RC_TAG                    a parameter that should be a structure tag has a value that is not supported by
   1080                                the TPM
   1081  TPM_RC_TYPE                   The type parameter of a TPMT_PUBLIC or TPMT_SENSITIVE has a value that is
   1082                                not supported by the TPM
   1083  TPM_RC_VALUE                  a parameter does not have one of its allowed values
   1084 
   1085 In some commands, a parameter may not be used because of various options of that command.
   1086 However, the unmarshaling code is required to validate that all parameters have values that are allowed
   1087 by the TPM 2.0 Part 2 definition of the parameter type even if that parameter is not used in the command
   1088 actions.
   1089 
   1090 5.9    Command Post Processing
   1091 
   1092 When the code that implements the detailed actions of the command completes, it returns a response
   1093 code. If that code is not TPM_RC_SUCCESS, the post processing code will not update any session or
   1094 audit data and will return a 10-octet response packet.
   1095 If the command completes successfully, the tag of the command determines if any authorization sessions
   1096 will be in the response. If so, the TPM will encrypt the first parameter of the response if indicated by the
   1097 authorization attributes. The TPM will then generate a new nonce value for each session and, if
   1098 appropriate, generate an HMAC.
   1099 If authorization HMAC computations are performed on the response, the HMAC keys used in the
   1100 response will be the same as the HMAC keys used in processing the HMAC in the command.
   1101 
   1102 
   1103 
   1104 
   1105 Page 10                                       TCG Published                                         Family 2.0
   1106 October 30, 2014                     Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   1107 Trusted Platform Module Library                                                              Part 3: Commands
   1109 
   1110 NOTE 1         This primarily affects authorizations associated with a first write to an NV Index using a bound
   1111                session. The computation of the HMAC in the response is performed as if the Name of the Index did
   1112                not change as a consequence of the command actions. The session binding to the NV Index will not
   1113                persist to any subsequent command.
   1114 
   1115 NOTE 2         The authorization attributes were validated during the session area validation to ensure that only
   1116                one session was used for parameter encryption of the response and that the command allowed
   1117                encryption in the response.
   1118 
   1119 NOTE 3         No session nonce value is used for a password authorization but the session data is present.
   1120 
   1121 Additionally, if the command is being audited by Command Audit, the audit digest is updated with the
   1122 cpHash of the command and rpHash of the response.
   1123 
   1124 
   1125 
   1126 
   1127 Family 2.0                                  TCG Published                                             Page 11
   1128 Level 00 Revision 01.16              Copyright  TCG 2006-2014                               October 30, 2014
   1129 Part 3: Commands                                                          Trusted Platform Module Library
   1131 
   1132 
   1133 
   1134 6     Response Values
   1135 
   1136 6.1    Tag
   1137 
   1138 When a command completes successfully, the tag parameter in the response shall have the same value
   1139 as the tag parameter in the command (TPM_ST_SESSIONS or TPM_RC_NO_SESSIONS). When a
   1140 command fails (the responseCode is not TPM_RC_SUCCESS), then the tag parameter in the response
   1141 shall be TPM_ST_NO_SESSIONS.
   1142 A special case exists when the command tag parameter is not an allowed value (TPM_ST_SESSIONS or
   1143 TPM_ST_NO_SESSIONS). For this case, it is assumed that the system software is attempting to send a
   1144 command formatted for a TPM 1.2 but the TPM is not capable of executing TPM 1.2 commands. So that
   1145 the TPM 1.2 compatible software will have a recognizable response, the TPM sets tag to
   1146 TPM_ST_RSP_COMMAND, responseSize to 00 00 00 0A16 and responseCode to TPM_RC_BAD_TAG.
   1147 This is the same response as the TPM 1.2 fatal error for TPM_BADTAG.
   1148 
   1149 6.2    Response Codes
   1150 
   1151 The normal response for any command is TPM_RC_SUCCESS. Any other value indicates that the
   1152 command did not complete and the state of the TPM is unchanged. An exception to this general rule is
   1153 that the logic associated with dictionary attack protection is allowed to be modified when an authorization
   1154 failure occurs.
   1155 Commands have response codes that are specific to that command, and those response codes are
   1156 enumerated in the detailed actions of each command. The codes associated with the unmarshaling of
   1157 parameters are documented Table 3. Another set of response code values are not command specific and
   1158 indicate a problem that is not specific to the command. That is, if the indicated problem is remedied, the
   1159 same command could be resubmitted and may complete normally.
   1160 The response codes that are not command specific are listed and described in Table 4.
   1161 The reference code for the command actions may have code that generates specific response codes
   1162 associated with a specific check but the listing of responses may not have that response code listed.
   1163 
   1164 
   1165 
   1166 
   1167 Page 12                                     TCG Published                                    Family 2.0
   1168 October 30, 2014                     Copyright  TCG 2006-2014                  Level 00 Revision 01.16
   1169 Trusted Platform Module Library                                                                 Part 3: Commands
   1171 
   1172                         Table 4  Command-Independent Response Codes
   1173 Response Code                Meaning
   1174 
   1175                              This response code may be returned by a TPM that supports command cancel.
   1176                              When the TPM receives an indication that the current command should be
   1177 TPM_RC_CANCELED              cancelled, the TPM may complete the command or return this code. If this code
   1178                              is returned, then the TPM state is not changed and the same command may be
   1179                              retried.
   1180                              This response code can be returned for commands that manage session
   1181                              contexts. It indicates that the gap between the lowest numbered active session
   1182 TPM_RC_CONTEXT_GAP           and the highest numbered session is at the limits of the session tracking logic.
   1183                              The remedy is to load the session context with the lowest number so that its
   1184                              tracking number can be updated.
   1185                              This response indicates that authorizations for objects subject to DA protection
   1186 TPM_RC_LOCKOUT               are not allowed at this time because the TPM is in DA lockout mode. The remedy
   1187                              is to wait or to exeucte TPM2_DictionaryAttackLockoutReset().
   1188                              A TPM may use a common pool of memory for objects, sessions, and other
   1189                              purposes. When the TPM does not have enough memory available to perform
   1190                              the actions of the command, it may return TPM_RC_MEMORY. This indicates
   1191 TPM_RC_MEMORY                that the TPM resource manager may flush either sessions or objects in order to
   1192                              make memory available for the command execution. A TPM may choose to
   1193                              return TPM_RC_OBJECT_MEMORY or TPM_RC_SESSION_MEMORY if it
   1194                              needs contexts of a particular type to be flushed.
   1195                              This response code indicates that the TPM is rate-limiting writes to the NV
   1196                              memory in order to prevent wearout. This response is possible for any command
   1197 TPM_RC_NV_RATE               that explicity writes to NV or commands that incidentally use NV such as a
   1198                              command that uses authorization session that may need to update the dictionary
   1199                              attack logic.
   1200                              This response code is similar to TPM_RC_NV_RATE but indicates that access to
   1201                              NV memory is currently not available and the command is not allowed to proceed
   1202 TPM_RC_NV_UNAVAILABLE
   1203                              until it is. This would occur in a system where the NV memory used by the TPM
   1204                              is not exclusive to the TPM and is a shared system resource.
   1205                              This response code indicates that the TPM has exhausted its handle space and
   1206                              no new objects can be loaded unless the TPM is rebooted. This does not occur in
   1207                              the reference implementation because of the way that object handles are
   1208 TPM_RC_OBJECT_HANDLES
   1209                              allocated. However, other implementations are allowed to assign each object a
   1210                              unique handle each time the object is loaded. A TPM using this implementation
   1211                                                     24
   1212                              would be able to load 2 objects before the object space is exhausted.
   1213                              This response code can be returned by any command that causes the TPM to
   1214                              need an object 'slot'. The most common case where this might be returned is
   1215                              when an object is loaded (TPM2_Load, TPM2_CreatePrimary(), or
   1216                              TPM2_ContextLoad()). However, the TPM implementation is allowed to use
   1217                              object slots for other reasons. In the reference implementation, the TPM copies a
   1218 TPM_RC_OBJECT_MEMORY
   1219                              referenced persistent object into RAM for the duration of the commannd. If all the
   1220                              slots are previously occupied, the TPM may return this value. A TPM is allowed
   1221                              to use object slots for other purposes and return this value. The remedy when
   1222                              this response is returned is for the TPM resource manager to flush a transient
   1223                              object.
   1224                              This response code indicates that a handle in the handle area of the command is
   1225                              not associated with a loaded object. The value of 'x' is in the range 0 to 6 with a
   1226                                                          st                                 th
   1227                              value of 0 indicating the 1 handle and 6 representing the 7 . Upper values are
   1228 TPM_RC_REFERENCE_Hx          provided for future use. The TPM resource manager needs to find the correct
   1229                              object and load it. It may then adjust the handle and retry the command.
   1230                              NOTE       Usually, this error indicates that the TPM resource manager has a corrupted
   1231                                         database.
   1232 
   1233 
   1234 
   1235 
   1236 Family 2.0                               TCG Published                                                    Page 13
   1237 Level 00 Revision 01.16             Copyright  TCG 2006-2014                                  October 30, 2014
   1238 Part 3: Commands                                                                Trusted Platform Module Library
   1240 
   1241 
   1242 Response Code                 Meaning
   1243 
   1244                               This response code indicates that a handle in the session area of the command
   1245                               is not associated with a loaded session. The value of 'x' is in the range 0 to 6 with
   1246                                                            st                                          th
   1247                               a value of 0 indicating the 1 session handle and 6 representing the 7 . Upper
   1248 TPM_RC_REFERENCE_Sx           values are provided for future use. The TPM resource manager needs to find the
   1249                               correct session and load it. It may then retry the command.
   1250                               NOTE Usually, this error indicates that the TPM resource manager has a
   1251                               corrupted database.
   1252 TPM_RC_RETRY                  the TPM was not able to start the command
   1253                        This response code indicates that the TPM does not have a handle to assign to a
   1254                        new session. This respose is only returned by TPM2_StartAuthSession(). It is
   1255 TPM_RC_SESSION_HANDLES
   1256                        listed here because the command is not in error and the TPM resource manager
   1257                        can remedy the situation by flushing a session (TPM2_FlushContext().
   1258                               This response code can be returned by any command that causes the TPM to
   1259                               need a session 'slot'. The most common case where this might be returned is
   1260                               when a session is loaded (TPM2_StartAuthSession() or TPM2_ContextLoad()).
   1261 TPM_RC_SESSION_MEMORY
   1262                               However, the TPM implementation is allowed to use object slots for other
   1263                               purposes. The remedy when this response is returned is for the TPM resource
   1264                               manager to flush a transient object.
   1265                               Normal completion for any command. If the responseCode is
   1266                               TPM_RC_SUCCESS, then the rest of the response has the format indicated in
   1267 TPM_RC_SUCCESS
   1268                               the response schematic. Otherwise, the response is a 10 octet value indicating
   1269                               an error.
   1270                               This response code indicates that the TPM is performing tests and cannot
   1271 TPM_RC_TESTING
   1272                               respond to the request at this time. The command may be retried.
   1273                               the TPM has suspended operation on the command; forward progress was made
   1274                               and the command may be retried.
   1275 TPM_RC_YIELDED
   1276                               See TPM 2.0 Part 1, Multi-tasking.
   1277                               NOTE        This cannot occur on the reference implementation.
   1278 
   1279 
   1280 
   1281 
   1282 Page 14                                      TCG Published                                           Family 2.0
   1283 October 30, 2014                     Copyright  TCG 2006-2014                          Level 00 Revision 01.16
   1284 Trusted Platform Module Library                                                        Part 3: Commands
   1286 
   1287 
   1288 
   1289 7   Implementation Dependent
   1290 
   1291 The actions code for each command makes assumptions about the behavior of various sub-systems.
   1292 There are many possible implementations of the subsystems that would achieve equivalent results. The
   1293 actions code is not written to anticipate all possible implementations of the sub-systems. Therefore, it is
   1294 the responsibility of the implementer to ensure that the necessary changes are made to the actions code
   1295 when the sub-system behavior changes.
   1296 
   1297 
   1298 
   1299 
   1300 Family 2.0                                TCG Published                                        Page 15
   1301 Level 00 Revision 01.16              Copyright  TCG 2006-2014                         October 30, 2014
   1302 Part 3: Commands                                                                Trusted Platform Module Library
   1304 
   1305 
   1306 
   1307 8     Detailed Actions Assumptions
   1308 
   1309 8.1       Introduction
   1310 
   1311 The C code in the Detailed Actions for each command is written with a set of assumptions about the
   1312 processing performed before the action code is called and the processing that will be done after the
   1313 action code completes.
   1314 
   1315 8.2       Pre-processing
   1316 
   1317 Before calling the command actions code, the following actions have occurred.
   1318          Verification that the handles in the handle area reference entities that are resident on the TPM.
   1319 
   1320       NOTE            If a handle is in the parameter portion of the command, the associated entity does not have to
   1321                       be loaded, but the handle is required to be the correct type.
   1322 
   1323          If use of a handle requires authorization, the Password, HMAC, or Policy session associated with
   1324           the handle has been verified.
   1325          If a command parameter was encrypted using parameter encryption, it was decrypted before
   1326           being unmarshaled.
   1327          If the command uses handles or parameters, the calling stack contains a pointer to a data
   1328           structure (in) that holds the unmarshaled values for the handles and command parameters. If
   1329           the response has handles or parameters, the calling stack contains a pointer to a data structure
   1330           (out) to hold the handles and response parameters generated by the command.
   1331          All parameters of the in structure have been validated and meet the requirements of the
   1332           parameter type as defined in TPM 2.0 Part 2.
   1333          Space set aside for the out structure is sufficient to hold the largest out structure that could be
   1334           produced by the command
   1335 
   1336 8.3       Post Processing
   1337 
   1338 When the function implementing the command actions completes,
   1339          response parameters that require parameter encryption will be encrypted after the command
   1340           actions complete;
   1341          audit and session contexts will be updated if the command response is TPM_RC_SUCCESS;
   1342           and
   1343          the command header and command response parameters will be marshaled to the response
   1344           buffer.
   1345 
   1346 
   1347 
   1348 
   1349 Page 16                                         TCG Published                                        Family 2.0
   1350 October 30, 2014                        Copyright  TCG 2006-2014                      Level 00 Revision 01.16
   1351 Trusted Platform Module Library                                                               Part 3: Commands
   1353 
   1354 
   1355 
   1356 9     Start-up
   1357 
   1358 9.1      Introduction
   1359 
   1360 This clause contains the commands used to manage the startup and restart state of a TPM.
   1361 
   1362 9.2      _TPM_Init
   1363 
   1364 9.2.1 General Description
   1365 
   1366 _TPM_Init initializes a TPM.
   1367 Initialization actions include testing code required to execute the next expected command. If the TPM is in
   1368 FUM, the next expected command is TPM2_FieldUpgradeData(); otherwise, the next expected command
   1369 is TPM2_Startup().
   1370 
   1371 NOTE 1           If the TPM performs self-tests after receiving _TPM_Init() and the TPM enters Failure mode before
   1372                  receiving TPM2_Startup() or TPM2_FieldUpgradeData(), then the TPM may be able to accept
   1373                  TPM2_GetTestResult() or TPM2_GetCapability().
   1374 
   1375 The means of signaling _TPM_Init shall be defined in the platform-specific specifications that define the
   1376 physical interface to the TPM. The platform shall send this indication whenever the platform starts its boot
   1377 process and only when the platform starts its boot process.
   1378 There shall be no software method of generating this indication that does not also reset the platform and
   1379 begin execution of the CRTM.
   1380 
   1381 NOTE 2           In the reference implementation, this signal causes an internal flag ( s_initialized) to be CLEAR.
   1382                  While this flag is CLEAR, the TPM will only accept the next expected command described above.
   1383 
   1384 
   1385 
   1386 
   1387 Family 2.0                                   TCG Published                                             Page 17
   1388 Level 00 Revision 01.16                Copyright  TCG 2006-2014                              October 30, 2014
   1389      Part 3: Commands                                                 Trusted Platform Module Library
   1391 
   1392 
   1393      9.2.2   Detailed Actions
   1394 
   1395      This function is used to process a _TPM_Init() indication.
   1396 
   1397  1   #include "InternalRoutines.h"
   1398  2   LIB_EXPORT void
   1399  3   _TPM_Init(
   1400  4       void
   1401  5       )
   1402  6   {
   1403  7       // Clear the failure mode flags
   1404  8       g_inFailureMode = FALSE;
   1405  9       g_forceFailureMode = FALSE;
   1406 10
   1407 11       // Initialize the NvEnvironment.
   1408 12       g_nvOk = NvPowerOn();
   1409 13
   1410 14       // Initialize crypto engine
   1411 15       CryptInitUnits();
   1412 16
   1413 17       // Start clock
   1414 18       TimePowerOn();
   1415 19
   1416 20       // Set initialization state
   1417 21       TPMInit();
   1418 22
   1419 23       // Initialize object table
   1420 24       ObjectStartup();
   1421 25
   1422 26       // Set g_DRTMHandle as unassigned
   1423 27       g_DRTMHandle = TPM_RH_UNASSIGNED;
   1424 28
   1425 29       // No H-CRTM, yet.
   1426 30       g_DrtmPreStartup = FALSE;
   1427 31
   1428 32       return;
   1429 33   }
   1430 
   1431 
   1432 
   1433 
   1434      Page 18                                      TCG Published                         Family 2.0
   1435      October 30, 2014                     Copyright  TCG 2006-2014        Level 00 Revision 01.16
   1436 Trusted Platform Module Library                                                                  Part 3: Commands
   1438 
   1439 
   1440 
   1441 9.3       TPM2_Startup
   1442 
   1443 9.3.1 General Description
   1444 
   1445 TPM2_Startup() is always preceded by _TPM_Init, which is the physical indication that TPM initialization
   1446 is necessary because of a system-wide reset. TPM2_Startup() is only valid after _TPM_Init. Additional
   1447 TPM2_Startup() commands are not allowed after it has completed successfully. If a TPM requires
   1448 TPM2_Startup() and another command is received, or if the TPM receives TPM2_Startup() when it is not
   1449 required, the TPM shall return TPM_RC_INITIALIZE.
   1450 
   1451 NOTE 1            See 9.2.1 for other command options for a TPM supporting field upgrade mode.
   1452 
   1453 NOTE 2            _TPM_Hash_Start, _TPM_Hash_Data, and _TPM_Hash_End are not commands and a platform -
   1454                   specific specification may allow t hese indications between _TPM_Init and TPM2_Startup().
   1455 
   1456 If in Failure mode, the TPM shall accept TPM2_GetTestResult() and TPM2_GetCapability() even if
   1457 TPM2_Startup() is not completed successfully or processed at all.
   1458 A platform-specific specification may restrict the localities at which TPM2_Startup() may be received.
   1459 A Shutdown/Startup sequence determines the way in which the TPM will operate in response to
   1460 TPM2_Startup(). The three sequences are:
   1461 1) TPM Reset  This is a Startup(CLEAR) preceded by either Shutdown(CLEAR) or no
   1462    TPM2_Shutdown(). On TPM Reset, all variables go back to their default initialization state.
   1463 
   1464       NOTE 3          Only those values that are specified as having a default initialization state are changed by TPM
   1465                       Reset. Persistent values that have no defa ult initialization state are not changed by this
   1466                       command. Values such as seeds have no default initialization state and only change due to
   1467                       specific commands.
   1468 
   1469 2) TPM Restart  This is a Startup(CLEAR) preceded by Shutdown(STATE). This preserves much of the
   1470    previous state of the TPM except that PCR and the controls associated with the Platform hierarchy
   1471    are all returned to their default initialization state;
   1472 3) TPM Resume  This is a Startup(STATE) preceded by Shutdown(STATE). This preserves the
   1473    previous state of the TPM including the static Root of Trust for Measurement (S-RTM) PCR and the
   1474    platform controls other than the phEnable and phEnableNV.
   1475 If a TPM receives Startup(STATE) and that was not preceded by Shutdown(STATE), the TPM shall return
   1476 TPM_RC_VALUE.
   1477 If, during TPM Restart or TPM Resume, the TPM fails to restore the state saved at the last
   1478 Shutdown(STATE), the TPM shall enter Failure Mode and return TPM_RC_FAILURE.
   1479 On any TPM2_Startup(),
   1480          phEnable and phEnableNV shall be SET;
   1481          all transient contexts (objects, sessions, and sequences) shall be flushed from TPM memory;
   1482          TPMS_TIME_INFO.time shall be reset to zero; and
   1483          use of lockoutAuth shall be enabled if lockoutRecovery is zero.
   1484 Additional actions are performed based on the Shutdown/Startup sequence.
   1485 On TPM Reset
   1486 
   1487 
   1488 
   1489 
   1490 Family 2.0                                    TCG Published                                              Page 19
   1491 Level 00 Revision 01.16                 Copyright  TCG 2006-2014                                October 30, 2014
   1492 Part 3: Commands                                                                 Trusted Platform Module Library
   1494 
   1495 
   1496       platformAuth and platformPolicy shall be set to the Empty Buffer,
   1497       For each NV index with TPMA_NV_WRITE_DEFINE CLEAR or TPMA_NV_WRITTEN CLEAR,
   1498        TPMA_NV_WRITELOCKED shall be CLEAR,
   1499       For each NV index with TPMA_NV_CLEAR_STCLEAR SET, TPMA_NV_WRITTEN shall be
   1500        CLEAR,
   1501       tracking data for saved session contexts shall be set to its initial value,
   1502       the object context sequence number is reset to zero,
   1503       a new context encryption key shall be generated,
   1504       TPMS_CLOCK_INFO.restartCount shall be reset to zero,
   1505       TPMS_CLOCK_INFO.resetCount shall be incremented,
   1506       the PCR Update Counter shall be clear to zero,
   1507       shEnable and ehEnable shall be SET, and
   1508       PCR in all banks are reset to their default initial conditions as determined by the relevant
   1509        platform-specific specification and the H-CRTM state (for exceptions, see TPM 2.0 Part 1, H-
   1510        CRTM before TPM2_Startup() and TPM2_Startup without H-CRTM)
   1511 
   1512    NOTE 4           PCR may be initialized any time between _TPM_Init and the end of TPM2_Startup(). PCR that
   1513                     are preserved by TPM Resume will need to be restored during TPM2_Startup().
   1514 
   1515    NOTE 5           See "Initializing PCR" in TPM 2.0 Part 1 for a description of the default initial conditions for a
   1516                     PCR.
   1517 
   1518 On TPM Restart
   1519       TPMS_CLOCK_INFO.restartCount shall be incremented,
   1520       shEnable and ehEnable shall be SET,
   1521       platformAuth and platformPolicy shall be set to the Empty Buffer,
   1522       For each NV index with TPMA_NV_WRITE_DEFINE CLEAR or TPMA_NV_WRITTEN CLEAR,
   1523        TPMA_NV_WRITELOCKED shall be CLEAR,
   1524       For each NV index with TPMA_NV_CLEAR_STCLEAR SET, TPMA_NV_WRITTEN shall be
   1525        CLEAR, and
   1526       PCR in all banks are reset to their default initial conditions.
   1527       If an H-CRTM Event Sequence is active, extend the PCR designated by the platform-specific
   1528        specification.
   1529 On TPM Resume
   1530       the H-CRTM startup method is the same for this TPM2_Startup() as for the previous
   1531        TPM2_Startup(); (TPM_RC_LOCALITY)
   1532       TPMS_CLOCK_INFO.restartCount shall be incremented; and
   1533       PCR that are specified in a platform-specific specification to be preserved on TPM Resume are
   1534        restored to their saved state and other PCR are set to their initial value as determined by a
   1535        platform-specific specification. For constraints, see TPM 2.0 Part 1, H-CRTM before
   1536        TPM2_Startup() and TPM2_Startup without H-CRTM.
   1537 Other TPM state may change as required to meet the needs of the implementation.
   1538 If the startupType is TPM_SU_STATE and the TPM requires TPM_SU_CLEAR, then the TPM shall return
   1539 TPM_RC_VALUE.
   1540 
   1541 
   1542 
   1543 Page 20                                        TCG Published                                           Family 2.0
   1544 October 30, 2014                      Copyright  TCG 2006-2014                         Level 00 Revision 01.16
   1545 Trusted Platform Module Library                                                        Part 3: Commands
   1547 
   1548 NOTE 6         The TPM will require     TPM_SU_CLEAR      when   no   shutdown   was   performed   or   after
   1549                Shutdown(CLEAR).
   1550 
   1551 NOTE 7         If startupType is neither TPM_SU_STATE nor TPM_SU_CLEAR, then the unmarshaling code returns
   1552                TPM_RC_VALUE.
   1553 
   1554 
   1555 
   1556 
   1557 Family 2.0                               TCG Published                                           Page 21
   1558 Level 00 Revision 01.16            Copyright  TCG 2006-2014                           October 30, 2014
   1559 Part 3: Commands                                                Trusted Platform Module Library
   1561 
   1562 
   1563 9.3.2    Command and Response
   1564 
   1565                            Table 5  TPM2_Startup Command
   1566 Type                     Name                  Description
   1567 
   1568 TPMI_ST_COMMAND_TAG      tag                   TPM_ST_NO_SESSIONS
   1569 UINT32                   commandSize
   1570 TPM_CC                   commandCode           TPM_CC_Startup {NV}
   1571 
   1572 TPM_SU                   startupType           TPM_SU_CLEAR or TPM_SU_STATE
   1573 
   1574 
   1575                            Table 6  TPM2_Startup Response
   1576 Type                     Name                  Description
   1577 
   1578 TPM_ST                   tag                   see clause 6
   1579 UINT32                   responseSize
   1580 TPM_RC                   responseCode
   1581 
   1582 
   1583 
   1584 
   1585 Page 22                                 TCG Published                             Family 2.0
   1586 October 30, 2014               Copyright  TCG 2006-2014             Level 00 Revision 01.16
   1587      Trusted Platform Module Library                                                             Part 3: Commands
   1589 
   1590 
   1591 
   1592      9.3.3   Detailed Actions
   1593 
   1594 1    #include "InternalRoutines.h"
   1595 2    #include "Startup_fp.h"
   1596 3    #ifdef TPM_CC_Startup // Conditional expansion of this file
   1597 
   1598 
   1599      Error Returns                     Meaning
   1600 
   1601      TPM_RC_LOCALITY                   a Startup(STATE) does not have the same H-CRTM state as the
   1602                                        previous Startup() or the locality of the startup is not 0 pr 3
   1603      TPM_RC_NV_UNINITIALIZED           the saved state cannot be recovered and a Startup(CLEAR) is
   1604                                        requried.
   1605      TPM_RC_VALUE                      start up type is not compatible with previous shutdown sequence
   1606 
   1607  4   TPM_RC
   1608  5   TPM2_Startup(
   1609  6       Startup_In        *in                 // IN: input parameter list
   1610  7       )
   1611  8   {
   1612  9       STARTUP_TYPE            startup;
   1613 10       TPM_RC                  result;
   1614 11       BOOL                    prevDrtmPreStartup;
   1615 12       BOOL                    prevStartupLoc3;
   1616 13       BYTE                    locality = _plat__LocalityGet();
   1617 14
   1618 15       // In the PC Client specification, only locality 0 and 3 are allowed
   1619 16       if(locality != 0 && locality != 3)
   1620 17           return TPM_RC_LOCALITY;
   1621 18       // Indicate that the locality was 3 unless there was an H-CRTM
   1622 19       if(g_DrtmPreStartup)
   1623 20           locality = 0;
   1624 21       g_StartupLocality3 = (locality == 3);
   1625 22
   1626 23       // The command needs NV update. Check if NV is available.
   1627 24       // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   1628 25       // this point
   1629 26       result = NvIsAvailable();
   1630 27       if(result != TPM_RC_SUCCESS)
   1631 28           return result;
   1632 29
   1633 30   // Input Validation
   1634 31
   1635 32       // Read orderly shutdown states from previous power cycle
   1636 33       NvReadReserved(NV_ORDERLY, &g_prevOrderlyState);
   1637 34
   1638 35       // See if the orderly state indicates that state was saved
   1639 36       if(     (g_prevOrderlyState & ~(PRE_STARTUP_FLAG | STARTUP_LOCALITY_3))
   1640 37           == TPM_SU_STATE)
   1641 38       {
   1642 39           // If so, extrat the saved flags (HACK)
   1643 40           prevDrtmPreStartup = (g_prevOrderlyState & PRE_STARTUP_FLAG) != 0;
   1644 41           prevStartupLoc3 = (g_prevOrderlyState & STARTUP_LOCALITY_3) != 0;
   1645 42           g_prevOrderlyState = TPM_SU_STATE;
   1646 43       }
   1647 44       else
   1648 45       {
   1649 46           prevDrtmPreStartup = 0;
   1650 47           prevStartupLoc3 = 0;
   1651 48       }
   1652 49       // if this startup is a TPM Resume, then the H-CRTM states have to match.
   1653 50       if(in->startupType == TPM_SU_STATE)
   1654 
   1655      Family 2.0                                  TCG Published                                         Page 23
   1656      Level 00 Revision 01.16               Copyright  TCG 2006-2014                             October 30, 2014
   1657       Part 3: Commands                                               Trusted Platform Module Library
   1659 
   1660  51      {
   1661  52             if(g_DrtmPreStartup != prevDrtmPreStartup)
   1662  53                 return TPM_RC_VALUE + RC_Startup_startupType;
   1663  54             if(g_StartupLocality3 != prevStartupLoc3)
   1664  55                 return TPM_RC_LOCALITY;
   1665  56      }
   1666  57
   1667  58      // if the previous power cycle was shut down with no StateSave command, or
   1668  59      // with StateSave command for CLEAR, or the part of NV used for TPM_SU_STATE
   1669  60      // cannot be recovered, then this cycle can not startup up with STATE
   1670  61      if(in->startupType == TPM_SU_STATE)
   1671  62      {
   1672  63          if(     g_prevOrderlyState == SHUTDOWN_NONE
   1673  64             ||   g_prevOrderlyState == TPM_SU_CLEAR)
   1674  65              return TPM_RC_VALUE + RC_Startup_startupType;
   1675  66
   1676  67             if(g_nvOk == FALSE)
   1677  68                 return TPM_RC_NV_UNINITIALIZED;
   1678  69      }
   1679  70
   1680  71   // Internal Date Update
   1681  72
   1682  73      // Translate the TPM2_ShutDown and TPM2_Startup sequence into the startup
   1683  74      // types. Will only be a SU_RESTART if the NV is OK
   1684  75      if(     in->startupType == TPM_SU_CLEAR
   1685  76          && g_prevOrderlyState == TPM_SU_STATE
   1686  77          && g_nvOk == TRUE)
   1687  78      {
   1688  79          startup = SU_RESTART;
   1689  80          // Read state reset data
   1690  81          NvReadReserved(NV_STATE_RESET, &gr);
   1691  82      }
   1692  83      // In this check, we don't need to look at g_nvOk because that was checked
   1693  84      // above
   1694  85      else if(in->startupType == TPM_SU_STATE && g_prevOrderlyState == TPM_SU_STATE)
   1695  86      {
   1696  87          // Read state clear and state reset data
   1697  88          NvReadReserved(NV_STATE_CLEAR, &gc);
   1698  89          NvReadReserved(NV_STATE_RESET, &gr);
   1699  90          startup = SU_RESUME;
   1700  91      }
   1701  92      else
   1702  93      {
   1703  94          startup = SU_RESET;
   1704  95      }
   1705  96
   1706  97      // Read persistent data from NV
   1707  98      NvReadPersistent();
   1708  99
   1709 100      // Crypto Startup
   1710 101      CryptUtilStartup(startup);
   1711 102
   1712 103      // Read the platform unique value that is used as VENDOR_PERMANENT auth value
   1713 104      g_platformUniqueDetails.t.size = (UINT16)_plat__GetUnique(1,
   1714 105                                         sizeof(g_platformUniqueDetails.t.buffer),
   1715 106                                         g_platformUniqueDetails.t.buffer);
   1716 107
   1717 108      // Start up subsystems
   1718 109      // Start counters and timers
   1719 110      TimeStartup(startup);
   1720 111
   1721 112      // Start dictionary attack subsystem
   1722 113      DAStartup(startup);
   1723 114
   1724 115      // Enable hierarchies
   1725 116      HierarchyStartup(startup);
   1726 
   1727       Page 24                                  TCG Published                             Family 2.0
   1728       October 30, 2014                  Copyright  TCG 2006-2014          Level 00 Revision 01.16
   1729       Trusted Platform Module Library                                              Part 3: Commands
   1731 
   1732 117
   1733 118       // Restore/Initialize PCR
   1734 119       PCRStartup(startup, locality);
   1735 120
   1736 121       // Restore/Initialize command audit information
   1737 122       CommandAuditStartup(startup);
   1738 123
   1739 124       // Object context variables
   1740 125       if(startup == SU_RESET)
   1741 126       {
   1742 127           // Reset object context ID to 0
   1743 128           gr.objectContextID = 0;
   1744 129           // Reset clearCount to 0
   1745 130           gr.clearCount= 0;
   1746 131       }
   1747 132
   1748 133       // Initialize session table
   1749 134       SessionStartup(startup);
   1750 135
   1751 136       // Initialize index/evict data.   This function clear read/write locks
   1752 137       // in NV index
   1753 138       NvEntityStartup(startup);
   1754 139
   1755 140       // Initialize the orderly shut down flag for this cycle to SHUTDOWN_NONE.
   1756 141       gp.orderlyState = SHUTDOWN_NONE;
   1757 142       NvWriteReserved(NV_ORDERLY, &gp.orderlyState);
   1758 143
   1759 144       // Update TPM internal states if command succeeded.
   1760 145       // Record a TPM2_Startup command has been received.
   1761 146       TPMRegisterStartup();
   1762 147
   1763 148       // The H-CRTM state no longer matters
   1764 149       g_DrtmPreStartup = FALSE;
   1765 150
   1766 151       return TPM_RC_SUCCESS;
   1767 152
   1768 153   }
   1769 154   #endif // CC_Startup
   1770 
   1771 
   1772 
   1773 
   1774       Family 2.0                              TCG Published                              Page 25
   1775       Level 00 Revision 01.16           Copyright  TCG 2006-2014                  October 30, 2014
   1776 Part 3: Commands                                                       Trusted Platform Module Library
   1778 
   1779 
   1780 9.4       TPM2_Shutdown
   1781 
   1782 9.4.1 General Description
   1783 
   1784 This command is used to prepare the TPM for a power cycle. The shutdownType parameter indicates
   1785 how the subsequent TPM2_Startup() will be processed.
   1786 For a shutdownType of any type, the volatile portion of Clock is saved to NV memory and the orderly
   1787 shutdown indication is SET. NV with the TPMA_NV_ORDERY attribute will be updated.
   1788 For a shutdownType of TPM_SU_STATE, the following additional items are saved:
   1789          tracking information for saved session contexts;
   1790          the session context counter;
   1791          PCR that are designated as being preserved by TPM2_Shutdown(TPM_SU_STATE);
   1792          the PCR Update Counter;
   1793          flags associated with supporting the TPMA_NV_WRITESTCLEAR and
   1794           TPMA_NV_READSTCLEAR attributes; and
   1795           the command audit digest and count.
   1796 The following items shall not be saved and will not be in TPM memory after the next TPM2_Startup:
   1797          TPM-memory-resident session contexts;
   1798          TPM-memory-resident transient objects; or
   1799          TPM-memory-resident hash contexts created by TPM2_HashSequenceStart().
   1800 Some values may be either derived from other values or saved to NV memory.
   1801 This command saves TPM state but does not change the state other than the internal indication that the
   1802 context has been saved. The TPM shall continue to accept commands. If a subsequent command
   1803 changes TPM state saved by this command, then the effect of this command is nullified. The TPM MAY
   1804 nullify this command for any subsequent command rather than check whether the command changed
   1805 state saved by this command. If this command is nullified. and if no TPM2_Shutdown() occurs before the
   1806 next TPM2_Startup(), then the next TPM2_Startup() shall be TPM2_Startup(CLEAR).
   1807 
   1808 
   1809 
   1810 
   1811 Page 26                                       TCG Published                               Family 2.0
   1812 October 30, 2014                         Copyright  TCG 2006-2014           Level 00 Revision 01.16
   1813 Trusted Platform Module Library                                                      Part 3: Commands
   1815 
   1816 
   1817 
   1818 9.4.2    Command and Response
   1819 
   1820                                   Table 7  TPM2_Shutdown Command
   1821 Type                          Name                  Description
   1822 
   1823                                                     TPM_ST_SESSIONS if an audit session is present;
   1824 TPMI_ST_COMMAND_TAG           tag
   1825                                                     otherwise, TPM_ST_NO_SESSIONS
   1826 UINT32                        commandSize
   1827 TPM_CC                        commandCode           TPM_CC_Shutdown {NV}
   1828 
   1829 TPM_SU                        shutdownType          TPM_SU_CLEAR or TPM_SU_STATE
   1830 
   1831 
   1832                                   Table 8  TPM2_Shutdown Response
   1833 Type                          Name                  Description
   1834 
   1835 TPM_ST                        tag                   see clause 6
   1836 UINT32                        responseSize
   1837 TPM_RC                        responseCode
   1838 
   1839 
   1840 
   1841 
   1842 Family 2.0                                 TCG Published                                    Page 27
   1843 Level 00 Revision 01.16              Copyright  TCG 2006-2014                      October 30, 2014
   1844      Part 3: Commands                                                          Trusted Platform Module Library
   1846 
   1847 
   1848 
   1849      9.4.3   Detailed Actions
   1850 
   1851 1    #include "InternalRoutines.h"
   1852 2    #include "Shutdown_fp.h"
   1853 3    #ifdef TPM_CC_Shutdown // Conditional expansion of this file
   1854 
   1855 
   1856      Error Returns                   Meaning
   1857 
   1858      TPM_RC_TYPE                     if PCR bank has been re-configured, a CLEAR StateSave() is
   1859                                      required
   1860 
   1861  4   TPM_RC
   1862  5   TPM2_Shutdown(
   1863  6       Shutdown_In       *in               // IN: input parameter list
   1864  7       )
   1865  8   {
   1866  9       TPM_RC            result;
   1867 10
   1868 11       // The command needs NV update. Check if NV is available.
   1869 12       // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   1870 13       // this point
   1871 14       result = NvIsAvailable();
   1872 15       if(result != TPM_RC_SUCCESS) return result;
   1873 16
   1874 17   // Input Validation
   1875 18
   1876 19       // If PCR bank has been reconfigured, a CLEAR state save is required
   1877 20       if(g_pcrReConfig && in->shutdownType == TPM_SU_STATE)
   1878 21           return TPM_RC_TYPE + RC_Shutdown_shutdownType;
   1879 22
   1880 23   // Internal Data Update
   1881 24
   1882 25       // PCR private date state save
   1883 26       PCRStateSave(in->shutdownType);
   1884 27
   1885 28       // Get DRBG state
   1886 29       CryptDrbgGetPutState(GET_STATE);
   1887 30
   1888 31       // Save all orderly data
   1889 32       NvWriteReserved(NV_ORDERLY_DATA, &go);
   1890 33
   1891 34       // Save RAM backed NV index data
   1892 35       NvStateSave();
   1893 36
   1894 37       if(in->shutdownType == TPM_SU_STATE)
   1895 38       {
   1896 39           // Save STATE_RESET and STATE_CLEAR data
   1897 40           NvWriteReserved(NV_STATE_CLEAR, &gc);
   1898 41           NvWriteReserved(NV_STATE_RESET, &gr);
   1899 42       }
   1900 43       else if(in->shutdownType == TPM_SU_CLEAR)
   1901 44       {
   1902 45           // Save STATE_RESET data
   1903 46           NvWriteReserved(NV_STATE_RESET, &gr);
   1904 47       }
   1905 48
   1906 49       // Write orderly shut down state
   1907 50       if(in->shutdownType == TPM_SU_CLEAR)
   1908 51           gp.orderlyState = TPM_SU_CLEAR;
   1909 52       else if(in->shutdownType == TPM_SU_STATE)
   1910 53       {
   1911 54           gp.orderlyState = TPM_SU_STATE;
   1912 55           // Hack for the H-CRTM and Startup locality settings
   1913 
   1914      Page 28                                     TCG Published                                    Family 2.0
   1915      October 30, 2014                    Copyright  TCG 2006-2014                    Level 00 Revision 01.16
   1916      Trusted Platform Module Library                                               Part 3: Commands
   1918 
   1919 56             if(g_DrtmPreStartup)
   1920 57                 gp.orderlyState |= PRE_STARTUP_FLAG;
   1921 58             else if(g_StartupLocality3)
   1922 59                 gp.orderlyState |= STARTUP_LOCALITY_3;
   1923 60       }
   1924 61       else
   1925 62           pAssert(FALSE);
   1926 63
   1927 64       NvWriteReserved(NV_ORDERLY, &gp.orderlyState);
   1928 65
   1929 66       //   If PRE_STARTUP_FLAG was SET, then it will stay set in gp.orderlyState even
   1930 67       //   if the TPM isn't actually shut down. This is OK because all other checks
   1931 68       //   of gp.orderlyState are to see if it is SHUTDOWN_NONE. So, having
   1932 69       //   gp.orderlyState set to another value that is also not SHUTDOWN_NONE, is not
   1933 70       //   an issue. This must be the case, otherwise, it would be impossible to add
   1934 71       //   an additional shutdown type without major changes to the code.
   1935 72
   1936 73       return TPM_RC_SUCCESS;
   1937 74   }
   1938 75   #endif // CC_Shutdown
   1939 
   1940 
   1941 
   1942 
   1943      Family 2.0                             TCG Published                                 Page 29
   1944      Level 00 Revision 01.16           Copyright  TCG 2006-2014                   October 30, 2014
   1945 Part 3: Commands                                                            Trusted Platform Module Library
   1947 
   1948 
   1949 10     Testing
   1950 
   1951 10.1    Introduction
   1952 
   1953 Compliance to standards for hardware security modules may require that the TPM test its functions
   1954 before the results that depend on those functions may be returned. The TPM may perform operations
   1955 using testable functions before those functions have been tested as long as the TPM returns no value
   1956 that depends on the correctness of the testable function.
   1957 
   1958 EXAMPLE          TPM2_PCR_Event() may be executed before the hash algorithms have been tested. However, until
   1959                  the hash algorithms have been tested, the contents of a PCR may not be used in any command if
   1960                  that command may result in a value being returned to the TPM user. This means that
   1961                  TPM2_PCR_Read() or TPM2_PolicyPCR() could not complete until the hashes have been checked
   1962                  but other TPM2_PCR_Event() commands may be executed even though the operation uses previous
   1963                  PCR values.
   1964 
   1965 If a command is received that requires return of a value that depends on untested functions, the TPM
   1966 shall test the required functions before completing the command.
   1967 Once the TPM has received TPM2_SelfTest() and before completion of all tests, the TPM is required to
   1968 return TPM_RC_TESTING for any command that uses a function that requires a test.
   1969 If a self-test fails at any time, the TPM will enter Failure mode. While in Failure mode, the TPM will return
   1970 TPM_RC_FAILURE for any command other than TPM2_GetTestResult() and TPM2_GetCapability(). The
   1971 TPM will remain in Failure mode until the next _TPM_Init.
   1972 
   1973 
   1974 
   1975 
   1976 Page 30                                       TCG Published                                     Family 2.0
   1977 October 30, 2014                      Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   1978 Trusted Platform Module Library                                                                   Part 3: Commands
   1980 
   1981 
   1982 
   1983 10.2     TPM2_SelfTest
   1984 
   1985 10.2.1 General Description
   1986 
   1987 This command causes the TPM to perform a test of its capabilities. If the fullTest is YES, the TPM will test
   1988 all functions. If fullTest = NO, the TPM will only test those functions that have not previously been tested.
   1989 If any tests are required, the TPM shall either
   1990 a) return TPM_RC_TESTING and begin self-test of the required functions, or
   1991 
   1992     NOTE 1           If fullTest is NO, and all functions have been tested, the TPM shall return TPM_RC_SUCCESS.
   1993 
   1994 b) perform the tests and return the test result when complete.
   1995 If the TPM uses option a), the TPM shall return TPM_RC_TESTING for any command that requires use
   1996 of a testable function, even if the functions required for completion of the command have already been
   1997 tested.
   1998 
   1999 NOTE 2          This command may cause the TPM to continue processing after it has returned the response. So
   2000                 that software can be notified of the completion of the testing, the interface may include controls that
   2001                 would allow the TPM to generate an interrupt when th e background processing is complete. This
   2002                 would be in addition to the interrupt that may be available for signaling normal command completion.
   2003                 It is not necessary that there be two interrupts, but the interface should provide a way to indicate the
   2004                 nature of the interrupt (normal command or deferred command).
   2005 
   2006 
   2007 
   2008 
   2009 Family 2.0                                    TCG Published                                                Page 31
   2010 Level 00 Revision 01.16                Copyright  TCG 2006-2014                                  October 30, 2014
   2011 Part 3: Commands                                                  Trusted Platform Module Library
   2013 
   2014 
   2015 10.2.2 Command and Response
   2016 
   2017                          Table 9  TPM2_SelfTest Command
   2018 Type                   Name                  Description
   2019 
   2020                                              TPM_ST_SESSIONS if an audit session is present;
   2021 TPMI_ST_COMMAND_TAG    tag
   2022                                              otherwise, TPM_ST_NO_SESSIONS
   2023 UINT32                 commandSize
   2024 TPM_CC                 commandCode           TPM_CC_SelfTest {NV}
   2025 
   2026                                              YES if full test to be performed
   2027 TPMI_YES_NO            fullTest
   2028                                              NO if only test of untested functions required
   2029 
   2030 
   2031                         Table 10  TPM2_SelfTest Response
   2032 Type                   Name                  Description
   2033 
   2034 TPM_ST                 tag                   see clause 6
   2035 UINT32                 responseSize
   2036 TPM_RC                 responseCode
   2037 
   2038 
   2039 
   2040 
   2041 Page 32                               TCG Published                                      Family 2.0
   2042 October 30, 2014             Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   2043      Trusted Platform Module Library                                                        Part 3: Commands
   2045 
   2046 
   2047 
   2048      10.2.3 Detailed Actions
   2049 
   2050 1    #include "InternalRoutines.h"
   2051 2    #include "SelfTest_fp.h"
   2052 3    #ifdef TPM_CC_SelfTest // Conditional expansion of this file
   2053 
   2054 
   2055      Error Returns                     Meaning
   2056 
   2057      TPM_RC_CANCELED                   the command was canceled (some incremental process may have
   2058                                        been made)
   2059      TPM_RC_TESTING                    self test in process
   2060 
   2061  4   TPM_RC
   2062  5   TPM2_SelfTest(
   2063  6       SelfTest_In      *in                   // IN: input parameter list
   2064  7       )
   2065  8   {
   2066  9   // Command Output
   2067 10
   2068 11       // Call self test function in crypt module
   2069 12       return CryptSelfTest(in->fullTest);
   2070 13   }
   2071 14   #endif // CC_SelfTest
   2072 
   2073 
   2074 
   2075 
   2076      Family 2.0                                   TCG Published                                    Page 33
   2077      Level 00 Revision 01.16                Copyright  TCG 2006-2014                       October 30, 2014
   2078 Part 3: Commands                                                                    Trusted Platform Module Library
   2080 
   2081 
   2082 10.3     TPM2_IncrementalSelfTest
   2083 
   2084 10.3.1 General Description
   2085 
   2086 This command causes the TPM to perform a test of the selected algorithms.
   2087 
   2088 NOTE 1           The toTest list indicates the algorithms that software would like the TPM to test in anticipation of
   2089                  future use. This allows tests to be done so that a future commands will not be delayed due to
   2090                  testing.
   2091 
   2092                  The implementation may treat algorithms on the toTest list as either 'test each completely' or 'test
   2093                  this combination.'
   2094 
   2095 EXAMPLE          If the toTest list includes AES and CTR mode, it may be interpreted as a request to test only AES in
   2096                  CTR mode. Alternatively, it may be interpreted as a request to test AES in all modes and CTR mode
   2097                  for all symmetric algorithms.
   2098 
   2099 
   2100 If toTest contains an algorithm that has already been tested, it will not be tested again.
   2101 
   2102 NOTE 2           The only way to force retesting of an algorithm is with TPM2_SelfTest( fullTest = YES).
   2103 
   2104 The TPM will return in toDoList a list of algorithms that are yet to be tested. This list is not the list of
   2105 algorithms that are scheduled to be tested but the algorithms/functions that have not been tested. Only
   2106 the algorithms on the toTest list are scheduled to be tested by this command.
   2107 
   2108 NOTE 3           An algorithm remains on the toDoList while any part of it remains untested.
   2109 
   2110 EXAMPLE          A symmetric algorithm remains untested until it is tested with all its modes.
   2111 
   2112 Making toTest an empty list allows the determination of the algorithms that remain untested without
   2113 triggering any testing.
   2114 If toTest is not an empty list, the TPM shall return TPM_RC_SUCCESS for this command and then return
   2115 TPM_RC_TESTING for any subsequent command (including TPM2_IncrementalSelfTest()) until the
   2116 requested testing is complete.
   2117 
   2118 NOTE 4           If toDoList is empty, then no additional tests are required and TPM_RC_TESTING will not be
   2119                  returned in subsequent commands and no additional delay will occur in a command due to testing.
   2120 
   2121 NOTE 5           If none of the algorithms listed in toTest is in the toDoList, then no tests will be performed.
   2122 
   2123 NOTE 6           The TPM cannot return TPM_RC_TESTING for this command, even when testing is not complete,
   2124                  because response parameters can only returned with the TPM_RC_SUCCESS return code.
   2125 
   2126 If all the parameters in this command are valid, the TPM returns TPM_RC_SUCCESS and the toDoList
   2127 (which may be empty).
   2128 
   2129 NOTE 7           An implementation may perform all requested tests before returning TPM_RC_SUCCESS, or it may
   2130                  return TPM_RC_SUCCESS for this command and then return TPM_RC_TESTING for all
   2131                  subsequence commands (including TPM2_IncrementatSelfTest()) until the requested tests are
   2132                  complete.
   2133 
   2134 
   2135 
   2136 
   2137 Page 34                                           TCG Published                                            Family 2.0
   2138 October 30, 2014                         Copyright  TCG 2006-2014                          Level 00 Revision 01.16
   2139 Trusted Platform Module Library                                                            Part 3: Commands
   2141 
   2142 
   2143 
   2144 10.3.2 Command and Response
   2145 
   2146                           Table 11  TPM2_IncrementalSelfTest Command
   2147 Type                          Name                  Description
   2148 
   2149                                                     TPM_ST_SESSIONS if an audit session is present;
   2150 TPMI_ST_COMMAND_TAG           tag
   2151                                                     otherwise, TPM_ST_NO_SESSIONS
   2152 UINT32                        commandSize
   2153 TPM_CC                        commandCode           TPM_CC_IncrementalSelfTest {NV}
   2154 
   2155 TPML_ALG                      toTest                list of algorithms that should be tested
   2156 
   2157 
   2158                           Table 12  TPM2_IncrementalSelfTest Response
   2159 Type                          Name                  Description
   2160 
   2161 TPM_ST                        tag                   see clause 6
   2162 UINT32                        responseSize
   2163 TPM_RC                        responseCode
   2164 
   2165 TPML_ALG                      toDoList              list of algorithms that need testing
   2166 
   2167 
   2168 
   2169 
   2170 Family 2.0                                 TCG Published                                         Page 35
   2171 Level 00 Revision 01.16             Copyright  TCG 2006-2014                              October 30, 2014
   2172      Part 3: Commands                                                            Trusted Platform Module Library
   2174 
   2175 
   2176 
   2177      10.3.3 Detailed Actions
   2178 
   2179 1    #include "InternalRoutines.h"
   2180 2    #include "IncrementalSelfTest_fp.h"
   2181 3    #ifdef TPM_CC_IncrementalSelfTest // Conditional expansion of this file
   2182 
   2183 
   2184      Error Returns                 Meaning
   2185 
   2186      TPM_RC_CANCELED               the command was canceled (some tests may have completed)
   2187      TPM_RC_VALUE                  an algorithm in the toTest list is not implemented
   2188 
   2189  4   TPM_RC
   2190  5   TPM2_IncrementalSelfTest(
   2191  6       IncrementalSelfTest_In        *in,                // IN: input parameter list
   2192  7       IncrementalSelfTest_Out       *out                // OUT: output parameter list
   2193  8       )
   2194  9   {
   2195 10       TPM_RC                         result;
   2196 11   // Command Output
   2197 12
   2198 13       // Call incremental self test function in crypt module. If this function
   2199 14       // returns TPM_RC_VALUE, it means that an algorithm on the 'toTest' list is
   2200 15       // not implemented.
   2201 16       result = CryptIncrementalSelfTest(&in->toTest, &out->toDoList);
   2202 17       if(result == TPM_RC_VALUE)
   2203 18           return TPM_RCS_VALUE + RC_IncrementalSelfTest_toTest;
   2204 19       return result;
   2205 20   }
   2206 21   #endif // CC_IncrementalSelfTest
   2207 
   2208 
   2209 
   2210 
   2211      Page 36                                    TCG Published                                      Family 2.0
   2212      October 30, 2014                   Copyright  TCG 2006-2014                       Level 00 Revision 01.16
   2213 Trusted Platform Module Library                                                      Part 3: Commands
   2215 
   2216 
   2217 10.4   TPM2_GetTestResult
   2218 
   2219 10.4.1 General Description
   2220 
   2221 This command returns manufacturer-specific information regarding the results of a self-test and an
   2222 indication of the test status.
   2223 If TPM2_SelfTest() has not been executed and a testable function has not been tested, testResult will be
   2224 TPM_RC_NEEDS_TEST. If TPM2_SelfTest() has been received and the tests are not complete,
   2225 testResult will be TPM_RC_TESTING. If testing of all functions is complete without functional failures,
   2226 testResult will be TPM_RC_SUCCESS. If any test failed, testResult will be TPM_RC_FAILURE.
   2227 This command will operate when the TPM is in Failure mode so that software can determine the test
   2228 status of the TPM and so that diagnostic information can be obtained for use in failure analysis. If the
   2229 TPM is in Failure mode, then tag is required to be TPM_ST_NO_SESSIONS or the TPM shall return
   2230 TPM_RC_FAILURE.
   2231 
   2232 
   2233 
   2234 
   2235 Family 2.0                               TCG Published                                       Page 37
   2236 Level 00 Revision 01.16             Copyright  TCG 2006-2014                        October 30, 2014
   2237 Part 3: Commands                                                   Trusted Platform Module Library
   2239 
   2240 
   2241 
   2242 10.4.2 Command and Response
   2243 
   2244                        Table 13  TPM2_GetTestResult Command
   2245  Type                   Name                  Description
   2246 
   2247                                               TPM_ST_SESSIONS if an audit session is present;
   2248  TPMI_ST_COMMAND_TAG    tag
   2249                                               otherwise, TPM_ST_NO_SESSIONS
   2250  UINT32                 commandSize
   2251  TPM_CC                 commandCode           TPM_CC_GetTestResult
   2252 
   2253 
   2254                        Table 14  TPM2_GetTestResult Response
   2255  Type                   Name                  Description
   2256 
   2257  TPMI_ST_COMMAND_TAG    tag                   see clause 6
   2258  UINT32                 responseSize
   2259  TPM_RC                 responseCode
   2260 
   2261                                               test result data
   2262  TPM2B_MAX_BUFFER       outData
   2263                                               contains manufacturer-specific information
   2264  TPM_RC                 testResult
   2265 
   2266 
   2267 
   2268 
   2269 Page 38                                TCG Published                                       Family 2.0
   2270 October 30, 2014               Copyright  TCG 2006-2014                 Level 00 Revision 01.16
   2271      Trusted Platform Module Library                                                         Part 3: Commands
   2273 
   2274 
   2275 
   2276      10.4.3 Detailed Actions
   2277 
   2278 1    #include "InternalRoutines.h"
   2279 2    #include "GetTestResult_fp.h"
   2280 3    #ifdef TPM_CC_GetTestResult // Conditional expansion of this file
   2281 
   2282      In the reference implementation, this function is only reachable if the TPM is not in failure mode meaning
   2283      that all tests that have been run have completed successfully. There is not test data and the test result is
   2284      TPM_RC_SUCCESS.
   2285 
   2286  4   TPM_RC
   2287  5   TPM2_GetTestResult(
   2288  6       GetTestResult_Out      *out               // OUT: output parameter list
   2289  7       )
   2290  8   {
   2291  9   // Command Output
   2292 10
   2293 11       // Call incremental self test function in crypt module
   2294 12       out->testResult = CryptGetTestResult(&out->outData);
   2295 13
   2296 14       return TPM_RC_SUCCESS;
   2297 15   }
   2298 16   #endif // CC_GetTestResult
   2299 
   2300 
   2301 
   2302 
   2303      Family 2.0                                 TCG Published                                        Page 39
   2304      Level 00 Revision 01.16              Copyright  TCG 2006-2014                          October 30, 2014
   2305 Part 3: Commands                                                                    Trusted Platform Module Library
   2307 
   2308 
   2309 11     Session Commands
   2310 
   2311 11.1     TPM2_StartAuthSession
   2312 
   2313 11.1.1 General Description
   2314 
   2315 This command is used to start an authorization session using alternative methods of establishing the
   2316 session key (sessionKey). The session key is then used to derive values used for authorization and for
   2317 encrypting parameters.
   2318 This command allows injection of a secret into the TPM using either asymmetric or symmetric encryption.
   2319 The type of tpmKey determines how the value in encryptedSalt is encrypted. The decrypted secret value
   2320 is used to compute the sessionKey.
   2321 
   2322 NOTE 1           If tpmKey Is TPM_RH_NULL, then encryptedSalt is required to be an Empty Buffer.
   2323 
   2324 The label value of SECRET (see Terms and Definitions in TPM 2.0 Part 1) is used in the recovery of
   2325 the secret value.
   2326 The TPM generates the sessionKey from the recovered secret value.
   2327 No authorization is required for tpmKey or bind.
   2328 
   2329 NOTE 2           The justification for using tpmKey without providing authorization is that the result of using the key is
   2330                  not available to the caller, except indirectly through the sessionKey. This does not represent a point
   2331                  of attack on the value of the key. If th e caller attempts to use the session without knowing the
   2332                  sessionKey value, it is an authorization failure that will trigger the dictionary attack logic.
   2333 
   2334 The entity referenced with the bind parameter contributes an authorization value to the sessionKey
   2335 generation process.
   2336 If both tpmKey and bind are TPM_ALG_NULL, then sessionKey is set to the Empty Buffer. If tpmKey is
   2337 not TPM_ALG_NULL, then encryptedSalt is used in the computation of sessionKey. If bind is not
   2338 TPM_ALG_NULL, the authValue of bind is used in the sessionKey computation.
   2339 If symmetric specifies a block cipher, then TPM_ALG_CFB is the only allowed value for the mode field in
   2340 the symmetric parameter (TPM_RC_MODE).
   2341 This command starts an authorization session and returns the session handle along with an initial
   2342 nonceTPM in the response.
   2343 If the TPM does not have                 a   free    slot   for   an   authorization     session,     it   shall   return
   2344 TPM_RC_SESSION_HANDLES.
   2345 If the TPM implements a gap scheme for assigning contextID values, then the TPM shall return
   2346 TPM_RC_CONTEXT_GAP if creating the session would prevent recycling of old saved contexts (See
   2347 Context Management in TPM 2.0 Part 1).
   2348 If tpmKey is not TPM_ALG_NULL then encryptedSalt shall be a TPM2B_ENCRYPTED_SECRET of the
   2349 proper type for tpmKey. The TPM shall return TPM_RC_HANDLE if the sensitive portion of tpmKey is not
   2350 loaded. The TPM shall return TPM_RC_VALUE if:
   2351 a) tpmKey references an RSA key and
   2352      1) encryptedSalt does not contain a value that is the size of the public modulus of tpmKey,
   2353      2) encryptedSalt has a value that is greater than the public modulus of tpmKey,
   2354      3) encryptedSalt is not a properly encoded OAEP value, or
   2355      4) the decrypted salt value is larger than the size of the digest produced by the nameAlg of tpmKey;
   2356         or
   2357 
   2358 
   2359 Page 40                                          TCG Published                                             Family 2.0
   2360 October 30, 2014                         Copyright  TCG 2006-2014                         Level 00 Revision 01.16
   2361 Trusted Platform Module Library                                                                 Part 3: Commands
   2363 
   2364 b) tpmKey references an ECC key and encryptedSalt
   2365     1) does not contain a TPMS_ECC_POINT or
   2366     2) is not a point on the curve of tpmKey;
   2367 
   2368     NOTE 3           When ECC is used, the point multiply process produces a value (Z) that is used in a KDF to
   2369                      produce the final secret value. The size of the secret value is an input parameter to the KDF
   2370                      and the result will be set to be the size of the digest produced by the nameAlg of tpmKey.
   2371 
   2372 c) tpmKey references a symmetric block cipher or a keyedHash object and encryptedSalt contains a
   2373    value that is larger than the size of the digest produced by the nameAlg of tpmKey.
   2374 If bind references a transient object, then the TPM shall return TPM_RC_HANDLE if the sensitive portion
   2375 of the object is not loaded.
   2376 For all session types, this command will cause initialization of the sessionKey and may establish binding
   2377 between the session and an object (the bind object). If sessionType is TPM_SE_POLICY or
   2378 TPM_SE_TRIAL, the additional session initialization is:
   2379         set policySessionpolicyDigest to a Zero Digest (the digest size for policySessionpolicyDigest
   2380          is the size of the digest produced by authHash);
   2381         authorization may be given at any locality;
   2382         authorization may apply to any command code;
   2383         authorization may apply to any command parameters or handles;
   2384         the authorization has no time limit;
   2385         an authValue is not needed when the authorization is used;
   2386         the session is not bound;
   2387         the session is not an audit session; and
   2388         the time at which the policy session was created is recorded.
   2389 Additionally, if sessionType is TPM_SE_TRIAL, the session will not be usable for authorization but can be
   2390 used to compute the authPolicy for an object.
   2391 
   2392 NOTE 4           Although this command changes the session allocation information in the TPM, it does not invalidate
   2393                  a saved context. That is, TPM2_Shutdown() is not required after this command in order to re-
   2394                  establish the orderly state of the TPM. This is because the created cont ext will occupy an available
   2395                  slot in the TPM and sessions in the TPM do not survive any TPM2_Startup(). However, if a created
   2396                  session is context saved, the orderly state does change.
   2397 
   2398 The TPM shall return TPM_RC_SIZE if nonceCaller is less than 16 octets or is greater than the size of
   2399 the digest produced by authHash.
   2400 
   2401 
   2402 
   2403 
   2404 Family 2.0                                    TCG Published                                              Page 41
   2405 Level 00 Revision 01.16                 Copyright  TCG 2006-2014                               October 30, 2014
   2406 Part 3: Commands                                                      Trusted Platform Module Library
   2408 
   2409 
   2410 
   2411 11.1.2 Command and Response
   2412 
   2413                        Table 15  TPM2_StartAuthSession Command
   2414 Type                      Name                  Description
   2415 
   2416                                                 TPM_ST_SESSIONS if an audit, decrypt, or encrypt
   2417 TPMI_ST_COMMAND_TAG       tag                   session is present; otherwise,
   2418                                                 TPM_ST_NO_SESSIONS
   2419 UINT32                    commandSize
   2420 TPM_CC                    commandCode           TPM_CC_StartAuthSession
   2421 
   2422                                                 handle of a loaded decrypt key used to encrypt salt
   2423 TPMI_DH_OBJECT+           tpmKey                may be TPM_RH_NULL
   2424                                                 Auth Index: None
   2425                                                 entity providing the authValue
   2426 TPMI_DH_ENTITY+           bind                  may be TPM_RH_NULL
   2427                                                 Auth Index: None
   2428 
   2429                                                 initial nonceCaller, sets nonce size for the session
   2430 TPM2B_NONCE               nonceCaller
   2431                                                 shall be at least 16 octets
   2432                                                 value encrypted according to the type of tpmKey
   2433 TPM2B_ENCRYPTED_SECRET encryptedSalt            If tpmKey is TPM_RH_NULL, this shall be the Empty
   2434                                                 Buffer.
   2435                                                 indicates the type of the session; simple HMAC or policy
   2436 TPM_SE                    sessionType
   2437                                                 (including a trial policy)
   2438                                                 the algorithm and key size for parameter encryption
   2439 TPMT_SYM_DEF+             symmetric
   2440                                                 may select TPM_ALG_NULL
   2441                                                 hash algorithm to use for the session
   2442 TPMI_ALG_HASH             authHash              Shall be a hash algorithm supported by the TPM and
   2443                                                 not TPM_ALG_NULL
   2444 
   2445 
   2446                        Table 16  TPM2_StartAuthSession Response
   2447 Type                      Name                  Description
   2448 TPM_ST                    tag                   see clause 6
   2449 UINT32                    responseSize
   2450 TPM_RC                    responseCode
   2451 
   2452 TPMI_SH_AUTH_SESSION      sessionHandle         handle for the newly created session
   2453 
   2454                                                 the initial nonce from the TPM, used in the computation
   2455 TPM2B_NONCE               nonceTPM
   2456                                                 of the sessionKey
   2457 
   2458 
   2459 
   2460 
   2461 Page 42                                  TCG Published                                      Family 2.0
   2462 October 30, 2014                 Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   2463      Trusted Platform Module Library                                                                Part 3: Commands
   2465 
   2466 
   2467 
   2468      11.1.3 Detailed Actions
   2469 
   2470 1    #include "InternalRoutines.h"
   2471 2    #include "StartAuthSession_fp.h"
   2472 3    #ifdef TPM_CC_StartAuthSession // Conditional expansion of this file
   2473 
   2474 
   2475      Error Returns                     Meaning
   2476 
   2477      TPM_RC_ATTRIBUTES                 tpmKey does not reference a decrypt key
   2478      TPM_RC_CONTEXT_GAP                the difference between the most recently created active context and
   2479                                        the oldest active context is at the limits of the TPM
   2480      TPM_RC_HANDLE                     input decrypt key handle only has public portion loaded
   2481      TPM_RC_MODE                       symmetric specifies a block cipher but the mode is not
   2482                                        TPM_ALG_CFB.
   2483      TPM_RC_SESSION_HANDLES            no session handle is available
   2484      TPM_RC_SESSION_MEMORY             no more slots for loading a session
   2485      TPM_RC_SIZE                       nonce less than 16 octets or greater than the size of the digest
   2486                                        produced by authHash
   2487      TPM_RC_VALUE                      secret size does not match decrypt key type; or the recovered secret
   2488                                        is larger than the digest size of the nameAlg of tpmKey; or, for an
   2489                                        RSA decrypt key, if encryptedSecret is greater than the public
   2490                                        exponent of tpmKey.
   2491 
   2492  4   TPM_RC
   2493  5   TPM2_StartAuthSession(
   2494  6       StartAuthSession_In       *in,                   // IN: input parameter buffer
   2495  7       StartAuthSession_Out      *out                   // OUT: output parameter buffer
   2496  8       )
   2497  9   {
   2498 10       TPM_RC                     result = TPM_RC_SUCCESS;
   2499 11       OBJECT                    *tpmKey;                // TPM key for decrypt salt
   2500 12       SESSION                   *session;               // session internal data
   2501 13       TPM2B_DATA                 salt;
   2502 14
   2503 15   // Input Validation
   2504 16
   2505 17       // Check input nonce size. IT should be at least 16 bytes but not larger
   2506 18       // than the digest size of session hash.
   2507 19       if(    in->nonceCaller.t.size < 16
   2508 20           || in->nonceCaller.t.size > CryptGetHashDigestSize(in->authHash))
   2509 21           return TPM_RC_SIZE + RC_StartAuthSession_nonceCaller;
   2510 22
   2511 23       // If an decrypt key is passed in, check its validation
   2512 24       if(in->tpmKey != TPM_RH_NULL)
   2513 25       {
   2514 26           // secret size cannot be 0
   2515 27           if(in->encryptedSalt.t.size == 0)
   2516 28               return TPM_RC_VALUE + RC_StartAuthSession_encryptedSalt;
   2517 29
   2518 30           // Get pointer to loaded decrypt key
   2519 31           tpmKey = ObjectGet(in->tpmKey);
   2520 32
   2521 33           // Decrypting salt requires accessing the private portion of a key.
   2522 34           // Therefore, tmpKey can not be a key with only public portion loaded
   2523 35           if(tpmKey->attributes.publicOnly)
   2524 36               return TPM_RC_HANDLE + RC_StartAuthSession_tpmKey;
   2525 37
   2526 38           // HMAC session input handle check.
   2527 
   2528      Family 2.0                                   TCG Published                                             Page 43
   2529      Level 00 Revision 01.16               Copyright  TCG 2006-2014                                October 30, 2014
   2530      Part 3: Commands                                                  Trusted Platform Module Library
   2532 
   2533 39             // tpmKey should be a decryption key
   2534 40             if(tpmKey->publicArea.objectAttributes.decrypt != SET)
   2535 41                 return TPM_RC_ATTRIBUTES + RC_StartAuthSession_tpmKey;
   2536 42
   2537 43             // Secret Decryption. A TPM_RC_VALUE, TPM_RC_KEY or Unmarshal errors
   2538 44             // may be returned at this point
   2539 45             result = CryptSecretDecrypt(in->tpmKey, &in->nonceCaller, "SECRET",
   2540 46                                         &in->encryptedSalt, &salt);
   2541 47             if(result != TPM_RC_SUCCESS)
   2542 48                 return TPM_RC_VALUE + RC_StartAuthSession_encryptedSalt;
   2543 49
   2544 50      }
   2545 51      else
   2546 52      {
   2547 53          // secret size must be 0
   2548 54          if(in->encryptedSalt.t.size != 0)
   2549 55              return TPM_RC_VALUE + RC_StartAuthSession_encryptedSalt;
   2550 56          salt.t.size = 0;
   2551 57      }
   2552 58      // If the bind handle references a transient object, make sure that the
   2553 59      // sensitive area is loaded so that the authValue can be accessed.
   2554 60      if(     HandleGetType(in->bind) == TPM_HT_TRANSIENT
   2555 61          && ObjectGet(in->bind)->attributes.publicOnly == SET)
   2556 62          return TPM_RC_HANDLE + RC_StartAuthSession_bind;
   2557 63
   2558 64      // If 'symmetric' is a symmetric block cipher (not TPM_ALG_NULL or TPM_ALG_XOR)
   2559 65      // then the mode must be CFB.
   2560 66      if(    in->symmetric.algorithm != TPM_ALG_NULL
   2561 67          && in->symmetric.algorithm != TPM_ALG_XOR
   2562 68          && in->symmetric.mode.sym != TPM_ALG_CFB)
   2563 69          return TPM_RC_MODE + RC_StartAuthSession_symmetric;
   2564 70
   2565 71   // Internal Data Update
   2566 72
   2567 73      // Create internal session structure. TPM_RC_CONTEXT_GAP, TPM_RC_NO_HANDLES
   2568 74      // or TPM_RC_SESSION_MEMORY errors may be returned returned at this point.
   2569 75      //
   2570 76      // The detailed actions for creating the session context are not shown here
   2571 77      // as the details are implementation dependent
   2572 78      // SessionCreate sets the output handle
   2573 79      result = SessionCreate(in->sessionType, in->authHash,
   2574 80                             &in->nonceCaller, &in->symmetric,
   2575 81                             in->bind, &salt, &out->sessionHandle);
   2576 82
   2577 83      if(result != TPM_RC_SUCCESS)
   2578 84          return result;
   2579 85
   2580 86   // Command Output
   2581 87
   2582 88      // Get session pointer
   2583 89      session = SessionGet(out->sessionHandle);
   2584 90
   2585 91      // Copy nonceTPM
   2586 92      out->nonceTPM = session->nonceTPM;
   2587 93
   2588 94       return TPM_RC_SUCCESS;
   2589 95   }
   2590 96   #endif // CC_StartAuthSession
   2591 
   2592 
   2593 
   2594 
   2595      Page 44                                  TCG Published                              Family 2.0
   2596      October 30, 2014                  Copyright  TCG 2006-2014            Level 00 Revision 01.16
   2597 Trusted Platform Module Library                                                     Part 3: Commands
   2599 
   2600 
   2601 11.2   TPM2_PolicyRestart
   2602 
   2603 11.2.1 General Description
   2604 
   2605 This command allows a policy authorization session to be returned to its initial state. This command is
   2606 used after the TPM returns TPM_RC_PCR_CHANGED. That response code indicates that a policy will
   2607 fail because the PCR have changed after TPM2_PolicyPCR() was executed. Restarting the session
   2608 allows the authorizations to be replayed because the session restarts with the same nonceTPM. If the
   2609 PCR are valid for the policy, the policy may then succeed.
   2610 This command does not reset the policy ID or the policy start time.
   2611 
   2612 
   2613 
   2614 
   2615 Family 2.0                                TCG Published                                     Page 45
   2616 Level 00 Revision 01.16              Copyright  TCG 2006-2014                      October 30, 2014
   2617 Part 3: Commands                                                  Trusted Platform Module Library
   2619 
   2620 
   2621 
   2622 11.2.2 Command and Response
   2623 
   2624                       Table 17  TPM2_PolicyRestart Command
   2625 Type                   Name                  Description
   2626 
   2627                                              TPM_ST_SESSIONS if an audit session is present;
   2628 TPMI_ST_COMMAND_TAG    tag
   2629                                              otherwise, TPM_ST_NO_SESSIONS
   2630 UINT32                 commandSize
   2631 TPM_CC                 commandCode           TPM_CC_PolicyRestart
   2632 
   2633 TPMI_SH_POLICY         sessionHandle         the handle for the policy session
   2634 
   2635 
   2636                       Table 18  TPM2_PolicyRestart Response
   2637 Type                   Name                  Description
   2638 
   2639 TPM_ST                 tag                   see clause 6
   2640 UINT32                 responseSize
   2641 TPM_RC                 responseCode
   2642 
   2643 
   2644 
   2645 
   2646 Page 46                               TCG Published                                 Family 2.0
   2647 October 30, 2014             Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   2648      Trusted Platform Module Library                                          Part 3: Commands
   2650 
   2651 
   2652 
   2653      11.2.3 Detailed Actions
   2654 
   2655  1   #include "InternalRoutines.h"
   2656  2   #include "PolicyRestart_fp.h"
   2657  3   #ifdef TPM_CC_PolicyRestart // Conditional expansion of this file
   2658  4   TPM_RC
   2659  5   TPM2_PolicyRestart(
   2660  6       PolicyRestart_In      *in              // IN: input parameter list
   2661  7       )
   2662  8   {
   2663  9       SESSION                     *session;
   2664 10       BOOL                         wasTrialSession;
   2665 11
   2666 12   // Internal Data Update
   2667 13
   2668 14       session = SessionGet(in->sessionHandle);
   2669 15       wasTrialSession = session->attributes.isTrialPolicy == SET;
   2670 16
   2671 17       // Initialize policy session
   2672 18       SessionResetPolicyData(session);
   2673 19
   2674 20       session->attributes.isTrialPolicy = wasTrialSession;
   2675 21
   2676 22       return TPM_RC_SUCCESS;
   2677 23   }
   2678 24   #endif // CC_PolicyRestart
   2679 
   2680 
   2681 
   2682 
   2683      Family 2.0                               TCG Published                         Page 47
   2684      Level 00 Revision 01.16             Copyright  TCG 2006-2014            October 30, 2014
   2685 Part 3: Commands                                                              Trusted Platform Module Library
   2687 
   2688 
   2689 12     Object Commands
   2690 
   2691 12.1    TPM2_Create
   2692 
   2693 12.1.1 General Description
   2694 
   2695 This command is used to create an object that can be loaded into a TPM using TPM2_Load(). If the
   2696 command completes successfully, the TPM will create the new object and return the objects creation
   2697 data (creationData), its public area (outPublic), and its encrypted sensitive area (outPrivate). Preservation
   2698 of the returned data is the responsibility of the caller. The object will need to be loaded (TPM2_Load())
   2699 before it may be used.
   2700 TPM2B_PUBLIC template (inPublic) contains all of the fields necessary to define the properties of the
   2701 new object. The setting for these fields is defined in Public Area Template in TPM 2.0 Part 1 and
   2702 TPMA_OBJECT in TPM 2.0 Part 2.
   2703 The parentHandle parameter shall reference a loaded decryption key that has both the public and
   2704 sensitive area loaded.
   2705 When defining the object, the caller provides a template structure for the object in a TPM2B_PUBLIC
   2706 structure (inPublic), an initial value for the objects authValue (inSensitive.userAuth), and, if the object is a
   2707 symmetric object, an optional initial data value (inSensitive.data). The TPM shall validate the consistency
   2708 of inPublic.attributes according to the Creation rules in TPMA_OBJECT in TPM 2.0 Part 2.
   2709 The inSensitive parameter may be encrypted using parameter encryption.
   2710 The methods in this clause are used by both TPM2_Create() and TPM2_CreatePrimary(). When a value
   2711 is indicated as being TPM-generated, the value is filled in by bits from the RNG if the command is
   2712 TPM2_Create() and with values from KDFa() if the command is TPM2_CreatePrimary(). The parameters
   2713 of each creation value are specified in TPM 2.0 Part 1.
   2714 The sensitiveDataOrigin attribute of inPublic shall be SET if inSensitive.data is an Empty Buffer and
   2715 CLEAR if inSensitive.data is not an Empty Buffer or the TPM shall return TPM_RC_ATTRIBUTES.
   2716 The TPM will create new data for the sensitive area and compute a TPMT_PUBLIC.unique from the
   2717 sensitive area based on the object type:
   2718 a) For a symmetric key:
   2719      1) If inSensitive.sensitive.data is the Empty Buffer, a TPM-generated key value is placed in the new
   2720         objects TPMT_SENSITIVE.sensitive.sym. The size of the key will be determined by
   2721         inPublic.publicArea.parameters.
   2722      2) If inSensitive.sensitive.data is not the Empty Buffer, the TPM will validate that the size of
   2723         inSensitive.data is no larger than the key size indicated in the inPublic template (TPM_RC_SIZE)
   2724         and copy the inSensitive.data to TPMT_SENSITIVE.sensitive.sym of the new object.
   2725      3) A TPM-generated obfuscation value is placed in TPMT_SENSITIVE.sensitive.seedValue. The
   2726         size of the obfuscation value is the size of the digest produced by the nameAlg in inPublic. This
   2727         value prevents the public unique value from leaking information about the sensitive area.
   2728      4) The TPMT_PUBLIC.unique.sym value for the new object is then generated, as shown in equation
   2729         (1) below, by hashing the key and obfuscation values in the TPMT_SENSITIVE with the nameAlg
   2730         of the object.
   2731                    unique  HnameAlg(sensitive.seedValue.buffer || sensitive.any.buffer)                     (1)
   2732 b) If the Object is an asymmetric key:
   2733      1) If inSensitive.sensitive.data is not the Empty Buffer, then the TPM shall return TPM_RC_VALUE.
   2734 
   2735 
   2736 
   2737 Page 48                                        TCG Published                                       Family 2.0
   2738 October 30, 2014                       Copyright  TCG 2006-2014                     Level 00 Revision 01.16
   2739 Trusted Platform Module Library                                                                  Part 3: Commands
   2741 
   2742     2) A TPM-generated private key value is created with the size determined by the parameters of
   2743        inPublic.publicArea.parameters.
   2744     3) If the key is a Storage Key, a TPM-generated TPMT_SENSITIVE.seedValue value is created;
   2745        otherwise, TPMT_SENSITIVE.seedValue.size is set to zero.
   2746 
   2747          NOTE 1       An Object that is not a storage key has no child Objects to encrypt, so it does not need a
   2748                       symmetric key.
   2749 
   2750     4) The public unique value is computed from the private key according to the methods of the key
   2751        type.
   2752     5) If the key is an ECC key and the scheme required by the curveID is not the same as scheme in
   2753        the public area of the template, then the TPM shall return TPM_RC_SCHEME.
   2754     6) If the key is an ECC key and the KDF required by the curveID is not the same as kdf in the pubic
   2755        area of the template, then the TPM shall return TPM_RC_KDF.
   2756 
   2757          NOTE 2            There is currently no command in which the caller may specify the KDF to be used with an
   2758                            ECC decryption key. Since there is no use for this capability, the reference implementation
   2759                            requires that the kdf in the template be set to TPM_ALG_NULL or TPM_RC_KDF is
   2760                            returned.
   2761 
   2762 c) If the Object is a keyedHash object:
   2763     1) If inSensitive.sensitive.data is an Empty Buffer, and neither sign nor decrypt is SET in
   2764        inPublic.attributes, the TPM shall return TPM_RC_ATTRIBUTES. This would be a data object
   2765        with no data.
   2766     2) If inSensitive.sensitive.data is not an Empty Buffer, the TPM will                                  copy    the
   2767        inSensitive.sensitive.data to TPMT_SENSITIVE.sensitive,bits of the new object.
   2768 
   2769          NOTE 3            The size of inSensitive.sensitive.data is limited to be no larger than the largest value of
   2770                            TPMT_SENSITIVE.sensitive.bits by MAX_SYM_DATA.
   2771 
   2772     3) If inSensitive.sensitive.data is an Empty Buffer, a TPM-generated key value that is the size of the
   2773        digest produced by the nameAlg in inPublic is placed in TPMT_SENSITIVE.sensitive.bits.
   2774     4) A TPM-generated obfuscation value that is the size of the digest produced by the nameAlg of
   2775        inPublic is placed in TPMT_SENSITIVE.seedValue.
   2776     5) The TPMT_PUBLIC.unique.keyedHash value for the new object is then generated, as shown in
   2777        equation (1) above, by hashing the key and obfuscation values in the TPMT_SENSITIVE with the
   2778        nameAlg of the object.
   2779 For TPM2_Load(), the TPM will apply normal symmetric protections to the created TPMT_SENSITIVE to
   2780 create outPublic.
   2781 
   2782 NOTE 4            The encryption key is derived from the symmetric seed in the sensitive area of the parent.
   2783 
   2784 In addition to outPublic and outPrivate, the TPM will build a TPMS_CREATION_DATA structure for the
   2785 object. TPMS_CREATION_DATA.outsideInfo is set to outsideInfo. This structure is returned in
   2786 creationData. Additionally, the digest of this structure is returned in creationHash, and, finally, a
   2787 TPMT_TK_CREATION is created so that the association between the creation data and the object may
   2788 be validated by TPM2_CertifyCreation().
   2789 If the object being created is a Storage Key and inPublic.objectAttributes.fixedParent is SET, then the
   2790 algorithms and parameters of inPublic are required to match those of the parent. The algorithms that must
   2791 match are inPublic.type, inPublic.nameAlg, and inPublic.parameters. If inPublic.type does not match, the
   2792 TPM shall return TPM_RC_TYPE. If inPublic.nameAlg does not match, the TPM shall return
   2793 TPM_RC_HASH. If inPublic.parameters does not match, the TPM shall return TPM_RC_ASSYMETRIC.
   2794 The TPM shall not differentiate between mismatches of the components of inPublic.parameters.
   2795 
   2796 
   2797 Family 2.0                                     TCG Published                                                 Page 49
   2798 Level 00 Revision 01.16                  Copyright  TCG 2006-2014                               October 30, 2014
   2799 Part 3: Commands                                                           Trusted Platform Module Library
   2801 
   2802 EXAMPLE      If the inPublic.parameters.ecc.symmetric.algorithm does not match the parent, the TPM shall return
   2803              TPM_RC_ ASYMMETRIC rather than TPM_RC_SYMMETRIC.
   2804 
   2805 
   2806 
   2807 
   2808 Page 50                                    TCG Published                                        Family 2.0
   2809 October 30, 2014                   Copyright  TCG 2006-2014                      Level 00 Revision 01.16
   2810 Trusted Platform Module Library                                                          Part 3: Commands
   2812 
   2813 
   2814 12.1.2 Command and Response
   2815 
   2816                                   Table 19  TPM2_Create Command
   2817 Type                          Name                  Description
   2818 
   2819 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   2820 UINT32                        commandSize
   2821 TPM_CC                        commandCode           TPM_CC_Create
   2822 
   2823                                                     handle of parent for new object
   2824 TPMI_DH_OBJECT                @parentHandle         Auth Index: 1
   2825                                                     Auth Role: USER
   2826 
   2827 TPM2B_SENSITIVE_CREATE        inSensitive           the sensitive data
   2828 TPM2B_PUBLIC                  inPublic              the public template
   2829                                                     data that will be included in the creation data for this
   2830 TPM2B_DATA                    outsideInfo           object to provide permanent, verifiable linkage between
   2831                                                     this object and some object owner data
   2832 TPML_PCR_SELECTION            creationPCR           PCR that will be used in creation data
   2833 
   2834 
   2835                                   Table 20  TPM2_Create Response
   2836 Type                          Name                  Description
   2837 
   2838 TPM_ST                        tag                   see clause 6
   2839 UINT32                        responseSize
   2840 TPM_RC                        responseCode
   2841 
   2842 TPM2B_PRIVATE                 outPrivate            the private portion of the object
   2843 TPM2B_PUBLIC                  outPublic             the public portion of the created object
   2844 TPM2B_CREATION_DATA           creationData          contains a TPMS_CREATION_DATA
   2845 TPM2B_DIGEST                  creationHash          digest of creationData using nameAlg of outPublic
   2846                                                     ticket used by TPM2_CertifyCreation() to validate that
   2847 TPMT_TK_CREATION              creationTicket
   2848                                                     the creation data was produced by the TPM
   2849 
   2850 
   2851 
   2852 
   2853 Family 2.0                                 TCG Published                                         Page 51
   2854 Level 00 Revision 01.16             Copyright  TCG 2006-2014                            October 30, 2014
   2855      Part 3: Commands                                                            Trusted Platform Module Library
   2857 
   2858 
   2859 
   2860      12.1.3 Detailed Actions
   2861 
   2862 1    #include "InternalRoutines.h"
   2863 2    #include "Object_spt_fp.h"
   2864 3    #include "Create_fp.h"
   2865 4    #ifdef TPM_CC_Create // Conditional expansion of this file
   2866 
   2867 
   2868      Error Returns               Meaning
   2869 
   2870      TPM_RC_ASYMMETRIC           non-duplicable storage key and its parent have different public
   2871                                  parameters
   2872      TPM_RC_ATTRIBUTES           sensitiveDataOrigin is CLEAR when 'sensitive.data' is an Empty
   2873                                  Buffer, or is SET when 'sensitive.data' is not empty; fixedTPM,
   2874                                  fixedParent, or encryptedDuplication attributes are inconsistent
   2875                                  between themselves or with those of the parent object; inconsistent
   2876                                  restricted, decrypt and sign attributes; attempt to inject sensitive data
   2877                                  for an asymmetric key; attempt to create a symmetric cipher key that
   2878                                  is not a decryption key
   2879      TPM_RC_HASH                 non-duplicable storage key and its parent have different name
   2880                                  algorithm
   2881      TPM_RC_KDF                  incorrect KDF specified for decrypting keyed hash object
   2882      TPM_RC_KEY                  invalid key size values in an asymmetric key public area
   2883      TPM_RC_KEY_SIZE             key size in public area for symmetric key differs from the size in the
   2884                                  sensitive creation area; may also be returned if the TPM does not
   2885                                  allow the key size to be used for a Storage Key
   2886      TPM_RC_RANGE                the exponent value of an RSA key is not supported.
   2887      TPM_RC_SCHEME               inconsistent attributes decrypt, sign, restricted and key's scheme ID;
   2888                                  or hash algorithm is inconsistent with the scheme ID for keyed hash
   2889                                  object
   2890      TPM_RC_SIZE                 size of public auth policy or sensitive auth value does not match
   2891                                  digest size of the name algorithm sensitive data size for the keyed
   2892                                  hash object is larger than is allowed for the scheme
   2893      TPM_RC_SYMMETRIC            a storage key with no symmetric algorithm specified; or non-storage
   2894                                  key with symmetric algorithm different from TPM_ALG_NULL
   2895      TPM_RC_TYPE                 unknown object type; non-duplicable storage key and its parent have
   2896                                  different types; parentHandle does not reference a restricted
   2897                                  decryption key in the storage hierarchy with both public and sensitive
   2898                                  portion loaded
   2899      TPM_RC_VALUE                exponent is not prime or could not find a prime using the provided
   2900                                  parameters for an RSA key; unsupported name algorithm for an ECC
   2901                                  key
   2902      TPM_RC_OBJECT_MEMORY        there is no free slot for the object. This implementation does not
   2903                                  return this error.
   2904 
   2905  5   TPM_RC
   2906  6   TPM2_Create(
   2907  7       Create_In        *in,            // IN: input parameter list
   2908  8       Create_Out       *out            // OUT: output parameter list
   2909  9       )
   2910 10   {
   2911 11       TPM_RC                  result = TPM_RC_SUCCESS;
   2912 12       TPMT_SENSITIVE          sensitive;
   2913 13       TPM2B_NAME              name;
   2914 14
   2915 
   2916      Page 52                                  TCG Published                                             Family 2.0
   2917      October 30, 2014                 Copyright  TCG 2006-2014                         Level 00 Revision 01.16
   2918      Trusted Platform Module Library                                                Part 3: Commands
   2920 
   2921 15   // Input Validation
   2922 16
   2923 17       OBJECT       *parentObject;
   2924 18
   2925 19       parentObject = ObjectGet(in->parentHandle);
   2926 20
   2927 21       // Does parent have the proper attributes?
   2928 22       if(!AreAttributesForParent(parentObject))
   2929 23           return TPM_RC_TYPE + RC_Create_parentHandle;
   2930 24
   2931 25       // The sensitiveDataOrigin attribute must be consistent with the setting of
   2932 26       // the size of the data object in inSensitive.
   2933 27       if(   (in->inPublic.t.publicArea.objectAttributes.sensitiveDataOrigin == SET)
   2934 28          != (in->inSensitive.t.sensitive.data.t.size == 0))
   2935 29           // Mismatch between the object attributes and the parameter.
   2936 30           return TPM_RC_ATTRIBUTES + RC_Create_inSensitive;
   2937 31
   2938 32       // Check attributes in input public area. TPM_RC_ASYMMETRIC, TPM_RC_ATTRIBUTES,
   2939 33       // TPM_RC_HASH, TPM_RC_KDF, TPM_RC_SCHEME, TPM_RC_SIZE, TPM_RC_SYMMETRIC,
   2940 34       // or TPM_RC_TYPE error may be returned at this point.
   2941 35       result = PublicAttributesValidation(FALSE, in->parentHandle,
   2942 36                                           &in->inPublic.t.publicArea);
   2943 37       if(result != TPM_RC_SUCCESS)
   2944 38           return RcSafeAddToResult(result, RC_Create_inPublic);
   2945 39
   2946 40       // Validate the sensitive area values
   2947 41       if( MemoryRemoveTrailingZeros(&in->inSensitive.t.sensitive.userAuth)
   2948 42               > CryptGetHashDigestSize(in->inPublic.t.publicArea.nameAlg))
   2949 43           return TPM_RC_SIZE + RC_Create_inSensitive;
   2950 44
   2951 45   // Command Output
   2952 46
   2953 47       // Create object crypto data
   2954 48       result = CryptCreateObject(in->parentHandle, &in->inPublic.t.publicArea,
   2955 49                                  &in->inSensitive.t.sensitive, &sensitive);
   2956 50       if(result != TPM_RC_SUCCESS)
   2957 51           return result;
   2958 52
   2959 53       // Fill in creation data
   2960 54       FillInCreationData(in->parentHandle, in->inPublic.t.publicArea.nameAlg,
   2961 55                          &in->creationPCR, &in->outsideInfo,
   2962 56                          &out->creationData, &out->creationHash);
   2963 57
   2964 58       // Copy public area from input to output
   2965 59       out->outPublic.t.publicArea = in->inPublic.t.publicArea;
   2966 60
   2967 61       // Compute name from public area
   2968 62       ObjectComputeName(&(out->outPublic.t.publicArea), &name);
   2969 63
   2970 64       // Compute creation ticket
   2971 65       TicketComputeCreation(EntityGetHierarchy(in->parentHandle), &name,
   2972 66                             &out->creationHash, &out->creationTicket);
   2973 67
   2974 68       // Prepare output private data from sensitive
   2975 69       SensitiveToPrivate(&sensitive, &name, in->parentHandle,
   2976 70                          out->outPublic.t.publicArea.nameAlg,
   2977 71                          &out->outPrivate);
   2978 72
   2979 73       return TPM_RC_SUCCESS;
   2980 74   }
   2981 75   #endif // CC_Create
   2982 
   2983 
   2984 
   2985 
   2986      Family 2.0                           TCG Published                                   Page 53
   2987      Level 00 Revision 01.16           Copyright  TCG 2006-2014                    October 30, 2014
   2988 Part 3: Commands                                                                    Trusted Platform Module Library
   2990 
   2991 
   2992 12.2     TPM2_Load
   2993 
   2994 12.2.1 General Description
   2995 
   2996 This command is used to load objects into the TPM. This command is used when both a TPM2B_PUBLIC
   2997 and TPM2B_PRIVATE are to be loaded. If only a TPM2B_PUBLIC is to be loaded, the
   2998 TPM2_LoadExternal command is used.
   2999 
   3000 NOTE 1            Loading an object is not the same as restoring a saved object context.
   3001 
   3002 The objects TPMA_OBJECT attributes will be checked according to the rules defined in
   3003 TPMA_OBJECT in TPM 2.0 Part 2 of this specification.
   3004 Objects loaded using this command will have a Name. The Name is the concatenation of nameAlg and
   3005 the digest of the public area using the nameAlg.
   3006 
   3007 NOTE 2            nameAlg is a parameter in the public area of the inPublic structure.
   3008 
   3009 If inPrivate.size is zero, the load will fail.
   3010 After inPrivate.buffer is decrypted using the symmetric key of the parent, the integrity value shall be
   3011 checked before the sensitive area is used, or unmarshaled.
   3012 
   3013 NOTE 3            Checking the integrity before the data is used prevents attacks on the sensitive area by fuzzing the
   3014                   data and looking at the differences in the response codes.
   3015 
   3016 The command returns a handle for the loaded object and the Name that the TPM computed for
   3017 inPublic.public (that is, the digest of the TPMT_PUBLIC structure in inPublic).
   3018 
   3019 NOTE 4            The TPM-computed Name is provided as a convenience to the caller for those cases where the
   3020                   caller does not implement the hash algorithms specified in the nameAlg of the object.
   3021 
   3022 NOTE 5            The returned handle is associated with the object until the object is flushed (TPM2_FlushContext) o r
   3023                   until the next TPM2_Startup.
   3024 
   3025 For all objects, the size of the key in the sensitive area shall be consistent with the key size indicated in
   3026 the public area or the TPM shall return TPM_RC_KEY_SIZE.
   3027 Before use, a loaded object shall be checked to validate that the public and sensitive portions are
   3028 properly linked, cryptographically. Use of an object includes use in any policy command. If the parts of the
   3029 object are not properly linked, the TPM shall return TPM_RC_BINDING.
   3030 
   3031 EXAMPLE 1         For a symmetric object, the unique value in the public area shall be the digest of the sensitive key
   3032                   and the obfuscation value.
   3033 
   3034 EXAMPLE 2         For a two-prime RSA key, the remainder when dividing the public modulus by the private key shall
   3035                   be zero and it shall be possible to form a priv ate exponent from the two prime factors of the public
   3036                   modulus.
   3037 
   3038 EXAMPLE 3         For an ECC key, the public point shall be f(x) where x is the private key.
   3039 
   3040 
   3041 
   3042 
   3043 Page 54                                           TCG Published                                         Family 2.0
   3044 October 30, 2014                          Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   3045 Trusted Platform Module Library                                                         Part 3: Commands
   3047 
   3048 
   3049 12.2.2 Command and Response
   3050 
   3051                                     Table 21  TPM2_Load Command
   3052 Type                          Name                  Description
   3053 
   3054 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   3055 UINT32                        commandSize
   3056 TPM_CC                        commandCode           TPM_CC_Load
   3057 
   3058                                                     TPM handle of parent key; shall not be a reserved
   3059                                                     handle
   3060 TPMI_DH_OBJECT                @parentHandle
   3061                                                     Auth Index: 1
   3062                                                     Auth Role: USER
   3063 
   3064 TPM2B_PRIVATE                 inPrivate             the private portion of the object
   3065 TPM2B_PUBLIC                  inPublic              the public portion of the object
   3066 
   3067 
   3068                                     Table 22  TPM2_Load Response
   3069 Type                          Name                  Description
   3070 
   3071 TPM_ST                        tag                   see clause 6
   3072 UINT32                        responseSize
   3073 TPM_RC                        responseCode
   3074 
   3075                                                     handle of type TPM_HT_TRANSIENT for the loaded
   3076 TPM_HANDLE                    objectHandle
   3077                                                     object
   3078 
   3079 TPM2B_NAME                    name                  Name of the loaded object
   3080 
   3081 
   3082 
   3083 
   3084 Family 2.0                                 TCG Published                                        Page 55
   3085 Level 00 Revision 01.16              Copyright  TCG 2006-2014                          October 30, 2014
   3086      Part 3: Commands                                                            Trusted Platform Module Library
   3088 
   3089 
   3090 
   3091      12.2.3 Detailed Actions
   3092 
   3093 1    #include "InternalRoutines.h"
   3094 2    #include "Load_fp.h"
   3095 3    #ifdef TPM_CC_Load // Conditional expansion of this file
   3096 4    #include "Object_spt_fp.h"
   3097 
   3098 
   3099      Error Returns               Meaning
   3100 
   3101      TPM_RC_ASYMMETRIC           storage key with different asymmetric type than parent
   3102      TPM_RC_ATTRIBUTES           inPulblic attributes are not allowed with selected parent
   3103      TPM_RC_BINDING              inPrivate and inPublic are not cryptographically bound
   3104      TPM_RC_HASH                 incorrect hash selection for signing key
   3105      TPM_RC_INTEGRITY            HMAC on inPrivate was not valid
   3106      TPM_RC_KDF                  KDF selection not allowed
   3107      TPM_RC_KEY                  the size of the object's unique field is not consistent with the indicated
   3108                                  size in the object's parameters
   3109      TPM_RC_OBJECT_MEMORY        no available object slot
   3110      TPM_RC_SCHEME               the signing scheme is not valid for the key
   3111      TPM_RC_SENSITIVE            the inPrivate did not unmarshal correctly
   3112      TPM_RC_SIZE                 inPrivate missing, or authPolicy size for inPublic or is not valid
   3113      TPM_RC_SYMMETRIC            symmetric algorithm not provided when required
   3114      TPM_RC_TYPE                 parentHandle is not a storage key, or the object to load is a storage
   3115                                  key but its parameters do not match the parameters of the parent.
   3116      TPM_RC_VALUE                decryption failure
   3117 
   3118  5   TPM_RC
   3119  6   TPM2_Load(
   3120  7       Load_In         *in,             // IN: input parameter list
   3121  8       Load_Out        *out             // OUT: output parameter list
   3122  9       )
   3123 10   {
   3124 11       TPM_RC                  result = TPM_RC_SUCCESS;
   3125 12       TPMT_SENSITIVE          sensitive;
   3126 13       TPMI_RH_HIERARCHY       hierarchy;
   3127 14       OBJECT                 *parentObject = NULL;
   3128 15       BOOL                    skipChecks = FALSE;
   3129 16
   3130 17   // Input Validation
   3131 18       if(in->inPrivate.t.size == 0)
   3132 19           return TPM_RC_SIZE + RC_Load_inPrivate;
   3133 20
   3134 21       parentObject = ObjectGet(in->parentHandle);
   3135 22       // Is the object that is being used as the parent actually a parent.
   3136 23       if(!AreAttributesForParent(parentObject))
   3137 24           return TPM_RC_TYPE + RC_Load_parentHandle;
   3138 25
   3139 26       // If the parent is fixedTPM, then the attributes of the object
   3140 27       // are either "correct by construction" or were validated
   3141 28       // when the object was imported. If they pass the integrity
   3142 29       // check, then the values are valid
   3143 30       if(parentObject->publicArea.objectAttributes.fixedTPM)
   3144 31           skipChecks = TRUE;
   3145 32       else
   3146 
   3147      Page 56                                  TCG Published                                             Family 2.0
   3148      October 30, 2014                 Copyright  TCG 2006-2014                         Level 00 Revision 01.16
   3149      Trusted Platform Module Library                                             Part 3: Commands
   3151 
   3152 33       {
   3153 34           // If parent doesn't have fixedTPM SET, then this can't have
   3154 35           // fixedTPM SET.
   3155 36           if(in->inPublic.t.publicArea.objectAttributes.fixedTPM == SET)
   3156 37               return TPM_RC_ATTRIBUTES + RC_Load_inPublic;
   3157 38
   3158 39           // Perform self check on input public area. A TPM_RC_SIZE, TPM_RC_SCHEME,
   3159 40           // TPM_RC_VALUE, TPM_RC_SYMMETRIC, TPM_RC_TYPE, TPM_RC_HASH,
   3160 41           // TPM_RC_ASYMMETRIC, TPM_RC_ATTRIBUTES or TPM_RC_KDF error may be returned
   3161 42           // at this point
   3162 43           result = PublicAttributesValidation(TRUE, in->parentHandle,
   3163 44                                               &in->inPublic.t.publicArea);
   3164 45           if(result != TPM_RC_SUCCESS)
   3165 46               return RcSafeAddToResult(result, RC_Load_inPublic);
   3166 47       }
   3167 48
   3168 49       // Compute the name of object
   3169 50       ObjectComputeName(&in->inPublic.t.publicArea, &out->name);
   3170 51
   3171 52       // Retrieve sensitive data. PrivateToSensitive() may return TPM_RC_INTEGRITY or
   3172 53       // TPM_RC_SENSITIVE
   3173 54       // errors may be returned at this point
   3174 55       result = PrivateToSensitive(&in->inPrivate, &out->name, in->parentHandle,
   3175 56                                   in->inPublic.t.publicArea.nameAlg,
   3176 57                                   &sensitive);
   3177 58       if(result != TPM_RC_SUCCESS)
   3178 59           return RcSafeAddToResult(result, RC_Load_inPrivate);
   3179 60
   3180 61   // Internal Data Update
   3181 62
   3182 63       // Get hierarchy of parent
   3183 64       hierarchy = ObjectGetHierarchy(in->parentHandle);
   3184 65
   3185 66       // Create internal object. A lot of different errors may be returned by this
   3186 67       // loading operation as it will do several validations, including the public
   3187 68       // binding check
   3188 69       result = ObjectLoad(hierarchy, &in->inPublic.t.publicArea, &sensitive,
   3189 70                           &out->name, in->parentHandle, skipChecks,
   3190 71                           &out->objectHandle);
   3191 72
   3192 73       if(result != TPM_RC_SUCCESS)
   3193 74           return result;
   3194 75
   3195 76       return TPM_RC_SUCCESS;
   3196 77   }
   3197 78   #endif // CC_Load
   3198 
   3199 
   3200 
   3201 
   3202      Family 2.0                            TCG Published                                 Page 57
   3203      Level 00 Revision 01.16            Copyright  TCG 2006-2014                October 30, 2014
   3204 Part 3: Commands                                                                  Trusted Platform Module Library
   3206 
   3207 
   3208 12.3     TPM2_LoadExternal
   3209 
   3210 12.3.1 General Description
   3211 
   3212 This command is used to load an object that is not a Protected Object into the TPM. The command allows
   3213 loading of a public area or both a public and sensitive area.
   3214 
   3215 NOTE 1          Typical use for loading a public area is to allow the TPM to validate an asymmetric signature.
   3216                 Typical use for loading both a public and sensitive area is to allow the TPM to be used as a crypto
   3217                 accelerator.
   3218 
   3219 Load of a public external object area allows the object be associated with a hierarchy so that the correct
   3220 algorithms may be used when creating tickets. The hierarchy parameter provides this association. If the
   3221 public and sensitive portions of the object are loaded, hierarchy is required to be TPM_RH_NULL.
   3222 
   3223 NOTE 2          If both the public and private portions of an object are loaded, the object is not allowed to appear to
   3224                 be part of a hierarchy.
   3225 
   3226 The objects TPMA_OBJECT attributes will be checked according to the rules defined in
   3227 TPMA_OBJECT in TPM 2.0 Part 2. In particular, fixedTPM, fixedParent, and restricted shall be CLEAR
   3228 if inPrivate is not the Empty Buffer.
   3229 
   3230 NOTE 3          The duplication status of a public key needs to be able to be the same as the full key which may be
   3231                 resident on a different TPM. If both the public and private parts of the key are loaded , then it is not
   3232                 possible for the key to be either fixedTPM or fixedParent, since, its private area would not be
   3233                 available in the clear to load.
   3234 
   3235 Objects loaded using this command will have a Name. The Name is the nameAlg of the object
   3236 concatenated with the digest of the public area using the nameAlg. The Qualified Name for the object will
   3237 be the same as its Name. The TPM will validate that the authPolicy is either the size of the digest
   3238 produced by nameAlg or the Empty Buffer.
   3239 
   3240 NOTE 4          If nameAlg is TPM_ALG_NULL, then the Name is the Empty Buffer. When the authorization value for
   3241                 an object with no Name is computed, no Name value is included in the HMAC. To ensure that these
   3242                 unnamed entities are not substituted, they should have an authValue that is statistically unique.
   3243 
   3244 NOTE 5          The digest size for TPM_ALG_NULL is zero.
   3245 
   3246 If the nameAlg is TPM_ALG_NULL, the TPM shall not verify the cryptographic binding between the public
   3247 and sensitive areas, but the TPM will validate that the size of the key in the sensitive area is consistent
   3248 with the size indicated in the public area. If it is not, the TPM shall return TPM_RC_KEY_SIZE.
   3249 
   3250 NOTE 6          For an ECC object, the TPM will verify that the public key is on the curve of the key before the public
   3251                 area is used.
   3252 
   3253 If nameAlg is not TPM_ALG_NULL, then the same consistency checks between inPublic and inPrivate
   3254 are made as for TPM2_Load().
   3255 
   3256 NOTE 7          Consistency checks are necessary because an object with a Name needs to have the public and
   3257                 sensitive portions cryptographically bound so that an attacker cannot mix pubic and sensitive areas.
   3258 
   3259 The command returns a handle for the loaded object and the Name that the TPM computed for
   3260 inPublic.public (that is, the TPMT_PUBLIC structure in inPublic).
   3261 
   3262 NOTE 8          The TPM-computed Name is provided as a convenience to the caller for those cases where the
   3263                 caller does not implement the hash algorithm specified in the nameAlg of the object.
   3264 
   3265 
   3266 
   3267 
   3268 Page 58                                         TCG Published                                           Family 2.0
   3269 October 30, 2014                       Copyright  TCG 2006-2014                         Level 00 Revision 01.16
   3270 Trusted Platform Module Library                                                           Part 3: Commands
   3272 
   3273 The hierarchy parameter associates the external object with a hierarchy. External objects are flushed
   3274 when their associated hierarchy is disabled. If hierarchy is TPM_RH_NULL, the object is part of no
   3275 hierarchy, and there is no implicit flush.
   3276 If hierarchy is TPM_RH_NULL or nameAlg is TPM_ALG_NULL, a ticket produced using the object shall
   3277 be a NULL Ticket.
   3278 
   3279 EXAMPLE        If a key is loaded with hierarchy set to TPM_RH_NULL, then TPM2_VerifySignature() will produce a
   3280                NULL Ticket of the required type.
   3281 
   3282 External objects are Temporary Objects. The saved external object contexts shall be invalidated at the
   3283 next TPM Reset.
   3284 
   3285 
   3286 
   3287 
   3288 Family 2.0                                 TCG Published                                           Page 59
   3289 Level 00 Revision 01.16              Copyright  TCG 2006-2014                            October 30, 2014
   3290 Part 3: Commands                                                   Trusted Platform Module Library
   3292 
   3293 
   3294 
   3295 12.3.2 Command and Response
   3296 
   3297                       Table 23  TPM2_LoadExternal Command
   3298 Type                   Name                  Description
   3299 
   3300                                              TPM_ST_SESSIONS if an audit, encrypt, or derypt
   3301 TPMI_ST_COMMAND_TAG    tag                   session is present; otherwise,
   3302                                              TPM_ST_NO_SESSIONS
   3303 UINT32                 commandSize
   3304 TPM_CC                 commandCode           TPM_CC_LoadExternal
   3305 
   3306 TPM2B_SENSITIVE        inPrivate             the sensitive portion of the object (optional)
   3307 TPM2B_PUBLIC+          inPublic              the public portion of the object
   3308 TPMI_RH_HIERARCHY+     hierarchy             hierarchy with which the object area is associated
   3309 
   3310 
   3311                       Table 24  TPM2_LoadExternal Response
   3312 Type                   Name                  Description
   3313 
   3314 TPM_ST                 tag                   see clause 6
   3315 UINT32                 responseSize
   3316 TPM_RC                 responseCode
   3317 
   3318                                              handle of type TPM_HT_TRANSIENT for the loaded
   3319 TPM_HANDLE             objectHandle
   3320                                              object
   3321 
   3322 TPM2B_NAME             name                  name of the loaded object
   3323 
   3324 
   3325 
   3326 
   3327 Page 60                               TCG Published                                       Family 2.0
   3328 October 30, 2014              Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   3329      Trusted Platform Module Library                                                                   Part 3: Commands
   3331 
   3332 
   3333 
   3334      12.3.3 Detailed Actions
   3335 
   3336 1    #include "InternalRoutines.h"
   3337 2    #include "LoadExternal_fp.h"
   3338 3    #ifdef TPM_CC_LoadExternal // Conditional expansion of this file
   3339 4    #include "Object_spt_fp.h"
   3340 
   3341 
   3342      Error Returns                     Meaning
   3343 
   3344      TPM_RC_ATTRIBUTES                 'fixedParent" and fixedTPM must be CLEAR on on an external key if
   3345                                        both public and sensitive portions are loaded
   3346      TPM_RC_BINDING                    the inPublic and inPrivate structures are not cryptographically bound.
   3347      TPM_RC_HASH                       incorrect hash selection for signing key
   3348      TPM_RC_HIERARCHY                  hierarchy is turned off, or only NULL hierarchy is allowed when
   3349                                        loading public and private parts of an object
   3350      TPM_RC_KDF                        incorrect KDF selection for decrypting keyedHash object
   3351      TPM_RC_KEY                        the size of the object's unique field is not consistent with the indicated
   3352                                        size in the object's parameters
   3353      TPM_RC_OBJECT_MEMORY              if there is no free slot for an object
   3354      TPM_RC_SCHEME                     the signing scheme is not valid for the key
   3355      TPM_RC_SIZE                       authPolicy is not zero and is not the size of a digest produced by the
   3356                                        object's nameAlg TPM_RH_NULL hierarchy
   3357      TPM_RC_SYMMETRIC                  symmetric algorithm not provided when required
   3358      TPM_RC_TYPE                       inPublic and inPrivate are not the same type
   3359 
   3360  5   TPM_RC
   3361  6   TPM2_LoadExternal(
   3362  7       LoadExternal_In       *in,                   // IN: input parameter list
   3363  8       LoadExternal_Out      *out                   // OUT: output parameter list
   3364  9       )
   3365 10   {
   3366 11       TPM_RC                 result;
   3367 12       TPMT_SENSITIVE        *sensitive;
   3368 13       BOOL                   skipChecks;
   3369 14
   3370 15   // Input Validation
   3371 16
   3372 17       // If the target hierarchy is turned off, the object can not be loaded.
   3373 18       if(!HierarchyIsEnabled(in->hierarchy))
   3374 19           return TPM_RC_HIERARCHY + RC_LoadExternal_hierarchy;
   3375 20
   3376 21       // the size of authPolicy is either 0 or the digest size of nameAlg
   3377 22       if(in->inPublic.t.publicArea.authPolicy.t.size != 0
   3378 23               && in->inPublic.t.publicArea.authPolicy.t.size !=
   3379 24               CryptGetHashDigestSize(in->inPublic.t.publicArea.nameAlg))
   3380 25           return TPM_RC_SIZE + RC_LoadExternal_inPublic;
   3381 26
   3382 27       // For loading an object with both public and sensitive
   3383 28       if(in->inPrivate.t.size != 0)
   3384 29       {
   3385 30           // An external object can only be loaded at TPM_RH_NULL hierarchy
   3386 31           if(in->hierarchy != TPM_RH_NULL)
   3387 32               return TPM_RC_HIERARCHY + RC_LoadExternal_hierarchy;
   3388 33           // An external object with a sensitive area must have fixedTPM == CLEAR
   3389 34           // fixedParent == CLEAR, and must have restrict CLEAR so that it does not
   3390 35           // appear to be a key that was created by this TPM.
   3391 
   3392      Family 2.0                                    TCG Published                                                  Page 61
   3393      Level 00 Revision 01.16                Copyright  TCG 2006-2014                                  October 30, 2014
   3394      Part 3: Commands                                                  Trusted Platform Module Library
   3396 
   3397 36             if(   in->inPublic.t.publicArea.objectAttributes.fixedTPM != CLEAR
   3398 37                || in->inPublic.t.publicArea.objectAttributes.fixedParent != CLEAR
   3399 38                || in->inPublic.t.publicArea.objectAttributes.restricted != CLEAR
   3400 39               )
   3401 40                 return TPM_RC_ATTRIBUTES + RC_LoadExternal_inPublic;
   3402 41       }
   3403 42
   3404 43       // Validate the scheme parameters
   3405 44       result = SchemeChecks(TRUE, TPM_RH_NULL, &in->inPublic.t.publicArea);
   3406 45       if(result != TPM_RC_SUCCESS)
   3407 46               return RcSafeAddToResult(result, RC_LoadExternal_inPublic);
   3408 47
   3409 48   // Internal Data Update
   3410 49       // Need the name to compute the qualified name
   3411 50       ObjectComputeName(&in->inPublic.t.publicArea, &out->name);
   3412 51       skipChecks = (in->inPublic.t.publicArea.nameAlg == TPM_ALG_NULL);
   3413 52
   3414 53       // If a sensitive area was provided, load it
   3415 54       if(in->inPrivate.t.size != 0)
   3416 55           sensitive = &in->inPrivate.t.sensitiveArea;
   3417 56       else
   3418 57           sensitive = NULL;
   3419 58
   3420 59       // Create external object. A TPM_RC_BINDING, TPM_RC_KEY, TPM_RC_OBJECT_MEMORY
   3421 60       // or TPM_RC_TYPE error may be returned by ObjectLoad()
   3422 61       result = ObjectLoad(in->hierarchy, &in->inPublic.t.publicArea,
   3423 62                           sensitive, &out->name, TPM_RH_NULL, skipChecks,
   3424 63                           &out->objectHandle);
   3425 64       return result;
   3426 65   }
   3427 66   #endif // CC_LoadExternal
   3428 
   3429 
   3430 
   3431 
   3432      Page 62                                  TCG Published                              Family 2.0
   3433      October 30, 2014                  Copyright  TCG 2006-2014             Level 00 Revision 01.16
   3434 Trusted Platform Module Library                                                                Part 3: Commands
   3436 
   3437 
   3438 12.4   TPM2_ReadPublic
   3439 
   3440 12.4.1 General Description
   3441 
   3442 This command allows access to the public area of a loaded object.
   3443 Use of the objectHandle does not require authorization.
   3444 
   3445 NOTE            Since the caller is not likely to know the public area of the object associated with objectHandle, it
   3446                 would not be possible to include the Name associated with objectHandle in the cpHash computation.
   3447 
   3448 If objectHandle references a sequence object, the TPM shall return TPM_RC_SEQUENCE.
   3449 
   3450 
   3451 
   3452 
   3453 Family 2.0                                   TCG Published                                              Page 63
   3454 Level 00 Revision 01.16                Copyright  TCG 2006-2014                               October 30, 2014
   3455 Part 3: Commands                                                  Trusted Platform Module Library
   3457 
   3458 
   3459 
   3460 12.4.2 Command and Response
   3461 
   3462                       Table 25  TPM2_ReadPublic Command
   3463 Type                   Name                  Description
   3464 
   3465                                              TPM_ST_SESSIONS if an audit or encrypt session is
   3466 TPMI_ST_COMMAND_TAG    tag
   3467                                              present; otherwise, TPM_ST_NO_SESSIONS
   3468 UINT32                 commandSize
   3469 TPM_CC                 commandCode           TPM_CC_ReadPublic
   3470 
   3471                                              TPM handle of an object
   3472 TPMI_DH_OBJECT         objectHandle
   3473                                              Auth Index: None
   3474 
   3475 
   3476                       Table 26  TPM2_ReadPublic Response
   3477 Type                   Name                  Description
   3478 
   3479 TPM_ST                 tag                   see clause 6
   3480 UINT32                 responseSize
   3481 TPM_RC                 responseCode
   3482 
   3483 TPM2B_PUBLIC           outPublic             structure containing the public area of an object
   3484 TPM2B_NAME             name                  name of the object
   3485 TPM2B_NAME             qualifiedName         the Qualified Name of the object
   3486 
   3487 
   3488 
   3489 
   3490 Page 64                               TCG Published                                      Family 2.0
   3491 October 30, 2014              Copyright  TCG 2006-2014                  Level 00 Revision 01.16
   3492      Trusted Platform Module Library                                                       Part 3: Commands
   3494 
   3495 
   3496 
   3497      12.4.3 Detailed Actions
   3498 
   3499 1    #include "InternalRoutines.h"
   3500 2    #include "ReadPublic_fp.h"
   3501 3    #ifdef TPM_CC_ReadPublic // Conditional expansion of this file
   3502 
   3503 
   3504      Error Returns                     Meaning
   3505 
   3506      TPM_RC_SEQUENCE                   can not read the public area of a sequence object
   3507 
   3508  4   TPM_RC
   3509  5   TPM2_ReadPublic(
   3510  6       ReadPublic_In     *in,                // IN: input parameter list
   3511  7       ReadPublic_Out    *out                // OUT: output parameter list
   3512  8       )
   3513  9   {
   3514 10       OBJECT                    *object;
   3515 11
   3516 12   // Input Validation
   3517 13
   3518 14       // Get loaded object pointer
   3519 15       object = ObjectGet(in->objectHandle);
   3520 16
   3521 17       // Can not read public area of a sequence object
   3522 18       if(ObjectIsSequence(object))
   3523 19           return TPM_RC_SEQUENCE;
   3524 20
   3525 21   // Command Output
   3526 22
   3527 23       // Compute size of public area in canonical form
   3528 24       out->outPublic.t.size = TPMT_PUBLIC_Marshal(&object->publicArea, NULL, NULL);
   3529 25
   3530 26       // Copy public area to output
   3531 27       out->outPublic.t.publicArea = object->publicArea;
   3532 28
   3533 29       // Copy name to output
   3534 30       out->name.t.size = ObjectGetName(in->objectHandle, &out->name.t.name);
   3535 31
   3536 32       // Copy qualified name to output
   3537 33       ObjectGetQualifiedName(in->objectHandle, &out->qualifiedName);
   3538 34
   3539 35       return TPM_RC_SUCCESS;
   3540 36   }
   3541 37   #endif // CC_ReadPublic
   3542 
   3543 
   3544 
   3545 
   3546      Family 2.0                                  TCG Published                                   Page 65
   3547      Level 00 Revision 01.16               Copyright  TCG 2006-2014                       October 30, 2014
   3548 Part 3: Commands                                                           Trusted Platform Module Library
   3550 
   3551 
   3552 12.5   TPM2_ActivateCredential
   3553 
   3554 12.5.1 General Description
   3555 
   3556 This command enables the association of a credential with an object in a way that ensures that the TPM
   3557 has validated the parameters of the credentialed object.
   3558 If both the public and private portions of activateHandle and keyHandle are not loaded, then the TPM
   3559 shall return TPM_RC_AUTH_UNAVAILABLE.
   3560 If keyHandle is not a Storage Key, then the TPM shall return TPM_RC_TYPE.
   3561 Authorization for activateHandle requires the ADMIN role.
   3562 The key associated with keyHandle is used to recover a seed from secret, which is the encrypted seed.
   3563 The Name of the object associated with activateHandle and the recovered seed are used in a KDF to
   3564 recover the symmetric key. The recovered seed (but not the Name) is used in a KDF to recover the
   3565 HMAC key.
   3566 The HMAC is used to validate that the credentialBlob is associated with activateHandle and that the data
   3567 in credentialBlob has not been modified. The linkage to the object associated with activateHandle is
   3568 achieved by including the Name in the HMAC calculation.
   3569 If the integrity checks succeed, credentialBlob is decrypted and returned as certInfo.
   3570 
   3571 
   3572 
   3573 
   3574 Page 66                                      TCG Published                                   Family 2.0
   3575 October 30, 2014                     Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   3576 Trusted Platform Module Library                                                            Part 3: Commands
   3578 
   3579 
   3580 
   3581 12.5.2 Command and Response
   3582 
   3583                           Table 27  TPM2_ActivateCredential Command
   3584 Type                              Name               Description
   3585 
   3586 TPMI_ST_COMMAND_TAG               tag                TPM_ST_SESSIONS
   3587 UINT32                            commandSize
   3588 TPM_CC                            commandCode        TPM_CC_ActivateCredential
   3589 
   3590                                                      handle of the object associated with certificate in
   3591                                                      credentialBlob
   3592 TPMI_DH_OBJECT                    @activateHandle
   3593                                                      Auth Index: 1
   3594                                                      Auth Role: ADMIN
   3595                                                      loaded key used to decrypt the TPMS_SENSITIVE in
   3596                                                      credentialBlob
   3597 TPMI_DH_OBJECT                    @keyHandle
   3598                                                      Auth Index: 2
   3599                                                      Auth Role: USER
   3600 
   3601 TPM2B_ID_OBJECT                   credentialBlob     the credential
   3602                                                      keyHandle algorithm-dependent encrypted seed that
   3603 TPM2B_ENCRYPTED_SECRET            secret
   3604                                                      protects credentialBlob
   3605 
   3606 
   3607                           Table 28  TPM2_ActivateCredential Response
   3608 Type                          Name                   Description
   3609 
   3610 TPM_ST                        tag                    see clause 6
   3611 UINT32                        responseSize
   3612 TPM_RC                        responseCode
   3613 
   3614                                                      the decrypted certificate information
   3615 TPM2B_DIGEST                  certInfo               the data should be no larger than the size of the digest
   3616                                                      of the nameAlg associated with keyHandle
   3617 
   3618 
   3619 
   3620 
   3621 Family 2.0                                 TCG Published                                            Page 67
   3622 Level 00 Revision 01.16                 Copyright  TCG 2006-2014                          October 30, 2014
   3623      Part 3: Commands                                                           Trusted Platform Module Library
   3625 
   3626 
   3627 
   3628      12.5.3 Detailed Actions
   3629 
   3630 1    #include "InternalRoutines.h"
   3631 2    #include "ActivateCredential_fp.h"
   3632 3    #ifdef TPM_CC_ActivateCredential // Conditional expansion of this file
   3633 4    #include "Object_spt_fp.h"
   3634 
   3635 
   3636      Error Returns                Meaning
   3637 
   3638      TPM_RC_ATTRIBUTES            keyHandle does not reference a decryption key
   3639      TPM_RC_ECC_POINT             secret is invalid (when keyHandle is an ECC key)
   3640      TPM_RC_INSUFFICIENT          secret is invalid (when keyHandle is an ECC key)
   3641      TPM_RC_INTEGRITY             credentialBlob fails integrity test
   3642      TPM_RC_NO_RESULT             secret is invalid (when keyHandle is an ECC key)
   3643      TPM_RC_SIZE                  secret size is invalid or the credentialBlob does not unmarshal
   3644                                   correctly
   3645      TPM_RC_TYPE                  keyHandle does not reference an asymmetric key.
   3646      TPM_RC_VALUE                 secret is invalid (when keyHandle is an RSA key)
   3647 
   3648  5   TPM_RC
   3649  6   TPM2_ActivateCredential(
   3650  7       ActivateCredential_In    *in,                 // IN: input parameter list
   3651  8       ActivateCredential_Out   *out                 // OUT: output parameter list
   3652  9       )
   3653 10   {
   3654 11       TPM_RC                        result = TPM_RC_SUCCESS;
   3655 12       OBJECT                       *object;        // decrypt key
   3656 13       OBJECT                       *activateObject;// key associated with
   3657 14       // credential
   3658 15       TPM2B_DATA                      data;              // credential data
   3659 16
   3660 17   // Input Validation
   3661 18
   3662 19       // Get decrypt key pointer
   3663 20       object = ObjectGet(in->keyHandle);
   3664 21
   3665 22       // Get certificated object pointer
   3666 23       activateObject = ObjectGet(in->activateHandle);
   3667 24
   3668 25       // input decrypt key must be an asymmetric, restricted decryption key
   3669 26       if(   !CryptIsAsymAlgorithm(object->publicArea.type)
   3670 27          || object->publicArea.objectAttributes.decrypt == CLEAR
   3671 28          || object->publicArea.objectAttributes.restricted == CLEAR)
   3672 29           return TPM_RC_TYPE + RC_ActivateCredential_keyHandle;
   3673 30
   3674 31   // Command output
   3675 32
   3676 33       // Decrypt input credential data via asymmetric decryption. A
   3677 34       // TPM_RC_VALUE, TPM_RC_KEY or unmarshal errors may be returned at this
   3678 35       // point
   3679 36       result = CryptSecretDecrypt(in->keyHandle, NULL,
   3680 37                                   "IDENTITY", &in->secret, &data);
   3681 38       if(result != TPM_RC_SUCCESS)
   3682 39       {
   3683 40           if(result == TPM_RC_KEY)
   3684 41               return TPM_RC_FAILURE;
   3685 42           return RcSafeAddToResult(result, RC_ActivateCredential_secret);
   3686 43       }
   3687 
   3688      Page 68                                     TCG Published                                      Family 2.0
   3689      October 30, 2014                    Copyright  TCG 2006-2014                     Level 00 Revision 01.16
   3690      Trusted Platform Module Library                                             Part 3: Commands
   3692 
   3693 44
   3694 45       // Retrieve secret data. A TPM_RC_INTEGRITY error or unmarshal
   3695 46       // errors may be returned at this point
   3696 47       result = CredentialToSecret(&in->credentialBlob,
   3697 48                                   &activateObject->name,
   3698 49                                   (TPM2B_SEED *) &data,
   3699 50                                   in->keyHandle,
   3700 51                                   &out->certInfo);
   3701 52       if(result != TPM_RC_SUCCESS)
   3702 53           return RcSafeAddToResult(result,RC_ActivateCredential_credentialBlob);
   3703 54
   3704 55       return TPM_RC_SUCCESS;
   3705 56   }
   3706 57   #endif // CC_ActivateCredential
   3707 
   3708 
   3709 
   3710 
   3711      Family 2.0                           TCG Published                                Page 69
   3712      Level 00 Revision 01.16           Copyright  TCG 2006-2014                 October 30, 2014
   3713 Part 3: Commands                                                         Trusted Platform Module Library
   3715 
   3716 
   3717 12.6   TPM2_MakeCredential
   3718 
   3719 12.6.1 General Description
   3720 
   3721 This command allows the TPM to perform the actions required of a Certificate Authority (CA) in creating a
   3722 TPM2B_ID_OBJECT containing an activation credential.
   3723 The TPM will produce a TPM_ID_OBJECT according to the methods in Credential Protection in TPM
   3724 2.0 Part 1.
   3725 The loaded public area referenced by handle is required to be the public area of a Storage key,
   3726 otherwise, the credential cannot be properly sealed.
   3727 This command does not use any TPM secrets nor does it require authorization. It is a convenience
   3728 function, using the TPM to perform cryptographic calculations that could be done externally.
   3729 
   3730 
   3731 
   3732 
   3733 Page 70                                    TCG Published                                    Family 2.0
   3734 October 30, 2014                    Copyright  TCG 2006-2014                  Level 00 Revision 01.16
   3735 Trusted Platform Module Library                                                         Part 3: Commands
   3737 
   3738 
   3739 
   3740 12.6.2 Command and Response
   3741 
   3742                            Table 29  TPM2_MakeCredential Command
   3743 Type                          Name                  Description
   3744 
   3745                                                     TPM_ST_SESSIONS if an audit, encrypt, or decrypt
   3746 TPMI_ST_COMMAND_TAG           tag                   session is present; otherwise,
   3747                                                     TPM_ST_NO_SESSIONS
   3748 UINT32                        commandSize
   3749 TPM_CC                        commandCode           TPM_CC_MakeCredential
   3750 
   3751                                                     loaded public area, used to encrypt the sensitive area
   3752 TPMI_DH_OBJECT                handle                containing the credential key
   3753                                                     Auth Index: None
   3754 
   3755 TPM2B_DIGEST                  credential            the credential information
   3756 TPM2B_NAME                    objectName            Name of the object to which the credential applies
   3757 
   3758 
   3759                            Table 30  TPM2_MakeCredential Response
   3760 Type                          Name                  Description
   3761 
   3762 TPM_ST                        tag                   see clause 6
   3763 UINT32                        responseSize
   3764 TPM_RC                        responseCode
   3765 
   3766 TPM2B_ID_OBJECT               credentialBlob        the credential
   3767                                                     handle algorithm-dependent data that wraps the key
   3768 TPM2B_ENCRYPTED_SECRET secret
   3769                                                     that encrypts credentialBlob
   3770 
   3771 
   3772 
   3773 
   3774 Family 2.0                                 TCG Published                                         Page 71
   3775 Level 00 Revision 01.16             Copyright  TCG 2006-2014                           October 30, 2014
   3776      Part 3: Commands                                                              Trusted Platform Module Library
   3778 
   3779 
   3780 
   3781      12.6.3 Detailed Actions
   3782 
   3783 1    #include "InternalRoutines.h"
   3784 2    #include "MakeCredential_fp.h"
   3785 3    #ifdef TPM_CC_MakeCredential // Conditional expansion of this file
   3786 4    #include "Object_spt_fp.h"
   3787 
   3788 
   3789      Error Returns                   Meaning
   3790 
   3791      TPM_RC_KEY                      handle referenced an ECC key that has a unique field that is not a
   3792                                      point on the curve of the key
   3793      TPM_RC_SIZE                     credential is larger than the digest size of Name algorithm of handle
   3794      TPM_RC_TYPE                     handle does not reference an asymmetric decryption key
   3795 
   3796  5   TPM_RC
   3797  6   TPM2_MakeCredential(
   3798  7       MakeCredential_In    *in,                 // IN: input parameter list
   3799  8       MakeCredential_Out   *out                 // OUT: output parameter list
   3800  9       )
   3801 10   {
   3802 11       TPM_RC                    result = TPM_RC_SUCCESS;
   3803 12
   3804 13       OBJECT                    *object;
   3805 14       TPM2B_DATA                data;
   3806 15
   3807 16   // Input Validation
   3808 17
   3809 18       // Get object pointer
   3810 19       object = ObjectGet(in->handle);
   3811 20
   3812 21       // input key must be an asymmetric, restricted decryption key
   3813 22       // NOTE: Needs to be restricted to have a symmetric value.
   3814 23       if(   !CryptIsAsymAlgorithm(object->publicArea.type)
   3815 24          || object->publicArea.objectAttributes.decrypt == CLEAR
   3816 25          || object->publicArea.objectAttributes.restricted == CLEAR
   3817 26         )
   3818 27           return TPM_RC_TYPE + RC_MakeCredential_handle;
   3819 28
   3820 29       // The credential information may not be larger than the digest size used for
   3821 30       // the Name of the key associated with handle.
   3822 31       if(in->credential.t.size > CryptGetHashDigestSize(object->publicArea.nameAlg))
   3823 32           return TPM_RC_SIZE + RC_MakeCredential_credential;
   3824 33
   3825 34   // Command Output
   3826 35
   3827 36       // Make encrypt key and its associated secret structure.
   3828 37       // Even though CrypeSecretEncrypt() may return
   3829 38       out->secret.t.size = sizeof(out->secret.t.secret);
   3830 39       result = CryptSecretEncrypt(in->handle, "IDENTITY", &data, &out->secret);
   3831 40       if(result != TPM_RC_SUCCESS)
   3832 41           return result;
   3833 42
   3834 43       // Prepare output credential data from secret
   3835 44       SecretToCredential(&in->credential, &in->objectName, (TPM2B_SEED *) &data,
   3836 45                          in->handle, &out->credentialBlob);
   3837 46
   3838 47       return TPM_RC_SUCCESS;
   3839 48   }
   3840 49   #endif // CC_MakeCredential
   3841 
   3842 
   3843 
   3844 
   3845      Page 72                                      TCG Published                                           Family 2.0
   3846      October 30, 2014                    Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   3847 Trusted Platform Module Library                                                        Part 3: Commands
   3849 
   3850 
   3851 12.7   TPM2_Unseal
   3852 
   3853 12.7.1 General Description
   3854 
   3855 This command returns the data in a loaded Sealed Data Object.
   3856 
   3857 NOTE            A random, TPM-generated, Sealed Data Object may be created by the TPM with TPM2_Create() or
   3858                 TPM2_CreatePrimary() using the template for a Sealed Data Object.
   3859 
   3860 The returned value may be encrypted using authorization session encryption.
   3861 If either restricted, decrypt, or sign is SET in the attributes of itemHandle, then the TPM shall return
   3862 TPM_RC_ATTRIBUTES. If the type of itemHandle is not TPM_ALG_KEYEDHASH, then the TPM shall
   3863 return TPM_RC_TYPE.
   3864 
   3865 
   3866 
   3867 
   3868 Family 2.0                                TCG Published                                        Page 73
   3869 Level 00 Revision 01.16             Copyright  TCG 2006-2014                          October 30, 2014
   3870 Part 3: Commands                                                  Trusted Platform Module Library
   3872 
   3873 
   3874 
   3875 12.7.2 Command and Response
   3876 
   3877                         Table 31  TPM2_Unseal Command
   3878 Type                   Name                  Description
   3879 
   3880 TPMI_ST_COMMAND_TAG    tag                   TPM_ST_SESSIONS
   3881 UINT32                 commandSize
   3882 TPM_CC                 commandCode           TPM_CC_Unseal
   3883 
   3884                                              handle of a loaded data object
   3885 TPMI_DH_OBJECT         @itemHandle           Auth Index: 1
   3886                                              Auth Role: USER
   3887 
   3888 
   3889                          Table 32  TPM2_Unseal Response
   3890 Type                   Name                  Description
   3891 
   3892 TPM_ST                 tag                   see clause 6
   3893 UINT32                 responseSize
   3894 TPM_RC                 responseCode
   3895 
   3896                                              unsealed data
   3897 TPM2B_SENSITIVE_DATA   outData
   3898                                              Size of outData is limited to be no more than 128 octets.
   3899 
   3900 
   3901 
   3902 
   3903 Page 74                               TCG Published                                     Family 2.0
   3904 October 30, 2014             Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   3905      Trusted Platform Module Library                                               Part 3: Commands
   3907 
   3908 
   3909 
   3910      12.7.3 Detailed Actions
   3911 
   3912 1    #include "InternalRoutines.h"
   3913 2    #include "Unseal_fp.h"
   3914 3    #ifdef TPM_CC_Unseal // Conditional expansion of this file
   3915 
   3916 
   3917      Error Returns                     Meaning
   3918 
   3919      TPM_RC_ATTRIBUTES                 itemHandle has wrong attributes
   3920      TPM_RC_TYPE                       itemHandle is not a KEYEDHASH data object
   3921 
   3922  4   TPM_RC
   3923  5   TPM2_Unseal(
   3924  6       Unseal_In         *in,
   3925  7       Unseal_Out        *out
   3926  8       )
   3927  9   {
   3928 10       OBJECT                    *object;
   3929 11
   3930 12   // Input Validation
   3931 13
   3932 14       // Get pointer to loaded object
   3933 15       object = ObjectGet(in->itemHandle);
   3934 16
   3935 17       // Input handle must be a data object
   3936 18       if(object->publicArea.type != TPM_ALG_KEYEDHASH)
   3937 19           return TPM_RC_TYPE + RC_Unseal_itemHandle;
   3938 20       if(   object->publicArea.objectAttributes.decrypt == SET
   3939 21          || object->publicArea.objectAttributes.sign == SET
   3940 22          || object->publicArea.objectAttributes.restricted == SET)
   3941 23           return TPM_RC_ATTRIBUTES + RC_Unseal_itemHandle;
   3942 24
   3943 25   // Command Output
   3944 26
   3945 27       // Copy data
   3946 28       MemoryCopy2B(&out->outData.b, &object->sensitive.sensitive.bits.b,
   3947 29                    sizeof(out->outData.t.buffer));
   3948 30
   3949 31       return TPM_RC_SUCCESS;
   3950 32   }
   3951 33   #endif // CC_Unseal
   3952 
   3953 
   3954 
   3955 
   3956      Family 2.0                                  TCG Published                           Page 75
   3957      Level 00 Revision 01.16               Copyright  TCG 2006-2014               October 30, 2014
   3958 Part 3: Commands                                                                Trusted Platform Module Library
   3960 
   3961 
   3962 12.8     TPM2_ObjectChangeAuth
   3963 
   3964 12.8.1 General Description
   3965 
   3966 This command is used to change the authorization secret for a TPM-resident object.
   3967 If successful, a new private area for the TPM-resident object associated with objectHandle is returned,
   3968 which includes the new authorization value.
   3969 This command does not change the authorization of the TPM-resident object on which it operates.
   3970 Therefore, the old authValue (of the TPM-resident object) is used when generating the response HMAC
   3971 key if required.
   3972 
   3973 NOTE 1         The returned outPrivate will need to be loaded before the new authorization will apply.
   3974 
   3975 NOTE 2         The TPM-resident object may be persistent and changing the authorization value of the persistent
   3976                object could prevent other users from accessing the object. This is why this command does not
   3977                change the TPM-resident object.
   3978 
   3979 EXAMPLE        If a persistent key is being used as a Storage Root Key and the authorization of the key is a well -
   3980                known value so that the key can be used generally, then changing the authorization value in the
   3981                persistent key would deny access to other users.
   3982 
   3983 This command may not be used to change the authorization value for an NV Index or a Primary Object.
   3984 
   3985 NOTE 3         If an NV Index is to have a new authorization, it is done with TPM2_NV_ChangeAuth().
   3986 
   3987 NOTE 4         If a Primary Object is to have a new authorization, it needs to be recreated (TPM2_CreatePrimary()).
   3988 
   3989 
   3990 
   3991 
   3992 Page 76                                       TCG Published                                              Family 2.0
   3993 October 30, 2014                      Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   3994 Trusted Platform Module Library                                                         Part 3: Commands
   3996 
   3997 
   3998 12.8.2 Command and Response
   3999 
   4000                           Table 33  TPM2_ObjectChangeAuth Command
   4001 Type                          Name                  Description
   4002 
   4003 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   4004 UINT32                        commandSize
   4005 TPM_CC                        commandCode           TPM_CC_ObjectChangeAuth
   4006 
   4007                                                     handle of the object
   4008 TPMI_DH_OBJECT                @objectHandle         Auth Index: 1
   4009                                                     Auth Role: ADMIN
   4010                                                     handle of the parent
   4011 TPMI_DH_OBJECT                parentHandle
   4012                                                     Auth Index: None
   4013 
   4014 TPM2B_AUTH                    newAuth               new authorization value
   4015 
   4016 
   4017                           Table 34  TPM2_ObjectChangeAuth Response
   4018 Type                          Name                  Description
   4019 
   4020 TPM_ST                        tag                   see clause 6
   4021 UINT32                        responseSize
   4022 TPM_RC                        responseCode
   4023 
   4024 TPM2B_PRIVATE                 outPrivate            private area containing the new authorization value
   4025 
   4026 
   4027 
   4028 
   4029 Family 2.0                                 TCG Published                                         Page 77
   4030 Level 00 Revision 01.16             Copyright  TCG 2006-2014                           October 30, 2014
   4031      Part 3: Commands                                                          Trusted Platform Module Library
   4033 
   4034 
   4035 
   4036      12.8.3 Detailed Actions
   4037 
   4038 1    #include "InternalRoutines.h"
   4039 2    #include "ObjectChangeAuth_fp.h"
   4040 3    #ifdef TPM_CC_ObjectChangeAuth // Conditional expansion of this file
   4041 4    #include "Object_spt_fp.h"
   4042 
   4043 
   4044      Error Returns               Meaning
   4045 
   4046      TPM_RC_SIZE                 newAuth is larger than the size of the digest of the Name algorithm of
   4047                                  objectHandle
   4048      TPM_RC_TYPE                 the key referenced by parentHandle is not the parent of the object
   4049                                  referenced by objectHandle; or objectHandle is a sequence object.
   4050 
   4051  5   TPM_RC
   4052  6   TPM2_ObjectChangeAuth(
   4053  7       ObjectChangeAuth_In    *in,                // IN: input parameter list
   4054  8       ObjectChangeAuth_Out   *out                // OUT: output parameter list
   4055  9       )
   4056 10   {
   4057 11       TPMT_SENSITIVE          sensitive;
   4058 12
   4059 13       OBJECT                 *object;
   4060 14       TPM2B_NAME              objectQN, QNCompare;
   4061 15       TPM2B_NAME              parentQN;
   4062 16
   4063 17   // Input Validation
   4064 18
   4065 19       // Get object pointer
   4066 20       object = ObjectGet(in->objectHandle);
   4067 21
   4068 22       // Can not change auth on sequence object
   4069 23       if(ObjectIsSequence(object))
   4070 24           return TPM_RC_TYPE + RC_ObjectChangeAuth_objectHandle;
   4071 25
   4072 26       // Make sure that the auth value is consistent with the nameAlg
   4073 27       if( MemoryRemoveTrailingZeros(&in->newAuth)
   4074 28               > CryptGetHashDigestSize(object->publicArea.nameAlg))
   4075 29           return TPM_RC_SIZE + RC_ObjectChangeAuth_newAuth;
   4076 30
   4077 31       // Check parent for object
   4078 32       // parent handle must be the parent of object handle. In this
   4079 33       // implementation we verify this by checking the QN of object. Other
   4080 34       // implementation may choose different method to verify this attribute.
   4081 35       ObjectGetQualifiedName(in->parentHandle, &parentQN);
   4082 36       ObjectComputeQualifiedName(&parentQN, object->publicArea.nameAlg,
   4083 37                                  &object->name, &QNCompare);
   4084 38
   4085 39       ObjectGetQualifiedName(in->objectHandle, &objectQN);
   4086 40       if(!Memory2BEqual(&objectQN.b, &QNCompare.b))
   4087 41           return TPM_RC_TYPE + RC_ObjectChangeAuth_parentHandle;
   4088 42
   4089 43   // Command Output
   4090 44
   4091 45       // Copy internal sensitive area
   4092 46       sensitive = object->sensitive;
   4093 47       // Copy authValue
   4094 48       sensitive.authValue = in->newAuth;
   4095 49
   4096 50       // Prepare output private data from sensitive
   4097 51       SensitiveToPrivate(&sensitive, &object->name, in->parentHandle,
   4098 52                          object->publicArea.nameAlg,
   4099 
   4100      Page 78                                  TCG Published                                           Family 2.0
   4101      October 30, 2014                  Copyright  TCG 2006-2014                     Level 00 Revision 01.16
   4102      Trusted Platform Module Library                               Part 3: Commands
   4104 
   4105 53                           &out->outPrivate);
   4106 54
   4107 55       return TPM_RC_SUCCESS;
   4108 56   }
   4109 57   #endif // CC_ObjectChangeAuth
   4110 
   4111 
   4112 
   4113 
   4114      Family 2.0                            TCG Published                 Page 79
   4115      Level 00 Revision 01.16           Copyright  TCG 2006-2014   October 30, 2014
   4116 Part 3: Commands                                                                Trusted Platform Module Library
   4118 
   4119 
   4120 13     Duplication Commands
   4121 
   4122 13.1     TPM2_Duplicate
   4123 
   4124 13.1.1 General Description
   4125 
   4126 This command duplicates a loaded object so that it may be used in a different hierarchy. The new parent
   4127 key for the duplicate may be on the same or different TPM or TPM_RH_NULL. Only the public area of
   4128 newParentHandle is required to be loaded.
   4129 
   4130 NOTE 1          Since the new parent may only be extant on a different TPM, it is likely that the new parents
   4131                 sensitive area could not be loaded in the TPM from which objectHandle is being duplicated.
   4132 
   4133 If encryptedDuplication is SET in the object being duplicated, then the TPM shall return
   4134 TPM_RC_SYMMETRIC if symmetricAlg is TPM_RH_NULL or TPM_RC_HIERARCHY if
   4135 newParentHandle is TPM_RH_NULL.
   4136 The authorization for this command shall be with a policy session.
   4137 If fixedParent of objectHandleattributes is SET, the TPM shall return TPM_RC_ATTRIBUTES. If
   4138 objectHandlenameAlg is TPM_ALG_NULL, the TPM shall return TPM_RC_TYPE.
   4139 The policySessioncommandCode parameter in the policy session is required to be TPM_CC_Duplicate
   4140 to indicate that authorization for duplication has been provided. This indicates that the policy that is being
   4141 used is a policy that is for duplication, and not a policy that would approve another use. That is, authority
   4142 to use an object does not grant authority to duplicate the object.
   4143 The policy is likely to include cpHash in order to restrict where duplication can occur.        If
   4144 TPM2_PolicyCpHash() has been executed as part of the policy, the policySessioncpHash is compared
   4145 to the cpHash of the command.
   4146 If TPM2_PolicyDuplicationSelect() has             been     executed      as     part    of    the    policy,    the
   4147 policySessionnameHash is compared to
   4148                        HpolicyAlg(objectHandleName || newParentHandleName)                                     (2)
   4149 If the compared hashes are not the same, then the TPM shall return TPM_RC_POLICY_FAIL.
   4150 
   4151 NOTE 2          It is allowed that policySesionnameHash and policySessioncpHash share the same memory
   4152                 space.
   4153 
   4154 NOTE 3          A duplication policy is not required to have either TPM2_PolicyDuplicationSelect() or
   4155                 TPM2_PolicyCpHash() as part of the policy. If neither is present, then the duplication policy may be
   4156                 satisfied with a policy that only contains TPM2_PolicyComman dCode(code = TPM_CC_Duplicate).
   4157 
   4158 The TPM shall follow the process of encryption defined in the Duplication subclause of Protected
   4159 Storage Hierarchy in TPM 2.0 Part 1.
   4160 
   4161 
   4162 
   4163 
   4164 Page 80                                        TCG Published                                         Family 2.0
   4165 October 30, 2014                       Copyright  TCG 2006-2014                       Level 00 Revision 01.16
   4166 Trusted Platform Module Library                                                          Part 3: Commands
   4168 
   4169 
   4170 
   4171 13.1.2 Command and Response
   4172 
   4173                               Table 35  TPM2_Duplicate Command
   4174 Type                          Name                  Description
   4175 
   4176 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   4177 UINT32                        commandSize
   4178 TPM_CC                        commandCode           TPM_CC_Duplicate
   4179 
   4180                                                     loaded object to duplicate
   4181 TPMI_DH_OBJECT                @objectHandle         Auth Index: 1
   4182                                                     Auth Role: DUP
   4183                                                     shall reference the public area of an asymmetric key
   4184 TPMI_DH_OBJECT+               newParentHandle
   4185                                                     Auth Index: None
   4186 
   4187                                                     optional symmetric encryption key
   4188 TPM2B_DATA                    encryptionKeyIn       The size for this key is set to zero when the TPM is to
   4189                                                     generate the key. This parameter may be encrypted.
   4190                                                     definition for the symmetric algorithm to be used for the
   4191 TPMT_SYM_DEF_OBJECT+          symmetricAlg          inner wrapper
   4192                                                     may be TPM_ALG_NULL if no inner wrapper is applied
   4193 
   4194 
   4195                               Table 36  TPM2_Duplicate Response
   4196 Type                          Name                  Description
   4197 
   4198 TPM_ST                        tag                   see clause 6
   4199 UINT32                        responseSize
   4200 TPM_RC                        responseCode
   4201 
   4202                                                     If the caller provided an encryption key or if
   4203                                                     symmetricAlg was TPM_ALG_NULL, then this will be
   4204 TPM2B_DATA                    encryptionKeyOut      the Empty Buffer; otherwise, it shall contain the TPM-
   4205                                                     generated, symmetric encryption key for the inner
   4206                                                     wrapper.
   4207                                                     private area that may be encrypted by encryptionKeyIn;
   4208 TPM2B_PRIVATE                 duplicate
   4209                                                     and may be doubly encrypted
   4210                                                     seed protected by the asymmetric algorithms of new
   4211 TPM2B_ENCRYPTED_SECRET outSymSeed
   4212                                                     parent (NP)
   4213 
   4214 
   4215 
   4216 
   4217 Family 2.0                                 TCG Published                                          Page 81
   4218 Level 00 Revision 01.16             Copyright  TCG 2006-2014                            October 30, 2014
   4219      Part 3: Commands                                                           Trusted Platform Module Library
   4221 
   4222 
   4223 
   4224      13.1.3 Detailed Actions
   4225 
   4226 1    #include "InternalRoutines.h"
   4227 2    #include "Duplicate_fp.h"
   4228 3    #ifdef TPM_CC_Duplicate // Conditional expansion of this file
   4229 4    #include "Object_spt_fp.h"
   4230 
   4231 
   4232      Error Returns                Meaning
   4233 
   4234      TPM_RC_ATTRIBUTES            key to duplicate has fixedParent SET
   4235      TPM_RC_HIERARCHY             encryptedDuplication is SET and newParentHandle specifies Null
   4236                                   Hierarchy
   4237      TPM_RC_KEY                   newParentHandle references invalid ECC key (public point not on the
   4238                                   curve)
   4239      TPM_RC_SIZE                  input encryption key size does not match the size specified in
   4240                                   symmetric algorithm
   4241      TPM_RC_SYMMETRIC             encryptedDuplication is SET but no symmetric algorithm is provided
   4242      TPM_RC_TYPE                  newParentHandle is neither a storage key nor TPM_RH_NULL; or
   4243                                   the object has a NULL nameAlg
   4244 
   4245  5   TPM_RC
   4246  6   TPM2_Duplicate(
   4247  7       Duplicate_In      *in,            // IN: input parameter list
   4248  8       Duplicate_Out     *out            // OUT: output parameter list
   4249  9       )
   4250 10   {
   4251 11       TPM_RC                   result = TPM_RC_SUCCESS;
   4252 12       TPMT_SENSITIVE           sensitive;
   4253 13
   4254 14       UINT16                   innerKeySize = 0; // encrypt key size for inner wrap
   4255 15
   4256 16       OBJECT                   *object;
   4257 17       TPM2B_DATA               data;
   4258 18
   4259 19   // Input Validation
   4260 20
   4261 21       // Get duplicate object pointer
   4262 22       object = ObjectGet(in->objectHandle);
   4263 23
   4264 24       // duplicate key must have fixParent bit CLEAR.
   4265 25       if(object->publicArea.objectAttributes.fixedParent == SET)
   4266 26           return TPM_RC_ATTRIBUTES + RC_Duplicate_objectHandle;
   4267 27
   4268 28       // Do not duplicate object with NULL nameAlg
   4269 29       if(object->publicArea.nameAlg == TPM_ALG_NULL)
   4270 30           return TPM_RC_TYPE + RC_Duplicate_objectHandle;
   4271 31
   4272 32       // new parent key must be a storage object or TPM_RH_NULL
   4273 33       if(in->newParentHandle != TPM_RH_NULL
   4274 34               && !ObjectIsStorage(in->newParentHandle))
   4275 35           return TPM_RC_TYPE + RC_Duplicate_newParentHandle;
   4276 36
   4277 37       // If the duplicates object has encryptedDuplication SET, then there must be
   4278 38       // an inner wrapper and the new parent may not be TPM_RH_NULL
   4279 39       if(object->publicArea.objectAttributes.encryptedDuplication == SET)
   4280 40       {
   4281 41           if(in->symmetricAlg.algorithm == TPM_ALG_NULL)
   4282 42               return TPM_RC_SYMMETRIC + RC_Duplicate_symmetricAlg;
   4283 43           if(in->newParentHandle == TPM_RH_NULL)
   4284 
   4285      Page 82                                   TCG Published                                       Family 2.0
   4286      October 30, 2014                 Copyright  TCG 2006-2014                       Level 00 Revision 01.16
   4287      Trusted Platform Module Library                                              Part 3: Commands
   4289 
   4290 44                return TPM_RC_HIERARCHY + RC_Duplicate_newParentHandle;
   4291 45       }
   4292 46
   4293 47       if(in->symmetricAlg.algorithm == TPM_ALG_NULL)
   4294 48       {
   4295 49           // if algorithm is TPM_ALG_NULL, input key size must be 0
   4296 50           if(in->encryptionKeyIn.t.size != 0)
   4297 51               return TPM_RC_SIZE + RC_Duplicate_encryptionKeyIn;
   4298 52       }
   4299 53       else
   4300 54       {
   4301 55           // Get inner wrap key size
   4302 56           innerKeySize = in->symmetricAlg.keyBits.sym;
   4303 57
   4304 58           // If provided the input symmetric key must match the size of the algorithm
   4305 59           if(in->encryptionKeyIn.t.size != 0
   4306 60                   && in->encryptionKeyIn.t.size != (innerKeySize + 7) / 8)
   4307 61               return TPM_RC_SIZE + RC_Duplicate_encryptionKeyIn;
   4308 62       }
   4309 63
   4310 64   // Command Output
   4311 65
   4312 66       if(in->newParentHandle != TPM_RH_NULL)
   4313 67       {
   4314 68
   4315 69           // Make encrypt key and its associated secret structure. A TPM_RC_KEY
   4316 70           // error may be returned at this point
   4317 71           out->outSymSeed.t.size = sizeof(out->outSymSeed.t.secret);
   4318 72           result = CryptSecretEncrypt(in->newParentHandle,
   4319 73                                       "DUPLICATE", &data, &out->outSymSeed);
   4320 74           pAssert(result != TPM_RC_VALUE);
   4321 75           if(result != TPM_RC_SUCCESS)
   4322 76               return result;
   4323 77       }
   4324 78       else
   4325 79       {
   4326 80           // Do not apply outer wrapper
   4327 81           data.t.size = 0;
   4328 82           out->outSymSeed.t.size = 0;
   4329 83       }
   4330 84
   4331 85       // Copy sensitive area
   4332 86       sensitive = object->sensitive;
   4333 87
   4334 88       // Prepare output private data from sensitive
   4335 89       SensitiveToDuplicate(&sensitive, &object->name, in->newParentHandle,
   4336 90                            object->publicArea.nameAlg, (TPM2B_SEED *) &data,
   4337 91                            &in->symmetricAlg, &in->encryptionKeyIn,
   4338 92                            &out->duplicate);
   4339 93
   4340 94       out->encryptionKeyOut = in->encryptionKeyIn;
   4341 95
   4342 96       return TPM_RC_SUCCESS;
   4343 97   }
   4344 98   #endif // CC_Duplicate
   4345 
   4346 
   4347 
   4348 
   4349      Family 2.0                            TCG Published                                 Page 83
   4350      Level 00 Revision 01.16           Copyright  TCG 2006-2014                  October 30, 2014
   4351 Part 3: Commands                                                        Trusted Platform Module Library
   4353 
   4354 
   4355 13.2   TPM2_Rewrap
   4356 
   4357 13.2.1 General Description
   4358 
   4359 This command allows the TPM to serve in the role as a Duplication Authority. If proper authorization for
   4360 use of the oldParent is provided, then an HMAC key and a symmetric key are recovered from inSymSeed
   4361 and used to integrity check and decrypt inDuplicate. A new protection seed value is generated according
   4362 to the methods appropriate for newParent and the blob is re-encrypted and a new integrity value is
   4363 computed. The re-encrypted blob is returned in outDuplicate and the symmetric key returned in
   4364 outSymKey.
   4365 In the rewrap process, L is DUPLICATE (see Terms and Definitions in TPM 2.0 Part 1).
   4366 If inSymSeed has a zero length, then oldParent is required to be TPM_RH_NULL and no decryption of
   4367 inDuplicate takes place.
   4368 If newParent is TPM_RH_NULL, then no encryption is performed on outDuplicate. outSymSeed will have
   4369 a zero length. See TPM 2.0 Part 2 encryptedDuplication.
   4370 
   4371 
   4372 
   4373 
   4374 Page 84                                    TCG Published                                   Family 2.0
   4375 October 30, 2014                    Copyright  TCG 2006-2014                 Level 00 Revision 01.16
   4376 Trusted Platform Module Library                                                        Part 3: Commands
   4378 
   4379 
   4380 
   4381 13.2.2 Command and Response
   4382 
   4383                                   Table 37  TPM2_Rewrap Command
   4384 Type                          Name                  Description
   4385 
   4386 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   4387 UINT32                        commandSize
   4388 TPM_CC                        commandCode           TPM_CC_Rewrap
   4389 
   4390                                                     parent of object
   4391 TPMI_DH_OBJECT+               @oldParent            Auth Index: 1
   4392                                                     Auth Role: User
   4393                                                     new parent of the object
   4394 TPMI_DH_OBJECT+               newParent
   4395                                                     Auth Index: None
   4396 
   4397                                                     an object encrypted using symmetric key derived from
   4398 TPM2B_PRIVATE                 inDuplicate
   4399                                                     inSymSeed
   4400 TPM2B_NAME                    name                  the Name of the object being rewrapped
   4401                                                     seed for symmetric key
   4402 TPM2B_ENCRYPTED_SECRET inSymSeed                    needs oldParent private key to recover the seed and
   4403                                                     generate the symmetric key
   4404 
   4405 
   4406                                   Table 38  TPM2_Rewrap Response
   4407 Type                          Name                  Description
   4408 
   4409 TPM_ST                        tag                   see clause 6
   4410 UINT32                        responseSize
   4411 TPM_RC                        responseCode
   4412 
   4413                                                     an object encrypted using symmetric key derived from
   4414 TPM2B_PRIVATE                 outDuplicate
   4415                                                     outSymSeed
   4416                                                     seed for a symmetric key protected by newParent
   4417 TPM2B_ENCRYPTED_SECRET outSymSeed
   4418                                                     asymmetric key
   4419 
   4420 
   4421 
   4422 
   4423 Family 2.0                                 TCG Published                                       Page 85
   4424 Level 00 Revision 01.16              Copyright  TCG 2006-2014                         October 30, 2014
   4425      Part 3: Commands                                                            Trusted Platform Module Library
   4427 
   4428 
   4429 
   4430      13.2.3 Detailed Actions
   4431 
   4432 1    #include "InternalRoutines.h"
   4433 2    #include "Rewrap_fp.h"
   4434 3    #ifdef TPM_CC_Rewrap // Conditional expansion of this file
   4435 4    #include "Object_spt_fp.h"
   4436 
   4437 
   4438      Error Returns                 Meaning
   4439 
   4440      TPM_RC_ATTRIBUTES             newParent is not a decryption key
   4441      TPM_RC_HANDLE                 oldParent does not consistent with inSymSeed
   4442      TPM_RC_INTEGRITY              the integrity check of inDuplicate failed
   4443      TPM_RC_KEY                    for an ECC key, the public key is not on the curve of the curve ID
   4444      TPM_RC_KEY_SIZE               the decrypted input symmetric key size does not matches the
   4445                                    symmetric algorithm key size of oldParent
   4446      TPM_RC_TYPE                   oldParent is not a storage key, or 'newParent is not a storage key
   4447      TPM_RC_VALUE                  for an 'oldParent; RSA key, the data to be decrypted is greater than
   4448                                    the public exponent
   4449      Unmarshal errors              errors during unmarshaling the input encrypted buffer to a ECC public
   4450                                    key, or unmarshal the private buffer to sensitive
   4451 
   4452  5   TPM_RC
   4453  6   TPM2_Rewrap(
   4454  7       Rewrap_In         *in,             // IN: input parameter list
   4455  8       Rewrap_Out        *out             // OUT: output parameter list
   4456  9       )
   4457 10   {
   4458 11       TPM_RC                   result = TPM_RC_SUCCESS;
   4459 12       OBJECT                   *oldParent;
   4460 13       TPM2B_DATA               data;               // symmetric key
   4461 14       UINT16                   hashSize = 0;
   4462 15       TPM2B_PRIVATE            privateBlob;        // A temporary private blob
   4463 16                                                    // to transit between old
   4464 17                                                    // and new wrappers
   4465 18
   4466 19   // Input Validation
   4467 20
   4468 21       if((in->inSymSeed.t.size == 0 && in->oldParent != TPM_RH_NULL)
   4469 22               || (in->inSymSeed.t.size != 0 && in->oldParent == TPM_RH_NULL))
   4470 23           return TPM_RC_HANDLE + RC_Rewrap_oldParent;
   4471 24
   4472 25       if(in->oldParent != TPM_RH_NULL)
   4473 26       {
   4474 27           // Get old parent pointer
   4475 28           oldParent = ObjectGet(in->oldParent);
   4476 29
   4477 30             // old parent key must be a storage object
   4478 31             if(!ObjectIsStorage(in->oldParent))
   4479 32                 return TPM_RC_TYPE + RC_Rewrap_oldParent;
   4480 33
   4481 34             // Decrypt input secret data via asymmetric decryption. A
   4482 35             // TPM_RC_VALUE, TPM_RC_KEY or unmarshal errors may be returned at this
   4483 36             // point
   4484 37             result = CryptSecretDecrypt(in->oldParent, NULL,
   4485 38                                         "DUPLICATE", &in->inSymSeed, &data);
   4486 39             if(result != TPM_RC_SUCCESS)
   4487 40                 return TPM_RC_VALUE + RC_Rewrap_inSymSeed;
   4488 41
   4489 
   4490      Page 86                                    TCG Published                                           Family 2.0
   4491      October 30, 2014                   Copyright  TCG 2006-2014                       Level 00 Revision 01.16
   4492       Trusted Platform Module Library                                             Part 3: Commands
   4494 
   4495  42           // Unwrap Outer
   4496  43           result = UnwrapOuter(in->oldParent, &in->name,
   4497  44                                oldParent->publicArea.nameAlg, (TPM2B_SEED *) &data,
   4498  45                                FALSE,
   4499  46                                in->inDuplicate.t.size, in->inDuplicate.t.buffer);
   4500  47           if(result != TPM_RC_SUCCESS)
   4501  48               return RcSafeAddToResult(result, RC_Rewrap_inDuplicate);
   4502  49
   4503  50           // Copy unwrapped data to temporary variable, remove the integrity field
   4504  51           hashSize = sizeof(UINT16) +
   4505  52                      CryptGetHashDigestSize(oldParent->publicArea.nameAlg);
   4506  53           privateBlob.t.size = in->inDuplicate.t.size - hashSize;
   4507  54           MemoryCopy(privateBlob.t.buffer, in->inDuplicate.t.buffer + hashSize,
   4508  55                      privateBlob.t.size, sizeof(privateBlob.t.buffer));
   4509  56       }
   4510  57       else
   4511  58       {
   4512  59           // No outer wrap from input blob.   Direct copy.
   4513  60           privateBlob = in->inDuplicate;
   4514  61       }
   4515  62
   4516  63       if(in->newParent != TPM_RH_NULL)
   4517  64       {
   4518  65           OBJECT          *newParent;
   4519  66           newParent = ObjectGet(in->newParent);
   4520  67
   4521  68           // New parent must be a storage object
   4522  69           if(!ObjectIsStorage(in->newParent))
   4523  70               return TPM_RC_TYPE + RC_Rewrap_newParent;
   4524  71
   4525  72           // Make new encrypt key and its associated secret structure. A
   4526  73           // TPM_RC_VALUE error may be returned at this point if RSA algorithm is
   4527  74           // enabled in TPM
   4528  75           out->outSymSeed.t.size = sizeof(out->outSymSeed.t.secret);
   4529  76           result = CryptSecretEncrypt(in->newParent,
   4530  77                                       "DUPLICATE", &data, &out->outSymSeed);
   4531  78           if(result != TPM_RC_SUCCESS) return result;
   4532  79
   4533  80   // Command output
   4534  81           // Copy temporary variable to output, reserve the space for integrity
   4535  82           hashSize = sizeof(UINT16) +
   4536  83                      CryptGetHashDigestSize(newParent->publicArea.nameAlg);
   4537  84           out->outDuplicate.t.size = privateBlob.t.size;
   4538  85           MemoryCopy(out->outDuplicate.t.buffer + hashSize, privateBlob.t.buffer,
   4539  86                      privateBlob.t.size, sizeof(out->outDuplicate.t.buffer));
   4540  87
   4541  88           // Produce outer wrapper for output
   4542  89           out->outDuplicate.t.size = ProduceOuterWrap(in->newParent, &in->name,
   4543  90                                      newParent->publicArea.nameAlg,
   4544  91                                      (TPM2B_SEED *) &data,
   4545  92                                      FALSE,
   4546  93                                      out->outDuplicate.t.size,
   4547  94                                      out->outDuplicate.t.buffer);
   4548  95
   4549  96       }
   4550  97       else // New parent is a null key so there is no seed
   4551  98       {
   4552  99           out->outSymSeed.t.size = 0;
   4553 100
   4554 101           // Copy privateBlob directly
   4555 102           out->outDuplicate = privateBlob;
   4556 103       }
   4557 104
   4558 105       return TPM_RC_SUCCESS;
   4559 106   }
   4560 107   #endif // CC_Rewrap
   4561 
   4562       Family 2.0                           TCG Published                                Page 87
   4563       Level 00 Revision 01.16           Copyright  TCG 2006-2014                 October 30, 2014
   4564 Part 3: Commands                                                                      Trusted Platform Module Library
   4566 
   4567 
   4568 13.3     TPM2_Import
   4569 
   4570 13.3.1 General Description
   4571 
   4572 This command allows an object to be encrypted using the symmetric encryption values of a Storage Key.
   4573 After encryption, the object may be loaded and used in the new hierarchy. The imported object (duplicate)
   4574 may be singly encrypted, multiply encrypted, or unencrypted.
   4575 If fixedTPM or fixedParent is SET in objectPublic, the TPM shall return TPM_RC_ATTRIBUTES.
   4576 If encryptedDuplication is SET in the object referenced by parentHandle, then encryptedDuplication shall
   4577 be SET in objectPublic (TPM_RC_ATTRIBUTES).
   4578 If encryptedDuplication is SET in objectPublic, then inSymSeed and encryptionKey shall not be Empty
   4579 buffers (TPM_RC_ATTRIBUTES). Recovery of the sensitive data of the object occurs in the TPM in a
   4580 multi--step process in the following order:
   4581 a) If inSymSeed has a non-zero size:
   4582     1) The asymmetric parameters and private key of parentHandle are used to recover the seed used
   4583        in the creation of the HMAC key and encryption keys used to protect the duplication blob.
   4584 
   4585          NOTE 1       When recovering the seed from inSymSeed, L is DUPLICATE.
   4586 
   4587     2) The integrity value in duplicate.buffer.integrityOuter is used to verify the integrity of the inner data
   4588        blob, which is the remainder of duplicate.buffer (TPM_RC_INTEGRITY).
   4589 
   4590          NOTE 2            The inner data blob will contain a TPMT_SENSITIVE and may contain a TPM2B_DIGEST
   4591                            for the innerIntegrity.
   4592 
   4593     3) The symmetric key recovered in 1) (2)is used to decrypt the inner data blob.
   4594 
   4595          NOTE 3            Checking the integrity before the data is used prevents attacks on the sensitive area by
   4596                            fuzzing the data and looking at the differences in the response codes.
   4597 
   4598 b) If encryptionKey is not an Empty Buffer:
   4599     1) Use encryptionKey to decrypt the inner blob.
   4600     2) Use the TPM2B_DIGEST at the start of the inner blob to verify the integrity of the inner blob
   4601        (TPM_RC_INTEGRITY).
   4602 c) Unmarshal the sensitive area
   4603 
   4604 NOTE 4            It is not necessary to validate that the sensitive area data is cryptographically bound to the public
   4605                   area other than that the Name of the public area is included in the HMAC. However, if the binding is
   4606                   not validated by this command, the binding must be checked each time the object is loaded. For an
   4607                   object that is imported under a parent with fixedTPM SET, binding need only be checked at import. If
   4608                   the parent has fixedTPM CLEAR, then the binding needs to be checked each time the object is
   4609                   loaded, or before the TPM performs an operation for which the binding affects the outcome of the
   4610                   operation (for example, TPM2_PolicySigned() or TPM2_Certify()).
   4611 
   4612                   Similarly, if the new parent's fixedTPM is set, the encryptedDuplication state need only be checked
   4613                   at import.
   4614 
   4615                   If the new parent is not fixedTPM, then that object will be loadable on any TPM (including SW
   4616                   versions) on which the new parent exists. This means that, each time an object is loaded under a
   4617                   parent that is not fixedTPM, it is necessary to validate all of the properties of that object. If the
   4618                   parent is fixedTPM, then the new private blob is integrity protec ted by the TPM that owns the
   4619                   parent. So, it is sufficient to validate the objects properties (attribute and public -private binding) on
   4620                   import and not again.
   4621 
   4622 After integrity checks and decryption, the TPM will create a new symmetrically encrypted private area
   4623 using the encryption key of the parent.
   4624 
   4625 Page 88                                            TCG Published                                             Family 2.0
   4626 October 30, 2014                          Copyright  TCG 2006-2014                          Level 00 Revision 01.16
   4627 Trusted Platform Module Library                                                             Part 3: Commands
   4629 
   4630 NOTE 5         The symmetric re-encryption is the normal integrity generation and symmetric encryption applied to
   4631                a child object.
   4632 
   4633 
   4634 
   4635 
   4636 Family 2.0                                 TCG Published                                             Page 89
   4637 Level 00 Revision 01.16              Copyright  TCG 2006-2014                              October 30, 2014
   4638 Part 3: Commands                                                    Trusted Platform Module Library
   4640 
   4641 
   4642 13.3.2 Command and Response
   4643 
   4644                          Table 39  TPM2_Import Command
   4645 Type                   Name                  Description
   4646 
   4647 TPMI_ST_COMMAND_TAG    tag                   TPM_ST_SESSIONS
   4648 UINT32                 commandSize
   4649 TPM_CC                 commandCode           TPM_CC_Import
   4650 
   4651                                              the handle of the new parent for the object
   4652 TPMI_DH_OBJECT         @parentHandle         Auth Index: 1
   4653                                              Auth Role: USER
   4654 
   4655                                              the optional symmetric encryption key used as the inner
   4656                                              wrapper for duplicate
   4657 TPM2B_DATA             encryptionKey
   4658                                              If symmetricAlg is TPM_ALG_NULL, then this
   4659                                              parameter shall be the Empty Buffer.
   4660                                              the public area of the object to be imported
   4661                                              This is provided so that the integrity value for duplicate
   4662 TPM2B_PUBLIC           objectPublic          and the object attributes can be checked.
   4663                                              NOTE        Even if the integrity value of the object is not
   4664                                                          checked on input, the object Name is required to
   4665                                                          create the integrity value for the imported object.
   4666 
   4667                                              the symmetrically encrypted duplicate object that may
   4668 TPM2B_PRIVATE          duplicate
   4669                                              contain an inner symmetric wrapper
   4670                                              symmetric key used to encrypt duplicate
   4671 TPM2B_ENCRYPTED_SECRET inSymSeed             inSymSeed is encrypted/encoded using the algorithms
   4672                                              of newParent.
   4673                                              definition for the symmetric algorithm to use for the inner
   4674                                              wrapper
   4675 TPMT_SYM_DEF_OBJECT+   symmetricAlg
   4676                                              If this algorithm is TPM_ALG_NULL, no inner wrapper is
   4677                                              present and encryptionKey shall be the Empty Buffer.
   4678 
   4679 
   4680                          Table 40  TPM2_Import Response
   4681 Type                   Name                  Description
   4682 
   4683 TPM_ST                 tag                   see clause 6
   4684 UINT32                 responseSize
   4685 TPM_RC                 responseCode
   4686 
   4687                                              the sensitive area encrypted with the symmetric key of
   4688 TPM2B_PRIVATE          outPrivate
   4689                                              parentHandle
   4690 
   4691 
   4692 
   4693 
   4694 Page 90                               TCG Published                                          Family 2.0
   4695 October 30, 2014             Copyright  TCG 2006-2014                      Level 00 Revision 01.16
   4696     Trusted Platform Module Library                                                                Part 3: Commands
   4698 
   4699 
   4700 
   4701     13.3.3 Detailed Actions
   4702 
   4703 1   #include "InternalRoutines.h"
   4704 2   #include "Import_fp.h"
   4705 3   #ifdef TPM_CC_Import // Conditional expansion of this file
   4706 4   #include "Object_spt_fp.h"
   4707 
   4708 
   4709     Error Returns                     Meaning
   4710 
   4711     TPM_RC_ASYMMETRIC                 non-duplicable storage key represented by objectPublic and its
   4712                                       parent referenced by parentHandle have different public parameters
   4713     TPM_RC_ATTRIBUTES                 attributes FixedTPM and fixedParent of objectPublic are not both
   4714                                       CLEAR; or inSymSeed is nonempty and parentHandle does not
   4715                                       reference a decryption key; or objectPublic and parentHandle have
   4716                                       incompatible or inconsistent attributes; or encrytpedDuplication is
   4717                                       SET in objectPublic but the inner or outer wrapper is missing.
   4718 
   4719     NOTE:           if the TPM provides parameter values, the parameter number will indicate symmetricKey (missing
   4720                     inner wrapper) or inSymSeed (missing outer wrapper).
   4721 
   4722 
   4723     TPM_RC_BINDING                    duplicate and objectPublic are not cryptographically
   4724                                       bound
   4725 
   4726     TPM_RC_ECC_POINT                  inSymSeed is nonempty and ECC point in inSymSeed is not on the
   4727                                       curve
   4728     TPM_RC_HASH                       non-duplicable storage key represented by objectPublic and its
   4729                                       parent referenced by parentHandle have different name algorithm
   4730     TPM_RC_INSUFFICIENT               inSymSeed is nonempty and failed to retrieve ECC point from the
   4731                                       secret; or unmarshaling sensitive value from duplicate failed the
   4732                                       result of inSymSeed decryption
   4733     TPM_RC_INTEGRITY                  duplicate integrity is broken
   4734     TPM_RC_KDF                        objectPublic representing decrypting keyed hash object specifies
   4735                                       invalid KDF
   4736     TPM_RC_KEY                        inconsistent parameters of objectPublic; or inSymSeed is nonempty
   4737                                       and parentHandle does not reference a key of supported type; or
   4738                                       invalid key size in objectPublic representing an asymmetric key
   4739     TPM_RC_NO_RESULT                  inSymSeed is nonempty and multiplication resulted in ECC point at
   4740                                       infinity
   4741     TPM_RC_OBJECT_MEMORY              no available object slot
   4742     TPM_RC_SCHEME                     inconsistent attributes decrypt, sign, restricted and key's scheme ID
   4743                                       in objectPublic; or hash algorithm is inconsistent with the scheme ID
   4744                                       for keyed hash object
   4745     TPM_RC_SIZE                       authPolicy size does not match digest size of the name algorithm in
   4746                                       objectPublic; or symmetricAlg and encryptionKey have different
   4747                                       sizes; or inSymSeed is nonempty and it size is not consistent with the
   4748                                       type of parentHandle; or unmarshaling sensitive value from duplicate
   4749                                       failed
   4750     TPM_RC_SYMMETRIC                  objectPublic is either a storage key with no symmetric algorithm or a
   4751                                       non-storage key with symmetric algorithm different from
   4752                                       TPM_ALG_NULL
   4753     TPM_RC_TYPE                       unsupported type of objectPublic; or non-duplicable storage key
   4754                                       represented by objectPublic and its parent referenced by
   4755                                       parentHandle are of different types; or parentHandle is not a storage
   4756                                       key; or only the public portion of parentHandle is loaded; or
   4757 
   4758     Family 2.0                                   TCG Published                                               Page 91
   4759     Level 00 Revision 01.16                Copyright  TCG 2006-2014                               October 30, 2014
   4760      Part 3: Commands                                                           Trusted Platform Module Library
   4762 
   4763                                   objectPublic and duplicate are of different types
   4764      TPM_RC_VALUE                 nonempty inSymSeed and its numeric value is greater than the
   4765                                   modulus of the key referenced by parentHandle or inSymSeed is
   4766                                   larger than the size of the digest produced by the name algorithm of
   4767                                   the symmetric key referenced by parentHandle
   4768 
   4769  5   TPM_RC
   4770  6   TPM2_Import(
   4771  7       Import_In         *in,            // IN: input parameter list
   4772  8       Import_Out        *out            // OUT: output parameter list
   4773  9       )
   4774 10   {
   4775 11
   4776 12       TPM_RC                   result = TPM_RC_SUCCESS;
   4777 13       OBJECT                   *parentObject;
   4778 14       TPM2B_DATA               data;                   // symmetric key
   4779 15       TPMT_SENSITIVE           sensitive;
   4780 16       TPM2B_NAME               name;
   4781 17
   4782 18       UINT16                   innerKeySize = 0;             // encrypt key size for inner
   4783 19                                                              // wrapper
   4784 20
   4785 21   // Input Validation
   4786 22
   4787 23       // FixedTPM and fixedParent must be CLEAR
   4788 24       if(   in->objectPublic.t.publicArea.objectAttributes.fixedTPM == SET
   4789 25          || in->objectPublic.t.publicArea.objectAttributes.fixedParent == SET)
   4790 26           return TPM_RC_ATTRIBUTES + RC_Import_objectPublic;
   4791 27
   4792 28       // Get parent pointer
   4793 29       parentObject = ObjectGet(in->parentHandle);
   4794 30
   4795 31       if(!AreAttributesForParent(parentObject))
   4796 32           return TPM_RC_TYPE + RC_Import_parentHandle;
   4797 33
   4798 34       if(in->symmetricAlg.algorithm != TPM_ALG_NULL)
   4799 35       {
   4800 36           // Get inner wrap key size
   4801 37           innerKeySize = in->symmetricAlg.keyBits.sym;
   4802 38           // Input symmetric key must match the size of algorithm.
   4803 39           if(in->encryptionKey.t.size != (innerKeySize + 7) / 8)
   4804 40               return TPM_RC_SIZE + RC_Import_encryptionKey;
   4805 41       }
   4806 42       else
   4807 43       {
   4808 44           // If input symmetric algorithm is NULL, input symmetric key size must
   4809 45           // be 0 as well
   4810 46           if(in->encryptionKey.t.size != 0)
   4811 47               return TPM_RCS_SIZE + RC_Import_encryptionKey;
   4812 48           // If encryptedDuplication is SET, then the object must have an inner
   4813 49           // wrapper
   4814 50           if(in->objectPublic.t.publicArea.objectAttributes.encryptedDuplication)
   4815 51               return TPM_RCS_ATTRIBUTES + RC_Import_encryptionKey;
   4816 52       }
   4817 53
   4818 54       // See if there is an outer wrapper
   4819 55       if(in->inSymSeed.t.size != 0)
   4820 56       {
   4821 57           // Decrypt input secret data via asymmetric decryption. TPM_RC_ATTRIBUTES,
   4822 58           // TPM_RC_ECC_POINT, TPM_RC_INSUFFICIENT, TPM_RC_KEY, TPM_RC_NO_RESULT,
   4823 59           // TPM_RC_SIZE, TPM_RC_VALUE may be returned at this point
   4824 60           result = CryptSecretDecrypt(in->parentHandle, NULL, "DUPLICATE",
   4825 61                                       &in->inSymSeed, &data);
   4826 62           pAssert(result != TPM_RC_BINDING);
   4827 
   4828 
   4829      Page 92                                   TCG Published                                         Family 2.0
   4830      October 30, 2014                 Copyright  TCG 2006-2014                       Level 00 Revision 01.16
   4831       Trusted Platform Module Library                                               Part 3: Commands
   4833 
   4834  63           if(result != TPM_RC_SUCCESS)
   4835  64               return RcSafeAddToResult(result, RC_Import_inSymSeed);
   4836  65       }
   4837  66       else
   4838  67       {
   4839  68           // If encrytpedDuplication is set, then the object must have an outer
   4840  69           // wrapper
   4841  70           if(in->objectPublic.t.publicArea.objectAttributes.encryptedDuplication)
   4842  71               return TPM_RCS_ATTRIBUTES + RC_Import_inSymSeed;
   4843  72           data.t.size = 0;
   4844  73       }
   4845  74
   4846  75       // Compute name of object
   4847  76       ObjectComputeName(&(in->objectPublic.t.publicArea), &name);
   4848  77
   4849  78       // Retrieve sensitive from private.
   4850  79       // TPM_RC_INSUFFICIENT, TPM_RC_INTEGRITY, TPM_RC_SIZE may be returned here.
   4851  80       result = DuplicateToSensitive(&in->duplicate, &name, in->parentHandle,
   4852  81                                     in->objectPublic.t.publicArea.nameAlg,
   4853  82                                     (TPM2B_SEED *) &data, &in->symmetricAlg,
   4854  83                                     &in->encryptionKey, &sensitive);
   4855  84       if(result != TPM_RC_SUCCESS)
   4856  85           return RcSafeAddToResult(result, RC_Import_duplicate);
   4857  86
   4858  87       // If the parent of this object has fixedTPM SET, then fully validate this
   4859  88       // object so that validation can be skipped when it is loaded
   4860  89       if(parentObject->publicArea.objectAttributes.fixedTPM == SET)
   4861  90       {
   4862  91           TPM_HANDLE       objectHandle;
   4863  92
   4864  93           // Perform self check on input public area. A TPM_RC_SIZE, TPM_RC_SCHEME,
   4865  94           // TPM_RC_VALUE, TPM_RC_SYMMETRIC, TPM_RC_TYPE, TPM_RC_HASH,
   4866  95           // TPM_RC_ASYMMETRIC, TPM_RC_ATTRIBUTES or TPM_RC_KDF error may be returned
   4867  96           // at this point
   4868  97           result = PublicAttributesValidation(TRUE, in->parentHandle,
   4869  98                                               &in->objectPublic.t.publicArea);
   4870  99           if(result != TPM_RC_SUCCESS)
   4871 100               return RcSafeAddToResult(result, RC_Import_objectPublic);
   4872 101
   4873 102           // Create internal object. A TPM_RC_KEY_SIZE, TPM_RC_KEY or
   4874 103           // TPM_RC_OBJECT_MEMORY error may be returned at this point
   4875 104           result = ObjectLoad(TPM_RH_NULL, &in->objectPublic.t.publicArea,
   4876 105                               &sensitive, NULL, in->parentHandle, FALSE,
   4877 106                               &objectHandle);
   4878 107           if(result != TPM_RC_SUCCESS)
   4879 108               return result;
   4880 109
   4881 110           // Don't need the object, just needed the checks to be performed so
   4882 111           // flush the object
   4883 112           ObjectFlush(objectHandle);
   4884 113       }
   4885 114
   4886 115   // Command output
   4887 116
   4888 117       // Prepare output private data from sensitive
   4889 118       SensitiveToPrivate(&sensitive, &name, in->parentHandle,
   4890 119                          in->objectPublic.t.publicArea.nameAlg,
   4891 120                          &out->outPrivate);
   4892 121
   4893 122       return TPM_RC_SUCCESS;
   4894 123   }
   4895 124   #endif // CC_Import
   4896 
   4897 
   4898 
   4899 
   4900       Family 2.0                           TCG Published                                  Page 93
   4901       Level 00 Revision 01.16           Copyright  TCG 2006-2014                   October 30, 2014
   4902 Part 3: Commands                                                              Trusted Platform Module Library
   4904 
   4905 
   4906 14     Asymmetric Primitives
   4907 
   4908 14.1    Introduction
   4909 
   4910 The commands in this clause provide low-level primitives for access to the asymmetric algorithms
   4911 implemented in the TPM. Many of these commands are only allowed if the asymmetric key is an
   4912 unrestricted key.
   4913 
   4914 14.2    TPM2_RSA_Encrypt
   4915 
   4916 14.2.1 General Description
   4917 
   4918 This command performs RSA encryption using the indicated padding scheme according to IETF RFC
   4919 3447. If the scheme of keyHandle is TPM_ALG_NULL, then the caller may use inScheme to specify the
   4920 padding scheme. If scheme of keyHandle is not TPM_ALG_NULL, then inScheme shall either be
   4921 TPM_ALG_NULL or be the same as scheme (TPM_RC_SCHEME).
   4922 The key referenced by keyHandle is required to be an RSA key (TPM_RC_KEY) with the decrypt attribute
   4923 SET (TPM_RC_ATTRIBUTES).
   4924 
   4925 NOTE            Requiring that the decrypt attribute be set allows the TPM to ensure that the scheme selection is
   4926                 done with the presumption that the scheme of the key is a decryption scheme selection. It is
   4927                 understood that this command will operate on a key with only the public part loaded so the caller
   4928                 may modify any key in any desired way. So, this constraint only serves to simplify the TPM logic.
   4929 
   4930 The three types of allowed padding are:
   4931 1) TPM_ALG_OAEP  Data is OAEP padded as described in 7.1 of IETF RFC 3447 (PKCS#1).
   4932    The only supported mask generation is MGF1.
   4933 2) TPM_ALG_RSAES  Data is padded as described in 7.2 of IETF RFC 3447 (PKCS#1).
   4934 3) TPM_ALG_NULL  Data is not padded by the TPM and the TPM will treat message as an
   4935    unsigned integer and perform a modular exponentiation of message using the public
   4936    exponent of the key referenced by keyHandle. This scheme is only used if both the scheme
   4937    in the key referenced by keyHandle is TPM_ALG_NULL, and the inScheme parameter of the
   4938    command is TPM_ALG_NULL. The input value cannot be larger than the public modulus of
   4939    the key referenced by keyHandle.
   4940 
   4941                                  Table 41  Padding Scheme Selection
   4942  keyHandlescheme             inScheme                          padding scheme used
   4943 
   4944                               TPM_ALG_NULL                      none
   4945  TPM_ALG_NULL                 TPM_ALG_RSAES                     RSAES
   4946                               TPM_ALG_OAEP                      OAEP
   4947                               TPM_ALG_NULL                      RSAES
   4948  TPM_ALG_RSAES                TPM_ALG_RSAES                     RSAES
   4949                               TPM_ALG_OAEP                      error (TPM_RC_SCHEME)
   4950                               TPM_ALG_NULL                      OAEP
   4951  TPM_ALG_OAEP                 TPM_ALG_RSAES                     error (TPM_RC_SCHEME)
   4952                               TPM_AGL_OAEP                      OAEP
   4953 
   4954 After padding, the data is RSAEP encrypted according to 5.1.1 of IETF RFC 3447 (PKCS#1).
   4955 
   4956 
   4957 Page 94                                       TCG Published                                        Family 2.0
   4958 October 30, 2014                      Copyright  TCG 2006-2014                     Level 00 Revision 01.16
   4959 Trusted Platform Module Library                                                                       Part 3: Commands
   4961 
   4962 NOTE 1             It is required that decrypt be SET so that the commands that load a key can validate that the
   4963                    scheme is consistent rather than have that deferred until the key is used.
   4964 
   4965 NOTE 2             If it is desired to use a key that had restricted SET, the caller may CLEAR restricted and load the
   4966                    public part of the key and use that unrestricted version of the key for encryption.
   4967 
   4968 If inScheme is used, and the scheme requires a hash algorithm it may not be TPM_ALG_NULL.
   4969 
   4970 NOTE 3             Because only the public portion of the key needs to be loaded for this command, th e caller can
   4971                    manipulate the attributes of the key in any way desired. As a result , the TPM shall not check the
   4972                    consistency of the attributes. The only property checking is that the key is an RSA key and that the
   4973                    padding scheme is supported.
   4974 
   4975 The message parameter is limited in size by the padding scheme according to the following table:
   4976 
   4977                               Table 42  Message Size Limits Based on Padding
   4978                                           Maximum Message Length
   4979 Scheme                                    (mLen) in Octets                     Comments
   4980 
   4981 TPM_ALG_OAEP                              mLen  k  2hLen  2
   4982 TPM_ALG_RSAES                             mLen  k  11
   4983 TPM_ALG_NULL                              mLen  k                             The numeric value of the message must be
   4984                                                                                less than the numeric value of the public
   4985                                                                                modulus (n).
   4986 NOTES
   4987 1)   k  the number of byes in the public modulus
   4988 2)   hLen  the number of octets in the digest produced by the hash algorithm used in the process
   4989 
   4990 The label parameter is optional. If provided (label.size != 0) then the TPM shall return TPM_RC_VALUE if
   4991 the last octet in label is not zero. If a zero octet occurs before label.buffer[label.size-1], the TPM shall
   4992 truncate the label at that point. The terminating octet of zero is included in the label used in the padding
   4993 scheme.
   4994 
   4995 NOTE 4             If the scheme does not use a label, the TPM will still verify that label is properly formatted if label is
   4996                    present.
   4997 
   4998 The function returns padded and encrypted value outData.
   4999 The message parameter in the command may be encrypted using parameter encryption.
   5000 
   5001 NOTE 5             Only the public area of keyHandle is required to be loaded. A public key may be loaded with any
   5002                    desired scheme. If the scheme is to be changed, a different public area must be loaded.
   5003 
   5004 
   5005 
   5006 
   5007 Family 2.0                                         TCG Published                                                Page 95
   5008 Level 00 Revision 01.16                     Copyright  TCG 2006-2014                                 October 30, 2014
   5009 Part 3: Commands                                                    Trusted Platform Module Library
   5011 
   5012 
   5013 14.2.2 Command and Response
   5014 
   5015                        Table 43  TPM2_RSA_Encrypt Command
   5016 Type                    Name                  Description
   5017 
   5018                                               TPM_ST_SESSIONS if an audit, encrypt, or decrypt
   5019 TPMI_ST_COMMAND_TAG     tag                   session is present; otherwise,
   5020                                               TPM_ST_NO_SESSIONS
   5021 UINT32                  commandSize
   5022 TPM_CC                  commandCode           TPM_CC_RSA_Encrypt
   5023 
   5024                                               reference to public portion of RSA key to use for
   5025 TPMI_DH_OBJECT          keyHandle             encryption
   5026                                               Auth Index: None
   5027 
   5028                                               message to be encrypted
   5029                                               NOTE 1     The data type was chosen because it limits the
   5030 TPM2B_PUBLIC_KEY_RSA    message                          overall size of the input to no greater than the size
   5031                                                          of the largest RSA public key. This may be larger
   5032                                                          than allowed for keyHandle.
   5033 
   5034                                               the padding scheme to use if scheme associated with
   5035 TPMT_RSA_DECRYPT+       inScheme
   5036                                               keyHandle is TPM_ALG_NULL
   5037                                               optional label L to be associated with the message
   5038 TPM2B_DATA              label                 Size of the buffer is zero if no label is present
   5039                                               NOTE 2     See description of label above.
   5040 
   5041 
   5042                        Table 44  TPM2_RSA_Encrypt Response
   5043 Type                    Name                  Description
   5044 
   5045 TPM_ST                  tag                   see clause 6
   5046 UINT32                  responseSize
   5047 TPM_RC                  responseCode
   5048 
   5049 TPM2B_PUBLIC_KEY_RSA    outData               encrypted output
   5050 
   5051 
   5052 
   5053 
   5054 Page 96                                TCG Published                                          Family 2.0
   5055 October 30, 2014                Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   5056      Trusted Platform Module Library                                                                 Part 3: Commands
   5058 
   5059 
   5060 
   5061      14.2.3 Detailed Actions
   5062 
   5063 1    #include "InternalRoutines.h"
   5064 2    #include "RSA_Encrypt_fp.h"
   5065 3    #ifdef TPM_CC_RSA_Encrypt // Conditional expansion of this file
   5066 4    #ifdef TPM_ALG_RSA
   5067 
   5068 
   5069      Error Returns                     Meaning
   5070 
   5071      TPM_RC_ATTRIBUTES                 decrypt attribute is not SET in key referenced by keyHandle
   5072      TPM_RC_KEY                        keyHandle does not reference an RSA key
   5073      TPM_RC_SCHEME                     incorrect input scheme, or the chosen scheme is not a valid RSA
   5074                                        decrypt scheme
   5075      TPM_RC_VALUE                      the numeric value of message is greater than the public modulus of
   5076                                        the key referenced by keyHandle, or label is not a null-terminated
   5077                                        string
   5078 
   5079  5   TPM_RC
   5080  6   TPM2_RSA_Encrypt(
   5081  7       RSA_Encrypt_In        *in,                 // IN: input parameter list
   5082  8       RSA_Encrypt_Out       *out                 // OUT: output parameter list
   5083  9       )
   5084 10   {
   5085 11       TPM_RC                    result;
   5086 12       OBJECT                    *rsaKey;
   5087 13       TPMT_RSA_DECRYPT          *scheme;
   5088 14       char                      *label = NULL;
   5089 15
   5090 16   // Input Validation
   5091 17
   5092 18       rsaKey = ObjectGet(in->keyHandle);
   5093 19
   5094 20       // selected key must be an RSA key
   5095 21       if(rsaKey->publicArea.type != TPM_ALG_RSA)
   5096 22           return TPM_RC_KEY + RC_RSA_Encrypt_keyHandle;
   5097 23
   5098 24       // selected key must have the decryption attribute
   5099 25       if(rsaKey->publicArea.objectAttributes.decrypt != SET)
   5100 26           return TPM_RC_ATTRIBUTES + RC_RSA_Encrypt_keyHandle;
   5101 27
   5102 28       // Is there a label?
   5103 29       if(in->label.t.size > 0)
   5104 30       {
   5105 31           // label is present, so make sure that is it NULL-terminated
   5106 32           if(in->label.t.buffer[in->label.t.size - 1] != 0)
   5107 33               return TPM_RC_VALUE + RC_RSA_Encrypt_label;
   5108 34           label = (char *)in->label.t.buffer;
   5109 35       }
   5110 36
   5111 37   // Command Output
   5112 38
   5113 39       // Select a scheme for encryption
   5114 40       scheme = CryptSelectRSAScheme(in->keyHandle, &in->inScheme);
   5115 41       if(scheme == NULL)
   5116 42           return TPM_RC_SCHEME + RC_RSA_Encrypt_inScheme;
   5117 43
   5118 44       // Encryption. TPM_RC_VALUE, or TPM_RC_SCHEME errors my be returned buy
   5119 45       // CryptEncyptRSA. Note: It can also return TPM_RC_ATTRIBUTES if the key does
   5120 46       // not have the decrypt attribute but that was checked above.
   5121 47       out->outData.t.size = sizeof(out->outData.t.buffer);
   5122 48       result = CryptEncryptRSA(&out->outData.t.size, out->outData.t.buffer, rsaKey,
   5123 
   5124      Family 2.0                                  TCG Published                                             Page 97
   5125      Level 00 Revision 01.16               Copyright  TCG 2006-2014                                 October 30, 2014
   5126      Part 3: Commands                                              Trusted Platform Module Library
   5128 
   5129 49                              scheme, in->message.t.size, in->message.t.buffer,
   5130 50                              label);
   5131 51       return result;
   5132 52   }
   5133 53   #endif
   5134 54   #endif // CC_RSA_Encrypt
   5135 
   5136 
   5137 
   5138 
   5139      Page 98                              TCG Published                              Family 2.0
   5140      October 30, 2014              Copyright  TCG 2006-2014             Level 00 Revision 01.16
   5141 Trusted Platform Module Library                                                        Part 3: Commands
   5143 
   5144 
   5145 14.3     TPM2_RSA_Decrypt
   5146 
   5147 14.3.1 General Description
   5148 
   5149 This command performs RSA decryption using the indicated padding scheme according to IETF RFC
   5150 3447 ((PKCS#1).
   5151 The scheme selection for this command is the same as for TPM2_RSA_Encrypt() and is shown in Table
   5152 41.
   5153 The key referenced by keyHandle shall be an RSA key (TPM_RC_KEY) with restricted CLEAR and
   5154 decrypt SET (TPM_RC_ATTRIBUTES).
   5155 This command uses the private key of keyHandle for this operation and authorization is required.
   5156 The TPM will perform a modular exponentiation of ciphertext using the private exponent associated with
   5157 keyHandle (this is described in IETF RFC 3447 (PKCS#1), clause 5.1.2). It will then validate the padding
   5158 according to the selected scheme. If the padding checks fail, TPM_RC_VALUE is returned. Otherwise,
   5159 the data is returned with the padding removed. If no padding is used, the returned value is an unsigned
   5160 integer value that is the result of the modular exponentiation of cipherText using the private exponent of
   5161 keyHandle. The returned value may include leading octets zeros so that it is the same size as the public
   5162 modulus. For the other padding schemes, the returned value will be smaller than the public modulus but
   5163 will contain all the data remaining after padding is removed and this may include leading zeros if the
   5164 original encrypted value contained leading zeros.
   5165 If a label is used in the padding process of the scheme during encryption, the label parameter is required
   5166 to be present in the decryption process and label is required to be the same in both cases. If label is not
   5167 the same, the decrypt operation is very likely to fail ((TPM_RC_VALUE). If label is present (label.size !=
   5168 0), it shall be a NULL-terminated string or the TPM will return TPM_RC_VALUE.
   5169 
   5170 NOTE 1          The size of label includes the terminating null.
   5171 
   5172 The message parameter in the response may be encrypted using parameter encryption.
   5173 If inScheme is used, and the scheme requires a hash algorithm it may not be TPM_ALG_NULL.
   5174 If the scheme does not require a label, the value in label is not used but the size of the label field is
   5175 checked for consistency with the indicated data type (TPM2B_DATA). That is, the field may not be larger
   5176 than allowed for a TPM2B_DATA.
   5177 
   5178 
   5179 
   5180 
   5181 Family 2.0                                    TCG Published                                      Page 99
   5182 Level 00 Revision 01.16                 Copyright  TCG 2006-2014                      October 30, 2014
   5183 Part 3: Commands                                                   Trusted Platform Module Library
   5185 
   5186 
   5187 
   5188 14.3.2 Command and Response
   5189 
   5190                        Table 45  TPM2_RSA_Decrypt Command
   5191 Type                    Name                  Description
   5192 
   5193 TPMI_ST_COMMAND_TAG     tag                   TPM_ST_SESSIONS
   5194 UINT32                  commandSize
   5195 TPM_CC                  commandCode           TPM_CC_RSA_Decrypt
   5196 
   5197                                               RSA key to use for decryption
   5198 TPMI_DH_OBJECT          @keyHandle            Auth Index: 1
   5199                                               Auth Role: USER
   5200 
   5201                                               cipher text to be decrypted
   5202 TPM2B_PUBLIC_KEY_RSA    cipherText            NOTE       An encrypted RSA data block is the size of the
   5203                                                          public modulus.
   5204 
   5205                                               the padding scheme to use if scheme associated with
   5206 TPMT_RSA_DECRYPT+       inScheme
   5207                                               keyHandle is TPM_ALG_NULL
   5208                                               label whose association with the message is to be
   5209 TPM2B_DATA              label
   5210                                               verified
   5211 
   5212 
   5213                        Table 46  TPM2_RSA_Decrypt Response
   5214 Type                    Name                  Description
   5215 
   5216 TPM_ST                  tag                   see clause 6
   5217 UINT32                  responseSize
   5218 TPM_RC                  responseCode
   5219 
   5220 TPM2B_PUBLIC_KEY_RSA    message               decrypted output
   5221 
   5222 
   5223 
   5224 
   5225 Page 100                               TCG Published                                       Family 2.0
   5226 October 30, 2014                Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   5227      Trusted Platform Module Library                                                                   Part 3: Commands
   5229 
   5230 
   5231 
   5232      14.3.3 Detailed Actions
   5233 
   5234 1    #include "InternalRoutines.h"
   5235 2    #include "RSA_Decrypt_fp.h"
   5236 3    #ifdef TPM_CC_RSA_Decrypt // Conditional expansion of this file
   5237 4    #ifdef TPM_ALG_RSA
   5238 
   5239 
   5240      Error Returns                     Meaning
   5241 
   5242      TPM_RC_BINDING                    The public an private parts of the key are not properly bound
   5243      TPM_RC_KEY                        keyHandle does not reference an unrestricted decrypt key
   5244      TPM_RC_SCHEME                     incorrect input scheme, or the chosen scheme is not a valid RSA
   5245                                        decrypt scheme
   5246      TPM_RC_SIZE                       cipherText is not the size of the modulus of key referenced by
   5247                                        keyHandle
   5248      TPM_RC_VALUE                      label is not a null terminated string or the value of cipherText is
   5249                                        greater that the modulus of keyHandle
   5250 
   5251  5   TPM_RC
   5252  6   TPM2_RSA_Decrypt(
   5253  7       RSA_Decrypt_In        *in,                   // IN: input parameter list
   5254  8       RSA_Decrypt_Out       *out                   // OUT: output parameter list
   5255  9       )
   5256 10   {
   5257 11       TPM_RC                             result;
   5258 12       OBJECT                            *rsaKey;
   5259 13       TPMT_RSA_DECRYPT                  *scheme;
   5260 14       char                              *label = NULL;
   5261 15
   5262 16   // Input Validation
   5263 17
   5264 18       rsaKey = ObjectGet(in->keyHandle);
   5265 19
   5266 20       // The selected key must be an RSA key
   5267 21       if(rsaKey->publicArea.type != TPM_ALG_RSA)
   5268 22           return TPM_RC_KEY + RC_RSA_Decrypt_keyHandle;
   5269 23
   5270 24       // The selected key must be an unrestricted decryption key
   5271 25       if(   rsaKey->publicArea.objectAttributes.restricted == SET
   5272 26          || rsaKey->publicArea.objectAttributes.decrypt == CLEAR)
   5273 27           return TPM_RC_ATTRIBUTES + RC_RSA_Decrypt_keyHandle;
   5274 28
   5275 29       //   NOTE: Proper operation of this command requires that the sensitive area
   5276 30       //   of the key is loaded. This is assured because authorization is required
   5277 31       //   to use the sensitive area of the key. In order to check the authorization,
   5278 32       //   the sensitive area has to be loaded, even if authorization is with policy.
   5279 33
   5280 34       // If label is present, make sure that it is a NULL-terminated string
   5281 35       if(in->label.t.size > 0)
   5282 36       {
   5283 37           // Present, so make sure that it is NULL-terminated
   5284 38           if(in->label.t.buffer[in->label.t.size - 1] != 0)
   5285 39               return TPM_RC_VALUE + RC_RSA_Decrypt_label;
   5286 40           label = (char *)in->label.t.buffer;
   5287 41       }
   5288 42
   5289 43   // Command Output
   5290 44
   5291 45       // Select a scheme for decrypt.
   5292 46       scheme = CryptSelectRSAScheme(in->keyHandle, &in->inScheme);
   5293 
   5294      Family 2.0                                   TCG Published                                             Page 101
   5295      Level 00 Revision 01.16                Copyright  TCG 2006-2014                                  October 30, 2014
   5296      Part 3: Commands                                               Trusted Platform Module Library
   5298 
   5299 47      if(scheme == NULL)
   5300 48          return TPM_RC_SCHEME + RC_RSA_Decrypt_inScheme;
   5301 49
   5302 50      // Decryption. TPM_RC_VALUE, TPM_RC_SIZE, and TPM_RC_KEY error may be
   5303 51      // returned by CryptDecryptRSA.
   5304 52      // NOTE: CryptDecryptRSA can also return TPM_RC_ATTRIBUTES or TPM_RC_BINDING
   5305 53      // when the key is not a decryption key but that was checked above.
   5306 54      out->message.t.size = sizeof(out->message.t.buffer);
   5307 55      result = CryptDecryptRSA(&out->message.t.size, out->message.t.buffer, rsaKey,
   5308 56                               scheme, in->cipherText.t.size,
   5309 57                               in->cipherText.t.buffer,
   5310 58                               label);
   5311 59
   5312 60       return result;
   5313 61   }
   5314 62   #endif
   5315 63   #endif // CC_RSA_Decrypt
   5316 
   5317 
   5318 
   5319 
   5320      Page 102                              TCG Published                                Family 2.0
   5321      October 30, 2014               Copyright  TCG 2006-2014             Level 00 Revision 01.16
   5322 Trusted Platform Module Library                                                                Part 3: Commands
   5324 
   5325 
   5326 14.4   TPM2_ECDH_KeyGen
   5327 
   5328 14.4.1 General Description
   5329 
   5330 This command uses the TPM to generate an ephemeral key pair ( de, Qe where Qe  [de]G). It uses the
   5331 private ephemeral key and a loaded public key (QS) to compute the shared secret value (P  [hde]QS).
   5332 keyHandle shall refer to a loaded ECC key. The sensitive portion of this key need not be loaded.
   5333 The curve parameters of the loaded ECC key are used to generate the ephemeral key.
   5334 
   5335 NOTE 1          This function is the equivalent of encrypting data to another objects public key. The seed value is
   5336                 used in a KDF to generate a symmetric key and that key is used to encrypt the data. Once the data
   5337                 is encrypted and the symmetric key discarded, only the ob ject with the private portion of the
   5338                 keyHandle will be able to decrypt it.
   5339 
   5340 The zPoint in the response may be encrypted using parameter encryption.
   5341 
   5342 
   5343 
   5344 
   5345 Family 2.0                                   TCG Published                                            Page 103
   5346 Level 00 Revision 01.16                Copyright  TCG 2006-2014                              October 30, 2014
   5347 Part 3: Commands                                                 Trusted Platform Module Library
   5349 
   5350 
   5351 
   5352 14.4.2 Command and Response
   5353 
   5354                       Table 47  TPM2_ECDH_KeyGen Command
   5355 Type                   Name                  Description
   5356 
   5357                                              TPM_ST_SESSIONS if an audit or encrypt session is
   5358 TPMI_ST_COMMAND_TAG    tag
   5359                                              present; otherwise, TPM_ST_NO_SESSIONS
   5360 UINT32                 commandSize
   5361 TPM_CC                 commandCode           TPM_CC_ECDH_KeyGen
   5362 
   5363                                              Handle of a loaded ECC key public area.
   5364 TPMI_DH_OBJECT         keyHandle
   5365                                              Auth Index: None
   5366 
   5367 
   5368                       Table 48  TPM2_ECDH_KeyGen Response
   5369 Type                   Name                  Description
   5370 
   5371 TPM_ST                 tag                   see clause 6
   5372 UINT32                 responseSize
   5373 TPM_RC                 responseCode
   5374 
   5375 TPM2B_ECC_POINT        zPoint                results of P  h[de]Qs
   5376 
   5377 TPM2B_ECC_POINT        pubPoint              generated ephemeral public point (Qe)
   5378 
   5379 
   5380 
   5381 
   5382 Page 104                              TCG Published                                    Family 2.0
   5383 October 30, 2014             Copyright  TCG 2006-2014                  Level 00 Revision 01.16
   5384      Trusted Platform Module Library                                                            Part 3: Commands
   5386 
   5387 
   5388 
   5389      14.4.3 Detailed Actions
   5390 
   5391 1    #include "InternalRoutines.h"
   5392 2    #include "ECDH_KeyGen_fp.h"
   5393 3    #ifdef TPM_CC_ECDH_KeyGen // Conditional expansion of this file
   5394 4    #ifdef TPM_ALG_ECC
   5395 
   5396 
   5397      Error Returns                     Meaning
   5398 
   5399      TPM_RC_KEY                        keyHandle does not reference a non-restricted decryption ECC key
   5400 
   5401  5   TPM_RC
   5402  6   TPM2_ECDH_KeyGen(
   5403  7       ECDH_KeyGen_In        *in,                 // IN: input parameter list
   5404  8       ECDH_KeyGen_Out       *out                 // OUT: output parameter list
   5405  9       )
   5406 10   {
   5407 11       OBJECT                    *eccKey;
   5408 12       TPM2B_ECC_PARAMETER        sensitive;
   5409 13       TPM_RC                     result;
   5410 14
   5411 15   // Input Validation
   5412 16
   5413 17       eccKey = ObjectGet(in->keyHandle);
   5414 18
   5415 19       // Input key must be a non-restricted, decrypt ECC key
   5416 20       if(   eccKey->publicArea.type != TPM_ALG_ECC)
   5417 21           return TPM_RCS_KEY + RC_ECDH_KeyGen_keyHandle;
   5418 22
   5419 23       if(     eccKey->publicArea.objectAttributes.restricted == SET
   5420 24          ||   eccKey->publicArea.objectAttributes.decrypt != SET
   5421 25         )
   5422 26           return TPM_RC_KEY + RC_ECDH_KeyGen_keyHandle;
   5423 27
   5424 28   // Command Output
   5425 29       do
   5426 30       {
   5427 31           // Create ephemeral ECC key
   5428 32           CryptNewEccKey(eccKey->publicArea.parameters.eccDetail.curveID,
   5429 33                          &out->pubPoint.t.point, &sensitive);
   5430 34
   5431 35           out->pubPoint.t.size = TPMS_ECC_POINT_Marshal(&out->pubPoint.t.point,
   5432 36                                  NULL, NULL);
   5433 37
   5434 38           // Compute Z
   5435 39           result = CryptEccPointMultiply(&out->zPoint.t.point,
   5436 40                                      eccKey->publicArea.parameters.eccDetail.curveID,
   5437 41                                      &sensitive, &eccKey->publicArea.unique.ecc);
   5438 42           // The point in the key is not on the curve. Indicate that the key is bad.
   5439 43           if(result == TPM_RC_ECC_POINT)
   5440 44               return TPM_RC_KEY + RC_ECDH_KeyGen_keyHandle;
   5441 45           // The other possible error is TPM_RC_NO_RESULT indicating that the
   5442 46           // multiplication resulted in the point at infinity, so get a new
   5443 47           // random key and start over (hardly ever happens).
   5444 48       }
   5445 49       while(result == TPM_RC_NO_RESULT);
   5446 50
   5447 51       if(result == TPM_RC_SUCCESS)
   5448 52           // Marshal the values to generate the point.
   5449 53           out->zPoint.t.size = TPMS_ECC_POINT_Marshal(&out->zPoint.t.point,
   5450 54                                                       NULL, NULL);
   5451 55
   5452 56       return result;
   5453 
   5454      Family 2.0                                  TCG Published                                          Page 105
   5455      Level 00 Revision 01.16               Copyright  TCG 2006-2014                            October 30, 2014
   5456      Part 3: Commands                                       Trusted Platform Module Library
   5458 
   5459 57   }
   5460 58   #endif
   5461 59   #endif // CC_ECDH_KeyGen
   5462 
   5463 
   5464 
   5465 
   5466      Page 106                        TCG Published                            Family 2.0
   5467      October 30, 2014           Copyright  TCG 2006-2014        Level 00 Revision 01.16
   5468 Trusted Platform Module Library                                                         Part 3: Commands
   5470 
   5471 
   5472 14.5   TPM2_ECDH_ZGen
   5473 
   5474 14.5.1 General Description
   5475 
   5476 This command uses the TPM to recover the Z value from a public point (QB) and a private key (ds). It will
   5477 perform the multiplication of the provided inPoint (QB) with the private key (ds) and return the coordinates
   5478 of the resultant point (Z = (xZ , yZ)  [hds]QB; where h is the cofactor of the curve).
   5479 keyHandle shall refer to a loaded, ECC key (TPM_RC_KEY) with the restricted attribute CLEAR and the
   5480 decrypt attribute SET (TPM_RC_ATTRIBUTES).
   5481 The scheme of the key referenced by keyHandle is required to be either TPM_ALG_ECDH or
   5482 TPM_ALG_NULL (TPM_RC_SCHEME).
   5483 inPoint is required to be on the curve of the key referenced by keyHandle (TPM_RC_ECC_POINT).
   5484 The parameters of the key referenced by keyHandle are used to perform the point multiplication.
   5485 
   5486 
   5487 
   5488 
   5489 Family 2.0                                 TCG Published                                       Page 107
   5490 Level 00 Revision 01.16              Copyright  TCG 2006-2014                          October 30, 2014
   5491 Part 3: Commands                                                   Trusted Platform Module Library
   5493 
   5494 
   5495 
   5496 14.5.2 Command and Response
   5497 
   5498                       Table 49  TPM2_ECDH_ZGen Command
   5499 Type                   Name                  Description
   5500 
   5501 TPMI_ST_COMMAND_TAG    tag                   TPM_ST_SESSIONS
   5502 UINT32                 commandSize
   5503 TPM_CC                 commandCode           TPM_CC_ECDH_ZGen
   5504 
   5505                                              handle of a loaded ECC key
   5506 TPMI_DH_OBJECT         @keyHandle            Auth Index: 1
   5507                                              Auth Role: USER
   5508 
   5509 TPM2B_ECC_POINT        inPoint               a public key
   5510 
   5511 
   5512                       Table 50  TPM2_ECDH_ZGen Response
   5513 Type                   Name                  Description
   5514 
   5515 TPM_ST                 tag                   see clause 6
   5516 UINT32                 responseSize
   5517 TPM_RC                 responseCode
   5518 
   5519                                              X and Y coordinates of the product of the multiplication
   5520 TPM2B_ECC_POINT        outPoint
   5521                                              Z = (xZ , yZ)  [hdS]QB
   5522 
   5523 
   5524 
   5525 
   5526 Page 108                              TCG Published                                     Family 2.0
   5527 October 30, 2014             Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   5528      Trusted Platform Module Library                                                               Part 3: Commands
   5530 
   5531 
   5532 
   5533      14.5.3 Detailed Actions
   5534 
   5535 1    #include "InternalRoutines.h"
   5536 2    #include "ECDH_ZGen_fp.h"
   5537 3    #ifdef TPM_CC_ECDH_ZGen // Conditional expansion of this file
   5538 4    #ifdef TPM_ALG_ECC
   5539 
   5540 
   5541      Error Returns                     Meaning
   5542 
   5543      TPM_RC_ATTRIBUTES                 key referenced by keyA is restricted or not a decrypt key
   5544      TPM_RC_KEY                        key referenced by keyA is not an ECC key
   5545      TPM_RC_NO_RESULT                  multiplying inPoint resulted in a point at infinity
   5546      TPM_RC_SCHEME                     the scheme of the key referenced by keyA is not TPM_ALG_NULL,
   5547                                        TPM_ALG_ECDH,
   5548 
   5549  5   TPM_RC
   5550  6   TPM2_ECDH_ZGen(
   5551  7       ECDH_ZGen_In      *in,                  // IN: input parameter list
   5552  8       ECDH_ZGen_Out     *out                  // OUT: output parameter list
   5553  9       )
   5554 10   {
   5555 11       TPM_RC                     result;
   5556 12       OBJECT                    *eccKey;
   5557 13
   5558 14   // Input Validation
   5559 15
   5560 16       eccKey = ObjectGet(in->keyHandle);
   5561 17
   5562 18       // Input key must be a non-restricted, decrypt ECC key
   5563 19       if(   eccKey->publicArea.type != TPM_ALG_ECC)
   5564 20           return TPM_RCS_KEY + RC_ECDH_ZGen_keyHandle;
   5565 21
   5566 22       if(     eccKey->publicArea.objectAttributes.restricted == SET
   5567 23          ||   eccKey->publicArea.objectAttributes.decrypt != SET
   5568 24         )
   5569 25           return TPM_RC_KEY + RC_ECDH_ZGen_keyHandle;
   5570 26
   5571 27       // Make sure the scheme allows this use
   5572 28       if(     eccKey->publicArea.parameters.eccDetail.scheme.scheme != TPM_ALG_ECDH
   5573 29           && eccKey->publicArea.parameters.eccDetail.scheme.scheme != TPM_ALG_NULL)
   5574 30           return TPM_RC_SCHEME + RC_ECDH_ZGen_keyHandle;
   5575 31
   5576 32   // Command Output
   5577 33
   5578 34       // Compute Z. TPM_RC_ECC_POINT or TPM_RC_NO_RESULT may be returned here.
   5579 35       result = CryptEccPointMultiply(&out->outPoint.t.point,
   5580 36                                      eccKey->publicArea.parameters.eccDetail.curveID,
   5581 37                                      &eccKey->sensitive.sensitive.ecc,
   5582 38                                      &in->inPoint.t.point);
   5583 39       if(result != TPM_RC_SUCCESS)
   5584 40           return RcSafeAddToResult(result, RC_ECDH_ZGen_inPoint);
   5585 41
   5586 42       out->outPoint.t.size = TPMS_ECC_POINT_Marshal(&out->outPoint.t.point,
   5587 43                                                     NULL, NULL);
   5588 44
   5589 45       return TPM_RC_SUCCESS;
   5590 46   }
   5591 47   #endif
   5592 48   #endif // CC_ECDH_ZGen
   5593 
   5594 
   5595 
   5596      Family 2.0                                    TCG Published                                        Page 109
   5597      Level 00 Revision 01.16                Copyright  TCG 2006-2014                              October 30, 2014
   5598 Part 3: Commands                                                       Trusted Platform Module Library
   5600 
   5601 
   5602 14.6   TPM2_ECC_Parameters
   5603 
   5604 14.6.1 General Description
   5605 
   5606 This command returns the parameters of an ECC curve identified by its TCG-assigned curveID.
   5607 
   5608 14.6.2 Command and Response
   5609 
   5610                           Table 51  TPM2_ECC_Parameters Command
   5611 Type                              Name                  Description
   5612 
   5613                                                         TPM_ST_SESSIONS if an audit session is
   5614 TPMI_ST_COMMAND_TAG               tag
   5615                                                         present; otherwise, TPM_ST_NO_SESSIONS
   5616 UINT32                            commandSize
   5617 TPM_CC                            commandCode           TPM_CC_ECC_Parameters
   5618 
   5619 TPMI_ECC_CURVE                    curveID               parameter set selector
   5620 
   5621 
   5622                           Table 52  TPM2_ECC_Parameters Response
   5623 Type                              Name                  Description
   5624 
   5625 TPM_ST                            tag                   see clause 6
   5626 UINT32                            responseSize
   5627 TPM_RC                            responseCode
   5628 
   5629 TPMS_ALGORITHM_DETAIL_ECC         parameters            ECC parameters for the selected curve
   5630 
   5631 
   5632 
   5633 
   5634 Page 110                                    TCG Published                                   Family 2.0
   5635 October 30, 2014                   Copyright  TCG 2006-2014                     Level 00 Revision 01.16
   5636      Trusted Platform Module Library                                               Part 3: Commands
   5638 
   5639 
   5640 
   5641      14.6.3 Detailed Actions
   5642 
   5643 1    #include "InternalRoutines.h"
   5644 2    #include "ECC_Parameters_fp.h"
   5645 3    #ifdef TPM_CC_ECC_Parameters // Conditional expansion of this file
   5646 4    #ifdef TPM_ALG_ECC
   5647 
   5648 
   5649      Error Returns                     Meaning
   5650 
   5651      TPM_RC_VALUE                      Unsupported ECC curve ID
   5652 
   5653  5   TPM_RC
   5654  6   TPM2_ECC_Parameters(
   5655  7       ECC_Parameters_In     *in,                // IN: input parameter list
   5656  8       ECC_Parameters_Out    *out                // OUT: output parameter list
   5657  9       )
   5658 10   {
   5659 11   // Command Output
   5660 12
   5661 13       // Get ECC curve parameters
   5662 14       if(CryptEccGetParameters(in->curveID, &out->parameters))
   5663 15           return TPM_RC_SUCCESS;
   5664 16       else
   5665 17           return TPM_RC_VALUE + RC_ECC_Parameters_curveID;
   5666 18   }
   5667 19   #endif
   5668 20   #endif // CC_ECC_Parameters
   5669 
   5670 
   5671 
   5672 
   5673      Family 2.0                                 TCG Published                           Page 111
   5674      Level 00 Revision 01.16               Copyright  TCG 2006-2014               October 30, 2014
   5675 Part 3: Commands                                                                 Trusted Platform Module Library
   5677 
   5678 
   5679 
   5680 
   5681 14.7     TPM2_ZGen_2Phase
   5682 
   5683 14.7.1    General Description
   5684 
   5685 This command supports two-phase key exchange protocols. The command is used in combination with
   5686 TPM2_EC_Ephemeral(). TPM2_EC_Ephemeral() generates an ephemeral key and returns the public
   5687 point of that ephemeral key along with a numeric value that allows the TPM to regenerate the associated
   5688 private key.
   5689 The input parameters for this command are a static public key (inQsU), an ephemeral key (inQeU) from
   5690 party B, and the commitCounter returned by TPM2_EC_Ephemeral(). The TPM uses the counter value to
   5691 regenerate the ephemeral private key (de,V) and the associated public key (Qe,V). keyA provides the static
   5692 ephemeral elements ds,V and Qs,V. This provides the two pairs of ephemeral and static keys that are
   5693 required for the schemes supported by this command.
   5694 The TPM will compute Z or Zs and Ze according to the selected scheme. If the scheme is not a two-phase
   5695 key exchange scheme or if the scheme is not supported, the TPM will return TPM_RC_SCHEME.
   5696 It is an error if inQsB or inQeB are not on the curve of keyA (TPM_RC_ECC_POINT).
   5697 
   5698 The two-phase key schemes that were assigned an algorithm ID as of the time of the publication of this
   5699 specification are TPM_ALG_ECDH, TPM_ALG_ECMQV, and TPM_ALG_SM2.
   5700 
   5701 If this command is supported, then support for TPM_ALG_ECDH is required. Support for
   5702 TPM_ALG_ECMQV or TPM_ALG_SM2 is optional.
   5703 
   5704 NOTE 1          If SM2 is supported and this command is supported, then the implementation is required to support
   5705                 the key exchange protocol of SM2, part 3.
   5706 
   5707 
   5708 For TPM_ALG_ECDH outZ1 will be Zs and outZ2 will Ze as defined in 6.1.1.2 of SP800-56A.
   5709 
   5710 NOTE 2          An unrestricted decryption key using ECDH may be used in either TPM2_ECDH_ZGen() or
   5711                 TPM2_ZGen_2Phase as the computation done with the private part of keyA is the same in both
   5712                 cases.
   5713 
   5714 
   5715 For TPM_ALG_ECMQV or TPM_ALG_SM2 outZ1 will be Z and outZ2 will be an Empty Point.
   5716 
   5717 NOTE 3          An Empty Point has two Empty Buffers as coordinates meaning the minimum size value for outZ2
   5718                 will be four.
   5719 
   5720 
   5721 If the input scheme is TPM_ALG_ECDH, then outZ1 will be Zs and outZ2 will be Ze. For schemes like
   5722 MQV (including SM2), outZ1 will contain the computed value and outZ2 will be an Empty Point.
   5723 
   5724 NOTE            The Z values returned by the TPM are a full point and not just an x -coordinate.
   5725 
   5726 If a computation of either Z produces the point at infinity, then the corresponding Z value will be an Empty
   5727 Point.
   5728 
   5729 
   5730 
   5731 
   5732 Page 112                                        TCG Published                                      Family 2.0
   5733 October 30, 2014                       Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   5734 Trusted Platform Module Library                                                              Part 3: Commands
   5736 
   5737 
   5738 
   5739 14.7.2   Command and Response
   5740 
   5741                             Table 53  TPM2_ZGen_2Phase Command
   5742 Type                          Name                  Description
   5743 
   5744 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   5745 UINT32                        commandSize
   5746 TPM_CC                        commandCode           TPM_CC_ ZGen_2Phase
   5747 
   5748                                                     handle of an unrestricted decryption key ECC
   5749                                                     The private key referenced by this handle is used as dS,A
   5750 TPMI_DH_OBJECT                @keyA
   5751                                                     Auth Index: 1
   5752                                                     Auth Role: USER
   5753 
   5754 TPM2B_ECC_POINT               inQsB                 other partys static public key (Qs,B = (Xs,B, Ys,B))
   5755 
   5756 TPM2B_ECC_POINT               inQeB                 other party's ephemeral public key (Qe,B = (Xe,B, Ye,B))
   5757 TPMI_ECC_KEY_EXCHANGE         inScheme              the key exchange scheme
   5758 UINT16                        counter               value returned by TPM2_EC_Ephemeral()
   5759 
   5760 
   5761                             Table 54  TPM2_ZGen_2Phase Response
   5762 Type                          Name                  Description
   5763 
   5764 TPM_ST                        tag
   5765 UINT32                        responseSize
   5766 TPM_RC                        responseCode
   5767 
   5768                                                     X and Y coordinates of the computed value (scheme
   5769 TPM2B_ECC_POINT               outZ1
   5770                                                     dependent)
   5771                                                     X and Y coordinates of the second computed value
   5772 TPM2B_ECC_POINT               outZ2
   5773                                                     (scheme dependent)
   5774 
   5775 
   5776 
   5777 
   5778 Family 2.0                                 TCG Published                                              Page 113
   5779 Level 00 Revision 01.16               Copyright  TCG 2006-2014                              October 30, 2014
   5780      Part 3: Commands                                                               Trusted Platform Module Library
   5782 
   5783 
   5784 
   5785      14.7.3   Detailed Actions
   5786 
   5787 1    #include "InternalRoutines.h"
   5788 2    #include "ZGen_2Phase_fp.h"
   5789 3    #ifdef TPM_CC_ZGen_2Phase // Conditional expansion of this file
   5790 
   5791      This command uses the TPM to recover one or two Z values in a two phase key exchange protocol
   5792 
   5793      Error Returns                    Meaning
   5794 
   5795      TPM_RC_ATTRIBUTES                key referenced by keyA is restricted or not a decrypt key
   5796      TPM_RC_ECC_POINT                 inQsB or inQeB is not on the curve of the key reference by keyA
   5797      TPM_RC_KEY                       key referenced by keyA is not an ECC key
   5798      TPM_RC_SCHEME                    the scheme of the key referenced by keyA is not TPM_ALG_NULL,
   5799                                       TPM_ALG_ECDH, TPM_ALG_ECMQV or TPM_ALG_SM2
   5800 
   5801  4   TPM_RC
   5802  5   TPM2_ZGen_2Phase(
   5803  6       ZGen_2Phase_In        *in,                 // IN: input parameter list
   5804  7       ZGen_2Phase_Out       *out                 // OUT: output parameter list
   5805  8       )
   5806  9   {
   5807 10       TPM_RC                    result;
   5808 11       OBJECT                   *eccKey;
   5809 12       TPM2B_ECC_PARAMETER       r;
   5810 13       TPM_ALG_ID                scheme;
   5811 14
   5812 15   // Input Validation
   5813 16
   5814 17       eccKey = ObjectGet(in->keyA);
   5815 18
   5816 19       // keyA must be an ECC key
   5817 20       if(eccKey->publicArea.type != TPM_ALG_ECC)
   5818 21           return TPM_RC_KEY + RC_ZGen_2Phase_keyA;
   5819 22
   5820 23       // keyA must not be restricted and must be a decrypt key
   5821 24       if(   eccKey->publicArea.objectAttributes.restricted == SET
   5822 25          || eccKey->publicArea.objectAttributes.decrypt != SET
   5823 26         )
   5824 27           return TPM_RC_ATTRIBUTES + RC_ZGen_2Phase_keyA;
   5825 28
   5826 29       // if the scheme of keyA is TPM_ALG_NULL, then use the input scheme; otherwise
   5827 30       // the input scheme must be the same as the scheme of keyA
   5828 31       scheme = eccKey->publicArea.parameters.asymDetail.scheme.scheme;
   5829 32       if(scheme != TPM_ALG_NULL)
   5830 33       {
   5831 34           if(scheme != in->inScheme)
   5832 35               return TPM_RC_SCHEME + RC_ZGen_2Phase_inScheme;
   5833 36       }
   5834 37       else
   5835 38           scheme = in->inScheme;
   5836 39       if(scheme == TPM_ALG_NULL)
   5837 40           return TPM_RC_SCHEME + RC_ZGen_2Phase_inScheme;
   5838 41
   5839 42       // Input points must be on the curve of keyA
   5840 43       if(!CryptEccIsPointOnCurve(eccKey->publicArea.parameters.eccDetail.curveID,
   5841 44                                  &in->inQsB.t.point))
   5842 45           return TPM_RC_ECC_POINT + RC_ZGen_2Phase_inQsB;
   5843 46
   5844 47       if(!CryptEccIsPointOnCurve(eccKey->publicArea.parameters.eccDetail.curveID,
   5845 48                                  &in->inQeB.t.point))
   5846 
   5847 
   5848      Page 114                                      TCG Published                                        Family 2.0
   5849      October 30, 2014                     Copyright  TCG 2006-2014                       Level 00 Revision 01.16
   5850      Trusted Platform Module Library                                             Part 3: Commands
   5852 
   5853 49           return TPM_RC_ECC_POINT + RC_ZGen_2Phase_inQeB;
   5854 50
   5855 51       if(!CryptGenerateR(&r, &in->counter,
   5856 52                          eccKey->publicArea.parameters.eccDetail.curveID,
   5857 53                          NULL))
   5858 54               return TPM_RC_VALUE + RC_ZGen_2Phase_counter;
   5859 55
   5860 56   // Command Output
   5861 57
   5862 58       result = CryptEcc2PhaseKeyExchange(&out->outZ1.t.point,
   5863 59                                       &out->outZ2.t.point,
   5864 60                                       eccKey->publicArea.parameters.eccDetail.curveID,
   5865 61                                       scheme,
   5866 62                                       &eccKey->sensitive.sensitive.ecc,
   5867 63                                       &r,
   5868 64                                       &in->inQsB.t.point,
   5869 65                                       &in->inQeB.t.point);
   5870 66       if(result == TPM_RC_SCHEME)
   5871 67           return TPM_RC_SCHEME + RC_ZGen_2Phase_inScheme;
   5872 68
   5873 69       if(result == TPM_RC_SUCCESS)
   5874 70           CryptEndCommit(in->counter);
   5875 71
   5876 72       return result;
   5877 73   }
   5878 74   #endif
   5879 
   5880 
   5881 
   5882 
   5883      Family 2.0                           TCG Published                                   Page 115
   5884      Level 00 Revision 01.16           Copyright  TCG 2006-2014                 October 30, 2014
   5885 Part 3: Commands                                                        Trusted Platform Module Library
   5887 
   5888 
   5889 15     Symmetric Primitives
   5890 
   5891 15.1    Introduction
   5892 
   5893 The commands in this clause provide low-level primitives for access to the symmetric algorithms
   5894 implemented in the TPM that operate on blocks of data. These include symmetric encryption and
   5895 decryption as well as hash and HMAC. All of the commands in this group are stateless. That is, they have
   5896 no persistent state that is retained in the TPM when the command is complete.
   5897 For hashing, HMAC, and Events that require large blocks of data with retained state, the sequence
   5898 commands are provided (see clause 1).
   5899 Some of the symmetric encryption/decryption modes use an IV. When an IV is used, it may be an
   5900 initiation value or a chained value from a previous stage. The chaining for each mode is:
   5901 
   5902 
   5903 
   5904 
   5905 Page 116                                   TCG Published                                   Family 2.0
   5906 October 30, 2014                    Copyright  TCG 2006-2014                 Level 00 Revision 01.16
   5907 Trusted Platform Module Library                                                                          Part 3: Commands
   5909 
   5910                                Table 55  Symmetric Chaining Process
   5911 Mode                 Chaining process
   5912 
   5913 TPM_ALG_CTR          The TPM will increment the entire IV provided by the caller. The next count value will be
   5914                      returned to the caller as ivOut. This can be the input value to the next encrypt or decrypt
   5915                      operation.
   5916                      ivIn is required to be the size of a block encrypted by the selected algorithm and key
   5917                      combination. If the size of ivIn is not correct, the TPM shall return TPM_RC_SIZE.
   5918                      EXAMPLE 1 AES requires that ivIn be 128 bits (16 octets).
   5919                      ivOut will be the size of a cipher block and not the size of the last encrypted block.
   5920                      NOTE         ivOut will be the value of the counter after the last block is encrypted.
   5921                      EXAMPLE 2 If ivIn were 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0016 and four data blocks
   5922                                    were encrypted, ivOut will have a value of
   5923                                    00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0416.
   5924                      All the bits of the IV are incremented as if it were an unsigned integer.
   5925 TPM_ALG_OFB          In Output Feedback (OFB), the output of the pseudo-random function (the block encryption
   5926                      algorithm) is XORed with a plaintext block to produce a ciphertext block. ivOut will be the
   5927                      value that was XORed with the last plaintext block. That value can be used as the ivIn for a
   5928                      next buffer.
   5929                      ivIn is required to be the size of a block encrypted by the selected algorithm and key
   5930                      combination. If the size of ivIn is not correct, the TPM shall return TPM_RC_SIZE.
   5931                      ivOut will be the size of a cipher block and not the size of the last encrypted block.
   5932 TPM_ALG_CBC          For Cipher Block Chaining (CBC), a block of ciphertext is XORed with the next plaintext
   5933                      block and that block is encrypted. The encrypted block is then input to the encryption of the
   5934                      next block. The last ciphertext block then is used as an IV for the next buffer.
   5935                      Even though the last ciphertext block is evident in the encrypted data, it is also returned in
   5936                      ivOut.
   5937                      ivIn is required to be the size of a block encrypted by the selected algorithm and key
   5938                      combination. If the size of ivIn is not correct, the TPM shall return TPM_RC_SIZE.
   5939                      inData is required to be an even multiple of the block encrypted by the selected algorithm
   5940                      and key combination. If the size of inData is not correct, the TPM shall return
   5941                      TPM_RC_SIZE.
   5942 TPM_ALG_CFB          Similar to CBC in that the last ciphertext block is an input to the encryption of the next block.
   5943                      ivOut will be the value that was XORed with the last plaintext block. That value can be used
   5944                      as the ivIn for a next buffer.
   5945                      ivIn is required to be the size of a block encrypted by the selected algorithm and key
   5946                      combination. If the size of ivIn is not correct, the TPM shall return TPM_RC_SIZE.
   5947                      ivOut will be the size of a cipher block and not the size of the last encrypted block.
   5948 TPM_ALG_ECB          Electronic Codebook (ECB) has no chaining. Each block of plaintext is encrypted using the
   5949                      key. ECB does not support chaining and ivIn shall be the Empty Buffer. ivOut will be the
   5950                      Empty Buffer.
   5951                      inData is required to be an even multiple of the block encrypted by the selected algorithm
   5952                      and key combination. If the size of inData is not correct, the TPM shall return
   5953                      TPM_RC_SIZE.
   5954 
   5955 
   5956 
   5957 
   5958 Family 2.0                                     TCG Published                                                  Page 117
   5959 Level 00 Revision 01.16                Copyright  TCG 2006-2014                                         October 30, 2014
   5960 Part 3: Commands                                                    Trusted Platform Module Library
   5962 
   5963 
   5964 
   5965 15.2   TPM2_EncryptDecrypt
   5966 
   5967 15.2.1 General Description
   5968 
   5969 This command performs symmetric encryption or decryption.
   5970 keyHandle shall reference a symmetric cipher object (TPM_RC_KEY).
   5971 For a restricted key, mode shall be either the same as the mode of the key, or TPM_ALG_NULL
   5972 (TPM_RC_VALUE). For an unrestricted key, mode may be the same or different from the mode of the key
   5973 but both shall not be TPM_ALG_NULL (TPM_RC_VALUE). If different, mode overrides the mode of the
   5974 key.
   5975 If the TPM allows this command to be canceled before completion, then the TPM may produce
   5976 incremental results and return TPM_RC_SUCCESS rather than TPM_RC_CANCELED. In such case,
   5977 outData may be less than inData.
   5978 
   5979 
   5980 
   5981 
   5982 Page 118                                 TCG Published                                Family 2.0
   5983 October 30, 2014                  Copyright  TCG 2006-2014               Level 00 Revision 01.16
   5984 Trusted Platform Module Library                                                           Part 3: Commands
   5986 
   5987 
   5988 
   5989 15.2.2 Command and Response
   5990 
   5991                            Table 56  TPM2_EncryptDecrypt Command
   5992 Type                          Name                  Description
   5993 
   5994 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   5995 UINT32                        commandSize
   5996 TPM_CC                        commandCode           TPM_CC_EncryptDecrypt
   5997 
   5998                                                     the symmetric key used for the operation
   5999 TPMI_DH_OBJECT                @keyHandle            Auth Index: 1
   6000                                                     Auth Role: USER
   6001 
   6002                                                     if YES, then the operation is decryption; if NO, the
   6003 TPMI_YES_NO                   decrypt
   6004                                                     operation is encryption
   6005                                                     symmetric mode
   6006 TPMI_ALG_SYM_MODE+            mode                  For a restricted key, this field shall match the default
   6007                                                     mode of the key or be TPM_ALG_NULL.
   6008 TPM2B_IV                      ivIn                  an initial value as required by the algorithm
   6009 TPM2B_MAX_BUFFER              inData                the data to be encrypted/decrypted
   6010 
   6011 
   6012                            Table 57  TPM2_EncryptDecrypt Response
   6013 Type                          Name                  Description
   6014 
   6015 TPM_ST                        tag                   see clause 6
   6016 UINT32                        responseSize
   6017 TPM_RC                        responseCode
   6018 
   6019 TPM2B_MAX_BUFFER              outData               encrypted or decrypted output
   6020 TPM2B_IV                      ivOut                 chaining value to use for IV in next round
   6021 
   6022 
   6023 
   6024 
   6025 Family 2.0                                 TCG Published                                          Page 119
   6026 Level 00 Revision 01.16               Copyright  TCG 2006-2014                           October 30, 2014
   6027      Part 3: Commands                                                               Trusted Platform Module Library
   6029 
   6030 
   6031 
   6032      15.2.3 Detailed Actions
   6033 
   6034 1    #include "InternalRoutines.h"
   6035 2    #include "EncryptDecrypt_fp.h"
   6036 3    #ifdef TPM_CC_EncryptDecrypt // Conditional expansion of this file
   6037 
   6038 
   6039      Error Returns                   Meaning
   6040 
   6041      TPM_RC_KEY                      is not a symmetric decryption key with both public and private
   6042                                      portions loaded
   6043      TPM_RC_SIZE                     IvIn size is incompatible with the block cipher mode; or inData size is
   6044                                      not an even multiple of the block size for CBC or ECB mode
   6045      TPM_RC_VALUE                    keyHandle is restricted and the argument mode does not match the
   6046                                      key's mode
   6047 
   6048  4   TPM_RC
   6049  5   TPM2_EncryptDecrypt(
   6050  6       EncryptDecrypt_In    *in,                 // IN: input parameter list
   6051  7       EncryptDecrypt_Out   *out                 // OUT: output parameter list
   6052  8       )
   6053  9   {
   6054 10       OBJECT               *symKey;
   6055 11       UINT16               keySize;
   6056 12       UINT16               blockSize;
   6057 13       BYTE                 *key;
   6058 14       TPM_ALG_ID           alg;
   6059 15
   6060 16   // Input Validation
   6061 17       symKey = ObjectGet(in->keyHandle);
   6062 18
   6063 19       // The input key should be a symmetric decrypt key.
   6064 20       if(    symKey->publicArea.type != TPM_ALG_SYMCIPHER
   6065 21          || symKey->attributes.publicOnly == SET)
   6066 22           return TPM_RC_KEY + RC_EncryptDecrypt_keyHandle;
   6067 23
   6068 24       // If the input mode is TPM_ALG_NULL, use the key's mode
   6069 25       if( in->mode == TPM_ALG_NULL)
   6070 26           in->mode = symKey->publicArea.parameters.symDetail.sym.mode.sym;
   6071 27
   6072 28       // If the key is restricted, the input symmetric mode should match the key's
   6073 29       // symmetric mode
   6074 30       if(   symKey->publicArea.objectAttributes.restricted == SET
   6075 31          && symKey->publicArea.parameters.symDetail.sym.mode.sym != in->mode)
   6076 32           return TPM_RC_VALUE + RC_EncryptDecrypt_mode;
   6077 33
   6078 34       // If the mode is null, then we have a problem.
   6079 35       // Note: Construction of a TPMT_SYM_DEF does not allow the 'mode' to be
   6080 36       // TPM_ALG_NULL so setting in->mode to the mode of the key should have
   6081 37       // produced a valid mode. However, this is suspenders.
   6082 38       if(in->mode == TPM_ALG_NULL)
   6083 39           return TPM_RC_VALUE + RC_EncryptDecrypt_mode;
   6084 40
   6085 41       // The input iv for ECB mode should be null. All the other modes should
   6086 42       // have an iv size same as encryption block size
   6087 43
   6088 44       keySize = symKey->publicArea.parameters.symDetail.sym.keyBits.sym;
   6089 45       alg = symKey->publicArea.parameters.symDetail.sym.algorithm;
   6090 46       blockSize = CryptGetSymmetricBlockSize(alg, keySize);
   6091 47       if(   (in->mode == TPM_ALG_ECB && in->ivIn.t.size != 0)
   6092 48          || (in->mode != TPM_ALG_ECB && in->ivIn.t.size != blockSize))
   6093 49           return TPM_RC_SIZE + RC_EncryptDecrypt_ivIn;
   6094 
   6095      Page 120                                     TCG Published                                           Family 2.0
   6096      October 30, 2014                    Copyright  TCG 2006-2014                         Level 00 Revision 01.16
   6097      Trusted Platform Module Library                                             Part 3: Commands
   6099 
   6100 50
   6101 51       // The input data size of CBC mode or ECB mode must be an even multiple of
   6102 52       // the symmetric algorithm's block size
   6103 53       if(   (in->mode == TPM_ALG_CBC || in->mode == TPM_ALG_ECB)
   6104 54          && (in->inData.t.size % blockSize) != 0)
   6105 55           return TPM_RC_SIZE + RC_EncryptDecrypt_inData;
   6106 56
   6107 57       // Copy IV
   6108 58       // Note: This is copied here so that the calls to the encrypt/decrypt functions
   6109 59       // will modify the output buffer, not the input buffer
   6110 60       out->ivOut = in->ivIn;
   6111 61
   6112 62   // Command Output
   6113 63
   6114 64       key = symKey->sensitive.sensitive.sym.t.buffer;
   6115 65       // For symmetric encryption, the cipher data size is the same as plain data
   6116 66       // size.
   6117 67       out->outData.t.size = in->inData.t.size;
   6118 68       if(in->decrypt == YES)
   6119 69       {
   6120 70           // Decrypt data to output
   6121 71           CryptSymmetricDecrypt(out->outData.t.buffer,
   6122 72                                 alg,
   6123 73                                 keySize, in->mode, key,
   6124 74                                 &(out->ivOut),
   6125 75                                 in->inData.t.size,
   6126 76                                 in->inData.t.buffer);
   6127 77       }
   6128 78       else
   6129 79       {
   6130 80           // Encrypt data to output
   6131 81           CryptSymmetricEncrypt(out->outData.t.buffer,
   6132 82                                 alg,
   6133 83                                 keySize,
   6134 84                                 in->mode, key,
   6135 85                                 &(out->ivOut),
   6136 86                                 in->inData.t.size,
   6137 87                                 in->inData.t.buffer);
   6138 88       }
   6139 89
   6140 90       return TPM_RC_SUCCESS;
   6141 91   }
   6142 92   #endif // CC_EncryptDecrypt
   6143 
   6144 
   6145 
   6146 
   6147      Family 2.0                           TCG Published                                  Page 121
   6148      Level 00 Revision 01.16           Copyright  TCG 2006-2014                 October 30, 2014
   6149 Part 3: Commands                                                                 Trusted Platform Module Library
   6151 
   6152 
   6153 15.3   TPM2_Hash
   6154 
   6155 15.3.1 General Description
   6156 
   6157 This command performs a hash operation on a data buffer and returns the results.
   6158 
   6159 NOTE            If the data buffer to be hashed is larger than will fit into the TPMs input buffer, then the sequence
   6160                 hash commands will need to be used.
   6161 
   6162 If the results of the hash will be used in a signing operation that uses a restricted signing key, then the
   6163 ticket returned by this command can indicate that the hash is safe to sign.
   6164 If the digest is not safe to sign, then the TPM will return a TPMT_TK_HASHCHECK with the hierarchy set
   6165 to TPM_RH_NULL and digest set to the Empty Buffer.
   6166 If hierarchy is TPM_RH_NULL, then digest in the ticket will be the Empty Buffer.
   6167 
   6168 
   6169 
   6170 
   6171 Page 122                                       TCG Published                                           Family 2.0
   6172 October 30, 2014                       Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   6173 Trusted Platform Module Library                                                          Part 3: Commands
   6175 
   6176 
   6177 
   6178 15.3.2 Command and Response
   6179 
   6180                                   Table 58  TPM2_Hash Command
   6181 Type                          Name                  Description
   6182 
   6183                                                     TPM_ST_SESSIONS if an audit, decrypt, or encrypt
   6184 TPMI_ST_COMMAND_TAG           tag                   session is present; otherwise,
   6185                                                     TPM_ST_NO_SESSIONS
   6186 UINT32                        commandSize
   6187 TPM_CC                        commandCode           TPM_CC_Hash
   6188 
   6189 TPM2B_MAX_BUFFER              data                  data to be hashed
   6190                                                     algorithm for the hash being computed  shall not be
   6191 TPMI_ALG_HASH                 hashAlg
   6192                                                     TPM_ALG_NULL
   6193 TPMI_RH_HIERARCHY+            hierarchy             hierarchy to use for the ticket (TPM_RH_NULL allowed)
   6194 
   6195 
   6196                                     Table 59  TPM2_Hash Response
   6197 Type                          Name                  Description
   6198 
   6199 TPM_ST                        tag                   see clause 6
   6200 UINT32                        responseSize
   6201 TPM_RC                        responseCode
   6202 
   6203 TPM2B_DIGEST                  outHash               results
   6204                                                     ticket indicating that the sequence of octets used to
   6205                                                     compute outDigest did not start with
   6206 TPMT_TK_HASHCHECK             validation            TPM_GENERATED_VALUE
   6207                                                     will be a NULL ticket if the digest may not be signed
   6208                                                     with a restricted key
   6209 
   6210 
   6211 
   6212 
   6213 Family 2.0                                 TCG Published                                        Page 123
   6214 Level 00 Revision 01.16              Copyright  TCG 2006-2014                          October 30, 2014
   6215      Part 3: Commands                                                   Trusted Platform Module Library
   6217 
   6218 
   6219 
   6220      15.3.3 Detailed Actions
   6221 
   6222  1   #include "InternalRoutines.h"
   6223  2   #include "Hash_fp.h"
   6224  3   #ifdef TPM_CC_Hash // Conditional expansion of this file
   6225  4   TPM_RC
   6226  5   TPM2_Hash(
   6227  6       Hash_In         *in,            // IN: input parameter list
   6228  7       Hash_Out        *out            // OUT: output parameter list
   6229  8       )
   6230  9   {
   6231 10       HASH_STATE         hashState;
   6232 11
   6233 12   // Command Output
   6234 13
   6235 14       // Output hash
   6236 15           // Start hash stack
   6237 16       out->outHash.t.size = CryptStartHash(in->hashAlg, &hashState);
   6238 17           // Adding hash data
   6239 18       CryptUpdateDigest2B(&hashState, &in->data.b);
   6240 19           // Complete hash
   6241 20       CryptCompleteHash2B(&hashState, &out->outHash.b);
   6242 21
   6243 22       // Output ticket
   6244 23       out->validation.tag = TPM_ST_HASHCHECK;
   6245 24       out->validation.hierarchy = in->hierarchy;
   6246 25
   6247 26       if(in->hierarchy == TPM_RH_NULL)
   6248 27       {
   6249 28           // Ticket is not required
   6250 29           out->validation.hierarchy = TPM_RH_NULL;
   6251 30           out->validation.digest.t.size = 0;
   6252 31       }
   6253 32       else if( in->data.t.size >= sizeof(TPM_GENERATED)
   6254 33               && !TicketIsSafe(&in->data.b))
   6255 34       {
   6256 35           // Ticket is not safe
   6257 36           out->validation.hierarchy = TPM_RH_NULL;
   6258 37           out->validation.digest.t.size = 0;
   6259 38       }
   6260 39       else
   6261 40       {
   6262 41           // Compute ticket
   6263 42           TicketComputeHashCheck(in->hierarchy, in->hashAlg,
   6264 43                                  &out->outHash, &out->validation);
   6265 44       }
   6266 45
   6267 46       return TPM_RC_SUCCESS;
   6268 47   }
   6269 48   #endif // CC_Hash
   6270 
   6271 
   6272 
   6273 
   6274      Page 124                               TCG Published                                 Family 2.0
   6275      October 30, 2014                Copyright  TCG 2006-2014               Level 00 Revision 01.16
   6276 Trusted Platform Module Library                                                              Part 3: Commands
   6278 
   6279 
   6280 15.4   TPM2_HMAC
   6281 
   6282 15.4.1 General Description
   6283 
   6284 This command performs an HMAC on the supplied data using the indicated hash algorithm.
   6285 The caller shall provide proper authorization for use of handle.
   6286 If the sign attribute is not SET in the key referenced by handle then the TPM shall return
   6287 TPM_RC_ATTRIBUTES. If the key type is not TPM_ALG_KEYEDHASH then the TPM shall return
   6288 TPM_RC_TYPE. If the key referenced by handle has the restricted attribute SET, the TPM shall return
   6289 TPM_RC_ATTRIBUTES.
   6290 If the default scheme of the key referenced by handle is not TPM_ALG_NULL, then the hashAlg
   6291 parameter is required to be either the same as the keys default or TPM_ALG_NULL (TPM_RC_VALUE).
   6292 If the default scheme of the key is TPM_ALG_NULL, then hashAlg is required to be a valid hash and not
   6293 TPM_ALG_NULL (TPM_RC_VALUE). (See hash selection matrix in Table 66.)
   6294 
   6295 NOTE            A key may only have both sign and decrypt SET if the key is unrestricted. When both sign and
   6296                 decrypt are set, there is no default scheme for the ke y and the hash algorithm must be specified.
   6297 
   6298 
   6299 
   6300 
   6301 Family 2.0                                  TCG Published                                           Page 125
   6302 Level 00 Revision 01.16               Copyright  TCG 2006-2014                              October 30, 2014
   6303 Part 3: Commands                                                  Trusted Platform Module Library
   6305 
   6306 
   6307 15.4.2 Command and Response
   6308 
   6309                          Table 60  TPM2_HMAC Command
   6310 Type                   Name                  Description
   6311 
   6312 TPMI_ST_COMMAND_TAG    tag                   TPM_ST_SESSIONS
   6313 UINT32                 commandSize
   6314 TPM_CC                 commandCode           TPM_CC_HMAC
   6315 
   6316                                              handle for the symmetric signing key providing the
   6317                                              HMAC key
   6318 TPMI_DH_OBJECT         @handle
   6319                                              Auth Index: 1
   6320                                              Auth Role: USER
   6321 
   6322 TPM2B_MAX_BUFFER       buffer                HMAC data
   6323 TPMI_ALG_HASH+         hashAlg               algorithm to use for HMAC
   6324 
   6325 
   6326                          Table 61  TPM2_HMAC Response
   6327 Type                   Name                  Description
   6328 
   6329 TPM_ST                 tag                   see clause 6
   6330 UINT32                 responseSize
   6331 TPM_RC                 responseCode
   6332 
   6333 TPM2B_DIGEST           outHMAC               the returned HMAC in a sized buffer
   6334 
   6335 
   6336 
   6337 
   6338 Page 126                              TCG Published                                    Family 2.0
   6339 October 30, 2014                Copyright  TCG 2006-2014                Level 00 Revision 01.16
   6340      Trusted Platform Module Library                                                                 Part 3: Commands
   6342 
   6343 
   6344 
   6345      15.4.3 Detailed Actions
   6346 
   6347 1    #include "InternalRoutines.h"
   6348 2    #include "HMAC_fp.h"
   6349 3    #ifdef TPM_CC_HMAC // Conditional expansion of this file
   6350 
   6351 
   6352      Error Returns                     Meaning
   6353 
   6354      TPM_RC_ATTRIBUTES                 key referenced by handle is not a signing key or is a restricted key
   6355      TPM_RC_TYPE                       key referenced by handle is not an HMAC key
   6356      TPM_RC_VALUE                      hashAlg is not compatible with the hash algorithm of the scheme of
   6357                                        the object referenced by handle
   6358 
   6359  4   TPM_RC
   6360  5   TPM2_HMAC(
   6361  6       HMAC_In           *in,                 // IN: input parameter list
   6362  7       HMAC_Out          *out                 // OUT: output parameter list
   6363  8       )
   6364  9   {
   6365 10       HMAC_STATE                 hmacState;
   6366 11       OBJECT                    *hmacObject;
   6367 12       TPMI_ALG_HASH              hashAlg;
   6368 13       TPMT_PUBLIC               *publicArea;
   6369 14
   6370 15   // Input Validation
   6371 16
   6372 17       // Get HMAC key object and public area pointers
   6373 18       hmacObject = ObjectGet(in->handle);
   6374 19       publicArea = &hmacObject->publicArea;
   6375 20
   6376 21       // Make sure that the key is an HMAC key
   6377 22       if(publicArea->type != TPM_ALG_KEYEDHASH)
   6378 23           return TPM_RCS_TYPE + RC_HMAC_handle;
   6379 24
   6380 25       // and that it is unrestricted
   6381 26       if(publicArea->objectAttributes.restricted == SET)
   6382 27           return TPM_RCS_ATTRIBUTES + RC_HMAC_handle;
   6383 28
   6384 29       // and that it is a signing key
   6385 30       if(publicArea->objectAttributes.sign != SET)
   6386 31           return TPM_RCS_KEY + RC_HMAC_handle;
   6387 32
   6388 33       // See if the key has a default
   6389 34       if(publicArea->parameters.keyedHashDetail.scheme.scheme == TPM_ALG_NULL)
   6390 35           // it doesn't so use the input value
   6391 36           hashAlg = in->hashAlg;
   6392 37       else
   6393 38       {
   6394 39           // key has a default so use it
   6395 40           hashAlg
   6396 41               = publicArea->parameters.keyedHashDetail.scheme.details.hmac.hashAlg;
   6397 42           // and verify that the input was either the TPM_ALG_NULL or the default
   6398 43           if(in->hashAlg != TPM_ALG_NULL && in->hashAlg != hashAlg)
   6399 44               hashAlg = TPM_ALG_NULL;
   6400 45       }
   6401 46       // if we ended up without a hash algorith then return an error
   6402 47       if(hashAlg == TPM_ALG_NULL)
   6403 48           return TPM_RCS_VALUE + RC_HMAC_hashAlg;
   6404 49
   6405 50   // Command Output
   6406 51
   6407 
   6408      Family 2.0                                   TCG Published                                             Page 127
   6409      Level 00 Revision 01.16               Copyright  TCG 2006-2014                                 October 30, 2014
   6410      Part 3: Commands                                               Trusted Platform Module Library
   6412 
   6413 52      // Start HMAC stack
   6414 53      out->outHMAC.t.size = CryptStartHMAC2B(hashAlg,
   6415 54                                             &hmacObject->sensitive.sensitive.bits.b,
   6416 55                                             &hmacState);
   6417 56      // Adding HMAC data
   6418 57      CryptUpdateDigest2B(&hmacState, &in->buffer.b);
   6419 58
   6420 59      // Complete HMAC
   6421 60      CryptCompleteHMAC2B(&hmacState, &out->outHMAC.b);
   6422 61
   6423 62       return TPM_RC_SUCCESS;
   6424 63   }
   6425 64   #endif // CC_HMAC
   6426 
   6427 
   6428 
   6429 
   6430      Page 128                              TCG Published                              Family 2.0
   6431      October 30, 2014               Copyright  TCG 2006-2014             Level 00 Revision 01.16
   6432 Trusted Platform Module Library                                                           Part 3: Commands
   6434 
   6435 
   6436 16     Random Number Generator
   6437 
   6438 16.1     TPM2_GetRandom
   6439 
   6440 16.1.1 General Description
   6441 
   6442 This command returns the next bytesRequested octets from the random number generator (RNG).
   6443 
   6444 NOTE 1         It is recommended that a TPM implement the RNG in a manner that would allow it to return RNG
   6445                octets such that, as long as the value of bytesRequested is not greater than the maximum digest
   6446                size, the frequency of bytesRequested being more than the number of octets available is an
   6447                infrequent occurrence.
   6448 
   6449 If bytesRequested is more than will fit into a TPM2B_DIGEST on the TPM, no error is returned but the
   6450 TPM will only return as much data as will fit into a TPM2B_DIGEST buffer for the TPM.
   6451 
   6452 NOTE 2         TPM2B_DIGEST is large enough to hold the largest dig est that may be produced by the TPM.
   6453                Because that digest size changes according to the implemented hashes, the maximum amount of
   6454                data returned by this command is TPM implementation-dependent.
   6455 
   6456 
   6457 
   6458 
   6459 Family 2.0                                TCG Published                                          Page 129
   6460 Level 00 Revision 01.16             Copyright  TCG 2006-2014                             October 30, 2014
   6461 Part 3: Commands                                                  Trusted Platform Module Library
   6463 
   6464 
   6465 16.1.2 Command and Response
   6466 
   6467                       Table 62  TPM2_GetRandom Command
   6468 Type                   Name                  Description
   6469 
   6470                                              TPM_ST_SESSIONS if an audit or encrypt session is
   6471 TPMI_ST_COMMAND_TAG    tag
   6472                                              present; otherwise, TPM_ST_NO_SESSIONS
   6473 UINT32                 commandSize
   6474 TPM_CC                 commandCode           TPM_CC_GetRandom
   6475 
   6476 UINT16                 bytesRequested        number of octets to return
   6477 
   6478 
   6479                       Table 63  TPM2_GetRandom Response
   6480 Type                   Name                  Description
   6481 
   6482 TPM_ST                 tag                   see clause 6
   6483 UINT32                 responseSize
   6484 TPM_RC                 responseCode
   6485 
   6486 TPM2B_DIGEST           randomBytes           the random octets
   6487 
   6488 
   6489 
   6490 
   6491 Page 130                              TCG Published                                  Family 2.0
   6492 October 30, 2014             Copyright  TCG 2006-2014                    Level 00 Revision 01.16
   6493      Trusted Platform Module Library                                                Part 3: Commands
   6495 
   6496 
   6497 
   6498      16.1.3 Detailed Actions
   6499 
   6500  1   #include "InternalRoutines.h"
   6501  2   #include "GetRandom_fp.h"
   6502  3   #ifdef TPM_CC_GetRandom // Conditional expansion of this file
   6503  4   TPM_RC
   6504  5   TPM2_GetRandom(
   6505  6       GetRandom_In     *in,            // IN: input parameter list
   6506  7       GetRandom_Out    *out            // OUT: output parameter list
   6507  8       )
   6508  9   {
   6509 10   // Command Output
   6510 11
   6511 12       // if the requested bytes exceed the output buffer size, generates the
   6512 13       // maximum bytes that the output buffer allows
   6513 14       if(in->bytesRequested > sizeof(TPMU_HA))
   6514 15           out->randomBytes.t.size = sizeof(TPMU_HA);
   6515 16       else
   6516 17           out->randomBytes.t.size = in->bytesRequested;
   6517 18
   6518 19       CryptGenerateRandom(out->randomBytes.t.size, out->randomBytes.t.buffer);
   6519 20
   6520 21       return TPM_RC_SUCCESS;
   6521 22   }
   6522 23   #endif // CC_GetRandom
   6523 
   6524 
   6525 
   6526 
   6527      Family 2.0                            TCG Published                                 Page 131
   6528      Level 00 Revision 01.16           Copyright  TCG 2006-2014                    October 30, 2014
   6529 Part 3: Commands                                                           Trusted Platform Module Library
   6531 
   6532 
   6533 16.2   TPM2_StirRandom
   6534 
   6535 16.2.1 General Description
   6536 
   6537 This command is used to add "additional information" to the RNG state.
   6538 
   6539 NOTE           The "additional information" is as defined in SP800 -90A.
   6540 
   6541 The inData parameter may not be larger than 128 octets.
   6542 
   6543 
   6544 
   6545 
   6546 Page 132                                      TCG Published                                  Family 2.0
   6547 October 30, 2014                      Copyright  TCG 2006-2014                 Level 00 Revision 01.16
   6548 Trusted Platform Module Library                                                      Part 3: Commands
   6550 
   6551 
   6552 
   6553 16.2.2 Command and Response
   6554 
   6555                              Table 64  TPM2_StirRandom Command
   6556 Type                          Name                  Description
   6557 
   6558                                                     TPM_ST_SESSIONS if an audit or decrypt session is
   6559 TPMI_ST_COMMAND_TAG           tag
   6560                                                     present; otherwise, TPM_ST_NO_SESSIONS
   6561 UINT32                        commandSize
   6562 TPM_CC                        commandCode           TPM_CC_StirRandom {NV}
   6563 
   6564 TPM2B_SENSITIVE_DATA          inData                additional information
   6565 
   6566 
   6567                              Table 65  TPM2_StirRandom Response
   6568 Type                          Name                  Description
   6569 
   6570 TPM_ST                        tag                   see clause 6
   6571 UINT32                        responseSize
   6572 TPM_RC                        responseCode
   6573 
   6574 
   6575 
   6576 
   6577 Family 2.0                                 TCG Published                                   Page 133
   6578 Level 00 Revision 01.16             Copyright  TCG 2006-2014                        October 30, 2014
   6579      Part 3: Commands                                                 Trusted Platform Module Library
   6581 
   6582 
   6583 
   6584      16.2.3 Detailed Actions
   6585 
   6586  1   #include "InternalRoutines.h"
   6587  2   #include "StirRandom_fp.h"
   6588  3   #ifdef TPM_CC_StirRandom // Conditional expansion of this file
   6589  4   TPM_RC
   6590  5   TPM2_StirRandom(
   6591  6       StirRandom_In   *in            // IN: input parameter list
   6592  7       )
   6593  8   {
   6594  9   // Internal Data Update
   6595 10       CryptStirRandom(in->inData.t.size, in->inData.t.buffer);
   6596 11
   6597 12       return TPM_RC_SUCCESS;
   6598 13   }
   6599 14   #endif // CC_StirRandom
   6600 
   6601 
   6602 
   6603 
   6604      Page 134                               TCG Published                               Family 2.0
   6605      October 30, 2014                Copyright  TCG 2006-2014             Level 00 Revision 01.16
   6606 Trusted Platform Module Library                                                                 Part 3: Commands
   6608 
   6609 
   6610 17     Hash/HMAC/Event Sequences
   6611 
   6612 17.1     Introduction
   6613 
   6614 All of the commands in this group are to support sequences for which an intermediate state must be
   6615 maintained. For a description of sequences, see Hash, HMAC, and Event Sequences in TPM 2.0 Part 1.
   6616 
   6617 17.2     TPM2_HMAC_Start
   6618 
   6619 17.2.1 General Description
   6620 
   6621 This command starts an HMAC sequence. The TPM will create and initialize an HMAC sequence
   6622 structure, assign a handle to the sequence, and set the authValue of the sequence object to the value in
   6623 auth.
   6624 
   6625 NOTE                The structure of a sequence object is vendor -dependent.
   6626 
   6627 The caller shall provide proper authorization for use of handle.
   6628 If the sign attribute is not SET in the key referenced by handle then the TPM shall return
   6629 TPM_RC_ATTRIBUTES. If the key type is not TPM_ALG_KEYEDHASH then the TPM shall return
   6630 TPM_RC_TYPE. If the key referenced by handle has the restricted attribute SET, the TPM shall return
   6631 TPM_RC_ATTRIBUTES.
   6632 If the default scheme of the key referenced by handle is not TPM_ALG_NULL, then the hashAlg
   6633 parameter is required to be either the same as the keys default or TPM_ALG_NULL (TPM_RC_VALUE).
   6634 If the default scheme of the key is TPM_ALG_NULL, then hashAlg is required to be a valid hash and not
   6635 TPM_ALG_NULL (TPM_RC_VALUE).
   6636 
   6637                                           Table 66  Hash Selection Matrix
   6638  handlerestricted          handlescheme
   6639  (key's restricted          (hash algorithm
   6640  attribute)                 from key's scheme)          hashAlg                   hash used
   6641                                                 (1)                                       (1)
   6642  CLEAR (unrestricted)       TPM_ALG_NULL                TPM_ALG_NULL              error         (TPM_RC_VALUE)
   6643  CLEAR                      TPM_ALG_NULL                valid hash                hashAlg
   6644  CLEAR                      valid hash                  TPM_ALG_NULL or same as   handlescheme
   6645                                                         handlescheme
   6646  SET (restricted)           don't care                  don't care                TPM_RC_ATTRIBUTES
   6647  NOTES:
   6648  1)    A hash algorithm is required for the HMAC.
   6649 
   6650 
   6651 
   6652 
   6653 Family 2.0                                          TCG Published                                    Page 135
   6654 Level 00 Revision 01.16                      Copyright  TCG 2006-2014                          October 30, 2014
   6655 Part 3: Commands                                                 Trusted Platform Module Library
   6657 
   6658 
   6659 
   6660 17.2.2 Command and Response
   6661 
   6662                       Table 67  TPM2_HMAC_Start Command
   6663 Type                   Name                  Description
   6664 
   6665 TPMI_ST_COMMAND_TAG    tag                   TPM_ST_SESSIONS
   6666 UINT32                 commandSize
   6667 TPM_CC                 commandCode           TPM_CC_HMAC_Start
   6668 
   6669                                              handle of an HMAC key
   6670 TPMI_DH_OBJECT         @handle               Auth Index: 1
   6671                                              Auth Role: USER
   6672 
   6673 TPM2B_AUTH             auth                  authorization value for subsequent use of the sequence
   6674 TPMI_ALG_HASH+         hashAlg               the hash algorithm to use for the HMAC
   6675 
   6676 
   6677                       Table 68  TPM2_HMAC_Start Response
   6678 Type                   Name                  Description
   6679 
   6680 TPM_ST                 tag                   see clause 6
   6681 UINT32                 responseSize
   6682 TPM_RC                 responseCode
   6683 
   6684 TPMI_DH_OBJECT         sequenceHandle        a handle to reference the sequence
   6685 
   6686 
   6687 
   6688 
   6689 Page 136                              TCG Published                                   Family 2.0
   6690 October 30, 2014              Copyright  TCG 2006-2014                 Level 00 Revision 01.16
   6691      Trusted Platform Module Library                                                                    Part 3: Commands
   6693 
   6694 
   6695 
   6696      17.2.3 Detailed Actions
   6697 
   6698 1    #include "InternalRoutines.h"
   6699 2    #include "HMAC_Start_fp.h"
   6700 3    #ifdef TPM_CC_HMAC_Start // Conditional expansion of this file
   6701 
   6702 
   6703      Error Returns                     Meaning
   6704 
   6705      TPM_RC_ATTRIBUTES                 key referenced by handle is not a signing key or is restricted
   6706      TPM_RC_OBJECT_MEMORY              no space to create an internal object
   6707      TPM_RC_KEY                        key referenced by handle is not an HMAC key
   6708      TPM_RC_VALUE                      hashAlg is not compatible with the hash algorithm of the scheme of
   6709                                        the object referenced by handle
   6710 
   6711  4   TPM_RC
   6712  5   TPM2_HMAC_Start(
   6713  6       HMAC_Start_In     *in,                 // IN: input parameter list
   6714  7       HMAC_Start_Out    *out                 // OUT: output parameter list
   6715  8       )
   6716  9   {
   6717 10       OBJECT                    *hmacObject;
   6718 11       TPMT_PUBLIC               *publicArea;
   6719 12       TPM_ALG_ID                 hashAlg;
   6720 13
   6721 14   // Input Validation
   6722 15
   6723 16       // Get HMAC key object and public area pointers
   6724 17       hmacObject = ObjectGet(in->handle);
   6725 18       publicArea = &hmacObject->publicArea;
   6726 19
   6727 20       // Make sure that the key is an HMAC key
   6728 21       if(publicArea->type != TPM_ALG_KEYEDHASH)
   6729 22           return TPM_RCS_TYPE + RC_HMAC_Start_handle;
   6730 23
   6731 24       // and that it is unrestricted
   6732 25       if(publicArea->objectAttributes.restricted == SET)
   6733 26           return TPM_RCS_ATTRIBUTES + RC_HMAC_Start_handle;
   6734 27
   6735 28       // and that it is a signing key
   6736 29       if(publicArea->objectAttributes.sign != SET)
   6737 30           return TPM_RCS_KEY + RC_HMAC_Start_handle;
   6738 31
   6739 32       // See if the key has a default
   6740 33       if(publicArea->parameters.keyedHashDetail.scheme.scheme == TPM_ALG_NULL)
   6741 34           // it doesn't so use the input value
   6742 35           hashAlg = in->hashAlg;
   6743 36       else
   6744 37       {
   6745 38           // key has a default so use it
   6746 39           hashAlg
   6747 40               = publicArea->parameters.keyedHashDetail.scheme.details.hmac.hashAlg;
   6748 41           // and verify that the input was either the TPM_ALG_NULL or the default
   6749 42           if(in->hashAlg != TPM_ALG_NULL && in->hashAlg != hashAlg)
   6750 43               hashAlg = TPM_ALG_NULL;
   6751 44       }
   6752 45       // if we ended up without a hash algorith then return an error
   6753 46       if(hashAlg == TPM_ALG_NULL)
   6754 47           return TPM_RCS_VALUE + RC_HMAC_Start_hashAlg;
   6755 48
   6756 49   // Internal Data Update
   6757 50
   6758 
   6759      Family 2.0                                   TCG Published                                              Page 137
   6760      Level 00 Revision 01.16               Copyright  TCG 2006-2014                                    October 30, 2014
   6761      Part 3: Commands                                               Trusted Platform Module Library
   6763 
   6764 51      // Create a HMAC sequence object. A TPM_RC_OBJECT_MEMORY error may be
   6765 52      // returned at this point
   6766 53      return ObjectCreateHMACSequence(hashAlg,
   6767 54                                      in->handle,
   6768 55                                      &in->auth,
   6769 56                                      &out->sequenceHandle);
   6770 57   }
   6771 58   #endif // CC_HMAC_Start
   6772 
   6773 
   6774 
   6775 
   6776      Page 138                              TCG Published                              Family 2.0
   6777      October 30, 2014               Copyright  TCG 2006-2014             Level 00 Revision 01.16
   6778 Trusted Platform Module Library                                                        Part 3: Commands
   6780 
   6781 
   6782 17.3   TPM2_HashSequenceStart
   6783 
   6784 17.3.1 General Description
   6785 
   6786 This command starts a hash or an Event Sequence. If hashAlg is an implemented hash, then a hash
   6787 sequence is started. If hashAlg is TPM_ALG_NULL, then an Event Sequence is started. If hashAlg is
   6788 neither an implemented algorithm nor TPM_ALG_NULL, then the TPM shall return TPM_RC_HASH.
   6789 Depending on hashAlg, the TPM will create and initialize a Hash Sequence context or an Event
   6790 Sequence context. Additionally, it will assign a handle to the context and set the authValue of the context
   6791 to the value in auth. A sequence context for an Event (hashAlg = TPM_ALG_NULL) contains a hash
   6792 context for each of the PCR banks implemented on the TPM.
   6793 
   6794 
   6795 
   6796 
   6797 Family 2.0                                TCG Published                                       Page 139
   6798 Level 00 Revision 01.16              Copyright  TCG 2006-2014                         October 30, 2014
   6799 Part 3: Commands                                                    Trusted Platform Module Library
   6801 
   6802 
   6803 
   6804 17.3.2 Command and Response
   6805 
   6806                       Table 69  TPM2_HashSequenceStart Command
   6807 Type                      Name                  Description
   6808 
   6809                                                 TPM_ST_SESSIONS if an audit or decrypt session is
   6810 TPMI_ST_COMMAND_TAG       tag
   6811                                                 present; otherwise, TPM_ST_NO_SESSIONS
   6812 UINT32                    commandSize
   6813 TPM_CC                    commandCode           TPM_CC_HashSequenceStart
   6814 
   6815 TPM2B_AUTH                auth                  authorization value for subsequent use of the sequence
   6816                                                 the hash algorithm to use for the hash sequence
   6817 TPMI_ALG_HASH+            hashAlg
   6818                                                 An Event Sequence starts if this is TPM_ALG_NULL.
   6819 
   6820 
   6821                       Table 70  TPM2_HashSequenceStart Response
   6822 Type                      Name                  Description
   6823 
   6824 TPM_ST                    tag                   see clause 6
   6825 UINT32                    responseSize
   6826 TPM_RC                    responseCode
   6827 
   6828 TPMI_DH_OBJECT            sequenceHandle        a handle to reference the sequence
   6829 
   6830 
   6831 
   6832 
   6833 Page 140                                 TCG Published                                   Family 2.0
   6834 October 30, 2014                 Copyright  TCG 2006-2014                 Level 00 Revision 01.16
   6835      Trusted Platform Module Library                                                      Part 3: Commands
   6837 
   6838 
   6839 
   6840      17.3.3 Detailed Actions
   6841 
   6842 1    #include "InternalRoutines.h"
   6843 2    #include "HashSequenceStart_fp.h"
   6844 3    #ifdef TPM_CC_HashSequenceStart // Conditional expansion of this file
   6845 
   6846 
   6847      Error Returns                     Meaning
   6848 
   6849      TPM_RC_OBJECT_MEMORY              no space to create an internal object
   6850 
   6851  4   TPM_RC
   6852  5   TPM2_HashSequenceStart(
   6853  6       HashSequenceStart_In      *in,                   // IN: input parameter list
   6854  7       HashSequenceStart_Out     *out                   // OUT: output parameter list
   6855  8       )
   6856  9   {
   6857 10   // Internal Data Update
   6858 11
   6859 12       if(in->hashAlg == TPM_ALG_NULL)
   6860 13           // Start a event sequence. A TPM_RC_OBJECT_MEMORY error may be
   6861 14           // returned at this point
   6862 15           return ObjectCreateEventSequence(&in->auth, &out->sequenceHandle);
   6863 16
   6864 17       // Start a hash sequence. A TPM_RC_OBJECT_MEMORY error may be
   6865 18       // returned at this point
   6866 19       return ObjectCreateHashSequence(in->hashAlg, &in->auth, &out->sequenceHandle);
   6867 20   }
   6868 21   #endif // CC_HashSequenceStart
   6869 
   6870 
   6871 
   6872 
   6873      Family 2.0                                   TCG Published                                Page 141
   6874      Level 00 Revision 01.16               Copyright  TCG 2006-2014                      October 30, 2014
   6875 Part 3: Commands                                                              Trusted Platform Module Library
   6877 
   6878 
   6879 17.4     TPM2_SequenceUpdate
   6880 
   6881 17.4.1 General Description
   6882 
   6883 This command is used to add data to a hash or HMAC sequence. The amount of data in buffer may be
   6884 any size up to the limits of the TPM.
   6885 
   6886 NOTE 1          In all TPM, a buffer size of 1,024 octets is allowed.
   6887 
   6888 Proper authorization for the sequence object associated with sequenceHandle is required. If an
   6889 authorization or audit of this command requires computation of a cpHash and an rpHash, the Name
   6890 associated with sequenceHandle will be the Empty Buffer.
   6891 If the command does not return TPM_RC_SUCCESS, the state of the sequence is unmodified.
   6892 If the sequence is intended to produce a digest that will be signed by a restricted signing key, then the
   6893 first block of data shall contain sizeof(TPM_GENERATED) octets and the first octets shall not be
   6894 TPM_GENERATED_VALUE.
   6895 
   6896 NOTE 2          This requirement allows the TPM to validate that the first block is safe to sign without having to
   6897                 accumulate octets over multiple calls.
   6898 
   6899 
   6900 
   6901 
   6902 Page 142                                        TCG Published                                       Family 2.0
   6903 October 30, 2014                        Copyright  TCG 2006-2014                    Level 00 Revision 01.16
   6904 Trusted Platform Module Library                                                      Part 3: Commands
   6906 
   6907 
   6908 17.4.2 Command and Response
   6909 
   6910                           Table 71  TPM2_SequenceUpdate Command
   6911 Type                          Name                  Description
   6912 
   6913 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   6914 UINT32                        commandSize
   6915 TPM_CC                        commandCode           TPM_CC_SequenceUpdate
   6916 
   6917                                                     handle for the sequence object
   6918 TPMI_DH_OBJECT                @sequenceHandle       Auth Index: 1
   6919                                                     Auth Role: USER
   6920 
   6921 TPM2B_MAX_BUFFER              buffer                data to be added to hash
   6922 
   6923 
   6924                           Table 72  TPM2_SequenceUpdate Response
   6925 Type                          Name                  Description
   6926 
   6927 TPM_ST                        tag                   see clause 6
   6928 UINT32                        responseSize
   6929 TPM_RC                        responseCode
   6930 
   6931 
   6932 
   6933 
   6934 Family 2.0                                 TCG Published                                  Page 143
   6935 Level 00 Revision 01.16                Copyright  TCG 2006-2014                     October 30, 2014
   6936      Part 3: Commands                                                        Trusted Platform Module Library
   6938 
   6939 
   6940 
   6941      17.4.3 Detailed Actions
   6942 
   6943 1    #include "InternalRoutines.h"
   6944 2    #include "SequenceUpdate_fp.h"
   6945 3    #ifdef TPM_CC_SequenceUpdate // Conditional expansion of this file
   6946 
   6947 
   6948      Error Returns                   Meaning
   6949 
   6950      TPM_RC_MODE                     sequenceHandle does not reference a hash or HMAC sequence
   6951                                      object
   6952 
   6953  4   TPM_RC
   6954  5   TPM2_SequenceUpdate(
   6955  6       SequenceUpdate_In     *in               // IN: input parameter list
   6956  7       )
   6957  8   {
   6958  9       OBJECT                      *object;
   6959 10
   6960 11   // Input Validation
   6961 12
   6962 13       // Get sequence object pointer
   6963 14       object = ObjectGet(in->sequenceHandle);
   6964 15
   6965 16       // Check that referenced object is a sequence object.
   6966 17       if(!ObjectIsSequence(object))
   6967 18           return TPM_RC_MODE + RC_SequenceUpdate_sequenceHandle;
   6968 19
   6969 20   // Internal Data Update
   6970 21
   6971 22       if(object->attributes.eventSeq == SET)
   6972 23       {
   6973 24           // Update event sequence object
   6974 25           UINT32           i;
   6975 26           HASH_OBJECT     *hashObject = (HASH_OBJECT *)object;
   6976 27           for(i = 0; i < HASH_COUNT; i++)
   6977 28           {
   6978 29               // Update sequence object
   6979 30               CryptUpdateDigest2B(&hashObject->state.hashState[i], &in->buffer.b);
   6980 31           }
   6981 32       }
   6982 33       else
   6983 34       {
   6984 35           HASH_OBJECT     *hashObject = (HASH_OBJECT *)object;
   6985 36
   6986 37           // Update hash/HMAC sequence object
   6987 38           if(hashObject->attributes.hashSeq == SET)
   6988 39           {
   6989 40               // Is this the first block of the sequence
   6990 41               if(hashObject->attributes.firstBlock == CLEAR)
   6991 42               {
   6992 43                   // If so, indicate that first block was received
   6993 44                   hashObject->attributes.firstBlock = SET;
   6994 45
   6995 46                    // Check the first block to see if the first block can contain
   6996 47                    // the TPM_GENERATED_VALUE. If it does, it is not safe for
   6997 48                    // a ticket.
   6998 49                    if(TicketIsSafe(&in->buffer.b))
   6999 50                        hashObject->attributes.ticketSafe = SET;
   7000 51                }
   7001 52                // Update sequence object hash/HMAC stack
   7002 53                CryptUpdateDigest2B(&hashObject->state.hashState[0], &in->buffer.b);
   7003 54
   7004 55           }
   7005 
   7006      Page 144                                   TCG Published                                    Family 2.0
   7007      October 30, 2014                    Copyright  TCG 2006-2014                 Level 00 Revision 01.16
   7008      Trusted Platform Module Library                                              Part 3: Commands
   7010 
   7011 56           else if(object->attributes.hmacSeq == SET)
   7012 57           {
   7013 58               HASH_OBJECT     *hashObject = (HASH_OBJECT *)object;
   7014 59
   7015 60                // Update sequence object hash/HMAC stack
   7016 61                CryptUpdateDigest2B(&hashObject->state.hmacState, &in->buffer.b);
   7017 62           }
   7018 63       }
   7019 64
   7020 65       return TPM_RC_SUCCESS;
   7021 66   }
   7022 67   #endif // CC_SequenceUpdate
   7023 
   7024 
   7025 
   7026 
   7027      Family 2.0                            TCG Published                               Page 145
   7028      Level 00 Revision 01.16           Copyright  TCG 2006-2014                  October 30, 2014
   7029 Part 3: Commands                                                                Trusted Platform Module Library
   7031 
   7032 
   7033 17.5     TPM2_SequenceComplete
   7034 
   7035 17.5.1 General Description
   7036 
   7037 This command adds the last part of data, if any, to a hash/HMAC sequence and returns the result.
   7038 
   7039 NOTE 1          This command is not used to complete an Event Sequence. TPM2_EventSequenceComplete() is
   7040                 used for that purpose.
   7041 
   7042 For a hash sequence, if the results of the hash will be used in a signing operation that uses a restricted
   7043 signing key, then the ticket returned by this command can indicate that the hash is safe to sign.
   7044 If the digest is not safe to sign, then validation will be a TPMT_TK_HASHCHECK with the hierarchy set to
   7045 TPM_RH_NULL and digest set to the Empty Buffer.
   7046 
   7047 NOTE 2          Regardless of the contents of the first octets of the hashed message, if the first buffer sent to the
   7048                 TPM had fewer than sizeof(TPM_GENERATED) octets, then the TPM will operate as if digest is not
   7049                 safe to sign.
   7050 
   7051 NOTE 3          The ticket is only required for a signing operation that uses a restricted signing key. It is always
   7052                 returned, but can be ignored if not needed.
   7053 
   7054 If sequenceHandle references an Event Sequence, then the TPM shall return TPM_RC_MODE.
   7055 Proper authorization for the sequence object associated with sequenceHandle is required. If an
   7056 authorization or audit of this command requires computation of a cpHash and an rpHash, the Name
   7057 associated with sequenceHandle will be the Empty Buffer.
   7058 If this command completes successfully, the sequenceHandle object will be flushed.
   7059 
   7060 
   7061 
   7062 
   7063 Page 146                                       TCG Published                                          Family 2.0
   7064 October 30, 2014                       Copyright  TCG 2006-2014                       Level 00 Revision 01.16
   7065 Trusted Platform Module Library                                                          Part 3: Commands
   7067 
   7068 
   7069 
   7070 17.5.2 Command and Response
   7071 
   7072                           Table 73  TPM2_SequenceComplete Command
   7073 Type                          Name                  Description
   7074 
   7075 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   7076 UINT32                        commandSize
   7077 TPM_CC                        commandCode           TPM_CC_SequenceComplete {F}
   7078 
   7079                                                     authorization for the sequence
   7080 TPMI_DH_OBJECT                @sequenceHandle       Auth Index: 1
   7081                                                     Auth Role: USER
   7082 
   7083 TPM2B_MAX_BUFFER              buffer                data to be added to the hash/HMAC
   7084 TPMI_RH_HIERARCHY+            hierarchy             hierarchy of the ticket for a hash
   7085 
   7086 
   7087                           Table 74  TPM2_SequenceComplete Response
   7088 Type                          Name                  Description
   7089 
   7090 TPM_ST                        tag                   see clause 6
   7091 UINT32                        responseSize
   7092 TPM_RC                        responseCode
   7093 
   7094 TPM2B_DIGEST                  result                the returned HMAC or digest in a sized buffer
   7095                                                     ticket indicating that the sequence of octets used to
   7096                                                     compute outDigest did not start with
   7097 TPMT_TK_HASHCHECK             validation            TPM_GENERATED_VALUE
   7098                                                     This is a NULL Ticket when the sequence is HMAC.
   7099 
   7100 
   7101 
   7102 
   7103 Family 2.0                                 TCG Published                                          Page 147
   7104 Level 00 Revision 01.16                Copyright  TCG 2006-2014                         October 30, 2014
   7105      Part 3: Commands                                                    Trusted Platform Module Library
   7107 
   7108 
   7109 
   7110      17.5.3 Detailed Actions
   7111 
   7112 1    #include "InternalRoutines.h"
   7113 2    #include "SequenceComplete_fp.h"
   7114 3    #ifdef TPM_CC_SequenceComplete // Conditional expansion of this file
   7115 4    #include <Platform.h>
   7116 
   7117 
   7118      Error Returns               Meaning
   7119 
   7120      TPM_RC_TYPE                 sequenceHandle does not reference a hash or HMAC sequence
   7121                                  object
   7122 
   7123  5   TPM_RC
   7124  6   TPM2_SequenceComplete(
   7125  7       SequenceComplete_In    *in,               // IN: input parameter list
   7126  8       SequenceComplete_Out   *out               // OUT: output parameter list
   7127  9       )
   7128 10   {
   7129 11       OBJECT                     *object;
   7130 12
   7131 13   // Input validation
   7132 14
   7133 15       // Get hash object pointer
   7134 16       object = ObjectGet(in->sequenceHandle);
   7135 17
   7136 18       // input handle must be a hash or HMAC sequence object.
   7137 19       if(   object->attributes.hashSeq == CLEAR
   7138 20          && object->attributes.hmacSeq == CLEAR)
   7139 21           return TPM_RC_MODE + RC_SequenceComplete_sequenceHandle;
   7140 22
   7141 23   // Command Output
   7142 24
   7143 25       if(object->attributes.hashSeq == SET)           // sequence object for hash
   7144 26       {
   7145 27           // Update last piece of data
   7146 28           HASH_OBJECT     *hashObject = (HASH_OBJECT *)object;
   7147 29
   7148 30          // Get the hash algorithm before the algorithm is lost in CryptCompleteHash
   7149 31           TPM_ALG_ID       hashAlg = hashObject->state.hashState[0].state.hashAlg;
   7150 32
   7151 33           CryptUpdateDigest2B(&hashObject->state.hashState[0], &in->buffer.b);
   7152 34
   7153 35           // Complete hash
   7154 36           out->result.t.size
   7155 37               = CryptGetHashDigestSize(
   7156 38                     CryptGetContextAlg(&hashObject->state.hashState[0]));
   7157 39
   7158 40           CryptCompleteHash2B(&hashObject->state.hashState[0], &out->result.b);
   7159 41
   7160 42           // Check if the first block of the sequence has been received
   7161 43           if(hashObject->attributes.firstBlock == CLEAR)
   7162 44           {
   7163 45               // If not, then this is the first block so see if it is 'safe'
   7164 46               // to sign.
   7165 47               if(TicketIsSafe(&in->buffer.b))
   7166 48                   hashObject->attributes.ticketSafe = SET;
   7167 49           }
   7168 50
   7169 51           // Output ticket
   7170 52           out->validation.tag = TPM_ST_HASHCHECK;
   7171 53           out->validation.hierarchy = in->hierarchy;
   7172 54
   7173 55           if(in->hierarchy == TPM_RH_NULL)
   7174 
   7175      Page 148                               TCG Published                                    Family 2.0
   7176      October 30, 2014                  Copyright  TCG 2006-2014               Level 00 Revision 01.16
   7177      Trusted Platform Module Library                                                Part 3: Commands
   7179 
   7180 56           {
   7181 57                // Ticket is not required
   7182 58                out->validation.digest.t.size = 0;
   7183 59           }
   7184 60           else if(object->attributes.ticketSafe == CLEAR)
   7185 61           {
   7186 62               // Ticket is not safe to generate
   7187 63               out->validation.hierarchy = TPM_RH_NULL;
   7188 64               out->validation.digest.t.size = 0;
   7189 65           }
   7190 66           else
   7191 67           {
   7192 68               // Compute ticket
   7193 69               TicketComputeHashCheck(out->validation.hierarchy, hashAlg,
   7194 70                                      &out->result, &out->validation);
   7195 71           }
   7196 72       }
   7197 73       else
   7198 74       {
   7199 75           HASH_OBJECT       *hashObject = (HASH_OBJECT *)object;
   7200 76
   7201 77           //   Update last piece of data
   7202 78           CryptUpdateDigest2B(&hashObject->state.hmacState, &in->buffer.b);
   7203 79           // Complete hash/HMAC
   7204 80           out->result.t.size =
   7205 81               CryptGetHashDigestSize(
   7206 82                   CryptGetContextAlg(&hashObject->state.hmacState.hashState));
   7207 83           CryptCompleteHMAC2B(&(hashObject->state.hmacState), &out->result.b);
   7208 84
   7209 85           // No ticket is generated for HMAC sequence
   7210 86           out->validation.tag = TPM_ST_HASHCHECK;
   7211 87           out->validation.hierarchy = TPM_RH_NULL;
   7212 88           out->validation.digest.t.size = 0;
   7213 89       }
   7214 90
   7215 91   // Internal Data Update
   7216 92
   7217 93       // mark sequence object as evict so it will be flushed on the way out
   7218 94       object->attributes.evict = SET;
   7219 95
   7220 96       return TPM_RC_SUCCESS;
   7221 97   }
   7222 98   #endif // CC_SequenceComplete
   7223 
   7224 
   7225 
   7226 
   7227      Family 2.0                             TCG Published                                Page 149
   7228      Level 00 Revision 01.16           Copyright  TCG 2006-2014                    October 30, 2014
   7229 Part 3: Commands                                                        Trusted Platform Module Library
   7231 
   7232 
   7233 17.6   TPM2_EventSequenceComplete
   7234 
   7235 17.6.1 General Description
   7236 
   7237 This command adds the last part of data, if any, to an Event Sequence and returns the result in a digest
   7238 list. If pcrHandle references a PCR and not TPM_RH_NULL, then the returned digest list is processed in
   7239 the same manner as the digest list input parameter to TPM2_PCR_Extend() with the pcrHandle in each
   7240 bank extended with the associated digest value.
   7241 If sequenceHandle references a hash or HMAC sequence, the TPM shall return TPM_RC_MODE.
   7242 Proper authorization for the sequence object associated with sequenceHandle is required. If an
   7243 authorization or audit of this command requires computation of a cpHash and an rpHash, the Name
   7244 associated with sequenceHandle will be the Empty Buffer.
   7245 If this command completes successfully, the sequenceHandle object will be flushed.
   7246 
   7247 
   7248 
   7249 
   7250 Page 150                                   TCG Published                                   Family 2.0
   7251 October 30, 2014                    Copyright  TCG 2006-2014                 Level 00 Revision 01.16
   7252 Trusted Platform Module Library                                                            Part 3: Commands
   7254 
   7255 
   7256 
   7257 17.6.2 Command and Response
   7258 
   7259                       Table 75  TPM2_EventSequenceComplete Command
   7260 Type                          Name                  Description
   7261 
   7262 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   7263 UINT32                        commandSize
   7264 TPM_CC                        commandCode           TPM_CC_EventSequenceComplete {NV F}
   7265 
   7266                                                     PCR to be extended with the Event data
   7267 TPMI_DH_PCR+                  @ pcrHandle           Auth Index: 1
   7268                                                     Auth Role: USER
   7269                                                     authorization for the sequence
   7270 TPMI_DH_OBJECT                @sequenceHandle       Auth Index: 2
   7271                                                     Auth Role: USER
   7272 
   7273 TPM2B_MAX_BUFFER              buffer                data to be added to the Event
   7274 
   7275 
   7276                       Table 76  TPM2_EventSequenceComplete Response
   7277 Type                          Name                  Description
   7278 
   7279 TPM_ST                        tag                   see clause 6
   7280 UINT32                        responseSize
   7281 TPM_RC                        responseCode
   7282 
   7283 TPML_DIGEST_VALUES            results               list of digests computed for the PCR
   7284 
   7285 
   7286 
   7287 
   7288 Family 2.0                                 TCG Published                                        Page 151
   7289 Level 00 Revision 01.16                Copyright  TCG 2006-2014                           October 30, 2014
   7290      Part 3: Commands                                                            Trusted Platform Module Library
   7292 
   7293 
   7294 
   7295      17.6.3 Detailed Actions
   7296 
   7297 1    #include "InternalRoutines.h"
   7298 2    #include "EventSequenceComplete_fp.h"
   7299 3    #ifdef TPM_CC_EventSequenceComplete // Conditional expansion of this file
   7300 
   7301 
   7302      Error Returns                 Meaning
   7303 
   7304      TPM_RC_LOCALITY               PCR extension is not allowed at the current locality
   7305      TPM_RC_MODE                   input handle is not a valid event sequence object
   7306 
   7307  4   TPM_RC
   7308  5   TPM2_EventSequenceComplete(
   7309  6       EventSequenceComplete_In      *in,                // IN: input parameter list
   7310  7       EventSequenceComplete_Out     *out                // OUT: output parameter list
   7311  8       )
   7312  9   {
   7313 10       TPM_RC              result;
   7314 11       HASH_OBJECT        *hashObject;
   7315 12       UINT32              i;
   7316 13       TPM_ALG_ID          hashAlg;
   7317 14
   7318 15   // Input validation
   7319 16
   7320 17       // get the event sequence object pointer
   7321 18       hashObject = (HASH_OBJECT *)ObjectGet(in->sequenceHandle);
   7322 19
   7323 20       // input handle must reference an event sequence object
   7324 21       if(hashObject->attributes.eventSeq != SET)
   7325 22           return TPM_RC_MODE + RC_EventSequenceComplete_sequenceHandle;
   7326 23
   7327 24       // see if a PCR extend is requested in call
   7328 25       if(in->pcrHandle != TPM_RH_NULL)
   7329 26       {
   7330 27           // see if extend of the PCR is allowed at the locality of the command,
   7331 28           if(!PCRIsExtendAllowed(in->pcrHandle))
   7332 29               return TPM_RC_LOCALITY;
   7333 30           // if an extend is going to take place, then check to see if there has
   7334 31           // been an orderly shutdown. If so, and the selected PCR is one of the
   7335 32           // state saved PCR, then the orderly state has to change. The orderly state
   7336 33           // does not change for PCR that are not preserved.
   7337 34           // NOTE: This doesn't just check for Shutdown(STATE) because the orderly
   7338 35           // state will have to change if this is a state-saved PCR regardless
   7339 36           // of the current state. This is because a subsequent Shutdown(STATE) will
   7340 37           // check to see if there was an orderly shutdown and not do anything if
   7341 38           // there was. So, this must indicate that a future Shutdown(STATE) has
   7342 39           // something to do.
   7343 40           if(gp.orderlyState != SHUTDOWN_NONE && PCRIsStateSaved(in->pcrHandle))
   7344 41           {
   7345 42               result = NvIsAvailable();
   7346 43               if(result != TPM_RC_SUCCESS) return result;
   7347 44               g_clearOrderly = TRUE;
   7348 45           }
   7349 46       }
   7350 47
   7351 48   // Command Output
   7352 49
   7353 50       out->results.count = 0;
   7354 51
   7355 52       for(i = 0; i < HASH_COUNT; i++)
   7356 53       {
   7357 54           hashAlg = CryptGetHashAlgByIndex(i);
   7358 
   7359      Page 152                                   TCG Published                                        Family 2.0
   7360      October 30, 2014                  Copyright  TCG 2006-2014                          Level 00 Revision 01.16
   7361      Trusted Platform Module Library                                             Part 3: Commands
   7363 
   7364 55           // Update last piece of data
   7365 56           CryptUpdateDigest2B(&hashObject->state.hashState[i], &in->buffer.b);
   7366 57           // Complete hash
   7367 58           out->results.digests[out->results.count].hashAlg = hashAlg;
   7368 59           CryptCompleteHash(&hashObject->state.hashState[i],
   7369 60                           CryptGetHashDigestSize(hashAlg),
   7370 61                           (BYTE *) &out->results.digests[out->results.count].digest);
   7371 62
   7372 63           // Extend PCR
   7373 64           if(in->pcrHandle != TPM_RH_NULL)
   7374 65               PCRExtend(in->pcrHandle, hashAlg,
   7375 66                         CryptGetHashDigestSize(hashAlg),
   7376 67                         (BYTE *) &out->results.digests[out->results.count].digest);
   7377 68           out->results.count++;
   7378 69       }
   7379 70
   7380 71   // Internal Data Update
   7381 72
   7382 73       // mark sequence object as evict so it will be flushed on the way out
   7383 74       hashObject->attributes.evict = SET;
   7384 75
   7385 76       return TPM_RC_SUCCESS;
   7386 77   }
   7387 78   #endif // CC_EventSequenceComplete
   7388 
   7389 
   7390 
   7391 
   7392      Family 2.0                           TCG Published                                  Page 153
   7393      Level 00 Revision 01.16           Copyright  TCG 2006-2014                 October 30, 2014
   7394 Part 3: Commands                                                                 Trusted Platform Module Library
   7396 
   7397 
   7398 18     Attestation Commands
   7399 
   7400 18.1     Introduction
   7401 
   7402 The attestation commands cause the TPM to sign an internally generated data structure. The contents of
   7403 the data structure vary according to the command.
   7404 All signing commands include a parameter (typically inScheme) for the caller to specify a scheme to be
   7405 used for the signing operation. This scheme will be applied only if the scheme of the key is
   7406 TPM_ALG_NULL or the key handle is TPM_RH_NULL. If the scheme for signHandle is not
   7407 TPM_ALG_NULL, then inScheme.scheme shall be TPM_ALG_NULL or the same as scheme in the
   7408 public area of the key. If the scheme for signHandle is TPM_ALG_NULL or the key handle is
   7409 TPM_RH_NULL, then inScheme will be used for the signing operation and may not be TPM_ALG_NULL.
   7410 The TPM shall return TPM_RC_SCHEME to indicate that the scheme is not appropriate.
   7411 For a signing key that is not restricted, the caller may specify the scheme to be used as long as the
   7412 scheme is compatible with the family of the key (for example, TPM_ALG_RSAPSS cannot be selected for
   7413 an ECC key). If the caller sets scheme to TPM_ALG_NULL, then the default scheme of the key is used.
   7414 For a restricted signing key, the key's scheme cannot be TPM_ALG_NULL and cannot be overridden.
   7415 If the handle for the signing key (signHandle) is TPM_RH_NULL, then all of the actions of the command
   7416 are performed and the attestation block is signed with the NULL Signature.
   7417 
   7418 NOTE 1          This mechanism is provided so that additional commands are not required to access the data that
   7419                 might be in an attestation structure.
   7420 
   7421 NOTE 2          When signHandle is TPM_RH_NULL, scheme is still required to be a valid signing scheme (may be
   7422                 TPM_ALG_NULL), but the scheme will have no effect on the format of the signature. It will always
   7423                 be the NULL Signature.
   7424 
   7425 TPM2_NV_Certify() is an attestation command that is documented in 1. The remaining attestation
   7426 commands are collected in the remainder of this clause.
   7427 Each of the attestation structures contains a TPMS_CLOCK_INFO structure and a firmware version
   7428 number. These values may be considered privacy-sensitive, because they would aid in the correlation of
   7429 attestations by different keys. To provide improved privacy, the resetCount, restartCount, and
   7430 firmwareVersion numbers are obfuscated when the signing key is not in the Endorsement or Platform
   7431 hierarchies.
   7432 The obfuscation value is computed by:
   7433      obfuscation  KDFa(signHandlenameAlg, shProof, OBFUSCATE, signHandleQN, 0, 128) (3)
   7434 Of the returned 128 bits, 64 bits are added to the versionNumber field of the attestation structure; 32 bits
   7435 are added to the clockInfo.resetCount and 32 bits are added to the clockInfo.restartCount. The order in
   7436 which the bits are added is implementation-dependent.
   7437 
   7438 NOTE 3          The obfuscation value for each signing key will be unique to that key in a specific location. That is,
   7439                 each version of a duplicated signing key will have a different obfuscation value.
   7440 
   7441 When the signing key is TPM_RH_NULL, the data structure is produced but not signed; and the values in
   7442 the signed data structure are obfuscated. When computing the obfuscation value for TPM_RH_NULL, the
   7443 hash used for context integrity is used.
   7444 
   7445 NOTE 4          The QN for TPM_RH_NULL is TPM_RH_NULL.
   7446 
   7447 If the signing scheme of signHandle is an anonymous scheme, then the attestation blocks will not contain
   7448 the Qualified Name of the signHandle.
   7449 Each of the attestation structures allows the caller to provide some qualifying data (qualifyingData). For
   7450 most signing schemes, this value will be placed in the TPMS_ATTEST.extraData parameter that is then
   7451 
   7452 Page 154                                       TCG Published                                           Family 2.0
   7453 October 30, 2014                       Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   7454 Trusted Platform Module Library                                           Part 3: Commands
   7456 
   7457 hashed and signed. However, for some schemes such as ECDAA, the qualifyingData is used in a
   7458 different manner (for details, see ECDAA in TPM 2.0 Part 1).
   7459 
   7460 
   7461 
   7462 
   7463 Family 2.0                           TCG Published                              Page 155
   7464 Level 00 Revision 01.16           Copyright  TCG 2006-2014               October 30, 2014
   7465 Part 3: Commands                                                                  Trusted Platform Module Library
   7467 
   7468 
   7469 
   7470 18.2     TPM2_Certify
   7471 
   7472 18.2.1 General Description
   7473 
   7474 The purpose of this command is to prove that an object with a specific Name is loaded in the TPM. By
   7475 certifying that the object is loaded, the TPM warrants that a public area with a given Name is self-
   7476 consistent and associated with a valid sensitive area. If a relying party has a public area that has the
   7477 same Name as a Name certified with this command, then the values in that public area are correct.
   7478 
   7479 NOTE 1          See 18.1 for description of how the signing scheme is selected.
   7480 
   7481 Authorization for objectHandle requires ADMIN role authorization. If performed with a policy session, the
   7482 session shall have a policySessioncommandCode set to TPM_CC_Certify. This indicates that the
   7483 policy that is being used is a policy that is for certification, and not a policy that would approve another
   7484 use. That is, authority to use an object does not grant authority to certify the object.
   7485 The object may be any object that is loaded with TPM2_Load() or TPM2_CreatePrimary(). An object that
   7486 only has its public area loaded cannot be certified.
   7487 
   7488 NOTE 2          The restriction occurs because the Name is used to identify the object being certified. If the TPM
   7489                 has not validated that the public area is associated with a mat ched sensitive area, then the public
   7490                 area may not represent a valid object and cannot be certified.
   7491 
   7492 The certification includes the Name and Qualified Name of the certified object as well as the Name and
   7493 the Qualified Name of the certifying object.
   7494 
   7495 NOTE 2          If signHandle is TPM_RH_NULL, the TPMS_ATTEST structure is returned and signature is a NULL
   7496                 Signature.
   7497 
   7498 
   7499 
   7500 
   7501 Page 156                                       TCG Published                                         Family 2.0
   7502 October 30, 2014                       Copyright  TCG 2006-2014                       Level 00 Revision 01.16
   7503 Trusted Platform Module Library                                                            Part 3: Commands
   7505 
   7506 
   7507 
   7508 18.2.2 Command and Response
   7509 
   7510                                   Table 77  TPM2_Certify Command
   7511 Type                          Name                  Description
   7512 
   7513 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   7514 UINT32                        commandSize
   7515 TPM_CC                        commandCode           TPM_CC_Certify
   7516 
   7517                                                     handle of the object to be certified
   7518 TPMI_DH_OBJECT                @objectHandle         Auth Index: 1
   7519                                                     Auth Role: ADMIN
   7520                                                     handle of the key used to sign the attestation structure
   7521 TPMI_DH_OBJECT+               @signHandle           Auth Index: 2
   7522                                                     Auth Role: USER
   7523 
   7524 TPM2B_DATA                    qualifyingData        user provided qualifying data
   7525                                                     signing scheme to use if the scheme for signHandle is
   7526 TPMT_SIG_SCHEME+              inScheme
   7527                                                     TPM_ALG_NULL
   7528 
   7529 
   7530                                   Table 78  TPM2_Certify Response
   7531 Type                          Name                  Description
   7532 
   7533 TPM_ST                        tag                   see clause 6
   7534 UINT32                        responseSize
   7535 TPM_RC                        responseCode          .
   7536 
   7537 TPM2B_ATTEST                  certifyInfo           the structure that was signed
   7538                                                     the asymmetric signature over certifyInfo using the key
   7539 TPMT_SIGNATURE                signature
   7540                                                     referenced by signHandle
   7541 
   7542 
   7543 
   7544 
   7545 Family 2.0                                 TCG Published                                         Page 157
   7546 Level 00 Revision 01.16             Copyright  TCG 2006-2014                              October 30, 2014
   7547      Part 3: Commands                                                           Trusted Platform Module Library
   7549 
   7550 
   7551 
   7552      18.2.3 Detailed Actions
   7553 
   7554 1    #include "InternalRoutines.h"
   7555 2    #include "Attest_spt_fp.h"
   7556 3    #include "Certify_fp.h"
   7557 4    #ifdef TPM_CC_Certify // Conditional expansion of this file
   7558 
   7559 
   7560      Error Returns               Meaning
   7561 
   7562      TPM_RC_KEY                  key referenced by signHandle is not a signing key
   7563      TPM_RC_SCHEME               inScheme is not compatible with signHandle
   7564      TPM_RC_VALUE                digest generated for inScheme is greater or has larger size than the
   7565                                  modulus of signHandle, or the buffer for the result in signature is too
   7566                                  small (for an RSA key); invalid commit status (for an ECC key with a
   7567                                  split scheme).
   7568 
   7569  5   TPM_RC
   7570  6   TPM2_Certify(
   7571  7       Certify_In      *in,             // IN: input parameter list
   7572  8       Certify_Out     *out             // OUT: output parameter list
   7573  9       )
   7574 10   {
   7575 11       TPM_RC                 result;
   7576 12       TPMS_ATTEST            certifyInfo;
   7577 13
   7578 14   // Command Output
   7579 15
   7580 16       // Filling in attest information
   7581 17       // Common fields
   7582 18       result = FillInAttestInfo(in->signHandle,
   7583 19                                 &in->inScheme,
   7584 20                                 &in->qualifyingData,
   7585 21                                 &certifyInfo);
   7586 22       if(result != TPM_RC_SUCCESS)
   7587 23       {
   7588 24           if(result == TPM_RC_KEY)
   7589 25               return TPM_RC_KEY + RC_Certify_signHandle;
   7590 26           else
   7591 27               return RcSafeAddToResult(result, RC_Certify_inScheme);
   7592 28       }
   7593 29       // Certify specific fields
   7594 30       // Attestation type
   7595 31       certifyInfo.type = TPM_ST_ATTEST_CERTIFY;
   7596 32       // Certified object name
   7597 33       certifyInfo.attested.certify.name.t.size =
   7598 34           ObjectGetName(in->objectHandle,
   7599 35                         &certifyInfo.attested.certify.name.t.name);
   7600 36       // Certified object qualified name
   7601 37       ObjectGetQualifiedName(in->objectHandle,
   7602 38                              &certifyInfo.attested.certify.qualifiedName);
   7603 39
   7604 40       // Sign attestation structure. A NULL signature will be returned if
   7605 41       // signHandle is TPM_RH_NULL. A TPM_RC_NV_UNAVAILABLE, TPM_RC_NV_RATE,
   7606 42       // TPM_RC_VALUE, TPM_RC_SCHEME or TPM_RC_ATTRIBUTES error may be returned
   7607 43       // by SignAttestInfo()
   7608 44       result = SignAttestInfo(in->signHandle,
   7609 45                               &in->inScheme,
   7610 46                               &certifyInfo,
   7611 47                               &in->qualifyingData,
   7612 48                               &out->certifyInfo,
   7613 49                               &out->signature);
   7614 
   7615      Page 158                                 TCG Published                                           Family 2.0
   7616      October 30, 2014                Copyright  TCG 2006-2014                         Level 00 Revision 01.16
   7617      Trusted Platform Module Library                                             Part 3: Commands
   7619 
   7620 50
   7621 51       // TPM_RC_ATTRIBUTES cannot be returned here as FillInAttestInfo would already
   7622 52       // have returned TPM_RC_KEY
   7623 53       pAssert(result != TPM_RC_ATTRIBUTES);
   7624 54
   7625 55       if(result != TPM_RC_SUCCESS)
   7626 56           return result;
   7627 57
   7628 58       // orderly state should be cleared because of the reporting of clock info
   7629 59       // if signing happens
   7630 60       if(in->signHandle != TPM_RH_NULL)
   7631 61           g_clearOrderly = TRUE;
   7632 62
   7633 63       return TPM_RC_SUCCESS;
   7634 64   }
   7635 65   #endif // CC_Certify
   7636 
   7637 
   7638 
   7639 
   7640      Family 2.0                            TCG Published                                Page 159
   7641      Level 00 Revision 01.16            Copyright  TCG 2006-2014                October 30, 2014
   7642 Part 3: Commands                                                                  Trusted Platform Module Library
   7644 
   7645 
   7646 18.3     TPM2_CertifyCreation
   7647 
   7648 18.3.1 General Description
   7649 
   7650 This command is used to prove the association between an object and its creation data. The TPM will
   7651 validate that the ticket was produced by the TPM and that the ticket validates the association between a
   7652 loaded public area and the provided hash of the creation data (creationHash).
   7653 
   7654 NOTE 1          See 18.1 for description of how the signing scheme is selected.
   7655 
   7656 The TPM will create a test ticket using the Name associated with objectHandle and creationHash as:
   7657              HMAC(proof, (TPM_ST_CREATION || objectHandleName || creationHash))                              (4)
   7658 This ticket is then compared to creation ticket. If the tickets are not the same, the TPM shall return
   7659 TPM_RC_TICKET.
   7660 If the ticket is valid, then the TPM will create a TPMS_ATTEST structure and place creationHash of the
   7661 command in the creationHash field of the structure. The Name associated with objectHandle will be
   7662 included in the attestation data that is then signed using the key associated with signHandle.
   7663 
   7664 NOTE 2          If signHandle is TPM_RH_NULL, the TPMS_ATTEST structure is returned and signature is a NULL
   7665                 Signature.
   7666 
   7667 ObjectHandle may be any object that is loaded with TPM2_Load() or TPM2_CreatePrimary().
   7668 
   7669 
   7670 
   7671 
   7672 Page 160                                       TCG Published                                        Family 2.0
   7673 October 30, 2014                       Copyright  TCG 2006-2014                       Level 00 Revision 01.16
   7674 Trusted Platform Module Library                                                           Part 3: Commands
   7676 
   7677 
   7678 
   7679 18.3.2 Command and Response
   7680 
   7681                            Table 79  TPM2_CertifyCreation Command
   7682 Type                          Name                  Description
   7683 
   7684 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   7685 UINT32                        commandSize
   7686 TPM_CC                        commandCode           TPM_CC_CertifyCreation
   7687 
   7688                                                     handle of the key that will sign the attestation block
   7689 TPMI_DH_OBJECT+               @signHandle           Auth Index: 1
   7690                                                     Auth Role: USER
   7691                                                     the object associated with the creation data
   7692 TPMI_DH_OBJECT                objectHandle
   7693                                                     Auth Index: None
   7694 
   7695 TPM2B_DATA                    qualifyingData        user-provided qualifying data
   7696                                                     hash of the creation data produced by TPM2_Create()
   7697 TPM2B_DIGEST                  creationHash
   7698                                                     or TPM2_CreatePrimary()
   7699                                                     signing scheme to use if the scheme for signHandle is
   7700 TPMT_SIG_SCHEME+              inScheme
   7701                                                     TPM_ALG_NULL
   7702                                                     ticket produced by TPM2_Create() or
   7703 TPMT_TK_CREATION              creationTicket
   7704                                                     TPM2_CreatePrimary()
   7705 
   7706 
   7707                            Table 80  TPM2_CertifyCreation Response
   7708 Type                          Name                  Description
   7709 
   7710 TPM_ST                        tag                   see clause 6
   7711 UINT32                        responseSize
   7712 TPM_RC                        responseCode
   7713 
   7714 TPM2B_ATTEST                  certifyInfo           the structure that was signed
   7715 TPMT_SIGNATURE                signature             the signature over certifyInfo
   7716 
   7717 
   7718 
   7719 
   7720 Family 2.0                                 TCG Published                                          Page 161
   7721 Level 00 Revision 01.16             Copyright  TCG 2006-2014                             October 30, 2014
   7722      Part 3: Commands                                                           Trusted Platform Module Library
   7724 
   7725 
   7726 
   7727      18.3.3 Detailed Actions
   7728 
   7729 1    #include "InternalRoutines.h"
   7730 2    #include "Attest_spt_fp.h"
   7731 3    #include "CertifyCreation_fp.h"
   7732 4    #ifdef TPM_CC_CertifyCreation // Conditional expansion of this file
   7733 
   7734 
   7735      Error Returns               Meaning
   7736 
   7737      TPM_RC_KEY                  key referenced by signHandle is not a signing key
   7738      TPM_RC_SCHEME               inScheme is not compatible with signHandle
   7739      TPM_RC_TICKET               creationTicket does not match objectHandle
   7740      TPM_RC_VALUE                digest generated for inScheme is greater or has larger size than the
   7741                                  modulus of signHandle, or the buffer for the result in signature is too
   7742                                  small (for an RSA key); invalid commit status (for an ECC key with a
   7743                                  split scheme).
   7744 
   7745  5   TPM_RC
   7746  6   TPM2_CertifyCreation(
   7747  7       CertifyCreation_In     *in,                // IN: input parameter list
   7748  8       CertifyCreation_Out    *out                // OUT: output parameter list
   7749  9       )
   7750 10   {
   7751 11       TPM_RC                 result;
   7752 12       TPM2B_NAME             name;
   7753 13       TPMT_TK_CREATION       ticket;
   7754 14       TPMS_ATTEST            certifyInfo;
   7755 15
   7756 16   // Input Validation
   7757 17
   7758 18       // CertifyCreation specific input validation
   7759 19       // Get certified object name
   7760 20       name.t.size = ObjectGetName(in->objectHandle, &name.t.name);
   7761 21       // Re-compute ticket
   7762 22       TicketComputeCreation(in->creationTicket.hierarchy, &name,
   7763 23                             &in->creationHash, &ticket);
   7764 24       // Compare ticket
   7765 25       if(!Memory2BEqual(&ticket.digest.b, &in->creationTicket.digest.b))
   7766 26           return TPM_RC_TICKET + RC_CertifyCreation_creationTicket;
   7767 27
   7768 28   // Command Output
   7769 29       // Common fields
   7770 30       result = FillInAttestInfo(in->signHandle, &in->inScheme, &in->qualifyingData,
   7771 31                                 &certifyInfo);
   7772 32       if(result != TPM_RC_SUCCESS)
   7773 33       {
   7774 34           if(result == TPM_RC_KEY)
   7775 35               return TPM_RC_KEY + RC_CertifyCreation_signHandle;
   7776 36           else
   7777 37               return RcSafeAddToResult(result, RC_CertifyCreation_inScheme);
   7778 38       }
   7779 39
   7780 40       // CertifyCreation specific fields
   7781 41       // Attestation type
   7782 42       certifyInfo.type = TPM_ST_ATTEST_CREATION;
   7783 43       certifyInfo.attested.creation.objectName = name;
   7784 44
   7785 45       // Copy the creationHash
   7786 46       certifyInfo.attested.creation.creationHash = in->creationHash;
   7787 47
   7788 48       // Sign attestation structure.   A NULL signature will be returned if
   7789 
   7790      Page 162                                 TCG Published                                           Family 2.0
   7791      October 30, 2014                  Copyright  TCG 2006-2014                       Level 00 Revision 01.16
   7792      Trusted Platform Module Library                                             Part 3: Commands
   7794 
   7795 49       // signHandle is TPM_RH_NULL. A TPM_RC_NV_UNAVAILABLE, TPM_RC_NV_RATE,
   7796 50       // TPM_RC_VALUE, TPM_RC_SCHEME or TPM_RC_ATTRIBUTES error may be returned at
   7797 51       // this point
   7798 52       result = SignAttestInfo(in->signHandle,
   7799 53                               &in->inScheme,
   7800 54                               &certifyInfo,
   7801 55                               &in->qualifyingData,
   7802 56                               &out->certifyInfo,
   7803 57                               &out->signature);
   7804 58
   7805 59       // TPM_RC_ATTRIBUTES cannot be returned here as FillInAttestInfo would already
   7806 60       // have returned TPM_RC_KEY
   7807 61       pAssert(result != TPM_RC_ATTRIBUTES);
   7808 62
   7809 63       if(result != TPM_RC_SUCCESS)
   7810 64           return result;
   7811 65
   7812 66       // orderly state should be cleared because of the reporting of clock info
   7813 67       // if signing happens
   7814 68       if(in->signHandle != TPM_RH_NULL)
   7815 69           g_clearOrderly = TRUE;
   7816 70
   7817 71       return TPM_RC_SUCCESS;
   7818 72   }
   7819 73   #endif // CC_CertifyCreation
   7820 
   7821 
   7822 
   7823 
   7824      Family 2.0                            TCG Published                                Page 163
   7825      Level 00 Revision 01.16            Copyright  TCG 2006-2014                October 30, 2014
   7826 Part 3: Commands                                                                  Trusted Platform Module Library
   7828 
   7829 
   7830 18.4     TPM2_Quote
   7831 
   7832 18.4.1 General Description
   7833 
   7834 This command is used to quote PCR values.
   7835 
   7836 NOTE            See 18.1 for description of how the signing scheme is selected.
   7837 
   7838 The TPM will hash the list of PCR selected by PCRselect using the hash algorithm associated with
   7839 signHandle (this is the hash algorithm of the signing scheme, not the nameAlg of signHandle).
   7840 The digest is computed as the hash of the concatenation of all of the digest values of the selected PCR.
   7841 The concatenation of PCR is described in TPM 2.0 Part 1, Selecting Multiple PCR.
   7842 
   7843 NOTE 2          If signHandle is TPM_RH_NULL, the TPMS_ATTEST structure is returned and signature is a NULL
   7844                 Signature.
   7845 
   7846 
   7847 
   7848 
   7849 Page 164                                       TCG Published                                        Family 2.0
   7850 October 30, 2014                       Copyright  TCG 2006-2014                       Level 00 Revision 01.16
   7851 Trusted Platform Module Library                                                          Part 3: Commands
   7853 
   7854 
   7855 
   7856 18.4.2 Command and Response
   7857 
   7858                                   Table 81  TPM2_Quote Command
   7859 Type                          Name                  Description
   7860 
   7861 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   7862 UINT32                        commandSize
   7863 TPM_CC                        commandCode           TPM_CC_Quote
   7864 
   7865                                                     handle of key that will perform signature
   7866 TPMI_DH_OBJECT+               @signHandle           Auth Index: 1
   7867                                                     Auth Role: USER
   7868 
   7869 TPM2B_DATA                    qualifyingData        data supplied by the caller
   7870                                                     signing scheme to use if the scheme for signHandle is
   7871 TPMT_SIG_SCHEME+              inScheme
   7872                                                     TPM_ALG_NULL
   7873 TPML_PCR_SELECTION            PCRselect             PCR set to quote
   7874 
   7875 
   7876                                   Table 82  TPM2_Quote Response
   7877 Type                          Name                  Description
   7878 
   7879 TPM_ST                        tag                   see clause 6
   7880 UINT32                        responseSize
   7881 TPM_RC                        responseCode
   7882 
   7883 TPM2B_ATTEST                  quoted                the quoted information
   7884 TPMT_SIGNATURE                signature             the signature over quoted
   7885 
   7886 
   7887 
   7888 
   7889 Family 2.0                                 TCG Published                                      Page 165
   7890 Level 00 Revision 01.16             Copyright  TCG 2006-2014                            October 30, 2014
   7891      Part 3: Commands                                                           Trusted Platform Module Library
   7893 
   7894 
   7895 
   7896      18.4.3 Detailed Actions
   7897 
   7898 1    #include "InternalRoutines.h"
   7899 2    #include "Attest_spt_fp.h"
   7900 3    #include "Quote_fp.h"
   7901 4    #ifdef TPM_CC_Quote // Conditional expansion of this file
   7902 
   7903 
   7904      Error Returns               Meaning
   7905 
   7906      TPM_RC_KEY                  signHandle does not reference a signing key;
   7907      TPM_RC_SCHEME               the scheme is not compatible with sign key type, or input scheme is
   7908                                  not compatible with default scheme, or the chosen scheme is not a
   7909                                  valid sign scheme
   7910 
   7911  5   TPM_RC
   7912  6   TPM2_Quote(
   7913  7       Quote_In        *in,             // IN: input parameter list
   7914  8       Quote_Out       *out             // OUT: output parameter list
   7915  9       )
   7916 10   {
   7917 11       TPM_RC                  result;
   7918 12       TPMI_ALG_HASH           hashAlg;
   7919 13       TPMS_ATTEST             quoted;
   7920 14
   7921 15   // Command Output
   7922 16
   7923 17       // Filling in attest information
   7924 18       // Common fields
   7925 19       // FillInAttestInfo may return TPM_RC_SCHEME or TPM_RC_KEY
   7926 20       result = FillInAttestInfo(in->signHandle,
   7927 21                                 &in->inScheme,
   7928 22                                 &in->qualifyingData,
   7929 23                                 &quoted);
   7930 24       if(result != TPM_RC_SUCCESS)
   7931 25       {
   7932 26           if(result == TPM_RC_KEY)
   7933 27               return TPM_RC_KEY + RC_Quote_signHandle;
   7934 28           else
   7935 29               return RcSafeAddToResult(result, RC_Quote_inScheme);
   7936 30       }
   7937 31
   7938 32       // Quote specific fields
   7939 33       // Attestation type
   7940 34       quoted.type = TPM_ST_ATTEST_QUOTE;
   7941 35
   7942 36       // Get hash algorithm in sign scheme. This hash algorithm is used to
   7943 37       // compute PCR digest. If there is no algorithm, then the PCR cannot
   7944 38       // be digested and this command returns TPM_RC_SCHEME
   7945 39       hashAlg = in->inScheme.details.any.hashAlg;
   7946 40
   7947 41       if(hashAlg == TPM_ALG_NULL)
   7948 42           return TPM_RC_SCHEME + RC_Quote_inScheme;
   7949 43
   7950 44       // Compute PCR digest
   7951 45       PCRComputeCurrentDigest(hashAlg,
   7952 46                               &in->PCRselect,
   7953 47                               &quoted.attested.quote.pcrDigest);
   7954 48
   7955 49       // Copy PCR select. "PCRselect" is modified in PCRComputeCurrentDigest
   7956 50       // function
   7957 51       quoted.attested.quote.pcrSelect = in->PCRselect;
   7958 52
   7959 
   7960      Page 166                                 TCG Published                                        Family 2.0
   7961      October 30, 2014                Copyright  TCG 2006-2014                       Level 00 Revision 01.16
   7962      Trusted Platform Module Library                                             Part 3: Commands
   7964 
   7965 53       // Sign attestation structure. A NULL signature will be returned if
   7966 54       // signHandle is TPM_RH_NULL. TPM_RC_VALUE, TPM_RC_SCHEME or TPM_RC_ATTRIBUTES
   7967 55       // error may be returned by SignAttestInfo.
   7968 56       // NOTE: TPM_RC_ATTRIBUTES means that the key is not a signing key but that
   7969 57       // was checked above and TPM_RC_KEY was returned. TPM_RC_VALUE means that the
   7970 58       // value to sign is too large but that means that the digest is too big and
   7971 59       // that can't happen.
   7972 60       result = SignAttestInfo(in->signHandle,
   7973 61                               &in->inScheme,
   7974 62                               &quoted,
   7975 63                               &in->qualifyingData,
   7976 64                               &out->quoted,
   7977 65                               &out->signature);
   7978 66       if(result != TPM_RC_SUCCESS)
   7979 67           return result;
   7980 68
   7981 69       // orderly state should be cleared because of the reporting of clock info
   7982 70       // if signing happens
   7983 71       if(in->signHandle != TPM_RH_NULL)
   7984 72           g_clearOrderly = TRUE;
   7985 73
   7986 74       return TPM_RC_SUCCESS;
   7987 75   }
   7988 76   #endif // CC_Quote
   7989 
   7990 
   7991 
   7992 
   7993      Family 2.0                           TCG Published                                 Page 167
   7994      Level 00 Revision 01.16           Copyright  TCG 2006-2014                 October 30, 2014
   7995 Part 3: Commands                                                                  Trusted Platform Module Library
   7997 
   7998 
   7999 18.5     TPM2_GetSessionAuditDigest
   8000 
   8001 18.5.1 General Description
   8002 
   8003 This command returns a digital signature of the audit session digest.
   8004 
   8005 NOTE 1          See 18.1 for description of how the signing scheme is selected.
   8006 
   8007 If sessionHandle is not an audit session, the TPM shall return TPM_RC_TYPE.
   8008 
   8009 NOTE 2          A session does not become an audit session until the successful completion of the command in
   8010                 which the session is first used as an audit session.
   8011 
   8012 This command requires authorization from the privacy administrator of the TPM (expressed with
   8013 Endorsement Authorization) as well as authorization to use the key associated with signHandle.
   8014 If this command is audited, then the audit digest that is signed will not include the digest of this command
   8015 because the audit digest is only updated when the command completes successfully.
   8016 This command does not cause the audit session to be closed and does not reset the digest value.
   8017 
   8018 NOTE 3          If sessionHandle is used as an audit session for this command, the command is audited in the same
   8019                 manner as any other command.
   8020 
   8021 NOTE 4          If signHandle is TPM_RH_NULL, the TPMS_ATTEST structure is returned and signature is a NULL
   8022                 Signature.
   8023 
   8024 
   8025 
   8026 
   8027 Page 168                                       TCG Published                                        Family 2.0
   8028 October 30, 2014                       Copyright  TCG 2006-2014                       Level 00 Revision 01.16
   8029 Trusted Platform Module Library                                                           Part 3: Commands
   8031 
   8032 
   8033 
   8034 18.5.2 Command and Response
   8035 
   8036                        Table 83  TPM2_GetSessionAuditDigest Command
   8037 Type                          Name                  Description
   8038 
   8039 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   8040 UINT32                        commandSize
   8041 TPM_CC                        commandCode           TPM_CC_GetSessionAuditDigest
   8042 
   8043                                                     handle of the privacy administrator
   8044                                                     (TPM_RH_ENDORSEMENT)
   8045 TPMI_RH_ENDORSEMENT           @privacyAdminHandle
   8046                                                     Auth Index: 1
   8047                                                     Auth Role: USER
   8048                                                     handle of the signing key
   8049 TPMI_DH_OBJECT+               @signHandle           Auth Index: 2
   8050                                                     Auth Role: USER
   8051                                                     handle of the audit session
   8052 TPMI_SH_HMAC                  sessionHandle
   8053                                                     Auth Index: None
   8054 
   8055 TPM2B_DATA                    qualifyingData        user-provided qualifying data  may be zero-length
   8056                                                     signing scheme to use if the scheme for signHandle is
   8057 TPMT_SIG_SCHEME+              inScheme
   8058                                                     TPM_ALG_NULL
   8059 
   8060 
   8061                        Table 84  TPM2_GetSessionAuditDigest Response
   8062 Type                          Name                  Description
   8063 
   8064 TPM_ST                        tag                   see clause 6
   8065 UINT32                        responseSize
   8066 TPM_RC                        responseCode
   8067 
   8068 TPM2B_ATTEST                  auditInfo             the audit information that was signed
   8069 TPMT_SIGNATURE                signature             the signature over auditInfo
   8070 
   8071 
   8072 
   8073 
   8074 Family 2.0                                 TCG Published                                       Page 169
   8075 Level 00 Revision 01.16             Copyright  TCG 2006-2014                             October 30, 2014
   8076      Part 3: Commands                                                            Trusted Platform Module Library
   8078 
   8079 
   8080 
   8081      18.5.3 Detailed Actions
   8082 
   8083 1    #include "InternalRoutines.h"
   8084 2    #include "Attest_spt_fp.h"
   8085 3    #include "GetSessionAuditDigest_fp.h"
   8086 4    #ifdef TPM_CC_GetSessionAuditDigest // Conditional expansion of this file
   8087 
   8088 
   8089      Error Returns                 Meaning
   8090 
   8091      TPM_RC_KEY                    key referenced by signHandle is not a signing key
   8092      TPM_RC_SCHEME                 inScheme is incompatible with signHandle type; or both scheme and
   8093                                    key's default scheme are empty; or scheme is empty while key's
   8094                                    default scheme requires explicit input scheme (split signing); or non-
   8095                                    empty default key scheme differs from scheme
   8096      TPM_RC_TYPE                   sessionHandle does not reference an audit session
   8097      TPM_RC_VALUE                  digest generated for the given scheme is greater than the modulus of
   8098                                    signHandle (for an RSA key); invalid commit status or failed to
   8099                                    generate r value (for an ECC key)
   8100 
   8101  5   TPM_RC
   8102  6   TPM2_GetSessionAuditDigest(
   8103  7       GetSessionAuditDigest_In      *in,                // IN: input parameter list
   8104  8       GetSessionAuditDigest_Out     *out                // OUT: output parameter list
   8105  9       )
   8106 10   {
   8107 11       TPM_RC                  result;
   8108 12       SESSION                *session;
   8109 13       TPMS_ATTEST             auditInfo;
   8110 14
   8111 15   // Input Validation
   8112 16
   8113 17       // SessionAuditDigest specific input validation
   8114 18       // Get session pointer
   8115 19       session = SessionGet(in->sessionHandle);
   8116 20
   8117 21       // session must be an audit session
   8118 22       if(session->attributes.isAudit == CLEAR)
   8119 23           return TPM_RC_TYPE + RC_GetSessionAuditDigest_sessionHandle;
   8120 24
   8121 25   // Command Output
   8122 26
   8123 27       // Filling in attest information
   8124 28       // Common fields
   8125 29       result = FillInAttestInfo(in->signHandle,
   8126 30                                 &in->inScheme,
   8127 31                                 &in->qualifyingData,
   8128 32                                 &auditInfo);
   8129 33       if(result != TPM_RC_SUCCESS)
   8130 34       {
   8131 35           if(result == TPM_RC_KEY)
   8132 36               return TPM_RC_KEY + RC_GetSessionAuditDigest_signHandle;
   8133 37           else
   8134 38               return RcSafeAddToResult(result, RC_GetSessionAuditDigest_inScheme);
   8135 39       }
   8136 40
   8137 41       // SessionAuditDigest specific fields
   8138 42       // Attestation type
   8139 43       auditInfo.type = TPM_ST_ATTEST_SESSION_AUDIT;
   8140 44
   8141 45       // Copy digest
   8142 46       auditInfo.attested.sessionAudit.sessionDigest = session->u2.auditDigest;
   8143 
   8144      Page 170                                   TCG Published                                          Family 2.0
   8145      October 30, 2014                  Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   8146      Trusted Platform Module Library                                             Part 3: Commands
   8148 
   8149 47
   8150 48       // Exclusive audit session
   8151 49       if(g_exclusiveAuditSession == in->sessionHandle)
   8152 50           auditInfo.attested.sessionAudit.exclusiveSession = TRUE;
   8153 51       else
   8154 52           auditInfo.attested.sessionAudit.exclusiveSession = FALSE;
   8155 53
   8156 54       // Sign attestation structure. A NULL signature will be returned if
   8157 55       // signHandle is TPM_RH_NULL. A TPM_RC_NV_UNAVAILABLE, TPM_RC_NV_RATE,
   8158 56       // TPM_RC_VALUE, TPM_RC_SCHEME or TPM_RC_ATTRIBUTES error may be returned at
   8159 57       // this point
   8160 58       result = SignAttestInfo(in->signHandle,
   8161 59                               &in->inScheme,
   8162 60                               &auditInfo,
   8163 61                               &in->qualifyingData,
   8164 62                               &out->auditInfo,
   8165 63                               &out->signature);
   8166 64       if(result != TPM_RC_SUCCESS)
   8167 65           return result;
   8168 66
   8169 67       // orderly state should be cleared because of the reporting of clock info
   8170 68       // if signing happens
   8171 69       if(in->signHandle != TPM_RH_NULL)
   8172 70           g_clearOrderly = TRUE;
   8173 71
   8174 72       return TPM_RC_SUCCESS;
   8175 73   }
   8176 74   #endif // CC_GetSessionAuditDigest
   8177 
   8178 
   8179 
   8180 
   8181      Family 2.0                           TCG Published                               Page 171
   8182      Level 00 Revision 01.16           Copyright  TCG 2006-2014                 October 30, 2014
   8183 Part 3: Commands                                                                  Trusted Platform Module Library
   8185 
   8186 
   8187 18.6     TPM2_GetCommandAuditDigest
   8188 
   8189 18.6.1 General Description
   8190 
   8191 This command returns the current value of the command audit digest, a digest of the commands being
   8192 audited, and the audit hash algorithm. These values are placed in an attestation structure and signed with
   8193 the key referenced by signHandle.
   8194 
   8195 NOTE 1          See 18.1 for description of how the signing scheme is selected.
   8196 
   8197 When this command completes successfully, and signHandle is not TPM_RH_NULL, the audit digest is
   8198 cleared. If signHandle is TPM_RH_NULL, signature is the Empty Buffer and the audit digest is not
   8199 cleared.
   8200 
   8201 NOTE 2          The way that the TPM tracks that the digest is clear is vendor-dependent. The reference
   8202                 implementation resets the size of the digest to zero.
   8203 
   8204 If this command is being audited, then the signed digest produced by the command will not include the
   8205 command. At the end of this command, the audit digest will be extended with cpHash and the rpHash of
   8206 the command which would change the command audit digest signed by the next invocation of this
   8207 command.
   8208 This command requires authorization from the privacy administrator of the TPM (expressed with
   8209 Endorsement Authorization) as well as authorization to use the key associated with signHandle.
   8210 
   8211 
   8212 
   8213 
   8214 Page 172                                       TCG Published                                        Family 2.0
   8215 October 30, 2014                       Copyright  TCG 2006-2014                       Level 00 Revision 01.16
   8216 Trusted Platform Module Library                                                            Part 3: Commands
   8218 
   8219 
   8220 
   8221 18.6.2 Command and Response
   8222 
   8223                       Table 85  TPM2_GetCommandAuditDigest Command
   8224  Type                         Name                   Description
   8225 
   8226  TPMI_ST_COMMAND_TAG          tag                    TPM_ST_SESSIONS
   8227  UINT32                       commandSize
   8228  TPM_CC                       commandCode            TPM_CC_GetCommandAuditDigest {NV}
   8229 
   8230                                                      handle of the privacy administrator
   8231                                                      (TPM_RH_ENDORSEMENT)
   8232  TPMI_RH_ENDORSEMENT          @privacyHandle
   8233                                                      Auth Index: 1
   8234                                                      Auth Role: USER
   8235                                                      the handle of the signing key
   8236  TPMI_DH_OBJECT+              @signHandle            Auth Index: 2
   8237                                                      Auth Role: USER
   8238 
   8239  TPM2B_DATA                   qualifyingData         other data to associate with this audit digest
   8240                                                      signing scheme to use if the scheme for signHandle is
   8241  TPMT_SIG_SCHEME+             inScheme
   8242                                                      TPM_ALG_NULL
   8243 
   8244 
   8245                       Table 86  TPM2_GetCommandAuditDigest Response
   8246 Type                          Name                  Description
   8247 
   8248 TPM_ST                        tag                   see clause 6
   8249 UINT32                        responseSize
   8250 TPM_RC                        responseCode
   8251 
   8252 TPM2B_ATTEST                  auditInfo             the auditInfo that was signed
   8253 TPMT_SIGNATURE                signature             the signature over auditInfo
   8254 
   8255 
   8256 
   8257 
   8258 Family 2.0                                 TCG Published                                            Page 173
   8259 Level 00 Revision 01.16             Copyright  TCG 2006-2014                              October 30, 2014
   8260      Part 3: Commands                                                            Trusted Platform Module Library
   8262 
   8263 
   8264 
   8265      18.6.3 Detailed Actions
   8266 
   8267 1    #include "InternalRoutines.h"
   8268 2    #include "Attest_spt_fp.h"
   8269 3    #include "GetCommandAuditDigest_fp.h"
   8270 4    #ifdef TPM_CC_GetCommandAuditDigest // Conditional expansion of this file
   8271 
   8272 
   8273      Error Returns                 Meaning
   8274 
   8275      TPM_RC_KEY                    key referenced by signHandle is not a signing key
   8276      TPM_RC_SCHEME                 inScheme is incompatible with signHandle type; or both scheme and
   8277                                    key's default scheme are empty; or scheme is empty while key's
   8278                                    default scheme requires explicit input scheme (split signing); or non-
   8279                                    empty default key scheme differs from scheme
   8280      TPM_RC_VALUE                  digest generated for the given scheme is greater than the modulus of
   8281                                    signHandle (for an RSA key); invalid commit status or failed to
   8282                                    generate r value (for an ECC key)
   8283 
   8284  5   TPM_RC
   8285  6   TPM2_GetCommandAuditDigest(
   8286  7       GetCommandAuditDigest_In      *in,                // IN: input parameter list
   8287  8       GetCommandAuditDigest_Out     *out                // OUT: output parameter list
   8288  9       )
   8289 10   {
   8290 11       TPM_RC                   result;
   8291 12       TPMS_ATTEST              auditInfo;
   8292 13
   8293 14   // Command Output
   8294 15
   8295 16       // Filling in attest information
   8296 17       // Common fields
   8297 18       result = FillInAttestInfo(in->signHandle,
   8298 19                                 &in->inScheme,
   8299 20                                 &in->qualifyingData,
   8300 21                                 &auditInfo);
   8301 22       if(result != TPM_RC_SUCCESS)
   8302 23       {
   8303 24           if(result == TPM_RC_KEY)
   8304 25               return TPM_RC_KEY + RC_GetCommandAuditDigest_signHandle;
   8305 26           else
   8306 27               return RcSafeAddToResult(result, RC_GetCommandAuditDigest_inScheme);
   8307 28       }
   8308 29
   8309 30       // CommandAuditDigest specific fields
   8310 31       // Attestation type
   8311 32       auditInfo.type = TPM_ST_ATTEST_COMMAND_AUDIT;
   8312 33
   8313 34       // Copy audit hash algorithm
   8314 35       auditInfo.attested.commandAudit.digestAlg = gp.auditHashAlg;
   8315 36
   8316 37       // Copy counter value
   8317 38       auditInfo.attested.commandAudit.auditCounter = gp.auditCounter;
   8318 39
   8319 40       // Copy command audit log
   8320 41       auditInfo.attested.commandAudit.auditDigest = gr.commandAuditDigest;
   8321 42       CommandAuditGetDigest(&auditInfo.attested.commandAudit.commandDigest);
   8322 43
   8323 44       //   Sign attestation structure. A NULL signature will be returned if
   8324 45       //   signHandle is TPM_RH_NULL. A TPM_RC_NV_UNAVAILABLE, TPM_RC_NV_RATE,
   8325 46       //   TPM_RC_VALUE, TPM_RC_SCHEME or TPM_RC_ATTRIBUTES error may be returned at
   8326 47       //   this point
   8327 
   8328      Page 174                                   TCG Published                                          Family 2.0
   8329      October 30, 2014                  Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   8330      Trusted Platform Module Library                                         Part 3: Commands
   8332 
   8333 48       result = SignAttestInfo(in->signHandle,
   8334 49                               &in->inScheme,
   8335 50                               &auditInfo,
   8336 51                               &in->qualifyingData,
   8337 52                               &out->auditInfo,
   8338 53                               &out->signature);
   8339 54
   8340 55       if(result != TPM_RC_SUCCESS)
   8341 56           return result;
   8342 57
   8343 58   // Internal Data Update
   8344 59
   8345 60       if(in->signHandle != TPM_RH_NULL)
   8346 61       {
   8347 62           // Reset log
   8348 63           gr.commandAuditDigest.t.size = 0;
   8349 64
   8350 65           // orderly state should be cleared because of the update in
   8351 66           // commandAuditDigest, as well as the reporting of clock info
   8352 67           g_clearOrderly = TRUE;
   8353 68       }
   8354 69
   8355 70       return TPM_RC_SUCCESS;
   8356 71   }
   8357 72   #endif // CC_GetCommandAuditDigest
   8358 
   8359 
   8360 
   8361 
   8362      Family 2.0                            TCG Published                          Page 175
   8363      Level 00 Revision 01.16            Copyright  TCG 2006-2014            October 30, 2014
   8364 Part 3: Commands                                                                  Trusted Platform Module Library
   8366 
   8367 
   8368 18.7     TPM2_GetTime
   8369 
   8370 18.7.1 General Description
   8371 
   8372 This command returns the current values of Time and Clock.
   8373 
   8374 NOTE 1          See 18.1 for description of how the signing scheme is selected.
   8375 
   8376 The values of Clock, resetCount and restartCount appear in two places in timeInfo: once in
   8377 TPMS_ATTEST.clockInfo and again in TPMS_ATTEST.attested.time.clockInfo. The firmware version
   8378 number       also      appears       in      two    places     (TPMS_ATTEST.firmwareVersion             and
   8379 TPMS_ATTEST.attested.time.firmwareVersion). If signHandle is in the endorsement or platform
   8380 hierarchies, both copies of the data will be the same. However, if signHandle is in the storage hierarchy or
   8381 is TPM_RH_NULL, the values in TPMS_ATTEST.clockInfo and TPMS_ATTEST.firmwareVersion are
   8382 obfuscated but the values in TPMS_ATTEST.attested.time are not.
   8383 
   8384 NOTE 2          The purpose of this duplication is to allow an entity who is trusted by the privacy Administrator to
   8385                 correlate the obfuscated values with the clear-text values. This command requires Endorsement
   8386                 Authorization.
   8387 
   8388 NOTE 3          If signHandle is TPM_RH_NULL, the TPMS_ATTEST structure is returned and signature is a NULL
   8389                 Signature.
   8390 
   8391 
   8392 
   8393 
   8394 Page 176                                       TCG Published                                         Family 2.0
   8395 October 30, 2014                       Copyright  TCG 2006-2014                       Level 00 Revision 01.16
   8396 Trusted Platform Module Library                                                           Part 3: Commands
   8398 
   8399 
   8400 
   8401 18.7.2 Command and Response
   8402 
   8403                                   Table 87  TPM2_GetTime Command
   8404 Type                          Name                  Description
   8405 
   8406 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   8407 UINT32                        commandSize
   8408 TPM_CC                        commandCode           TPM_CC_GetTime
   8409 
   8410                                                     handle of the privacy administrator
   8411                                                     (TPM_RH_ENDORSEMENT)
   8412 TPMI_RH_ENDORSEMENT           @privacyAdminHandle
   8413                                                     Auth Index: 1
   8414                                                     Auth Role: USER
   8415                                                     the keyHandle identifier of a loaded key that can
   8416                                                     perform digital signatures
   8417 TPMI_DH_OBJECT+               @signHandle
   8418                                                     Auth Index: 2
   8419                                                     Auth Role: USER
   8420 
   8421 TPM2B_DATA                    qualifyingData        data to tick stamp
   8422                                                     signing scheme to use if the scheme for signHandle is
   8423 TPMT_SIG_SCHEME+              inScheme
   8424                                                     TPM_ALG_NULL
   8425 
   8426 
   8427                                   Table 88  TPM2_GetTime Response
   8428 Type                          Name                  Description
   8429 
   8430 TPM_ST                        tag                   see clause 6
   8431 UINT32                        responseSize
   8432 TPM_RC                        responseCode          .
   8433 
   8434 TPM2B_ATTEST                  timeInfo              standard TPM-generated attestation block
   8435 TPMT_SIGNATURE                signature             the signature over timeInfo
   8436 
   8437 
   8438 
   8439 
   8440 Family 2.0                                 TCG Published                                        Page 177
   8441 Level 00 Revision 01.16              Copyright  TCG 2006-2014                            October 30, 2014
   8442      Part 3: Commands                                                          Trusted Platform Module Library
   8444 
   8445 
   8446 
   8447      18.7.3 Detailed Actions
   8448 
   8449 1    #include "InternalRoutines.h"
   8450 2    #include "Attest_spt_fp.h"
   8451 3    #include "GetTime_fp.h"
   8452 4    #ifdef TPM_CC_GetTime // Conditional expansion of this file
   8453 
   8454 
   8455      Error Returns               Meaning
   8456 
   8457      TPM_RC_KEY                  key referenced by signHandle is not a signing key
   8458      TPM_RC_SCHEME               inScheme is incompatible with signHandle type; or both scheme and
   8459                                  key's default scheme are empty; or scheme is empty while key's
   8460                                  default scheme requires explicit input scheme (split signing); or non-
   8461                                  empty default key scheme differs from scheme
   8462      TPM_RC_VALUE                digest generated for the given scheme is greater than the modulus of
   8463                                  signHandle (for an RSA key); invalid commit status or failed to
   8464                                  generate r value (for an ECC key)
   8465 
   8466  5   TPM_RC
   8467  6   TPM2_GetTime(
   8468  7       GetTime_In      *in,             // IN: input parameter list
   8469  8       GetTime_Out     *out             // OUT: output parameter list
   8470  9       )
   8471 10   {
   8472 11       TPM_RC                 result;
   8473 12       TPMS_ATTEST            timeInfo;
   8474 13
   8475 14   // Command Output
   8476 15
   8477 16       // Filling in attest information
   8478 17       // Common fields
   8479 18       result = FillInAttestInfo(in->signHandle,
   8480 19                                 &in->inScheme,
   8481 20                                 &in->qualifyingData,
   8482 21                                 &timeInfo);
   8483 22       if(result != TPM_RC_SUCCESS)
   8484 23       {
   8485 24           if(result == TPM_RC_KEY)
   8486 25               return TPM_RC_KEY + RC_GetTime_signHandle;
   8487 26           else
   8488 27               return RcSafeAddToResult(result, RC_GetTime_inScheme);
   8489 28       }
   8490 29
   8491 30       // GetClock specific fields
   8492 31       // Attestation type
   8493 32       timeInfo.type = TPM_ST_ATTEST_TIME;
   8494 33
   8495 34       // current clock in plain text
   8496 35       timeInfo.attested.time.time.time = g_time;
   8497 36       TimeFillInfo(&timeInfo.attested.time.time.clockInfo);
   8498 37
   8499 38       // Firmware version in plain text
   8500 39       timeInfo.attested.time.firmwareVersion
   8501 40           = ((UINT64) gp.firmwareV1) << 32;
   8502 41       timeInfo.attested.time.firmwareVersion += gp.firmwareV2;
   8503 42
   8504 43       // Sign attestation structure. A NULL signature will be returned if
   8505 44       // signHandle is TPM_RH_NULL. A TPM_RC_NV_UNAVAILABLE, TPM_RC_NV_RATE,
   8506 45       // TPM_RC_VALUE, TPM_RC_SCHEME or TPM_RC_ATTRIBUTES error may be returned at
   8507 46       // this point
   8508 47       result = SignAttestInfo(in->signHandle,
   8509 
   8510      Page 178                                  TCG Published                                         Family 2.0
   8511      October 30, 2014                Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   8512      Trusted Platform Module Library                                             Part 3: Commands
   8514 
   8515 48                               &in->inScheme,
   8516 49                               &timeInfo,
   8517 50                               &in->qualifyingData,
   8518 51                               &out->timeInfo,
   8519 52                               &out->signature);
   8520 53       if(result != TPM_RC_SUCCESS)
   8521 54           return result;
   8522 55
   8523 56       // orderly state should be cleared because of the reporting of clock info
   8524 57       // if signing happens
   8525 58       if(in->signHandle != TPM_RH_NULL)
   8526 59           g_clearOrderly = TRUE;
   8527 60
   8528 61       return TPM_RC_SUCCESS;
   8529 62   }
   8530 63   #endif // CC_GetTime
   8531 
   8532 
   8533 
   8534 
   8535      Family 2.0                           TCG Published                               Page 179
   8536      Level 00 Revision 01.16           Copyright  TCG 2006-2014                 October 30, 2014
   8537 Part 3: Commands                                                              Trusted Platform Module Library
   8539 
   8540 
   8541 19     Ephemeral EC Keys
   8542 
   8543 19.1    Introduction
   8544 
   8545 The TPM generates keys that have different lifetimes. TPM keys in a hierarchy can be persistent for as
   8546 long as the seed of the hierarchy is unchanged and these keys may be used multiple times. Other TPM-
   8547 generated keys are only useful for a single operation. Some of these single-use keys are used in the
   8548 command in which they are created. Examples of this use are TPM2_Duplicate() where an ephemeral
   8549 key is created for a single pass key exchange with another TPM. However, there are other cases, such
   8550 as anonymous attestation, where the protocol requires two passes where the public part of the ephemeral
   8551 key is used outside of the TPM before the final command "consumes" the ephemeral key.
   8552 For these uses, TPM2_Commit() or TPM2_EC_Ephemeral() may be used to have the TPM create an
   8553 ephemeral EC key and return the public part of the key for external use. Then in a subsequent command,
   8554 the caller provides a reference to the ephemeral key so that the TPM can retrieve or recreate the
   8555 associated private key.
   8556 When an ephemeral EC key is created, it is assigned a number and that number is returned to the caller
   8557 as the identifier for the key. This number is not a handle. A handle is assigned to a key that may be
   8558 context saved but these ephemeral EC keys may not be saved and do not have a full key context. When
   8559 a subsequent command uses the ephemeral key, the caller provides the number of the ephemeral key.
   8560 The TPM uses that number to either look up or recompute the associated private key. After the key is
   8561 used, the TPM records the fact that the key has been used so that it cannot be used again.
   8562 As mentioned, the TPM can keep each assigned private ephemeral key in memory until it is used.
   8563 However, this could consume a large amount of memory. To limit the memory size, the TPM is allowed to
   8564 restrict the number of pending private keys  keys that have been allocated but not used.
   8565 
   8566 NOTE            The minimum number of ephemeral keys is determined by a platform specific specification
   8567 
   8568 To further reduce the memory requirements for the ephemeral private keys, the TPM is allowed to use
   8569 pseudo-random values for the ephemeral keys. Instead of keeping the full value of the key in memory, the
   8570 TPM can use a counter as input to a KDF. Incrementing the counter will cause the TPM to generate a
   8571 new pseudo-random value.
   8572 Using the counter to generate pseudo-random private ephemeral keys greatly simplifies tracking of key
   8573 usage. When a counter value is used to create a key, a bit in an array may be set to indicate that the key
   8574 use is pending. When the ephemeral key is consumed, the bit is cleared. This prevents the key from
   8575 being used more than once.
   8576 Since the TPM is allowed to restrict the number of pending ephemeral keys, the array size can be limited.
   8577 For example, a 128 bit array would allow 128 keys to be "pending".
   8578 The management of the array is described in greater detail in the Split Operations clause in Annex C of
   8579 TPM 2.0 Part 1.
   8580 
   8581 
   8582 
   8583 
   8584 Page 180                                      TCG Published                                        Family 2.0
   8585 October 30, 2014                      Copyright  TCG 2006-2014                     Level 00 Revision 01.16
   8586 Trusted Platform Module Library                                                            Part 3: Commands
   8588 
   8589 
   8590 
   8591 19.2   TPM2_Commit
   8592 
   8593 19.2.1 General Description
   8594 
   8595 TPM2_Commit() performs the first part of an ECC anonymous signing operation. The TPM will perform
   8596 the point multiplications on the provided points and return intermediate signing values. The signHandle
   8597 parameter shall refer to an ECC key with the sign attribute (TPM_RC_ATTRIBUTES) and the signing
   8598 scheme must be anonymous (TPM_RC_SCHEME). Currently, TPM_ALG_ECDAA is the only defined
   8599 anonymous scheme.
   8600 
   8601 NOTE           This command cannot be used with a sign+decrypt key because that type of key is req uired to have
   8602                a scheme of TPM_ALG_NULL.
   8603 
   8604 For this command, p1, s2 and y2 are optional parameters. If s2 is an Empty Buffer, then the TPM shall
   8605 return TPM_RC_SIZE if y2 is not an Empty Buffer.
   8606 The algorithm is specified in the TPM 2.0 Part 1 Annex for ECC, TPM2_Commit().
   8607 
   8608 
   8609 
   8610 
   8611 Family 2.0                                 TCG Published                                          Page 181
   8612 Level 00 Revision 01.16              Copyright  TCG 2006-2014                             October 30, 2014
   8613 Part 3: Commands                                                 Trusted Platform Module Library
   8615 
   8616 
   8617 
   8618 19.2.2 Command and Response
   8619 
   8620                         Table 89  TPM2_Commit Command
   8621 Type                    Name                Description
   8622 
   8623 TPMI_ST_COMMAND_TAG     tag                 TPM_ST_SESSIONS
   8624 
   8625 UINT32                  commandSize
   8626 
   8627 TPM_CC                  commandCode         TPM_CC_Commit
   8628 
   8629                                             handle of the key that will be used in the signing
   8630                                             operation
   8631 TPMI_DH_OBJECT          @signHandle
   8632                                             Auth Index: 1
   8633                                             Auth Role: USER
   8634 
   8635 TPM2B_ECC_POINT         P1                  a point (M) on the curve used by signHandle
   8636 
   8637 TPM2B_SENSITIVE_DATA    s2                  octet array used to derive x-coordinate of a base point
   8638 
   8639 TPM2B_ECC_PARAMETER     y2                  y coordinate of the point associated with s2
   8640 
   8641 
   8642                         Table 90  TPM2_Commit Response
   8643 Type                    Name                Description
   8644 
   8645 TPM_ST                  tag                 see 6
   8646 
   8647 UINT32                  responseSize
   8648 
   8649 TPM_RC                  responseCode
   8650 
   8651 TPM2B_ECC_POINT         K                   ECC point K  [ds](x2, y2)
   8652 
   8653 TPM2B_ECC_POINT         L                   ECC point L  [r](x2, y2)
   8654 
   8655 TPM2B_ECC_POINT         E                   ECC point E  [r]P1
   8656 
   8657 UINT16                  counter             least-significant 16 bits of commitCount
   8658 
   8659 
   8660 
   8661 
   8662 Page 182                           TCG Published                                        Family 2.0
   8663 October 30, 2014              Copyright  TCG 2006-2014                  Level 00 Revision 01.16
   8664      Trusted Platform Module Library                                                                      Part 3: Commands
   8666 
   8667 
   8668      19.2.3 Detailed Actions
   8669 
   8670 1    #include "InternalRoutines.h"
   8671 2    #include "Commit_fp.h"
   8672 3    #ifdef TPM_CC_Commit // Conditional expansion of this file
   8673 4    #ifdef TPM_ALG_ECC
   8674 
   8675 
   8676      Error Returns                     Meaning
   8677 
   8678      TPM_RC_ATTRIBUTES                 keyHandle references a restricted key that is not a signing key
   8679      TPM_RC_ECC_POINT                  either P1 or the point derived from s2 is not on the curve of
   8680                                        keyHandle
   8681      TPM_RC_HASH                       invalid name algorithm in keyHandle
   8682      TPM_RC_KEY                        keyHandle does not reference an ECC key
   8683      TPM_RC_SCHEME                     the scheme of keyHandle is not an anonymous scheme
   8684      TPM_RC_NO_RESULT                  K, L or E was a point at infinity; or failed to generate r value
   8685      TPM_RC_SIZE                       s2 is empty but y2 is not or s2 provided but y2 is not
   8686 
   8687  5   TPM_RC
   8688  6   TPM2_Commit(
   8689  7       Commit_In         *in,                 // IN: input parameter list
   8690  8       Commit_Out        *out                 // OUT: output parameter list
   8691  9       )
   8692 10   {
   8693 11       OBJECT                    *eccKey;
   8694 12       TPMS_ECC_POINT             P2;
   8695 13       TPMS_ECC_POINT            *pP2 = NULL;
   8696 14       TPMS_ECC_POINT            *pP1 = NULL;
   8697 15       TPM2B_ECC_PARAMETER        r;
   8698 16       TPM2B                     *p;
   8699 17       TPM_RC                     result;
   8700 18       TPMS_ECC_PARMS            *parms;
   8701 19
   8702 20   // Input Validation
   8703 21
   8704 22       eccKey = ObjectGet(in->signHandle);
   8705 23       parms = & eccKey->publicArea.parameters.eccDetail;
   8706 24
   8707 25       // Input key must be an ECC key
   8708 26       if(eccKey->publicArea.type != TPM_ALG_ECC)
   8709 27           return TPM_RC_KEY + RC_Commit_signHandle;
   8710 28
   8711 29        // This command may only be used with a sign-only key using an anonymous
   8712 30        // scheme.
   8713 31        // NOTE: a sign + decrypt key has no scheme so it will not be an anonymous one
   8714 32        // and an unrestricted sign key might no have a signing scheme but it can't
   8715 33        // be use in Commit()
   8716 34       if(!CryptIsSchemeAnonymous(parms->scheme.scheme))
   8717 35                return TPM_RC_SCHEME + RC_Commit_signHandle;
   8718 36
   8719 37       // Make sure that both parts of P2 are present if either is present
   8720 38       if((in->s2.t.size == 0) != (in->y2.t.size == 0))
   8721 39           return TPM_RC_SIZE + RC_Commit_y2;
   8722 40
   8723 41       // Get prime modulus for the curve. This is needed later but getting this now
   8724 42       // allows confirmation that the curve exists
   8725 43       p = (TPM2B *)CryptEccGetParameter('p', parms->curveID);
   8726 44
   8727 45       // if no p, then the curve ID is bad
   8728 
   8729 
   8730      Family 2.0                                    TCG Published                                               Page 183
   8731      Level 00 Revision 01.16                Copyright  TCG 2006-2014                                     October 30, 2014
   8732       Part 3: Commands                                                  Trusted Platform Module Library
   8734 
   8735  46      // NOTE: This should never occur if the input unmarshaling code is working
   8736  47      // correctly
   8737  48      pAssert(p != NULL);
   8738  49
   8739  50      // Get the random value that will be used in the point multiplications
   8740  51      // Note: this does not commit the count.
   8741  52      if(!CryptGenerateR(&r, NULL, parms->curveID, &eccKey->name))
   8742  53          return TPM_RC_NO_RESULT;
   8743  54
   8744  55      // Set up P2 if s2 and Y2 are provided
   8745  56      if(in->s2.t.size != 0)
   8746  57      {
   8747  58          pP2 = &P2;
   8748  59
   8749  60          // copy y2 for P2
   8750  61          MemoryCopy2B(&P2.y.b, &in->y2.b, sizeof(P2.y.t.buffer));
   8751  62          // Compute x2 HnameAlg(s2) mod p
   8752  63
   8753  64          //      do the hash operation on s2 with the size of curve 'p'
   8754  65          P2.x.t.size = CryptHashBlock(eccKey->publicArea.nameAlg,
   8755  66                                       in->s2.t.size,
   8756  67                                       in->s2.t.buffer,
   8757  68                                       p->size,
   8758  69                                       P2.x.t.buffer);
   8759  70
   8760  71          // If there were error returns in the hash routine, indicate a problem
   8761  72          // with the hash in
   8762  73          if(P2.x.t.size == 0)
   8763  74              return TPM_RC_HASH + RC_Commit_signHandle;
   8764  75
   8765  76          // set p2.x = hash(s2) mod p
   8766  77          if(CryptDivide(&P2.x.b, p, NULL, &P2.x.b) != TPM_RC_SUCCESS)
   8767  78              return TPM_RC_NO_RESULT;
   8768  79
   8769  80          if(!CryptEccIsPointOnCurve(parms->curveID, pP2))
   8770  81              return TPM_RC_ECC_POINT + RC_Commit_s2;
   8771  82
   8772  83          if(eccKey->attributes.publicOnly == SET)
   8773  84              return TPM_RC_KEY + RC_Commit_signHandle;
   8774  85
   8775  86      }
   8776  87      // If there is a P1, make sure that it is on the curve
   8777  88      // NOTE: an "empty" point has two UINT16 values which are the size values
   8778  89      // for each of the coordinates.
   8779  90      if(in->P1.t.size > 4)
   8780  91      {
   8781  92          pP1 = &in->P1.t.point;
   8782  93          if(!CryptEccIsPointOnCurve(parms->curveID, pP1))
   8783  94              return TPM_RC_ECC_POINT + RC_Commit_P1;
   8784  95      }
   8785  96
   8786  97      // Pass the parameters to CryptCommit.
   8787  98      // The work is not done in-line because it does several point multiplies
   8788  99      // with the same curve. There is significant optimization by not
   8789 100      // having to reload the curve parameters multiple times.
   8790 101      result = CryptCommitCompute(&out->K.t.point,
   8791 102                                  &out->L.t.point,
   8792 103                                  &out->E.t.point,
   8793 104                                  parms->curveID,
   8794 105                                  pP1,
   8795 106                                  pP2,
   8796 107                                  &eccKey->sensitive.sensitive.ecc,
   8797 108                                  &r);
   8798 109      if(result != TPM_RC_SUCCESS)
   8799 110          return result;
   8800 111
   8801 
   8802       Page 184                              TCG Published                                 Family 2.0
   8803       October 30, 2014               Copyright  TCG 2006-2014                Level 00 Revision 01.16
   8804       Trusted Platform Module Library                                             Part 3: Commands
   8806 
   8807 112       out->K.t.size = TPMS_ECC_POINT_Marshal(&out->K.t.point, NULL, NULL);
   8808 113       out->L.t.size = TPMS_ECC_POINT_Marshal(&out->L.t.point, NULL, NULL);
   8809 114       out->E.t.size = TPMS_ECC_POINT_Marshal(&out->E.t.point, NULL, NULL);
   8810 115
   8811 116       // The commit computation was successful so complete the commit by setting
   8812 117       // the bit
   8813 118       out->counter = CryptCommit();
   8814 119
   8815 120       return TPM_RC_SUCCESS;
   8816 121   }
   8817 122   #endif
   8818 123   #endif // CC_Commit
   8819 
   8820 
   8821 
   8822 
   8823       Family 2.0                           TCG Published                               Page 185
   8824       Level 00 Revision 01.16           Copyright  TCG 2006-2014                 October 30, 2014
   8825 Part 3: Commands                                                   Trusted Platform Module Library
   8827 
   8828 
   8829 
   8830 19.3   TPM2_EC_Ephemeral
   8831 
   8832 19.3.1 General Description
   8833 
   8834 TPM2_EC_Ephemeral() creates an ephemeral key for use in a two-phase key exchange protocol.
   8835 The TPM will use the commit mechanism to assign an ephemeral key r and compute a public point Q 
   8836 [r]G where G is the generator point associated with curveID.
   8837 
   8838 
   8839 
   8840 
   8841 Page 186                                TCG Published                                Family 2.0
   8842 October 30, 2014                  Copyright  TCG 2006-2014              Level 00 Revision 01.16
   8843 Trusted Platform Module Library                                                           Part 3: Commands
   8845 
   8846 
   8847 
   8848 19.3.2 Command and Response
   8849 
   8850                             Table 91  TPM2_EC_Ephemeral Command
   8851 Type                              Name                Description
   8852 
   8853                                                       TPM_ST_SESSIONS if an audit or encrypt session is
   8854 TPMI_ST_COMMAND_TAG               tag
   8855                                                       present; otherwise, TPM_ST_NO_SESSIONS
   8856 
   8857 UINT32                            commandSize
   8858 
   8859 TPM_CC                            commandCode         TPM_CC_EC_Ephemeral
   8860 
   8861 TPMI_ECC_CURVE                    curveID             The curve for the computed ephemeral point
   8862 
   8863 
   8864                             Table 92  TPM2_EC_Ephemeral Response
   8865 Type                              Name                Description
   8866 
   8867 TPM_ST                            tag                 see 6
   8868 
   8869 UINT32                            responseSize
   8870 
   8871 TPM_RC                            responseCode
   8872 
   8873 TPM2B_ECC_POINT                   Q                   ephemeral public key Q  [r]G
   8874 
   8875 UINT16                            counter             least-significant 16 bits of commitCount
   8876 
   8877 
   8878 
   8879 
   8880 Family 2.0                                 TCG Published                                         Page 187
   8881 Level 00 Revision 01.16                 Copyright  TCG 2006-2014                         October 30, 2014
   8882      Part 3: Commands                                                     Trusted Platform Module Library
   8884 
   8885 
   8886      19.3.3 Detailed Actions
   8887 
   8888 1    #include "InternalRoutines.h"
   8889 2    #include "EC_Ephemeral_fp.h"
   8890 3    #ifdef TPM_CC_EC_Ephemeral // Conditional expansion of this file
   8891 4    #ifdef TPM_ALG_ECC
   8892 
   8893 
   8894      Error Returns                    Meaning
   8895 
   8896      none                             ...
   8897 
   8898  5   TPM_RC
   8899  6   TPM2_EC_Ephemeral(
   8900  7       EC_Ephemeral_In       *in,               // IN: input parameter list
   8901  8       EC_Ephemeral_Out      *out               // OUT: output parameter list
   8902  9       )
   8903 10   {
   8904 11       TPM2B_ECC_PARAMETER          r;
   8905 12
   8906 13       // Get the random value that will be used in the point multiplications
   8907 14       // Note: this does not commit the count.
   8908 15       if(!CryptGenerateR(&r,
   8909 16                          NULL,
   8910 17                          in->curveID,
   8911 18                          NULL))
   8912 19           return TPM_RC_NO_RESULT;
   8913 20
   8914 21       CryptEccPointMultiply(&out->Q.t.point, in->curveID, &r, NULL);
   8915 22
   8916 23       // commit the count value
   8917 24       out->counter = CryptCommit();
   8918 25
   8919 26       return TPM_RC_SUCCESS;
   8920 27   }
   8921 28   #endif
   8922 29   #endif // CC_EC_Ephemeral
   8923 
   8924 
   8925 
   8926 
   8927      Page 188                                    TCG Published                               Family 2.0
   8928      October 30, 2014                       Copyright  TCG 2006-2014             Level 00 Revision 01.16
   8929 Trusted Platform Module Library                                                           Part 3: Commands
   8931 
   8932 
   8933 20     Signing and Signature Verification
   8934 
   8935 20.1     TPM2_VerifySignature
   8936 
   8937 20.1.1 General Description
   8938 
   8939 This command uses loaded keys to validate a signature on a message with the message digest passed
   8940 to the TPM.
   8941 If the signature check succeeds, then the TPM will produce a TPMT_TK_VERIFIED. Otherwise, the TPM
   8942 shall return TPM_RC_SIGNATURE.
   8943 
   8944 NOTE 1          A valid ticket may be used in subsequent commands to provide proof to the TPM that the TPM has
   8945                 validated the signature over the message using the key referenced by keyHandle.
   8946 
   8947 If keyHandle references an asymmetric key, only the public portion of the key needs to be loaded. If
   8948 keyHandle references a symmetric key, both the public and private portions need to be loaded.
   8949 
   8950 NOTE 2          The sensitive area of the symmetric object is required to allow verification of the symmetric
   8951                 signature (the HMAC).
   8952 
   8953 
   8954 
   8955 
   8956 Family 2.0                                 TCG Published                                         Page 189
   8957 Level 00 Revision 01.16              Copyright  TCG 2006-2014                            October 30, 2014
   8958 Part 3: Commands                                                    Trusted Platform Module Library
   8960 
   8961 
   8962 20.1.2 Command and Response
   8963 
   8964                       Table 93  TPM2_VerifySignature Command
   8965 Type                    Name                  Description
   8966 
   8967                                               TPM_ST_SESSIONS if an audit or encrypt session is
   8968 TPMI_ST_COMMAND_TAG     tag
   8969                                               present; otherwise, TPM_ST_NO_SESSIONS
   8970 UINT32                  commandSize
   8971 TPM_CC                  commandCode           TPM_CC_VerifySignature
   8972 
   8973                                               handle of public key that will be used in the validation
   8974 TPMI_DH_OBJECT          keyHandle
   8975                                               Auth Index: None
   8976 
   8977 TPM2B_DIGEST            digest                digest of the signed message
   8978 TPMT_SIGNATURE          signature             signature to be tested
   8979 
   8980 
   8981                       Table 94  TPM2_VerifySignature Response
   8982 Type                    Name                  Description
   8983 
   8984 TPM_ST                  tag                   see clause 6
   8985 UINT32                  responseSize
   8986 TPM_RC                  responseCode
   8987 
   8988 TPMT_TK_VERIFIED        validation
   8989 
   8990 
   8991 
   8992 
   8993 Page 190                               TCG Published                                      Family 2.0
   8994 October 30, 2014              Copyright  TCG 2006-2014                    Level 00 Revision 01.16
   8995      Trusted Platform Module Library                                                               Part 3: Commands
   8997 
   8998 
   8999 
   9000      20.1.3 Detailed Actions
   9001 
   9002 1    #include "InternalRoutines.h"
   9003 2    #include "VerifySignature_fp.h"
   9004 3    #ifdef TPM_CC_VerifySignature // Conditional expansion of this file
   9005 
   9006 
   9007      Error Returns                     Meaning
   9008 
   9009      TPM_RC_ATTRIBUTES                 keyHandle does not reference a signing key
   9010      TPM_RC_SIGNATURE                  signature is not genuine
   9011      TPM_RC_SCHEME                     CryptVerifySignature()
   9012      TPM_RC_HANDLE                     the input handle is references an HMAC key but the private portion is
   9013                                        not loaded
   9014 
   9015  4   TPM_RC
   9016  5   TPM2_VerifySignature(
   9017  6       VerifySignature_In        *in,                   // IN: input parameter list
   9018  7       VerifySignature_Out       *out                   // OUT: output parameter list
   9019  8       )
   9020  9   {
   9021 10       TPM_RC                     result;
   9022 11       TPM2B_NAME                 name;
   9023 12       OBJECT                    *signObject;
   9024 13       TPMI_RH_HIERARCHY          hierarchy;
   9025 14
   9026 15   // Input Validation
   9027 16
   9028 17       // Get sign object pointer
   9029 18       signObject = ObjectGet(in->keyHandle);
   9030 19
   9031 20       // The object to validate the signature must be a signing key.
   9032 21       if(signObject->publicArea.objectAttributes.sign != SET)
   9033 22           return TPM_RC_ATTRIBUTES + RC_VerifySignature_keyHandle;
   9034 23
   9035 24       // Validate Signature. TPM_RC_SCHEME, TPM_RC_HANDLE or TPM_RC_SIGNATURE
   9036 25       // error may be returned by CryptCVerifySignatrue()
   9037 26       result = CryptVerifySignature(in->keyHandle, &in->digest, &in->signature);
   9038 27       if(result != TPM_RC_SUCCESS)
   9039 28           return RcSafeAddToResult(result, RC_VerifySignature_signature);
   9040 29
   9041 30   // Command Output
   9042 31
   9043 32       hierarchy = ObjectGetHierarchy(in->keyHandle);
   9044 33       if(   hierarchy == TPM_RH_NULL
   9045 34          || signObject->publicArea.nameAlg == TPM_ALG_NULL)
   9046 35       {
   9047 36           // produce empty ticket if hierarchy is TPM_RH_NULL or nameAlg is
   9048 37           // TPM_ALG_NULL
   9049 38           out->validation.tag = TPM_ST_VERIFIED;
   9050 39           out->validation.hierarchy = TPM_RH_NULL;
   9051 40           out->validation.digest.t.size = 0;
   9052 41       }
   9053 42       else
   9054 43       {
   9055 44           // Get object name that verifies the signature
   9056 45           name.t.size = ObjectGetName(in->keyHandle, &name.t.name);
   9057 46           // Compute ticket
   9058 47           TicketComputeVerified(hierarchy, &in->digest, &name, &out->validation);
   9059 48       }
   9060 49
   9061 50       return TPM_RC_SUCCESS;
   9062 
   9063      Family 2.0                                  TCG Published                                               Page 191
   9064      Level 00 Revision 01.16               Copyright  TCG 2006-2014                               October 30, 2014
   9065      Part 3: Commands                                           Trusted Platform Module Library
   9067 
   9068 51   }
   9069 52   #endif // CC_VerifySignature
   9070 
   9071 
   9072 
   9073 
   9074      Page 192                            TCG Published                            Family 2.0
   9075      October 30, 2014               Copyright  TCG 2006-2014        Level 00 Revision 01.16
   9076 Trusted Platform Module Library                                                                Part 3: Commands
   9078 
   9079 
   9080 20.2     TPM2_Sign
   9081 
   9082 20.2.1 General Description
   9083 
   9084 This command causes the TPM to sign an externally provided hash with the specified symmetric or
   9085 asymmetric signing key.
   9086 
   9087 NOTE 1          Symmetric signing is done with the TPM HMAC commands.
   9088 
   9089 If keyHandle references a restricted signing key, then validation shall be provided, indicating that the TPM
   9090 performed the hash of the data and validation shall indicate that hashed data did not start with
   9091 TPM_GENERATED_VALUE.
   9092 
   9093 NOTE 2          If the hashed data did start with TPM_GENERATED_VALUE, then the validation will be a NULL
   9094                 ticket.
   9095 
   9096 If the scheme of keyHandle is not TPM_ALG_NULL, then inScheme shall either be the same scheme as
   9097 keyHandle or TPM_ALG_NULL.
   9098 If the scheme of keyHandle is TPM_ALG_NULL, the TPM will sign using inScheme; otherwise, it will sign
   9099 using the scheme of keyHandle.
   9100 
   9101 NOTE 3          When the signing scheme uses a hash algorithm, the algorithm is defined in the qualifying data of
   9102                 the scheme. This is the same algorithm that is required to be used in producing digest. The size of
   9103                 digest must match that of the hash algorithm in the scheme.
   9104 
   9105 If inScheme is not a valid signing scheme for the type of keyHandle (or TPM_ALG_NULL), then the TPM
   9106 shall return TPM_RC_SCHEME.
   9107 If the scheme of keyHandle is an anonymous scheme, then inScheme shall have the same scheme
   9108 algorithm as keyHandle and inScheme will contain a counter value that will be used in the signing
   9109 process.
   9110 If validation is provided, then the hash algorithm used in computing the digest is required to be the hash
   9111 algorithm specified in the scheme of keyHandle (TPM_RC_TICKET).
   9112 If the validation parameter is not the Empty Buffer, then it will be checked even if the key referenced by
   9113 keyHandle is not a restricted signing key.
   9114 
   9115 NOTE 4          If keyHandle is both a sign and decrypt key, keyHandle will have an scheme of TPM_ALG_NULL. If
   9116                 validation is provided, then it must be a NULL validation ticket or the ticket validation will fail.
   9117 
   9118 
   9119 
   9120 
   9121 Family 2.0                                   TCG Published                                            Page 193
   9122 Level 00 Revision 01.16                Copyright  TCG 2006-2014                               October 30, 2014
   9123 Part 3: Commands                                                   Trusted Platform Module Library
   9125 
   9126 
   9127 20.2.2 Command and Response
   9128 
   9129                              Table 95  TPM2_Sign Command
   9130 Type                   Name                  Description
   9131 
   9132 TPMI_ST_COMMAND_TAG    tag                   TPM_ST_SESSIONS
   9133 UINT32                 commandSize
   9134 TPM_CC                 commandCode           TPM_CC_Sign
   9135 
   9136                                              Handle of key that will perform signing
   9137 TPMI_DH_OBJECT         @keyHandle            Auth Index: 1
   9138                                              Auth Role: USER
   9139 
   9140 TPM2B_DIGEST           digest                digest to be signed
   9141                                              signing scheme to use if the scheme for keyHandle is
   9142 TPMT_SIG_SCHEME+       inScheme
   9143                                              TPM_ALG_NULL
   9144                                              proof that digest was created by the TPM
   9145 TPMT_TK_HASHCHECK      validation            If keyHandle is not a restricted signing key, then this
   9146                                              may be a NULL Ticket with tag =
   9147                                              TPM_ST_CHECKHASH.
   9148 
   9149 
   9150                              Table 96  TPM2_Sign Response
   9151 Type                   Name                  Description
   9152 
   9153 TPM_ST                 tag                   see clause 6
   9154 UINT32                 responseSize
   9155 TPM_RC                 responseCode
   9156 
   9157 TPMT_SIGNATURE         signature             the signature
   9158 
   9159 
   9160 
   9161 
   9162 Page 194                              TCG Published                                       Family 2.0
   9163 October 30, 2014              Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   9164      Trusted Platform Module Library                                                                 Part 3: Commands
   9166 
   9167 
   9168 
   9169      20.2.3 Detailed Actions
   9170 
   9171 1    #include "InternalRoutines.h"
   9172 2    #include "Sign_fp.h"
   9173 3    #ifdef TPM_CC_Sign // Conditional expansion of this file
   9174 4    #include "Attest_spt_fp.h"
   9175 
   9176 
   9177      Error Returns                     Meaning
   9178 
   9179      TPM_RC_BINDING                    The public and private portions of the key are not properly bound.
   9180      TPM_RC_KEY                        signHandle does not reference a signing key;
   9181      TPM_RC_SCHEME                     the scheme is not compatible with sign key type, or input scheme is
   9182                                        not compatible with default scheme, or the chosen scheme is not a
   9183                                        valid sign scheme
   9184      TPM_RC_TICKET                     validation is not a valid ticket
   9185      TPM_RC_VALUE                      the value to sign is larger than allowed for the type of keyHandle
   9186 
   9187  5   TPM_RC
   9188  6   TPM2_Sign(
   9189  7       Sign_In          *in,                   // IN: input parameter list
   9190  8       Sign_Out         *out                   // OUT: output parameter list
   9191  9       )
   9192 10   {
   9193 11       TPM_RC                     result;
   9194 12       TPMT_TK_HASHCHECK          ticket;
   9195 13       OBJECT                    *signKey;
   9196 14
   9197 15   // Input Validation
   9198 16       // Get sign key pointer
   9199 17       signKey = ObjectGet(in->keyHandle);
   9200 18
   9201 19       // pick a scheme for sign. If the input sign scheme is not compatible with
   9202 20       // the default scheme, return an error.
   9203 21       result = CryptSelectSignScheme(in->keyHandle, &in->inScheme);
   9204 22       if(result != TPM_RC_SUCCESS)
   9205 23       {
   9206 24           if(result == TPM_RC_KEY)
   9207 25               return TPM_RC_KEY + RC_Sign_keyHandle;
   9208 26           else
   9209 27               return RcSafeAddToResult(result, RC_Sign_inScheme);
   9210 28       }
   9211 29
   9212 30       // If validation is provided, or the key is restricted, check the ticket
   9213 31       if(   in->validation.digest.t.size != 0
   9214 32          || signKey->publicArea.objectAttributes.restricted == SET)
   9215 33       {
   9216 34           // Compute and compare ticket
   9217 35           TicketComputeHashCheck(in->validation.hierarchy,
   9218 36                                  in->inScheme.details.any.hashAlg,
   9219 37                                  &in->digest, &ticket);
   9220 38
   9221 39           if(!Memory2BEqual(&in->validation.digest.b, &ticket.digest.b))
   9222 40               return TPM_RC_TICKET + RC_Sign_validation;
   9223 41       }
   9224 42       else
   9225 43       // If we don't have a ticket, at least verify that the provided 'digest'
   9226 44       // is the size of the scheme hashAlg digest.
   9227 45       // NOTE: this does not guarantee that the 'digest' is actually produced using
   9228 46       // the indicated hash algorithm, but at least it might be.
   9229 47       {
   9230 
   9231      Family 2.0                                    TCG Published                                           Page 195
   9232      Level 00 Revision 01.16                Copyright  TCG 2006-2014                                October 30, 2014
   9233      Part 3: Commands                                                  Trusted Platform Module Library
   9235 
   9236 48           if(       in->digest.t.size
   9237 49                 != CryptGetHashDigestSize(in->inScheme.details.any.hashAlg))
   9238 50                 return TPM_RCS_SIZE + RC_Sign_digest;
   9239 51       }
   9240 52
   9241 53   // Command Output
   9242 54       // Sign the hash. A TPM_RC_VALUE or TPM_RC_SCHEME
   9243 55       // error may be returned at this point
   9244 56       result = CryptSign(in->keyHandle, &in->inScheme, &in->digest, &out->signature);
   9245 57
   9246 58       return result;
   9247 59   }
   9248 60   #endif // CC_Sign
   9249 
   9250 
   9251 
   9252 
   9253      Page 196                                TCG Published                               Family 2.0
   9254      October 30, 2014                  Copyright  TCG 2006-2014            Level 00 Revision 01.16
   9255 Trusted Platform Module Library                                                       Part 3: Commands
   9257 
   9258 
   9259 21     Command Audit
   9260 
   9261 21.1    Introduction
   9262 
   9263 If a command has been selected for command audit, the command audit status will be updated when that
   9264 command completes successfully. The digest is updated as:
   9265              commandAuditDigestnew  HauditAlg(commandAuditDigestold || cpHash || rpHash)           (5)
   9266 where
   9267          HauditAlg                       hash function using the algorithm of the audit sequence
   9268          commandAuditDigest              accumulated digest
   9269          cpHash                          the command parameter hash
   9270          rpHash                          the response parameter hash
   9271 
   9272 auditAlg, the hash algorithm, is set using TPM2_SetCommandCodeAuditStatus.
   9273 
   9274 
   9275 TPM2_Shutdown() cannot be audited but TPM2_Startup() can be audited. If the cpHash of the
   9276 TPM2_Startup() is TPM_SU_STATE, that would indicate that a TPM2_Shutdown() had been successfully
   9277 executed.
   9278 TPM2_SetCommandCodeAuditStatus() is always audited.
   9279 If the TPM is in Failure mode, command audit is not functional.
   9280 
   9281 
   9282 
   9283 
   9284 Family 2.0                                TCG Published                                      Page 197
   9285 Level 00 Revision 01.16              Copyright  TCG 2006-2014                        October 30, 2014
   9286 Part 3: Commands                                                               Trusted Platform Module Library
   9288 
   9289 
   9290 
   9291 21.2     TPM2_SetCommandCodeAuditStatus
   9292 
   9293 21.2.1 General Description
   9294 
   9295 This command may be used by the Privacy Administrator or platform to change the audit status of a
   9296 command or to set the hash algorithm used for the audit digest, but not both at the same time.
   9297 If the auditAlg parameter is a supported hash algorithm and not the same as the current algorithm, then
   9298 the TPM will check both setList and clearList are empty (zero length). If so, then the algorithm is changed,
   9299 and the audit digest is cleared. If auditAlg is TPM_ALG_NULL or the same as the current algorithm, then
   9300 the algorithm and audit digest are unchanged and the setList and clearList will be processed.
   9301 
   9302 NOTE 1          Because the audit digest is cleared, the audit counter will increment the next time that an audited
   9303                 command is executed.
   9304 
   9305 Use of TPM2_SetCommandCodeAuditStatus() to change the list of audited commands is an audited
   9306 event. If TPM_CC_SetCommandCodeAuditStatus is in clearList, the fact that it is in clearList is ignored.
   9307 
   9308 NOTE 2          Use of this command to change the audit hash algorithm is not audited and the digest is reset when
   9309                 the command completes. The change in the audit hash algorith m is the evidence that this command
   9310                 was used to change the algorithm.
   9311 
   9312 The commands in setList indicate the commands to be added to the list of audited commands and the
   9313 commands in clearList indicate the commands that will no longer be audited. It is not an error if a
   9314 command in setList is already audited or is not implemented. It is not an error if a command in clearList is
   9315 not currently being audited or is not implemented.
   9316 If a command code is in both setList and clearList, then it will not be audited (that is, setList shall be
   9317 processed first).
   9318 
   9319 
   9320 
   9321 
   9322 Page 198                                      TCG Published                                         Family 2.0
   9323 October 30, 2014                      Copyright  TCG 2006-2014                       Level 00 Revision 01.16
   9324 Trusted Platform Module Library                                                       Part 3: Commands
   9326 
   9327 
   9328 
   9329 21.2.2 Command and Response
   9330 
   9331                    Table 97  TPM2_SetCommandCodeAuditStatus Command
   9332  Type                         Name                Description
   9333 
   9334  TPMI_ST_COMMAND_TAG          tag                 TPM_ST_SESSIONS
   9335  UINT32                       commandSize
   9336  TPM_CC                       commandCode         TPM_CC_SetCommandCodeAuditStatus {NV}
   9337 
   9338                                                   TPM_RH_OWNER or TPM_RH_PLATFORM+{PP}
   9339  TPMI_RH_PROVISION            @auth               Auth Index: 1
   9340                                                   Auth Role: USER
   9341 
   9342                                                   hash algorithm for the audit digest; if
   9343  TPMI_ALG_HASH+               auditAlg
   9344                                                   TPM_ALG_NULL, then the hash is not changed
   9345                                                   list of commands that will be added to those that will
   9346  TPML_CC                      setList
   9347                                                   be audited
   9348  TPML_CC                      clearList           list of commands that will no longer be audited
   9349 
   9350 
   9351                    Table 98  TPM2_SetCommandCodeAuditStatus Response
   9352  Type                         Name                Description
   9353 
   9354  TPM_ST                       tag                 see clause 6
   9355  UINT32                       responseSize
   9356  TPM_RC                       responseCode
   9357 
   9358 
   9359 
   9360 
   9361 Family 2.0                              TCG Published                                         Page 199
   9362 Level 00 Revision 01.16             Copyright  TCG 2006-2014                         October 30, 2014
   9363      Part 3: Commands                                                  Trusted Platform Module Library
   9365 
   9366 
   9367 
   9368      21.2.3 Detailed Actions
   9369 
   9370  1   #include "InternalRoutines.h"
   9371  2   #include "SetCommandCodeAuditStatus_fp.h"
   9372  3   #ifdef TPM_CC_SetCommandCodeAuditStatus // Conditional expansion of this file
   9373  4   TPM_RC
   9374  5   TPM2_SetCommandCodeAuditStatus(
   9375  6       SetCommandCodeAuditStatus_In      *in             // IN: input parameter list
   9376  7       )
   9377  8   {
   9378  9       TPM_RC          result;
   9379 10       UINT32          i;
   9380 11       BOOL            changed = FALSE;
   9381 12
   9382 13       // The command needs NV update. Check if NV is available.
   9383 14       // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   9384 15       // this point
   9385 16       result = NvIsAvailable();
   9386 17       if(result != TPM_RC_SUCCESS)
   9387 18           return result;
   9388 19
   9389 20   // Internal Data Update
   9390 21
   9391 22       // Update hash algorithm
   9392 23       if(   in->auditAlg != TPM_ALG_NULL
   9393 24          && in->auditAlg != gp.auditHashAlg)
   9394 25       {
   9395 26           // Can't change the algorithm and command list at the same time
   9396 27           if(in->setList.count != 0 || in->clearList.count != 0)
   9397 28               return TPM_RC_VALUE + RC_SetCommandCodeAuditStatus_auditAlg;
   9398 29
   9399 30           // Change the hash algorithm for audit
   9400 31           gp.auditHashAlg = in->auditAlg;
   9401 32
   9402 33           // Set the digest size to a unique value that indicates that the digest
   9403 34           // algorithm has been changed. The size will be cleared to zero in the
   9404 35           // command audit processing on exit.
   9405 36           gr.commandAuditDigest.t.size = 1;
   9406 37
   9407 38           // Save the change of command audit data (this sets g_updateNV so that NV
   9408 39           // will be updated on exit.)
   9409 40           NvWriteReserved(NV_AUDIT_HASH_ALG, &gp.auditHashAlg);
   9410 41
   9411 42       } else {
   9412 43
   9413 44           // Process set list
   9414 45           for(i = 0; i < in->setList.count; i++)
   9415 46
   9416 47                // If change is made in CommandAuditSet, set changed flag
   9417 48                if(CommandAuditSet(in->setList.commandCodes[i]))
   9418 49                    changed = TRUE;
   9419 50
   9420 51           // Process clear list
   9421 52           for(i = 0; i < in->clearList.count; i++)
   9422 53               // If change is made in CommandAuditClear, set changed flag
   9423 54               if(CommandAuditClear(in->clearList.commandCodes[i]))
   9424 55                   changed = TRUE;
   9425 56
   9426 57           // if change was made to command list, update NV
   9427 58           if(changed)
   9428 59               // this sets g_updateNV so that NV will be updated on exit.
   9429 60               NvWriteReserved(NV_AUDIT_COMMANDS, &gp.auditComands);
   9430 61       }
   9431 62
   9432 
   9433      Page 200                                    TCG Published                           Family 2.0
   9434      October 30, 2014                   Copyright  TCG 2006-2014             Level 00 Revision 01.16
   9435      Trusted Platform Module Library                               Part 3: Commands
   9437 
   9438 63       return TPM_RC_SUCCESS;
   9439 64   }
   9440 65   #endif // CC_SetCommandCodeAuditStatus
   9441 
   9442 
   9443 
   9444 
   9445      Family 2.0                             TCG Published               Page 201
   9446      Level 00 Revision 01.16           Copyright  TCG 2006-2014   October 30, 2014
   9447 Part 3: Commands                                                             Trusted Platform Module Library
   9449 
   9450 
   9451 22     Integrity Collection (PCR)
   9452 
   9453 22.1     Introduction
   9454 
   9455 In TPM 1.2, an Event was hashed using SHA-1 and then the 20-octet digest was extended to a PCR
   9456 using TPM_Extend(). This specification allows the use of multiple PCR at a given Index, each using a
   9457 different hash algorithm. Rather than require that the external software generate multiple hashes of the
   9458 Event with each being extended to a different PCR, the Event data may be sent to the TPM for hashing.
   9459 This ensures that the resulting digests will properly reflect the algorithms chosen for the PCR even if the
   9460 calling software is unable to implement the hash algorithm.
   9461 
   9462 NOTE 1          There is continued support for software hashing of events with TPM2_PCR_Extend().
   9463 
   9464 To support recording of an Event that is larger than the TPM input buffer, the caller may use the
   9465 command sequence described in clause 1.
   9466 Change to a PCR requires authorization. The authorization may be with either an authorization value or
   9467 an authorization policy. The platform-specific specifications determine which PCR may be controlled by
   9468 policy. All other PCR are controlled by authorization.
   9469 If a PCR may be associated with a policy, then the algorithm ID of that policy determines whether the
   9470 policy is to be applied. If the algorithm ID is not TPM_ALG_NULL, then the policy digest associated with
   9471 the PCR must match the policySessionpolicyDigest in a policy session. If the algorithm ID is
   9472 TPM_ALG_NULL, then no policy is present and the authorization requires an EmptyAuth.
   9473 If a platform-specific specification indicates that PCR are grouped, then all the PCR in the group use the
   9474 same authorization policy or authorization value.
   9475 PcrUpdateCounter counter will be incremented on the successful completion of any command that
   9476 modifies (Extends or resets) a PCR unless the platform-specific specification explicitly excludes the PCR
   9477 from being counted.
   9478 
   9479 NOTE 2          If a command causes PCR in multiple banks to change, the PCR Update Counter may be
   9480                 incremented either once or once for each bank.
   9481 
   9482 A platform-specific specification may designate a set of PCR that are under control of the TCB. These
   9483 PCR may not be modified without the proper authorization. Updates of these PCR shall not cause the
   9484 PCR Update Counter to increment.
   9485 
   9486 EXAMPLE         Updates of the TCB PCR will not cause the PCR update counter to increment because these PCR
   9487                 are changed at the whim of the TCB and may not represent the trust state of the platform.
   9488 
   9489 
   9490 
   9491 
   9492 Page 202                                      TCG Published                                         Family 2.0
   9493 October 30, 2014                      Copyright  TCG 2006-2014                     Level 00 Revision 01.16
   9494 Trusted Platform Module Library                                                                    Part 3: Commands
   9496 
   9497 
   9498 22.2     TPM2_PCR_Extend
   9499 
   9500 22.2.1 General Description
   9501 
   9502 This command is used to cause an update to the indicated PCR. The digests parameter contains one or
   9503 more tagged digest values identified by an algorithm ID. For each digest, the PCR associated with
   9504 pcrHandle is Extended into the bank identified by the tag (hashAlg).
   9505 
   9506 EXAMPLE           A SHA1 digest would be Extended i nto the SHA1 bank and a SHA256 digest would be Extended into
   9507                   the SHA256 bank.
   9508 
   9509 For each list entry, the TPM will check to see if pcrNum is implemented for that algorithm. If so, the TPM
   9510 shall perform the following operation:
   9511           PCR.digestnew [pcrNum][alg]  Halg(PCR.digestold [pcrNum][alg] || data[alg].buffer))                       (6)
   9512 where
   9513          Halg()                               hash function using the hash algorithm associated with the PCR
   9514                                               instance
   9515          PCR.digest                           the digest value in a PCR
   9516          pcrNum                               the PCR numeric selector (pcrHandle)
   9517          alg                                  the PCR algorithm selector for the digest
   9518          data[alg].buffer                     the bank-specific data to be extended
   9519 
   9520 
   9521 If no digest value is specified for a bank, then the PCR in that bank is not modified.
   9522 
   9523 NOTE 1            This allows consistent operation of the digests list for all of the Event recording commands.
   9524 
   9525 If a digest is present and the PCR in that bank is not implemented, the digest value is not used.
   9526 
   9527 NOTE 2            If the caller includes digests for algorithms that are not implemented, then the TPM will fail the call
   9528                   because the unmarshalling of digests will fail. Each of the entries in the list is a TPMT_HA, which is
   9529                   a hash algorithm followed by a digest. If the algorithm is not implemented, unmarshalling of the
   9530                   hashAlg will fail and the TPM will return TPM_RC_HASH.
   9531 
   9532 If the TPM unmarshals the hashAlg of a list entry and the unmarshaled value is not a hash algorithm
   9533 implemented on the TPM, the TPM shall return TPM_RC_HASH.
   9534 The pcrHandle parameter is allowed to reference TPM_RH_NULL. If so, the input parameters are
   9535 processed but no action is taken by the TPM. This permits the caller to probe for implemented hash
   9536 algorithms as an alternative to TPM2_GetCapability.
   9537 
   9538 NOTE 3            This command allows a list of digests so that PCR in all banks may be updated in a single
   9539                   command. While the semantics of this command allow multiple extends to a single PCR bank, this is
   9540                   not the preferred use and the limit on the number of entries in the list make this use somewhat
   9541                   impractical.
   9542 
   9543 
   9544 
   9545 
   9546 Family 2.0                                      TCG Published                                              Page 203
   9547 Level 00 Revision 01.16                  Copyright  TCG 2006-2014                                 October 30, 2014
   9548 Part 3: Commands                                                  Trusted Platform Module Library
   9550 
   9551 
   9552 22.2.2 Command and Response
   9553 
   9554                       Table 99  TPM2_PCR_Extend Command
   9555 Type                   Name                  Description
   9556 
   9557 TPMI_ST_COMMAND_TAG    tag                   TPM_ST_SESSIONS
   9558 UINT32                 commandSize
   9559 TPM_CC                 commandCode           TPM_CC_PCR_Extend {NV}
   9560 
   9561                                              handle of the PCR
   9562 TPMI_DH_PCR+           @pcrHandle            Auth Handle: 1
   9563                                              Auth Role: USER
   9564 
   9565 TPML_DIGEST_VALUES     digests               list of tagged digest values to be extended
   9566 
   9567 
   9568                       Table 100  TPM2_PCR_Extend Response
   9569 Type                   Name                  Description
   9570 
   9571 TPM_ST                 tag                   see clause 6
   9572 UINT32                 responseSize
   9573 TPM_RC                 responseCode          .
   9574 
   9575 
   9576 
   9577 
   9578 Page 204                              TCG Published                                        Family 2.0
   9579 October 30, 2014             Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   9580      Trusted Platform Module Library                                                               Part 3: Commands
   9582 
   9583 
   9584 
   9585      22.2.3 Detailed Actions
   9586 
   9587 1    #include "InternalRoutines.h"
   9588 2    #include "PCR_Extend_fp.h"
   9589 3    #ifdef TPM_CC_PCR_Extend // Conditional expansion of this file
   9590 
   9591 
   9592      Error Returns                     Meaning
   9593 
   9594      TPM_RC_LOCALITY                   current command locality is not allowed to extend the PCR
   9595                                        referenced by pcrHandle
   9596 
   9597  4   TPM_RC
   9598  5   TPM2_PCR_Extend(
   9599  6       PCR_Extend_In     *in                 // IN: input parameter list
   9600  7       )
   9601  8   {
   9602  9       TPM_RC                  result;
   9603 10       UINT32                  i;
   9604 11
   9605 12   // Input Validation
   9606 13
   9607 14       //   NOTE: This function assumes that the unmarshaling function for 'digests' will
   9608 15       //   have validated that all of the indicated hash algorithms are valid. If the
   9609 16       //   hash algorithms are correct, the unmarshaling code will unmarshal a digest
   9610 17       //   of the size indicated by the hash algorithm. If the overall size is not
   9611 18       //   consistent, the unmarshaling code will run out of input data or have input
   9612 19       //   data left over. In either case, it will cause an unmarshaling error and this
   9613 20       //   function will not be called.
   9614 21
   9615 22       // For NULL handle, do nothing and return success
   9616 23       if(in->pcrHandle == TPM_RH_NULL)
   9617 24           return TPM_RC_SUCCESS;
   9618 25
   9619 26       // Check if the extend operation is allowed by the current command locality
   9620 27       if(!PCRIsExtendAllowed(in->pcrHandle))
   9621 28           return TPM_RC_LOCALITY;
   9622 29
   9623 30       // If PCR is state saved and we need to update orderlyState, check NV
   9624 31       // availability
   9625 32       if(PCRIsStateSaved(in->pcrHandle) && gp.orderlyState != SHUTDOWN_NONE)
   9626 33       {
   9627 34           result = NvIsAvailable();
   9628 35           if(result != TPM_RC_SUCCESS) return result;
   9629 36           g_clearOrderly = TRUE;
   9630 37       }
   9631 38
   9632 39   // Internal Data Update
   9633 40
   9634 41       // Iterate input digest list to extend
   9635 42       for(i = 0; i < in->digests.count; i++)
   9636 43       {
   9637 44           PCRExtend(in->pcrHandle, in->digests.digests[i].hashAlg,
   9638 45                     CryptGetHashDigestSize(in->digests.digests[i].hashAlg),
   9639 46                     (BYTE *) &in->digests.digests[i].digest);
   9640 47       }
   9641 48
   9642 49       return TPM_RC_SUCCESS;
   9643 50   }
   9644 51   #endif // CC_PCR_Extend
   9645 
   9646 
   9647 
   9648 
   9649      Family 2.0                                  TCG Published                                          Page 205
   9650      Level 00 Revision 01.16               Copyright  TCG 2006-2014                               October 30, 2014
   9651 Part 3: Commands                                                             Trusted Platform Module Library
   9653 
   9654 
   9655 22.3   TPM2_PCR_Event
   9656 
   9657 22.3.1 General Description
   9658 
   9659 This command is used to cause an update to the indicated PCR.
   9660 The data in eventData is hashed using the hash algorithm associated with each bank in which the
   9661 indicated PCR has been allocated. After the data is hashed, the digests list is returned. If the pcrHandle
   9662 references an implemented PCR and not TPM_ALG_NULL, the digests list is processed as in
   9663 TPM2_PCR_Extend().
   9664 A TPM shall support an Event.size of zero through 1,024 inclusive (Event.size is an octet count). An
   9665 Event.size of zero indicates that there is no data but the indicated operations will still occur,
   9666 
   9667 EXAMPLE 1       If the command implements PCR[2] in a SHA1 bank and a SHA256 bank, then an extend to PCR[2]
   9668                 will cause eventData to be hashed twice, once with SHA1 and once with SHA256. The SHA1 hash of
   9669                 eventData will be Extended to PCR[2] in the SHA1 bank and the SHA256 hash of eventData will be
   9670                 Extended to PCR[2] of the SHA256 bank.
   9671 
   9672 On successful command completion, digests will contain the list of tagged digests of eventData that was
   9673 computed in preparation for extending the data into the PCR. At the option of the TPM, the list may
   9674 contain a digest for each bank, or it may only contain a digest for each bank in which pcrHandle is extant.
   9675 If pcrHandle is TPM_RH_NULL, the TPM may return either an empty list or a digest for each bank.
   9676 
   9677 EXAMPLE 2       Assume a TPM that implements a SHA1 bank and a SHA256 bank and that PCR[22] is only
   9678                 implemented in the SHA1 bank. If pcrHandle references PCR[22], then digests may contain either a
   9679                 SHA1 and a SHA256 digest or just a SHA1 digest.
   9680 
   9681 
   9682 
   9683 
   9684 Page 206                                      TCG Published                                       Family 2.0
   9685 October 30, 2014                      Copyright  TCG 2006-2014                    Level 00 Revision 01.16
   9686 Trusted Platform Module Library                                                  Part 3: Commands
   9688 
   9689 
   9690 22.3.2 Command and Response
   9691 
   9692                              Table 101  TPM2_PCR_Event Command
   9693 Type                          Name                  Description
   9694 
   9695 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   9696 UINT32                        commandSize
   9697 TPM_CC                        commandCode           TPM_CC_PCR_Event {NV}
   9698 
   9699                                                     Handle of the PCR
   9700 TPMI_DH_PCR+                  @pcrHandle            Auth Handle: 1
   9701                                                     Auth Role: USER
   9702 
   9703 TPM2B_EVENT                   eventData             Event data in sized buffer
   9704 
   9705 
   9706                              Table 102  TPM2_PCR_Event Response
   9707 Type                          Name                  Description
   9708 
   9709 TPM_ST                        tag                   see clause 6
   9710 UINT32                        responseSize
   9711 TPM_RC                        responseCode          .
   9712 
   9713 TPML_DIGEST_VALUES            digests
   9714 
   9715 
   9716 
   9717 
   9718 Family 2.0                                 TCG Published                              Page 207
   9719 Level 00 Revision 01.16             Copyright  TCG 2006-2014                    October 30, 2014
   9720      Part 3: Commands                                                          Trusted Platform Module Library
   9722 
   9723 
   9724 
   9725      22.3.3 Detailed Actions
   9726 
   9727 1    #include "InternalRoutines.h"
   9728 2    #include "PCR_Event_fp.h"
   9729 3    #ifdef TPM_CC_PCR_Event // Conditional expansion of this file
   9730 
   9731 
   9732      Error Returns                 Meaning
   9733 
   9734      TPM_RC_LOCALITY               current command locality is not allowed to extend the PCR
   9735                                    referenced by pcrHandle
   9736 
   9737  4   TPM_RC
   9738  5   TPM2_PCR_Event(
   9739  6       PCR_Event_In      *in,             // IN: input parameter list
   9740  7       PCR_Event_Out     *out             // OUT: output parameter list
   9741  8       )
   9742  9   {
   9743 10       TPM_RC                result;
   9744 11       HASH_STATE            hashState;
   9745 12       UINT32                i;
   9746 13       UINT16                size;
   9747 14
   9748 15   // Input Validation
   9749 16
   9750 17       // If a PCR extend is required
   9751 18       if(in->pcrHandle != TPM_RH_NULL)
   9752 19       {
   9753 20           // If the PCR is not allow to extend, return error
   9754 21           if(!PCRIsExtendAllowed(in->pcrHandle))
   9755 22               return TPM_RC_LOCALITY;
   9756 23
   9757 24           // If PCR is state saved and we need to update orderlyState, check NV
   9758 25           // availability
   9759 26           if(PCRIsStateSaved(in->pcrHandle) && gp.orderlyState != SHUTDOWN_NONE)
   9760 27           {
   9761 28               result = NvIsAvailable();
   9762 29               if(result != TPM_RC_SUCCESS) return result;
   9763 30               g_clearOrderly = TRUE;
   9764 31           }
   9765 32       }
   9766 33
   9767 34   // Internal Data Update
   9768 35
   9769 36       out->digests.count = HASH_COUNT;
   9770 37
   9771 38       // Iterate supported PCR bank algorithms to extend
   9772 39       for(i = 0; i < HASH_COUNT; i++)
   9773 40       {
   9774 41           TPM_ALG_ID hash = CryptGetHashAlgByIndex(i);
   9775 42           out->digests.digests[i].hashAlg = hash;
   9776 43           size = CryptStartHash(hash, &hashState);
   9777 44           CryptUpdateDigest2B(&hashState, &in->eventData.b);
   9778 45           CryptCompleteHash(&hashState, size,
   9779 46                             (BYTE *) &out->digests.digests[i].digest);
   9780 47           if(in->pcrHandle != TPM_RH_NULL)
   9781 48               PCRExtend(in->pcrHandle, hash, size,
   9782 49                         (BYTE *) &out->digests.digests[i].digest);
   9783 50       }
   9784 51
   9785 52       return TPM_RC_SUCCESS;
   9786 53   }
   9787 54   #endif // CC_PCR_Event
   9788 
   9789 
   9790      Page 208                                  TCG Published                                     Family 2.0
   9791      October 30, 2014                  Copyright  TCG 2006-2014                     Level 00 Revision 01.16
   9792 Trusted Platform Module Library                                                                 Part 3: Commands
   9794 
   9795 
   9796 22.4   TPM2_PCR_Read
   9797 
   9798 22.4.1 General Description
   9799 
   9800 This command returns the values of all PCR specified in pcrSelectionIn.
   9801 The TPM will process the list of TPMS_PCR_SELECTION in pcrSelectionIn in order. Within each
   9802 TPMS_PCR_SELECTION, the TPM will process the bits in the pcrSelect array in ascending PCR order
   9803 (see TPM 2.0 Part 2 for definition of the PCR order). If a bit is SET, and the indicated PCR is present,
   9804 then the TPM will add the digest of the PCR to the list of values to be returned in pcrValues.
   9805 The TPM will continue processing bits until all have been processed or until pcrValues would be too large
   9806 to fit into the output buffer if additional values were added.
   9807 The returned pcrSelectionOut will have a bit SET in its pcrSelect structures for each value present in
   9808 pcrValues.
   9809 The current value of the PCR Update Counter is returned in pcrUpdateCounter.
   9810 The returned list may be empty if none of the selected PCR are implemented.
   9811 
   9812 NOTE            If no PCR are returned from a bank, the selector for the bank will be present in pcrSelectionOut.
   9813 
   9814 No authorization is required to read a PCR and any implemented PCR may be read from any locality.
   9815 
   9816 
   9817 
   9818 
   9819 Family 2.0                                   TCG Published                                              Page 209
   9820 Level 00 Revision 01.16                Copyright  TCG 2006-2014                                October 30, 2014
   9821 Part 3: Commands                                                  Trusted Platform Module Library
   9823 
   9824 
   9825 
   9826 22.4.2 Command and Response
   9827 
   9828                       Table 103  TPM2_PCR_Read Command
   9829 Type                   Name                  Description
   9830 
   9831                                              TPM_ST_SESSIONS if an audit session is present;
   9832 TPMI_ST_COMMAND_TAG    tag
   9833                                              otherwise, TPM_ST_NO_SESSIONS
   9834 UINT32                 commandSize
   9835 TPM_CC                 commandCode           TPM_CC_PCR_Read
   9836 
   9837 TPML_PCR_SELECTION     pcrSelectionIn        The selection of PCR to read
   9838 
   9839 
   9840                       Table 104  TPM2_PCR_Read Response
   9841 Type                   Name                  Description
   9842 
   9843 TPM_ST                 tag                   see clause 6
   9844 UINT32                 responseSize
   9845 TPM_RC                 responseCode
   9846 
   9847 UINT32                 pcrUpdateCounter      the current value of the PCR update counter
   9848 TPML_PCR_SELECTION     pcrSelectionOut       the PCR in the returned list
   9849                                              the contents of the PCR indicated in pcrSelect as
   9850 TPML_DIGEST            pcrValues
   9851                                              tagged digests
   9852 
   9853 
   9854 
   9855 
   9856 Page 210                              TCG Published                                    Family 2.0
   9857 October 30, 2014             Copyright  TCG 2006-2014                      Level 00 Revision 01.16
   9858      Trusted Platform Module Library                                            Part 3: Commands
   9860 
   9861 
   9862 
   9863      22.4.3 Detailed Actions
   9864 
   9865  1   #include "InternalRoutines.h"
   9866  2   #include "PCR_Read_fp.h"
   9867  3   #ifdef TPM_CC_PCR_Read // Conditional expansion of this file
   9868  4   TPM_RC
   9869  5   TPM2_PCR_Read(
   9870  6       PCR_Read_In      *in,            // IN: input parameter list
   9871  7       PCR_Read_Out     *out            // OUT: output parameter list
   9872  8       )
   9873  9   {
   9874 10   // Command Output
   9875 11
   9876 12       // Call PCR read function. input pcrSelectionIn parameter could be changed
   9877 13       // to reflect the actual PCR being returned
   9878 14       PCRRead(&in->pcrSelectionIn, &out->pcrValues, &out->pcrUpdateCounter);
   9879 15
   9880 16       out->pcrSelectionOut = in->pcrSelectionIn;
   9881 17
   9882 18       return TPM_RC_SUCCESS;
   9883 19   }
   9884 20   #endif // CC_PCR_Read
   9885 
   9886 
   9887 
   9888 
   9889      Family 2.0                            TCG Published                             Page 211
   9890      Level 00 Revision 01.16           Copyright  TCG 2006-2014                October 30, 2014
   9891 Part 3: Commands                                                              Trusted Platform Module Library
   9893 
   9894 
   9895 22.5     TPM2_PCR_Allocate
   9896 
   9897 22.5.1 General Description
   9898 
   9899 This command is used to set the desired PCR allocation of PCR and algorithms. This command requires
   9900 Platform Authorization.
   9901 The TPM will evaluate the request and, if sufficient memory is available for the requested allocation, the
   9902 TPM will store the allocation request for use during the next TPM2_Startup(TPM_SU_CLEAR) operation.
   9903 The PCR allocation in place when this command is executed will be retained until the next
   9904 TPM2_Startup(TPM_SU_CLEAR).              If this command is received multiple times before a
   9905 TPM2_Startup(TPM_SU_CLEAR), each one overwrites the previous stored allocation.
   9906 This command will only change the allocations of banks that are listed in pcrAllocation.
   9907 EXAMPLE      If a TPM supports SHA1 and SHA256, then it maintains an allocation for two banks (one of which could
   9908              be empty). If a TPM_PCR_ALLOCATE() only has a selector for the SHA1 bank, then only the allocation
   9909              of the SHA1 bank will be changed and the SHA256 bank will re main unchanged. To change the
   9910              allocation of a TPM from 24 SHA1 PCR and no SHA256 PCR to 24 SHA256 PCR and no SHA1 PCR, the
   9911              pcrAllocation would have to have two selections: one for the empty SHA1 bank and one for the SHA256
   9912              bank with 24 PCR.
   9913 
   9914 
   9915 If a bank is listed more than once, then the last selection in the pcrAllocation list is the one that the TPM
   9916 will attempt to allocate.
   9917 This command shall not allocate more PCR in any bank than there are PCR attribute definitions. The
   9918 PCR attribute definitions indicate how a PCR is to be managed  if it is resettable, the locality for update,
   9919 etc. In the response to this command, the TPM returns the maximum number of PCR allowed for any
   9920 bank.
   9921 When PCR are allocated, if DRTM_PCR is defined, the resulting allocation must have at least one bank
   9922 with the D-RTM PCR allocated. If HCRTM_PCR is defined, the resulting allocation must have at least
   9923 one bank with the HCRTM_PCR allocated. If not, the TPM returns TPM_RC_PCR.
   9924 The TPM may return TPM_RC_SUCCESS even though the request fails. This is to allow the TPM to
   9925 return information about the size needed for the requested allocation and the size available. If the
   9926 sizeNeeded parameter in the return is less than or equal to the sizeAvailable parameter, then the
   9927 allocationSuccess parameter will be YES. Alternatively, if the request fails, The TPM may return
   9928 TPM_RC_NO_RESULT.
   9929 
   9930 NOTE 1          An example for this type of failure is a TPM that can only support one bank at a time and cannot
   9931                 support arbitrary distribution of PCR among banks.
   9932 
   9933 After this command, TPM2_Shutdown() is only allowed to have a startupType equal to TPM_SU_CLEAR.
   9934 
   9935 NOTE 2          Even if this command does not cause the PCR allocation to change, the TPM cannot have its state
   9936                 saved. This is done in order to simplify the implementat ion. There is no need to optimize this
   9937                 command as it is not expected to be used more than once in the lifetime of the TPM (it can be used
   9938                 any number of times but there is no justification for optimization).
   9939 
   9940 
   9941 
   9942 
   9943 Page 212                                      TCG Published                                        Family 2.0
   9944 October 30, 2014                      Copyright  TCG 2006-2014                      Level 00 Revision 01.16
   9945 Trusted Platform Module Library                                                          Part 3: Commands
   9947 
   9948 
   9949 22.5.2 Command and Response
   9950 
   9951                            Table 105  TPM2_PCR_Allocate Command
   9952 Type                          Name                   Description
   9953 
   9954 TPMI_ST_COMMAND_TAG           tag                    TPM_ST_SESSIONS
   9955 UINT32                        commandSize
   9956 TPM_CC                        commandCode            TPM_CC_PCR_Allocate {NV}
   9957 
   9958                                                      TPM_RH_PLATFORM+{PP}
   9959 TPMI_RH_PLATFORM              @authHandle            Auth Index: 1
   9960                                                      Auth Role: USER
   9961 
   9962 TPML_PCR_SELECTION            pcrAllocation          the requested allocation
   9963 
   9964 
   9965                             Table 106  TPM2_PCR_Allocate Response
   9966 Type                          Name                   Description
   9967 
   9968 TPM_ST                        tag                    see clause 6
   9969 UINT32                        responseSize
   9970 TPM_RC                        responseCode
   9971 
   9972 TPMI_YES_NO                   allocationSuccess      YES if the allocation succeeded
   9973 UINT32                        maxPCR                 maximum number of PCR that may be in a bank
   9974 UINT32                        sizeNeeded             number of octets required to satisfy the request
   9975                                                      Number of octets available. Computed before the
   9976 UINT32                        sizeAvailable
   9977                                                      allocation.
   9978 
   9979 
   9980 
   9981 
   9982 Family 2.0                                  TCG Published                                        Page 213
   9983 Level 00 Revision 01.16             Copyright  TCG 2006-2014                            October 30, 2014
   9984      Part 3: Commands                                                            Trusted Platform Module Library
   9986 
   9987 
   9988 
   9989      22.5.3 Detailed Actions
   9990 
   9991 1    #include "InternalRoutines.h"
   9992 2    #include "PCR_Allocate_fp.h"
   9993 3    #ifdef TPM_CC_PCR_Allocate // Conditional expansion of this file
   9994 
   9995 
   9996      Error Returns                    Meaning
   9997 
   9998      TPM_RC_PCR                       the allocation did not have required PCR
   9999      TPM_RC_NV_UNAVAILABLE            NV is not accessible
   10000      TPM_RC_NV_RATE                   NV is in a rate-limiting mode
   10001 
   10002  4   TPM_RC
   10003  5   TPM2_PCR_Allocate(
   10004  6       PCR_Allocate_In       *in,                 // IN: input parameter list
   10005  7       PCR_Allocate_Out      *out                 // OUT: output parameter list
   10006  8       )
   10007  9   {
   10008 10       TPM_RC      result;
   10009 11
   10010 12       // The command needs NV update. Check if NV is available.
   10011 13       // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   10012 14       // this point.
   10013 15       // Note: These codes are not listed in the return values above because it is
   10014 16       // an implementation choice to check in this routine rather than in a common
   10015 17       // function that is called before these actions are called. These return values
   10016 18       // are described in the Response Code section of Part 3.
   10017 19       result = NvIsAvailable();
   10018 20       if(result != TPM_RC_SUCCESS)
   10019 21           return result;
   10020 22
   10021 23   // Command Output
   10022 24
   10023 25       // Call PCR Allocation function.
   10024 26       result = PCRAllocate(&in->pcrAllocation, &out->maxPCR,
   10025 27                                            &out->sizeNeeded, &out->sizeAvailable);
   10026 28       if(result == TPM_RC_PCR)
   10027 29           return result;
   10028 30
   10029 31       //
   10030 32       out->allocationSuccess = (result == TPM_RC_SUCCESS);
   10031 33
   10032 34       // if re-configuration succeeds, set the flag to indicate PCR configuration is
   10033 35       // going to be changed in next boot
   10034 36       if(out->allocationSuccess == YES)
   10035 37           g_pcrReConfig = TRUE;
   10036 38
   10037 39       return TPM_RC_SUCCESS;
   10038 40   }
   10039 41   #endif // CC_PCR_Allocate
   10040 
   10041 
   10042 
   10043 
   10044      Page 214                                      TCG Published                                   Family 2.0
   10045      October 30, 2014                     Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   10046 Trusted Platform Module Library                                                               Part 3: Commands
   10048 
   10049 
   10050 22.6     TPM2_PCR_SetAuthPolicy
   10051 
   10052 22.6.1 General Description
   10053 
   10054 This command is used to associate a policy with a PCR or group of PCR. The policy determines the
   10055 conditions under which a PCR may be extended or reset.
   10056 A policy may only be associated with a PCR that has been defined by a platform-specific specification as
   10057 allowing a policy. If the TPM implementation does not allow a policy for pcrNum, the TPM shall return
   10058 TPM_RC_VALUE.
   10059 A platform-specific specification may group PCR so that they share a common policy. In such case, a
   10060 pcrNum that selects any of the PCR in the group will change the policy for all PCR in the group.
   10061 The policy setting is persistent and may only be changed by TPM2_PCR_SetAuthPolicy() or by
   10062 TPM2_ChangePPS().
   10063 Before this command is first executed on a TPM or after TPM2_ChangePPS(), the access control on the
   10064 PCR will be set to the default value defined in the platform-specific specification.
   10065 
   10066 NOTE 1          It is expected that the typical default will be with the policy hash set to TPM_ALG_NULL and an
   10067                 Empty Buffer for the authPolicy value. This will allow an EmptyAuth to be used as the authorization
   10068                 value.
   10069 
   10070 If the size of the data buffer in authPolicy is not the size of a digest produced by hashAlg, the TPM shall
   10071 return TPM_RC_SIZE.
   10072 
   10073 NOTE 2          If hashAlg is TPM_ALG_NULL, then the size is required to be zero.
   10074 
   10075 This command requires platformAuth/platformPolicy.
   10076 
   10077 NOTE 3          If the PCR is in multiple policy sets, the policy will be changed in only one set. The set that is
   10078                 changed will be implementation dependent.
   10079 
   10080 
   10081 
   10082 
   10083 Family 2.0                                  TCG Published                                            Page 215
   10084 Level 00 Revision 01.16               Copyright  TCG 2006-2014                               October 30, 2014
   10085 Part 3: Commands                                                  Trusted Platform Module Library
   10087 
   10088 
   10089 22.6.2 Command and Response
   10090 
   10091                    Table 107  TPM2_PCR_SetAuthPolicy Command
   10092 Type                   Name                  Description
   10093 
   10094 TPMI_ST_COMMAND_TAG    tag                   TPM_ST_SESSIONS
   10095 UINT32                 commandSize
   10096 TPM_CC                 commandCode           TPM_CC_PCR_SetAuthPolicy {NV}
   10097 
   10098                                              TPM_RH_PLATFORM+{PP}
   10099 TPMI_RH_PLATFORM       @authHandle           Auth Index: 1
   10100                                              Auth Role: USER
   10101 
   10102 TPM2B_DIGEST           authPolicy            the desired authPolicy
   10103 TPMI_ALG_HASH+         hashAlg               the hash algorithm of the policy
   10104 TPMI_DH_PCR            pcrNum                the PCR for which the policy is to be set
   10105 
   10106 
   10107                    Table 108  TPM2_PCR_SetAuthPolicy Response
   10108 Type                   Name                  Description
   10109 
   10110 TPM_ST                 tag                   see clause 6
   10111 UINT32                 responseSize
   10112 TPM_RC                 responseCode
   10113 
   10114 
   10115 
   10116 
   10117 Page 216                              TCG Published                                      Family 2.0
   10118 October 30, 2014             Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   10119      Trusted Platform Module Library                                                                 Part 3: Commands
   10121 
   10122 
   10123 
   10124      22.6.3 Detailed Actions
   10125 
   10126 1    #include "InternalRoutines.h"
   10127 2    #include "PCR_SetAuthPolicy_fp.h"
   10128 3    #ifdef TPM_CC_PCR_SetAuthPolicy // Conditional expansion of this file
   10129 
   10130 
   10131      Error Returns                     Meaning
   10132 
   10133      TPM_RC_SIZE                       size of authPolicy is not the size of a digest produced by policyDigest
   10134      TPM_RC_VALUE                      PCR referenced by pcrNum is not a member of a PCR policy group
   10135 
   10136  4   TPM_RC
   10137  5   TPM2_PCR_SetAuthPolicy(
   10138  6       PCR_SetAuthPolicy_In       *in                   // IN: input parameter list
   10139  7       )
   10140  8   {
   10141  9       UINT32       groupIndex;
   10142 10
   10143 11       TPM_RC       result;
   10144 12
   10145 13       // The command needs NV update. Check if NV is available.
   10146 14       // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   10147 15       // this point
   10148 16       result = NvIsAvailable();
   10149 17       if(result != TPM_RC_SUCCESS) return result;
   10150 18
   10151 19   // Input Validation:
   10152 20
   10153 21       // Check the authPolicy consistent with hash algorithm
   10154 22       if(in->authPolicy.t.size != CryptGetHashDigestSize(in->hashAlg))
   10155 23           return TPM_RC_SIZE + RC_PCR_SetAuthPolicy_authPolicy;
   10156 24
   10157 25       // If PCR does not belong to a policy group, return TPM_RC_VALUE
   10158 26       if(!PCRBelongsPolicyGroup(in->pcrNum, &groupIndex))
   10159 27           return TPM_RC_VALUE + RC_PCR_SetAuthPolicy_pcrNum;
   10160 28
   10161 29   // Internal Data Update
   10162 30
   10163 31       // Set PCR policy
   10164 32       gp.pcrPolicies.hashAlg[groupIndex] = in->hashAlg;
   10165 33       gp.pcrPolicies.policy[groupIndex] = in->authPolicy;
   10166 34
   10167 35       // Save new policy to NV
   10168 36       NvWriteReserved(NV_PCR_POLICIES, &gp.pcrPolicies);
   10169 37
   10170 38       return TPM_RC_SUCCESS;
   10171 39   }
   10172 40   #endif // CC_PCR_SetAuthPolicy
   10173 
   10174 
   10175 
   10176 
   10177      Family 2.0                                   TCG Published                                                Page 217
   10178      Level 00 Revision 01.16               Copyright  TCG 2006-2014                                 October 30, 2014
   10179 Part 3: Commands                                                      Trusted Platform Module Library
   10181 
   10182 
   10183 22.7   TPM2_PCR_SetAuthValue
   10184 
   10185 22.7.1 General Description
   10186 
   10187 This command changes the authValue of a PCR or group of PCR.
   10188 An authValue may only be associated with a PCR that has been defined by a platform-specific
   10189 specification as allowing an authorization value. If the TPM implementation does not allow an
   10190 authorization for pcrNum, the TPM shall return TPM_RC_VALUE. A platform-specific specification may
   10191 group PCR so that they share a common authorization value. In such case, a pcrNum that selects any of
   10192 the PCR in the group will change the authValue value for all PCR in the group.
   10193 The authorization setting is set to EmptyAuth on each STARTUP(CLEAR) or by TPM2_Clear(). The
   10194 authorization setting is preserved by SHUTDOWN(STATE).
   10195 
   10196 
   10197 
   10198 
   10199 Page 218                                  TCG Published                                 Family 2.0
   10200 October 30, 2014                   Copyright  TCG 2006-2014               Level 00 Revision 01.16
   10201 Trusted Platform Module Library                                                       Part 3: Commands
   10203 
   10204 
   10205 
   10206 22.7.2 Command and Response
   10207 
   10208                           Table 109  TPM2_PCR_SetAuthValue Command
   10209 Type                          Name                  Description
   10210 
   10211 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   10212 UINT32                        commandSize
   10213 TPM_CC                        commandCode           TPM_CC_PCR_SetAuthValue
   10214 
   10215                                                     handle for a PCR that may have an authorization value
   10216                                                     set
   10217 TPMI_DH_PCR                   @pcrHandle
   10218                                                     Auth Index: 1
   10219                                                     Auth Role: USER
   10220 
   10221 TPM2B_DIGEST                  auth                  the desired authorization value
   10222 
   10223 
   10224                           Table 110  TPM2_PCR_SetAuthValue Response
   10225 Type                          Name                  Description
   10226 
   10227 TPM_ST                        tag                   see clause 6
   10228 UINT32                        responseSize
   10229 TPM_RC                        responseCode
   10230 
   10231 
   10232 
   10233 
   10234 Family 2.0                                 TCG Published                                      Page 219
   10235 Level 00 Revision 01.16              Copyright  TCG 2006-2014                        October 30, 2014
   10236      Part 3: Commands                                                       Trusted Platform Module Library
   10238 
   10239 
   10240 
   10241      22.7.3 Detailed Actions
   10242 
   10243 1    #include "InternalRoutines.h"
   10244 2    #include "PCR_SetAuthValue_fp.h"
   10245 3    #ifdef TPM_CC_PCR_SetAuthValue // Conditional expansion of this file
   10246 
   10247 
   10248      Error Returns                 Meaning
   10249 
   10250      TPM_RC_VALUE                  PCR referenced by pcrHandle is not a member of a PCR
   10251                                    authorization group
   10252 
   10253  4   TPM_RC
   10254  5   TPM2_PCR_SetAuthValue(
   10255  6       PCR_SetAuthValue_In       *in              // IN: input parameter list
   10256  7       )
   10257  8   {
   10258  9       UINT32      groupIndex;
   10259 10       TPM_RC      result;
   10260 11
   10261 12   // Input Validation:
   10262 13
   10263 14       // If PCR does not belong to an auth group, return TPM_RC_VALUE
   10264 15       if(!PCRBelongsAuthGroup(in->pcrHandle, &groupIndex))
   10265 16           return TPM_RC_VALUE;
   10266 17
   10267 18       // The command may cause the orderlyState to be cleared due to the update of
   10268 19       // state clear data. If this is the case, Check if NV is available.
   10269 20       // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   10270 21       // this point
   10271 22       if(gp.orderlyState != SHUTDOWN_NONE)
   10272 23       {
   10273 24           result = NvIsAvailable();
   10274 25           if(result != TPM_RC_SUCCESS) return result;
   10275 26           g_clearOrderly = TRUE;
   10276 27       }
   10277 28
   10278 29   // Internal Data Update
   10279 30
   10280 31       // Set PCR authValue
   10281 32       gc.pcrAuthValues.auth[groupIndex] = in->auth;
   10282 33
   10283 34       return TPM_RC_SUCCESS;
   10284 35   }
   10285 36   #endif // CC_PCR_SetAuthValue
   10286 
   10287 
   10288 
   10289 
   10290      Page 220                                 TCG Published                                   Family 2.0
   10291      October 30, 2014                    Copyright  TCG 2006-2014                Level 00 Revision 01.16
   10292 Trusted Platform Module Library                                                             Part 3: Commands
   10294 
   10295 
   10296 22.8     TPM2_PCR_Reset
   10297 
   10298 22.8.1 General Description
   10299 
   10300 If the attribute of a PCR allows the PCR to be reset and proper authorization is provided, then this
   10301 command may be used to set the PCR to zero. The attributes of the PCR may restrict the locality that can
   10302 perform the reset operation.
   10303 
   10304 NOTE 1         The definition of TPMI_DH_PCR in TPM 2.0 Part 2 indicates that if pcrHandle is out of the allowed
   10305                range for PCR, then the appropriate return value is TPM_RC_VALUE.
   10306 
   10307 If pcrHandle references a PCR that cannot be reset, the TPM shall return TPM_RC_LOCALITY.
   10308 
   10309 NOTE 2         TPM_RC_LOCALITY is returned because the reset attributes are defined on a per -locality basis.
   10310 
   10311 
   10312 
   10313 
   10314 Family 2.0                                 TCG Published                                            Page 221
   10315 Level 00 Revision 01.16              Copyright  TCG 2006-2014                              October 30, 2014
   10316 Part 3: Commands                                                Trusted Platform Module Library
   10318 
   10319 
   10320 22.8.2 Command and Response
   10321 
   10322                       Table 111  TPM2_PCR_Reset Command
   10323 Type                   Name                  Description
   10324 
   10325 TPMI_ST_COMMAND_TAG    tag                   TPM_ST_SESSIONS
   10326 UINT32                 commandSize
   10327 TPM_CC                 commandCode           TPM_CC_PCR_Reset {NV}
   10328 
   10329                                              the PCR to reset
   10330 TPMI_DH_PCR            @pcrHandle            Auth Index: 1
   10331                                              Auth Role: USER
   10332 
   10333 
   10334                       Table 112  TPM2_PCR_Reset Response
   10335 Type                   Name                  Description
   10336 
   10337 TPM_ST                 tag                   see clause 6
   10338 UINT32                 responseSize
   10339 TPM_RC                 responseCode
   10340 
   10341 
   10342 
   10343 
   10344 Page 222                              TCG Published                               Family 2.0
   10345 October 30, 2014             Copyright  TCG 2006-2014               Level 00 Revision 01.16
   10346      Trusted Platform Module Library                                                              Part 3: Commands
   10348 
   10349 
   10350 
   10351      22.8.3 Detailed Actions
   10352 
   10353 1    #include "InternalRoutines.h"
   10354 2    #include "PCR_Reset_fp.h"
   10355 3    #ifdef TPM_CC_PCR_Reset // Conditional expansion of this file
   10356 
   10357 
   10358      Error Returns                     Meaning
   10359 
   10360      TPM_RC_LOCALITY                   current command locality is not allowed to reset the PCR referenced
   10361                                        by pcrHandle
   10362 
   10363  4   TPM_RC
   10364  5   TPM2_PCR_Reset(
   10365  6       PCR_Reset_In      *in                 // IN: input parameter list
   10366  7       )
   10367  8   {
   10368  9       TPM_RC        result;
   10369 10
   10370 11   // Input Validation
   10371 12
   10372 13       // Check if the reset operation is allowed by the current command locality
   10373 14       if(!PCRIsResetAllowed(in->pcrHandle))
   10374 15           return TPM_RC_LOCALITY;
   10375 16
   10376 17       // If PCR is state saved and we need to update orderlyState, check NV
   10377 18       // availability
   10378 19       if(PCRIsStateSaved(in->pcrHandle) && gp.orderlyState != SHUTDOWN_NONE)
   10379 20       {
   10380 21           result = NvIsAvailable();
   10381 22           if(result != TPM_RC_SUCCESS)
   10382 23               return result;
   10383 24           g_clearOrderly = TRUE;
   10384 25       }
   10385 26
   10386 27   // Internal Data Update
   10387 28
   10388 29       // Reset selected PCR in all banks to 0
   10389 30       PCRSetValue(in->pcrHandle, 0);
   10390 31
   10391 32       // Indicate that the PCR changed so that pcrCounter will be incremented if
   10392 33       // necessary.
   10393 34       PCRChanged(in->pcrHandle);
   10394 35
   10395 36       return TPM_RC_SUCCESS;
   10396 37   }
   10397 38   #endif // CC_PCR_Reset
   10398 
   10399 
   10400 
   10401 
   10402      Family 2.0                                  TCG Published                                             Page 223
   10403      Level 00 Revision 01.16               Copyright  TCG 2006-2014                              October 30, 2014
   10404 Part 3: Commands                                                                  Trusted Platform Module Library
   10406 
   10407 
   10408 22.9   _TPM_Hash_Start
   10409 
   10410 22.9.1 Description
   10411 
   10412 This indication from the TPM interface indicates the start of an H-CRTM measurement sequence. On
   10413 receipt of this indication, the TPM will initialize an H-CRTM Event Sequence context.
   10414 If no object memory is available for creation of the sequence context, the TPM will flush the context of an
   10415 object so that creation of the sequence context will always succeed.
   10416 A platform-specific specification may allow this indication before TPM2_Startup().
   10417 
   10418 NOTE            If this indication occurs after TPM2_Startup(), i t is the responsibility of software to ensure that an
   10419                 object context slot is available or to deal with the consequences of having the TPM select an
   10420                 arbitrary object to be flushed. If this indication occurs before TPM2_Startup() then all context slots
   10421                 are available.
   10422 
   10423 
   10424 
   10425 
   10426 Page 224                                        TCG Published                                           Family 2.0
   10427 October 30, 2014                       Copyright  TCG 2006-2014                         Level 00 Revision 01.16
   10428      Trusted Platform Module Library                                                Part 3: Commands
   10430 
   10431 
   10432      22.9.2 Detailed Actions
   10433 
   10434 1    #include "InternalRoutines.h"
   10435 
   10436      This function is called to process a _TPM_Hash_Start() indication.
   10437 
   10438  2   void
   10439  3   _TPM_Hash_Start(
   10440  4       void
   10441  5       )
   10442  6   {
   10443  7       TPM_RC                 result;
   10444  8       TPMI_DH_OBJECT         handle;
   10445  9
   10446 10       // If a DRTM sequence object exists, free it up
   10447 11       if(g_DRTMHandle != TPM_RH_UNASSIGNED)
   10448 12       {
   10449 13           ObjectFlush(g_DRTMHandle);
   10450 14           g_DRTMHandle = TPM_RH_UNASSIGNED;
   10451 15       }
   10452 16
   10453 17       // Create an event sequence object and store the handle in global
   10454 18       // g_DRTMHandle. A TPM_RC_OBJECT_MEMORY error may be returned at this point
   10455 19       // The null value for the 'auth' parameter will cause the sequence structure to
   10456 20       // be allocated without being set as present. This keeps the sequence from
   10457 21       // being left behind if the sequence is terminated early.
   10458 22       result = ObjectCreateEventSequence(NULL, &g_DRTMHandle);
   10459 23
   10460 24       // If a free slot was not available, then free up a slot.
   10461 25       if(result != TPM_RC_SUCCESS)
   10462 26       {
   10463 27           // An implementation does not need to have a fixed relationship between
   10464 28           // slot numbers and handle numbers. To handle the general case, scan for
   10465 29           // a handle that is assigned and free it for the DRTM sequence.
   10466 30           // In the reference implementation, the relationship between handles and
   10467 31           // slots is fixed. So, if the call to ObjectCreateEvenSequence()
   10468 32           // failed indicating that all slots are occupied, then the first handle we
   10469 33           // are going to check (TRANSIENT_FIRST) will be occupied. It will be freed
   10470 34           // so that it can be assigned for use as the DRTM sequence object.
   10471 35           for(handle = TRANSIENT_FIRST; handle < TRANSIENT_LAST; handle++)
   10472 36           {
   10473 37               // try to flush the first object
   10474 38               if(ObjectIsPresent(handle))
   10475 39                   break;
   10476 40           }
   10477 41           // If the first call to find a slot fails but none of the slots is occupied
   10478 42           // then there's a big problem
   10479 43           pAssert(handle < TRANSIENT_LAST);
   10480 44
   10481 45            // Free the slot
   10482 46            ObjectFlush(handle);
   10483 47
   10484 48            // Try to create an event sequence object again. This time, we must
   10485 49            // succeed.
   10486 50            result = ObjectCreateEventSequence(NULL, &g_DRTMHandle);
   10487 51            pAssert(result == TPM_RC_SUCCESS);
   10488 52       }
   10489 53
   10490 54       return;
   10491 55   }
   10492 
   10493 
   10494 
   10495 
   10496      Family 2.0                                TCG Published                             Page 225
   10497      Level 00 Revision 01.16              Copyright  TCG 2006-2014                 October 30, 2014
   10498 Part 3: Commands                                                      Trusted Platform Module Library
   10500 
   10501 
   10502 22.10 _TPM_Hash_Data
   10503 
   10504 22.10.1    Description
   10505 
   10506 This indication from the TPM interface indicates arrival of one or more octets of data that are to be
   10507 included in the H-CRTM Event Sequence sequence context created by the _TPM_Hash_Start indication.
   10508 The context holds data for each hash algorithm for each PCR bank implemented on the TPM.
   10509 If no H-CRTM Event Sequence context exists, this indication is discarded and no other action is
   10510 performed.
   10511 
   10512 
   10513 
   10514 
   10515 Page 226                                  TCG Published                                 Family 2.0
   10516 October 30, 2014                   Copyright  TCG 2006-2014                Level 00 Revision 01.16
   10517      Trusted Platform Module Library                                               Part 3: Commands
   10519 
   10520 
   10521 
   10522      22.10.2      Detailed Actions
   10523 
   10524 1    #include "InternalRoutines.h"
   10525 2    #include "Platform.h"
   10526 3    #include "PCR_fp.h"
   10527 
   10528      This function is called to process a _TPM_Hash_Data() indication.
   10529 
   10530  4   void
   10531  5   _TPM_Hash_Data(
   10532  6       UINT32             dataSize,        // IN: size of data to be extend
   10533  7       BYTE              *data             // IN: data buffer
   10534  8       )
   10535  9   {
   10536 10       UINT32             i;
   10537 11       HASH_OBJECT       *hashObject;
   10538 12       TPMI_DH_PCR        pcrHandle = TPMIsStarted()
   10539 13                                     ? PCR_FIRST + DRTM_PCR : PCR_FIRST + HCRTM_PCR;
   10540 14
   10541 15       // If there is no DRTM sequence object, then _TPM_Hash_Start
   10542 16       // was not called so this function returns without doing
   10543 17       // anything.
   10544 18       if(g_DRTMHandle == TPM_RH_UNASSIGNED)
   10545 19           return;
   10546 20
   10547 21       hashObject = (HASH_OBJECT *)ObjectGet(g_DRTMHandle);
   10548 22       pAssert(hashObject->attributes.eventSeq);
   10549 23
   10550 24       // For each of the implemented hash algorithms, update the digest with the
   10551 25       // data provided.
   10552 26       for(i = 0; i < HASH_COUNT; i++)
   10553 27       {
   10554 28           // make sure that the PCR is implemented for this algorithm
   10555 29           if(PcrIsAllocated(pcrHandle,
   10556 30                               hashObject->state.hashState[i].state.hashAlg))
   10557 31               // Update sequence object
   10558 32               CryptUpdateDigest(&hashObject->state.hashState[i], dataSize, data);
   10559 33       }
   10560 34
   10561 35       return;
   10562 36   }
   10563 
   10564 
   10565 
   10566 
   10567      Family 2.0                               TCG Published                             Page 227
   10568      Level 00 Revision 01.16             Copyright  TCG 2006-2014                 October 30, 2014
   10569 Part 3: Commands                                                                   Trusted Platform Module Library
   10571 
   10572 
   10573 22.11 _TPM_Hash_End
   10574 
   10575 22.11.1       Description
   10576 
   10577 This indication from the TPM interface indicates the end of the H-CRTM measurement. This indication is
   10578 discarded and no other action performed if the TPM does not contain an H-CRTM Event Sequence
   10579 context.
   10580 
   10581 NOTE 1              An H-CRTM Event Sequence context is created by _TPM_Hash_Start().
   10582 
   10583 If the H-CRTM Event Sequence occurs after TPM2_Startup(), the TPM will set all of the PCR designated
   10584 in the platform-specific specifications as resettable by this event to the value indicated in the platform
   10585 specific specification, and increment restartCount. The TPM will then Extend the Event Sequence
   10586 digest/digests into the designated D-RTM PCR (PCR[17]).
   10587                        PCR[17][hashAlg]  HhashAlg (initial_value || HhashAlg (hash_data))                          (7)
   10588 where
   10589           hashAlg                             hash algorithm associated with a bank of PCR
   10590           initial_value                       initialization value specified in the platform-specific specification
   10591                                               (should be 00)
   10592           hash_data                           all the octets of data received in _TPM_Hash_Data indications
   10593 A _TPM_Hash_End indication that occurs after TPM2_Startup() will increment pcrUpdateCounter unless
   10594 a platform-specific specification excludes modifications of PCR[DRTM] from causing an increment.
   10595 A platform-specific specification may allow an H-CRTM Event Sequence before TPM2_Startup(). If so,
   10596 _TPM_Hash_End will complete the digest, initialize PCR[0] with a digest-size value of 4, and then extend
   10597 the H-CRTM Event Sequence data into PCR[0].
   10598                             PCR[0][hashAlg]  HhashAlg (004 || HhashAlg (hash_data))                               (8)
   10599 
   10600 NOTE 2              The entire sequence of _TPM_Hash_Start, _TPM_Hash_Data, and _TPM_Hash_End are required to
   10601                     complete before TPM2_Startup() or the sequence will have no effect on the TPM.
   10602 
   10603 NOTE 3              PCR[0] does not need to be updated according to (8) until the end of TPM2_Startup().
   10604 
   10605 
   10606 
   10607 
   10608 Page 228                                          TCG Published                                            Family 2.0
   10609 October 30, 2014                          Copyright  TCG 2006-2014                      Level 00 Revision 01.16
   10610      Trusted Platform Module Library                                                Part 3: Commands
   10612 
   10613 
   10614      22.11.2       Detailed Actions
   10615 
   10616 1    #include "InternalRoutines.h"
   10617 
   10618      This function is called to process a _TPM_Hash_End() indication.
   10619 
   10620  2   void
   10621  3   _TPM_Hash_End(
   10622  4       void
   10623  5       )
   10624  6   {
   10625  7
   10626  8       UINT32            i;
   10627  9       TPM2B_DIGEST      digest;
   10628 10       HASH_OBJECT      *hashObject;
   10629 11       TPMI_DH_PCR       pcrHandle;
   10630 12
   10631 13       // If the DRTM handle is not being used, then either _TPM_Hash_Start has not
   10632 14       // been called, _TPM_Hash_End was previously called, or some other command
   10633 15       // was executed and the sequence was aborted.
   10634 16       if(g_DRTMHandle == TPM_RH_UNASSIGNED)
   10635 17           return;
   10636 18
   10637 19       // Get DRTM sequence object
   10638 20       hashObject = (HASH_OBJECT *)ObjectGet(g_DRTMHandle);
   10639 21
   10640 22       // Is this _TPM_Hash_End after Startup or before
   10641 23       if(TPMIsStarted())
   10642 24       {
   10643 25           // After
   10644 26
   10645 27             // Reset the DRTM PCR
   10646 28             PCRResetDynamics();
   10647 29
   10648 30             // Extend the DRTM_PCR.
   10649 31             pcrHandle = PCR_FIRST + DRTM_PCR;
   10650 32
   10651 33             // DRTM sequence increments restartCount
   10652 34             gr.restartCount++;
   10653 35       }
   10654 36       else
   10655 37       {
   10656 38           pcrHandle = PCR_FIRST + HCRTM_PCR;
   10657 39       }
   10658 40
   10659 41       // Complete hash and extend PCR, or if this is an HCRTM, complete
   10660 42       // the hash, reset the H-CRTM register (PCR[0]) to 0...04, and then
   10661 43       // extend the H-CRTM data
   10662 44       for(i = 0; i < HASH_COUNT; i++)
   10663 45       {
   10664 46           TPMI_ALG_HASH       hash = CryptGetHashAlgByIndex(i);
   10665 47           // make sure that the PCR is implemented for this algorithm
   10666 48           if(PcrIsAllocated(pcrHandle,
   10667 49                               hashObject->state.hashState[i].state.hashAlg))
   10668 50           {
   10669 51               // Complete hash
   10670 52               digest.t.size = CryptGetHashDigestSize(hash);
   10671 53               CryptCompleteHash2B(&hashObject->state.hashState[i], &digest.b);
   10672 54
   10673 55                  PcrDrtm(pcrHandle, hash, &digest);
   10674 56             }
   10675 57       }
   10676 58
   10677 59       // Flush sequence object.
   10678 
   10679 
   10680      Family 2.0                               TCG Published                              Page 229
   10681      Level 00 Revision 01.16             Copyright  TCG 2006-2014                  October 30, 2014
   10682      Part 3: Commands                                             Trusted Platform Module Library
   10684 
   10685 60       ObjectFlush(g_DRTMHandle);
   10686 61
   10687 62       g_DRTMHandle = TPM_RH_UNASSIGNED;
   10688 63
   10689 64       g_DrtmPreStartup = TRUE;
   10690 65
   10691 66       return;
   10692 67   }
   10693 
   10694 
   10695 
   10696 
   10697      Page 230                                TCG Published                          Family 2.0
   10698      October 30, 2014                 Copyright  TCG 2006-2014        Level 00 Revision 01.16
   10699 Trusted Platform Module Library                                                                Part 3: Commands
   10701 
   10702 
   10703 23     Enhanced Authorization (EA) Commands
   10704 
   10705 23.1     Introduction
   10706 
   10707 The commands in this clause 1 are used for policy evaluation. When successful, each command will
   10708 update the policySessionpolicyDigest in a policy session context in order to establish that the
   10709 authorizations required to use an object have been provided. Many of the commands will also modify
   10710 other parts of a policy context so that the caller may constrain the scope of the authorization that is
   10711 provided.
   10712 
   10713 NOTE 1          Many of the terms used in this clause are described in detail in TPM 2.0 Part 1 and are not redefined
   10714                 in this clause.
   10715 
   10716 The policySession parameter of the command is the handle of the policy session context to be modified
   10717 by the command.
   10718 If the policySession parameter indicates a trial policy session, then the policySessionpolicyDigest will
   10719 be updated and the indicated validations are not performed.
   10720 
   10721 NOTE 2          A policy session is set to a trial policy by TPM2_StartAuthSession(sessionType = TPM_SE_TRIAL).
   10722 
   10723 NOTE 3          Unless there is an unmarshaling error in the parameters of the command, these commands will
   10724                 return TPM_RC_SUCCESS when policySession references a trial session.
   10725 
   10726 NOTE 4          Policy context other than the policySessionpolicyDigest may be updated for a trial policy but it is
   10727                 not required.
   10728 
   10729 
   10730 
   10731 
   10732 Family 2.0                                   TCG Published                                             Page 231
   10733 Level 00 Revision 01.16                Copyright  TCG 2006-2014                               October 30, 2014
   10734 Part 3: Commands                                                              Trusted Platform Module Library
   10736 
   10737 
   10738 23.2   Signed Authorization Actions
   10739 
   10740 23.2.1 Introduction
   10741 
   10742 The TPM2_PolicySigned, TPM_PolicySecret, and TPM2_PolicyTicket commands use many of the same
   10743 functions. This clause consolidates those functions to simplify the document and to ensure uniformity of
   10744 the operations.
   10745 
   10746 23.2.2 Policy Parameter Checks
   10747 
   10748 These parameter checks will be performed when indicated in the description of each of the commands:
   10749 a) nonceTPM  If this parameter is not the Empty Buffer, and it does not match
   10750    policySessionnonceTPM, then the TPM shall return TPM_RC_VALUE. This parameter is required
   10751    to be present if expiration is non-zero (TPM_RC_EXPIRED).
   10752 b) expiration  If this parameter is not zero, then its absolute value is compared to the time in seconds
   10753    since the policySessionnonceTPM was generated. If more time has passed than indicated in
   10754    expiration, the TPM shall return TPM_RC_EXPIRED. If nonceTPM is the Empty buffer, and expiration
   10755    is non-zero, then the TPM shall return TPM_RC_EXPIRED.
   10756     If policySessiontimeout is greater than policySessionstartTime plus the absolute value of
   10757     expiration, then policySessiontimeout is set to policySessionstartTime plus the absolute value of
   10758     expiration. That is, policySessiontimeout can only be changed to a smaller value.
   10759 c) timeout  This parameter is compared to the current TPM time. If policySessiontimeout is in the
   10760    past, then the TPM shall return TPM_RC_EXPIRED.
   10761 
   10762     NOTE 1          The expiration parameter is present in the TPM2_PolicySigned and TPM2_PolicySecret
   10763                     command and timeout is the analogous parameter in the TPM2_PolicyTicket command.
   10764 
   10765 d) cpHashA  If this parameter is not an Empty Buffer
   10766 
   10767     NOTE 2          CpHashA is the hash of the command to be executed using this policy session in the
   10768                     authorization. The algorithm used to compute this hash is required to be the algorithm of the
   10769                     policy session.
   10770 
   10771     1) the TPM shall return TPM_RC_CPHASH if policySessioncpHash is set and the contents of
   10772        policySessioncpHash are not the same as cpHashA; or
   10773 
   10774         NOTE 3          cpHash is the expected cpHash value held in the policy session context.
   10775 
   10776     2) the TPM shall return TPM_RC_SIZE                    if   cpHashA     is   not     the   same    size   as
   10777        policySessionpolicyDigest.
   10778 
   10779         NOTE 4          policySessionpolicyDigest is the size of the digest produced by the hash algorithm used
   10780                         to compute policyDigest.
   10781 
   10782 
   10783 
   10784 
   10785 Page 232                                      TCG Published                                       Family 2.0
   10786 October 30, 2014                      Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   10787 Trusted Platform Module Library                                                                  Part 3: Commands
   10789 
   10790 
   10791 23.2.3 Policy Digest Update Function (PolicyUpdate())
   10792 
   10793 This is the update process for policySessionpolicyDigest used by TPM2_PolicySigned(),
   10794 TPM2_PolicySecret(), TPM2_PolicyTicket(), and TPM2_PolicyAuthorize(). The function prototype for the
   10795 update function is:
   10796                                    PolicyUpdate(commandCode, arg2, arg3)                                           (9)
   10797 where
   10798          arg2                                 a TPM2B_NAME
   10799          arg3                                 a TPM2B
   10800 These parameters are used to update policySessionpolicyDigest by
   10801                  policyDigestnew  HpolicyAlg(policyDigestold || commandCode || arg2.name)                       (10)
   10802 followed by
   10803                           policyDigestnew+1  HpolicyAlg(policyDigestnew || arg3.buffer)                         (11)
   10804 where
   10805          HpolicyAlg()                         the hash algorithm chosen when the policy session was started
   10806 
   10807 NOTE 1             If arg3 is a TPM2B_NAME, then arg3.buffer will actually be an arg3.name.
   10808 
   10809 NOTE 2             The arg2.size and arg3.size fields are not included in the hashes.
   10810 
   10811 NOTE 3             PolicyUpdate() uses two hash operations because arg2 and arg3 are variable-sized and the
   10812                    concatenation of arg2 and arg3 in a single hash could produce the same digest even though arg2
   10813                    and arg3 are different. For example, arg2 = 1 2 3 and arg3 = 4 5 6 would produce the same digest
   10814                    as arg2 = 1 2 and arg3 = 3 4 5 6. Processing of the arguments separately in different Extend
   10815                    operation insures that the digest produced by PolicyUpdate() will be different if arg2 and arg3 are
   10816                    different.
   10817 
   10818 
   10819 
   10820 
   10821 Family 2.0                                      TCG Published                                           Page 233
   10822 Level 00 Revision 01.16                   Copyright  TCG 2006-2014                              October 30, 2014
   10823 Part 3: Commands                                                               Trusted Platform Module Library
   10825 
   10826 
   10827 
   10828 23.2.4 Policy Context Updates
   10829 
   10830 When a policy command modifies some part of the policy session context other than the
   10831 policySessionpolicyDigest, the following rules apply.
   10832         cpHash  this parameter may only be changed if it contains its initialization value (an Empty
   10833          String). If cpHash is not the Empty String when a policy command attempts to update it, the TPM
   10834          will return an error (TPM_RC_CPHASH) if the current and update values are not the same.
   10835         timeOut  this parameter may only be changed to a smaller value. If a command attempts to
   10836          update this value with a larger value (longer into the future), the TPM will discard the update
   10837          value. This is not an error condition.
   10838         commandCode  once set by a policy command, this value may not be changed except by
   10839          TPM2_PolicyRestart(). If a policy command tries to change this to a different value, an error is
   10840          returned (TPM_RC_POLICY_CC).
   10841         pcrUpdateCounter  this parameter is updated by TPM2_PolicyPCR(). This value may only be
   10842          set once during a policy. Each time TPM2_PolicyPCR() executes, it checks to see if
   10843          policySessionpcrUpdateCounter has its default state, indicating that this is the first
   10844          TPM2_PolicyPCR(). If it has its default value, then policySessionpcrUpdateCounter is set to the
   10845          current value of pcrUpdateCounter. If policySessionpcrUpdateCounter does not have its default
   10846          value and its value is not the same as pcrUpdateCounter, the TPM shall return
   10847          TPM_RC_PCR_CHANGED.
   10848 
   10849    NOTE 1            If this parameter and pcrUpdateCounter are not the same, it indicates that PCR have changed
   10850                      since checked by the previous TPM2_PolicyPCR(). Since they have changed, the previous PCR
   10851                      validation is no longer valid.
   10852 
   10853         commandLocality  this parameter is the logical AND of all enabled localities. All localities are
   10854          enabled for a policy when the policy session is created. TPM2_PolicyLocalities() selectively
   10855          disables localities. Once use of a policy for a locality has been disabled, it cannot be enabled
   10856          except by TPM2_PolicyRestart().
   10857         isPPRequired  once SET, this parameter may only be CLEARed by TPM2_PolicyRestart().
   10858         isAuthValueNeeded  once SET, this parameter may only be CLEARed by
   10859          TPM2_PolicyPassword() or TPM2_PolicyRestart().
   10860         isPasswordNeeded  once SET, this parameter may only be CLEARed by
   10861          TPM2_PolicyAuthValue() or TPM2_PolicyRestart(),
   10862 
   10863 NOTE 2           Both TPM2_PolicyAuthValue() and TPM2_PolicyPassword() change policySessionpolicyDigest in
   10864                  the same way. The different commands simply indicate to the TPM the format used for the authValue
   10865                  (HMAC or clear text). Both commands could be in the same policy. The final instance of these
   10866                  commands determines the format.
   10867 
   10868 
   10869 
   10870 
   10871 Page 234                                       TCG Published                                       Family 2.0
   10872 October 30, 2014                       Copyright  TCG 2006-2014                     Level 00 Revision 01.16
   10873 Trusted Platform Module Library                                                                Part 3: Commands
   10875 
   10876 
   10877 23.2.5 Policy Ticket Creation
   10878 
   10879 If, for TPM2_PolicySigned() or TPM2_PolicySecret(), the caller specified a negative value for expiration,
   10880 and the nonceTPM matches policySession->nonceTPM, then the TPM will return a ticket that includes a
   10881 value indicating when the authorization expires. If expiration is non-negative, then the TPM will return a
   10882 NULL ticket.
   10883 The required computation for the digest in the authorization ticket is:
   10884         HMAC(proof, HpolicyAlg(ticketType || timeout || cpHashA || policyRef || authObjectName)) (12)
   10885 where
   10886          proof                             secret associated with the storage primary seed (SPS) of the
   10887                                            TPM
   10888          HpolicyAlg                        hash function using the hash algorithm associated with the policy
   10889                                            session
   10890          ticketType                        either TPM_ST_AUTH_SECRET or TPM_ST_AUTH_SIGNED,
   10891                                            used to indicate type of the ticket
   10892 
   10893          NOTE 1          If the  ticket is produced   by   TPM2_PolicySecret () then   ticketType  is
   10894                          TPM_ST_AUTH_SECRET and if produced by TPM2_PolicySigned() then ticketType is
   10895                          TPM_ST_AUTH_SIGNED.
   10896 
   10897 
   10898          timeout                           implementation-specific representation of the expiration time of
   10899                                            the ticket; required to be the implementation equivalent of
   10900                                            policySessionstartTime plus the absolute value of expiration
   10901 
   10902          NOTE 2          timeout is not the same as expiration. The expiration value in the aHash is a relative time,
   10903                          using the creation time of the authorization session (TPM2_StartAuthSession()) as its
   10904                          reference. The timeout parameter is an absolute time, using TPM Clock as the reference.
   10905 
   10906 
   10907          cpHashA                           the command parameter digest for the command being
   10908                                            authorized; computed using the hash algorithm of the policy
   10909                                            session
   10910          policyRef                         the commands that use this function have a policyRef parameter
   10911                                            and the value of that parameter is used here
   10912          authObjectName                   Name associated with the authObject parameter
   10913 
   10914 
   10915 
   10916 
   10917 Family 2.0                                   TCG Published                                             Page 235
   10918 Level 00 Revision 01.16                Copyright  TCG 2006-2014                               October 30, 2014
   10919 Part 3: Commands                                                                 Trusted Platform Module Library
   10921 
   10922 23.3    TPM2_PolicySigned
   10923 
   10924 23.3.1 General Description
   10925 
   10926 This command includes a signed authorization in a policy. The command ties the policy to a signing key
   10927 by including the Name of the signing key in the policyDigest
   10928 If policySession is a trial session, the TPM will not check the signature and will update
   10929 policySessionpolicyDigest as described in 23.2.3 as if a properly signed authorization was received, but
   10930 no ticket will be produced.
   10931 If policySession is not a trial session, the TPM will validate auth and only perform the update if it is a valid
   10932 signature over the fields of the command.
   10933 The authorizing entity will sign a digest of the authorization qualifiers: nonceTPM, expiration, cpHashA,
   10934 and policyRef. The digest is computed as:
   10935                      aHash  HauthAlg(nonceTPM || expiration || cpHashA || policyRef)                       (13)
   10936 where
   10937         HauthAlg()                           the hash associated with the auth parameter of this command
   10938 
   10939         NOTE 1            Each signature and key combination indicates the scheme and each scheme has an
   10940                           associated hash.
   10941 
   10942 
   10943         nonceTPM                             the nonceTPM parameter from the TPM2_StartAuthSession()
   10944                                              response. If the authorization is not limited to this session, the
   10945                                              size of this value is zero.
   10946 
   10947         NOTE 2            This parameter must be present if expiration is non-zero.
   10948 
   10949 
   10950         expiration                           time limit on authorization set by authorizing object. This 32-bit
   10951                                              value is set to zero if the expiration time is not being set.
   10952         cpHashA                              digest of the command parameters for the command being
   10953                                              approved using the hash algorithm of the policy session. Set to
   10954                                              an EmptyAuth if the authorization is not limited to a specific
   10955                                              command.
   10956 
   10957         NOTE 3            This is not the cpHash of this TPM2_PolicySigned() command.
   10958 
   10959 
   10960         policyRef                            an opaque value determined by the authorizing entity. Set to the
   10961                                              Empty Buffer if no value is present.
   10962 
   10963 EXAMPLE          The computation for an aHash if there are no restrictions is:
   10964 
   10965 
   10966                                        aHash  HauthAlg(00 00 00 0016)
   10967                  which is the hash of an expiration time of zero.
   10968 
   10969 The aHash is signed by the key associated with a key whose handle is authObject. The signature and
   10970 signing parameters are combined to create the auth parameter.
   10971 The TPM will perform the parameter checks listed in 23.2.2
   10972 If the parameter checks succeed, the TPM will construct a test digest (tHash) over the provided
   10973 parameters using the same formulation as shown in equation (13) above.
   10974 If tHash does not match the digest of the signed aHash, then the authorization fails and the TPM shall
   10975 return TPM_RC_POLICY_FAIL and make no change to policySessionpolicyDigest.
   10976 
   10977 
   10978 Page 236                                         TCG Published                                     Family 2.0
   10979 October 30, 2014                        Copyright  TCG 2006-2014                     Level 00 Revision 01.16
   10980 Trusted Platform Module Library                                                       Part 3: Commands
   10982 
   10983 When all validations have succeeded, policySessionpolicyDigest is updated by PolicyUpdate() (see
   10984 23.2.3).
   10985                  PolicyUpdate(TPM_CC_PolicySigned, authObjectName, policyRef)                       (14)
   10986 policySession is updated as described in 23.2.4. The TPM will optionally produce a ticket as described in
   10987 23.2.5.
   10988 Authorization to use authObject is not required.
   10989 
   10990 
   10991 
   10992 
   10993 Family 2.0                                 TCG Published                                    Page 237
   10994 Level 00 Revision 01.16              Copyright  TCG 2006-2014                        October 30, 2014
   10995 Part 3: Commands                                                     Trusted Platform Module Library
   10997 
   10998 
   10999 
   11000 23.3.2 Command and Response
   11001 
   11002                       Table 113  TPM2_PolicySigned Command
   11003 Type                   Name                   Description
   11004 
   11005                                               TPM_ST_SESSIONS if an audit, encrypt, or decrypt
   11006 TPMI_ST_COMMAND_TAG    tag                    session is present; otherwise,
   11007                                               TPM_ST_NO_SESSIONS
   11008 UINT32                 commandSize
   11009 TPM_CC                 commandCode            TPM_CC_PolicySigned
   11010 
   11011                                               handle for a key that will validate the signature
   11012 TPMI_DH_OBJECT         authObject
   11013                                               Auth Index: None
   11014                                               handle for the policy session being extended
   11015 TPMI_SH_POLICY         policySession
   11016                                               Auth Index: None
   11017 
   11018                                               the policy nonce for the session
   11019 TPM2B_NONCE            nonceTPM
   11020                                               This can be the Empty Buffer.
   11021                                               digest of the command parameters to which this
   11022                                               authorization is limited
   11023 TPM2B_DIGEST           cpHashA                This is not the cpHash for this command but the cpHash
   11024                                               for the command to which this policy session will be
   11025                                               applied. If it is not limited, the parameter will be the
   11026                                               Empty Buffer.
   11027                                               a reference to a policy relating to the authorization 
   11028                                               may be the Empty Buffer
   11029 TPM2B_NONCE            policyRef
   11030                                               Size is limited to be no larger than the nonce size
   11031                                               supported on the TPM.
   11032                                               time when authorization will expire, measured in
   11033                                               seconds from the time that nonceTPM was generated
   11034 INT32                  expiration
   11035                                               If expiration is non-negative, a NULL Ticket is returned.
   11036                                               See 23.2.5.
   11037 TPMT_SIGNATURE         auth                   signed authorization (not optional)
   11038 
   11039 
   11040                       Table 114  TPM2_PolicySigned Response
   11041 Type                   Name                   Description
   11042 
   11043 TPM_ST                 tag                    see clause 6
   11044 UINT32                 responseSize
   11045 TPM_RC                 responseCode
   11046 
   11047                                               implementation-specific time value, used to indicate to
   11048                                               the TPM when the ticket expires
   11049 TPM2B_TIMEOUT          timeout
   11050                                               NOTE        If policyTicket is a NULL Ticket, then this shall be
   11051                                                           the Empty Buffer.
   11052 
   11053                                               produced if the command succeeds and expiration in
   11054 TPMT_TK_AUTH           policyTicket           the command was non-zero; this ticket will use the
   11055                                               TPMT_ST_AUTH_SIGNED structure tag. See 23.2.5
   11056 
   11057 
   11058 
   11059 
   11060 Page 238                               TCG Published                                           Family 2.0
   11061 October 30, 2014              Copyright  TCG 2006-2014                      Level 00 Revision 01.16
   11062      Trusted Platform Module Library                                                                  Part 3: Commands
   11064 
   11065 
   11066 
   11067      23.3.3 Detailed Actions
   11068 
   11069 1    #include "InternalRoutines.h"
   11070 2    #include "Policy_spt_fp.h"
   11071 3    #include "PolicySigned_fp.h"
   11072 4    #ifdef TPM_CC_PolicySigned // Conditional expansion of this file
   11073 
   11074 
   11075      Error Returns                     Meaning
   11076 
   11077      TPM_RC_CPHASH                     cpHash was previously set to a different value
   11078      TPM_RC_EXPIRED                    expiration indicates a time in the past or expiration is non-zero but no
   11079                                        nonceTPM is present
   11080      TPM_RC_HANDLE                     authObject need to have sensitive portion loaded
   11081      TPM_RC_KEY                        authObject is not a signing scheme
   11082      TPM_RC_NONCE                      nonceTPM is not the nonce associated with the policySession
   11083      TPM_RC_SCHEME                     the signing scheme of auth is not supported by the TPM
   11084      TPM_RC_SIGNATURE                  the signature is not genuine
   11085      TPM_RC_SIZE                       input cpHash has wrong size
   11086      TPM_RC_VALUE                      input policyID or expiration does not match the internal data in policy
   11087                                        session
   11088 
   11089  5   TPM_RC
   11090  6   TPM2_PolicySigned(
   11091  7       PolicySigned_In       *in,                  // IN: input parameter list
   11092  8       PolicySigned_Out      *out                  // OUT: output parameter list
   11093  9       )
   11094 10   {
   11095 11       TPM_RC                     result = TPM_RC_SUCCESS;
   11096 12       SESSION                   *session;
   11097 13       TPM2B_NAME                 entityName;
   11098 14       TPM2B_DIGEST               authHash;
   11099 15       HASH_STATE                 hashState;
   11100 16       UINT32                     expiration = (in->expiration < 0)
   11101 17                                               ? -(in->expiration) : in->expiration;
   11102 18       UINT64                     authTimeout = 0;
   11103 19
   11104 20   // Input Validation
   11105 21
   11106 22       // Set up local pointers
   11107 23       session = SessionGet(in->policySession);               // the session structure
   11108 24
   11109 25       // Only do input validation if this is not a trial policy session
   11110 26       if(session->attributes.isTrialPolicy == CLEAR)
   11111 27       {
   11112 28           if(expiration != 0)
   11113 29               authTimeout = expiration * 1000 + session->startTime;
   11114 30
   11115 31           result = PolicyParameterChecks(session, authTimeout,
   11116 32                                           &in->cpHashA, &in->nonceTPM,
   11117 33                                           RC_PolicySigned_nonceTPM,
   11118 34                                           RC_PolicySigned_cpHashA,
   11119 35                                           RC_PolicySigned_expiration);
   11120 36           if(result != TPM_RC_SUCCESS)
   11121 37               return result;
   11122 38
   11123 39           // Re-compute the digest being signed
   11124 40           /*(See part 3 specification)
   11125 
   11126      Family 2.0                                   TCG Published                                                 Page 239
   11127      Level 00 Revision 01.16                Copyright  TCG 2006-2014                                October 30, 2014
   11128       Part 3: Commands                                                Trusted Platform Module Library
   11130 
   11131  41           // The digest is computed as:
   11132  42           //     aHash := hash ( nonceTPM | expiration | cpHashA | policyRef)
   11133  43           // where:
   11134  44           //      hash()      the hash associated with the signed auth
   11135  45           //      nonceTPM    the nonceTPM value from the TPM2_StartAuthSession .
   11136  46           //                  response If the authorization is not limited to this
   11137  47           //                  session, the size of this value is zero.
   11138  48           //      expiration time limit on authorization set by authorizing object.
   11139  49           //                  This 32-bit value is set to zero if the expiration
   11140  50           //                  time is not being set.
   11141  51           //      cpHashA     hash of the command parameters for the command being
   11142  52           //                  approved using the hash algorithm of the PSAP session.
   11143  53           //                  Set to NULLauth if the authorization is not limited
   11144  54           //                  to a specific command.
   11145  55           //      policyRef   hash of an opaque value determined by the authorizing
   11146  56           //                  object. Set to the NULLdigest if no hash is present.
   11147  57           */
   11148  58           // Start hash
   11149  59           authHash.t.size = CryptStartHash(CryptGetSignHashAlg(&in->auth),
   11150  60                                            &hashState);
   11151  61
   11152  62           // add nonceTPM
   11153  63           CryptUpdateDigest2B(&hashState, &in->nonceTPM.b);
   11154  64
   11155  65           // add expiration
   11156  66           CryptUpdateDigestInt(&hashState, sizeof(UINT32), (BYTE*) &in->expiration);
   11157  67
   11158  68           // add cpHashA
   11159  69           CryptUpdateDigest2B(&hashState, &in->cpHashA.b);
   11160  70
   11161  71           // add policyRef
   11162  72           CryptUpdateDigest2B(&hashState, &in->policyRef.b);
   11163  73
   11164  74           // Complete digest
   11165  75           CryptCompleteHash2B(&hashState, &authHash.b);
   11166  76
   11167  77           // Validate Signature. A TPM_RC_SCHEME, TPM_RC_HANDLE or TPM_RC_SIGNATURE
   11168  78           // error may be returned at this point
   11169  79           result = CryptVerifySignature(in->authObject, &authHash, &in->auth);
   11170  80           if(result != TPM_RC_SUCCESS)
   11171  81               return RcSafeAddToResult(result, RC_PolicySigned_auth);
   11172  82       }
   11173  83   // Internal Data Update
   11174  84       // Need the Name of the signing entity
   11175  85       entityName.t.size = EntityGetName(in->authObject, &entityName.t.name);
   11176  86
   11177  87       // Update policy with input policyRef and name of auth key
   11178  88       // These values are updated even if the session is a trial session
   11179  89       PolicyContextUpdate(TPM_CC_PolicySigned, &entityName, &in->policyRef,
   11180  90                           &in->cpHashA, authTimeout, session);
   11181  91
   11182  92   // Command Output
   11183  93
   11184  94       // Create ticket and timeout buffer if in->expiration < 0 and this is not
   11185  95       // a trial session.
   11186  96       // NOTE: PolicyParameterChecks() makes sure that nonceTPM is present
   11187  97       // when expiration is non-zero.
   11188  98       if(   in->expiration < 0
   11189  99          && session->attributes.isTrialPolicy == CLEAR
   11190 100         )
   11191 101       {
   11192 102           // Generate timeout buffer. The format of output timeout buffer is
   11193 103           // TPM-specific.
   11194 104           // Note: can't do a direct copy because the output buffer is a byte
   11195 105           // array and it may not be aligned to accept a 64-bit value. The method
   11196 106           // used has the side-effect of making the returned value a big-endian,
   11197 
   11198       Page 240                               TCG Published                              Family 2.0
   11199       October 30, 2014                Copyright  TCG 2006-2014             Level 00 Revision 01.16
   11200       Trusted Platform Module Library                                             Part 3: Commands
   11202 
   11203 107           // 64-bit value that is byte aligned.
   11204 108           out->timeout.t.size = sizeof(UINT64);
   11205 109           UINT64_TO_BYTE_ARRAY(authTimeout, out->timeout.t.buffer);
   11206 110
   11207 111           // Compute policy ticket
   11208 112           TicketComputeAuth(TPM_ST_AUTH_SIGNED, EntityGetHierarchy(in->authObject),
   11209 113                             authTimeout, &in->cpHashA, &in->policyRef, &entityName,
   11210 114                             &out->policyTicket);
   11211 115       }
   11212 116       else
   11213 117       {
   11214 118           // Generate a null ticket.
   11215 119           // timeout buffer is null
   11216 120           out->timeout.t.size = 0;
   11217 121
   11218 122           // auth ticket is null
   11219 123           out->policyTicket.tag = TPM_ST_AUTH_SIGNED;
   11220 124           out->policyTicket.hierarchy = TPM_RH_NULL;
   11221 125           out->policyTicket.digest.t.size = 0;
   11222 126       }
   11223 127
   11224 128       return TPM_RC_SUCCESS;
   11225 129   }
   11226 130   #endif // CC_PolicySigned
   11227 
   11228 
   11229 
   11230 
   11231       Family 2.0                           TCG Published                                Page 241
   11232       Level 00 Revision 01.16           Copyright  TCG 2006-2014                 October 30, 2014
   11233 Part 3: Commands                                                                 Trusted Platform Module Library
   11235 
   11236 
   11237 23.4     TPM2_PolicySecret
   11238 
   11239 23.4.1 General Description
   11240 
   11241 This command includes a secret-based authorization to a policy. The caller proves knowledge of the
   11242 secret value using an authorization session using the authValue associated with authHandle. A password
   11243 session, an HMAC session, or a policy session containing TPM2_PolicyAuthValue() or
   11244 TPM2_PolicyPassword() will satisfy this requirement.
   11245 If a policy session is used and use of the authValue of authHandle is not required, the TPM will return
   11246 TPM_RC_MODE.
   11247 The secret is the authValue of the entity whose handle is authHandle, which may be any TPM entity with
   11248 a handle and an associated authValue. This includes the reserved handles (for example, Platform,
   11249 Storage, and Endorsement), NV Indexes, and loaded objects.
   11250 
   11251 NOTE 1           The authorization value for a hierarchy cannot be used in this command if the hierarchy is disabled.
   11252 
   11253 If the authorization check fails, then the normal dictionary attack logic is invoked.
   11254 If the authorization provided by the authorization session is valid, the command parameters are checked
   11255 as described in 23.2.2.
   11256 nonceTPM must be present if expiration is non-zero.
   11257 When all validations have succeeded, policySessionpolicyDigest is updated by PolicyUpdate() (see
   11258 23.2.3).
   11259                   PolicyUpdate(TPM_CC_PolicySecret, authObjectName, policyRef)                                   (15)
   11260 policySession is updated as described in 23.2.4. The TPM will optionally produce a ticket as described in
   11261 23.2.5.
   11262 If the session is a trial session, policySessionpolicyDigest is updated as if the authorization is valid but
   11263 no check is performed.
   11264 
   11265 NOTE 2           If an HMAC is used to convey the authorization, a separate session is needed for the authorization.
   11266                  Because the HMAC in that authorization will include a nonce that prevents replay of the
   11267                  authorization, the value of the nonceTPM parameter in this command is limited. It is retained mostly
   11268                  to provide processing consistency with TPM2_PolicySigned().
   11269 
   11270 
   11271 
   11272 
   11273 Page 242                                        TCG Published                                          Family 2.0
   11274 October 30, 2014                        Copyright  TCG 2006-2014                       Level 00 Revision 01.16
   11275 Trusted Platform Module Library                                                            Part 3: Commands
   11277 
   11278 
   11279 23.4.2 Command and Response
   11280 
   11281                             Table 115  TPM2_PolicySecret Command
   11282 Type                          Name                   Description
   11283 
   11284 TPMI_ST_COMMAND_TAG           tag                    TPM_ST_SESSIONS
   11285 UINT32                        commandSize
   11286 TPM_CC                        commandCode            TPM_CC_PolicySecret
   11287 
   11288                                                      handle for an entity providing the authorization
   11289 TPMI_DH_ENTITY                @authHandle            Auth Index: 1
   11290                                                      Auth Role: USER
   11291                                                      handle for the policy session being extended
   11292 TPMI_SH_POLICY                policySession
   11293                                                      Auth Index: None
   11294 
   11295                                                      the policy nonce for the session
   11296 TPM2B_NONCE                   nonceTPM
   11297                                                      This can be the Empty Buffer.
   11298                                                      digest of the command parameters to which this
   11299                                                      authorization is limited
   11300 TPM2B_DIGEST                  cpHashA                This not the cpHash for this command but the cpHash
   11301                                                      for the command to which this policy session will be
   11302                                                      applied. If it is not limited, the parameter will be the
   11303                                                      Empty Buffer.
   11304                                                      a reference to a policy relating to the authorization 
   11305                                                      may be the Empty Buffer
   11306 TPM2B_NONCE                   policyRef
   11307                                                      Size is limited to be no larger than the nonce size
   11308                                                      supported on the TPM.
   11309                                                      time when authorization will expire, measured in
   11310                                                      seconds from the time that nonceTPM was generated
   11311 INT32                         expiration
   11312                                                      If expiration is non-negative, a NULL Ticket is returned.
   11313                                                      See 23.2.5.
   11314 
   11315 
   11316                             Table 116  TPM2_PolicySecret Response
   11317 Type                          Name                   Description
   11318 
   11319 TPM_ST                        tag                    see clause 6
   11320 UINT32                        responseSize
   11321 TPM_RC                        responseCode
   11322 
   11323                                                      implementation-specific time value used to indicate to
   11324 TPM2B_TIMEOUT                 timeout                the TPM when the ticket expires; this ticket will use the
   11325                                                      TPMT_ST_AUTH_SECRET structure tag
   11326                                                      produced if the command succeeds and expiration in
   11327 TPMT_TK_AUTH                  policyTicket
   11328                                                      the command was non-zero. See 23.2.5
   11329 
   11330 
   11331 
   11332 
   11333 Family 2.0                                  TCG Published                                          Page 243
   11334 Level 00 Revision 01.16             Copyright  TCG 2006-2014                              October 30, 2014
   11335      Part 3: Commands                                                             Trusted Platform Module Library
   11337 
   11338 
   11339 
   11340      23.4.3 Detailed Actions
   11341 
   11342 1    #include "InternalRoutines.h"
   11343 2    #include "PolicySecret_fp.h"
   11344 3    #ifdef TPM_CC_PolicySecret // Conditional expansion of this file
   11345 4    #include "Policy_spt_fp.h"
   11346 
   11347 
   11348      Error Returns                 Meaning
   11349 
   11350      TPM_RC_CPHASH                 cpHash for policy was previously set to a value that is not the same
   11351                                    as cpHashA
   11352      TPM_RC_EXPIRED                expiration indicates a time in the past
   11353      TPM_RC_NONCE                  nonceTPM does not match the nonce associated with policySession
   11354      TPM_RC_SIZE                   cpHashA is not the size of a digest for the hash associated with
   11355                                    policySession
   11356      TPM_RC_VALUE                  input policyID or expiration does not match the internal data in policy
   11357                                    session
   11358 
   11359  5   TPM_RC
   11360  6   TPM2_PolicySecret(
   11361  7       PolicySecret_In    *in,                 // IN: input parameter list
   11362  8       PolicySecret_Out   *out                 // OUT: output parameter list
   11363  9       )
   11364 10   {
   11365 11       TPM_RC                  result;
   11366 12       SESSION                *session;
   11367 13       TPM2B_NAME              entityName;
   11368 14       UINT32                  expiration = (in->expiration < 0)
   11369 15                                            ? -(in->expiration) : in->expiration;
   11370 16       UINT64                  authTimeout = 0;
   11371 17
   11372 18   // Input Validation
   11373 19
   11374 20       // Get pointer to the session structure
   11375 21       session = SessionGet(in->policySession);
   11376 22
   11377 23       //Only do input validation if this is not a trial policy session
   11378 24       if(session->attributes.isTrialPolicy == CLEAR)
   11379 25       {
   11380 26
   11381 27           if(expiration != 0)
   11382 28               authTimeout = expiration * 1000 + session->startTime;
   11383 29
   11384 30           result = PolicyParameterChecks(session, authTimeout,
   11385 31                                           &in->cpHashA, &in->nonceTPM,
   11386 32                                           RC_PolicySecret_nonceTPM,
   11387 33                                           RC_PolicySecret_cpHashA,
   11388 34                                           RC_PolicySecret_expiration);
   11389 35           if(result != TPM_RC_SUCCESS)
   11390 36               return result;
   11391 37       }
   11392 38
   11393 39   // Internal Data Update
   11394 40       // Need the name of the authorizing entity
   11395 41       entityName.t.size = EntityGetName(in->authHandle, &entityName.t.name);
   11396 42
   11397 43       // Update policy context with input policyRef and name of auth key
   11398 44       // This value is computed even for trial sessions. Possibly update the cpHash
   11399 45       PolicyContextUpdate(TPM_CC_PolicySecret, &entityName, &in->policyRef,
   11400 46                           &in->cpHashA, authTimeout, session);
   11401 
   11402      Page 244                                   TCG Published                                           Family 2.0
   11403      October 30, 2014                   Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   11404      Trusted Platform Module Library                                             Part 3: Commands
   11406 
   11407 47
   11408 48   // Command Output
   11409 49
   11410 50       // Create ticket and timeout buffer if in->expiration < 0 and this is not
   11411 51       // a trial session.
   11412 52       // NOTE: PolicyParameterChecks() makes sure that nonceTPM is present
   11413 53       // when expiration is non-zero.
   11414 54       if(   in->expiration < 0
   11415 55          && session->attributes.isTrialPolicy == CLEAR
   11416 56         )
   11417 57       {
   11418 58           // Generate timeout buffer. The format of output timeout buffer is
   11419 59           // TPM-specific.
   11420 60           // Note: can't do a direct copy because the output buffer is a byte
   11421 61           // array and it may not be aligned to accept a 64-bit value. The method
   11422 62           // used has the side-effect of making the returned value a big-endian,
   11423 63           // 64-bit value that is byte aligned.
   11424 64           out->timeout.t.size = sizeof(UINT64);
   11425 65           UINT64_TO_BYTE_ARRAY(authTimeout, out->timeout.t.buffer);
   11426 66
   11427 67           // Compute policy ticket
   11428 68           TicketComputeAuth(TPM_ST_AUTH_SECRET, EntityGetHierarchy(in->authHandle),
   11429 69                             authTimeout, &in->cpHashA, &in->policyRef,
   11430 70                             &entityName, &out->policyTicket);
   11431 71       }
   11432 72       else
   11433 73       {
   11434 74           // timeout buffer is null
   11435 75           out->timeout.t.size = 0;
   11436 76
   11437 77           // auth ticket is null
   11438 78           out->policyTicket.tag = TPM_ST_AUTH_SECRET;
   11439 79           out->policyTicket.hierarchy = TPM_RH_NULL;
   11440 80           out->policyTicket.digest.t.size = 0;
   11441 81       }
   11442 82
   11443 83       return TPM_RC_SUCCESS;
   11444 84   }
   11445 85   #endif // CC_PolicySecret
   11446 
   11447 
   11448 
   11449 
   11450      Family 2.0                           TCG Published                                Page 245
   11451      Level 00 Revision 01.16           Copyright  TCG 2006-2014                 October 30, 2014
   11452 Part 3: Commands                                                         Trusted Platform Module Library
   11454 
   11455 
   11456 23.5   TPM2_PolicyTicket
   11457 
   11458 23.5.1 General Description
   11459 
   11460 This command is similar to TPM2_PolicySigned() except that it takes a ticket instead of a signed
   11461 authorization. The ticket represents a validated authorization that had an expiration time associated with
   11462 it.
   11463 The parameters of this command are checked as described in 23.2.2.
   11464 If the checks succeed, the TPM uses the timeout, cpHashA, policyRef, and authName to construct a
   11465 ticket to compare with the value in ticket. If these tickets match, then the TPM will create a TPM2B_NAME
   11466 (objectName) using authName and update the context of policySession by PolicyUpdate() (see 23.2.3).
   11467                          PolicyUpdate(commandCode, authName, policyRef)                               (16)
   11468 If the structure tag of ticket is TPM_ST_AUTH_SECRET, then commandCode will be
   11469 TPM_CC_PolicySecret. If the structure tag of ticket is TPM_ST_AUTH_SIGNED, then commandCode will
   11470 be TPM_CC_PolicySIgned.
   11471 policySession is updated as described in 23.2.4.
   11472 
   11473 
   11474 
   11475 
   11476 Page 246                                    TCG Published                                    Family 2.0
   11477 October 30, 2014                    Copyright  TCG 2006-2014                  Level 00 Revision 01.16
   11478 Trusted Platform Module Library                                                            Part 3: Commands
   11480 
   11481 
   11482 
   11483 23.5.2 Command and Response
   11484 
   11485                             Table 117  TPM2_PolicyTicket Command
   11486 Type                          Name                   Description
   11487 
   11488                                                      TPM_ST_SESSIONS if an audit or decrypt session is
   11489 TPMI_ST_COMMAND_TAG           tag
   11490                                                      present; otherwise, TPM_ST_NO_SESSIONS
   11491 UINT32                        commandSize
   11492 TPM_CC                        commandCode            TPM_CC_PolicyTicket
   11493 
   11494                                                      handle for the policy session being extended
   11495 TPMI_SH_POLICY                policySession
   11496                                                      Auth Index: None
   11497 
   11498                                                      time when authorization will expire
   11499 TPM2B_TIMEOUT                 timeout                The contents are TPM specific. This shall be the value
   11500                                                      returned when ticket was produced.
   11501                                                      digest of the command parameters to which this
   11502                                                      authorization is limited
   11503 TPM2B_DIGEST                  cpHashA
   11504                                                      If it is not limited, the parameter will be the Empty
   11505                                                      Buffer.
   11506                                                      reference to a qualifier for the policy  may be the
   11507 TPM2B_NONCE                   policyRef
   11508                                                      Empty Buffer
   11509 TPM2B_NAME                    authName               name of the object that provided the authorization
   11510                                                      an authorization ticket returned by the TPM in response
   11511 TPMT_TK_AUTH                  ticket
   11512                                                      to a TPM2_PolicySigned() or TPM2_PolicySecret()
   11513 
   11514 
   11515                             Table 118  TPM2_PolicyTicket Response
   11516 Type                          Name                   Description
   11517 
   11518 TPM_ST                        tag                    see clause 6
   11519 UINT32                        responseSize
   11520 TPM_RC                        responseCode
   11521 
   11522 
   11523 
   11524 
   11525 Family 2.0                                  TCG Published                                           Page 247
   11526 Level 00 Revision 01.16                Copyright  TCG 2006-2014                           October 30, 2014
   11527      Part 3: Commands                                                             Trusted Platform Module Library
   11529 
   11530 
   11531 
   11532      23.5.3 Detailed Actions
   11533 
   11534 1    #include "InternalRoutines.h"
   11535 2    #include "PolicyTicket_fp.h"
   11536 3    #ifdef TPM_CC_PolicyTicket // Conditional expansion of this file
   11537 4    #include "Policy_spt_fp.h"
   11538 
   11539 
   11540      Error Returns                Meaning
   11541 
   11542      TPM_RC_CPHASH                policy's cpHash was previously set to a different value
   11543      TPM_RC_EXPIRED               timeout value in the ticket is in the past and the ticket has expired
   11544      TPM_RC_SIZE                  timeout or cpHash has invalid size for the
   11545      TPM_RC_TICKET                ticket is not valid
   11546 
   11547  5   TPM_RC
   11548  6   TPM2_PolicyTicket(
   11549  7       PolicyTicket_In    *in                   // IN: input parameter list
   11550  8       )
   11551  9   {
   11552 10       TPM_RC                    result;
   11553 11       SESSION                  *session;
   11554 12       UINT64                    timeout;
   11555 13       TPMT_TK_AUTH              ticketToCompare;
   11556 14       TPM_CC                    commandCode = TPM_CC_PolicySecret;
   11557 15
   11558 16   // Input Validation
   11559 17
   11560 18       // Get pointer to the session structure
   11561 19       session = SessionGet(in->policySession);
   11562 20
   11563 21       // NOTE: A trial policy session is not allowed to use this command.
   11564 22       // A ticket is used in place of a previously given authorization. Since
   11565 23       // a trial policy doesn't actually authenticate, the validated
   11566 24       // ticket is not necessary and, in place of using a ticket, one
   11567 25       // should use the intended authorization for which the ticket
   11568 26       // would be a substitute.
   11569 27       if(session->attributes.isTrialPolicy)
   11570 28           return TPM_RCS_ATTRIBUTES + RC_PolicyTicket_policySession;
   11571 29
   11572 30       // Restore timeout data. The format of timeout buffer is TPM-specific.
   11573 31       // In this implementation, we simply copy the value of timeout to the
   11574 32       // buffer.
   11575 33       if(in->timeout.t.size != sizeof(UINT64))
   11576 34           return TPM_RC_SIZE + RC_PolicyTicket_timeout;
   11577 35       timeout = BYTE_ARRAY_TO_UINT64(in->timeout.t.buffer);
   11578 36
   11579 37       // Do the normal checks on the cpHashA and timeout values
   11580 38       result = PolicyParameterChecks(session, timeout,
   11581 39                                      &in->cpHashA, NULL,
   11582 40                                      0,                       // no bad nonce return
   11583 41                                      RC_PolicyTicket_cpHashA,
   11584 42                                      RC_PolicyTicket_timeout);
   11585 43       if(result != TPM_RC_SUCCESS)
   11586 44           return result;
   11587 45
   11588 46       // Validate Ticket
   11589 47       // Re-generate policy ticket by input parameters
   11590 48       TicketComputeAuth(in->ticket.tag, in->ticket.hierarchy, timeout, &in->cpHashA,
   11591 49                         &in->policyRef, &in->authName, &ticketToCompare);
   11592 50
   11593 51       // Compare generated digest with input ticket digest
   11594 
   11595      Page 248                                   TCG Published                                             Family 2.0
   11596      October 30, 2014                  Copyright  TCG 2006-2014                         Level 00 Revision 01.16
   11597      Trusted Platform Module Library                                            Part 3: Commands
   11599 
   11600 52       if(!Memory2BEqual(&in->ticket.digest.b, &ticketToCompare.digest.b))
   11601 53           return TPM_RC_TICKET + RC_PolicyTicket_ticket;
   11602 54
   11603 55   // Internal Data Update
   11604 56
   11605 57       // Is this ticket to take the place of a TPM2_PolicySigned() or
   11606 58       // a TPM2_PolicySecret()?
   11607 59       if(in->ticket.tag == TPM_ST_AUTH_SIGNED)
   11608 60           commandCode = TPM_CC_PolicySigned;
   11609 61       else if(in->ticket.tag == TPM_ST_AUTH_SECRET)
   11610 62           commandCode = TPM_CC_PolicySecret;
   11611 63       else
   11612 64           // There could only be two possible tag values. Any other value should
   11613 65           // be caught by the ticket validation process.
   11614 66           pAssert(FALSE);
   11615 67
   11616 68       // Update policy context
   11617 69       PolicyContextUpdate(commandCode, &in->authName, &in->policyRef,
   11618 70                           &in->cpHashA, timeout, session);
   11619 71
   11620 72       return TPM_RC_SUCCESS;
   11621 73   }
   11622 74   #endif // CC_PolicyTicket
   11623 
   11624 
   11625 
   11626 
   11627      Family 2.0                           TCG Published                              Page 249
   11628      Level 00 Revision 01.16           Copyright  TCG 2006-2014                October 30, 2014
   11629 Part 3: Commands                                                                  Trusted Platform Module Library
   11631 
   11632 
   11633 23.6     TPM2_PolicyOR
   11634 
   11635 23.6.1 General Description
   11636 
   11637 This command allows options in authorizations without requiring that the TPM evaluate all of the options.
   11638 If a policy may be satisfied by different sets of conditions, the TPM need only evaluate one set that
   11639 satisfies the policy. This command will indicate that one of the required sets of conditions has been
   11640 satisfied.
   11641 PolicySessionpolicyDigest is compared against the list of provided values. If the current
   11642 policySessionpolicyDigest does not match any value in the list, the TPM shall return TPM_RC_VALUE.
   11643 Otherwise, it will replace policySessionpolicyDigest with the digest of the concatenation of all of the
   11644 digests and return TPM_RC_SUCCESS.
   11645 If policySession is a trial session, the TPM will assume that policySessionpolicyDigest matches one of
   11646 the list entries and compute the new value of policyDigest.
   11647 The algorithm for computing the new value for policyDigest of policySession is:
   11648 a) Concatenate all the digest values in pHashList:
   11649                 digests  pHashList.digests[1].buffer ||  || pHashList.digests[n].buffer                         (17)
   11650 
   11651     NOTE 1           The TPM will not return an error if the size of an entry is not the same as the size of the digest
   11652                      of the policy. However, that entry cannot match policyDigest.
   11653 
   11654 b) Reset policyDigest to a Zero Digest.
   11655 c) Extend the command code and the hashes computed in step a) above:
   11656                policyDigestnew  HpolicyAlg(policyDigestold || TPM_CC_PolicyOR || digests)                        (18)
   11657 
   11658     NOTE 2           The computation in b) and c) above is equivalent to:
   11659                           policyDigestnew  HpolicyAlg(00 || TPM_CC_PolicyOR || digests)
   11660 
   11661 A TPM shall support a list with at least eight tagged digest values.
   11662 
   11663 NOTE 3          If policies are to be portable between TPMs, then they should not use more than eight values.
   11664 
   11665 
   11666 
   11667 
   11668 Page 250                                        TCG Published                                           Family 2.0
   11669 October 30, 2014                       Copyright  TCG 2006-2014                         Level 00 Revision 01.16
   11670 Trusted Platform Module Library                                                           Part 3: Commands
   11672 
   11673 
   11674 23.6.2 Command and Response
   11675 
   11676                               Table 119  TPM2_PolicyOR Command
   11677 Type                          Name                   Description
   11678 
   11679                                                      TPM_ST_SESSIONS if an audit session is present;
   11680 TPMI_ST_COMMAND_TAG           tag
   11681                                                      otherwise, TPM_ST_NO_SESSIONS
   11682 UINT32                        commandSize
   11683 TPM_CC                        commandCode            TPM_CC_PolicyOR.
   11684 
   11685                                                      handle for the policy session being extended
   11686 TPMI_SH_POLICY                policySession
   11687                                                      Auth Index: None
   11688 
   11689 TPML_DIGEST                   pHashList              the list of hashes to check for a match
   11690 
   11691 
   11692                               Table 120  TPM2_PolicyOR Response
   11693 Type                          Name                   Description
   11694 
   11695 TPM_ST                        tag                    see clause 6
   11696 UINT32                        responseSize
   11697 TPM_RC                        responseCode
   11698 
   11699 
   11700 
   11701 
   11702 Family 2.0                                  TCG Published                                         Page 251
   11703 Level 00 Revision 01.16             Copyright  TCG 2006-2014                             October 30, 2014
   11704      Part 3: Commands                                                           Trusted Platform Module Library
   11706 
   11707 
   11708 
   11709      23.6.3 Detailed Actions
   11710 
   11711 1    #include "InternalRoutines.h"
   11712 2    #include "PolicyOR_fp.h"
   11713 3    #ifdef TPM_CC_PolicyOR // Conditional expansion of this file
   11714 4    #include "Policy_spt_fp.h"
   11715 
   11716 
   11717      Error Returns                 Meaning
   11718 
   11719      TPM_RC_VALUE                  no digest in pHashList matched the current value of policyDigest for
   11720                                    policySession
   11721 
   11722  5   TPM_RC
   11723  6   TPM2_PolicyOR(
   11724  7       PolicyOR_In      *in               // IN: input parameter list
   11725  8       )
   11726  9   {
   11727 10       SESSION       *session;
   11728 11       UINT32         i;
   11729 12
   11730 13   // Input Validation and Update
   11731 14
   11732 15       // Get pointer to the session structure
   11733 16       session = SessionGet(in->policySession);
   11734 17
   11735 18       // Compare and Update Internal Session policy if match
   11736 19       for(i = 0; i < in->pHashList.count; i++)
   11737 20       {
   11738 21           if(   session->attributes.isTrialPolicy == SET
   11739 22              || (Memory2BEqual(&session->u2.policyDigest.b,
   11740 23                                &in->pHashList.digests[i].b))
   11741 24             )
   11742 25           {
   11743 26               // Found a match
   11744 27               HASH_STATE      hashState;
   11745 28               TPM_CC          commandCode = TPM_CC_PolicyOR;
   11746 29
   11747 30                 // Start hash
   11748 31                 session->u2.policyDigest.t.size = CryptStartHash(session->authHashAlg,
   11749 32                                                                &hashState);
   11750 33                 // Set policyDigest to 0 string and add it to hash
   11751 34                 MemorySet(session->u2.policyDigest.t.buffer, 0,
   11752 35                           session->u2.policyDigest.t.size);
   11753 36                 CryptUpdateDigest2B(&hashState, &session->u2.policyDigest.b);
   11754 37
   11755 38                 // add command code
   11756 39                 CryptUpdateDigestInt(&hashState, sizeof(TPM_CC), &commandCode);
   11757 40
   11758 41                 // Add each of the hashes in the list
   11759 42                 for(i = 0; i < in->pHashList.count; i++)
   11760 43                 {
   11761 44                     // Extend policyDigest
   11762 45                     CryptUpdateDigest2B(&hashState, &in->pHashList.digests[i].b);
   11763 46                 }
   11764 47                 // Complete digest
   11765 48                 CryptCompleteHash2B(&hashState, &session->u2.policyDigest.b);
   11766 49
   11767 50                 return TPM_RC_SUCCESS;
   11768 51           }
   11769 52       }
   11770 53       // None of the values in the list matched the current policyDigest
   11771 54       return TPM_RC_VALUE + RC_PolicyOR_pHashList;
   11772 55   }
   11773 
   11774      Page 252                                   TCG Published                                         Family 2.0
   11775      October 30, 2014                  Copyright  TCG 2006-2014                       Level 00 Revision 01.16
   11776      Trusted Platform Module Library                               Part 3: Commands
   11778 
   11779 56   #endif // CC_PolicyOR
   11780 
   11781 
   11782 
   11783 
   11784      Family 2.0                           TCG Published                 Page 253
   11785      Level 00 Revision 01.16           Copyright  TCG 2006-2014   October 30, 2014
   11786 Part 3: Commands                                                                   Trusted Platform Module Library
   11788 
   11789 
   11790 23.7     TPM2_PolicyPCR
   11791 
   11792 23.7.1 General Description
   11793 
   11794 This command is used to cause conditional gating of a policy based on PCR. This command together
   11795 with TPM2_PolicyOR() allows one group of authorizations to occur when PCR are in one state and a
   11796 different set of authorizations when the PCR are in a different state. If this command is used for a trial
   11797 policySession, policySessionpolicyDigest will be updated using the values from the command rather
   11798 than the values from digest of the TPM PCR.
   11799 The TPM will modify the pcrs parameter so that bits that correspond to unimplemented PCR are CLEAR.
   11800 If policySession is not a trial policy session, the TPM will use the modified value of pcrs to select PCR
   11801 values to hash according to TPM 2.0 Part 1, Selecting Multiple PCR. The hash algorithm of the policy
   11802 session is used to compute a digest (digestTPM) of the selected PCR. If pcrDigest does not have a length
   11803 of zero, then it is compared to digestTPM; and if the values do not match, the TPM shall return
   11804 TPM_RC_VALUE and make no change to policySessionpolicyDigest. If the values match, or if the
   11805 length of pcrDigest is zero, then policySessionpolicyDigest is extended by:
   11806           policyDigestnew  HpolicyAlg(policyDigestold || TPM_CC_PolicyPCR || pcrs || digestTPM)                    (19)
   11807 where
   11808          pcrs                                the pcrs parameter with bits corresponding to unimplemented
   11809                                              PCR set to 0
   11810          digestTPM                           the digest of the selected PCR using the hash algorithm of the
   11811                                              policy session
   11812 
   11813 NOTE 1            If the caller provides the expected PCR value, the intention is that the policy evaluation stop at that
   11814                  point if the PCR do not match. If the caller does not provide the expected PCR value, then the
   11815                  validity of the settings will not be determined until an attempt is made to use the policy for
   11816                  authorization. If the policy is constructed such that the PCR check comes before user authorization
   11817                  checks, this early termination would allow software to avoid unnecessary prompts for user input to
   11818                  satisfy a policy that would fail later due to incorrect PCR values.
   11819 
   11820 After this command completes successfully, the TPM shall return TPM_RC_PCR_CHANGED if the policy
   11821 session is used for authorization and the PCR are not known to be correct.
   11822 The TPM uses a generation number (pcrUpdateCounter) that is incremented each time PCR are
   11823 updated (unless the PCR being changed is specified not to cause a change to this counter). The value of
   11824 this counter is stored in the policy session context (policySessionpcrUpdateCounter) when this
   11825 command is executed. When the policy is used for authorization, the current value of the counter is
   11826 compared to the value in the policy session context and the authorization will fail if the values are not the
   11827 same.
   11828 When this command is executed, policySessionpcrUpdateCounter is checked to see if it has been
   11829 previously set (in the reference implementation, it has a value of zero if not previously set). If it has been
   11830 set, it will be compared with the current value of pcrUpdateCounter to determine if any PCR changes
   11831 have occurred. If the values are different, the TPM shall return TPM_RC_PCR_CHANGED.
   11832 
   11833 NOTE 2           Since the pcrUpdateCounter is updated if any PCR is extended (except those specified not to do
   11834                  so), this means that the command will fail even if a PCR not specified in the policy is updated. This
   11835                  is an optimization for the purposes of conserving internal TPM memory. This would be a rare
   11836                  occurrence. and, if this should occur, the policy could be reset using the TPM2_PolicyRestart
   11837                  command and rerun.
   11838 
   11839 If policySessionpcrUpdateCounter has not been set, then it is set to the current value of
   11840 pcrUpdateCounter.
   11841 
   11842 
   11843 
   11844 
   11845 Page 254                                         TCG Published                                            Family 2.0
   11846 October 30, 2014                        Copyright  TCG 2006-2014                         Level 00 Revision 01.16
   11847 Trusted Platform Module Library                                                              Part 3: Commands
   11849 
   11850 If policySession is a trial policy session, the TPM will not check any PCR and will compute:
   11851          policyDigestnew  HpolicyAlg(policyDigestold || TPM_CC_PolicyPCR || pcrs || pcrDigest)              (20)
   11852 In this computation, pcrs is the input parameter without modification.
   11853 
   11854 NOTE 3          The pcrs parameter is expected to match the configuration of the TPM for which the policy is being
   11855                 computed which may not be the same as the TPM on which the trial policy is being computed.
   11856 
   11857 NOTE 4          Although no PCR are checked in a trial policy session, pcrDigest is expected to correspond to some
   11858                 useful PCR values. It is legal, but pointless, to have the TP M aid in calculating a policyDigest
   11859                 corresponding to PCR values that are not useful in practice.
   11860 
   11861 
   11862 
   11863 
   11864 Family 2.0                                  TCG Published                                           Page 255
   11865 Level 00 Revision 01.16               Copyright  TCG 2006-2014                              October 30, 2014
   11866 Part 3: Commands                                                   Trusted Platform Module Library
   11868 
   11869 
   11870 23.7.2 Command and Response
   11871 
   11872                       Table 121  TPM2_PolicyPCR Command
   11873 Type                   Name                   Description
   11874 
   11875                                               TPM_ST_SESSIONS if an audit or decrypt session is
   11876 TPMI_ST_COMMAND_TAG    tag
   11877                                               present; otherwise, TPM_ST_NO_SESSIONS
   11878 UINT32                 commandSize
   11879 TPM_CC                 commandCode            TPM_CC_PolicyPCR
   11880 
   11881                                               handle for the policy session being extended
   11882 TPMI_SH_POLICY         policySession
   11883                                               Auth Index: None
   11884 
   11885                                               expected digest value of the selected PCR using the
   11886 TPM2B_DIGEST           pcrDigest
   11887                                               hash algorithm of the session; may be zero length
   11888 TPML_PCR_SELECTION     pcrs                   the PCR to include in the check digest
   11889 
   11890 
   11891                       Table 122  TPM2_PolicyPCR Response
   11892 Type                   Name                   Description
   11893 
   11894 TPM_ST                 tag                    see clause 6
   11895 UINT32                 responseSize
   11896 TPM_RC                 responseCode
   11897 
   11898 
   11899 
   11900 
   11901 Page 256                               TCG Published                                    Family 2.0
   11902 October 30, 2014              Copyright  TCG 2006-2014                  Level 00 Revision 01.16
   11903      Trusted Platform Module Library                                                              Part 3: Commands
   11905 
   11906 
   11907 
   11908      23.7.3 Detailed Actions
   11909 
   11910 1    #include "InternalRoutines.h"
   11911 2    #include "PolicyPCR_fp.h"
   11912 3    #ifdef TPM_CC_PolicyPCR // Conditional expansion of this file
   11913 
   11914 
   11915      Error Returns                     Meaning
   11916 
   11917      TPM_RC_VALUE                      if provided, pcrDigest does not match the current PCR settings
   11918      TPM_RC_PCR_CHANGED                a previous TPM2_PolicyPCR() set pcrCounter and it has changed
   11919 
   11920  4   TPM_RC
   11921  5   TPM2_PolicyPCR(
   11922  6       PolicyPCR_In      *in                 // IN: input parameter list
   11923  7       )
   11924  8   {
   11925  9       SESSION           *session;
   11926 10       TPM2B_DIGEST       pcrDigest;
   11927 11       BYTE               pcrs[sizeof(TPML_PCR_SELECTION)];
   11928 12       UINT32             pcrSize;
   11929 13       BYTE              *buffer;
   11930 14       TPM_CC             commandCode = TPM_CC_PolicyPCR;
   11931 15       HASH_STATE         hashState;
   11932 16
   11933 17   // Input Validation
   11934 18
   11935 19       // Get pointer to the session structure
   11936 20       session = SessionGet(in->policySession);
   11937 21
   11938 22       // Do validation for non trial session
   11939 23       if(session->attributes.isTrialPolicy == CLEAR)
   11940 24       {
   11941 25           // Make sure that this is not going to invalidate a previous PCR check
   11942 26           if(session->pcrCounter != 0 && session->pcrCounter != gr.pcrCounter)
   11943 27               return TPM_RC_PCR_CHANGED;
   11944 28
   11945 29           // Compute current PCR digest
   11946 30           PCRComputeCurrentDigest(session->authHashAlg, &in->pcrs, &pcrDigest);
   11947 31
   11948 32           // If the caller specified the PCR digest and it does not
   11949 33           // match the current PCR settings, return an error..
   11950 34           if(in->pcrDigest.t.size != 0)
   11951 35           {
   11952 36               if(!Memory2BEqual(&in->pcrDigest.b, &pcrDigest.b))
   11953 37                   return TPM_RC_VALUE + RC_PolicyPCR_pcrDigest;
   11954 38           }
   11955 39       }
   11956 40       else
   11957 41       {
   11958 42           // For trial session, just use the input PCR digest
   11959 43           pcrDigest = in->pcrDigest;
   11960 44       }
   11961 45   // Internal Data Update
   11962 46
   11963 47       // Update policy hash
   11964 48       // policyDigestnew = hash(   policyDigestold || TPM_CC_PolicyPCR
   11965 49       //                      || pcrs || pcrDigest)
   11966 50       // Start hash
   11967 51       CryptStartHash(session->authHashAlg, &hashState);
   11968 52
   11969 53       // add old digest
   11970 54       CryptUpdateDigest2B(&hashState, &session->u2.policyDigest.b);
   11971 
   11972      Family 2.0                                  TCG Published                                         Page 257
   11973      Level 00 Revision 01.16               Copyright  TCG 2006-2014                              October 30, 2014
   11974      Part 3: Commands                                               Trusted Platform Module Library
   11976 
   11977 55
   11978 56      // add commandCode
   11979 57      CryptUpdateDigestInt(&hashState, sizeof(TPM_CC), &commandCode);
   11980 58
   11981 59      // add PCRS
   11982 60      buffer = pcrs;
   11983 61      pcrSize = TPML_PCR_SELECTION_Marshal(&in->pcrs, &buffer, NULL);
   11984 62      CryptUpdateDigest(&hashState, pcrSize, pcrs);
   11985 63
   11986 64      // add PCR digest
   11987 65      CryptUpdateDigest2B(&hashState, &pcrDigest.b);
   11988 66
   11989 67      // complete the hash and get the results
   11990 68      CryptCompleteHash2B(&hashState, &session->u2.policyDigest.b);
   11991 69
   11992 70      // update pcrCounter in session context for non trial session
   11993 71      if(session->attributes.isTrialPolicy == CLEAR)
   11994 72      {
   11995 73          session->pcrCounter = gr.pcrCounter;
   11996 74      }
   11997 75
   11998 76       return TPM_RC_SUCCESS;
   11999 77   }
   12000 78   #endif // CC_PolicyPCR
   12001 
   12002 
   12003 
   12004 
   12005      Page 258                              TCG Published                              Family 2.0
   12006      October 30, 2014               Copyright  TCG 2006-2014             Level 00 Revision 01.16
   12007 Trusted Platform Module Library                                                           Part 3: Commands
   12009 
   12010 
   12011 23.8   TPM2_PolicyLocality
   12012 
   12013 23.8.1 General Description
   12014 
   12015 This command indicates that the authorization will be limited to a specific locality.
   12016 policySessioncommandLocality is a parameter kept in the session context. When the policy session is
   12017 started, this parameter is initialized to a value that allows the policy to apply to any locality.
   12018 If locality has a value greater than 31, then an extended locality is indicated. For an extended locality, the
   12019 TPM will validate that policySessioncommandLocality has not previously been set or that the current
   12020 value of policySessioncommandLocality is the same as locality (TPM_RC_RANGE).
   12021 When locality is not an extended locality, the TPM will validate that the policySessioncommandLocality
   12022 is not set to an extended locality value (TPM_RC_RANGE). If not the TPM will disable any locality not
   12023 SET in the locality parameter. If the result of disabling localities results in no locality being enabled, the
   12024 TPM will return TPM_RC_RANGE.
   12025 If no error occurred in the validation of locality, policySessionpolicyDigest is extended with
   12026              policyDigestnew  HpolicyAlg(policyDigestold || TPM_CC_PolicyLocality || locality)          (21)
   12027 Then policySessioncommandLocality is updated to indicate which localities are still allowed after
   12028 execution of TPM2_PolicyLocality().
   12029 When the policy session is used to authorize a command, the authorization will fail if the locality used for
   12030 the command is not one of the enabled localities in policySessioncommandLocality.
   12031 
   12032 
   12033 
   12034 
   12035 Family 2.0                                  TCG Published                                        Page 259
   12036 Level 00 Revision 01.16               Copyright  TCG 2006-2014                           October 30, 2014
   12037 Part 3: Commands                                                      Trusted Platform Module Library
   12039 
   12040 
   12041 
   12042 23.8.2 Command and Response
   12043 
   12044                       Table 123  TPM2_PolicyLocality Command
   12045 Type                    Name                   Description
   12046 
   12047                                                TPM_ST_SESSIONS if an audit session is present;
   12048 TPMI_ST_COMMAND_TAG     tag
   12049                                                otherwise, TPM_ST_NO_SESSIONS
   12050 UINT32                  commandSize
   12051 TPM_CC                  commandCode            TPM_CC_PolicyLocality
   12052 
   12053                                                handle for the policy session being extended
   12054 TPMI_SH_POLICY          policySession
   12055                                                Auth Index: None
   12056 
   12057 TPMA_LOCALITY           locality               the allowed localities for the policy
   12058 
   12059 
   12060                       Table 124  TPM2_PolicyLocality Response
   12061 Type                    Name                   Description
   12062 
   12063 TPM_ST                  tag                    see clause 6
   12064 UINT32                  responseSize
   12065 TPM_RC                  responseCode
   12066 
   12067 
   12068 
   12069 
   12070 Page 260                                TCG Published                                    Family 2.0
   12071 October 30, 2014              Copyright  TCG 2006-2014                      Level 00 Revision 01.16
   12072      Trusted Platform Module Library                                                                   Part 3: Commands
   12074 
   12075 
   12076 
   12077      23.8.3 Detailed Actions
   12078 
   12079 1    #include "InternalRoutines.h"
   12080 2    #include "PolicyLocality_fp.h"
   12081 3    #ifdef TPM_CC_PolicyLocality // Conditional expansion of this file
   12082 
   12083      Limit a policy to a specific locality
   12084 
   12085      Error Returns                       Meaning
   12086 
   12087      TPM_RC_RANGE                        all the locality values selected by locality have been disabled by
   12088                                          previous TPM2_PolicyLocality() calls.
   12089 
   12090  4   TPM_RC
   12091  5   TPM2_PolicyLocality(
   12092  6        PolicyLocality_In        *in                 // IN: input parameter list
   12093  7        )
   12094  8   {
   12095  9        SESSION        *session;
   12096 10        BYTE            marshalBuffer[sizeof(TPMA_LOCALITY)];
   12097 11        BYTE            prevSetting[sizeof(TPMA_LOCALITY)];
   12098 12        UINT32          marshalSize;
   12099 13        BYTE           *buffer;
   12100 14        TPM_CC          commandCode = TPM_CC_PolicyLocality;
   12101 15        HASH_STATE      hashState;
   12102 16
   12103 17   // Input Validation
   12104 18
   12105 19        // Get pointer to the session structure
   12106 20        session = SessionGet(in->policySession);
   12107 21
   12108 22        // Get new locality setting in canonical form
   12109 23        buffer = marshalBuffer;
   12110 24        marshalSize = TPMA_LOCALITY_Marshal(&in->locality, &buffer, NULL);
   12111 25
   12112 26        // Its an error if the locality parameter is zero
   12113 27        if(marshalBuffer[0] == 0)
   12114 28            return TPM_RC_RANGE + RC_PolicyLocality_locality;
   12115 29
   12116 30        // Get existing locality setting in canonical form
   12117 31        buffer = prevSetting;
   12118 32        TPMA_LOCALITY_Marshal(&session->commandLocality, &buffer, NULL);
   12119 33
   12120 34        // If the locality has previously been set
   12121 35        if(    prevSetting[0] != 0
   12122 36            // then the current locality setting and the requested have to be the same
   12123 37            // type (that is, either both normal or both extended
   12124 38            && ((prevSetting[0] < 32) != (marshalBuffer[0] < 32)))
   12125 39            return TPM_RC_RANGE + RC_PolicyLocality_locality;
   12126 40
   12127 41        // See if the input is a regular or extended locality
   12128 42        if(marshalBuffer[0] < 32)
   12129 43        {
   12130 44            // if there was no previous setting, start with all normal localities
   12131 45            // enabled
   12132 46            if(prevSetting[0] == 0)
   12133 47                prevSetting[0] = 0x1F;
   12134 48
   12135 49             // AND the new setting with the previous setting and store it in prevSetting
   12136 50             prevSetting[0] &= marshalBuffer[0];
   12137 51
   12138 52             // The result setting can not be 0
   12139 53             if(prevSetting[0] == 0)
   12140 
   12141      Family 2.0                                     TCG Published                                           Page 261
   12142      Level 00 Revision 01.16                 Copyright  TCG 2006-2014                                 October 30, 2014
   12143      Part 3: Commands                                                Trusted Platform Module Library
   12145 
   12146 54              return TPM_RC_RANGE + RC_PolicyLocality_locality;
   12147 55      }
   12148 56      else
   12149 57      {
   12150 58          // for extended locality
   12151 59          // if the locality has already been set, then it must match the
   12152 60          if(prevSetting[0] != 0 && prevSetting[0] != marshalBuffer[0])
   12153 61              return TPM_RC_RANGE + RC_PolicyLocality_locality;
   12154 62
   12155 63          // Setting is OK
   12156 64          prevSetting[0] = marshalBuffer[0];
   12157 65
   12158 66      }
   12159 67
   12160 68   // Internal Data Update
   12161 69
   12162 70      // Update policy hash
   12163 71      // policyDigestnew = hash(policyDigestold || TPM_CC_PolicyLocality || locality)
   12164 72      // Start hash
   12165 73      CryptStartHash(session->authHashAlg, &hashState);
   12166 74
   12167 75      // add old digest
   12168 76      CryptUpdateDigest2B(&hashState, &session->u2.policyDigest.b);
   12169 77
   12170 78      // add commandCode
   12171 79      CryptUpdateDigestInt(&hashState, sizeof(TPM_CC), &commandCode);
   12172 80
   12173 81      // add input locality
   12174 82      CryptUpdateDigest(&hashState, marshalSize, marshalBuffer);
   12175 83
   12176 84      // complete the digest
   12177 85      CryptCompleteHash2B(&hashState, &session->u2.policyDigest.b);
   12178 86
   12179 87      // update session locality by unmarshal function. The function must succeed
   12180 88      // because both input and existing locality setting have been validated.
   12181 89      buffer = prevSetting;
   12182 90      TPMA_LOCALITY_Unmarshal(&session->commandLocality, &buffer,
   12183 91                              (INT32 *) &marshalSize);
   12184 92
   12185 93       return TPM_RC_SUCCESS;
   12186 94   }
   12187 95   #endif // CC_PolicyLocality
   12188 
   12189 
   12190 
   12191 
   12192      Page 262                              TCG Published                               Family 2.0
   12193      October 30, 2014               Copyright  TCG 2006-2014             Level 00 Revision 01.16
   12194 Trusted Platform Module Library                                                            Part 3: Commands
   12196 
   12197 
   12198 23.9    TPM2_PolicyNV
   12199 
   12200 23.9.1 General Description
   12201 
   12202 This command is used to cause conditional gating of a policy based on the contents of an NV Index.
   12203 If policySession is a trial policy session, the TPM will update policySessionpolicyDigest as shown in
   12204 equations (22) and (23) below and return TPM_RC_SUCCESS. It will not perform any validation. The
   12205 remainder of this general description would apply only if policySession is not a trial policy session.
   12206 An authorization session providing authorization to read the NV Index shall be provided.
   12207 
   12208 NOTE               If read access is controlled by policy, the policy should include a branch that authorizes a
   12209                    TPM2_PolicyNV().
   12210 
   12211 If TPMA_NV_WRITTEN is not SET in the NV Index, the TPM shall return TPM_RC_NV_UNINITIALIZED.
   12212 The TPM will validate that the size of operandB plus offset is not greater than the size of the NV Index. If
   12213 it is, the TPM shall return TPM_RC_SIZE.
   12214 operandA begins at offest into the NV index contents and has a size equal to the size of operandB. The
   12215 TPM will perform the indicated arithmetic check using operandA and operandB. . If the check fails, the
   12216 TPM shall return TPM_RC_POLICY and not change policySessionpolicyDigest. If the check succeeds,
   12217 the TPM will hash the arguments:
   12218                            args  HpolicyAlg(operandB.buffer || offset || operation)                       (22)
   12219 where
   12220          HpolicyAlg()                       hash function using the algorithm of the policy session
   12221          operandB                           the value used for the comparison
   12222          offset                             offset from the start of the NV Index data to start the comparison
   12223          operation                          the operation parameter indicating the comparison being
   12224                                             performed
   12225 
   12226 
   12227 The value of args and the Name of the NV Index are extended to policySessionpolicyDigest by
   12228         policyDigestnew  HpolicyAlg(policyDigestold || TPM_CC_PolicyNV || args || nvIndexName)           (23)
   12229 where
   12230          HpolicyAlg()                       hash function using the algorithm of the policy session
   12231          args                               value computed in equation (22)
   12232          nvIndexName                       the Name of the NV Index
   12233 
   12234 
   12235 The signed arithmetic operations are performed using twos-compliment.
   12236 Magnitude comparisons assume that the octet at offset zero in the referenced NV location and in
   12237 operandB contain the most significant octet of the data.
   12238 
   12239 
   12240 
   12241 
   12242 Family 2.0                                   TCG Published                                          Page 263
   12243 Level 00 Revision 01.16                 Copyright  TCG 2006-2014                          October 30, 2014
   12244 Part 3: Commands                                                    Trusted Platform Module Library
   12246 
   12247 
   12248 
   12249 23.9.2 Command and Response
   12250 
   12251                        Table 125  TPM2_PolicyNV Command
   12252 Type                   Name                   Description
   12253 
   12254 TPMI_ST_COMMAND_TAG    tag                    TPM_ST_SESSIONS
   12255 UINT32                 commandSize
   12256 TPM_CC                 commandCode            TPM_CC_PolicyNV
   12257 
   12258                                               handle indicating the source of the authorization value
   12259 TPMI_RH_NV_AUTH        @authHandle            Auth Index: 1
   12260                                               Auth Role: USER
   12261                                               the NV Index of the area to read
   12262 TPMI_RH_NV_INDEX       nvIndex
   12263                                               Auth Index: None
   12264                                               handle for the policy session being extended
   12265 TPMI_SH_POLICY         policySession
   12266                                               Auth Index: None
   12267 
   12268 TPM2B_OPERAND          operandB               the second operand
   12269 UINT16                 offset                 the offset in the NV Index for the start of operand A
   12270 TPM_EO                 operation              the comparison to make
   12271 
   12272 
   12273                        Table 126  TPM2_PolicyNV Response
   12274 Type                   Name                   Description
   12275 
   12276 TPM_ST                 tag                    see clause 6
   12277 UINT32                 responseSize
   12278 TPM_RC                 responseCode
   12279 
   12280 
   12281 
   12282 
   12283 Page 264                               TCG Published                                      Family 2.0
   12284 October 30, 2014                Copyright  TCG 2006-2014                  Level 00 Revision 01.16
   12285      Trusted Platform Module Library                                                                   Part 3: Commands
   12287 
   12288 
   12289 
   12290      23.9.3 Detailed Actions
   12291 
   12292 1    #include "InternalRoutines.h"
   12293 2    #include "PolicyNV_fp.h"
   12294 3    #ifdef TPM_CC_PolicyNV // Conditional expansion of this file
   12295 4    #include "Policy_spt_fp.h"
   12296 5    #include "NV_spt_fp.h"         // Include NV support routine for read access check
   12297 
   12298 
   12299      Error Returns                     Meaning
   12300 
   12301      TPM_RC_AUTH_TYPE                  NV index authorization type is not correct
   12302      TPM_RC_NV_LOCKED                  NV index read locked
   12303      TPM_RC_NV_UNINITIALIZED           the NV index has not been initialized
   12304      TPM_RC_POLICY                     the comparison to the NV contents failed
   12305      TPM_RC_SIZE                       the size of nvIndex data starting at offset is less than the size of
   12306                                        operandB
   12307 
   12308  6   TPM_RC
   12309  7   TPM2_PolicyNV(
   12310  8       PolicyNV_In       *in                  // IN: input parameter list
   12311  9       )
   12312 10   {
   12313 11       TPM_RC                   result;
   12314 12       SESSION                 *session;
   12315 13       NV_INDEX                 nvIndex;
   12316 14           BYTE                 nvBuffer[sizeof(in->operandB.t.buffer)];
   12317 15       TPM2B_NAME               nvName;
   12318 16       TPM_CC                   commandCode = TPM_CC_PolicyNV;
   12319 17       HASH_STATE               hashState;
   12320 18       TPM2B_DIGEST             argHash;
   12321 19
   12322 20   // Input Validation
   12323 21
   12324 22       // Get NV index information
   12325 23       NvGetIndexInfo(in->nvIndex, &nvIndex);
   12326 24
   12327 25       // Get pointer to the session structure
   12328 26       session = SessionGet(in->policySession);
   12329 27
   12330 28       //If this is a trial policy, skip all validations and the operation
   12331 29       if(session->attributes.isTrialPolicy == CLEAR)
   12332 30       {
   12333 31           // NV Read access check. NV index should be allowed for read. A
   12334 32           // TPM_RC_AUTH_TYPE or TPM_RC_NV_LOCKED error may be return at this
   12335 33           // point
   12336 34           result = NvReadAccessChecks(in->authHandle, in->nvIndex);
   12337 35           if(result != TPM_RC_SUCCESS) return result;
   12338 36
   12339 37           // Valid NV data size should not be smaller than input operandB size
   12340 38           if((nvIndex.publicArea.dataSize - in->offset) < in->operandB.t.size)
   12341 39               return TPM_RC_SIZE + RC_PolicyNV_operandB;
   12342 40
   12343 41           // Arithmetic Comparison
   12344 42
   12345 43           // Get NV data. The size of NV data equals the input operand B size
   12346 44           NvGetIndexData(in->nvIndex, &nvIndex, in->offset,
   12347 45                          in->operandB.t.size, nvBuffer);
   12348 46
   12349 47           switch(in->operation)
   12350 48           {
   12351 
   12352      Family 2.0                                   TCG Published                                             Page 265
   12353      Level 00 Revision 01.16                Copyright  TCG 2006-2014                                  October 30, 2014
   12354       Part 3: Commands                                               Trusted Platform Module Library
   12356 
   12357  49              case TPM_EO_EQ:
   12358  50                  // compare A = B
   12359  51                  if(CryptCompare(in->operandB.t.size, nvBuffer,
   12360  52                                  in->operandB.t.size, in->operandB.t.buffer)   != 0)
   12361  53                      return TPM_RC_POLICY;
   12362  54                  break;
   12363  55              case TPM_EO_NEQ:
   12364  56                  // compare A != B
   12365  57                  if(CryptCompare(in->operandB.t.size, nvBuffer,
   12366  58                                  in->operandB.t.size, in->operandB.t.buffer)   == 0)
   12367  59                      return TPM_RC_POLICY;
   12368  60                  break;
   12369  61              case TPM_EO_SIGNED_GT:
   12370  62                  // compare A > B signed
   12371  63                  if(CryptCompareSigned(in->operandB.t.size, nvBuffer,
   12372  64                                  in->operandB.t.size, in->operandB.t.buffer)   <= 0)
   12373  65                      return TPM_RC_POLICY;
   12374  66                  break;
   12375  67              case TPM_EO_UNSIGNED_GT:
   12376  68                  // compare A > B unsigned
   12377  69                  if(CryptCompare(in->operandB.t.size, nvBuffer,
   12378  70                                  in->operandB.t.size, in->operandB.t.buffer)   <= 0)
   12379  71                      return TPM_RC_POLICY;
   12380  72                  break;
   12381  73              case TPM_EO_SIGNED_LT:
   12382  74                  // compare A < B signed
   12383  75                  if(CryptCompareSigned(in->operandB.t.size, nvBuffer,
   12384  76                                  in->operandB.t.size, in->operandB.t.buffer)   >= 0)
   12385  77                      return TPM_RC_POLICY;
   12386  78                  break;
   12387  79              case TPM_EO_UNSIGNED_LT:
   12388  80                  // compare A < B unsigned
   12389  81                  if(CryptCompare(in->operandB.t.size, nvBuffer,
   12390  82                                  in->operandB.t.size, in->operandB.t.buffer)   >= 0)
   12391  83                      return TPM_RC_POLICY;
   12392  84                  break;
   12393  85              case TPM_EO_SIGNED_GE:
   12394  86                  // compare A >= B signed
   12395  87                  if(CryptCompareSigned(in->operandB.t.size, nvBuffer,
   12396  88                                  in->operandB.t.size, in->operandB.t.buffer)   < 0)
   12397  89                      return TPM_RC_POLICY;
   12398  90                  break;
   12399  91              case TPM_EO_UNSIGNED_GE:
   12400  92                  // compare A >= B unsigned
   12401  93                  if(CryptCompare(in->operandB.t.size, nvBuffer,
   12402  94                                  in->operandB.t.size, in->operandB.t.buffer)   < 0)
   12403  95                      return TPM_RC_POLICY;
   12404  96                  break;
   12405  97              case TPM_EO_SIGNED_LE:
   12406  98                  // compare A <= B signed
   12407  99                  if(CryptCompareSigned(in->operandB.t.size, nvBuffer,
   12408 100                                  in->operandB.t.size, in->operandB.t.buffer)   > 0)
   12409 101                      return TPM_RC_POLICY;
   12410 102                  break;
   12411 103              case TPM_EO_UNSIGNED_LE:
   12412 104                  // compare A <= B unsigned
   12413 105                  if(CryptCompare(in->operandB.t.size, nvBuffer,
   12414 106                                  in->operandB.t.size, in->operandB.t.buffer)   > 0)
   12415 107                      return TPM_RC_POLICY;
   12416 108                  break;
   12417 109              case TPM_EO_BITSET:
   12418 110                  // All bits SET in B are SET in A. ((A&B)=B)
   12419 111              {
   12420 112                  UINT32 i;
   12421 113                  for (i = 0; i < in->operandB.t.size; i++)
   12422 114                      if((nvBuffer[i] & in->operandB.t.buffer[i])
   12423 
   12424       Page 266                              TCG Published                                  Family 2.0
   12425       October 30, 2014               Copyright  TCG 2006-2014             Level 00 Revision 01.16
   12426       Trusted Platform Module Library                                          Part 3: Commands
   12428 
   12429 115                                 != in->operandB.t.buffer[i])
   12430 116                             return TPM_RC_POLICY;
   12431 117                }
   12432 118                break;
   12433 119                case TPM_EO_BITCLEAR:
   12434 120                    // All bits SET in B are CLEAR in A. ((A&B)=0)
   12435 121                {
   12436 122                    UINT32 i;
   12437 123                    for (i = 0; i < in->operandB.t.size; i++)
   12438 124                        if((nvBuffer[i] & in->operandB.t.buffer[i]) != 0)
   12439 125                            return TPM_RC_POLICY;
   12440 126                }
   12441 127                break;
   12442 128                default:
   12443 129                    pAssert(FALSE);
   12444 130                    break;
   12445 131           }
   12446 132       }
   12447 133
   12448 134   // Internal Data Update
   12449 135
   12450 136       // Start argument hash
   12451 137       argHash.t.size = CryptStartHash(session->authHashAlg, &hashState);
   12452 138
   12453 139       // add operandB
   12454 140       CryptUpdateDigest2B(&hashState, &in->operandB.b);
   12455 141
   12456 142       // add offset
   12457 143       CryptUpdateDigestInt(&hashState, sizeof(UINT16), &in->offset);
   12458 144
   12459 145       // add operation
   12460 146       CryptUpdateDigestInt(&hashState, sizeof(TPM_EO), &in->operation);
   12461 147
   12462 148       // complete argument digest
   12463 149       CryptCompleteHash2B(&hashState, &argHash.b);
   12464 150
   12465 151       // Update policyDigest
   12466 152       // Start digest
   12467 153       CryptStartHash(session->authHashAlg, &hashState);
   12468 154
   12469 155       // add old digest
   12470 156       CryptUpdateDigest2B(&hashState, &session->u2.policyDigest.b);
   12471 157
   12472 158       // add commandCode
   12473 159       CryptUpdateDigestInt(&hashState, sizeof(TPM_CC), &commandCode);
   12474 160
   12475 161       // add argument digest
   12476 162       CryptUpdateDigest2B(&hashState, &argHash.b);
   12477 163
   12478 164       // Adding nvName
   12479 165       nvName.t.size = EntityGetName(in->nvIndex, &nvName.t.name);
   12480 166       CryptUpdateDigest2B(&hashState, &nvName.b);
   12481 167
   12482 168       // complete the digest
   12483 169       CryptCompleteHash2B(&hashState, &session->u2.policyDigest.b);
   12484 170
   12485 171       return TPM_RC_SUCCESS;
   12486 172   }
   12487 173   #endif // CC_PolicyNV
   12488 
   12489 
   12490 
   12491 
   12492       Family 2.0                             TCG Published                          Page 267
   12493       Level 00 Revision 01.16           Copyright  TCG 2006-2014              October 30, 2014
   12494 Part 3: Commands                                                            Trusted Platform Module Library
   12496 
   12497 
   12498 23.10 TPM2_PolicyCounterTimer
   12499 
   12500 23.10.1        General Description
   12501 
   12502 This command is used to cause conditional gating of a policy based on the contents of the
   12503 TPMS_TIME_INFO structure.
   12504 If policySession is a trial policy session, the TPM will update policySessionpolicyDigest as shown in
   12505 equations (24) and (25) below and return TPM_RC_SUCCESS. It will not perform any validation. The
   12506 remainder of this general description would apply only if policySession is not a trial policy session.
   12507 The TPM will perform the indicated arithmetic check on the indicated portion of the TPMS_TIME_INFO
   12508 structure. If the check fails, the TPM shall return TPM_RC_POLICY and not change
   12509 policySessionpolicyDigest. If the check succeeds, the TPM will hash the arguments:
   12510                           args  HpolicyAlg(operandB.buffer || offset || operation)                    (24)
   12511 where
   12512           HpolicyAlg()                    hash function using the algorithm of the policy session
   12513           operandB.buffer                 the value used for the comparison
   12514           offset                          offset from the start of the TPMS_TIME_INFO structure at which
   12515                                           the comparison starts
   12516           operation                       the operation parameter indicating the comparison being
   12517                                           performed
   12518 
   12519 
   12520 The value of args is extended to policySessionpolicyDigest by
   12521              policyDigestnew  HpolicyAlg(policyDigestold || TPM_CC_PolicyCounterTimer || args)        (25)
   12522 where
   12523           HpolicyAlg()                    hash function using the algorithm of the policy session
   12524           args                            value computed in equation (24)
   12525 
   12526 
   12527 The signed arithmetic operations are performed using twos-compliment. The indicated portion of the
   12528 TPMS_TIME_INFO structure begins at offset and has a length of operandB.size. If the octets to be
   12529 compared overflows the TPMS_TIME_INFO structure, the TPM returns TPM_RC_RANGE. The structure
   12530 is marshaled into its canonical form with no padding. The TPM does not check for alignment of the offset
   12531 with a TPMS_TIME_INFO structure member.
   12532 Magnitude comparisons assume that the octet at offset zero in the referenced location and in operandB
   12533 contain the most significant octet of the data.
   12534 
   12535 
   12536 
   12537 
   12538 Page 268                                     TCG Published                                    Family 2.0
   12539 October 30, 2014                      Copyright  TCG 2006-2014                  Level 00 Revision 01.16
   12540 Trusted Platform Module Library                                                         Part 3: Commands
   12542 
   12543 
   12544 
   12545 23.10.2    Command and Response
   12546 
   12547                         Table 127  TPM2_PolicyCounterTimer Command
   12548 Type                          Name                   Description
   12549 
   12550                                                      TPM_ST_SESSIONS if an audit or decrypt session is
   12551 TPMI_ST_COMMAND_TAG           tag
   12552                                                      present; otherwise, TPM_ST_NO_SESSIONS
   12553 UINT32                        commandSize
   12554 TPM_CC                        commandCode            TPM_CC_PolicyCounterTimer
   12555 
   12556                                                      handle for the policy session being extended
   12557 TPMI_SH_POLICY                policySession
   12558                                                      Auth Index: None
   12559 
   12560 TPM2B_OPERAND                 operandB               the second operand
   12561                                                      the offset in TPMS_TIME_INFO structure for the start of
   12562 UINT16                        offset
   12563                                                      operand A
   12564 TPM_EO                        operation              the comparison to make
   12565 
   12566 
   12567                         Table 128  TPM2_PolicyCounterTimer Response
   12568 Type                          Name                   Description
   12569 
   12570 TPM_ST                        tag                    see clause 6
   12571 UINT32                        responseSize
   12572 TPM_RC                        responseCode
   12573 
   12574 
   12575 
   12576 
   12577 Family 2.0                                  TCG Published                                         Page 269
   12578 Level 00 Revision 01.16                Copyright  TCG 2006-2014                        October 30, 2014
   12579      Part 3: Commands                                                         Trusted Platform Module Library
   12581 
   12582 
   12583 
   12584      23.10.3     Detailed Actions
   12585 
   12586 1    #include "InternalRoutines.h"
   12587 2    #include "PolicyCounterTimer_fp.h"
   12588 3    #ifdef TPM_CC_PolicyCounterTimer // Conditional expansion of this file
   12589 4    #include "Policy_spt_fp.h"
   12590 
   12591 
   12592      Error Returns                  Meaning
   12593 
   12594      TPM_RC_POLICY                  the comparison of the selected portion of the TPMS_TIME_INFO with
   12595                                     operandB failed
   12596      TPM_RC_RANGE                   offset + size exceed size of TPMS_TIME_INFO structure
   12597 
   12598  5   TPM_RC
   12599  6   TPM2_PolicyCounterTimer(
   12600  7       PolicyCounterTimer_In      *in              // IN: input parameter list
   12601  8       )
   12602  9   {
   12603 10       TPM_RC                result;
   12604 11       SESSION              *session;
   12605 12       TIME_INFO             infoData;      // data buffer of TPMS_TIME_INFO
   12606 13       TPM_CC                commandCode = TPM_CC_PolicyCounterTimer;
   12607 14       HASH_STATE            hashState;
   12608 15       TPM2B_DIGEST          argHash;
   12609 16
   12610 17   // Input Validation
   12611 18
   12612 19       // If the command is going to use any part of the counter or timer, need
   12613 20       // to verify that time is advancing.
   12614 21       // The time and clock vales are the first two 64-bit values in the clock
   12615 22       if(in->offset < sizeof(UINT64) + sizeof(UINT64))
   12616 23       {
   12617 24           // Using Clock or Time so see if clock is running. Clock doesn't run while
   12618 25           // NV is unavailable.
   12619 26           // TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned here.
   12620 27           result = NvIsAvailable();
   12621 28           if(result != TPM_RC_SUCCESS)
   12622 29               return result;
   12623 30       }
   12624 31       // Get pointer to the session structure
   12625 32       session = SessionGet(in->policySession);
   12626 33
   12627 34       //If this is a trial policy, skip all validations and the operation
   12628 35       if(session->attributes.isTrialPolicy == CLEAR)
   12629 36       {
   12630 37           // Get time data info. The size of time info data equals the input
   12631 38           // operand B size. A TPM_RC_RANGE error may be returned at this point
   12632 39           result = TimeGetRange(in->offset, in->operandB.t.size, &infoData);
   12633 40           if(result != TPM_RC_SUCCESS) return result;
   12634 41
   12635 42             // Arithmetic Comparison
   12636 43             switch(in->operation)
   12637 44             {
   12638 45                 case TPM_EO_EQ:
   12639 46                     // compare A = B
   12640 47                     if(CryptCompare(in->operandB.t.size, infoData,
   12641 48                                     in->operandB.t.size, in->operandB.t.buffer) != 0)
   12642 49                         return TPM_RC_POLICY;
   12643 50                     break;
   12644 51                 case TPM_EO_NEQ:
   12645 52                     // compare A != B
   12646 53                     if(CryptCompare(in->operandB.t.size, infoData,
   12647 
   12648      Page 270                                   TCG Published                                     Family 2.0
   12649      October 30, 2014                     Copyright  TCG 2006-2014                 Level 00 Revision 01.16
   12650       Trusted Platform Module Library                                                Part 3: Commands
   12652 
   12653  54                                    in->operandB.t.size, in->operandB.t.buffer)   == 0)
   12654  55                        return TPM_RC_POLICY;
   12655  56                    break;
   12656  57                case TPM_EO_SIGNED_GT:
   12657  58                    // compare A > B signed
   12658  59                    if(CryptCompareSigned(in->operandB.t.size, infoData,
   12659  60                                    in->operandB.t.size, in->operandB.t.buffer)   <= 0)
   12660  61                        return TPM_RC_POLICY;
   12661  62                    break;
   12662  63                case TPM_EO_UNSIGNED_GT:
   12663  64                    // compare A > B unsigned
   12664  65                    if(CryptCompare(in->operandB.t.size, infoData,
   12665  66                                    in->operandB.t.size, in->operandB.t.buffer)   <= 0)
   12666  67                        return TPM_RC_POLICY;
   12667  68                    break;
   12668  69                case TPM_EO_SIGNED_LT:
   12669  70                    // compare A < B signed
   12670  71                    if(CryptCompareSigned(in->operandB.t.size, infoData,
   12671  72                                    in->operandB.t.size, in->operandB.t.buffer)   >= 0)
   12672  73                        return TPM_RC_POLICY;
   12673  74                    break;
   12674  75                case TPM_EO_UNSIGNED_LT:
   12675  76                    // compare A < B unsigned
   12676  77                    if(CryptCompare(in->operandB.t.size, infoData,
   12677  78                                    in->operandB.t.size, in->operandB.t.buffer)   >= 0)
   12678  79                        return TPM_RC_POLICY;
   12679  80                    break;
   12680  81                case TPM_EO_SIGNED_GE:
   12681  82                    // compare A >= B signed
   12682  83                    if(CryptCompareSigned(in->operandB.t.size, infoData,
   12683  84                                    in->operandB.t.size, in->operandB.t.buffer)   < 0)
   12684  85                        return TPM_RC_POLICY;
   12685  86                    break;
   12686  87                case TPM_EO_UNSIGNED_GE:
   12687  88                    // compare A >= B unsigned
   12688  89                    if(CryptCompare(in->operandB.t.size, infoData,
   12689  90                                    in->operandB.t.size, in->operandB.t.buffer)   < 0)
   12690  91                        return TPM_RC_POLICY;
   12691  92                    break;
   12692  93                case TPM_EO_SIGNED_LE:
   12693  94                    // compare A <= B signed
   12694  95                    if(CryptCompareSigned(in->operandB.t.size, infoData,
   12695  96                                    in->operandB.t.size, in->operandB.t.buffer)   > 0)
   12696  97                        return TPM_RC_POLICY;
   12697  98                    break;
   12698  99                case TPM_EO_UNSIGNED_LE:
   12699 100                    // compare A <= B unsigned
   12700 101                    if(CryptCompare(in->operandB.t.size, infoData,
   12701 102                                    in->operandB.t.size, in->operandB.t.buffer)   > 0)
   12702 103                        return TPM_RC_POLICY;
   12703 104                    break;
   12704 105                case TPM_EO_BITSET:
   12705 106                    // All bits SET in B are SET in A. ((A&B)=B)
   12706 107                {
   12707 108                    UINT32 i;
   12708 109                    for (i = 0; i < in->operandB.t.size; i++)
   12709 110                        if(   (infoData[i] & in->operandB.t.buffer[i])
   12710 111                           != in->operandB.t.buffer[i])
   12711 112                            return TPM_RC_POLICY;
   12712 113                }
   12713 114                break;
   12714 115                case TPM_EO_BITCLEAR:
   12715 116                    // All bits SET in B are CLEAR in A. ((A&B)=0)
   12716 117                {
   12717 118                    UINT32 i;
   12718 119                    for (i = 0; i < in->operandB.t.size; i++)
   12719 
   12720       Family 2.0                            TCG Published                                  Page 271
   12721       Level 00 Revision 01.16           Copyright  TCG 2006-2014                    October 30, 2014
   12722       Part 3: Commands                                               Trusted Platform Module Library
   12724 
   12725 120                      if((infoData[i] & in->operandB.t.buffer[i]) != 0)
   12726 121                          return TPM_RC_POLICY;
   12727 122              }
   12728 123              break;
   12729 124              default:
   12730 125                  pAssert(FALSE);
   12731 126                  break;
   12732 127          }
   12733 128      }
   12734 129
   12735 130   // Internal Data Update
   12736 131
   12737 132      // Start argument list hash
   12738 133      argHash.t.size = CryptStartHash(session->authHashAlg, &hashState);
   12739 134      // add operandB
   12740 135      CryptUpdateDigest2B(&hashState, &in->operandB.b);
   12741 136      // add offset
   12742 137      CryptUpdateDigestInt(&hashState, sizeof(UINT16), &in->offset);
   12743 138      // add operation
   12744 139      CryptUpdateDigestInt(&hashState, sizeof(TPM_EO), &in->operation);
   12745 140      // complete argument hash
   12746 141      CryptCompleteHash2B(&hashState, &argHash.b);
   12747 142
   12748 143      // update policyDigest
   12749 144      // start hash
   12750 145      CryptStartHash(session->authHashAlg, &hashState);
   12751 146
   12752 147      // add old digest
   12753 148      CryptUpdateDigest2B(&hashState, &session->u2.policyDigest.b);
   12754 149
   12755 150      // add commandCode
   12756 151      CryptUpdateDigestInt(&hashState, sizeof(TPM_CC), &commandCode);
   12757 152
   12758 153      // add argument digest
   12759 154      CryptUpdateDigest2B(&hashState, &argHash.b);
   12760 155
   12761 156      // complete the digest
   12762 157      CryptCompleteHash2B(&hashState, &session->u2.policyDigest.b);
   12763 158
   12764 159       return TPM_RC_SUCCESS;
   12765 160   }
   12766 161   #endif // CC_PolicyCounterTimer
   12767 
   12768 
   12769 
   12770 
   12771       Page 272                               TCG Published                               Family 2.0
   12772       October 30, 2014                  Copyright  TCG 2006-2014             Level 00 Revision 01.16
   12773 Trusted Platform Module Library                                                             Part 3: Commands
   12775 
   12776 
   12777 23.11 TPM2_PolicyCommandCode
   12778 
   12779 23.11.1     General Description
   12780 
   12781 This command indicates that the authorization will be limited to a specific command code.
   12782 If policySessioncommandCode has its default value, then it will be set to code. If
   12783 policySessioncommandCode does not have its default value, then the TPM will return
   12784 TPM_RC_VALUE if the two values are not the same.
   12785 If code is not implemented, the TPM will return TPM_RC_POLICY_CC.
   12786 If the TPM does not return an error, it will update policySessionpolicyDigest by
   12787           policyDigestnew  HpolicyAlg(policyDigestold || TPM_CC_PolicyCommandCode || code)                   (26)
   12788 
   12789 NOTE 1          If a previous TPM2_PolicyCommandCode() had been executed, then it is probable that the policy
   12790                 expression is improperly formed but the TPM does not return an error.
   12791 
   12792 NOTE 2          A TPM2_PolicyOR() would be used to allow an authorization to be used for multiple commands.
   12793 
   12794 When the policy session is used to authorize a command, the TPM will fail the command if the
   12795 commandCode of that command does not match policySessioncommandCode.
   12796 This command, or TPM2_PolicyDuplicationSelect(), is required to enable the policy to be used for ADMIN
   12797 role authorization.
   12798 
   12799 EXAMPLE         Before TPM2_Certify() can     be   executed,   TPM2_PolicyCommandCode()     with   code   set   to
   12800                 TPM_CC_Certify is required.
   12801 
   12802 
   12803 
   12804 
   12805 Family 2.0                                  TCG Published                                          Page 273
   12806 Level 00 Revision 01.16               Copyright  TCG 2006-2014                             October 30, 2014
   12807 Part 3: Commands                                                    Trusted Platform Module Library
   12809 
   12810 
   12811 23.11.2    Command and Response
   12812 
   12813                    Table 129  TPM2_PolicyCommandCode Command
   12814 Type                    Name                   Description
   12815 
   12816                                                TPM_ST_SESSIONS if an audit session is present;
   12817 TPMI_ST_COMMAND_TAG     tag
   12818                                                otherwise, TPM_ST_NO_SESSIONS
   12819 UINT32                  commandSize
   12820 TPM_CC                  commandCode            TPM_CC_PolicyCommandCode
   12821 
   12822                                                handle for the policy session being extended
   12823 TPMI_SH_POLICY          policySession
   12824                                                Auth Index: None
   12825 
   12826 TPM_CC                  code                   the allowed commandCode
   12827 
   12828 
   12829                    Table 130  TPM2_PolicyCommandCode Response
   12830 Type                    Name                   Description
   12831 
   12832 TPM_ST                  tag                    see clause 6
   12833 UINT32                  responseSize
   12834 TPM_RC                  responseCode
   12835 
   12836 
   12837 
   12838 
   12839 Page 274                                TCG Published                                    Family 2.0
   12840 October 30, 2014               Copyright  TCG 2006-2014                  Level 00 Revision 01.16
   12841      Trusted Platform Module Library                                                             Part 3: Commands
   12843 
   12844 
   12845 
   12846      23.11.3    Detailed Actions
   12847 
   12848 1    #include "InternalRoutines.h"
   12849 2    #include "PolicyCommandCode_fp.h"
   12850 3    #ifdef TPM_CC_PolicyCommandCode // Conditional expansion of this file
   12851 
   12852 
   12853      Error Returns                     Meaning
   12854 
   12855      TPM_RC_VALUE                      commandCode of policySession previously set to a different value
   12856 
   12857  4   TPM_RC
   12858  5   TPM2_PolicyCommandCode(
   12859  6       PolicyCommandCode_In      *in                   // IN: input parameter list
   12860  7       )
   12861  8   {
   12862  9       SESSION      *session;
   12863 10       TPM_CC       commandCode = TPM_CC_PolicyCommandCode;
   12864 11       HASH_STATE   hashState;
   12865 12
   12866 13   // Input validation
   12867 14
   12868 15       // Get pointer to the session structure
   12869 16       session = SessionGet(in->policySession);
   12870 17
   12871 18       if(session->commandCode != 0 && session->commandCode != in->code)
   12872 19           return TPM_RC_VALUE + RC_PolicyCommandCode_code;
   12873 20       if(!CommandIsImplemented(in->code))
   12874 21           return TPM_RC_POLICY_CC + RC_PolicyCommandCode_code;
   12875 22
   12876 23   // Internal Data Update
   12877 24       // Update policy hash
   12878 25       // policyDigestnew = hash(policyDigestold || TPM_CC_PolicyCommandCode || code)
   12879 26       // Start hash
   12880 27       CryptStartHash(session->authHashAlg, &hashState);
   12881 28
   12882 29       // add old digest
   12883 30       CryptUpdateDigest2B(&hashState, &session->u2.policyDigest.b);
   12884 31
   12885 32       // add commandCode
   12886 33       CryptUpdateDigestInt(&hashState, sizeof(TPM_CC), &commandCode);
   12887 34
   12888 35       // add input commandCode
   12889 36       CryptUpdateDigestInt(&hashState, sizeof(TPM_CC), &in->code);
   12890 37
   12891 38       // complete the hash and get the results
   12892 39       CryptCompleteHash2B(&hashState, &session->u2.policyDigest.b);
   12893 40
   12894 41       // update commandCode value in session context
   12895 42       session->commandCode = in->code;
   12896 43
   12897 44       return TPM_RC_SUCCESS;
   12898 45   }
   12899 46   #endif // CC_PolicyCommandCode
   12900 
   12901 
   12902 
   12903 
   12904      Family 2.0                                  TCG Published                                          Page 275
   12905      Level 00 Revision 01.16               Copyright  TCG 2006-2014                             October 30, 2014
   12906 Part 3: Commands                                                        Trusted Platform Module Library
   12908 
   12909 
   12910 23.12 TPM2_PolicyPhysicalPresence
   12911 
   12912 23.12.1     General Description
   12913 
   12914 This command indicates that physical presence will need to be asserted at the time the authorization is
   12915 performed.
   12916 If this command is successful, policySessionisPPRequired will be SET to indicate that this check is
   12917 required when the policy is used for authorization. Additionally, policySessionpolicyDigest is extended
   12918 with
   12919             policyDigestnew  HpolicyAlg(policyDigestold || TPM_CC_PolicyPhysicalPresence)          (27)
   12920 
   12921 
   12922 
   12923 
   12924 Page 276                                   TCG Published                                   Family 2.0
   12925 October 30, 2014                    Copyright  TCG 2006-2014                 Level 00 Revision 01.16
   12926 Trusted Platform Module Library                                                         Part 3: Commands
   12928 
   12929 
   12930 
   12931 23.12.2    Command and Response
   12932 
   12933                       Table 131  TPM2_PolicyPhysicalPresence Command
   12934 Type                          Name                   Description
   12935 
   12936                                                      TPM_ST_SESSIONS if an audit session is present;
   12937 TPMI_ST_COMMAND_TAG           tag
   12938                                                      otherwise, TPM_ST_NO_SESSIONS
   12939 UINT32                        commandSize
   12940 TPM_CC                        commandCode            TPM_CC_PolicyPhysicalPresence
   12941 
   12942                                                      handle for the policy session being extended
   12943 TPMI_SH_POLICY                policySession
   12944                                                      Auth Index: None
   12945 
   12946 
   12947                       Table 132  TPM2_PolicyPhysicalPresence Response
   12948 Type                          Name                   Description
   12949 
   12950 TPM_ST                        tag                    see clause 6
   12951 UINT32                        responseSize
   12952 TPM_RC                        responseCode
   12953 
   12954 
   12955 
   12956 
   12957 Family 2.0                                  TCG Published                                         Page 277
   12958 Level 00 Revision 01.16             Copyright  TCG 2006-2014                           October 30, 2014
   12959      Part 3: Commands                                                Trusted Platform Module Library
   12961 
   12962 
   12963 
   12964      23.12.3    Detailed Actions
   12965 
   12966  1   #include "InternalRoutines.h"
   12967  2   #include "PolicyPhysicalPresence_fp.h"
   12968  3   #ifdef TPM_CC_PolicyPhysicalPresence // Conditional expansion of this file
   12969  4   TPM_RC
   12970  5   TPM2_PolicyPhysicalPresence(
   12971  6       PolicyPhysicalPresence_In   *in             // IN: input parameter list
   12972  7       )
   12973  8   {
   12974  9       SESSION      *session;
   12975 10       TPM_CC       commandCode = TPM_CC_PolicyPhysicalPresence;
   12976 11       HASH_STATE   hashState;
   12977 12
   12978 13   // Internal Data Update
   12979 14
   12980 15       // Get pointer to the session structure
   12981 16       session = SessionGet(in->policySession);
   12982 17
   12983 18       // Update policy hash
   12984 19       // policyDigestnew = hash(policyDigestold || TPM_CC_PolicyPhysicalPresence)
   12985 20       // Start hash
   12986 21       CryptStartHash(session->authHashAlg, &hashState);
   12987 22
   12988 23       // add old digest
   12989 24       CryptUpdateDigest2B(&hashState, &session->u2.policyDigest.b);
   12990 25
   12991 26       // add commandCode
   12992 27       CryptUpdateDigestInt(&hashState, sizeof(TPM_CC), &commandCode);
   12993 28
   12994 29       // complete the digest
   12995 30       CryptCompleteHash2B(&hashState, &session->u2.policyDigest.b);
   12996 31
   12997 32       // update session attribute
   12998 33       session->attributes.isPPRequired = SET;
   12999 34
   13000 35       return TPM_RC_SUCCESS;
   13001 36   }
   13002 37   #endif // CC_PolicyPhysicalPresence
   13003 
   13004 
   13005 
   13006 
   13007      Page 278                                TCG Published                             Family 2.0
   13008      October 30, 2014                 Copyright  TCG 2006-2014            Level 00 Revision 01.16
   13009 Trusted Platform Module Library                                                      Part 3: Commands
   13011 
   13012 
   13013 23.13 TPM2_PolicyCpHash
   13014 
   13015 23.13.1    General Description
   13016 
   13017 This command is used to allow a policy to be bound to a specific command and command parameters.
   13018 TPM2_PolicySigned(), TPM2_PolicySecret(), and TPM2_PolicyTIcket() are designed to allow an
   13019 authorizing entity to execute an arbitrary command as the cpHashA parameter of those commands is not
   13020 included in policySessionpolicyDigest. TPM2_PolicyCommandCode() allows the policy to be bound to a
   13021 specific Command Code so that only certain entities may authorize specific command codes. This
   13022 command allows the policy to be restricted such that an entity may only authorize a command with a
   13023 specific set of parameters.
   13024 If policySessioncpHash is already set and not the same as cpHashA, then the TPM shall return
   13025 TPM_RC_VALUE. If cpHashA does not have the size of the policySessionpolicyDigest, the TPM shall
   13026 return TPM_RC_SIZE.
   13027 If the cpHashA checks succeed, policySessioncpHash                  is   set   to     cpHashA    and
   13028 policySessionpolicyDigest is updated with
   13029            policyDigestnew  HpolicyAlg(policyDigestold || TPM_CC_PolicyCpHash || cpHashA)       (28)
   13030 
   13031 
   13032 
   13033 
   13034 Family 2.0                              TCG Published                                      Page 279
   13035 Level 00 Revision 01.16            Copyright  TCG 2006-2014                         October 30, 2014
   13036 Part 3: Commands                                                   Trusted Platform Module Library
   13038 
   13039 
   13040 
   13041 23.13.2    Command and Response
   13042 
   13043                       Table 133  TPM2_PolicyCpHash Command
   13044 Type                    Name                   Description
   13045 
   13046                                                TPM_ST_SESSIONS if an audit or decrypt session is
   13047 TPMI_ST_COMMAND_TAG     tag
   13048                                                present; otherwise, TPM_ST_NO_SESSIONS
   13049 UINT32                  commandSize
   13050 TPM_CC                  commandCode            TPM_CC_PolicyCpHash
   13051 
   13052                                                handle for the policy session being extended
   13053 TPMI_SH_POLICY          policySession
   13054                                                Auth Index: None
   13055 
   13056 TPM2B_DIGEST            cpHashA                the cpHash added to the policy
   13057 
   13058 
   13059                       Table 134  TPM2_PolicyCpHash Response
   13060 Type                    Name                   Description
   13061 
   13062 TPM_ST                  tag                    see clause 6
   13063 UINT32                  responseSize
   13064 TPM_RC                  responseCode
   13065 
   13066 
   13067 
   13068 
   13069 Page 280                                TCG Published                                    Family 2.0
   13070 October 30, 2014              Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   13071      Trusted Platform Module Library                                                               Part 3: Commands
   13073 
   13074 
   13075 
   13076      23.13.3    Detailed Actions
   13077 
   13078 1    #include "InternalRoutines.h"
   13079 2    #include "PolicyCpHash_fp.h"
   13080 3    #ifdef TPM_CC_PolicyCpHash // Conditional expansion of this file
   13081 
   13082 
   13083      Error Returns                     Meaning
   13084 
   13085      TPM_RC_CPHASH                     cpHash of policySession has previously been set to a different value
   13086      TPM_RC_SIZE                       cpHashA is not the size of a digest produced by the hash algorithm
   13087                                        associated with policySession
   13088 
   13089  4   TPM_RC
   13090  5   TPM2_PolicyCpHash(
   13091  6       PolicyCpHash_In       *in                   // IN: input parameter list
   13092  7       )
   13093  8   {
   13094  9       SESSION      *session;
   13095 10       TPM_CC       commandCode = TPM_CC_PolicyCpHash;
   13096 11       HASH_STATE   hashState;
   13097 12
   13098 13   // Input Validation
   13099 14
   13100 15       // Get pointer to the session structure
   13101 16       session = SessionGet(in->policySession);
   13102 17
   13103 18       // A new cpHash is given in input parameter, but cpHash in session context
   13104 19       // is not empty, or is not the same as the new cpHash
   13105 20       if(    in->cpHashA.t.size != 0
   13106 21           && session->u1.cpHash.t.size != 0
   13107 22           && !Memory2BEqual(&in->cpHashA.b, &session->u1.cpHash.b)
   13108 23          )
   13109 24           return TPM_RC_CPHASH;
   13110 25
   13111 26       // A valid cpHash must have the same size as session hash digest
   13112 27       if(in->cpHashA.t.size != CryptGetHashDigestSize(session->authHashAlg))
   13113 28           return TPM_RC_SIZE + RC_PolicyCpHash_cpHashA;
   13114 29
   13115 30   // Internal Data Update
   13116 31
   13117 32       // Update policy hash
   13118 33       // policyDigestnew = hash(policyDigestold || TPM_CC_PolicyCpHash || cpHashA)
   13119 34       // Start hash
   13120 35       CryptStartHash(session->authHashAlg, &hashState);
   13121 36
   13122 37       // add old digest
   13123 38       CryptUpdateDigest2B(&hashState, &session->u2.policyDigest.b);
   13124 39
   13125 40       // add commandCode
   13126 41       CryptUpdateDigestInt(&hashState, sizeof(TPM_CC), &commandCode);
   13127 42
   13128 43       // add cpHashA
   13129 44       CryptUpdateDigest2B(&hashState, &in->cpHashA.b);
   13130 45
   13131 46       // complete the digest and get the results
   13132 47       CryptCompleteHash2B(&hashState, &session->u2.policyDigest.b);
   13133 48
   13134 49       // update cpHash in session context
   13135 50       session->u1.cpHash = in->cpHashA;
   13136 51       session->attributes.iscpHashDefined = SET;
   13137 52
   13138 53       return TPM_RC_SUCCESS;
   13139 
   13140      Family 2.0                                  TCG Published                                              Page 281
   13141      Level 00 Revision 01.16               Copyright  TCG 2006-2014                               October 30, 2014
   13142      Part 3: Commands                                        Trusted Platform Module Library
   13144 
   13145 54   }
   13146 55   #endif // CC_PolicyCpHash
   13147 
   13148 
   13149 
   13150 
   13151      Page 282                         TCG Published                            Family 2.0
   13152      October 30, 2014            Copyright  TCG 2006-2014        Level 00 Revision 01.16
   13153 Trusted Platform Module Library                                                            Part 3: Commands
   13155 
   13156 
   13157 23.14 TPM2_PolicyNameHash
   13158 
   13159 23.14.1     General Description
   13160 
   13161 This command allows a policy to be bound to a specific set of TPM entities without being bound to the
   13162 parameters of the command. This is most useful for commands such as TPM2_Duplicate() and for
   13163 TPM2_PCR_Event() when the referenced PCR requires a policy.
   13164 The nameHash parameter should contain the digest of the Names associated with the handles to be used
   13165 in the authorized command.
   13166 
   13167 EXAMPLE         For the TPM2_Duplicate() command, two han dles are provided. One is the handle of the object
   13168                 being duplicated and the other is the handle of the new parent. For that command, nameHash would
   13169                 contain:
   13170                    nameHash  H policyAlg (objectHandleName || newParentHandleName)
   13171 
   13172 If policySessioncpHash is already set, the TPM shall return TPM_RC_VALUE. If the size of nameHash
   13173 is not the size of policySessionpolicyDigest, the TPM shall return TPM_RC_SIZE. Otherwise,
   13174 policySessioncpHash is set to nameHash.
   13175 If this command completes successfully, the cpHash of the authorized command will not be used for
   13176 validation. Only the digest of the Names associated with the handles in the command will be used.
   13177 
   13178 NOTE 1          This allows the space normally       used   to   hold   policySessioncpHash   to   be    used    for
   13179                 policySessionnameHash instead.
   13180 
   13181 The policySessionpolicyDigest will be updated with
   13182           policyDigestnew  HpolicyAlg(policyDigestold || TPM_CC_PolicyNameHash || nameHash)                     (29)
   13183 
   13184 NOTE 2          This command will often be used with TPM2_PolicyAuthorize() where the owner of the object being
   13185                 duplicated provides approval for their object to be migrated to a specific new parent.
   13186 
   13187 
   13188 
   13189 
   13190 Family 2.0                                 TCG Published                                               Page 283
   13191 Level 00 Revision 01.16               Copyright  TCG 2006-2014                            October 30, 2014
   13192 Part 3: Commands                                                     Trusted Platform Module Library
   13194 
   13195 
   13196 23.14.2    Command and Response
   13197 
   13198                       Table 135  TPM2_PolicyNameHash Command
   13199 Type                     Name                   Description
   13200 
   13201                                                 TPM_ST_SESSIONS if an audit or decrypt session is
   13202 TPMI_ST_COMMAND_TAG      tag
   13203                                                 present; otherwise, TPM_ST_NO_SESSIONS
   13204 UINT32                   commandSize
   13205 TPM_CC                   commandCode            TPM_CC_PolicyNameHash
   13206 
   13207                                                 handle for the policy session being extended
   13208 TPMI_SH_POLICY           policySession
   13209                                                 Auth Index: None
   13210 
   13211 TPM2B_DIGEST             nameHash               the digest to be added to the policy
   13212 
   13213 
   13214                       Table 136  TPM2_PolicyNameHash Response
   13215 Type                     Name                   Description
   13216 
   13217 TPM_ST                   tag                    see clause 6
   13218 UINT32                   responseSize
   13219 TPM_RC                   responseCode
   13220 
   13221 
   13222 
   13223 
   13224 Page 284                                 TCG Published                                    Family 2.0
   13225 October 30, 2014               Copyright  TCG 2006-2014                    Level 00 Revision 01.16
   13226      Trusted Platform Module Library                                                             Part 3: Commands
   13228 
   13229 
   13230 
   13231      23.14.3    Detailed Actions
   13232 
   13233 1    #include "InternalRoutines.h"
   13234 2    #include "PolicyNameHash_fp.h"
   13235 3    #ifdef TPM_CC_PolicyNameHash // Conditional expansion of this file
   13236 
   13237 
   13238      Error Returns                     Meaning
   13239 
   13240      TPM_RC_CPHASH                     nameHash has been previously set to a different value
   13241      TPM_RC_SIZE                       nameHash is not the size of the digest produced by the hash
   13242                                        algorithm associated with policySession
   13243 
   13244  4   TPM_RC
   13245  5   TPM2_PolicyNameHash(
   13246  6       PolicyNameHash_In     *in                  // IN: input parameter list
   13247  7       )
   13248  8   {
   13249  9       SESSION               *session;
   13250 10       TPM_CC                 commandCode = TPM_CC_PolicyNameHash;
   13251 11       HASH_STATE             hashState;
   13252 12
   13253 13   // Input Validation
   13254 14
   13255 15       // Get pointer to the session structure
   13256 16       session = SessionGet(in->policySession);
   13257 17
   13258 18       // A new nameHash is given in input parameter, but cpHash in session context
   13259 19       // is not empty
   13260 20       if(in->nameHash.t.size != 0 && session->u1.cpHash.t.size != 0)
   13261 21           return TPM_RC_CPHASH;
   13262 22
   13263 23       // A valid nameHash must have the same size as session hash digest
   13264 24       if(in->nameHash.t.size != CryptGetHashDigestSize(session->authHashAlg))
   13265 25           return TPM_RC_SIZE + RC_PolicyNameHash_nameHash;
   13266 26
   13267 27   // Internal Data Update
   13268 28
   13269 29       // Update policy hash
   13270 30       // policyDigestnew = hash(policyDigestold || TPM_CC_PolicyNameHash || nameHash)
   13271 31       // Start hash
   13272 32       CryptStartHash(session->authHashAlg, &hashState);
   13273 33
   13274 34       // add old digest
   13275 35       CryptUpdateDigest2B(&hashState, &session->u2.policyDigest.b);
   13276 36
   13277 37       // add commandCode
   13278 38       CryptUpdateDigestInt(&hashState, sizeof(TPM_CC), &commandCode);
   13279 39
   13280 40       // add nameHash
   13281 41       CryptUpdateDigest2B(&hashState, &in->nameHash.b);
   13282 42
   13283 43       // complete the digest
   13284 44       CryptCompleteHash2B(&hashState, &session->u2.policyDigest.b);
   13285 45
   13286 46       // clear iscpHashDefined bit to indicate now this field contains a nameHash
   13287 47       session->attributes.iscpHashDefined = CLEAR;
   13288 48
   13289 49       // update nameHash in session context
   13290 50       session->u1.cpHash = in->nameHash;
   13291 51
   13292 52       return TPM_RC_SUCCESS;
   13293 53   }
   13294 
   13295      Family 2.0                                  TCG Published                                        Page 285
   13296      Level 00 Revision 01.16               Copyright  TCG 2006-2014                             October 30, 2014
   13297      Part 3: Commands                                          Trusted Platform Module Library
   13299 
   13300 54   #endif // CC_PolicyNameHash
   13301 
   13302 
   13303 
   13304 
   13305      Page 286                           TCG Published                            Family 2.0
   13306      October 30, 2014              Copyright  TCG 2006-2014        Level 00 Revision 01.16
   13307 Trusted Platform Module Library                                                                    Part 3: Commands
   13309 
   13310 
   13311 23.15 TPM2_PolicyDuplicationSelect
   13312 
   13313 23.15.1       General Description
   13314 
   13315 This command allows qualification of duplication to allow duplication to a selected new parent.
   13316 If this command not used in conjunction with TPM2_PolicyAuthorize(), then only the new parent is
   13317 selected.
   13318 
   13319 EXAMPLE           When an object is created when the list of allowed duplication targets is known, the policy would be
   13320                   created with includeObject CLEAR.
   13321 
   13322 NOTE 1            Only the new parent may be selected because, without TPM2_PolicyAuthorize(), the Name of the
   13323                   Object to be duplicated would need to be known at the time that Object's policy is created. However,
   13324                   since the Name of the Object includes its policy, the Name is not known.
   13325 
   13326 If used in conjunction with TPM2_PolicyAuthorize(), then the authorizer of the new policy has the option
   13327 of selecting just the new parent or of selecting both the new parent and the duplication Object..
   13328 
   13329 NOTE 2            If the authorizing entity for an TPM2_PolicyAuthorize() only specifies the new parent, t hen that
   13330                   authorization may be applied to the duplication of any number of other Objects. If the authorizing
   13331                   entity specifies both a new parent and the duplicated Object, then the authorization only applies to
   13332                   that pairing of Object and new parent.
   13333 
   13334 If either policySessioncpHash or policySessionnameHash has been previously set, the TPM shall
   13335 return TPM_RC_CPHASH. Otherwise, policySessionnameHash will be set to:
   13336                            nameHash  HpolicyAlg(objectName || newParentName)                                       (30)
   13337 
   13338 NOTE 3            It is allowed that policySesionnameHash and policySessioncpHash share the same memory
   13339                   space.
   13340 
   13341 The policySessionpolicyDigest will be updated according to the setting of includeObject. If equal to
   13342 YES, policySessionpolicyDigest is updated by:
   13343           policyDigestnew  HpolicyAlg(policyDigestold || TPM_CC_PolicyDuplicationSelect ||
   13344                                   objectName || newParentName || includeObject)                                     (31)
   13345 If includeObject is NO, policySessionpolicyDigest is updated by:
   13346           policyDigestnew  HpolicyAlg(policyDigestold || TPM_CC_PolicyDuplicationSelect ||
   13347                                   newParentName || includeObject)                                                   (32)
   13348 
   13349 NOTE 4            policySessioncpHash receives the digest of both Names so that the check performed in
   13350                   TPM2_Duplicate() may be the same regardless of which Names are included in
   13351                   policySessionpolicyDigest. This means that, when TPM2_PolicyDuplicationSelect() is executed, it
   13352                   is only valid for a specific pair of duplication object and new parent.
   13353 
   13354 If the command succeeds, policySessioncommandCode is set to TPM_CC_Duplicate.
   13355 
   13356 NOTE 5            The normal use of this command is before a TPM2_PolicyAuthorize(). An authorized entity would
   13357                   approve a policyDigest that allowed duplication to a specific new parent. The authorizing entity may
   13358                   want to limit the authorization so that the approval allows on ly a specific object to be duplicated to
   13359                   the new parent. In that case, the authorizing entity would approve the policyDigest of equation (31).
   13360 
   13361 
   13362 
   13363 
   13364 Family 2.0                                      TCG Published                                              Page 287
   13365 Level 00 Revision 01.16                  Copyright  TCG 2006-2014                                 October 30, 2014
   13366 Part 3: Commands                                                     Trusted Platform Module Library
   13368 
   13369 
   13370 23.15.2    Command and Response
   13371 
   13372                    Table 137  TPM2_PolicyDuplicationSelect Command
   13373 Type                     Name                   Description
   13374 
   13375                                                 TPM_ST_SESSIONS if an audit or decrypt session is
   13376 TPMI_ST_COMMAND_TAG      tag
   13377                                                 present; otherwise, TPM_ST_NO_SESSIONS
   13378 UINT32                   commandSize
   13379 TPM_CC                   commandCode            TPM_CC_PolicyDuplicationSelect
   13380 
   13381                                                 handle for the policy session being extended
   13382 TPMI_SH_POLICY           policySession
   13383                                                 Auth Index: None
   13384 
   13385 TPM2B_NAME               objectName             the Name of the object to be duplicated
   13386 TPM2B_NAME               newParentName          the Name of the new parent
   13387                                                 if YES, the objectName will be included in the value in
   13388 TPMI_YES_NO              includeObject
   13389                                                 policySessionpolicyDigest
   13390 
   13391 
   13392                    Table 138  TPM2_PolicyDuplicationSelect Response
   13393 Type                     Name                   Description
   13394 
   13395 TPM_ST                   tag                    see clause 6
   13396 UINT32                   responseSize
   13397 TPM_RC                   responseCode
   13398 
   13399 
   13400 
   13401 
   13402 Page 288                                 TCG Published                                     Family 2.0
   13403 October 30, 2014               Copyright  TCG 2006-2014                     Level 00 Revision 01.16
   13404      Trusted Platform Module Library                                                        Part 3: Commands
   13406 
   13407 
   13408 
   13409      23.15.3    Detailed Actions
   13410 
   13411 1    #include "InternalRoutines.h"
   13412 2    #include "PolicyDuplicationSelect_fp.h"
   13413 3    #ifdef TPM_CC_PolicyDuplicationSelect // Conditional expansion of this file
   13414 
   13415 
   13416      Error Returns                     Meaning
   13417 
   13418      TPM_RC_COMMAND_CODE               commandCode of 'policySession; is not empty
   13419      TPM_RC_CPHASH                     cpHash of policySession is not empty
   13420 
   13421  4   TPM_RC
   13422  5   TPM2_PolicyDuplicationSelect(
   13423  6       PolicyDuplicationSelect_In       *in                 // IN: input parameter list
   13424  7       )
   13425  8   {
   13426  9       SESSION           *session;
   13427 10       HASH_STATE        hashState;
   13428 11       TPM_CC            commandCode = TPM_CC_PolicyDuplicationSelect;
   13429 12
   13430 13   // Input Validation
   13431 14
   13432 15       // Get pointer to the session structure
   13433 16       session = SessionGet(in->policySession);
   13434 17
   13435 18       // cpHash in session context must be empty
   13436 19       if(session->u1.cpHash.t.size != 0)
   13437 20           return TPM_RC_CPHASH;
   13438 21
   13439 22       // commandCode in session context must be empty
   13440 23       if(session->commandCode != 0)
   13441 24           return TPM_RC_COMMAND_CODE;
   13442 25
   13443 26   // Internal Data Update
   13444 27
   13445 28       // Update name hash
   13446 29       session->u1.cpHash.t.size = CryptStartHash(session->authHashAlg, &hashState);
   13447 30
   13448 31       // add objectName
   13449 32       CryptUpdateDigest2B(&hashState, &in->objectName.b);
   13450 33
   13451 34       // add new parent name
   13452 35       CryptUpdateDigest2B(&hashState, &in->newParentName.b);
   13453 36
   13454 37       // complete hash
   13455 38       CryptCompleteHash2B(&hashState, &session->u1.cpHash.b);
   13456 39
   13457 40       // update policy hash
   13458 41       // Old policyDigest size should be the same as the new policyDigest size since
   13459 42       // they are using the same hash algorithm
   13460 43       session->u2.policyDigest.t.size
   13461 44               = CryptStartHash(session->authHashAlg, &hashState);
   13462 45
   13463 46       // add old policy
   13464 47       CryptUpdateDigest2B(&hashState, &session->u2.policyDigest.b);
   13465 48
   13466 49       // add command code
   13467 50       CryptUpdateDigestInt(&hashState, sizeof(TPM_CC), &commandCode);
   13468 51
   13469 52       // add objectName
   13470 53       if(in->includeObject == YES)
   13471 54           CryptUpdateDigest2B(&hashState, &in->objectName.b);
   13472 
   13473      Family 2.0                                  TCG Published                                   Page 289
   13474      Level 00 Revision 01.16               Copyright  TCG 2006-2014                        October 30, 2014
   13475      Part 3: Commands                                               Trusted Platform Module Library
   13477 
   13478 55
   13479 56      // add new parent name
   13480 57      CryptUpdateDigest2B(&hashState, &in->newParentName.b);
   13481 58
   13482 59      // add includeObject
   13483 60      CryptUpdateDigestInt(&hashState, sizeof(TPMI_YES_NO), &in->includeObject);
   13484 61
   13485 62      // complete digest
   13486 63      CryptCompleteHash2B(&hashState, &session->u2.policyDigest.b);
   13487 64
   13488 65      // clear iscpHashDefined bit to indicate now this field contains a nameHash
   13489 66      session->attributes.iscpHashDefined = CLEAR;
   13490 67
   13491 68      // set commandCode in session context
   13492 69      session->commandCode = TPM_CC_Duplicate;
   13493 70
   13494 71       return TPM_RC_SUCCESS;
   13495 72   }
   13496 73   #endif // CC_PolicyDuplicationSelect
   13497 
   13498 
   13499 
   13500 
   13501      Page 290                               TCG Published                             Family 2.0
   13502      October 30, 2014                Copyright  TCG 2006-2014            Level 00 Revision 01.16
   13503 Trusted Platform Module Library                                                                  Part 3: Commands
   13505 
   13506 
   13507 23.16 TPM2_PolicyAuthorize
   13508 
   13509 23.16.1     General Description
   13510 
   13511 This command allows policies to change. If a policy were static, then it would be difficult to add users to a
   13512 policy. This command lets a policy authority sign a new policy so that it may be used in an existing policy.
   13513 The authorizing entity signs a structure that contains
   13514                               aHash  HaHashAlg(approvedPolicy || policyRef)                                      (33)
   13515 The aHashAlg is required to be the nameAlg of the key used to sign the aHash. The aHash value is then
   13516 signed (symmetric or asymmetric) by keySign. That signature is then checked by the TPM in
   13517 TPM2_VerifySignature() which produces a ticket by
   13518                     HMAC(proof, (TPM_ST_VERIFIED || aHash || keySignName))                                       (34)
   13519 
   13520 NOTE 1          The reason for the validation is because of the expectation that the policy will be used multiple times
   13521                 and it is more efficient to check a ticket than to load an object each time to check a signature.
   13522 
   13523 The ticket is then used in TPM2_PolicyAuthorize() to validate the parameters.
   13524 The keySign parameter is required to be a valid object name using nameAlg other than TPM_ALG_NULL.
   13525 If the first two octets of keySign are not a valid hash algorithm, the TPM shall return TPM_RC_HASH. If
   13526 the remainder of the Name is not the size of the indicated digest, the TPM shall return TPM_RC_SIZE.
   13527 The TPM validates that the approvedPolicy matches the current value of policySessionpolicyDigest and
   13528 if not, shall return TPM_RC_VALUE.
   13529 The TPM then validates that the parameters to TPM2_PolicyAuthorize() match the values used to
   13530 generate the ticket. If so, the TPM will reset policySessionpolicyDigest to a Zero Digest. Then it will
   13531 update policySessionpolicyDigest with PolicyUpdate() (see 23.2.3).
   13532                       PolicyUpdate(TPM_CC_PolicyAuthorize, keySign, policyRef)                                    (35)
   13533 If the ticket is not valid, the TPM shall return TPM_RC_POLICY.
   13534 If policySession is a trial session, policySessionpolicyDigest is extended as if the ticket is valid without
   13535 actual verification.
   13536 
   13537 NOTE 2          The unmarshaling process requires that a proper TPMT_TK_VERIFIED be provided for checkTicket
   13538                 but it may be a NULL Ticket. A NULL ticket is useful in a trial policy, where the caller uses the TPM
   13539                 to perform policy calculations but does not have a valid authorization ticket.
   13540 
   13541 
   13542 
   13543 
   13544 Family 2.0                                    TCG Published                                              Page 291
   13545 Level 00 Revision 01.16                Copyright  TCG 2006-2014                                 October 30, 2014
   13546 Part 3: Commands                                                    Trusted Platform Module Library
   13548 
   13549 
   13550 23.16.2    Command and Response
   13551 
   13552                       Table 139  TPM2_PolicyAuthorize Command
   13553 Type                    Name                   Description
   13554 
   13555                                                TPM_ST_SESSIONS if an audit or decrypt session is
   13556 TPMI_ST_COMMAND_TAG     tag
   13557                                                present; otherwise, TPM_ST_NO_SESSIONS
   13558 UINT32                  commandSize
   13559 TPM_CC                  commandCode            TPM_CC_PolicyAuthorize
   13560 
   13561                                                handle for the policy session being extended
   13562 TPMI_SH_POLICY          policySession
   13563                                                Auth Index: None
   13564 
   13565 TPM2B_DIGEST            approvedPolicy         digest of the policy being approved
   13566 TPM2B_NONCE             policyRef              a policy qualifier
   13567 TPM2B_NAME              keySign                Name of a key that can sign a policy addition
   13568                                                ticket validating that approvedPolicy and policyRef were
   13569 TPMT_TK_VERIFIED        checkTicket
   13570                                                signed by keySign
   13571 
   13572 
   13573                       Table 140  TPM2_PolicyAuthorize Response
   13574 Type                    Name                   Description
   13575 
   13576 TPM_ST                  tag                    see clause 6
   13577 UINT32                  responseSize
   13578 TPM_RC                  responseCode
   13579 
   13580 
   13581 
   13582 
   13583 Page 292                                TCG Published                                    Family 2.0
   13584 October 30, 2014              Copyright  TCG 2006-2014                    Level 00 Revision 01.16
   13585      Trusted Platform Module Library                                                             Part 3: Commands
   13587 
   13588 
   13589 
   13590      23.16.3     Detailed Actions
   13591 
   13592 1    #include "InternalRoutines.h"
   13593 2    #include "PolicyAuthorize_fp.h"
   13594 3    #ifdef TPM_CC_PolicyAuthorize // Conditional expansion of this file
   13595 4    #include "Policy_spt_fp.h"
   13596 
   13597 
   13598      Error Returns                     Meaning
   13599 
   13600      TPM_RC_HASH                       hash algorithm in keyName is not supported
   13601      TPM_RC_SIZE                       keyName is not the correct size for its hash algorithm
   13602      TPM_RC_VALUE                      the current policyDigest of policySession does not match
   13603                                        approvedPolicy; or checkTicket doesn't match the provided values
   13604 
   13605  5   TPM_RC
   13606  6   TPM2_PolicyAuthorize(
   13607  7       PolicyAuthorize_In    *in                   // IN: input parameter list
   13608  8       )
   13609  9   {
   13610 10       SESSION                     *session;
   13611 11       TPM2B_DIGEST                 authHash;
   13612 12       HASH_STATE                   hashState;
   13613 13       TPMT_TK_VERIFIED             ticket;
   13614 14       TPM_ALG_ID                   hashAlg;
   13615 15       UINT16                       digestSize;
   13616 16
   13617 17   // Input Validation
   13618 18
   13619 19       // Get pointer to the session structure
   13620 20       session = SessionGet(in->policySession);
   13621 21
   13622 22       // Extract from the Name of the key, the algorithm used to compute it's Name
   13623 23       hashAlg = BYTE_ARRAY_TO_UINT16(in->keySign.t.name);
   13624 24
   13625 25       // 'keySign' parameter needs to use a supported hash algorithm, otherwise
   13626 26       // can't tell how large the digest should be
   13627 27       digestSize = CryptGetHashDigestSize(hashAlg);
   13628 28       if(digestSize == 0)
   13629 29           return TPM_RC_HASH + RC_PolicyAuthorize_keySign;
   13630 30
   13631 31       if(digestSize != (in->keySign.t.size - 2))
   13632 32           return TPM_RC_SIZE + RC_PolicyAuthorize_keySign;
   13633 33
   13634 34       //If this is a trial policy, skip all validations
   13635 35       if(session->attributes.isTrialPolicy == CLEAR)
   13636 36       {
   13637 37           // Check that "approvedPolicy" matches the current value of the
   13638 38           // policyDigest in policy session
   13639 39           if(!Memory2BEqual(&session->u2.policyDigest.b,
   13640 40                             &in->approvedPolicy.b))
   13641 41               return TPM_RC_VALUE + RC_PolicyAuthorize_approvedPolicy;
   13642 42
   13643 43             // Validate ticket TPMT_TK_VERIFIED
   13644 44             // Compute aHash. The authorizing object sign a digest
   13645 45             // aHash := hash(approvedPolicy || policyRef).
   13646 46             // Start hash
   13647 47             authHash.t.size = CryptStartHash(hashAlg, &hashState);
   13648 48
   13649 49             // add approvedPolicy
   13650 50             CryptUpdateDigest2B(&hashState, &in->approvedPolicy.b);
   13651 51
   13652 
   13653      Family 2.0                                   TCG Published                                         Page 293
   13654      Level 00 Revision 01.16               Copyright  TCG 2006-2014                             October 30, 2014
   13655      Part 3: Commands                                               Trusted Platform Module Library
   13657 
   13658 52          // add policyRef
   13659 53          CryptUpdateDigest2B(&hashState, &in->policyRef.b);
   13660 54
   13661 55          // complete hash
   13662 56          CryptCompleteHash2B(&hashState, &authHash.b);
   13663 57
   13664 58          // re-compute TPMT_TK_VERIFIED
   13665 59          TicketComputeVerified(in->checkTicket.hierarchy, &authHash,
   13666 60                                &in->keySign, &ticket);
   13667 61
   13668 62          // Compare ticket digest. If not match, return error
   13669 63          if(!Memory2BEqual(&in->checkTicket.digest.b, &ticket.digest.b))
   13670 64              return TPM_RC_VALUE+ RC_PolicyAuthorize_checkTicket;
   13671 65      }
   13672 66
   13673 67   // Internal Data Update
   13674 68
   13675 69      // Set policyDigest to zero digest
   13676 70      MemorySet(session->u2.policyDigest.t.buffer, 0,
   13677 71                session->u2.policyDigest.t.size);
   13678 72
   13679 73      // Update policyDigest
   13680 74      PolicyContextUpdate(TPM_CC_PolicyAuthorize, &in->keySign, &in->policyRef,
   13681 75                          NULL, 0, session);
   13682 76
   13683 77      return TPM_RC_SUCCESS;
   13684 78
   13685 79   }
   13686 80   #endif // CC_PolicyAuthorize
   13687 
   13688 
   13689 
   13690 
   13691      Page 294                              TCG Published                              Family 2.0
   13692      October 30, 2014               Copyright  TCG 2006-2014             Level 00 Revision 01.16
   13693 Trusted Platform Module Library                                                          Part 3: Commands
   13695 
   13696 
   13697 23.17 TPM2_PolicyAuthValue
   13698 
   13699 23.17.1     General Description
   13700 
   13701 This command allows a policy to be bound to the authorization value of the authorized object.
   13702 When this command completes successfully, policySessionisAuthValueNeeded is SET to indicate that
   13703 the authValue will be included in hmacKey when the authorization HMAC is computed for the command
   13704 being authorized using this session. Additionally, policySessionisPasswordNeeded will be CLEAR.
   13705 
   13706 NOTE            If a policy does not use this command, then the hmacKey for the authorized command would only
   13707                 use sessionKey. If sessionKey is not present, then the hmacKey is an Empty Buffer and no HMAC
   13708                 would be computed.
   13709 
   13710 If successful, policySessionpolicyDigest will be updated with
   13711                 policyDigestnew  HpolicyAlg(policyDigestold || TPM_CC_PolicyAuthValue)                 (36)
   13712 
   13713 
   13714 
   13715 
   13716 Family 2.0                                 TCG Published                                        Page 295
   13717 Level 00 Revision 01.16              Copyright  TCG 2006-2014                           October 30, 2014
   13718 Part 3: Commands                                                     Trusted Platform Module Library
   13720 
   13721 
   13722 
   13723 23.17.2    Command and Response
   13724 
   13725                       Table 141  TPM2_PolicyAuthValue Command
   13726 Type                     Name                   Description
   13727 
   13728                                                 TPM_ST_SESSIONS if an audit session is present;
   13729 TPMI_ST_COMMAND_TAG      tag
   13730                                                 otherwise, TPM_ST_NO_SESSIONS
   13731 UINT32                   commandSize
   13732 TPM_CC                   commandCode            TPM_CC_PolicyAuthValue
   13733 
   13734                                                 handle for the policy session being extended
   13735 TPMI_SH_POLICY           policySession
   13736                                                 Auth Index: None
   13737 
   13738 
   13739                       Table 142  TPM2_PolicyAuthValue Response
   13740 Type                     Name                   Description
   13741 
   13742 TPM_ST                   tag                    see clause 6
   13743 UINT32                   responseSize
   13744 TPM_RC                   responseCode
   13745 
   13746 
   13747 
   13748 
   13749 Page 296                                 TCG Published                                    Family 2.0
   13750 October 30, 2014               Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   13751      Trusted Platform Module Library                                            Part 3: Commands
   13753 
   13754 
   13755 
   13756      23.17.3    Detailed Actions
   13757 
   13758  1   #include "InternalRoutines.h"
   13759  2   #include "PolicyAuthValue_fp.h"
   13760  3   #ifdef TPM_CC_PolicyAuthValue // Conditional expansion of this file
   13761  4   #include "Policy_spt_fp.h"
   13762  5   TPM_RC
   13763  6   TPM2_PolicyAuthValue(
   13764  7       PolicyAuthValue_In    *in            // IN: input parameter list
   13765  8       )
   13766  9   {
   13767 10       SESSION               *session;
   13768 11       TPM_CC                 commandCode = TPM_CC_PolicyAuthValue;
   13769 12       HASH_STATE             hashState;
   13770 13
   13771 14   // Internal Data Update
   13772 15
   13773 16       // Get pointer to the session structure
   13774 17       session = SessionGet(in->policySession);
   13775 18
   13776 19       // Update policy hash
   13777 20       // policyDigestnew = hash(policyDigestold || TPM_CC_PolicyAuthValue)
   13778 21       //   Start hash
   13779 22       CryptStartHash(session->authHashAlg, &hashState);
   13780 23
   13781 24       // add old digest
   13782 25       CryptUpdateDigest2B(&hashState, &session->u2.policyDigest.b);
   13783 26
   13784 27       // add commandCode
   13785 28       CryptUpdateDigestInt(&hashState, sizeof(TPM_CC), &commandCode);
   13786 29
   13787 30       // complete the hash and get the results
   13788 31       CryptCompleteHash2B(&hashState, &session->u2.policyDigest.b);
   13789 32
   13790 33       // update isAuthValueNeeded bit in the session context
   13791 34       session->attributes.isAuthValueNeeded = SET;
   13792 35       session->attributes.isPasswordNeeded = CLEAR;
   13793 36
   13794 37       return TPM_RC_SUCCESS;
   13795 38   }
   13796 39   #endif // CC_PolicyAuthValue
   13797 
   13798 
   13799 
   13800 
   13801      Family 2.0                             TCG Published                            Page 297
   13802      Level 00 Revision 01.16           Copyright  TCG 2006-2014                October 30, 2014
   13803 Part 3: Commands                                                                 Trusted Platform Module Library
   13805 
   13806 
   13807 23.18 TPM2_PolicyPassword
   13808 
   13809 23.18.1     General Description
   13810 
   13811 This command allows a policy to be bound to the authorization value of the authorized object.
   13812 When this command completes successfully, policySessionisPasswordNeeded is SET to indicate that
   13813 authValue of the authorized object will be checked when the session is used for authorization. The caller
   13814 will provide the authValue in clear text in the hmac parameter of the authorization. The comparison of
   13815 hmac to authValue is performed as if the authorization is a password.
   13816 
   13817 NOTE 1          The parameter field in the policy session where the authorization value is provided is called hmac. If
   13818                 TPM2_PolicyPassword() is part of the sequence, then the field will c ontain a password and not an
   13819                 HMAC.
   13820 
   13821 If successful, policySessionpolicyDigest will be updated with
   13822                 policyDigestnew  HpolicyAlg(policyDigestold || TPM_CC_PolicyAuthValue)                          (37)
   13823 
   13824 NOTE 2          This is the same extend value as used with TPM2_PolicyAuthValue so that the evaluation may be
   13825                 done using either an HMAC or a password with no change to the authPolicy of the object. The
   13826                 reason that two commands are present is to indicate to the TPM if the hmac field in the authorization
   13827                 will contain an HMAC or a password value.
   13828 
   13829 When this command is successful, policySessionisAuthValueNeeded will be CLEAR.
   13830 
   13831 
   13832 
   13833 
   13834 Page 298                                       TCG Published                                           Family 2.0
   13835 October 30, 2014                       Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   13836 Trusted Platform Module Library                                                         Part 3: Commands
   13838 
   13839 
   13840 
   13841 23.18.2    Command and Response
   13842 
   13843                           Table 143  TPM2_PolicyPassword Command
   13844 Type                          Name                   Description
   13845 
   13846                                                      TPM_ST_SESSIONS if an audit session is present;
   13847 TPMI_ST_COMMAND_TAG           tag
   13848                                                      otherwise, TPM_ST_NO_SESSIONS
   13849 UINT32                        commandSize
   13850 TPM_CC                        commandCode            TPM_CC_PolicyPassword
   13851 
   13852                                                      handle for the policy session being extended
   13853 TPMI_SH_POLICY                policySession
   13854                                                      Auth Index: None
   13855 
   13856 
   13857                           Table 144  TPM2_PolicyPassword Response
   13858 Type                          Name                   Description
   13859 
   13860 TPM_ST                        tag                    see clause 6
   13861 UINT32                        responseSize
   13862 TPM_RC                        responseCode
   13863 
   13864 
   13865 
   13866 
   13867 Family 2.0                                  TCG Published                                         Page 299
   13868 Level 00 Revision 01.16             Copyright  TCG 2006-2014                           October 30, 2014
   13869      Part 3: Commands                                                   Trusted Platform Module Library
   13871 
   13872 
   13873 
   13874      23.18.3    Detailed Actions
   13875 
   13876  1   #include "InternalRoutines.h"
   13877  2   #include "PolicyPassword_fp.h"
   13878  3   #ifdef TPM_CC_PolicyPassword // Conditional expansion of this file
   13879  4   #include "Policy_spt_fp.h"
   13880  5   TPM_RC
   13881  6   TPM2_PolicyPassword(
   13882  7       PolicyPassword_In     *in            // IN: input parameter list
   13883  8       )
   13884  9   {
   13885 10       SESSION               *session;
   13886 11       TPM_CC                 commandCode = TPM_CC_PolicyAuthValue;
   13887 12       HASH_STATE             hashState;
   13888 13
   13889 14   // Internal Data Update
   13890 15
   13891 16       // Get pointer to the session structure
   13892 17       session = SessionGet(in->policySession);
   13893 18
   13894 19       // Update policy hash
   13895 20       // policyDigestnew = hash(policyDigestold || TPM_CC_PolicyAuthValue)
   13896 21       // Start hash
   13897 22       CryptStartHash(session->authHashAlg, &hashState);
   13898 23
   13899 24       // add old digest
   13900 25       CryptUpdateDigest2B(&hashState, &session->u2.policyDigest.b);
   13901 26
   13902 27       // add commandCode
   13903 28       CryptUpdateDigestInt(&hashState, sizeof(TPM_CC), &commandCode);
   13904 29
   13905 30       // complete the digest
   13906 31       CryptCompleteHash2B(&hashState, &session->u2.policyDigest.b);
   13907 32
   13908 33       // Update isPasswordNeeded bit
   13909 34       session->attributes.isPasswordNeeded = SET;
   13910 35       session->attributes.isAuthValueNeeded = CLEAR;
   13911 36
   13912 37       return TPM_RC_SUCCESS;
   13913 38   }
   13914 39   #endif // CC_PolicyPassword
   13915 
   13916 
   13917 
   13918 
   13919      Page 300                                 TCG Published                               Family 2.0
   13920      October 30, 2014                  Copyright  TCG 2006-2014             Level 00 Revision 01.16
   13921 Trusted Platform Module Library                                                   Part 3: Commands
   13923 
   13924 
   13925 23.19 TPM2_PolicyGetDigest
   13926 
   13927 23.19.1    General Description
   13928 
   13929 This command returns the current policyDigest of the session. This command allows the TPM to be used
   13930 to perform the actions required to pre-compute the authPolicy for an object.
   13931 
   13932 
   13933 
   13934 
   13935 Family 2.0                             TCG Published                                    Page 301
   13936 Level 00 Revision 01.16           Copyright  TCG 2006-2014                       October 30, 2014
   13937 Part 3: Commands                                                    Trusted Platform Module Library
   13939 
   13940 
   13941 
   13942 23.19.2    Command and Response
   13943 
   13944                       Table 145  TPM2_PolicyGetDigest Command
   13945 Type                    Name                   Description
   13946 
   13947                                                TPM_ST_SESSIONS if an audit or encrypt session is
   13948 TPMI_ST_COMMAND_TAG     tag
   13949                                                present; otherwise, TPM_ST_NO_SESSIONS
   13950 UINT32                  commandSize
   13951 TPM_CC                  commandCode            TPM_CC_PolicyGetDigest
   13952 
   13953                                                handle for the policy session
   13954 TPMI_SH_POLICY          policySession
   13955                                                Auth Index: None
   13956 
   13957 
   13958                       Table 146  TPM2_PolicyGetDigest Response
   13959 Type                    Name                   Description
   13960 
   13961 TPM_ST                  tag                    see clause 6
   13962 UINT32                  responseSize
   13963 TPM_RC                  responseCode
   13964 
   13965 TPM2B_DIGEST            policyDigest           the current value of the policySessionpolicyDigest
   13966 
   13967 
   13968 
   13969 
   13970 Page 302                                TCG Published                                   Family 2.0
   13971 October 30, 2014              Copyright  TCG 2006-2014                    Level 00 Revision 01.16
   13972      Trusted Platform Module Library                                                Part 3: Commands
   13974 
   13975 
   13976 
   13977      23.19.3    Detailed Actions
   13978 
   13979  1   #include "InternalRoutines.h"
   13980  2   #include "PolicyGetDigest_fp.h"
   13981  3   #ifdef TPM_CC_PolicyGetDigest // Conditional expansion of this file
   13982  4   TPM_RC
   13983  5   TPM2_PolicyGetDigest(
   13984  6       PolicyGetDigest_In        *in,             // IN: input parameter list
   13985  7       PolicyGetDigest_Out       *out             // OUT: output parameter list
   13986  8       )
   13987  9   {
   13988 10       SESSION      *session;
   13989 11
   13990 12   // Command Output
   13991 13
   13992 14       // Get pointer to the session structure
   13993 15       session = SessionGet(in->policySession);
   13994 16
   13995 17       out->policyDigest = session->u2.policyDigest;
   13996 18
   13997 19       return TPM_RC_SUCCESS;
   13998 20   }
   13999 21   #endif // CC_PolicyGetDigest
   14000 
   14001 
   14002 
   14003 
   14004      Family 2.0                              TCG Published                               Page 303
   14005      Level 00 Revision 01.16              Copyright  TCG 2006-2014                 October 30, 2014
   14006 Part 3: Commands                                                                 Trusted Platform Module Library
   14008 
   14009 
   14010 23.20 TPM2_PolicyNvWritten
   14011 
   14012 23.20.1     General Description
   14013 
   14014 This command allows a policy to be bound to the TPMA_NV_WRITTEN attributes. This is a deferred
   14015 assertion. Values are stored in the policy session context and checked when the policy is used for
   14016 authorization.
   14017 If policySessioncheckNVWritten is CLEAR, it is SET and policySessionnvWrittenState is set to
   14018 writtenSet.   If policySessioncheckNVWritten is SET, the TPM will return TPM_RC_VALUE if
   14019 policySessionnvWrittenState and writtenSet are not the same.
   14020 If the TPM does not return an error, it will update policySessionpolicyDigest by
   14021           policyDigestnew  HpolicyAlg(policyDigestold || TPM_CC_PolicyNvWritten || writtenSet)                  (38)
   14022 When the policy session is used to authorize a command, the TPM will fail the command if
   14023 policySessioncheckNVWritten is SET and nvIndexattributesTPMA_NV_WRITTEN does not match
   14024 policySessionnvWrittenState.
   14025 
   14026 NOTE 1          A typical use case is a simple policy for the first write during manufacturing provisioning that would
   14027                 require TPMA_NV_WRITTEN CLEAR and a more complex policy for later use that would require
   14028                 TPMA_NV_WRITTEN SET.
   14029 
   14030 NOTE 2          When an Index is written, it has a different authorization name than an Index that has not been
   14031                 written. It is possible to use this change in the NV Index to create a write-once Index.
   14032 
   14033 
   14034 
   14035 
   14036 Page 304                                       TCG Published                                           Family 2.0
   14037 October 30, 2014                       Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   14038 Trusted Platform Module Library                                                          Part 3: Commands
   14040 
   14041 
   14042 23.20.2    Command and Response
   14043 
   14044                           Table 147  TPM2_PolicyNvWritten Command
   14045 Type                          Name                   Description
   14046 
   14047                                                      TPM_ST_SESSIONS if an audit session is present;
   14048 TPMI_ST_COMMAND_TAG           tag
   14049                                                      otherwise, TPM_ST_NO_SESSIONS
   14050 UINT32                        commandSize
   14051 TPM_CC                        commandCode            TPM_CC_PolicyNVWritten
   14052 
   14053                                                      handle for the policy session being extended
   14054 TPMI_SH_POLICY                policySession
   14055                                                      Auth Index: None
   14056 
   14057                                                      YES if NV Index is required to have been written
   14058 TPMI_YES_NO                   writtenSet
   14059                                                      NO if NV Index is required not to have been written
   14060 
   14061 
   14062                           Table 148  TPM2_PolicyNvWritten Response
   14063 Type                          Name                   Description
   14064 
   14065 TPM_ST                        tag                    see clause 6
   14066 UINT32                        responseSize
   14067 TPM_RC                        responseCode
   14068 
   14069 
   14070 
   14071 
   14072 Family 2.0                                  TCG Published                                         Page 305
   14073 Level 00 Revision 01.16             Copyright  TCG 2006-2014                            October 30, 2014
   14074      Part 3: Commands                                                              Trusted Platform Module Library
   14076 
   14077 
   14078 
   14079      23.20.3    Detailed Actions
   14080 
   14081 1    #include "InternalRoutines.h"
   14082 2    #include "PolicyNvWritten_fp.h"
   14083 3    #ifdef TPM_CC_PolicyNvWritten // Conditional expansion of this file
   14084 
   14085      Make an NV Index policy dependent on the state of the TPMA_NV_WRITTEN attribute of the index.
   14086 
   14087      Error Returns                   Meaning
   14088 
   14089      TPM_RC_VALUE                    a conflicting request for the attribute has already been processed
   14090 
   14091  4   TPM_RC
   14092  5   TPM2_PolicyNvWritten(
   14093  6       PolicyNvWritten_In    *in                 // IN: input parameter list
   14094  7       )
   14095  8   {
   14096  9       SESSION      *session;
   14097 10       TPM_CC        commandCode = TPM_CC_PolicyNvWritten;
   14098 11       HASH_STATE    hashState;
   14099 12
   14100 13   // Input Validation
   14101 14
   14102 15       // Get pointer to the session structure
   14103 16       session = SessionGet(in->policySession);
   14104 17
   14105 18       // If already set is this a duplicate (the same setting)? If it
   14106 19       // is a conflicting setting, it is an error
   14107 20       if(session->attributes.checkNvWritten == SET)
   14108 21       {
   14109 22           if((    (session->attributes.nvWrittenState == SET)
   14110 23               != (in->writtenSet == YES)))
   14111 24               return TPM_RC_VALUE + RC_PolicyNvWritten_writtenSet;
   14112 25       }
   14113 26
   14114 27   // Internal Data Update
   14115 28
   14116 29       // Set session attributes so that the NV Index needs to be checked
   14117 30       session->attributes.checkNvWritten = SET;
   14118 31       session->attributes.nvWrittenState = (in->writtenSet == YES);
   14119 32
   14120 33       // Update policy hash
   14121 34       // policyDigestnew = hash(policyDigestold || TPM_CC_PolicyNvWritten
   14122 35       //                          || writtenSet)
   14123 36       // Start hash
   14124 37       CryptStartHash(session->authHashAlg, &hashState);
   14125 38
   14126 39       // add old digest
   14127 40       CryptUpdateDigest2B(&hashState, &session->u2.policyDigest.b);
   14128 41
   14129 42       // add commandCode
   14130 43       CryptUpdateDigestInt(&hashState, sizeof(TPM_CC), &commandCode);
   14131 44
   14132 45       // add the byte of writtenState
   14133 46       CryptUpdateDigestInt(&hashState, sizeof(TPMI_YES_NO), &in->writtenSet);
   14134 47
   14135 48       // complete the digest
   14136 49       CryptCompleteHash2B(&hashState, &session->u2.policyDigest.b);
   14137 50
   14138 51       return TPM_RC_SUCCESS;
   14139 52   }
   14140 53   #endif // CC_PolicyNvWritten
   14141 
   14142 
   14143      Page 306                                     TCG Published                                           Family 2.0
   14144      October 30, 2014                    Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   14145 Trusted Platform Module Library                               Part 3: Commands
   14147 
   14148 
   14149 
   14150 
   14151 Family 2.0                           TCG Published                 Page 307
   14152 Level 00 Revision 01.16           Copyright  TCG 2006-2014   October 30, 2014
   14153 Part 3: Commands                                                           Trusted Platform Module Library
   14155 
   14156 
   14157 
   14158 24     Hierarchy Commands
   14159 
   14160 24.1     TPM2_CreatePrimary
   14161 
   14162 24.1.1 General Description
   14163 
   14164 This command is used to create a Primary Object under one of the Primary Seeds or a Temporary Object
   14165 under TPM_RH_NULL. The command uses a TPM2B_PUBLIC as a template for the object to be created.
   14166 The command will create and load a Primary Object. The sensitive area is not returned.
   14167 
   14168 NOTE 1:         Since the sensitive data is not returned, the key cannot be reloaded.   It can either be made
   14169                 persistent or it can be recreated.
   14170 
   14171 Any type of object and attributes combination that is allowed by TPM2_Create() may be created by this
   14172 command. The constraints on templates and parameters are the same as TPM2_Create() except that a
   14173 Primary Storage Key and a Temporary Storage Key are not constrained to use the algorithms of their
   14174 parents.
   14175 For setting of the attributes of the created object, fixedParent, fixedTPM, decrypt, and restricted are
   14176 implied to be SET in the parent (a Permanent Handle). The remaining attributes are implied to be CLEAR.
   14177 The TPM will derive the object from the Primary Seed indicated in primaryHandle using an approved
   14178 KDF. All of the bits of the template are used in the creation of the Primary Key. Methods for creating a
   14179 Primary Object from a Primary Seed are described in TPM 2.0 Part 1 and implemented in TPM 2.0 Part 4.
   14180 If this command is called multiple times with the same inPublic parameter, inSensitive.data, and Primary
   14181 Seed, the TPM shall produce the same Primary Object.
   14182 
   14183 NOTE 2          If the Primary Seed is changed, the Primary Objects generated with the new seed shall be
   14184                 statistically unique even if the parameters of the call are the same.
   14185 
   14186 This command requires authorization. Authorization for a Primary Object attached to the Platform Primary
   14187 Seed (PPS) shall be provided by platformAuth or platformPolicy. Authorization for a Primary Object
   14188 attached to the Storage Primary Seed (SPS) shall be provided by ownerAuth or ownerPolicy.
   14189 Authorization for a Primary Key attached to the Endorsement Primary Seed (EPS) shall be provided by
   14190 endorsementAuth or endorsementPolicy.
   14191 
   14192 
   14193 
   14194 
   14195 Page 308                                     TCG Published                                      Family 2.0
   14196 October 30, 2014                     Copyright  TCG 2006-2014                    Level 00 Revision 01.16
   14197 Trusted Platform Module Library                                                          Part 3: Commands
   14199 
   14200 
   14201 
   14202 24.1.2 Command and Response
   14203 
   14204                            Table 149  TPM2_CreatePrimary Command
   14205 Type                          Name                  Description
   14206 
   14207 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   14208 UINT32                        commandSize
   14209 TPM_CC                        commandCode           TPM_CC_CreatePrimary
   14210 
   14211                                                     TPM_RH_ENDORSEMENT, TPM_RH_OWNER,
   14212                                                     TPM_RH_PLATFORM+{PP}, or TPM_RH_NULL
   14213 TPMI_RH_HIERARCHY+            @primaryHandle
   14214                                                     Auth Index: 1
   14215                                                     Auth Role: USER
   14216 
   14217 TPM2B_SENSITIVE_CREATE        inSensitive           the sensitive data, see TPM 2.0 Part 1 Sensitive Values
   14218 TPM2B_PUBLIC                  inPublic              the public template
   14219                                                     data that will be included in the creation data for this
   14220 TPM2B_DATA                    outsideInfo           object to provide permanent, verifiable linkage between
   14221                                                     this object and some object owner data
   14222 TPML_PCR_SELECTION            creationPCR           PCR that will be used in creation data
   14223 
   14224 
   14225                            Table 150  TPM2_CreatePrimary Response
   14226 Type                          Name                  Description
   14227 
   14228 TPM_ST                        tag                   see clause 6
   14229 UINT32                        responseSize
   14230 TPM_RC                        responseCode
   14231 
   14232                                                     handle of type TPM_HT_TRANSIENT for created
   14233 TPM_HANDLE                    objectHandle
   14234                                                     Primary Object
   14235 
   14236 TPM2B_PUBLIC                  outPublic             the public portion of the created object
   14237 TPM2B_CREATION_DATA           creationData          contains a TPMT_CREATION_DATA
   14238 TPM2B_DIGEST                  creationHash          digest of creationData using nameAlg of outPublic
   14239                                                     ticket used by TPM2_CertifyCreation() to validate that
   14240 TPMT_TK_CREATION              creationTicket
   14241                                                     the creation data was produced by the TPM
   14242 TPM2B_NAME                    name                  the name of the created object
   14243 
   14244 
   14245 
   14246 
   14247 Family 2.0                                 TCG Published                                        Page 309
   14248 Level 00 Revision 01.16              Copyright  TCG 2006-2014                           October 30, 2014
   14249      Part 3: Commands                                                               Trusted Platform Module Library
   14251 
   14252 
   14253 
   14254      24.1.3 Detailed Actions
   14255 
   14256 1    #include "InternalRoutines.h"
   14257 2    #include "CreatePrimary_fp.h"
   14258 3    #ifdef TPM_CC_CreatePrimary // Conditional expansion of this file
   14259 4    #include "Object_spt_fp.h"
   14260 5    #include <Platform.h>
   14261 
   14262 
   14263      Error Returns                  Meaning
   14264 
   14265      TPM_RC_ATTRIBUTES              sensitiveDataOrigin is CLEAR when 'sensitive.data' is an Empty
   14266                                     Buffer, or is SET when 'sensitive.data' is not empty; fixedTPM,
   14267                                     fixedParent, or encryptedDuplication attributes are inconsistent
   14268                                     between themselves or with those of the parent object; inconsistent
   14269                                     restricted, decrypt and sign attributes; attempt to inject sensitive data
   14270                                     for an asymmetric key; attempt to create a symmetric cipher key that
   14271                                     is not a decryption key
   14272      TPM_RC_KDF                     incorrect KDF specified for decrypting keyed hash object
   14273      TPM_RC_OBJECT_MEMORY           there is no free slot for the object
   14274      TPM_RC_SCHEME                  inconsistent attributes decrypt, sign, restricted and key's scheme ID;
   14275                                     or hash algorithm is inconsistent with the scheme ID for keyed hash
   14276                                     object
   14277      TPM_RC_SIZE                    size of public auth policy or sensitive auth value does not match
   14278                                     digest size of the name algorithm sensitive data size for the keyed
   14279                                     hash object is larger than is allowed for the scheme
   14280      TPM_RC_SYMMETRIC               a storage key with no symmetric algorithm specified; or non-storage
   14281                                     key with symmetric algorithm different from TPM_ALG_NULL
   14282      TPM_RC_TYPE                    unknown object type;
   14283 
   14284  6   TPM_RC
   14285  7   TPM2_CreatePrimary(
   14286  8       CreatePrimary_In    *in,                  // IN: input parameter list
   14287  9       CreatePrimary_Out   *out                  // OUT: output parameter list
   14288 10       )
   14289 11   {
   14290 12   // Local variables
   14291 13       TPM_RC              result = TPM_RC_SUCCESS;
   14292 14       TPMT_SENSITIVE      sensitive;
   14293 15
   14294 16   // Input Validation
   14295 17       // The sensitiveDataOrigin attribute must be consistent with the setting of
   14296 18       // the size of the data object in inSensitive.
   14297 19       if(   (in->inPublic.t.publicArea.objectAttributes.sensitiveDataOrigin == SET)
   14298 20          != (in->inSensitive.t.sensitive.data.t.size == 0 ))
   14299 21           // Mismatch between the object attributes and the parameter.
   14300 22           return TPM_RC_ATTRIBUTES + RC_CreatePrimary_inSensitive;
   14301 23
   14302 24       // Check attributes in input public area. TPM_RC_ATTRIBUTES, TPM_RC_KDF,
   14303 25       // TPM_RC_SCHEME, TPM_RC_SIZE, TPM_RC_SYMMETRIC, or TPM_RC_TYPE error may
   14304 26       // be returned at this point.
   14305 27       result = PublicAttributesValidation(FALSE, in->primaryHandle,
   14306 28                                           &in->inPublic.t.publicArea);
   14307 29       if(result != TPM_RC_SUCCESS)
   14308 30           return RcSafeAddToResult(result, RC_CreatePrimary_inPublic);
   14309 31
   14310 32       // Validate the sensitive area values
   14311 33       if( MemoryRemoveTrailingZeros(&in->inSensitive.t.sensitive.userAuth)
   14312 34               > CryptGetHashDigestSize(in->inPublic.t.publicArea.nameAlg))
   14313 
   14314 
   14315      Page 310                                     TCG Published                                            Family 2.0
   14316      October 30, 2014                    Copyright  TCG 2006-2014                         Level 00 Revision 01.16
   14317      Trusted Platform Module Library                                                Part 3: Commands
   14319 
   14320 35           return TPM_RC_SIZE + RC_CreatePrimary_inSensitive;
   14321 36
   14322 37   // Command output
   14323 38
   14324 39       // Generate Primary Object
   14325 40       // The primary key generation process uses the Name of the input public
   14326 41       // template to compute the key. The keys are generated from the template
   14327 42       // before anything in the template is allowed to be changed.
   14328 43       // A TPM_RC_KDF, TPM_RC_SIZE error may be returned at this point
   14329 44       result = CryptCreateObject(in->primaryHandle, &in->inPublic.t.publicArea,
   14330 45                                  &in->inSensitive.t.sensitive,&sensitive);
   14331 46       if(result != TPM_RC_SUCCESS)
   14332 47           return result;
   14333 48
   14334 49       // Fill in creation data
   14335 50       FillInCreationData(in->primaryHandle, in->inPublic.t.publicArea.nameAlg,
   14336 51                          &in->creationPCR, &in->outsideInfo, &out->creationData,
   14337 52                          &out->creationHash);
   14338 53
   14339 54       // Copy public area
   14340 55       out->outPublic = in->inPublic;
   14341 56
   14342 57       // Fill in private area for output
   14343 58       ObjectComputeName(&(out->outPublic.t.publicArea), &out->name);
   14344 59
   14345 60       // Compute creation ticket
   14346 61       TicketComputeCreation(EntityGetHierarchy(in->primaryHandle), &out->name,
   14347 62                             &out->creationHash, &out->creationTicket);
   14348 63
   14349 64       // Create a internal object. A TPM_RC_OBJECT_MEMORY error may be returned
   14350 65       // at this point.
   14351 66       result = ObjectLoad(in->primaryHandle, &in->inPublic.t.publicArea, &sensitive,
   14352 67                           &out->name, in->primaryHandle, TRUE, &out->objectHandle);
   14353 68
   14354 69       return result;
   14355 70   }
   14356 71   #endif // CC_CreatePrimary
   14357 
   14358 
   14359 
   14360 
   14361      Family 2.0                           TCG Published                                  Page 311
   14362      Level 00 Revision 01.16           Copyright  TCG 2006-2014                    October 30, 2014
   14363 Part 3: Commands                                                           Trusted Platform Module Library
   14365 
   14366 
   14367 24.2   TPM2_HierarchyControl
   14368 
   14369 24.2.1 General Description
   14370 
   14371 This command enables and disables use of a hierarchy and its associated NV storage. The command
   14372 allows phEnable, phEnableNV, shEnable, and ehEnable to be changed when the proper authorization is
   14373 provided.
   14374 This command may be used to CLEAR phEnable and phEnableNV if platformAuth/platformPolicy is
   14375 provided. phEnable may not be SET using this command.
   14376 This command may be used to CLEAR shEnable if either platformAuth/platformPolicy                          or
   14377 ownerAuth/ownerPolicy is provided. shEnable may be SET if platformAuth/platformPolicy is provided.
   14378 This command may be used to CLEAR ehEnable if either platformAuth/platformPolicy or
   14379 endorsementAuth/endorsementPolicy is provided. ehEnable may be SET if platformAuth/platformPolicy is
   14380 provided.
   14381 When this command is used to CLEAR phEnable, shEnable, or ehEnable, the TPM will disable use of
   14382 any persistent entity associated with the disabled hierarchy and will flush any transient objects associated
   14383 with the disabled hierarchy.
   14384 When this command is used to CLEAR shEnable, the TPM will disable access to any NV index that has
   14385 TPMA_NV_PLATFORMCREATE CLEAR (indicating that the NV Index was defined using Owner
   14386 Authorization). As long as shEnable is CLEAR, the TPM will return an error in response to any command
   14387 that attempts to operate upon an NV index that has TPMA_NV_PLATFORMCREATE CLEAR.
   14388 When this command is used to CLEAR phEnableNV, the TPM will disable access to any NV index that
   14389 has TPMA_NV_PLATFORMCREATE SET (indicating that the NV Index was defined using Platform
   14390 Authorization). As long as phEnableNV is CLEAR, the TPM will return an error in response to any
   14391 command that attempts to operate upon an NV index that has TPMA_NV_PLATFORMCREATE SET.
   14392 
   14393 
   14394 
   14395 
   14396 Page 312                                     TCG Published                                    Family 2.0
   14397 October 30, 2014                     Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   14398 Trusted Platform Module Library                                                        Part 3: Commands
   14400 
   14401 
   14402 
   14403 24.2.2 Command and Response
   14404 
   14405                           Table 151  TPM2_HierarchyControl Command
   14406 Type                          Name                  Description
   14407 
   14408 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   14409 
   14410 UINT32                        commandSize
   14411 
   14412 TPM_CC                        commandCode           TPM_CC_HierarchyControl {NV E}
   14413 
   14414                                                     TPM_RH_ENDORSEMENT, TPM_RH_OWNER or
   14415                                                     TPM_RH_PLATFORM+{PP}
   14416 TPMI_RH_HIERARCHY             @authHandle
   14417                                                     Auth Index: 1
   14418                                                     Auth Role: USER
   14419 
   14420                                                     the enable being modified
   14421 TPMI_RH_ENABLES               enable                TPM_RH_ENDORSEMENT, TPM_RH_OWNER,
   14422                                                     TPM_RH_PLATFORM, or TPM_RH_PLATFORM_NV
   14423                                                     YES if the enable should be SET, NO if the enable
   14424 TPMI_YES_NO                   state
   14425                                                     should be CLEAR
   14426 
   14427 
   14428                           Table 152  TPM2_HierarchyControl Response
   14429 Type                          Name                  Description
   14430 
   14431 TPM_ST                        tag                   see clause 6
   14432 
   14433 UINT32                        responseSize
   14434 
   14435 TPM_RC                        responseCode
   14436 
   14437 
   14438 
   14439 
   14440 Family 2.0                                 TCG Published                                      Page 313
   14441 Level 00 Revision 01.16               Copyright  TCG 2006-2014                        October 30, 2014
   14442      Part 3: Commands                                                           Trusted Platform Module Library
   14444 
   14445 
   14446 
   14447      24.2.3 Detailed Actions
   14448 
   14449 1    #include "InternalRoutines.h"
   14450 2    #include "HierarchyControl_fp.h"
   14451 3    #ifdef TPM_CC_HierarchyControl // Conditional expansion of this file
   14452 
   14453 
   14454      Error Returns               Meaning
   14455 
   14456      TPM_RC_AUTH_TYPE            authHandle is not applicable to hierarchy in its current state
   14457 
   14458  4   TPM_RC
   14459  5   TPM2_HierarchyControl(
   14460  6       HierarchyControl_In    *in                 // IN: input parameter list
   14461  7       )
   14462  8   {
   14463  9       TPM_RC      result;
   14464 10       BOOL        select = (in->state == YES);
   14465 11       BOOL        *selected = NULL;
   14466 12
   14467 13   // Input Validation
   14468 14       switch(in->enable)
   14469 15       {
   14470 16           // Platform hierarchy has to be disabled by platform auth
   14471 17           // If the platform hierarchy has already been disabled, only a reboot
   14472 18           // can enable it again
   14473 19           case TPM_RH_PLATFORM:
   14474 20           case TPM_RH_PLATFORM_NV:
   14475 21               if(in->authHandle != TPM_RH_PLATFORM)
   14476 22                   return TPM_RC_AUTH_TYPE;
   14477 23               break;
   14478 24
   14479 25           // ShEnable may be disabled if PlatformAuth/PlatformPolicy or
   14480 26           // OwnerAuth/OwnerPolicy is provided. If ShEnable is disabled, then it
   14481 27           // may only be enabled if PlatformAuth/PlatformPolicy is provided.
   14482 28           case TPM_RH_OWNER:
   14483 29               if(   in->authHandle != TPM_RH_PLATFORM
   14484 30                  && in->authHandle != TPM_RH_OWNER)
   14485 31                   return TPM_RC_AUTH_TYPE;
   14486 32               if(   gc.shEnable == FALSE && in->state == YES
   14487 33                  && in->authHandle != TPM_RH_PLATFORM)
   14488 34                   return TPM_RC_AUTH_TYPE;
   14489 35               break;
   14490 36
   14491 37           // EhEnable may be disabled if either PlatformAuth/PlatformPolicy or
   14492 38           // EndosementAuth/EndorsementPolicy is provided. If EhEnable is disabled,
   14493 39           // then it may only be enabled if PlatformAuth/PlatformPolicy is
   14494 40           // provided.
   14495 41           case TPM_RH_ENDORSEMENT:
   14496 42               if(   in->authHandle != TPM_RH_PLATFORM
   14497 43                  && in->authHandle != TPM_RH_ENDORSEMENT)
   14498 44                   return TPM_RC_AUTH_TYPE;
   14499 45               if(   gc.ehEnable == FALSE && in->state == YES
   14500 46                  && in->authHandle != TPM_RH_PLATFORM)
   14501 47                   return TPM_RC_AUTH_TYPE;
   14502 48               break;
   14503 49           default:
   14504 50               pAssert(FALSE);
   14505 51               break;
   14506 52       }
   14507 53
   14508 54   // Internal Data Update
   14509 55
   14510 56       // Enable or disable the selected hierarchy
   14511 
   14512      Page 314                                 TCG Published                                       Family 2.0
   14513      October 30, 2014                 Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   14514       Trusted Platform Module Library                                             Part 3: Commands
   14516 
   14517  57       // Note: the authorization processing for this command may keep these
   14518  58       // command actions from being executed. For example, if phEnable is
   14519  59       // CLEAR, then platformAuth cannot be used for authorization. This
   14520  60       // means that would not be possible to use platformAuth to change the
   14521  61       // state of phEnable from CLEAR to SET.
   14522  62       // If it is decided that platformPolicy can still be used when phEnable
   14523  63       // is CLEAR, then this code could SET phEnable when proper platform
   14524  64       // policy is provided.
   14525  65       switch(in->enable)
   14526  66       {
   14527  67           case TPM_RH_OWNER:
   14528  68               selected = &gc.shEnable;
   14529  69               break;
   14530  70           case TPM_RH_ENDORSEMENT:
   14531  71               selected = &gc.ehEnable;
   14532  72               break;
   14533  73           case TPM_RH_PLATFORM:
   14534  74               selected = &g_phEnable;
   14535  75               break;
   14536  76           case TPM_RH_PLATFORM_NV:
   14537  77               selected = &gc.phEnableNV;
   14538  78               break;
   14539  79           default:
   14540  80               pAssert(FALSE);
   14541  81               break;
   14542  82       }
   14543  83       if(selected != NULL && *selected != select)
   14544  84       {
   14545  85           // Before changing the internal state, make sure that NV is available.
   14546  86           // Only need to update NV if changing the orderly state
   14547  87           if(gp.orderlyState != SHUTDOWN_NONE)
   14548  88           {
   14549  89               // The command needs NV update. Check if NV is available.
   14550  90               // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   14551  91               // this point
   14552  92               result = NvIsAvailable();
   14553  93               if(result != TPM_RC_SUCCESS)
   14554  94                   return result;
   14555  95           }
   14556  96           // state is changing and NV is available so modify
   14557  97           *selected = select;
   14558  98           // If a hierarchy was just disabled, flush it
   14559  99           if(select == CLEAR && in->enable != TPM_RH_PLATFORM_NV)
   14560 100           // Flush hierarchy
   14561 101               ObjectFlushHierarchy(in->enable);
   14562 102
   14563 103           // orderly state should be cleared because of the update to state clear data
   14564 104           // This gets processed in ExecuteCommand() on the way out.
   14565 105           g_clearOrderly = TRUE;
   14566 106       }
   14567 107       return TPM_RC_SUCCESS;
   14568 108   }
   14569 109   #endif // CC_HierarchyControl
   14570 
   14571 
   14572 
   14573 
   14574       Family 2.0                           TCG Published                                   Page 315
   14575       Level 00 Revision 01.16           Copyright  TCG 2006-2014                 October 30, 2014
   14576 Part 3: Commands                                                        Trusted Platform Module Library
   14578 
   14579 
   14580 24.3   TPM2_SetPrimaryPolicy
   14581 
   14582 24.3.1 General Description
   14583 
   14584 This command allows setting of the authorization policy for the lockout (lockoutPolicy), the platform
   14585 hierarchy (platformPolicy), the storage hierarchy (ownerPolicy), and the endorsement hierarchy
   14586 (endorsementPolicy).
   14587 The command requires an authorization session. The session shall use the current authValue or satisfy
   14588 the current authPolicy for the referenced hierarchy.
   14589 The policy that is changed is the policy associated with authHandle.
   14590 If the enable associated with authHandle is not SET, then the associated authorization values (authValue
   14591 or authPolicy) may not be used.
   14592 
   14593 
   14594 
   14595 
   14596 Page 316                                    TCG Published                                  Family 2.0
   14597 October 30, 2014                     Copyright  TCG 2006-2014                Level 00 Revision 01.16
   14598 Trusted Platform Module Library                                                           Part 3: Commands
   14600 
   14601 
   14602 
   14603 24.3.2 Command and Response
   14604 
   14605                           Table 153  TPM2_SetPrimaryPolicy Command
   14606 Type                          Name                  Description
   14607 
   14608 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   14609 
   14610 UINT32                        commandSize
   14611 
   14612 TPM_CC                        commandCode           TPM_CC_SetPrimaryPolicy {NV}
   14613 
   14614                                                     TPM_RH_LOCKOUT, TPM_RH_ENDORSEMENT,
   14615                                                     TPM_RH_OWNER or TPM_RH_PLATFORM+{PP}
   14616 TPMI_RH_HIERARCHY_AUTH        @authHandle
   14617                                                     Auth Index: 1
   14618                                                     Auth Role: USER
   14619 
   14620                                                     an authorization policy digest; may be the Empty Buffer
   14621 TPM2B_DIGEST                  authPolicy            If hashAlg is TPM_ALG_NULL, then this shall be an
   14622                                                     Empty Buffer.
   14623                                                     the hash algorithm to use for the policy
   14624 TPMI_ALG_HASH+                hashAlg               If the authPolicy is an Empty Buffer, then this field shall
   14625                                                     be TPM_ALG_NULL.
   14626 
   14627 
   14628                           Table 154  TPM2_SetPrimaryPolicy Response
   14629 Type                          Name                  Description
   14630 
   14631 TPM_ST                        tag                   see clause 6
   14632 
   14633 UINT32                        responseSize
   14634 
   14635 TPM_RC                        responseCode
   14636 
   14637 
   14638 
   14639 
   14640 Family 2.0                                 TCG Published                                          Page 317
   14641 Level 00 Revision 01.16             Copyright  TCG 2006-2014                             October 30, 2014
   14642      Part 3: Commands                                                           Trusted Platform Module Library
   14644 
   14645 
   14646 
   14647      24.3.3 Detailed Actions
   14648 
   14649 1    #include "InternalRoutines.h"
   14650 2    #include "SetPrimaryPolicy_fp.h"
   14651 3    #ifdef TPM_CC_SetPrimaryPolicy // Conditional expansion of this file
   14652 
   14653 
   14654      Error Returns               Meaning
   14655 
   14656      TPM_RC_SIZE                 size of input authPolicy is not consistent with input hash algorithm
   14657 
   14658  4   TPM_RC
   14659  5   TPM2_SetPrimaryPolicy(
   14660  6       SetPrimaryPolicy_In    *in                 // IN: input parameter list
   14661  7       )
   14662  8   {
   14663  9       TPM_RC                  result;
   14664 10
   14665 11   // Input Validation
   14666 12
   14667 13       // Check the authPolicy consistent with hash algorithm. If the policy size is
   14668 14       // zero, then the algorithm is required to be TPM_ALG_NULL
   14669 15       if(in->authPolicy.t.size != CryptGetHashDigestSize(in->hashAlg))
   14670 16           return TPM_RC_SIZE + RC_SetPrimaryPolicy_authPolicy;
   14671 17
   14672 18       // The command need NV update for OWNER and ENDORSEMENT hierarchy, and
   14673 19       // might need orderlyState update for PLATFROM hierarchy.
   14674 20       // Check if NV is available. A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE
   14675 21       // error may be returned at this point
   14676 22       result = NvIsAvailable();
   14677 23       if(result != TPM_RC_SUCCESS)
   14678 24           return result;
   14679 25
   14680 26   // Internal Data Update
   14681 27
   14682 28       // Set hierarchy policy
   14683 29       switch(in->authHandle)
   14684 30       {
   14685 31           case TPM_RH_OWNER:
   14686 32               gp.ownerAlg = in->hashAlg;
   14687 33               gp.ownerPolicy = in->authPolicy;
   14688 34               NvWriteReserved(NV_OWNER_ALG, &gp.ownerAlg);
   14689 35               NvWriteReserved(NV_OWNER_POLICY, &gp.ownerPolicy);
   14690 36               break;
   14691 37           case TPM_RH_ENDORSEMENT:
   14692 38               gp.endorsementAlg = in->hashAlg;
   14693 39               gp.endorsementPolicy = in->authPolicy;
   14694 40               NvWriteReserved(NV_ENDORSEMENT_ALG, &gp.endorsementAlg);
   14695 41               NvWriteReserved(NV_ENDORSEMENT_POLICY, &gp.endorsementPolicy);
   14696 42               break;
   14697 43           case TPM_RH_PLATFORM:
   14698 44               gc.platformAlg = in->hashAlg;
   14699 45               gc.platformPolicy = in->authPolicy;
   14700 46               // need to update orderly state
   14701 47               g_clearOrderly = TRUE;
   14702 48               break;
   14703 49           case TPM_RH_LOCKOUT:
   14704 50               gp.lockoutAlg = in->hashAlg;
   14705 51               gp.lockoutPolicy = in->authPolicy;
   14706 52               NvWriteReserved(NV_LOCKOUT_ALG, &gp.lockoutAlg);
   14707 53               NvWriteReserved(NV_LOCKOUT_POLICY, &gp.lockoutPolicy);
   14708 54               break;
   14709 55
   14710 56           default:
   14711 
   14712      Page 318                                 TCG Published                                             Family 2.0
   14713      October 30, 2014                 Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   14714      Trusted Platform Module Library                               Part 3: Commands
   14716 
   14717 57                pAssert(FALSE);
   14718 58                break;
   14719 59       }
   14720 60
   14721 61       return TPM_RC_SUCCESS;
   14722 62   }
   14723 63   #endif // CC_SetPrimaryPolicy
   14724 
   14725 
   14726 
   14727 
   14728      Family 2.0                           TCG Published                 Page 319
   14729      Level 00 Revision 01.16           Copyright  TCG 2006-2014   October 30, 2014
   14730 Part 3: Commands                                                              Trusted Platform Module Library
   14732 
   14733 
   14734 24.4     TPM2_ChangePPS
   14735 
   14736 24.4.1 General Description
   14737 
   14738 This replaces the current PPS with a value from the RNG and sets platformPolicy to the default
   14739 initialization value (the Empty Buffer).
   14740 
   14741 NOTE 1          A policy that is the Empty Buffer can match no policy.
   14742 
   14743 NOTE 2          Platform Authorization is not changed.
   14744 
   14745 All resident transient and persistent objects in the Platform hierarchy are flushed.
   14746 Saved contexts in the Platform hierarchy that were created under the old PPS will no longer be able to be
   14747 loaded.
   14748 The policy hash algorithm for PCR is reset to TPM_ALG_NULL.
   14749 This command does not clear any NV Index values.
   14750 
   14751 NOTE 3          Index values belonging to the Platform are preserved because the indexes may have configuration
   14752                 information that will be the same after the PPS changes. The Platform may remove the indexes that
   14753                 are no longer needed using TPM2_NV_UndefineSpace().
   14754 
   14755 This command requires Platform Authorization.
   14756 
   14757 
   14758 
   14759 
   14760 Page 320                                       TCG Published                                       Family 2.0
   14761 October 30, 2014                       Copyright  TCG 2006-2014                    Level 00 Revision 01.16
   14762 Trusted Platform Module Library                                             Part 3: Commands
   14764 
   14765 
   14766 
   14767 24.4.2 Command and Response
   14768 
   14769                             Table 155  TPM2_ChangePPS Command
   14770  Type                         Name                Description
   14771 
   14772  TPMI_ST_COMMAND_TAG          tag                 TPM_ST_SESSIONS
   14773  UINT32                       commandSize
   14774  TPM_CC                       commandCode         TPM_CC_ChangePPS {NV E}
   14775 
   14776                                                   TPM_RH_PLATFORM+{PP}
   14777  TPMI_RH_PLATFORM             @authHandle         Auth Index: 1
   14778                                                   Auth Role: USER
   14779 
   14780 
   14781                              Table 156  TPM2_ChangePPS Response
   14782  Type                         Name                Description
   14783  TPM_ST                       tag                 see clause 6
   14784  UINT32                       responseSize
   14785  TPM_RC                       responseCode
   14786 
   14787 
   14788 
   14789 
   14790 Family 2.0                             TCG Published                             Page 321
   14791 Level 00 Revision 01.16             Copyright  TCG 2006-2014               October 30, 2014
   14792      Part 3: Commands                                                  Trusted Platform Module Library
   14794 
   14795 
   14796 
   14797      24.4.3 Detailed Actions
   14798 
   14799  1   #include "InternalRoutines.h"
   14800  2   #include "ChangePPS_fp.h"
   14801  3   #ifdef TPM_CC_ChangePPS // Conditional expansion of this file
   14802  4   TPM_RC
   14803  5   TPM2_ChangePPS(
   14804  6       ChangePPS_In   *in             // IN: input parameter list
   14805  7       )
   14806  8   {
   14807  9       UINT32         i;
   14808 10       TPM_RC         result;
   14809 11
   14810 12       // Check if NV is available. A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE
   14811 13       // error may be returned at this point
   14812 14       result = NvIsAvailable();
   14813 15       if(result != TPM_RC_SUCCESS) return result;
   14814 16
   14815 17       // Input parameter is not reference in command action
   14816 18       in = NULL;
   14817 19
   14818 20   // Internal Data Update
   14819 21
   14820 22       // Reset platform hierarchy seed from RNG
   14821 23       CryptGenerateRandom(PRIMARY_SEED_SIZE, gp.PPSeed.t.buffer);
   14822 24
   14823 25       // Create a new phProof value from RNG to prevent the saved platform
   14824 26       // hierarchy contexts being loaded
   14825 27       CryptGenerateRandom(PROOF_SIZE, gp.phProof.t.buffer);
   14826 28
   14827 29       // Set platform authPolicy to null
   14828 30       gc.platformAlg = TPM_ALG_NULL;
   14829 31       gc.platformPolicy.t.size = 0;
   14830 32
   14831 33       // Flush loaded object in platform hierarchy
   14832 34       ObjectFlushHierarchy(TPM_RH_PLATFORM);
   14833 35
   14834 36       // Flush platform evict object and index in NV
   14835 37       NvFlushHierarchy(TPM_RH_PLATFORM);
   14836 38
   14837 39       // Save hierarchy changes to NV
   14838 40       NvWriteReserved(NV_PP_SEED, &gp.PPSeed);
   14839 41       NvWriteReserved(NV_PH_PROOF, &gp.phProof);
   14840 42
   14841 43       // Re-initialize PCR policies
   14842 44       for(i = 0; i < NUM_POLICY_PCR_GROUP; i++)
   14843 45       {
   14844 46           gp.pcrPolicies.hashAlg[i] = TPM_ALG_NULL;
   14845 47           gp.pcrPolicies.policy[i].t.size = 0;
   14846 48       }
   14847 49       NvWriteReserved(NV_PCR_POLICIES, &gp.pcrPolicies);
   14848 50
   14849 51       // orderly state should be cleared because of the update to state clear data
   14850 52       g_clearOrderly = TRUE;
   14851 53
   14852 54       return TPM_RC_SUCCESS;
   14853 55   }
   14854 56   #endif // CC_ChangePPS
   14855 
   14856 
   14857 
   14858 
   14859      Page 322                                 TCG Published                              Family 2.0
   14860      October 30, 2014                Copyright  TCG 2006-2014              Level 00 Revision 01.16
   14861 Trusted Platform Module Library                                                                Part 3: Commands
   14863 
   14864 
   14865 24.5   TPM2_ChangeEPS
   14866 
   14867 24.5.1 General Description
   14868 
   14869 This replaces the current EPS with a value from the RNG and sets the Endorsement hierarchy controls to
   14870 their default initialization values: ehEnable is SET, endorsementAuth and endorsementPolicy both equal
   14871 to the Empty Buffer. It will flush any resident objects (transient or persistent) in the EPS hierarchy and not
   14872 allow objects in the hierarchy associated with the previous EPS to be loaded.
   14873 
   14874 NOTE            In the reference implementation, ehProof is a non-volatile value from the RNG. It is allowed that the
   14875                 ehProof be generated by a KDF using both the EPS and SPS as inputs. If generated with a KDF, the
   14876                 ehProof can be generated on an as-needed basis or made a non-volatile value.
   14877 
   14878 This command requires Platform Authorization.
   14879 
   14880 
   14881 
   14882 
   14883 Family 2.0                                   TCG Published                                             Page 323
   14884 Level 00 Revision 01.16                Copyright  TCG 2006-2014                               October 30, 2014
   14885 Part 3: Commands                                           Trusted Platform Module Library
   14887 
   14888 
   14889 
   14890 24.5.2 Command and Response
   14891 
   14892                        Table 157  TPM2_ChangeEPS Command
   14893  Type                   Name                Description
   14894 
   14895  TPMI_ST_COMMAND_TAG    tag                 TPM_ST_SESSIONS
   14896  UINT32                 commandSize
   14897  TPM_CC                 commandCode         TPM_CC_ChangeEPS {NV E}
   14898 
   14899                                             TPM_RH_PLATFORM+{PP}
   14900  TPMI_RH_PLATFORM       @authHandle         Auth Handle: 1
   14901                                             Auth Role: USER
   14902 
   14903 
   14904                        Table 158  TPM2_ChangeEPS Response
   14905  Type                   Name                Description
   14906  TPM_ST                 tag                 see clause 6
   14907  UINT32                 responseSize
   14908  TPM_RC                 responseCode
   14909 
   14910 
   14911 
   14912 
   14913 Page 324                           TCG Published                             Family 2.0
   14914 October 30, 2014              Copyright  TCG 2006-2014         Level 00 Revision 01.16
   14915      Trusted Platform Module Library                                             Part 3: Commands
   14917 
   14918 
   14919 
   14920      24.5.3 Detailed Actions
   14921 
   14922  1   #include "InternalRoutines.h"
   14923  2   #include "ChangeEPS_fp.h"
   14924  3   #ifdef TPM_CC_ChangeEPS // Conditional expansion of this file
   14925  4   TPM_RC
   14926  5   TPM2_ChangeEPS(
   14927  6       ChangeEPS_In     *in              // IN: input parameter list
   14928  7       )
   14929  8   {
   14930  9       TPM_RC           result;
   14931 10
   14932 11       // The command needs NV update. Check if NV is available.
   14933 12       // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   14934 13       // this point
   14935 14       result = NvIsAvailable();
   14936 15       if(result != TPM_RC_SUCCESS) return result;
   14937 16
   14938 17       // Input parameter is not reference in command action
   14939 18       in = NULL;
   14940 19
   14941 20   // Internal Data Update
   14942 21
   14943 22       // Reset endorsement hierarchy seed from RNG
   14944 23       CryptGenerateRandom(PRIMARY_SEED_SIZE, gp.EPSeed.t.buffer);
   14945 24
   14946 25       // Create new ehProof value from RNG
   14947 26       CryptGenerateRandom(PROOF_SIZE, gp.ehProof.t.buffer);
   14948 27
   14949 28       // Enable endorsement hierarchy
   14950 29       gc.ehEnable = TRUE;
   14951 30
   14952 31       // set authValue buffer to zeros
   14953 32       MemorySet(gp.endorsementAuth.t.buffer, 0, gp.endorsementAuth.t.size);
   14954 33       // Set endorsement authValue to null
   14955 34       gp.endorsementAuth.t.size = 0;
   14956 35
   14957 36       // Set endorsement authPolicy to null
   14958 37       gp.endorsementAlg = TPM_ALG_NULL;
   14959 38       gp.endorsementPolicy.t.size = 0;
   14960 39
   14961 40       // Flush loaded object in endorsement hierarchy
   14962 41       ObjectFlushHierarchy(TPM_RH_ENDORSEMENT);
   14963 42
   14964 43       // Flush evict object of endorsement hierarchy stored in NV
   14965 44       NvFlushHierarchy(TPM_RH_ENDORSEMENT);
   14966 45
   14967 46       // Save hierarchy changes to NV
   14968 47       NvWriteReserved(NV_EP_SEED, &gp.EPSeed);
   14969 48       NvWriteReserved(NV_EH_PROOF, &gp.ehProof);
   14970 49       NvWriteReserved(NV_ENDORSEMENT_AUTH, &gp.endorsementAuth);
   14971 50       NvWriteReserved(NV_ENDORSEMENT_ALG, &gp.endorsementAlg);
   14972 51       NvWriteReserved(NV_ENDORSEMENT_POLICY, &gp.endorsementPolicy);
   14973 52
   14974 53       // orderly state should be cleared because of the update to state clear data
   14975 54       g_clearOrderly = TRUE;
   14976 55
   14977 56       return TPM_RC_SUCCESS;
   14978 57   }
   14979 58   #endif // CC_ChangeEPS
   14980 
   14981 
   14982 
   14983 
   14984      Family 2.0                             TCG Published                             Page 325
   14985      Level 00 Revision 01.16           Copyright  TCG 2006-2014                 October 30, 2014
   14986 Part 3: Commands                                                              Trusted Platform Module Library
   14988 
   14989 
   14990 24.6    TPM2_Clear
   14991 
   14992 24.6.1 General Description
   14993 
   14994 This command removes all TPM context associated with a specific Owner.
   14995 The clear operation will:
   14996        flush resident objects (persistent and volatile) in the Storage and Endorsement hierarchies;
   14997        delete any NV Index with TPMA_NV_PLATFORMCREATE == CLEAR;
   14998        change the SPS to a new value from the TPMs random number generator (RNG),
   14999        change shProof and ehProof,
   15000 
   15001     NOTE             The proof values may be set from the RNG or derived from the associated new Primary Seed. If
   15002                      derived from the Primary Seeds, the derivation of ehProof shall use both the SPS and EPS. The
   15003                      computation shall use the SPS as an HMAC key and the derived value may then be a parameter
   15004                      in a second HMAC in which the EPS is the HMAC key. The reference design uses values from
   15005                      the RNG.
   15006 
   15007        SET shEnable and ehEnable;
   15008        set ownerAuth, endorsementAuth, and lockoutAuth to the Empty Buffer;
   15009        set ownerPolicy, endorsementPolicy, and lockoutPolicy to the Empty Buffer;
   15010        set Clock to zero;
   15011        set resetCount to zero;
   15012        set restartCount to zero; and
   15013        set Safe to YES.
   15014 This command requires Platform Authorization or Lockout Authorization. If TPM2_ClearControl() has
   15015 disabled this command, the TPM shall return TPM_RC_DISABLED.
   15016 If this command is authorized using lockoutAuth, the HMAC in the response shall use the new
   15017 lockoutAuth value (that is, the Empty Buffer) when computing response HMAC.
   15018 
   15019 
   15020 
   15021 
   15022 Page 326                                       TCG Published                                       Family 2.0
   15023 October 30, 2014                        Copyright  TCG 2006-2014                    Level 00 Revision 01.16
   15024 Trusted Platform Module Library                                             Part 3: Commands
   15026 
   15027 
   15028 
   15029 24.6.2 Command and Response
   15030 
   15031                                   Table 159  TPM2_Clear Command
   15032  Type                         Name                 Description
   15033 
   15034  TPMI_ST_COMMAND_TAG          tag                  TPM_ST_SESSIONS
   15035  UINT32                       commandSize
   15036  TPM_CC                       commandCode          TPM_CC_Clear {NV E}
   15037 
   15038                                                    TPM_RH_LOCKOUT or TPM_RH_PLATFORM+{PP}
   15039  TPMI_RH_CLEAR                @authHandle          Auth Handle: 1
   15040                                                    Auth Role: USER
   15041 
   15042 
   15043                                   Table 160  TPM2_Clear Response
   15044  Type                         Name                 Description
   15045  TPM_ST                       tag                  see clause 6
   15046  UINT32                       responseSize
   15047  TPM_RC                       responseCode
   15048 
   15049 
   15050 
   15051 
   15052 Family 2.0                              TCG Published                            Page 327
   15053 Level 00 Revision 01.16             Copyright  TCG 2006-2014               October 30, 2014
   15054      Part 3: Commands                                                       Trusted Platform Module Library
   15056 
   15057 
   15058 
   15059      24.6.3 Detailed Actions
   15060 
   15061 1    #include "InternalRoutines.h"
   15062 2    #include "Clear_fp.h"
   15063 3    #ifdef TPM_CC_Clear // Conditional expansion of this file
   15064 
   15065 
   15066      Error Returns                   Meaning
   15067 
   15068      TPM_RC_DISABLED                 Clear command has been disabled
   15069 
   15070  4   TPM_RC
   15071  5   TPM2_Clear(
   15072  6       Clear_In          *in                // IN: input parameter list
   15073  7       )
   15074  8   {
   15075  9       TPM_RC                  result;
   15076 10
   15077 11       // Input parameter is not reference in command action
   15078 12       in = NULL;
   15079 13
   15080 14       // The command needs NV update. Check if NV is available.
   15081 15       // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   15082 16       // this point
   15083 17       result = NvIsAvailable();
   15084 18       if(result != TPM_RC_SUCCESS) return result;
   15085 19
   15086 20   // Input Validation
   15087 21
   15088 22       // If Clear command is disabled, return an error
   15089 23       if(gp.disableClear)
   15090 24           return TPM_RC_DISABLED;
   15091 25
   15092 26   // Internal Data Update
   15093 27
   15094 28       // Reset storage hierarchy seed from RNG
   15095 29       CryptGenerateRandom(PRIMARY_SEED_SIZE, gp.SPSeed.t.buffer);
   15096 30
   15097 31       // Create new shProof and ehProof value from RNG
   15098 32       CryptGenerateRandom(PROOF_SIZE, gp.shProof.t.buffer);
   15099 33       CryptGenerateRandom(PROOF_SIZE, gp.ehProof.t.buffer);
   15100 34
   15101 35       // Enable storage and endorsement hierarchy
   15102 36       gc.shEnable = gc.ehEnable = TRUE;
   15103 37
   15104 38       // set the authValue buffers to zero
   15105 39       MemorySet(gp.ownerAuth.t.buffer, 0, gp.ownerAuth.t.size);
   15106 40       MemorySet(gp.endorsementAuth.t.buffer, 0, gp.endorsementAuth.t.size);
   15107 41       MemorySet(gp.lockoutAuth.t.buffer, 0, gp.lockoutAuth.t.size);
   15108 42       // Set storage, endorsement and lockout authValue to null
   15109 43       gp.ownerAuth.t.size = gp.endorsementAuth.t.size = gp.lockoutAuth.t.size = 0;
   15110 44
   15111 45       // Set storage, endorsement, and lockout authPolicy to null
   15112 46       gp.ownerAlg = gp.endorsementAlg = gp.lockoutAlg = TPM_ALG_NULL;
   15113 47       gp.ownerPolicy.t.size = 0;
   15114 48       gp.endorsementPolicy.t.size = 0;
   15115 49       gp.lockoutPolicy.t.size = 0;
   15116 50
   15117 51       // Flush loaded object in storage and endorsement hierarchy
   15118 52       ObjectFlushHierarchy(TPM_RH_OWNER);
   15119 53       ObjectFlushHierarchy(TPM_RH_ENDORSEMENT);
   15120 54
   15121 55       // Flush owner and endorsement object and owner index in NV
   15122 56       NvFlushHierarchy(TPM_RH_OWNER);
   15123 
   15124      Page 328                                    TCG Published                                Family 2.0
   15125      October 30, 2014                      Copyright  TCG 2006-2014             Level 00 Revision 01.16
   15126      Trusted Platform Module Library                                             Part 3: Commands
   15128 
   15129 57       NvFlushHierarchy(TPM_RH_ENDORSEMENT);
   15130 58
   15131 59       // Save hierarchy changes to NV
   15132 60       NvWriteReserved(NV_SP_SEED, &gp.SPSeed);
   15133 61       NvWriteReserved(NV_SH_PROOF, &gp.shProof);
   15134 62       NvWriteReserved(NV_EH_PROOF, &gp.ehProof);
   15135 63       NvWriteReserved(NV_OWNER_AUTH, &gp.ownerAuth);
   15136 64       NvWriteReserved(NV_ENDORSEMENT_AUTH, &gp.endorsementAuth);
   15137 65       NvWriteReserved(NV_LOCKOUT_AUTH, &gp.lockoutAuth);
   15138 66       NvWriteReserved(NV_OWNER_ALG, &gp.ownerAlg);
   15139 67       NvWriteReserved(NV_ENDORSEMENT_ALG, &gp.endorsementAlg);
   15140 68       NvWriteReserved(NV_LOCKOUT_ALG, &gp.lockoutAlg);
   15141 69       NvWriteReserved(NV_OWNER_POLICY, &gp.ownerPolicy);
   15142 70       NvWriteReserved(NV_ENDORSEMENT_POLICY, &gp.endorsementPolicy);
   15143 71       NvWriteReserved(NV_LOCKOUT_POLICY, &gp.lockoutPolicy);
   15144 72
   15145 73       // Initialize dictionary attack parameters
   15146 74       DAPreInstall_Init();
   15147 75
   15148 76       // Reset clock
   15149 77       go.clock = 0;
   15150 78       go.clockSafe = YES;
   15151 79       // Update the DRBG state whenever writing orderly state to NV
   15152 80       CryptDrbgGetPutState(GET_STATE);
   15153 81       NvWriteReserved(NV_ORDERLY_DATA, &go);
   15154 82
   15155 83       // Reset counters
   15156 84       gp.resetCount = gr.restartCount = gr.clearCount = 0;
   15157 85       gp.auditCounter = 0;
   15158 86       NvWriteReserved(NV_RESET_COUNT, &gp.resetCount);
   15159 87       NvWriteReserved(NV_AUDIT_COUNTER, &gp.auditCounter);
   15160 88
   15161 89       // orderly state should be cleared because of the update to state clear data
   15162 90       g_clearOrderly = TRUE;
   15163 91
   15164 92       return TPM_RC_SUCCESS;
   15165 93   }
   15166 94   #endif // CC_Clear
   15167 
   15168 
   15169 
   15170 
   15171      Family 2.0                           TCG Published                               Page 329
   15172      Level 00 Revision 01.16           Copyright  TCG 2006-2014                 October 30, 2014
   15173 Part 3: Commands                                                           Trusted Platform Module Library
   15175 
   15176 
   15177 24.7   TPM2_ClearControl
   15178 
   15179 24.7.1 General Description
   15180 
   15181 TPM2_ClearControl() disables and enables the execution of TPM2_Clear().
   15182 The TPM will SET the TPMs TPMA_PERMANENT.disableClear attribute if disable is YES and will
   15183 CLEAR the attribute if disable is NO. When the attribute is SET, TPM2_Clear() may not be executed.
   15184 
   15185 NOTE           This is to simplify the logic of TPM2_Clear(). TPM2_ClearControl() can be called using Platform
   15186                Authorization to CLEAR the disableClear attribute and then execute TPM2_Clear().
   15187 
   15188 Lockout Authorization may be used to SET disableClear but not to CLEAR it.
   15189 Platform Authorization may be used to SET or CLEAR disableClear.
   15190 
   15191 
   15192 
   15193 
   15194 Page 330                                    TCG Published                                       Family 2.0
   15195 October 30, 2014                    Copyright  TCG 2006-2014                     Level 00 Revision 01.16
   15196 Trusted Platform Module Library                                                      Part 3: Commands
   15198 
   15199 
   15200 
   15201 24.7.2 Command and Response
   15202 
   15203                             Table 161  TPM2_ClearControl Command
   15204  Type                         Name                Description
   15205 
   15206  TPMI_ST_COMMAND_TAG          tag                 TPM_ST_SESSIONS
   15207  UINT32                       commandSize
   15208  TPM_CC                       commandCode         TPM_CC_ClearControl {NV}
   15209 
   15210                                                   TPM_RH_LOCKOUT or TPM_RH_PLATFORM+{PP}
   15211  TPMI_RH_CLEAR                @auth               Auth Handle: 1
   15212                                                   Auth Role: USER
   15213 
   15214                                                   YES if the disableOwnerClear flag is to be SET, NO if
   15215  TPMI_YES_NO                  disable
   15216                                                   the flag is to be CLEAR.
   15217 
   15218 
   15219                             Table 162  TPM2_ClearControl Response
   15220  Type                         Name                Description
   15221 
   15222  TPM_ST                       tag                 see clause 6
   15223  UINT32                       responseSize
   15224  TPM_RC                       responseCode
   15225 
   15226 
   15227 
   15228 
   15229 Family 2.0                             TCG Published                                        Page 331
   15230 Level 00 Revision 01.16             Copyright  TCG 2006-2014                        October 30, 2014
   15231      Part 3: Commands                                                      Trusted Platform Module Library
   15233 
   15234 
   15235 
   15236      24.7.3 Detailed Actions
   15237 
   15238 1    #include "InternalRoutines.h"
   15239 2    #include "ClearControl_fp.h"
   15240 3    #ifdef TPM_CC_ClearControl // Conditional expansion of this file
   15241 
   15242 
   15243      Error Returns                   Meaning
   15244 
   15245      TPM_RC_AUTH_FAIL                authorization is not properly given
   15246 
   15247  4   TPM_RC
   15248  5   TPM2_ClearControl(
   15249  6       ClearControl_In       *in                 // IN: input parameter list
   15250  7       )
   15251  8   {
   15252  9       TPM_RC      result;
   15253 10
   15254 11       // The command needs NV update. Check if NV is available.
   15255 12       // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   15256 13       // this point
   15257 14       result = NvIsAvailable();
   15258 15       if(result != TPM_RC_SUCCESS) return result;
   15259 16
   15260 17   // Input Validation
   15261 18
   15262 19       // LockoutAuth may be used to set disableLockoutClear to TRUE but not to FALSE
   15263 20       if(in->auth == TPM_RH_LOCKOUT && in->disable == NO)
   15264 21           return TPM_RC_AUTH_FAIL;
   15265 22
   15266 23   // Internal Data Update
   15267 24
   15268 25       if(in->disable == YES)
   15269 26           gp.disableClear = TRUE;
   15270 27       else
   15271 28           gp.disableClear = FALSE;
   15272 29
   15273 30       // Record the change to NV
   15274 31       NvWriteReserved(NV_DISABLE_CLEAR, &gp.disableClear);
   15275 32
   15276 33       return TPM_RC_SUCCESS;
   15277 34   }
   15278 35   #endif // CC_ClearControl
   15279 
   15280 
   15281 
   15282 
   15283      Page 332                                     TCG Published                              Family 2.0
   15284      October 30, 2014                    Copyright  TCG 2006-2014               Level 00 Revision 01.16
   15285 Trusted Platform Module Library                                                             Part 3: Commands
   15287 
   15288 
   15289 24.8   TPM2_HierarchyChangeAuth
   15290 
   15291 24.8.1 General Description
   15292 
   15293 This command allows the authorization secret for a hierarchy or lockout to be changed using the current
   15294 authorization value as the command authorization.
   15295 If authHandle is TPM_RH_PLATFORM, then platformAuth is changed. If authHandle is
   15296 TPM_RH_OWNER, then ownerAuth is changed. If authHandle is TPM_RH_ENDORSEMENT, then
   15297 endorsementAuth is changed. If authHandle is TPM_RH_LOCKOUT, then lockoutAuth is changed.
   15298 If authHandle is TPM_RH_PLATFORM, then Physical Presence may need to be asserted for this
   15299 command to succeed (see 26.2, TPM2_PP_Commands).
   15300 The authorization value may be no larger than the digest produced by the hash algorithm used for context
   15301 integrity.
   15302 
   15303 EXAMPLE         If SHA384 is used in the computation of the integrity values for saved contexts, then the largest
   15304                 authorization value is 48 octets.
   15305 
   15306 
   15307 
   15308 
   15309 Family 2.0                                  TCG Published                                          Page 333
   15310 Level 00 Revision 01.16               Copyright  TCG 2006-2014                             October 30, 2014
   15311 Part 3: Commands                                                   Trusted Platform Module Library
   15313 
   15314 
   15315 24.8.2 Command and Response
   15316 
   15317                    Table 163  TPM2_HierarchyChangeAuth Command
   15318 Type                     Name                  Description
   15319 
   15320 TPMI_ST_COMMAND_TAG      tag                   TPM_ST_SESSIONS
   15321 UINT32                   commandSize
   15322 TPM_CC                   commandCode           TPM_CC_HierarchyChangeAuth {NV}
   15323 
   15324                                                TPM_RH_LOCKOUT, TPM_RH_ENDORSEMENT,
   15325                                                TPM_RH_OWNER or TPM_RH_PLATFORM+{PP}
   15326 TPMI_RH_HIERARCHY_AUTH   @authHandle
   15327                                                Auth Index: 1
   15328                                                Auth Role: USER
   15329 
   15330 TPM2B_AUTH               newAuth               new authorization value
   15331 
   15332 
   15333                    Table 164  TPM2_HierarchyChangeAuth Response
   15334 Type                     Name                  Description
   15335 
   15336 TPM_ST                   tag                   see clause 6
   15337 UINT32                   responseSize
   15338 TPM_RC                   responseCode
   15339 
   15340 
   15341 
   15342 
   15343 Page 334                                TCG Published                                Family 2.0
   15344 October 30, 2014               Copyright  TCG 2006-2014                 Level 00 Revision 01.16
   15345      Trusted Platform Module Library                                                                Part 3: Commands
   15347 
   15348 
   15349 
   15350      24.8.3 Detailed Actions
   15351 
   15352 1    #include "InternalRoutines.h"
   15353 2    #include "HierarchyChangeAuth_fp.h"
   15354 3    #ifdef TPM_CC_HierarchyChangeAuth // Conditional expansion of this file
   15355 4    #include "Object_spt_fp.h"
   15356 
   15357 
   15358      Error Returns                     Meaning
   15359 
   15360      TPM_RC_SIZE                       newAuth size is greater than that of integrity hash digest
   15361 
   15362  5   TPM_RC
   15363  6   TPM2_HierarchyChangeAuth(
   15364  7       HierarchyChangeAuth_In    *in                    // IN: input parameter list
   15365  8       )
   15366  9   {
   15367 10       TPM_RC       result;
   15368 11
   15369 12       // The command needs NV update. Check if NV is available.
   15370 13       // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   15371 14       // this point
   15372 15       result = NvIsAvailable();
   15373 16       if(result != TPM_RC_SUCCESS) return result;
   15374 17
   15375 18       // Make sure the the auth value is a reasonable size (not larger than
   15376 19       // the size of the digest produced by the integrity hash. The integrity
   15377 20       // hash is assumed to produce the longest digest of any hash implemented
   15378 21       // on the TPM.
   15379 22       if( MemoryRemoveTrailingZeros(&in->newAuth)
   15380 23               > CryptGetHashDigestSize(CONTEXT_INTEGRITY_HASH_ALG))
   15381 24           return TPM_RC_SIZE + RC_HierarchyChangeAuth_newAuth;
   15382 25
   15383 26       // Set hierarchy authValue
   15384 27       switch(in->authHandle)
   15385 28       {
   15386 29       case TPM_RH_OWNER:
   15387 30           gp.ownerAuth = in->newAuth;
   15388 31           NvWriteReserved(NV_OWNER_AUTH, &gp.ownerAuth);
   15389 32           break;
   15390 33       case TPM_RH_ENDORSEMENT:
   15391 34           gp.endorsementAuth = in->newAuth;
   15392 35           NvWriteReserved(NV_ENDORSEMENT_AUTH, &gp.endorsementAuth);
   15393 36           break;
   15394 37       case TPM_RH_PLATFORM:
   15395 38           gc.platformAuth = in->newAuth;
   15396 39           // orderly state should be cleared
   15397 40           g_clearOrderly = TRUE;
   15398 41           break;
   15399 42       case TPM_RH_LOCKOUT:
   15400 43           gp.lockoutAuth = in->newAuth;
   15401 44           NvWriteReserved(NV_LOCKOUT_AUTH, &gp.lockoutAuth);
   15402 45           break;
   15403 46       default:
   15404 47           pAssert(FALSE);
   15405 48           break;
   15406 49       }
   15407 50
   15408 51       return TPM_RC_SUCCESS;
   15409 52   }
   15410 53   #endif // CC_HierarchyChangeAuth
   15411 
   15412 
   15413 
   15414 
   15415      Family 2.0                                   TCG Published                                          Page 335
   15416      Level 00 Revision 01.16               Copyright  TCG 2006-2014                                October 30, 2014
   15417 Part 3: Commands                                                             Trusted Platform Module Library
   15419 
   15420 
   15421 25     Dictionary Attack Functions
   15422 
   15423 25.1    Introduction
   15424 
   15425 A TPM is required to have support for logic that will help prevent a dictionary attack on an authorization
   15426 value. The protection is provided by a counter that increments when a password authorization or an
   15427 HMAC authorization fails. When the counter reaches a predefined value, the TPM will not accept, for
   15428 some time interval, further requests that require authorization and the TPM is in Lockout mode. While the
   15429 TPM is in Lockout mode, the TPM will return TPM_RC_LOCKED if the command requires use of an
   15430 objects or Indexs authValue unless the authorization applies to an entry in the Platform hierarchy.
   15431 
   15432 NOTE            Authorizations for objects and NV Index values in the Platform hierarchy are never locked out.
   15433                 However, a command that requires multiple authorizations will not be accepted when the TPM is in
   15434                 Lockout mode unless all of the authorizations reference objects and indexes in the Platform
   15435                 hierarchy.
   15436 
   15437 If the TPM is continuously powered for the duration of newRecoveryTime and no authorization failures
   15438 occur, the authorization failure counter will be decremented by one. This property is called self-healing.
   15439 Self-healing shall not cause the count of failed attempts to decrement below zero.
   15440 The count of failed attempts, the lockout interval, and self-healing interval are settable using
   15441 TPM2_DictionaryAttackParameters(). The lockout parameters and the current value of the lockout
   15442 counter can be read with TPM2_GetCapability().
   15443 Dictionary attack protection does not apply to an entity associated with a permanent handle (handle type
   15444 == TPM_HT_PERMANENT).
   15445 
   15446 25.2    TPM2_DictionaryAttackLockReset
   15447 
   15448 25.2.1 General Description
   15449 
   15450 This command cancels the effect of a TPM lockout due to a number of successive authorization failures.
   15451 If this command is properly authorized, the lockout counter is set to zero.
   15452 Only one lockoutAuth authorization failure is allowed for this command during a lockoutRecovery interval
   15453 (set using TPM2_DictionaryAttackParameters().
   15454 
   15455 
   15456 
   15457 
   15458 Page 336                                     TCG Published                                        Family 2.0
   15459 October 30, 2014                      Copyright  TCG 2006-2014                    Level 00 Revision 01.16
   15460 Trusted Platform Module Library                                                 Part 3: Commands
   15462 
   15463 
   15464 
   15465 25.2.2 Command and Response
   15466 
   15467                     Table 165  TPM2_DictionaryAttackLockReset Command
   15468  Type                         Name                Description
   15469 
   15470  TPMI_ST_COMMAND_TAG          tag                 TPM_ST_SESSIONS
   15471  UINT32                       commandSize
   15472  TPM_CC                       commandCode         TPM_CC_DictionaryAttackLockReset {NV}
   15473 
   15474                                                   TPM_RH_LOCKOUT
   15475  TPMI_RH_LOCKOUT              @lockHandle         Auth Index: 1
   15476                                                   Auth Role: USER
   15477 
   15478 
   15479                      Table 166  TPM2_DictionaryAttackLockReset Response
   15480  Type                         Name                Description
   15481  TPM_ST                       tag                 see clause 6
   15482  UINT32                       responseSize
   15483  TPM_RC                       responseCode
   15484 
   15485 
   15486 
   15487 
   15488 Family 2.0                             TCG Published                                    Page 337
   15489 Level 00 Revision 01.16             Copyright  TCG 2006-2014                   October 30, 2014
   15490      Part 3: Commands                                                  Trusted Platform Module Library
   15492 
   15493 
   15494 
   15495      25.2.3 Detailed Actions
   15496 
   15497  1   #include "InternalRoutines.h"
   15498  2   #include "DictionaryAttackLockReset_fp.h"
   15499  3   #ifdef TPM_CC_DictionaryAttackLockReset // Conditional expansion of this file
   15500  4   TPM_RC
   15501  5   TPM2_DictionaryAttackLockReset(
   15502  6       DictionaryAttackLockReset_In      *in             // IN: input parameter list
   15503  7       )
   15504  8   {
   15505  9       TPM_RC         result;
   15506 10
   15507 11       // Input parameter is not reference in command action
   15508 12       in = NULL;
   15509 13
   15510 14       // The command needs NV update. Check if NV is available.
   15511 15       // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   15512 16       // this point
   15513 17       result = NvIsAvailable();
   15514 18       if(result != TPM_RC_SUCCESS) return result;
   15515 19
   15516 20   // Internal Data Update
   15517 21
   15518 22       // Set failed tries to 0
   15519 23       gp.failedTries = 0;
   15520 24
   15521 25       // Record the changes to NV
   15522 26       NvWriteReserved(NV_FAILED_TRIES, &gp.failedTries);
   15523 27
   15524 28       return TPM_RC_SUCCESS;
   15525 29   }
   15526 30   #endif // CC_DictionaryAttackLockReset
   15527 
   15528 
   15529 
   15530 
   15531      Page 338                                    TCG Published                           Family 2.0
   15532      October 30, 2014                   Copyright  TCG 2006-2014            Level 00 Revision 01.16
   15533 Trusted Platform Module Library                                                               Part 3: Commands
   15535 
   15536 
   15537 25.3   TPM2_DictionaryAttackParameters
   15538 
   15539 25.3.1 General Description
   15540 
   15541 This command changes the lockout parameters.
   15542 The command requires Lockout Authorization.
   15543 The timeout parameters (newRecoveryTime and lockoutRecovery) indicate values that are measured with
   15544 respect to the Time and not Clock.
   15545 
   15546 NOTE            Use of Time means that the TPM shall be continuously powered for the duration of a timeout.
   15547 
   15548 If newRecoveryTime is zero, then DA protection is disabled. Authorizations are checked but authorization
   15549 failures will not cause the TPM to enter lockout.
   15550 If newMaxTries is zero, the TPM will be in lockout and use of DA protected entities will be disabled.
   15551 If lockoutRecovery is zero, then the recovery interval is a boot cycle (_TPM_Init followed by
   15552 Startup(CLEAR).
   15553 This command will set the authorization failure count (failedTries) to zero.
   15554 Only one lockoutAuth authorization failure is allowed for this command during a lockoutRecovery interval.
   15555 
   15556 
   15557 
   15558 
   15559 Family 2.0                                  TCG Published                                            Page 339
   15560 Level 00 Revision 01.16               Copyright  TCG 2006-2014                               October 30, 2014
   15561 Part 3: Commands                                                    Trusted Platform Module Library
   15563 
   15564 
   15565 
   15566 25.3.2 Command and Response
   15567 
   15568                    Table 167  TPM2_DictionaryAttackParameters Command
   15569  Type                      Name                Description
   15570 
   15571  TPMI_ST_COMMAND_TAG       tag                 TPM_ST_SESSIONS
   15572  UINT32                    commandSize
   15573  TPM_CC                    commandCode         TPM_CC_DictionaryAttackParameters {NV}
   15574 
   15575                                                TPM_RH_LOCKOUT
   15576  TPMI_RH_LOCKOUT           @lockHandle         Auth Index: 1
   15577                                                Auth Role: USER
   15578 
   15579                                                count of authorization failures before the lockout is
   15580  UINT32                    newMaxTries
   15581                                                imposed
   15582                                                time in seconds before the authorization failure count
   15583                                                is automatically decremented
   15584  UINT32                    newRecoveryTime
   15585                                                A value of zero indicates that DA protection is
   15586                                                disabled.
   15587                                                time in seconds after a lockoutAuth failure before use
   15588  UINT32                    lockoutRecovery     of lockoutAuth is allowed
   15589                                                A value of zero indicates that a reboot is required.
   15590 
   15591 
   15592                    Table 168  TPM2_DictionaryAttackParameters Response
   15593  Type                      Name                Description
   15594 
   15595  TPM_ST                    tag                 see clause 6
   15596  UINT32                    responseSize
   15597  TPM_RC                    responseCode
   15598 
   15599 
   15600 
   15601 
   15602 Page 340                              TCG Published                                        Family 2.0
   15603 October 30, 2014                 Copyright  TCG 2006-2014                 Level 00 Revision 01.16
   15604      Trusted Platform Module Library                                              Part 3: Commands
   15606 
   15607 
   15608 
   15609      25.3.3 Detailed Actions
   15610 
   15611  1   #include "InternalRoutines.h"
   15612  2   #include "DictionaryAttackParameters_fp.h"
   15613  3   #ifdef TPM_CC_DictionaryAttackParameters // Conditional expansion of this file
   15614  4   TPM_RC
   15615  5   TPM2_DictionaryAttackParameters(
   15616  6       DictionaryAttackParameters_In    *in             // IN: input parameter list
   15617  7       )
   15618  8   {
   15619  9       TPM_RC           result;
   15620 10
   15621 11       // The command needs NV update. Check if NV is available.
   15622 12       // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   15623 13       // this point
   15624 14       result = NvIsAvailable();
   15625 15       if(result != TPM_RC_SUCCESS) return result;
   15626 16
   15627 17   // Internal Data Update
   15628 18
   15629 19       // Set dictionary attack parameters
   15630 20       gp.maxTries = in->newMaxTries;
   15631 21       gp.recoveryTime = in->newRecoveryTime;
   15632 22       gp.lockoutRecovery = in->lockoutRecovery;
   15633 23
   15634 24       // Set failed tries to 0
   15635 25       gp.failedTries = 0;
   15636 26
   15637 27       // Record the changes to NV
   15638 28       NvWriteReserved(NV_FAILED_TRIES, &gp.failedTries);
   15639 29       NvWriteReserved(NV_MAX_TRIES, &gp.maxTries);
   15640 30       NvWriteReserved(NV_RECOVERY_TIME, &gp.recoveryTime);
   15641 31       NvWriteReserved(NV_LOCKOUT_RECOVERY, &gp.lockoutRecovery);
   15642 32
   15643 33       return TPM_RC_SUCCESS;
   15644 34   }
   15645 35   #endif // CC_DictionaryAttackParameters
   15646 
   15647 
   15648 
   15649 
   15650      Family 2.0                               TCG Published                            Page 341
   15651      Level 00 Revision 01.16           Copyright  TCG 2006-2014                  October 30, 2014
   15652 Part 3: Commands                                                             Trusted Platform Module Library
   15654 
   15655 
   15656 26     Miscellaneous Management Functions
   15657 
   15658 26.1    Introduction
   15659 
   15660 This clause contains commands that do not logically group with any other commands.
   15661 
   15662 26.2    TPM2_PP_Commands
   15663 
   15664 26.2.1 General Description
   15665 
   15666 This command is used to determine which commands require assertion of Physical Presence (PP) in
   15667 addition to platformAuth/platformPolicy.
   15668 This command requires that auth is TPM_RH_PLATFORM and that Physical Presence be asserted.
   15669 After this command executes successfully, the commands listed in setList will be added to the list of
   15670 commands that require that Physical Presence be asserted when the handle associated with the
   15671 authorization is TPM_RH_PLATFORM. The commands in clearList will no longer require assertion of
   15672 Physical Presence in order to authorize a command.
   15673 If a command is not in either list, its state is not changed. If a command is in both lists, then it will no
   15674 longer require Physical Presence (for example, setList is processed first).
   15675 Only commands with               handle types of TPMI_RH_PLATFORM, TPMI_RH_PROVISION,
   15676 TPMI_RH_CLEAR, or TPMI_RH_HIERARCHY can be gated with Physical Presence. If any other
   15677 command is in either list, it is discarded.
   15678 When a command requires that Physical Presence be provided, then Physical Presence shall be
   15679 asserted for either an HMAC or a Policy authorization.
   15680 
   15681 NOTE            Physical Presence may be made a requirement of any policy.
   15682 
   15683 TPM2_PP_Commands() always requires assertion of Physical Presence.
   15684 
   15685 
   15686 
   15687 
   15688 Page 342                                     TCG Published                                     Family 2.0
   15689 October 30, 2014                      Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   15690 Trusted Platform Module Library                                                       Part 3: Commands
   15692 
   15693 
   15694 
   15695 26.2.2 Command and Response
   15696 
   15697                            Table 169  TPM2_PP_Commands Command
   15698  Type                         Name                Description
   15699 
   15700  TPMI_ST_COMMAND_TAG          tag                 TPM_ST_SESSIONS
   15701  UINT32                       commandSize
   15702  TPM_CC                       commandCode         TPM_CC_PP_Commands {NV}
   15703 
   15704                                                   TPM_RH_PLATFORM+PP
   15705  TPMI_RH_PLATFORM             @auth               Auth Index: 1
   15706                                                   Auth Role: USER + Physical Presence
   15707 
   15708                                                   list of commands to be added to those that will require
   15709  TPML_CC                      setList
   15710                                                   that Physical Presence be asserted
   15711                                                   list of commands that will no longer require that
   15712  TPML_CC                      clearList
   15713                                                   Physical Presence be asserted
   15714 
   15715 
   15716                            Table 170  TPM2_PP_Commands Response
   15717  Type                         Name                Description
   15718 
   15719  TPM_ST                       tag                 see clause 6
   15720  UINT32                       responseSize
   15721  TPM_RC                       responseCode
   15722 
   15723 
   15724 
   15725 
   15726 Family 2.0                              TCG Published                                         Page 343
   15727 Level 00 Revision 01.16             Copyright  TCG 2006-2014                         October 30, 2014
   15728      Part 3: Commands                                                  Trusted Platform Module Library
   15730 
   15731 
   15732 
   15733      26.2.3 Detailed Actions
   15734 
   15735  1   #include "InternalRoutines.h"
   15736  2   #include "PP_Commands_fp.h"
   15737  3   #ifdef TPM_CC_PP_Commands // Conditional expansion of this file
   15738  4   TPM_RC
   15739  5   TPM2_PP_Commands(
   15740  6       PP_Commands_In   *in           // IN: input parameter list
   15741  7       )
   15742  8   {
   15743  9       UINT32           i;
   15744 10
   15745 11       TPM_RC      result;
   15746 12
   15747 13       // The command needs NV update. Check if NV is available.
   15748 14       // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   15749 15       // this point
   15750 16       result = NvIsAvailable();
   15751 17       if(result != TPM_RC_SUCCESS) return result;
   15752 18
   15753 19   // Internal Data Update
   15754 20
   15755 21       // Process set list
   15756 22       for(i = 0; i < in->setList.count; i++)
   15757 23           // If command is implemented, set it as PP required. If the input
   15758 24           // command is not a PP command, it will be ignored at
   15759 25           // PhysicalPresenceCommandSet().
   15760 26           if(CommandIsImplemented(in->setList.commandCodes[i]))
   15761 27               PhysicalPresenceCommandSet(in->setList.commandCodes[i]);
   15762 28
   15763 29       // Process clear list
   15764 30       for(i = 0; i < in->clearList.count; i++)
   15765 31           // If command is implemented, clear it as PP required. If the input
   15766 32           // command is not a PP command, it will be ignored at
   15767 33           // PhysicalPresenceCommandClear(). If the input command is
   15768 34           // TPM2_PP_Commands, it will be ignored as well
   15769 35           if(CommandIsImplemented(in->clearList.commandCodes[i]))
   15770 36               PhysicalPresenceCommandClear(in->clearList.commandCodes[i]);
   15771 37
   15772 38       // Save the change of PP list
   15773 39       NvWriteReserved(NV_PP_LIST, &gp.ppList);
   15774 40
   15775 41       return TPM_RC_SUCCESS;
   15776 42   }
   15777 43   #endif // CC_PP_Commands
   15778 
   15779 
   15780 
   15781 
   15782      Page 344                               TCG Published                                Family 2.0
   15783      October 30, 2014                Copyright  TCG 2006-2014              Level 00 Revision 01.16
   15784 Trusted Platform Module Library                                                            Part 3: Commands
   15786 
   15787 
   15788 26.3   TPM2_SetAlgorithmSet
   15789 
   15790 26.3.1 General Description
   15791 
   15792 This command allows the platform to change the set of algorithms that are used by the TPM. The
   15793 algorithmSet setting is a vendor-dependent value.
   15794 If the changing of the algorithm set results in a change of the algorithms of PCR banks, then the TPM will
   15795 need to be reset (_TPM_Init and TPM2_Startup(TPM_SU_CLEAR)) before the new PCR settings take
   15796 effect. After this command executes successfully, if startupType in the next TPM2_Startup() is not
   15797 TPM_SU_CLEAR, the TPM shall return TPM_RC_VALUE and enter Failure mode.
   15798 This command does not change the algorithms available to the platform.
   15799 
   15800 NOTE            The reference implementation does not have support for this command. In particular, it does not
   15801                 support use of this command to selectively disable algorithms. Proper support would require
   15802                 modification of the unmarshaling code so that each time an algorithm is unmarshaled, it would be
   15803                 verified as being enabled.
   15804 
   15805 
   15806 
   15807 
   15808 Family 2.0                                  TCG Published                                          Page 345
   15809 Level 00 Revision 01.16               Copyright  TCG 2006-2014                            October 30, 2014
   15810 Part 3: Commands                                                    Trusted Platform Module Library
   15812 
   15813 
   15814 26.3.2 Command and Response
   15815 
   15816                        Table 171  TPM2_SetAlgorithmSet Command
   15817  Type                     Name                   Description
   15818 
   15819  TPMI_ST_COMMAND_TAG      tag                    TPM_ST_SESSIONS
   15820  UINT32                   commandSize
   15821  TPM_CC                   commandCode            TPM_CC_SetAlgorithmSet {NV}
   15822 
   15823                                                  TPM_RH_PLATFORM
   15824  TPMI_RH_PLATFORM         @authHandle            Auth Index: 1
   15825                                                  Auth Role: USER
   15826 
   15827                                                  a TPM vendor-dependent value indicating the
   15828  UINT32                   algorithmSet
   15829                                                  algorithm set selection
   15830 
   15831 
   15832                        Table 172  TPM2_SetAlgorithmSet Response
   15833  Type                     Name                   Description
   15834 
   15835  TPM_ST                   tag                    see clause 6
   15836  UINT32                   responseSize
   15837  TPM_RC                   responseCode
   15838 
   15839 
   15840 
   15841 
   15842 Page 346                                 TCG Published                                  Family 2.0
   15843 October 30, 2014                Copyright  TCG 2006-2014                 Level 00 Revision 01.16
   15844      Trusted Platform Module Library                                             Part 3: Commands
   15846 
   15847 
   15848 
   15849      26.3.3 Detailed Actions
   15850 
   15851  1   #include "InternalRoutines.h"
   15852  2   #include "SetAlgorithmSet_fp.h"
   15853  3   #ifdef TPM_CC_SetAlgorithmSet // Conditional expansion of this file
   15854  4   TPM_RC
   15855  5   TPM2_SetAlgorithmSet(
   15856  6       SetAlgorithmSet_In     *in            // IN: input parameter list
   15857  7       )
   15858  8   {
   15859  9       TPM_RC       result;
   15860 10
   15861 11       // The command needs NV update. Check if NV is available.
   15862 12       // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   15863 13       // this point
   15864 14       result = NvIsAvailable();
   15865 15       if(result != TPM_RC_SUCCESS) return result;
   15866 16
   15867 17   // Internal Data Update
   15868 18       gp.algorithmSet = in->algorithmSet;
   15869 19
   15870 20       // Write the algorithm set changes to NV
   15871 21       NvWriteReserved(NV_ALGORITHM_SET, &gp.algorithmSet);
   15872 22
   15873 23       return TPM_RC_SUCCESS;
   15874 24   }
   15875 25   #endif // CC_SetAlgorithmSet
   15876 
   15877 
   15878 
   15879 
   15880      Family 2.0                              TCG Published                            Page 347
   15881      Level 00 Revision 01.16           Copyright  TCG 2006-2014                 October 30, 2014
   15882 Part 3: Commands                                                                  Trusted Platform Module Library
   15884 
   15885 
   15886 27     Field Upgrade
   15887 
   15888 27.1     Introduction
   15889 
   15890 This clause contains the commands for managing field upgrade of the firmware in the TPM. The field
   15891 upgrade scheme may be used for replacement or augmentation of the firmware installed in the TPM.
   15892 
   15893 EXAMPLE 1        If an algorithm is found to be flawed, a patch of that algori thm might be installed using the firmware
   15894                  upgrade process. The patch might be a replacement of a portion of the code or a complete
   15895                  replacement of the firmware.
   15896 
   15897 EXAMPLE 2        If an additional set of ECC parameters is needed, the firmware process may be used to add the
   15898                  parameters to the TPM data set.
   15899 
   15900 The     field  upgrade    process     uses    two     commands       (TPM2_FieldUpgradeStart()  and
   15901 TPM2_FieldUpgradeData()). TPM2_FieldUpgradeStart() validates that a signature on the provided digest
   15902 is from the TPM manufacturer and that proper authorization is provided using platformPolicy.
   15903 
   15904 NOTE 1           The platformPolicy for field upgraded is defined by the PM and may include requirements that the
   15905                  upgrade be signed by the PM or the TPM owner and include any other constraints that are desired
   15906                  by the PM.
   15907 
   15908 If the proper authorization is given, the TPM will retain the signed digest and enter the Field Upgrade
   15909 mode (FUM). While in FUM, the TPM will accept TPM2_FieldUpgradeData() commands. It may accept
   15910 other commands if it is able to complete them using the previously installed firmware. Otherwise, it will
   15911 return TPM_RC_UPGRADE.
   15912 Each block of the field upgrade shall contain the digest of the next block of the field upgrade data. That
   15913 digest shall be included in the digest of the previous block. The digest of the first block is signed by the
   15914 TPM manufacturer. That signature and first block digest are the parameters for
   15915 TPM2_FieldUpgradeStart(). The digest is saved in the TPM as the required digest for the next field
   15916 upgrade data block and as the identifier of the field upgrade sequence.
   15917 For each field upgrade data block that is sent to the TPM by TPM2_FieldUpgradeData(), the TPM shall
   15918 validate that the digest matches the required digest and if not, shall return TPM_RC_VALUE. The TPM
   15919 shall extract the digest of the next expected block and return that value to the caller, along with the digest
   15920 of the first data block of the update sequence.
   15921 The system may attempt to abandon the firmware upgrade by using a zero-length buffer in
   15922 TPM2_FieldUpdateData(). If the TPM is able to resume operation using the firmware present when the
   15923 upgrade started, then the TPM will indicate that it has abandon the update by setting the digest of the
   15924 next block to the Empty Buffer. If the TPM cannot abandon the update, it will return the expected next
   15925 digest.
   15926 The system may also attempt to abandon the update because of a power interruption. If the TPM is able
   15927 to resume normal operations, then it will respond normally to TPM2_Startup(). If the TPM is not able to
   15928 resume normal operations, then it will respond to any command but TPM2_FieldUpgradeData() with
   15929 TPM_RC_FIELDUPGRADE.
   15930 After a _TPM_Init, system software may not be able to resume the field upgrade that was in process
   15931 when the power interruption occurred. In such case, the TPM firmware may be reset to one of two other
   15932 values:
   15933         the original firmware that was installed at the factory (initial firmware); or
   15934         the firmware that was in the TPM when the field upgrade process started (previous firmware).
   15935 The TPM retains the digest of the first block for these firmware images and checks to see if the first block
   15936 after _TPM_Init matches either of those digests. If so, the firmware update process restarts and the
   15937 original firmware may be loaded.
   15938 
   15939 
   15940 Page 348                                         TCG Published                                           Family 2.0
   15941 October 30, 2014                        Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   15942 Trusted Platform Module Library                                                                   Part 3: Commands
   15944 
   15945 NOTE 2            The TPM is required to accept the previous firmware as either a vendor-provided update or as
   15946                   recovered from the TPM using TPM2_FirmwareRead().
   15947 
   15948 When the last block of the firmware upgrade is loaded into the TPM (indicated to the TPM by data in the
   15949 data block in a TPM vendor-specific manner), the TPM will complete the upgrade process. If the TPM is
   15950 able to resume normal operations without a reboot, it will set the hash algorithm of the next block to
   15951 TPM_ALG_NULL and return TPM_RC_SUCCESS. If a reboot is required, the TPM shall return
   15952 TPM_RC_REBOOT in response to the last TPM2_FieldUpgradeData() and all subsequent TPM
   15953 commands until a _TPM_Init is received.
   15954 
   15955 NOTE 3            Because no additional data is allowed when the response code is not TPM_RC_SUCCESS, the TPM
   15956                   returns TPM_RC_SUCCESS for all calls to TPM2_FieldUpgradeData() except the last. In this
   15957                   manner, the TPM is able to indicate the digest of the next block. If a _TPM_Init occurs while the
   15958                   TPM is in FUM, the next block may be the digest for the first block of the original firmware. If it is
   15959                   not, then the TPM will not accept the original firmware until the next _TPM_Init when the TPM is in
   15960                   FUM.
   15961 
   15962 During the field upgrade process, either the one specified in this clause or a vendor proprietary field
   15963 upgrade process, the TPM shall preserve:
   15964         Primary Seeds;
   15965         Hierarchy authValue, authPolicy, and proof values;
   15966         Lockout authValue and authorization failure count values;
   15967         PCR authValue and authPolicy values;
   15968         NV Index allocations and contents;
   15969         Persistent object allocations and contents; and
   15970         Clock.
   15971 
   15972 NOTE 4            A platform manufacturer may provide a means to change preserved data to accommodate a case
   15973                   where a field upgrade fixes a flaw that might have compromised TPM secrets.
   15974 
   15975 
   15976 
   15977 
   15978 Family 2.0                                     TCG Published                                              Page 349
   15979 Level 00 Revision 01.16                  Copyright  TCG 2006-2014                                October 30, 2014
   15980 Part 3: Commands                                                               Trusted Platform Module Library
   15982 
   15983 
   15984 27.2   TPM2_FieldUpgradeStart
   15985 
   15986 27.2.1 General Description
   15987 
   15988 This command uses platformPolicy and a TPM Vendor Authorization Key to authorize a Field Upgrade
   15989 Manifest.
   15990 If the signature checks        succeed,     the   authorization   is   valid   and   the   TPM     will   accept
   15991 TPM2_FieldUpgradeData().
   15992 This signature is checked against the loaded key referenced by keyHandle. This key will have a Name
   15993 that is the same as a value that is part of the TPM firmware data. If the signature is not valid, the TPM
   15994 shall return TPM_RC_SIGNATURE.
   15995 
   15996 NOTE            A loaded key is used rather than a hard -coded key to reduce the amount of memory needed for this
   15997                 key data in case more than one vendor key is needed.
   15998 
   15999 
   16000 
   16001 
   16002 Page 350                                      TCG Published                                        Family 2.0
   16003 October 30, 2014                      Copyright  TCG 2006-2014                      Level 00 Revision 01.16
   16004 Trusted Platform Module Library                                                          Part 3: Commands
   16006 
   16007 
   16008 27.2.2 Command and Response
   16009 
   16010                           Table 173  TPM2_FieldUpgradeStart Command
   16011 Type                          Name                  Description
   16012 
   16013 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   16014 UINT32                        commandSize
   16015 TPM_CC                        commandCode           TPM_CC_FieldUpgradeStart
   16016 
   16017                                                     TPM_RH_PLATFORM+{PP}
   16018 TPMI_RH_PLATFORM              @authorization        Auth Index:1
   16019                                                     Auth Role: ADMIN
   16020                                                     handle of a public area that contains the TPM Vendor
   16021                                                     Authorization Key that will be used to validate
   16022 TPMI_DH_OBJECT                keyHandle             manifestSignature
   16023                                                     Auth Index: None
   16024 
   16025 TPM2B_DIGEST                  fuDigest              digest of the first block in the field upgrade sequence
   16026                                                     signature over fuDigest using the key associated with
   16027 TPMT_SIGNATURE                manifestSignature
   16028                                                     keyHandle (not optional)
   16029 
   16030 
   16031                           Table 174  TPM2_FieldUpgradeStart Response
   16032 Type                          Name                  Description
   16033 
   16034 TPM_ST                        tag                   see clause 6
   16035 UINT32                        responseSize
   16036 TPM_RC                        responseCode
   16037 
   16038 
   16039 
   16040 
   16041 Family 2.0                                 TCG Published                                         Page 351
   16042 Level 00 Revision 01.16             Copyright  TCG 2006-2014                            October 30, 2014
   16043      Part 3: Commands                                                 Trusted Platform Module Library
   16045 
   16046 
   16047 
   16048      27.2.3 Detailed Actions
   16049 
   16050  1   #include "InternalRoutines.h"
   16051  2   #include "FieldUpgradeStart_fp.h"
   16052  3   #ifdef TPM_CC_FieldUpgradeStart // Conditional expansion of this file
   16053  4   TPM_RC
   16054  5   TPM2_FieldUpgradeStart(
   16055  6       FieldUpgradeStart_In     *in             // IN: input parameter list
   16056  7       )
   16057  8   {
   16058  9       // Not implemented
   16059 10       UNUSED_PARAMETER(in);
   16060 11       return TPM_RC_SUCCESS;
   16061 12   }
   16062 13   #endif
   16063 
   16064 
   16065 
   16066 
   16067      Page 352                                TCG Published                              Family 2.0
   16068      October 30, 2014                   Copyright  TCG 2006-2014            Level 00 Revision 01.16
   16069 Trusted Platform Module Library                                                     Part 3: Commands
   16071 
   16072 
   16073 27.3   TPM2_FieldUpgradeData
   16074 
   16075 27.3.1 General Description
   16076 
   16077 This command will take the actual field upgrade image to be installed on the TPM. The exact format of
   16078 fuData is vendor-specific. This command is only possible following a successful
   16079 TPM2_FieldUpgradeStart().    If    the    TPM     has    not   received     a   properly  authorized
   16080 TPM2_FieldUpgradeStart(), then the TPM shall return TPM_RC_FIELDUPGRADE.
   16081 The TPM will validate that the digest of fuData matches an expected value. If so, the TPM may buffer or
   16082 immediately apply the update. If the digest of fuData does not match an expected value, the TPM shall
   16083 return TPM_RC_VALUE.
   16084 
   16085 
   16086 
   16087 
   16088 Family 2.0                               TCG Published                                    Page 353
   16089 Level 00 Revision 01.16            Copyright  TCG 2006-2014                        October 30, 2014
   16090 Part 3: Commands                                                    Trusted Platform Module Library
   16092 
   16093 
   16094 
   16095 27.3.2 Command and Response
   16096 
   16097                       Table 175  TPM2_FieldUpgradeData Command
   16098 Type                     Name                  Description
   16099 
   16100                                                TPM_ST_SESSIONS if an audit or decrypt session is
   16101 TPMI_ST_COMMAND_TAG      tag
   16102                                                present; otherwise, TPM_ST_NO_SESSIONS
   16103 UINT32                   commandSize
   16104 TPM_CC                   commandCode           TPM_CC_FieldUpgradeData {NV}
   16105 
   16106 TPM2B_MAX_BUFFER         fuData                field upgrade image data
   16107 
   16108 
   16109                       Table 176  TPM2_FieldUpgradeData Response
   16110 Type                     Name                  Description
   16111 
   16112 TPM_ST                   tag                   see clause 6
   16113 UINT32                   responseSize
   16114 TPM_RC                   responseCode
   16115 
   16116                                                tagged digest of the next block
   16117 TPMT_HA+                 nextDigest
   16118                                                TPM_ALG_NULL if field update is complete
   16119 TPMT_HA                  firstDigest           tagged digest of the first block of the sequence
   16120 
   16121 
   16122 
   16123 
   16124 Page 354                                TCG Published                                     Family 2.0
   16125 October 30, 2014               Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   16126      Trusted Platform Module Library                                                Part 3: Commands
   16128 
   16129 
   16130 
   16131      27.3.3 Detailed Actions
   16132 
   16133  1   #include "InternalRoutines.h"
   16134  2   #include "FieldUpgradeData_fp.h"
   16135  3   #ifdef TPM_CC_FieldUpgradeData // Conditional expansion of this file
   16136  4   TPM_RC
   16137  5   TPM2_FieldUpgradeData(
   16138  6       FieldUpgradeData_In       *in,             // IN: input parameter list
   16139  7       FieldUpgradeData_Out      *out             // OUT: output parameter list
   16140  8       )
   16141  9   {
   16142 10       // Not implemented
   16143 11       UNUSED_PARAMETER(in);
   16144 12       UNUSED_PARAMETER(out);
   16145 13       return TPM_RC_SUCCESS;
   16146 14   }
   16147 15   #endif
   16148 
   16149 
   16150 
   16151 
   16152      Family 2.0                              TCG Published                               Page 355
   16153      Level 00 Revision 01.16              Copyright  TCG 2006-2014                 October 30, 2014
   16154 Part 3: Commands                                                              Trusted Platform Module Library
   16156 
   16157 
   16158 27.4     TPM2_FirmwareRead
   16159 
   16160 27.4.1 General Description
   16161 
   16162 This command is used to read a copy of the current firmware installed in the TPM.
   16163 The presumption is that the data will be returned in reverse order so that the last block in the sequence
   16164 would be the first block given to the TPM in case of a failure recovery. If the TPM2_FirmwareRead
   16165 sequence completes successfully, then the data provided from the TPM will be sufficient to allow the TPM
   16166 to recover from an abandoned upgrade of this firmware.
   16167 To start the sequence of retrieving the data, the caller sets sequenceNumber to zero. When the TPM has
   16168 returned all the firmware data, the TPM will return the Empty Buffer as fuData.
   16169 The contents of fuData are opaque to the caller.
   16170 
   16171 NOTE 1          The caller should retain the ordering of the update blocks so that the blocks sent to the TPM have
   16172                 the same size and inverse order as the blocks returned by a sequence of calls to this command.
   16173 
   16174 NOTE 2          Support for this command is optional even if the TPM implements TPM2_FieldUpgradeStart() a nd
   16175                 TPM2_FieldUpgradeData().
   16176 
   16177 
   16178 
   16179 
   16180 Page 356                                      TCG Published                                        Family 2.0
   16181 October 30, 2014                      Copyright  TCG 2006-2014                      Level 00 Revision 01.16
   16182 Trusted Platform Module Library                                                         Part 3: Commands
   16184 
   16185 
   16186 27.4.2 Command and Response
   16187 
   16188                            Table 177  TPM2_FirmwareRead Command
   16189 Type                          Name                  Description
   16190 
   16191                                                     TPM_ST_SESSIONS if an audit or encrypt session is
   16192 TPMI_ST_COMMAND_TAG           tag
   16193                                                     present; otherwise, TPM_ST_NO_SESSIONS
   16194 UINT32                        commandSize
   16195 TPM_CC                        commandCode           TPM_CC_FirmwareRead
   16196 
   16197                                                     the number of previous calls to this command in this
   16198 UINT32                        sequenceNumber        sequence
   16199                                                     set to 0 on the first call
   16200 
   16201 
   16202                            Table 178  TPM2_FirmwareRead Response
   16203 Type                          Name                  Description
   16204 
   16205 TPM_ST                        tag                   see clause 6
   16206 UINT32                        responseSize
   16207 TPM_RC                        responseCode
   16208 
   16209 TPM2B_MAX_BUFFER              fuData                field upgrade image data
   16210 
   16211 
   16212 
   16213 
   16214 Family 2.0                                 TCG Published                                       Page 357
   16215 Level 00 Revision 01.16             Copyright  TCG 2006-2014                           October 30, 2014
   16216      Part 3: Commands                                               Trusted Platform Module Library
   16218 
   16219 
   16220 
   16221      27.4.3 Detailed Actions
   16222 
   16223  1   #include "InternalRoutines.h"
   16224  2   #include "FirmwareRead_fp.h"
   16225  3   #ifdef TPM_CC_FirmwareRead // Conditional expansion of this file
   16226  4   TPM_RC
   16227  5   TPM2_FirmwareRead(
   16228  6       FirmwareRead_In    *in,            // IN: input parameter list
   16229  7       FirmwareRead_Out   *out            // OUT: output parameter list
   16230  8       )
   16231  9   {
   16232 10       // Not implemented
   16233 11       UNUSED_PARAMETER(in);
   16234 12       UNUSED_PARAMETER(out);
   16235 13       return TPM_RC_SUCCESS;
   16236 14   }
   16237 15   #endif // CC_FirmwareRead
   16238 
   16239 
   16240 
   16241 
   16242      Page 358                              TCG Published                               Family 2.0
   16243      October 30, 2014                Copyright  TCG 2006-2014              Level 00 Revision 01.16
   16244 Trusted Platform Module Library                                                                Part 3: Commands
   16246 
   16247 
   16248 28     Context Management
   16249 
   16250 28.1    Introduction
   16251 
   16252 Three of the commands in this clause (TPM2_ContextSave(), TPM2_ContextLoad(), and
   16253 TPM2_FlushContext()) implement the resource management described in the "Context Management"
   16254 clause in TPM 2.0 Part 1.
   16255 The fourth command in this clause (TPM2_EvictControl()) is used to control the persistence of loadable
   16256 objects in TPM memory. Background for this command may be found in the "Owner and Platform Evict
   16257 Objects" clause in TPM 2.0 Part 1.
   16258 
   16259 28.2    TPM2_ContextSave
   16260 
   16261 28.2.1 General Description
   16262 
   16263 This command saves a session context, object context, or sequence object context outside the TPM.
   16264 No authorization sessions of any type are allowed with this command and tag is required to be
   16265 TPM_ST_NO_SESSIONS.
   16266 
   16267 NOTE            This preclusion avoids complex issues of dealing with the same session in handle and in the session
   16268                 area. While it might be possible to provide specificity, it would add unnecessary complexity to the
   16269                 TPM and, because this capability would provide no application benefit, use of authorization sessions
   16270                 for audit or encryption is prohibited.
   16271 
   16272 The TPM shall encrypt and integrity protect the TPM2B_CONTEXT_SENSITIVE context as described in
   16273 the "Context Protection" clause in TPM 2.0 Part 1.
   16274 See the Context Data clause in TPM 2.0 Part 2 for a description of the context structure in the response.
   16275 
   16276 
   16277 
   16278 
   16279 Family 2.0                                   TCG Published                                            Page 359
   16280 Level 00 Revision 01.16                Copyright  TCG 2006-2014                              October 30, 2014
   16281 Part 3: Commands                                                 Trusted Platform Module Library
   16283 
   16284 
   16285 
   16286 28.2.2 Command and Response
   16287 
   16288                        Table 179  TPM2_ContextSave Command
   16289  Type                   Name                 Description
   16290 
   16291  TPMI_ST_COMMAND_TAG    tag                  TPM_ST_NO_SESSIONS
   16292  UINT32                 commandSize
   16293  TPM_CC                 commandCode          TPM_CC_ContextSave
   16294 
   16295                                              handle of the resource to save
   16296  TPMI_DH_CONTEXT        saveHandle
   16297                                              Auth Index: None
   16298 
   16299 
   16300                        Table 180  TPM2_ContextSave Response
   16301  Type                   Name                 Description
   16302 
   16303  TPM_ST                 tag                  see clause 6
   16304  UINT32                 responseSize
   16305  TPM_RC                 responseCode
   16306 
   16307  TPMS_CONTEXT           context
   16308 
   16309 
   16310 
   16311 
   16312 Page 360                             TCG Published                                 Family 2.0
   16313 October 30, 2014              Copyright  TCG 2006-2014                Level 00 Revision 01.16
   16314      Trusted Platform Module Library                                                           Part 3: Commands
   16316 
   16317 
   16318 
   16319      28.2.3 Detailed Actions
   16320 
   16321 1    #include "InternalRoutines.h"
   16322 2    #include "ContextSave_fp.h"
   16323 3    #ifdef TPM_CC_ContextSave // Conditional expansion of this file
   16324 4    #include "Context_spt_fp.h"
   16325 
   16326 
   16327      Error Returns                     Meaning
   16328 
   16329      TPM_RC_CONTEXT_GAP                a contextID could not be assigned for a session context save
   16330      TPM_RC_TOO_MANY_CONTEXTS          no more contexts can be saved as the counter has maxed out
   16331 
   16332  5   TPM_RC
   16333  6   TPM2_ContextSave(
   16334  7       ContextSave_In        *in,              // IN: input parameter list
   16335  8       ContextSave_Out       *out              // OUT: output parameter list
   16336  9       )
   16337 10   {
   16338 11       TPM_RC            result;
   16339 12       UINT16            fingerprintSize;      // The size of fingerprint in context
   16340 13       // blob.
   16341 14       UINT64            contextID = 0;        // session context ID
   16342 15       TPM2B_SYM_KEY     symKey;
   16343 16       TPM2B_IV          iv;
   16344 17
   16345 18       TPM2B_DIGEST      integrity;
   16346 19       UINT16            integritySize;
   16347 20       BYTE              *buffer;
   16348 21
   16349 22       // This command may cause the orderlyState to be cleared due to
   16350 23       // the update of state reset data. If this is the case, check if NV is
   16351 24       // available first
   16352 25       if(gp.orderlyState != SHUTDOWN_NONE)
   16353 26       {
   16354 27           // The command needs NV update. Check if NV is available.
   16355 28           // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   16356 29           // this point
   16357 30           result = NvIsAvailable();
   16358 31           if(result != TPM_RC_SUCCESS) return result;
   16359 32       }
   16360 33
   16361 34   // Internal Data Update
   16362 35
   16363 36       // Initialize output handle. At the end of command action, the output
   16364 37       // handle of an object will be replaced, while the output handle
   16365 38       // for a session will be the same as input
   16366 39       out->context.savedHandle = in->saveHandle;
   16367 40
   16368 41       // Get the size of fingerprint in context blob. The sequence value in
   16369 42       // TPMS_CONTEXT structure is used as the fingerprint
   16370 43       fingerprintSize = sizeof(out->context.sequence);
   16371 44
   16372 45       // Compute the integrity size at the beginning of context blob
   16373 46       integritySize = sizeof(integrity.t.size)
   16374 47                       + CryptGetHashDigestSize(CONTEXT_INTEGRITY_HASH_ALG);
   16375 48
   16376 49       // Perform object or session specific context save
   16377 50       switch(HandleGetType(in->saveHandle))
   16378 51       {
   16379 52       case TPM_HT_TRANSIENT:
   16380 53       {
   16381 54           OBJECT          *object = ObjectGet(in->saveHandle);
   16382 
   16383      Family 2.0                               TCG Published                                         Page 361
   16384      Level 00 Revision 01.16            Copyright  TCG 2006-2014                              October 30, 2014
   16385       Part 3: Commands                                                  Trusted Platform Module Library
   16387 
   16388  55          OBJECT         *outObject =
   16389  56                                 (OBJECT *)(out->context.contextBlob.t.buffer
   16390  57                                             + integritySize + fingerprintSize);
   16391  58
   16392  59          // Set size of the context data. The contents of context blob is vendor
   16393  60          // defined. In this implementation, the size is size of integrity
   16394  61          // plus fingerprint plus the whole internal OBJECT structure
   16395  62          out->context.contextBlob.t.size = integritySize +
   16396  63                                            fingerprintSize + sizeof(OBJECT);
   16397  64          // Make sure things fit
   16398  65          pAssert(out->context.contextBlob.t.size
   16399  66                  < sizeof(out->context.contextBlob.t.buffer));
   16400  67
   16401  68          // Copy the whole internal OBJECT structure to context blob, leave
   16402  69          // the size for fingerprint
   16403  70          *outObject = *object;
   16404  71
   16405  72          // Increment object context ID
   16406  73          gr.objectContextID++;
   16407  74          // If object context ID overflows, TPM should be put in failure mode
   16408  75          if(gr.objectContextID == 0)
   16409  76              FAIL(FATAL_ERROR_INTERNAL);
   16410  77
   16411  78          // Fill in other return values for an object.
   16412  79          out->context.sequence = gr.objectContextID;
   16413  80          // For regular object, savedHandle is 0x80000000. For sequence object,
   16414  81          // savedHandle is 0x80000001. For object with stClear, savedHandle
   16415  82          // is 0x80000002
   16416  83          if(ObjectIsSequence(object))
   16417  84          {
   16418  85              out->context.savedHandle = 0x80000001;
   16419  86              SequenceDataImportExport(object, outObject, EXPORT_STATE);
   16420  87          }
   16421  88          else if(object->attributes.stClear == SET)
   16422  89          {
   16423  90              out->context.savedHandle = 0x80000002;
   16424  91          }
   16425  92          else
   16426  93          {
   16427  94              out->context.savedHandle = 0x80000000;
   16428  95          }
   16429  96
   16430  97          // Get object hierarchy
   16431  98          out->context.hierarchy = ObjectDataGetHierarchy(object);
   16432  99
   16433 100          break;
   16434 101      }
   16435 102      case TPM_HT_HMAC_SESSION:
   16436 103      case TPM_HT_POLICY_SESSION:
   16437 104      {
   16438 105          SESSION         *session = SessionGet(in->saveHandle);
   16439 106
   16440 107          // Set size of the context data. The contents of context blob is vendor
   16441 108          // defined. In this implementation, the size of context blob is the
   16442 109          // size of a internal session structure plus the size of
   16443 110          // fingerprint plus the size of integrity
   16444 111          out->context.contextBlob.t.size = integritySize +
   16445 112                                            fingerprintSize + sizeof(*session);
   16446 113
   16447 114          // Make sure things fit
   16448 115          pAssert(out->context.contextBlob.t.size
   16449 116                  < sizeof(out->context.contextBlob.t.buffer));
   16450 117
   16451 118          // Copy the whole internal SESSION structure to context blob.
   16452 119          // Save space for fingerprint at the beginning of the buffer
   16453 120          // This is done before anything else so that the actual context
   16454 
   16455       Page 362                              TCG Published                                 Family 2.0
   16456       October 30, 2014               Copyright  TCG 2006-2014               Level 00 Revision 01.16
   16457       Trusted Platform Module Library                                               Part 3: Commands
   16459 
   16460 121           // can be reclaimed after this call
   16461 122           MemoryCopy(out->context.contextBlob.t.buffer
   16462 123                      + integritySize + fingerprintSize,
   16463 124                      session, sizeof(*session),
   16464 125                      sizeof(out->context.contextBlob.t.buffer)
   16465 126                               - integritySize - fingerprintSize);
   16466 127
   16467 128           // Fill in the other return parameters for a session
   16468 129           // Get a context ID and set the session tracking values appropriately
   16469 130           // TPM_RC_CONTEXT_GAP is a possible error.
   16470 131           // SessionContextSave() will flush the in-memory context
   16471 132           // so no additional errors may occur after this call.
   16472 133           result = SessionContextSave(out->context.savedHandle, &contextID);
   16473 134           if(result != TPM_RC_SUCCESS) return result;
   16474 135
   16475 136           // sequence number is the current session contextID
   16476 137           out->context.sequence = contextID;
   16477 138
   16478 139           // use TPM_RH_NULL as hierarchy for session context
   16479 140           out->context.hierarchy = TPM_RH_NULL;
   16480 141
   16481 142           break;
   16482 143       }
   16483 144       default:
   16484 145           // SaveContext may only take an object handle or a session handle.
   16485 146           // All the other handle type should be filtered out at unmarshal
   16486 147           pAssert(FALSE);
   16487 148           break;
   16488 149       }
   16489 150
   16490 151       // Save fingerprint at the beginning of encrypted area of context blob.
   16491 152       // Reserve the integrity space
   16492 153       MemoryCopy(out->context.contextBlob.t.buffer + integritySize,
   16493 154                  &out->context.sequence, sizeof(out->context.sequence),
   16494 155                  sizeof(out->context.contextBlob.t.buffer) - integritySize);
   16495 156
   16496 157       // Compute context encryption key
   16497 158       ComputeContextProtectionKey(&out->context, &symKey, &iv);
   16498 159
   16499 160       // Encrypt context blob
   16500 161       CryptSymmetricEncrypt(out->context.contextBlob.t.buffer + integritySize,
   16501 162                             CONTEXT_ENCRYPT_ALG, CONTEXT_ENCRYPT_KEY_BITS,
   16502 163                             TPM_ALG_CFB, symKey.t.buffer, &iv,
   16503 164                             out->context.contextBlob.t.size - integritySize,
   16504 165                             out->context.contextBlob.t.buffer + integritySize);
   16505 166
   16506 167       // Compute integrity hash for the object
   16507 168       // In this implementation, the same routine is used for both sessions
   16508 169       // and objects.
   16509 170       ComputeContextIntegrity(&out->context, &integrity);
   16510 171
   16511 172       // add integrity at the beginning of context blob
   16512 173       buffer = out->context.contextBlob.t.buffer;
   16513 174       TPM2B_DIGEST_Marshal(&integrity, &buffer, NULL);
   16514 175
   16515 176       // orderly state should be cleared because of the update of state reset and
   16516 177       // state clear data
   16517 178       g_clearOrderly = TRUE;
   16518 179
   16519 180       return TPM_RC_SUCCESS;
   16520 181   }
   16521 182   #endif // CC_ContextSave
   16522 
   16523 
   16524 
   16525 
   16526       Family 2.0                           TCG Published                                 Page 363
   16527       Level 00 Revision 01.16           Copyright  TCG 2006-2014                   October 30, 2014
   16528 Part 3: Commands                                                              Trusted Platform Module Library
   16530 
   16531 
   16532 28.3   TPM2_ContextLoad
   16533 
   16534 28.3.1 General Description
   16535 
   16536 This command is used to reload a context that has been saved by TPM2_ContextSave().
   16537 No authorization sessions of any type are allowed with this command and tag is required to be
   16538 TPM_ST_NO_SESSIONS (see note in 28.2.1).
   16539 The TPM will return TPM_RC_HIERARCHY if the context is associated with a hierarchy that is disabled.
   16540 
   16541 NOTE            Contexts for authorization sessions and for sequence objects belong to the NULL hierarchy which is
   16542                 never disabled.
   16543 
   16544 See the Context Data clause in TPM 2.0 Part 2 for a description of the values in the context parameter.
   16545 If the integrity HMAC of the saved context is not valid, the TPM shall return TPM_RC_INTEGRITY.
   16546 The TPM shall perform a check on the decrypted context as described in the "Context Confidentiality
   16547 Protections" clause of TPM 2.0 Part 1 and enter failure mode if the check fails.
   16548 
   16549 
   16550 
   16551 
   16552 Page 364                                      TCG Published                                         Family 2.0
   16553 October 30, 2014                      Copyright  TCG 2006-2014                      Level 00 Revision 01.16
   16554 Trusted Platform Module Library                                                      Part 3: Commands
   16556 
   16557 
   16558 
   16559 28.3.2 Command and Response
   16560 
   16561                             Table 181  TPM2_ContextLoad Command
   16562  Type                         Name                Description
   16563 
   16564  TPMI_ST_COMMAND_TAG          tag                 TPM_ST_NO_SESSIONS
   16565  UINT32                       commandSize
   16566  TPM_CC                       commandCode         TPM_CC_ContextLoad
   16567 
   16568  TPMS_CONTEXT                 context             the context blob
   16569 
   16570 
   16571                             Table 182  TPM2_ContextLoad Response
   16572  Type                         Name                Description
   16573 
   16574  TPM_ST                       tag                 see clause 6
   16575  UINT32                       responseSize
   16576  TPM_RC                       responseCode
   16577 
   16578                                                   the handle assigned to the resource after it has been
   16579  TPMI_DH_CONTEXT              loadedHandle
   16580                                                   successfully loaded
   16581 
   16582 
   16583 
   16584 
   16585 Family 2.0                             TCG Published                                         Page 365
   16586 Level 00 Revision 01.16             Copyright  TCG 2006-2014                        October 30, 2014
   16587      Part 3: Commands                                                             Trusted Platform Module Library
   16589 
   16590 
   16591 
   16592      28.3.3 Detailed Actions
   16593 
   16594 1    #include "InternalRoutines.h"
   16595 2    #include "ContextLoad_fp.h"
   16596 3    #ifdef TPM_CC_ContextLoad // Conditional expansion of this file
   16597 4    #include "Context_spt_fp.h"
   16598 
   16599 
   16600      Error Returns                 Meaning
   16601 
   16602      TPM_RC_CONTEXT_GAP            there is only one available slot and this is not the oldest saved
   16603                                    session context
   16604      TPM_RC_HANDLE                 'context. savedHandle' does not reference a saved session
   16605      TPM_RC_HIERARCHY              'context.hierarchy' is disabled
   16606      TPM_RC_INTEGRITY              context integrity check fail
   16607      TPM_RC_OBJECT_MEMORY          no free slot for an object
   16608      TPM_RC_SESSION_MEMORY         no free session slots
   16609      TPM_RC_SIZE                   incorrect context blob size
   16610 
   16611  5   TPM_RC
   16612  6   TPM2_ContextLoad(
   16613  7       ContextLoad_In     *in,                  // IN: input parameter list
   16614  8       ContextLoad_Out    *out                  // OUT: output parameter list
   16615  9       )
   16616 10   {
   16617 11   // Local Variables
   16618 12       TPM_RC      result = TPM_RC_SUCCESS;
   16619 13
   16620 14       TPM2B_DIGEST       integrityToCompare;
   16621 15       TPM2B_DIGEST       integrity;
   16622 16       UINT16             integritySize;
   16623 17       UINT64             fingerprint;
   16624 18       BYTE               *buffer;
   16625 19       INT32              size;
   16626 20
   16627 21       TPM_HT             handleType;
   16628 22       TPM2B_SYM_KEY      symKey;
   16629 23       TPM2B_IV           iv;
   16630 24
   16631 25   // Input Validation
   16632 26
   16633 27       // Check context blob size
   16634 28       handleType = HandleGetType(in->context.savedHandle);
   16635 29
   16636 30       // Check integrity
   16637 31       // In this implementation, the same routine is used for both sessions
   16638 32       // and objects.
   16639 33       integritySize = CryptGetHashDigestSize(CONTEXT_INTEGRITY_HASH_ALG);
   16640 34
   16641 35       // Get integrity from context blob
   16642 36       buffer = in->context.contextBlob.t.buffer;
   16643 37       size = (INT32) in->context.contextBlob.t.size;
   16644 38       result = TPM2B_DIGEST_Unmarshal(&integrity, &buffer, &size);
   16645 39       if(result != TPM_RC_SUCCESS)
   16646 40           return result;
   16647 41       if(integrity.t.size != integritySize)
   16648 42           return TPM_RC_SIZE;
   16649 43
   16650 44       integritySize += sizeof(integrity.t.size);
   16651 
   16652 
   16653      Page 366                                    TCG Published                                         Family 2.0
   16654      October 30, 2014                   Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   16655       Trusted Platform Module Library                                                Part 3: Commands
   16657 
   16658  45
   16659  46       // Compute context integrity
   16660  47       ComputeContextIntegrity(&in->context, &integrityToCompare);
   16661  48
   16662  49       // Compare integrity
   16663  50       if(!Memory2BEqual(&integrity.b, &integrityToCompare.b))
   16664  51           return TPM_RC_INTEGRITY + RC_ContextLoad_context;
   16665  52
   16666  53       // Compute context encryption key
   16667  54       ComputeContextProtectionKey(&in->context, &symKey, &iv);
   16668  55
   16669  56       // Decrypt context data in place
   16670  57       CryptSymmetricDecrypt(in->context.contextBlob.t.buffer + integritySize,
   16671  58                             CONTEXT_ENCRYPT_ALG, CONTEXT_ENCRYPT_KEY_BITS,
   16672  59                             TPM_ALG_CFB, symKey.t.buffer, &iv,
   16673  60                             in->context.contextBlob.t.size - integritySize,
   16674  61                             in->context.contextBlob.t.buffer + integritySize);
   16675  62
   16676  63       // Read the fingerprint value, skip the leading integrity size
   16677  64       MemoryCopy(&fingerprint, in->context.contextBlob.t.buffer + integritySize,
   16678  65                  sizeof(fingerprint), sizeof(fingerprint));
   16679  66       // Check fingerprint. If the check fails, TPM should be put to failure mode
   16680  67       if(fingerprint != in->context.sequence)
   16681  68           FAIL(FATAL_ERROR_INTERNAL);
   16682  69
   16683  70       // Perform object or session specific input check
   16684  71       switch(handleType)
   16685  72       {
   16686  73       case TPM_HT_TRANSIENT:
   16687  74       {
   16688  75           // Get a pointer to the object in the context blob
   16689  76           OBJECT      *outObject = (OBJECT *)(in->context.contextBlob.t.buffer
   16690  77                                   + integritySize + sizeof(fingerprint));
   16691  78
   16692  79           // Discard any changes to the handle that the TRM might have made
   16693  80           in->context.savedHandle = TRANSIENT_FIRST;
   16694  81
   16695  82           // If hierarchy is disabled, no object context can be loaded in this
   16696  83           // hierarchy
   16697  84           if(!HierarchyIsEnabled(in->context.hierarchy))
   16698  85               return TPM_RC_HIERARCHY + RC_ContextLoad_context;
   16699  86
   16700  87           // Restore object. A TPM_RC_OBJECT_MEMORY error may be returned at
   16701  88           // this point
   16702  89           result = ObjectContextLoad(outObject, &out->loadedHandle);
   16703  90           if(result != TPM_RC_SUCCESS)
   16704  91               return result;
   16705  92
   16706  93           // If this is a sequence object, the crypto library may need to
   16707  94           // reformat the data into an internal format
   16708  95           if(ObjectIsSequence(outObject))
   16709  96               SequenceDataImportExport(ObjectGet(out->loadedHandle),
   16710  97                                        outObject, IMPORT_STATE);
   16711  98
   16712  99           break;
   16713 100       }
   16714 101       case TPM_HT_POLICY_SESSION:
   16715 102       case TPM_HT_HMAC_SESSION:
   16716 103       {
   16717 104
   16718 105           SESSION      *session = (SESSION *)(in->context.contextBlob.t.buffer
   16719 106                                            + integritySize + sizeof(fingerprint));
   16720 107
   16721 108           // This command may cause the orderlyState to be cleared due to
   16722 109           // the update of state reset data. If this is the case, check if NV is
   16723 110           // available first
   16724 
   16725       Family 2.0                            TCG Published                                 Page 367
   16726       Level 00 Revision 01.16           Copyright  TCG 2006-2014                    October 30, 2014
   16727       Part 3: Commands                                                  Trusted Platform Module Library
   16729 
   16730 111          if(gp.orderlyState != SHUTDOWN_NONE)
   16731 112          {
   16732 113              // The command needs NV update. Check if NV is available.
   16733 114              // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned
   16734 115              // at this point
   16735 116              result = NvIsAvailable();
   16736 117              if(result != TPM_RC_SUCCESS)
   16737 118                  return result;
   16738 119          }
   16739 120
   16740 121          // Check if input handle points to a valid saved session
   16741 122          if(!SessionIsSaved(in->context.savedHandle))
   16742 123              return TPM_RC_HANDLE + RC_ContextLoad_context;
   16743 124
   16744 125          // Restore session. A TPM_RC_SESSION_MEMORY, TPM_RC_CONTEXT_GAP error
   16745 126          // may be returned at this point
   16746 127          result = SessionContextLoad(session, &in->context.savedHandle);
   16747 128          if(result != TPM_RC_SUCCESS)
   16748 129              return result;
   16749 130
   16750 131          out->loadedHandle = in->context.savedHandle;
   16751 132
   16752 133          // orderly state should be cleared because of the update of state
   16753 134          // reset and state clear data
   16754 135          g_clearOrderly = TRUE;
   16755 136
   16756 137          break;
   16757 138      }
   16758 139      default:
   16759 140          // Context blob may only have an object handle or a session handle.
   16760 141          // All the other handle type should be filtered out at unmarshal
   16761 142          pAssert(FALSE);
   16762 143          break;
   16763 144      }
   16764 145
   16765 146       return TPM_RC_SUCCESS;
   16766 147   }
   16767 148   #endif // CC_ContextLoad
   16768 
   16769 
   16770 
   16771 
   16772       Page 368                              TCG Published                                 Family 2.0
   16773       October 30, 2014               Copyright  TCG 2006-2014               Level 00 Revision 01.16
   16774 Trusted Platform Module Library                                                            Part 3: Commands
   16776 
   16777 
   16778 28.4   TPM2_FlushContext
   16779 
   16780 28.4.1 General Description
   16781 
   16782 This command causes all context associated with a loaded object or session to be removed from TPM
   16783 memory.
   16784 This command may not be used to remove a persistent object from the TPM.
   16785 A session does not have to be loaded in TPM memory to have its context flushed. The saved session
   16786 context associated with the indicated handle is invalidated.
   16787 No sessions of any type are allowed with               this   command    and    tag   is    required   to   be
   16788 TPM_ST_NO_SESSIONS (see note in 28.2.1).
   16789 If the handle is for a transient object and the handle is not associated with a loaded object, then the TPM
   16790 shall return TPM_RC_HANDLE.
   16791 If the handle is for an authorization session and the handle does not reference a loaded or active session,
   16792 then the TPM shall return TPM_RC_HANDLE.
   16793 NOTE flushHandle is a parameter and not a handle. If it were in the handle area, the TPM would
   16794 validate that the context for the referenced entity is in the TPM. When a TPM2_FlushContext references a
   16795 saved session context, it is not necessary for the context to be in the TPM. When the flushHandle is in
   16796 the parameter area, the TPM does not validate that associated context is actually in the TPM.
   16797 
   16798 
   16799 
   16800 
   16801 Family 2.0                                TCG Published                                         Page 369
   16802 Level 00 Revision 01.16              Copyright  TCG 2006-2014                             October 30, 2014
   16803 Part 3: Commands                                                     Trusted Platform Module Library
   16805 
   16806 
   16807 
   16808 28.4.2 Command and Response
   16809 
   16810                        Table 183  TPM2_FlushContext Command
   16811  Type                    Name                  Description
   16812 
   16813  TPMI_ST_COMMAND_TAG     tag                   TPM_ST_NO_SESSIONS
   16814  UINT32                  commandSize
   16815  TPM_CC                  commandCode           TPM_CC_FlushContext
   16816 
   16817                                                the handle of the item to flush
   16818  TPMI_DH_CONTEXT         flushHandle
   16819                                                NOTE        This is a use of a handle as a parameter.
   16820 
   16821 
   16822                        Table 184  TPM2_FlushContext Response
   16823  Type                    Name                  Description
   16824 
   16825  TPM_ST                  tag                   see clause 6
   16826  UINT32                  responseSize
   16827  TPM_RC                  responseCode
   16828 
   16829 
   16830 
   16831 
   16832 Page 370                               TCG Published                                         Family 2.0
   16833 October 30, 2014               Copyright  TCG 2006-2014                    Level 00 Revision 01.16
   16834      Trusted Platform Module Library                                                               Part 3: Commands
   16836 
   16837 
   16838 
   16839      28.4.3 Detailed Actions
   16840 
   16841 1    #include "InternalRoutines.h"
   16842 2    #include "FlushContext_fp.h"
   16843 3    #ifdef TPM_CC_FlushContext // Conditional expansion of this file
   16844 
   16845 
   16846      Error Returns                     Meaning
   16847 
   16848      TPM_RC_HANDLE                     flushHandle does not reference a loaded object or session
   16849 
   16850  4   TPM_RC
   16851  5   TPM2_FlushContext(
   16852  6       FlushContext_In       *in                  // IN: input parameter list
   16853  7       )
   16854  8   {
   16855  9   // Internal Data Update
   16856 10
   16857 11       // Call object or session specific routine to flush
   16858 12       switch(HandleGetType(in->flushHandle))
   16859 13       {
   16860 14       case TPM_HT_TRANSIENT:
   16861 15           if(!ObjectIsPresent(in->flushHandle))
   16862 16               return TPM_RC_HANDLE;
   16863 17           // Flush object
   16864 18           ObjectFlush(in->flushHandle);
   16865 19           break;
   16866 20       case TPM_HT_HMAC_SESSION:
   16867 21       case TPM_HT_POLICY_SESSION:
   16868 22           if(   !SessionIsLoaded(in->flushHandle)
   16869 23              && !SessionIsSaved(in->flushHandle)
   16870 24             )
   16871 25               return TPM_RC_HANDLE;
   16872 26
   16873 27           // If the session to be flushed is the exclusive audit session, then
   16874 28           // indicate that there is no exclusive audit session any longer.
   16875 29           if(in->flushHandle == g_exclusiveAuditSession)
   16876 30               g_exclusiveAuditSession = TPM_RH_UNASSIGNED;
   16877 31
   16878 32           // Flush session
   16879 33           SessionFlush(in->flushHandle);
   16880 34           break;
   16881 35       default:
   16882 36           // This command only take object or session handle.              Other handles
   16883 37           // should be filtered out at handle unmarshal
   16884 38           pAssert(FALSE);
   16885 39           break;
   16886 40       }
   16887 41
   16888 42       return TPM_RC_SUCCESS;
   16889 43   }
   16890 44   #endif // CC_FlushContext
   16891 
   16892 
   16893 
   16894 
   16895      Family 2.0                                  TCG Published                                          Page 371
   16896      Level 00 Revision 01.16               Copyright  TCG 2006-2014                               October 30, 2014
   16897 Part 3: Commands                                                               Trusted Platform Module Library
   16899 
   16900 
   16901 28.5     TPM2_EvictControl
   16902 
   16903 28.5.1 General Description
   16904 
   16905 This command allows a transient object to be made persistent or a persistent object to be evicted.
   16906 
   16907 NOTE 1           A transient object is one that may be removed from TPM memory using either TPM2_FlushContext
   16908                  or TPM2_Startup(). A persistent object is not removed from TPM memory by TPM2_FlushContext()
   16909                  or TPM2_Startup().
   16910 
   16911 If objectHandle is a transient object, then the call is to make the object persistent and assign
   16912 persistentHandle to the persistent version of the object. If objectHandle is a persistent object, then the call
   16913 is to evict the persistent object.
   16914 Before execution of TPM2_EvictControl code below, the TPM verifies that objectHandle references an
   16915 object that is resident on the TPM and that persistentHandle is a valid handle for a persistent object.
   16916 
   16917 NOTE 2           This requirement simplifies the unmarshaling code so that it only need check that persistentHandle
   16918                  is always a persistent object.
   16919 
   16920 If objectHandle references a transient object:
   16921 a) The TPM shall return TPM_RC_ATTRIBUTES if
   16922      1) it is in the hierarchy of TPM_RH_NULL,
   16923      2) only the public portion of the object is loaded, or
   16924      3) the stClear is SET in the object or in an ancestor key.
   16925 b) The TPM shall return TPM_RC_HIERARCHY if the object is not in the proper hierarchy as
   16926    determined by auth.
   16927      1) If auth is TPM_RH_PLATFORM, the proper hierarchy is the Platform hierarchy.
   16928      2) If auth is TPM_RH_OWNER, the proper hierarchy is either the Storage or the Endorsement
   16929         hierarchy.
   16930 c) The TPM shall return TPM_RC_RANGE if persistentHandle is not in the proper range as determined
   16931    by auth.
   16932      1) If auth is TPM_RH_OWNER, then persistentHandle shall be in the inclusive range of
   16933         81 00 00 0016 to 81 7F FF FF16.
   16934      2) If auth is TPM_RH_PLATFORM, then persistentHandle shall be in the inclusive range of
   16935         81 80 00 0016 to 81 FF FF FF16.
   16936 d) The TPM shall return TPM_RC_NV_DEFINED if a persistent object exists with the same handle as
   16937    persistentHandle.
   16938 e) The TPM shall return TPM_RC_NV_SPACE if insufficient space is available to make the object
   16939    persistent.
   16940 f)   The TPM shall return TPM_RC_NV_SPACE if execution of this command will prevent the TPM from
   16941      being able to hold two transient objects of any kind.
   16942 
   16943      NOTE 3          This requirement anticipates that a TPM may be implemented suc h that all TPM memory is non-
   16944                      volatile and not subject to endurance issues. In such case, there is no movement of an object
   16945                      between memory of different types and it is necessary that the TPM ensure that it is always
   16946                      possible for the management software to m ove objects to/from TPM memory in order to ensure
   16947                      that the objects required for command execution can be context restored.
   16948 
   16949 g) If the TPM returns TPM_RC_SUCCESS, the object referenced by objectHandle will not be flushed
   16950    and both objectHandle and persistentHandle may be used to access the object.
   16951 
   16952 Page 372                                       TCG Published                                        Family 2.0
   16953 October 30, 2014                       Copyright  TCG 2006-2014                      Level 00 Revision 01.16
   16954 Trusted Platform Module Library                                                             Part 3: Commands
   16956 
   16957 If objectHandle references a persistent object:
   16958 a) The TPM shall return TPM_RC_RANGE if objectHandle is not in the proper range as determined by
   16959    auth. If auth is TPM_RC_OWNER, objectHandle shall be in the inclusive range of 81 00 00 0016 to
   16960    81 7F FF FF16. If auth is TPM_RC_PLATFORM, objectHandle may be any valid persistent object
   16961    handle.
   16962 b) If the TPM returns TPM_RC_SUCCESS, objectHandle will be removed from persistent memory and
   16963    no longer be accessible.
   16964 
   16965 NOTE 4          The persistent object is not converted to a transient object, as this would prevent the immediate
   16966                 revocation of an object by removing it from persistent memory.
   16967 
   16968 
   16969 
   16970 
   16971 Family 2.0                                  TCG Published                                          Page 373
   16972 Level 00 Revision 01.16               Copyright  TCG 2006-2014                             October 30, 2014
   16973 Part 3: Commands                                                    Trusted Platform Module Library
   16975 
   16976 
   16977 28.5.2 Command and Response
   16978 
   16979                        Table 185  TPM2_EvictControl Command
   16980  Type                   Name                   Description
   16981 
   16982  TPMI_ST_COMMAND_TAG    tag                    TPM_ST_SESSIONS
   16983  UINT32                 commandSize
   16984  TPM_CC                 commandCode            TPM_CC_EvictControl {NV}
   16985 
   16986                                                TPM_RH_OWNER or TPM_RH_PLATFORM+{PP}
   16987  TPMI_RH_PROVISION      @auth                  Auth Handle: 1
   16988                                                Auth Role: USER
   16989                                                the handle of a loaded object
   16990  TPMI_DH_OBJECT         objectHandle
   16991                                                Auth Index: None
   16992 
   16993                                                if objectHandle is a transient object handle, then this is
   16994                                                the persistent handle for the object
   16995  TPMI_DH_PERSISTENT     persistentHandle
   16996                                                if objectHandle is a persistent object handle, then it
   16997                                                shall be the same value as persistentHandle
   16998 
   16999 
   17000                        Table 186  TPM2_EvictControl Response
   17001  Type                   Name                   Description
   17002 
   17003  TPM_ST                 tag                    see clause 6
   17004  UINT32                 responseSize
   17005  TPM_RC                 responseCode
   17006 
   17007 
   17008 
   17009 
   17010 Page 374                               TCG Published                                       Family 2.0
   17011 October 30, 2014              Copyright  TCG 2006-2014                     Level 00 Revision 01.16
   17012      Trusted Platform Module Library                                                                Part 3: Commands
   17014 
   17015 
   17016 
   17017      28.5.3 Detailed Actions
   17018 
   17019 1    #include "InternalRoutines.h"
   17020 2    #include "EvictControl_fp.h"
   17021 3    #ifdef TPM_CC_EvictControl // Conditional expansion of this file
   17022 
   17023 
   17024      Error Returns                     Meaning
   17025 
   17026      TPM_RC_ATTRIBUTES                 an object with temporary, stClear or publicOnly attribute SET cannot
   17027                                        be made persistent
   17028      TPM_RC_HIERARCHY                  auth cannot authorize the operation in the hierarchy of evictObject
   17029      TPM_RC_HANDLE                     evictHandle of the persistent object to be evicted is not the same as
   17030                                        the persistentHandle argument
   17031      TPM_RC_NV_HANDLE                  persistentHandle is unavailable
   17032      TPM_RC_NV_SPACE                   no space in NV to make evictHandle persistent
   17033      TPM_RC_RANGE                      persistentHandle is not in the range corresponding to the hierarchy of
   17034                                        evictObject
   17035 
   17036  4   TPM_RC
   17037  5   TPM2_EvictControl(
   17038  6       EvictControl_In       *in                   // IN: input parameter list
   17039  7       )
   17040  8   {
   17041  9       TPM_RC       result;
   17042 10       OBJECT       *evictObject;
   17043 11
   17044 12       // The command needs NV update. Check if NV is available.
   17045 13       // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   17046 14       // this point
   17047 15       result = NvIsAvailable();
   17048 16       if(result != TPM_RC_SUCCESS) return result;
   17049 17
   17050 18   // Input Validation
   17051 19
   17052 20       // Get internal object pointer
   17053 21       evictObject = ObjectGet(in->objectHandle);
   17054 22
   17055 23       // Temporary, stClear or public only objects can not be made persistent
   17056 24       if(   evictObject->attributes.temporary == SET
   17057 25          || evictObject->attributes.stClear == SET
   17058 26          || evictObject->attributes.publicOnly == SET
   17059 27         )
   17060 28           return TPM_RC_ATTRIBUTES + RC_EvictControl_objectHandle;
   17061 29
   17062 30       // If objectHandle refers to a persistent object, it should be the same as
   17063 31       // input persistentHandle
   17064 32       if(   evictObject->attributes.evict == SET
   17065 33          && evictObject->evictHandle != in->persistentHandle
   17066 34         )
   17067 35           return TPM_RC_HANDLE + RC_EvictControl_objectHandle;
   17068 36
   17069 37       // Additional auth validation
   17070 38       if(in->auth == TPM_RH_PLATFORM)
   17071 39       {
   17072 40           // To make persistent
   17073 41           if(evictObject->attributes.evict == CLEAR)
   17074 42           {
   17075 43               // Platform auth can not set evict object in storage or endorsement
   17076 44               // hierarchy
   17077 
   17078      Family 2.0                                   TCG Published                                               Page 375
   17079      Level 00 Revision 01.16               Copyright  TCG 2006-2014                                October 30, 2014
   17080      Part 3: Commands                                               Trusted Platform Module Library
   17082 
   17083 45              if(evictObject->attributes.ppsHierarchy == CLEAR)
   17084 46                  return TPM_RC_HIERARCHY + RC_EvictControl_objectHandle;
   17085 47
   17086 48              // Platform cannot use a handle outside of platform persistent range.
   17087 49              if(!NvIsPlatformPersistentHandle(in->persistentHandle))
   17088 50                  return TPM_RC_RANGE + RC_EvictControl_persistentHandle;
   17089 51          }
   17090 52          // Platform auth can delete any persistent object
   17091 53      }
   17092 54      else if(in->auth == TPM_RH_OWNER)
   17093 55      {
   17094 56          // Owner auth can not set or clear evict object in platform hierarchy
   17095 57          if(evictObject->attributes.ppsHierarchy == SET)
   17096 58              return TPM_RC_HIERARCHY + RC_EvictControl_objectHandle;
   17097 59
   17098 60          // Owner cannot use a handle outside of owner persistent range.
   17099 61          if(   evictObject->attributes.evict == CLEAR
   17100 62             && !NvIsOwnerPersistentHandle(in->persistentHandle)
   17101 63            )
   17102 64              return TPM_RC_RANGE + RC_EvictControl_persistentHandle;
   17103 65      }
   17104 66      else
   17105 67      {
   17106 68          // Other auth is not allowed in this command and should be filtered out
   17107 69          // at unmarshal process
   17108 70          pAssert(FALSE);
   17109 71      }
   17110 72
   17111 73   // Internal Data Update
   17112 74
   17113 75      // Change evict state
   17114 76      if(evictObject->attributes.evict == CLEAR)
   17115 77      {
   17116 78          // Make object persistent
   17117 79          // A TPM_RC_NV_HANDLE or TPM_RC_NV_SPACE error may be returned at this
   17118 80          // point
   17119 81          result = NvAddEvictObject(in->persistentHandle, evictObject);
   17120 82          if(result != TPM_RC_SUCCESS) return result;
   17121 83      }
   17122 84      else
   17123 85      {
   17124 86          // Delete the persistent object in NV
   17125 87          NvDeleteEntity(evictObject->evictHandle);
   17126 88      }
   17127 89
   17128 90      return TPM_RC_SUCCESS;
   17129 91
   17130 92   }
   17131 93   #endif // CC_EvictControl
   17132 
   17133 
   17134 
   17135 
   17136      Page 376                              TCG Published                                Family 2.0
   17137      October 30, 2014               Copyright  TCG 2006-2014             Level 00 Revision 01.16
   17138 Trusted Platform Module Library                                                               Part 3: Commands
   17140 
   17141 
   17142 29     Clocks and Timers
   17143 
   17144 29.1    TPM2_ReadClock
   17145 
   17146 29.1.1 General Description
   17147 
   17148 This command reads the current TPMS_TIME_INFO structure that contains the current setting of Time,
   17149 Clock, resetCount, and restartCount.
   17150 No authorization sessions of any type are allowed with this command and tag is required to be
   17151 TPM_ST_NO_SESSIONS.
   17152 
   17153 NOTE           This command is intended to allow the TCB to have access to values that have the potential to be
   17154                privacy sensitive. The values may be read without authorization because the TCB will not disclose
   17155                these values. Since they are not signed and cannot be accessed in a command that uses an
   17156                authorization session, it is not possible for any entity, other than the TCB, to be assured that the
   17157                values are accurate.
   17158 
   17159 
   17160 
   17161 
   17162 Family 2.0                                  TCG Published                                            Page 377
   17163 Level 00 Revision 01.16               Copyright  TCG 2006-2014                              October 30, 2014
   17164 Part 3: Commands                                            Trusted Platform Module Library
   17166 
   17167 
   17168 29.1.2 Command and Response
   17169 
   17170                       Table 187  TPM2_ReadClock Command
   17171 Type                   Name                  Description
   17172 
   17173 TPMI_ST_COMMAND_TAG    tag                   TPM_ST_NO_SESSIONS
   17174 UINT32                 commandSize
   17175 TPM_CC                 commandCode           TPM_CC_ReadClock
   17176 
   17177 
   17178                       Table 188  TPM2_ReadClock Response
   17179 Type                   Name                  Description
   17180 
   17181 TPM_ST                 tag                   see clause 6
   17182 UINT32                 responseSize
   17183 TPM_RC                 responseCode
   17184 
   17185 TPMS_TIME_INFO         currentTime
   17186 
   17187 
   17188 
   17189 
   17190 Page 378                              TCG Published                           Family 2.0
   17191 October 30, 2014             Copyright  TCG 2006-2014            Level 00 Revision 01.16
   17192      Trusted Platform Module Library                                      Part 3: Commands
   17194 
   17195 
   17196 
   17197      29.1.3 Detailed Actions
   17198 
   17199  1   #include "InternalRoutines.h"
   17200  2   #include "ReadClock_fp.h"
   17201  3   #ifdef TPM_CC_ReadClock // Conditional expansion of this file
   17202  4   TPM_RC
   17203  5   TPM2_ReadClock(
   17204  6       ReadClock_Out    *out            // OUT: output parameter list
   17205  7       )
   17206  8   {
   17207  9   // Command Output
   17208 10
   17209 11       out->currentTime.time = g_time;
   17210 12       TimeFillInfo(&out->currentTime.clockInfo);
   17211 13
   17212 14       return TPM_RC_SUCCESS;
   17213 15   }
   17214 16   #endif // CC_ReadClock
   17215 
   17216 
   17217 
   17218 
   17219      Family 2.0                            TCG Published                       Page 379
   17220      Level 00 Revision 01.16           Copyright  TCG 2006-2014          October 30, 2014
   17221 Part 3: Commands                                                                  Trusted Platform Module Library
   17223 
   17224 
   17225 29.2   TPM2_ClockSet
   17226 
   17227 29.2.1 General Description
   17228 
   17229 This command is used to advance the value of the TPMs Clock. The command will fail if newTime is less
   17230 than the current value of Clock or if the new time is greater than FF FF 00 00 00 00 00 0016. If both of
   17231 these checks succeed, Clock is set to newTime. If either of these checks fails, the TPM shall return
   17232 TPM_RC_VALUE and make no change to Clock.
   17233 
   17234 NOTE           This maximum setting would prevent Clock from rolling over to zero for approximately 8,000 year s if
   17235                the Clock update rate was set so that TPM time was passing 33 percent faster than real time. This
   17236                would still be more than 6,000 years before Clock would roll over to zero. Because Clock will not roll
   17237                over in the lifetime of the TPM, there is no need for external software to deal with the possibility that
   17238                Clock may wrap around.
   17239 
   17240 If the value of Clock after the update makes the volatile and non-volatile versions of
   17241 TPMS_CLOCK_INFO.clock differ by more than the reported update interval, then the TPM shall update
   17242 the non-volatile version of TPMS_CLOCK_INFO.clock before returning.
   17243 This command requires Platform Authorization or Owner Authorization.
   17244 
   17245 
   17246 
   17247 
   17248 Page 380                                       TCG Published                                            Family 2.0
   17249 October 30, 2014                       Copyright  TCG 2006-2014                         Level 00 Revision 01.16
   17250 Trusted Platform Module Library                                                         Part 3: Commands
   17252 
   17253 
   17254 
   17255 29.2.2 Command and Response
   17256 
   17257                               Table 189  TPM2_ClockSet Command
   17258 Type                          Name                  Description
   17259 
   17260 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   17261 UINT32                        commandSize
   17262 TPM_CC                        commandCode           TPM_CC_ClockSet {NV}
   17263 
   17264                                                     TPM_RH_OWNER or TPM_RH_PLATFORM+{PP}
   17265 TPMI_RH_PROVISION             @auth                 Auth Handle: 1
   17266                                                     Auth Role: USER
   17267 
   17268 UINT64                        newTime               new Clock setting in milliseconds
   17269 
   17270 
   17271                               Table 190  TPM2_ClockSet Response
   17272 Type                          Name                  Description
   17273 
   17274 TPM_ST                        tag                   see clause 6
   17275 UINT32                        responseSize
   17276 TPM_RC                        responseCode
   17277 
   17278 
   17279 
   17280 
   17281 Family 2.0                                 TCG Published                                     Page 381
   17282 Level 00 Revision 01.16             Copyright  TCG 2006-2014                           October 30, 2014
   17283      Part 3: Commands                                                     Trusted Platform Module Library
   17285 
   17286 
   17287 
   17288      29.2.3 Detailed Actions
   17289 
   17290 1    #include "InternalRoutines.h"
   17291 2    #include "ClockSet_fp.h"
   17292 3    #ifdef TPM_CC_ClockSet // Conditional expansion of this file
   17293 
   17294      Read the current TPMS_TIMER_INFO structure settings
   17295 
   17296      Error Returns                 Meaning
   17297 
   17298      TPM_RC_VALUE                  invalid new clock
   17299 
   17300  4   TPM_RC
   17301  5   TPM2_ClockSet(
   17302  6       ClockSet_In       *in              // IN: input parameter list
   17303  7       )
   17304  8   {
   17305  9   #define CLOCK_UPDATE_MASK    ((1ULL << NV_CLOCK_UPDATE_INTERVAL)- 1)
   17306 10       UINT64      clockNow;
   17307 11
   17308 12   // Input Validation
   17309 13
   17310 14       // new time can not be bigger than 0xFFFF000000000000 or smaller than
   17311 15       // current clock
   17312 16       if(in->newTime > 0xFFFF000000000000ULL
   17313 17               || in->newTime < go.clock)
   17314 18           return TPM_RC_VALUE + RC_ClockSet_newTime;
   17315 19
   17316 20   // Internal Data Update
   17317 21
   17318 22       // Internal Data Update
   17319 23       clockNow = go.clock;    // grab the old value
   17320 24       go.clock = in->newTime;       // set the new value
   17321 25       // Check to see if the update has caused a need for an nvClock update
   17322 26       if((in->newTime & CLOCK_UPDATE_MASK) > (clockNow & CLOCK_UPDATE_MASK))
   17323 27       {
   17324 28           CryptDrbgGetPutState(GET_STATE);
   17325 29           NvWriteReserved(NV_ORDERLY_DATA, &go);
   17326 30
   17327 31           // Now the time state is safe
   17328 32           go.clockSafe = YES;
   17329 33       }
   17330 34
   17331 35       return TPM_RC_SUCCESS;
   17332 36   }
   17333 37   #endif // CC_ClockSet
   17334 
   17335 
   17336 
   17337 
   17338      Page 382                                  TCG Published                                Family 2.0
   17339      October 30, 2014                  Copyright  TCG 2006-2014               Level 00 Revision 01.16
   17340 Trusted Platform Module Library                                                                Part 3: Commands
   17342 
   17343 
   17344 29.3   TPM2_ClockRateAdjust
   17345 
   17346 29.3.1 General Description
   17347 
   17348 This command adjusts the rate of advance of Clock and Time to provide a better approximation to real
   17349 time.
   17350 The rateAdjust value is relative to the current rate and not the nominal rate of advance.
   17351 
   17352 EXAMPLE 1       If this command had been called three times with rateAdjust = TPM_CLOCK_COARSE_SLOWER
   17353                 and once with rateAdjust = TPM_CLOCK_COARSE_FASTER, the net effect will be as if the
   17354                 command had been called twice with rateAdjust = TPM_CLOCK_COARSE_SLOWER.
   17355 
   17356 The range of adjustment shall be sufficient to allow Clock and Time to advance at real time but no more.
   17357 If the requested adjustment would make the rate advance faster or slower than the nominal accuracy of
   17358 the input frequency, the TPM shall return TPM_RC_VALUE.
   17359 
   17360 EXAMPLE 2       If the frequency tolerance of the TPM's input clock is +/-10 percent, then the TPM will return
   17361                 TPM_RC_VALUE if the adjustment would make Clock run more than 10 percent faster or slower than
   17362                 nominal. That is, if the input oscillator were nominally 100 megahertz (MHz), then 1 millisecond (ms)
   17363                 would normally take 100,000 counts. The update Clock should be adjustable so that 1 ms is between
   17364                 90,000 and 110,000 counts.
   17365 
   17366 The interpretation of fine and coarse adjustments is implementation-specific.
   17367 The nominal rate of advance for Clock and Time shall be accurate to within 15 percent. That is, with no
   17368 adjustment applied, Clock and Time shall be advanced at a rate within 15 percent of actual time.
   17369 
   17370 NOTE            If the adjustments are incorrect, it will be possible to make the difference between advance of
   17371                 Clock/Time and real time to be as much as 1.15 2 or ~1.33.
   17372 
   17373 Changes to the current Clock update rate adjustment need not be persisted across TPM power cycles.
   17374 
   17375 
   17376 
   17377 
   17378 Family 2.0                                   TCG Published                                             Page 383
   17379 Level 00 Revision 01.16                Copyright  TCG 2006-2014                               October 30, 2014
   17380 Part 3: Commands                                                   Trusted Platform Module Library
   17382 
   17383 
   17384 
   17385 29.3.2 Command and Response
   17386 
   17387                       Table 191  TPM2_ClockRateAdjust Command
   17388 Type                     Name                  Description
   17389 
   17390 TPMI_ST_COMMAND_TAG      tag                   TPM_ST_SESSIONS
   17391 UINT32                   commandSize
   17392 TPM_CC                   commandCode           TPM_CC_ClockRateAdjust
   17393 
   17394                                                TPM_RH_OWNER or TPM_RH_PLATFORM+{PP}
   17395 TPMI_RH_PROVISION        @auth                 Auth Handle: 1
   17396                                                Auth Role: USER
   17397 
   17398 TPM_CLOCK_ADJUST         rateAdjust            Adjustment to current Clock update rate
   17399 
   17400 
   17401                       Table 192  TPM2_ClockRateAdjust Response
   17402 Type                     Name                  Description
   17403 
   17404 TPM_ST                   tag                   see clause 6
   17405 UINT32                   responseSize
   17406 TPM_RC                   responseCode
   17407 
   17408 
   17409 
   17410 
   17411 Page 384                                TCG Published                                    Family 2.0
   17412 October 30, 2014               Copyright  TCG 2006-2014                  Level 00 Revision 01.16
   17413      Trusted Platform Module Library                                        Part 3: Commands
   17415 
   17416 
   17417 
   17418      29.3.3 Detailed Actions
   17419 
   17420  1   #include "InternalRoutines.h"
   17421  2   #include "ClockRateAdjust_fp.h"
   17422  3   #ifdef TPM_CC_ClockRateAdjust // Conditional expansion of this file
   17423  4   TPM_RC
   17424  5   TPM2_ClockRateAdjust(
   17425  6       ClockRateAdjust_In    *in            // IN: input parameter list
   17426  7       )
   17427  8   {
   17428  9   // Internal Data Update
   17429 10       TimeSetAdjustRate(in->rateAdjust);
   17430 11
   17431 12       return TPM_RC_SUCCESS;
   17432 13   }
   17433 14   #endif // CC_ClockRateAdjust
   17434 
   17435 
   17436 
   17437 
   17438      Family 2.0                             TCG Published                        Page 385
   17439      Level 00 Revision 01.16           Copyright  TCG 2006-2014            October 30, 2014
   17440 Part 3: Commands                                                                 Trusted Platform Module Library
   17442 
   17443 
   17444 30     Capability Commands
   17445 
   17446 30.1     Introduction
   17447 
   17448 The TPM has numerous values that indicate the state, capabilities, and properties of the TPM. These
   17449 values are needed for proper management of the TPM. The TPM2_GetCapability() command is used to
   17450 access these values.
   17451 TPM2_GetCapability() allows reporting of multiple values in a single call. The values are grouped
   17452 according to type.
   17453 
   17454 NOTE            TPM2_TestParms()is used to determine if a TPM supports a particular combination of algorith m
   17455                 parameters
   17456 
   17457 
   17458 30.2     TPM2_GetCapability
   17459 
   17460 30.2.1 General Description
   17461 
   17462 This command returns various information regarding the TPM and its current state.
   17463 The capability parameter determines the category of data returned. The property parameter selects the
   17464 first value of the selected category to be returned. If there is no property that corresponds to the value of
   17465 property, the next higher value is returned, if it exists.
   17466 
   17467 EXAMPLE 1       The list of handles of transient objects currently loaded in the TPM may be read one at a time. O n
   17468                 the first read, set the property to TRANSIENT_FIRST and propertyCount to one. If a transient object
   17469                 is present, the lowest numbered handle is returned and moreData will be YES if transient objects
   17470                 with higher handles are loaded. On the subsequent call, u se returned handle value plus 1 in order to
   17471                 access the next higher handle.
   17472 
   17473 The propertyCount parameter indicates the number of capabilities in the indicated group that are
   17474 requested. The TPM will return the number of requested values (propertyCount) or until the last property
   17475 of the requested type has been returned.
   17476 
   17477 NOTE 1          The type of the capability is determined by a combination of capability and property.
   17478 
   17479 NOTE 2          If the propertyCount selects an unimplemented property, the next higher implemented property is
   17480                 returned.
   17481 
   17482 When all of the properties of the requested type have been returned, the moreData parameter in the
   17483 response will be set to NO. Otherwise, it will be set to YES.
   17484 
   17485 NOTE 3          The moreData parameter will be YES if there are more properties even if the requested number of
   17486                 capabilities has been returned.
   17487 
   17488 The TPM is not required to return more than one value at a time. It is not required to provide the same
   17489 number of values in response to subsequent requests.
   17490 
   17491 EXAMPLE 2       A TPM may return 4 properties in response to a TPM2_GetCapability( capability =
   17492                 TPM_CAP_TPM_PROPERTY, property = TPM_PT_MANUFACTURER, propertyCount = 8 ) and for a
   17493                 latter request with the same parameters, the TPM m ay return as few as one and as many as 8
   17494                 values.
   17495 
   17496 When the TPM is in Failure mode, a TPM is required to allow use of this command for access of the
   17497 following capabilities:
   17498 
   17499 
   17500 
   17501 
   17502 Page 386                                       TCG Published                                            Family 2.0
   17503 October 30, 2014                       Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   17504 Trusted Platform Module Library                                                                  Part 3: Commands
   17506 
   17507 
   17508          TPM_PT_MANUFACTURER
   17509          TPM_PT_VENDOR_STRING_1
   17510     
   17511                                            (3)
   17512           TPM_PT_VENDOR_STRING_2
   17513     
   17514                                            (3)
   17515           TPM_PT_VENDOR_STRING_3
   17516     
   17517                                            (3)
   17518           TPM_PT_VENDOR_STRING_4
   17519          TPM_PT_VENDOR_TPM_TYPE
   17520          TPM_PT_FIRMWARE_VERSION_1
   17521          TPM_PT_FIRMWARE_VERSION_2
   17522 
   17523 NOTE 4          If the vendor string does not require one of these values, the property type does not need to exist.
   17524 
   17525 A vendor may optionally allow the TPM to return other values.
   17526 If in Failure mode and a capability is requested that is not available in Failure mode, the TPM shall return
   17527 no value.
   17528 
   17529 EXAMPLE 3       Assume the TPM is in Failure mode and the TPM only supports reporting of the minimum required
   17530                 set of properties (the limited set to TPML_TAGGED_PCR_PROPERTY values). If a
   17531                 TPM2_GetCapability is received requesting a capability that has a property type value greater than
   17532                 TPM_PT_FIRMWARE_VERSION_2, the TPM will return a zero length list with the moreData
   17533                 parameter set to NO. If the property type is less than TPM_PT_MANUFACTURER, the TPM will
   17534                 return TPM_PT_MANUFACTURER.
   17535 
   17536 In Failure mode, tag is required to be TPM_ST_NO_SESSIONS or the TPM shall return
   17537 TPM_RC_FAILURE.
   17538 The capability categories and the types of the return values are:
   17539 
   17540  capability                            property                    Return Type
   17541                                                       (1)
   17542  TPM_CAP_ALGS                          TPM_ALG_ID                  TPML_ALG_PROPERTY
   17543  TPM_CAP_HANDLES                       TPM_HANDLE                  TPML_HANDLE
   17544  TPM_CAP_COMMANDS                      TPM_CC                      TPML_CCA
   17545  TPM_CAP_PP_COMMANDS                   TPM_CC                      TPML_CC
   17546  TPM_CAP_AUDIT_COMMANDS                TPM_CC                      TPML_CC
   17547  TPM_CAP_PCRS                          Reserved                    TPML_PCR_SELECTION
   17548  TPM_CAP_TPM_PROPERTIES                TPM_PT                      TPML_TAGGED_TPM_PROPERTY
   17549  TPM_CAP_PCR_PROPERTIES                TPM_PT_PCR                  TPML_TAGGED_PCR_PROPERTY
   17550                                                             (1)
   17551  TPM_CAP_ECC_CURVE                     TPM_ECC_CURVE               TPML_ECC_CURVE
   17552  TPM_CAP_VENDOR_PROPERTY               manufacturer specific       manufacturer-specific values
   17553  NOTES:
   17554  (1) The TPM_ALG_ID or TPM_ECC_CURVE is cast to a UINT32
   17555 
   17556 
   17557 
   17558 
   17559 Family 2.0                                     TCG Published                                             Page 387
   17560 Level 00 Revision 01.16                Copyright  TCG 2006-2014                                 October 30, 2014
   17561 Part 3: Commands                                                               Trusted Platform Module Library
   17563 
   17564 
   17565       TPM_CAP_ALGS  Returns a list of TPMS_ALG_PROPERTIES. Each entry is an algorithm ID
   17566        and a set of properties of the algorithm.
   17567       TPM_CAP_HANDLES  Returns a list of all of the handles within the handle range of the
   17568        property parameter. The range of the returned handles is determined by the handle type (the
   17569        most-significant octet (MSO) of the property). Any of the defined handle types is allowed
   17570 
   17571    EXAMPLE 4        If the MSO of property is TPM_HT_NV_INDEX, then the TPM will return a list of NV Index
   17572                     values.
   17573 
   17574    EXAMPLE 5        If the MSO of property is TPM_HT_PCR, then the TPM will return a list of PCR.
   17575 
   17576       For this capability, use of TPM_HT_LOADED_SESSION and TPM_HT_SAVED_SESSION is
   17577        allowed. Requesting handles with a handle type of TPM_HT_LOADED_SESSION will return
   17578        handles for loaded sessions. The returned handle values will have a handle type of either
   17579        TPM_HT_HMAC_SESSION or TPM_HT_POLICY_SESSION. If saved sessions are requested,
   17580        all returned values will have the TPM_HT_HMAC_SESSION handle type because the TPM does
   17581        not track the session type of saved sessions.
   17582 
   17583    NOTE 5           TPM_HT_LOADED_SESSION and TPM_HT_HMAC_SESSION have the same value, as do
   17584                     TPM_HT_SAVED_SESSION and TPM_HT_POLICY_SESSION. It is not possible to request that
   17585                     the TPM return a list of loaded HMAC sessions without including the policy sessions.
   17586 
   17587       TPM_CAP_COMMANDS  Returns a list of the command attributes for all of the commands
   17588        implemented in the TPM, starting with the TPM_CC indicated by the property parameter. If
   17589        vendor specific commands are implemented, the vendor-specific command attribute with the
   17590        lowest commandIndex, is returned after the non-vendor-specific (base) command.
   17591 
   17592    NOTE 6           The type of the property parameter is a TPM_CC while the type of the returned list is
   17593                     TPML_CCA.
   17594 
   17595       TPM_CAP_PP_COMMANDS  Returns a list of all of the commands currently requiring Physical
   17596        Presence for confirmation of platform authorization. The list will start with the TPM_CC indicated
   17597        by property.
   17598       TPM_CAP_AUDIT_COMMANDS  Returns a list of all of the commands currently set for
   17599        command audit.
   17600       TPM_CAP_PCRS  Returns the current allocation of PCR in a TPML_PCR_SELECTION. The
   17601        property parameter shall be zero. The TPM will always respond to this command with the full
   17602        PCR allocation and moreData will be NO.
   17603       TPM_CAP_TPM_PROPERTIES  Returns a list of tagged properties. The tag is a TPM_PT and
   17604        the property is a 32-bit value. The properties are returned in groups. Each property group is on a
   17605        256-value boundary (that is, the boundary occurs when the TPM_PT is evenly divisible by 256).
   17606        The TPM will only return values in the same group as the property parameter in the command.
   17607       TPM_CAP_PCR_PROPERTIES  Returns a list of tagged PCR properties. The tag is a
   17608        TPM_PT_PCR and the property is a TPMS_PCR_SELECT.
   17609    The input command property is a TPM_PT_PCR (see TPM 2.0 Part 2 for PCR properties to be
   17610    requested) that specifies the first property to be returned. If propertyCount is greater than 1, the list of
   17611    properties begins with that property and proceeds in TPM_PT_PCR sequence.
   17612    Each item in the list is a TPMS_PCR_SELECT structure that contains a bitmap of all PCR.
   17613 
   17614    NOTE 7           A PCR index in all banks (all hash algorithms) has the same properties, so the hash algorithm is
   17615                     not specified here.
   17616 
   17617 
   17618 
   17619 
   17620 Page 388                                      TCG Published                                          Family 2.0
   17621 October 30, 2014                      Copyright  TCG 2006-2014                       Level 00 Revision 01.16
   17622 Trusted Platform Module Library                                                           Part 3: Commands
   17624 
   17625 
   17626        TPM_CAP_TPM_ECC_CURVES  Returns a list of ECC curve identifiers currently available for
   17627         use in the TPM.
   17628 The moreData parameter will have a value of YES if there are more values of the requested type that
   17629 were not returned.
   17630 If no next capability exists, the TPM will return a zero-length list and moreData will have a value of NO.
   17631 
   17632 
   17633 
   17634 
   17635 Family 2.0                                 TCG Published                                        Page 389
   17636 Level 00 Revision 01.16               Copyright  TCG 2006-2014                          October 30, 2014
   17637 Part 3: Commands                                                     Trusted Platform Module Library
   17639 
   17640 
   17641 
   17642 30.2.2 Command and Response
   17643 
   17644                         Table 193  TPM2_GetCapability Command
   17645  Type                     Name                 Description
   17646 
   17647                                                TPM_ST_SESSIONS if an audit session is present;
   17648  TPMI_ST_COMMAND_TAG      tag
   17649                                                otherwise, TPM_ST_NO_SESSIONS
   17650  UINT32                   commandSize
   17651  TPM_CC                   commandCode          TPM_CC_GetCapability
   17652 
   17653  TPM_CAP                  capability           group selection; determines the format of the response
   17654  UINT32                   property             further definition of information
   17655  UINT32                   propertyCount        number of properties of the indicated type to return
   17656 
   17657 
   17658                         Table 194  TPM2_GetCapability Response
   17659  Type                     Name                 Description
   17660 
   17661  TPM_ST                   tag                  see clause 6
   17662  UINT32                   responseSize
   17663  TPM_RC                   responseCode
   17664 
   17665  TPMI_YES_NO              moreData             flag to indicate if there are more values of this type
   17666  TPMS_CAPABILITY_DATA     capabilityData       the capability data
   17667 
   17668 
   17669 
   17670 
   17671 Page 390                               TCG Published                                       Family 2.0
   17672 October 30, 2014                Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   17673      Trusted Platform Module Library                                                                 Part 3: Commands
   17675 
   17676 
   17677 
   17678      30.2.3 Detailed Actions
   17679 
   17680 1    #include "InternalRoutines.h"
   17681 2    #include "GetCapability_fp.h"
   17682 3    #ifdef TPM_CC_GetCapability // Conditional expansion of this file
   17683 
   17684 
   17685      Error Returns                     Meaning
   17686 
   17687      TPM_RC_HANDLE                     value of property is in an unsupported handle range for the
   17688                                        TPM_CAP_HANDLES capability value
   17689      TPM_RC_VALUE                      invalid capability; or property is not 0 for the TPM_CAP_PCRS
   17690                                        capability value
   17691 
   17692  4   TPM_RC
   17693  5   TPM2_GetCapability(
   17694  6       GetCapability_In      *in,                  // IN: input parameter list
   17695  7       GetCapability_Out     *out                  // OUT: output parameter list
   17696  8       )
   17697  9   {
   17698 10   // Command Output
   17699 11
   17700 12       // Set output capability type the same as input type
   17701 13       out->capabilityData.capability = in->capability;
   17702 14
   17703 15       switch(in->capability)
   17704 16       {
   17705 17       case TPM_CAP_ALGS:
   17706 18           out->moreData = AlgorithmCapGetImplemented((TPM_ALG_ID) in->property,
   17707 19                           in->propertyCount, &out->capabilityData.data.algorithms);
   17708 20           break;
   17709 21       case TPM_CAP_HANDLES:
   17710 22           switch(HandleGetType((TPM_HANDLE) in->property))
   17711 23           {
   17712 24           case TPM_HT_TRANSIENT:
   17713 25               // Get list of handles of loaded transient objects
   17714 26               out->moreData = ObjectCapGetLoaded((TPM_HANDLE) in->property,
   17715 27                                                  in->propertyCount,
   17716 28                                                  &out->capabilityData.data.handles);
   17717 29               break;
   17718 30           case TPM_HT_PERSISTENT:
   17719 31               // Get list of handles of persistent objects
   17720 32               out->moreData = NvCapGetPersistent((TPM_HANDLE) in->property,
   17721 33                                                  in->propertyCount,
   17722 34                                                  &out->capabilityData.data.handles);
   17723 35               break;
   17724 36           case TPM_HT_NV_INDEX:
   17725 37               // Get list of defined NV index
   17726 38               out->moreData = NvCapGetIndex((TPM_HANDLE) in->property,
   17727 39                                             in->propertyCount,
   17728 40                                             &out->capabilityData.data.handles);
   17729 41               break;
   17730 42           case TPM_HT_LOADED_SESSION:
   17731 43               // Get list of handles of loaded sessions
   17732 44               out->moreData = SessionCapGetLoaded((TPM_HANDLE) in->property,
   17733 45                                                   in->propertyCount,
   17734 46                                                   &out->capabilityData.data.handles);
   17735 47               break;
   17736 48           case TPM_HT_ACTIVE_SESSION:
   17737 49               // Get list of handles of
   17738 50               out->moreData = SessionCapGetSaved((TPM_HANDLE) in->property,
   17739 51                                                  in->propertyCount,
   17740 52                                                  &out->capabilityData.data.handles);
   17741 
   17742      Family 2.0                                   TCG Published                                           Page 391
   17743      Level 00 Revision 01.16               Copyright  TCG 2006-2014                                 October 30, 2014
   17744       Part 3: Commands                                                Trusted Platform Module Library
   17746 
   17747  53               break;
   17748  54           case TPM_HT_PCR:
   17749  55               // Get list of handles of PCR
   17750  56               out->moreData = PCRCapGetHandles((TPM_HANDLE) in->property,
   17751  57                                                in->propertyCount,
   17752  58                                                &out->capabilityData.data.handles);
   17753  59               break;
   17754  60           case TPM_HT_PERMANENT:
   17755  61               // Get list of permanent handles
   17756  62               out->moreData = PermanentCapGetHandles(
   17757  63                                   (TPM_HANDLE) in->property,
   17758  64                                   in->propertyCount,
   17759  65                                   &out->capabilityData.data.handles);
   17760  66               break;
   17761  67           default:
   17762  68               // Unsupported input handle type
   17763  69               return TPM_RC_HANDLE + RC_GetCapability_property;
   17764  70               break;
   17765  71           }
   17766  72           break;
   17767  73       case TPM_CAP_COMMANDS:
   17768  74           out->moreData = CommandCapGetCCList((TPM_CC) in->property,
   17769  75                                               in->propertyCount,
   17770  76                                               &out->capabilityData.data.command);
   17771  77           break;
   17772  78       case TPM_CAP_PP_COMMANDS:
   17773  79           out->moreData = PhysicalPresenceCapGetCCList((TPM_CC) in->property,
   17774  80                           in->propertyCount, &out->capabilityData.data.ppCommands);
   17775  81           break;
   17776  82       case TPM_CAP_AUDIT_COMMANDS:
   17777  83           out->moreData = CommandAuditCapGetCCList((TPM_CC) in->property,
   17778  84                                           in->propertyCount,
   17779  85                                           &out->capabilityData.data.auditCommands);
   17780  86           break;
   17781  87       case TPM_CAP_PCRS:
   17782  88           // Input property must be 0
   17783  89           if(in->property != 0)
   17784  90               return TPM_RC_VALUE + RC_GetCapability_property;
   17785  91           out->moreData = PCRCapGetAllocation(in->propertyCount,
   17786  92                                               &out->capabilityData.data.assignedPCR);
   17787  93           break;
   17788  94       case TPM_CAP_PCR_PROPERTIES:
   17789  95           out->moreData = PCRCapGetProperties((TPM_PT_PCR) in->property,
   17790  96                                             in->propertyCount,
   17791  97                                             &out->capabilityData.data.pcrProperties);
   17792  98           break;
   17793  99       case TPM_CAP_TPM_PROPERTIES:
   17794 100           out->moreData = TPMCapGetProperties((TPM_PT) in->property,
   17795 101                                             in->propertyCount,
   17796 102                                             &out->capabilityData.data.tpmProperties);
   17797 103           break;
   17798 104   #ifdef TPM_ALG_ECC
   17799 105       case TPM_CAP_ECC_CURVES:
   17800 106           out->moreData = CryptCapGetECCCurve((TPM_ECC_CURVE   ) in->property,
   17801 107                                               in->propertyCount,
   17802 108                                               &out->capabilityData.data.eccCurves);
   17803 109           break;
   17804 110   #endif // TPM_ALG_ECC
   17805 111       case TPM_CAP_VENDOR_PROPERTY:
   17806 112           // vendor property is not implemented
   17807 113       default:
   17808 114           // Unexpected TPM_CAP value
   17809 115           return TPM_RC_VALUE;
   17810 116           break;
   17811 117       }
   17812 118
   17813 
   17814       Page 392                               TCG Published                              Family 2.0
   17815       October 30, 2014                Copyright  TCG 2006-2014             Level 00 Revision 01.16
   17816       Trusted Platform Module Library                               Part 3: Commands
   17818 
   17819 119       return TPM_RC_SUCCESS;
   17820 120   }
   17821 121   #endif // CC_GetCapability
   17822 
   17823 
   17824 
   17825 
   17826       Family 2.0                           TCG Published                 Page 393
   17827       Level 00 Revision 01.16           Copyright  TCG 2006-2014   October 30, 2014
   17828 Part 3: Commands                                                        Trusted Platform Module Library
   17830 
   17831 
   17832 30.3   TPM2_TestParms
   17833 
   17834 30.3.1 General Description
   17835 
   17836 This command is used to check to see if specific combinations of algorithm parameters are supported.
   17837 The TPM will unmarshal the provided TPMT_PUBLIC_PARMS. If the parameters unmarshal correctly,
   17838 then the TPM will return TPM_RC_SUCCESS, indicating that the parameters are valid for the TPM. The
   17839 TPM will return the appropriate unmarshaling error if a parameter is not valid.
   17840 
   17841 
   17842 
   17843 
   17844 Page 394                                   TCG Published                                   Family 2.0
   17845 October 30, 2014                    Copyright  TCG 2006-2014                 Level 00 Revision 01.16
   17846 Trusted Platform Module Library                                                      Part 3: Commands
   17848 
   17849 
   17850 
   17851 30.3.2 Command and Response
   17852 
   17853                              Table 195  TPM2_TestParms Command
   17854  Type                         Name                 Description
   17855 
   17856                                                    TPM_ST_SESSIONS if an audit session is present;
   17857  TPMI_ST_COMMAND_TAG          tag
   17858                                                    otherwise, TPM_ST_NO_SESSIONS
   17859  UINT32                       commandSize
   17860  TPM_CC                       commandCode          TPM_CC_TestParms
   17861 
   17862  TPMT_PUBLIC_PARMS            parameters           algorithm parameters to be validated
   17863 
   17864 
   17865                              Table 196  TPM2_TestParms Response
   17866  Type                         Name                 Description
   17867 
   17868  TPM_ST                       tag                  see clause 6
   17869  UINT32                       responseSize
   17870  TPM_RC                       responseCode         TPM_RC
   17871 
   17872 
   17873 
   17874 
   17875 Family 2.0                               TCG Published                                    Page 395
   17876 Level 00 Revision 01.16             Copyright  TCG 2006-2014                        October 30, 2014
   17877      Part 3: Commands                                                 Trusted Platform Module Library
   17879 
   17880 
   17881 
   17882      30.3.3 Detailed Actions
   17883 
   17884  1   #include "InternalRoutines.h"
   17885  2   #include "TestParms_fp.h"
   17886  3   #ifdef TPM_CC_TestParms // Conditional expansion of this file
   17887  4   TPM_RC
   17888  5   TPM2_TestParms(
   17889  6       TestParms_In   *in             // IN: input parameter list
   17890  7       )
   17891  8   {
   17892  9       // Input parameter is not reference in command action
   17893 10       in = NULL;
   17894 11
   17895 12       // The parameters are tested at unmarshal process.   We do nothing in command
   17896 13       // action
   17897 14       return TPM_RC_SUCCESS;
   17898 15   }
   17899 16   #endif // CC_TestParms
   17900 
   17901 
   17902 
   17903 
   17904      Page 396                               TCG Published                                Family 2.0
   17905      October 30, 2014                Copyright  TCG 2006-2014              Level 00 Revision 01.16
   17906 Trusted Platform Module Library                                                               Part 3: Commands
   17908 
   17909 
   17910 31     Non-volatile Storage
   17911 
   17912 31.1     Introduction
   17913 
   17914 The NV commands are used to create, update, read, and delete allocations of space in NV memory.
   17915 Before an Index may be used, it must be defined (TPM2_NV_DefineSpace()).
   17916 An Index may be modified if the proper write authorization is provided or read if the proper read
   17917 authorization is provided. Different controls are available for reading and writing.
   17918 An Index may have an Index-specific authValue and authPolicy. The authValue may be used to authorize
   17919 reading if TPMA_NV_AUTHREAD is SET and writing if TPMA_NV_AUTHREAD is SET. The authPolicy
   17920 may be used to authorize reading if TPMA_NV_POLICYREAD is SET and writing if
   17921 TPMA_NV_POLICYWRITE is SET.
   17922 For commands that have both authHandle and nvIndex parameters, authHandle can be an NV Index,
   17923 Platform Authorization, or Owner Authorization. If authHandle is an NV Index, it must be the same as
   17924 nvIndex (TPM_RC_NV_AUTHORIZATION).
   17925 TPMA_NV_PPREAD and TPMA_NV_PPWRITE indicate if reading or writing of the NV Index may be
   17926 authorized by platformAuth or platformPolicy.
   17927 TPMA_NV_OWNERREAD and TPMA_NV_OWNERWRITE indicate if reading or writing of the NV Index
   17928 may be authorized by ownerAuth or ownerPolicy.
   17929 If an operation on an NV index requires authorization, and the authHandle parameter is the handle of an
   17930 NV Index, then the nvIndex parameter must have the same value or the TPM will return
   17931 TPM_RC_NV_AUTHORIZATION.
   17932 
   17933 NOTE 1          This check ensures that the authorization that was provided is associated with the NV Index being
   17934                 authorized.
   17935 
   17936 For creating an Index, Owner Authorization may not be used if shEnable is CLEAR and Platform
   17937 Authorization may not be used if phEnableNV is CLEAR.
   17938 If an Index was defined using Platform Authorization, then that Index is not accessible when phEnableNV
   17939 is CLEAR. If an Index was defined using Owner Authorization, then that Index is not accessible when
   17940 shEnable is CLEAR.
   17941 For read access control, any combination of TPMA_NV_PPREAD, TPMA_NV_OWNERREAD,
   17942 TPMA_NV_AUTHREAD, or TPMA_NV_POLICYREAD is allowed as long as at least one is SET.
   17943 For write access control, any combination of TPMA_NV_PPWRITE, TPMA_NV_OWNERWRITE,
   17944 TPMA_NV_AUTHWRITE, or TPMA_NV_POLICYWRITE is allowed as long as at least one is SET.
   17945 If an Index has been defined and not written, then any operation on the NV Index that requires read
   17946 authorization will fail (TPM_RC_NV_INITIALIZED). This check may be made before or after other
   17947 authorization checks but shall be performed before checking the NV Index authValue. An authorization
   17948 failure due to the NV Index not having been written shall not be logged by the dictionary attack logic.
   17949 If TPMA_NV_CLEAR_STCLEAR is SET, then the TPMA_NV_WRITTEN will be CLEAR on each
   17950 TPM2_Startup(TPM_SU_CLEAR). TPMA_NV_CLEAR_STCLEAR     shall   not  be   SET   if
   17951 TPMA_NV_COUNTER is SET.
   17952 The code in the Detailed Actions clause of each command is written to interface with an implementation-
   17953 dependent library that allows access to NV memory. The actions assume no specific layout of the
   17954 structure of the NV data.
   17955 Only one NV Index may be directly referenced in a command.
   17956 
   17957 NOTE 2          This means that, if authHandle references an NV Index, then nvIndex will have the same value.
   17958                 However, this does not limit the number of changes that may occur as side effects. For example, any
   17959                 number of NV Indexes might be relocated as a result of deleting or adding a NV Index.
   17960 
   17961 Family 2.0                                  TCG Published                                            Page 397
   17962 Level 00 Revision 01.16               Copyright  TCG 2006-2014                               October 30, 2014
   17963 Part 3: Commands                                                                 Trusted Platform Module Library
   17965 
   17966 
   17967 31.2     NV Counters
   17968 
   17969 When an Index has the TPMA_NV_COUNTER attribute set, it behaves as a monotonic counter and may
   17970 only be updated using TPM2_NV_Increment().
   17971 When an NV counter is created, the TPM shall initialize the 8-octet counter value with a number that is
   17972 greater than any count value for any NV counter on the TPM since the time of TPM manufacture.
   17973 An NV counter may be defined with the TPMA_NV_ORDERLY attribute to indicate that the NV Index is
   17974 expected to be modified at a high frequency and that the data is only required to persist when the TPM
   17975 goes through an orderly shutdown process. The TPM may update the counter value in RAM and
   17976 occasionally update the non-volatile version of the counter. An orderly shutdown is one occasion to
   17977 update the non-volatile count. If the difference between the volatile and non-volatile version of the counter
   17978 becomes as large as MAX_ORDERLY_COUNT, this shall be another occasion for updating the non-
   17979 volatile count.
   17980 Before an NV counter can be used, the TPM shall validate that the count is not less than a previously
   17981 reported value. If the TPMA_NV_ORDERLY attribute is not SET, or if the TPM experienced an orderly
   17982 shutdown, then the count is assumed to be correct. If the TPMA_NV_ORDERLY attribute is SET, and the
   17983 TPM shutdown was not orderly, then the TPM shall OR MAX_ORDERLY_COUNT to the contents of the
   17984 non-volatile counter and set that as the current count.
   17985 
   17986 NOTE 1          Because the TPM would have updated the NV Index if the difference between the count values was
   17987                 equal to MAX_ORDERLY_COUNT + 1, the highest value that could have been in the NV Index is
   17988                 MAX_ORDERLY_COUNT so it is safe to restore that value.
   17989 
   17990 NOTE 2          The TPM may implement the RAM portion of the counter such that the effective value of the NV
   17991                 counter is the sum of both the volatile and non-volatile parts. If so, then the TPM may initialize the
   17992                 RAM version of the counter to MAX_ORDERLY_COUNT and no update of NV is necessary.
   17993 
   17994 NOTE 3          When a new NV counter is created, the TPM may search all the coun ters to determine which has the
   17995                 highest value. In this search, the TPM would use the sum of the non -volatile and RAM portions of
   17996                 the counter. The RAM portion of the counter shall be properly initialized to reflect shutdown process
   17997                 (orderly or not) of the TPM.
   17998 
   17999 
   18000 
   18001 
   18002 Page 398                                       TCG Published                                           Family 2.0
   18003 October 30, 2014                       Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   18004 Trusted Platform Module Library                                                                 Part 3: Commands
   18006 
   18007 
   18008 31.3     TPM2_NV_DefineSpace
   18009 
   18010 31.3.1 General Description
   18011 
   18012 This command defines the attributes of an NV Index and causes the TPM to reserve space to hold the
   18013 data associated with the NV Index. If a definition already exists at the NV Index, the TPM will return
   18014 TPM_RC_NV_DEFINED.
   18015 The TPM will return TPM_RC_ATTRIBUTES if more                            than   one   of     TPMA_NV_COUNTER,
   18016 TPMA_NV_BITS, or TPMA_NV_EXTEND is SET in publicInfo.
   18017 
   18018 NOTE 1         It is not required that any of these three attributes be set.
   18019 
   18020 The TPM shall return TPM_RC_ATTRIBUTES if TPMA_NV_WRITTEN, TPM_NV_READLOCKED, or
   18021 TPMA_NV_WRITELOCKED is SET.
   18022 If TPMA_NV_COUNTER or TPMA_NV_BITS is SET, then publicInfodataSize shall be set to eight (8) or
   18023 the TPM shall return TPM_RC_SIZE.
   18024 If TPMA_NV_EXTEND is SET, then publicInfodataSize shall match the digest size of the
   18025 publicInfo.nameAlg or the TPM shall return TPM_RC_SIZE.
   18026 If the NV Index is an ordinary Index and publicInfodataSize is larger than supported by the TPM
   18027 implementation then the TPM shall return TPM_RC_SIZE.
   18028 
   18029 NOTE 2         The limit for the data size may vary according to the type of the index. For example, if the index has
   18030                TPMA_NV_ORDERLY SET, then the maximum size of an ordinary NV Index may be less than the
   18031                size of an ordinary NV Index that has TPMA_NV_ORDERLY CLEAR.
   18032 
   18033 At least one of TPMA_NV_PPREAD, TPMA_NV_OWNERREAD, TPMA_NV_AUTHREAD,                                              or
   18034 TPMA_NV_POLICYREAD shall be SET or the TPM shall return TPM_RC_ATTRIBUTES.
   18035 At least one of TPMA_NV_PPWRITE, TPMA_NV_OWNERWRITE, TPMA_NV_AUTHWRITE, or
   18036 TPMA_NV_POLICYWRITE shall be SET or the TPM shall return TPM_RC_ATTRIBUTES.
   18037 If TPMA_NV_CLEAR_STCLEAR is SET, then TPMA_NV_COUNTER shall be CLEAR or the TPM shall
   18038 return TPM_RC_ATTRIBUTES.
   18039 If platformAuth/platformPolicy is used for authorization, then TPMA_NV_PLATFORMCREATE shall be
   18040 SET in publicInfo. If ownerAuth/ownerPolicy is used for authorization, TPMA_NV_PLATFORMCREATE
   18041 shall be CLEAR in publicInfo. If TPMA_NV_PLATFORMCREATE is not set correctly for the authorization,
   18042 the TPM shall return TPM_RC_ATTRIBUTES.
   18043 If TPMA_NV_POLICY_DELETE is SET, then the authorization shall be with Platform Authorization or the
   18044 TPM shall return TPM_RC_ATTRIBUTES.
   18045 If the implementation does not support TPM2_NV_Increment(),                            the    TPM    shall    return
   18046 TPM_RC_ATTRIBUTES if TPMA_NV_COUNTER is SET.
   18047 If the implementation does not support TPM2_NV_SetBits(),                             the     TPM    shall    return
   18048 TPM_RC_ATTRIBUTES if TPMA_NV_BITS is SET.
   18049 If the implementation does not support TPM2_NV_Extend(),                              the     TPM    shall    return
   18050 TPM_RC_ATTRIBUTES if TPMA_NV_EXTEND is SET.
   18051 If the implementation does not support TPM2_NV_UndefineSpaceSpecial(), the TPM shall return
   18052 TPM_RC_ATTRIBUTES if TPMA_NV_POLICY_DELETE is SET.
   18053 After the successful completion of this command, the NV Index exists but TPMA_NV_WRITTEN will be
   18054 CLEAR. Any access of the NV data will return TPM_RC_NV_UINITIALIZED.
   18055 
   18056 
   18057 
   18058 
   18059 Family 2.0                                    TCG Published                                            Page 399
   18060 Level 00 Revision 01.16                Copyright  TCG 2006-2014                                October 30, 2014
   18061 Part 3: Commands                                                            Trusted Platform Module Library
   18063 
   18064 In some implementations, an NV Index with the TPMA_NV_COUNTER attribute may require special TPM
   18065 resources that provide higher endurance than regular NV. For those implementations, if this command
   18066 fails because of lack of resources, the TPM will return TPM_RC_NV_SPACE.
   18067 The value of auth is saved in the created structure. The size of auth is limited to be no larger than the size
   18068 of the digest produced by the NV Index's nameAlg (TPM_RC_SIZE).
   18069 
   18070 
   18071 
   18072 
   18073 Page 400                                      TCG Published                                     Family 2.0
   18074 October 30, 2014                      Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   18075 Trusted Platform Module Library                                                      Part 3: Commands
   18077 
   18078 
   18079 
   18080 31.3.2 Command and Response
   18081 
   18082                           Table 197  TPM2_NV_DefineSpace Command
   18083  Type                         Name                 Description
   18084 
   18085  TPMI_ST_COMMAND_TAG          tag                  TPM_ST_SESSIONS
   18086  UINT32                       commandSize
   18087  TPM_CC                       commandCode          TPM_CC_NV_DefineSpace {NV}
   18088 
   18089                                                    TPM_RH_OWNER or TPM_RH_PLATFORM+{PP}
   18090  TPMI_RH_PROVISION            @authHandle          Auth Index: 1
   18091                                                    Auth Role: USER
   18092 
   18093  TPM2B_AUTH                   auth                 the authorization value
   18094  TPM2B_NV_PUBLIC              publicInfo           the public parameters of the NV area
   18095 
   18096 
   18097                           Table 198  TPM2_NV_DefineSpace Response
   18098  Type                         Name                 Description
   18099 
   18100  TPM_ST                       tag                  see clause 6
   18101  UINT32                       responseSize
   18102  TPM_RC                       responseCode
   18103 
   18104 
   18105 
   18106 
   18107 Family 2.0                               TCG Published                                    Page 401
   18108 Level 00 Revision 01.16              Copyright  TCG 2006-2014                       October 30, 2014
   18109      Part 3: Commands                                                              Trusted Platform Module Library
   18111 
   18112 
   18113 
   18114      31.3.3 Detailed Actions
   18115 
   18116 1    #include "InternalRoutines.h"
   18117 2    #include "NV_DefineSpace_fp.h"
   18118 3    #ifdef TPM_CC_NV_DefineSpace // Conditional expansion of this file
   18119 
   18120 
   18121      Error Returns                 Meaning
   18122 
   18123      TPM_RC_NV_ATTRIBUTES          attributes of the index are not consistent
   18124      TPM_RC_NV_DEFINED             index already exists
   18125      TPM_RC_HIERARCHY              for authorizations using TPM_RH_PLATFORM phEnable_NV is
   18126                                    clear.
   18127      TPM_RC_NV_SPACE               Insufficient space for the index
   18128      TPM_RC_SIZE                   'auth->size' or 'publicInfo->authPolicy.size' is larger than the digest
   18129                                    size of 'publicInfo->nameAlg', or 'publicInfo->dataSize' is not
   18130                                    consistent with 'publicInfo->attributes'.
   18131 
   18132  4   TPM_RC
   18133  5   TPM2_NV_DefineSpace(
   18134  6       NV_DefineSpace_In   *in                  // IN: input parameter list
   18135  7       )
   18136  8   {
   18137  9       TPM_RC          result;
   18138 10       TPMA_NV         attributes;
   18139 11       UINT16          nameSize;
   18140 12
   18141 13       nameSize = CryptGetHashDigestSize(in->publicInfo.t.nvPublic.nameAlg);
   18142 14
   18143 15       // Check if NV is available. NvIsAvailable may return TPM_RC_NV_UNAVAILABLE
   18144 16       // TPM_RC_NV_RATE or TPM_RC_SUCCESS.
   18145 17       result = NvIsAvailable();
   18146 18       if(result != TPM_RC_SUCCESS)
   18147 19           return result;
   18148 20
   18149 21   // Input Validation
   18150 22       // If an index is being created by the owner and shEnable is
   18151 23       // clear, then we would not reach this point because ownerAuth
   18152 24       // can't be given when shEnable is CLEAR. However, if phEnable
   18153 25       // is SET but phEnableNV is CLEAR, we have to check here
   18154 26       if(in->authHandle == TPM_RH_PLATFORM && gc.phEnableNV == CLEAR)
   18155 27           return TPM_RC_HIERARCHY + RC_NV_DefineSpace_authHandle;
   18156 28
   18157 29       attributes = in->publicInfo.t.nvPublic.attributes;
   18158 30
   18159 31       //TPMS_NV_PUBLIC validation.
   18160 32       // Counters and bit fields must have a size of 8
   18161 33       if (   (attributes.TPMA_NV_COUNTER == SET || attributes.TPMA_NV_BITS == SET)
   18162 34           && (in->publicInfo.t.nvPublic.dataSize != 8))
   18163 35           return TPM_RC_SIZE + RC_NV_DefineSpace_publicInfo;
   18164 36
   18165 37       // check that the authPolicy consistent with hash algorithm
   18166 38       if(   in->publicInfo.t.nvPublic.authPolicy.t.size != 0
   18167 39          && in->publicInfo.t.nvPublic.authPolicy.t.size != nameSize)
   18168 40           return TPM_RC_SIZE + RC_NV_DefineSpace_publicInfo;
   18169 41
   18170 42       // make sure that the authValue is not too large
   18171 43       MemoryRemoveTrailingZeros(&in->auth);
   18172 44       if(in->auth.t.size > nameSize)
   18173 45           return TPM_RC_SIZE + RC_NV_DefineSpace_auth;
   18174 46
   18175 
   18176      Page 402                                   TCG Published                                                Family 2.0
   18177      October 30, 2014                   Copyright  TCG 2006-2014                         Level 00 Revision 01.16
   18178       Trusted Platform Module Library                                                Part 3: Commands
   18180 
   18181  47       //TPMA_NV validation.
   18182  48       // Locks may not be SET and written cannot be SET
   18183  49       if(   attributes.TPMA_NV_WRITTEN == SET
   18184  50          || attributes.TPMA_NV_WRITELOCKED == SET
   18185  51          || attributes.TPMA_NV_READLOCKED == SET)
   18186  52           return TPM_RC_ATTRIBUTES + RC_NV_DefineSpace_publicInfo;
   18187  53
   18188  54       // There must be a way to read the index
   18189  55       if(   attributes.TPMA_NV_OWNERREAD == CLEAR
   18190  56          && attributes.TPMA_NV_PPREAD == CLEAR
   18191  57          && attributes.TPMA_NV_AUTHREAD == CLEAR
   18192  58          && attributes.TPMA_NV_POLICYREAD == CLEAR)
   18193  59           return TPM_RC_ATTRIBUTES + RC_NV_DefineSpace_publicInfo;
   18194  60
   18195  61       // There must be a way to write the index
   18196  62       if(   attributes.TPMA_NV_OWNERWRITE == CLEAR
   18197  63          && attributes.TPMA_NV_PPWRITE == CLEAR
   18198  64          && attributes.TPMA_NV_AUTHWRITE == CLEAR
   18199  65          && attributes.TPMA_NV_POLICYWRITE == CLEAR)
   18200  66           return TPM_RC_ATTRIBUTES + RC_NV_DefineSpace_publicInfo;
   18201  67
   18202  68       // Make sure that no attribute is used that is not supported by the proper
   18203  69       // command
   18204  70   #if CC_NV_Increment == NO
   18205  71       if( attributes.TPMA_NV_COUNTER == SET)
   18206  72           return TPM_RC_ATTRIBUTES + RC_NV_DefineSpace_publicInfo;
   18207  73   #endif
   18208  74   #if CC_NV_SetBits == NO
   18209  75          if( attributes.TPMA_NV_BITS == SET)
   18210  76              return TPM_RC_ATTRIBUTES + RC_NV_DefineSpace_publicInfo;
   18211  77   #endif
   18212  78   #if CC_NV_Extend == NO
   18213  79         if( attributes.TPMA_NV_EXTEND == SET)
   18214  80             return TPM_RC_ATTRIBUTES + RC_NV_DefineSpace_publicInfo;
   18215  81   #endif
   18216  82   #if CC_NV_UndefineSpaceSpecial == NO
   18217  83        if( attributes.TPMA_NV_POLICY_DELETE == SET)
   18218  84            return TPM_RC_ATTRIBUTES + RC_NV_DefineSpace_publicInfo;
   18219  85   #endif
   18220  86
   18221  87       // Can be COUNTER or BITS or EXTEND but not more than one
   18222  88       if( attributes.TPMA_NV_COUNTER == SET
   18223  89          && attributes.TPMA_NV_BITS == SET)
   18224  90           return TPM_RC_ATTRIBUTES + RC_NV_DefineSpace_publicInfo;
   18225  91       if(   attributes.TPMA_NV_COUNTER == SET
   18226  92          && attributes.TPMA_NV_EXTEND == SET)
   18227  93           return TPM_RC_ATTRIBUTES + RC_NV_DefineSpace_publicInfo;
   18228  94       if(   attributes.TPMA_NV_BITS == SET
   18229  95          && attributes.TPMA_NV_EXTEND == SET)
   18230  96           return TPM_RC_ATTRIBUTES + RC_NV_DefineSpace_publicInfo;
   18231  97
   18232  98       // An index with TPMA_NV_CLEAR_STCLEAR can't be a counter and can't have
   18233  99       // TPMA_NV_WRITEDEFINE SET
   18234 100       if(     attributes.TPMA_NV_CLEAR_STCLEAR == SET
   18235 101           && (    attributes.TPMA_NV_COUNTER == SET
   18236 102                || attributes.TPMA_NV_WRITEDEFINE == SET)
   18237 103          )
   18238 104           return TPM_RC_ATTRIBUTES + RC_NV_DefineSpace_publicInfo;
   18239 105
   18240 106       // Make sure that the creator of the index can delete the index
   18241 107       if( (    in->publicInfo.t.nvPublic.attributes.TPMA_NV_PLATFORMCREATE == SET
   18242 108              && in->authHandle == TPM_RH_OWNER
   18243 109             )
   18244 110          || (   in->publicInfo.t.nvPublic.attributes.TPMA_NV_PLATFORMCREATE == CLEAR
   18245 111              && in->authHandle == TPM_RH_PLATFORM
   18246 112             )
   18247 
   18248       Family 2.0                           TCG Published                                  Page 403
   18249       Level 00 Revision 01.16           Copyright  TCG 2006-2014                    October 30, 2014
   18250       Part 3: Commands                                                     Trusted Platform Module Library
   18252 
   18253 113         )
   18254 114             return TPM_RC_ATTRIBUTES + RC_NV_DefineSpace_authHandle;
   18255 115
   18256 116      // If TPMA_NV_POLICY_DELETE is SET, then the index must be defined by
   18257 117      // the platform
   18258 118      if(    in->publicInfo.t.nvPublic.attributes.TPMA_NV_POLICY_DELETE == SET
   18259 119         && TPM_RH_PLATFORM != in->authHandle
   18260 120        )
   18261 121          return TPM_RC_ATTRIBUTES + RC_NV_DefineSpace_publicInfo;
   18262 122
   18263 123      // If the NV index is used as a PCR, the data size must match the digest
   18264 124      // size
   18265 125      if(   in->publicInfo.t.nvPublic.attributes.TPMA_NV_EXTEND == SET
   18266 126         && in->publicInfo.t.nvPublic.dataSize != nameSize
   18267 127        )
   18268 128          return TPM_RC_ATTRIBUTES + RC_NV_DefineSpace_publicInfo;
   18269 129
   18270 130      // See if the index is already defined.
   18271 131      if(NvIsUndefinedIndex(in->publicInfo.t.nvPublic.nvIndex))
   18272 132          return TPM_RC_NV_DEFINED;
   18273 133
   18274 134   // Internal Data Update
   18275 135       // define the space. A TPM_RC_NV_SPACE error may be returned at this point
   18276 136       result = NvDefineIndex(&in->publicInfo.t.nvPublic, &in->auth);
   18277 137       if(result != TPM_RC_SUCCESS)
   18278 138           return result;
   18279 139
   18280 140      return TPM_RC_SUCCESS;
   18281 141
   18282 142   }
   18283 143   #endif // CC_NV_DefineSpace
   18284 
   18285 
   18286 
   18287 
   18288       Page 404                                 TCG Published                                 Family 2.0
   18289       October 30, 2014                  Copyright  TCG 2006-2014               Level 00 Revision 01.16
   18290 Trusted Platform Module Library                                                           Part 3: Commands
   18292 
   18293 
   18294 31.4   TPM2_NV_UndefineSpace
   18295 
   18296 31.4.1 General Description
   18297 
   18298 This command removes an Index from the TPM.
   18299 If nvIndex is not defined, the TPM shall return TPM_RC_HANDLE.
   18300 If nvIndex references an Index that has its TPMA_NV_PLATFORMCREATE attribute SET, the TPM shall
   18301 return TPM_RC_NV_AUTHORIZATION unless Platform Authorization is provided.
   18302 If nvIndex references an Index that has its TPMA_NV_POLICY_DELETE attribute SET, the TPM shall
   18303 return TPM_RC_ATTRIBUTES.
   18304 
   18305 NOTE           An Index with TPMA_NV_PLATFORMCREATE CLEAR may be deleted with Platform Authorization
   18306                as long as shEnable is SET. If shEnable is CLEAR, indexes created using Owner Authorization are
   18307                not accessible even for deletion by the platform .
   18308 
   18309 
   18310 
   18311 
   18312 Family 2.0                                TCG Published                                          Page 405
   18313 Level 00 Revision 01.16             Copyright  TCG 2006-2014                             October 30, 2014
   18314 Part 3: Commands                                               Trusted Platform Module Library
   18316 
   18317 
   18318 31.4.2 Command and Response
   18319 
   18320                      Table 199  TPM2_NV_UndefineSpace Command
   18321  Type                    Name                Description
   18322 
   18323  TPMI_ST_COMMAND_TAG     tag                 TPM_ST_SESSIONS
   18324  UINT32                  commandSize
   18325  TPM_CC                  commandCode         TPM_CC_NV_UndefineSpace {NV}
   18326 
   18327                                              TPM_RH_OWNER or TPM_RH_PLATFORM+{PP}
   18328  TPMI_RH_PROVISION       @authHandle         Auth Index: 1
   18329                                              Auth Role: USER
   18330                                              the NV Index to remove from NV space
   18331  TPMI_RH_NV_INDEX        nvIndex
   18332                                              Auth Index: None
   18333 
   18334 
   18335                      Table 200  TPM2_NV_UndefineSpace Response
   18336  Type                    Name                Description
   18337 
   18338  TPM_ST                  tag                 see clause 6
   18339  UINT32                  responseSize
   18340  TPM_RC                  responseCode
   18341 
   18342 
   18343 
   18344 
   18345 Page 406                            TCG Published                                   Family 2.0
   18346 October 30, 2014               Copyright  TCG 2006-2014             Level 00 Revision 01.16
   18347      Trusted Platform Module Library                                                              Part 3: Commands
   18349 
   18350 
   18351 
   18352      31.4.3 Detailed Actions
   18353 
   18354 1    #include "InternalRoutines.h"
   18355 2    #include "NV_UndefineSpace_fp.h"
   18356 3    #ifdef TPM_CC_NV_UndefineSpace // Conditional expansion of this file
   18357 
   18358 
   18359      Error Returns                     Meaning
   18360 
   18361      TPM_RC_ATTRIBUTES                 TPMA_NV_POLICY_DELETE is SET in the Index referenced by
   18362                                        nvIndex so this command may not be used to delete this Index (see
   18363                                        TPM2_NV_UndefineSpaceSpecial())
   18364      TPM_RC_NV_AUTHORIZATION           attempt to use ownerAuth to delete an index created by the platform
   18365 
   18366  4   TPM_RC
   18367  5   TPM2_NV_UndefineSpace(
   18368  6       NV_UndefineSpace_In       *in                   // IN: input parameter list
   18369  7       )
   18370  8   {
   18371  9       TPM_RC            result;
   18372 10       NV_INDEX          nvIndex;
   18373 11
   18374 12       // The command needs NV update. Check if NV is available.
   18375 13       // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   18376 14       // this point
   18377 15       result = NvIsAvailable();
   18378 16       if(result != TPM_RC_SUCCESS) return result;
   18379 17
   18380 18   // Input Validation
   18381 19
   18382 20       // Get NV index info
   18383 21       NvGetIndexInfo(in->nvIndex, &nvIndex);
   18384 22
   18385 23       // This command can't be used to delete an index with TPMA_NV_POLICY_DELETE SET
   18386 24       if(SET == nvIndex.publicArea.attributes.TPMA_NV_POLICY_DELETE)
   18387 25           return TPM_RC_ATTRIBUTES + RC_NV_UndefineSpace_nvIndex;
   18388 26
   18389 27       // The owner may only delete an index that was defined with ownerAuth. The
   18390 28       // platform may delete an index that was created with either auth.
   18391 29       if(   in->authHandle == TPM_RH_OWNER
   18392 30          && nvIndex.publicArea.attributes.TPMA_NV_PLATFORMCREATE == SET)
   18393 31           return TPM_RC_NV_AUTHORIZATION;
   18394 32
   18395 33   // Internal Data Update
   18396 34
   18397 35       // Call implementation dependent internal routine to delete NV index
   18398 36       NvDeleteEntity(in->nvIndex);
   18399 37
   18400 38       return TPM_RC_SUCCESS;
   18401 39   }
   18402 40   #endif // CC_NV_UndefineSpace
   18403 
   18404 
   18405 
   18406 
   18407      Family 2.0                                  TCG Published                                             Page 407
   18408      Level 00 Revision 01.16               Copyright  TCG 2006-2014                              October 30, 2014
   18409 Part 3: Commands                                                         Trusted Platform Module Library
   18411 
   18412 
   18413 31.5   TPM2_NV_UndefineSpaceSpecial
   18414 
   18415 31.5.1 General Description
   18416 
   18417 This command allows removal of a platform-created NV Index that has TPMA_NV_POLICY_DELETE
   18418 SET.
   18419 This command requires that the policy of the NV Index be satisfied before the NV Index may be deleted.
   18420 Because administrative role is required, the policy must contain a command that sets the policy command
   18421 code to TPM_CC_NV_UndefineSpaceSpecial. This indicates that the policy that is being used is a policy
   18422 that is for this command, and not a policy that would approve another use. That is, authority to use an
   18423 object does not grant authority to undefine the object.
   18424 If nvIndex is not defined, the TPM shall return TPM_RC_HANDLE.
   18425 If nvIndex references an     Index  that    has   its    TPMA_NV_PLATFORMCREATE                         or
   18426 TPMA_NV_POLICY_DELETE attribute CLEAR, the TPM shall return TPM_RC_ATTRIBUTES.
   18427 
   18428 NOTE           An   Index    with     TPMA_NV_PLATFORMCREATE              CLEAR       may be deleted  with
   18429                TPM2_UndefineSpace()as long as shEnable is SET. If shEnable is CLEAR, indexes created using
   18430                Owner Authorization are not accessible even for deletion by the platform .
   18431 
   18432 
   18433 
   18434 
   18435 Page 408                                   TCG Published                                    Family 2.0
   18436 October 30, 2014                   Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   18437 Trusted Platform Module Library                                               Part 3: Commands
   18439 
   18440 
   18441 31.5.2 Command and Response
   18442 
   18443                      Table 201  TPM2_NV_UndefineSpaceSpecial Command
   18444  Type                         Name                Description
   18445 
   18446  TPMI_ST_COMMAND_TAG          tag                 TPM_ST_SESSIONS
   18447  UINT32                       commandSize
   18448  TPM_CC                       commandCode         TPM_CC_NV_UndefineSpaceSpecial {NV}
   18449 
   18450                                                   Index to be deleted
   18451  TPMI_RH_NV_INDEX             @nvIndex            Auth Index: 1
   18452                                                   Auth Role: ADMIN
   18453                                                   TPM_RH_PLATFORM + {PP}
   18454  TPMI_RH_PLATFORM             @platform           Auth Index: 2
   18455                                                   Auth Role: USER
   18456 
   18457 
   18458                      Table 202  TPM2_NV_UndefineSpaceSpecial Response
   18459  Type                         Name                Description
   18460 
   18461  TPM_ST                       tag                 see clause 6
   18462  UINT32                       responseSize
   18463  TPM_RC                       responseCode
   18464 
   18465 
   18466 
   18467 
   18468 Family 2.0                              TCG Published                                 Page 409
   18469 Level 00 Revision 01.16             Copyright  TCG 2006-2014                 October 30, 2014
   18470      Part 3: Commands                                                        Trusted Platform Module Library
   18472 
   18473 
   18474 
   18475      31.5.3 Detailed Actions
   18476 
   18477 1    #include "InternalRoutines.h"
   18478 2    #include "NV_UndefineSpaceSpecial_fp.h"
   18479 3    #ifdef TPM_CC_NV_UndefineSpaceSpecial // Conditional expansion of this file
   18480 
   18481 
   18482      Error Returns                    Meaning
   18483 
   18484      TPM_RC_ATTRIBUTES                TPMA_NV_POLICY_DELETE is not SET in the Index referenced by
   18485                                       nvIndex
   18486 
   18487  4   TPM_RC
   18488  5   TPM2_NV_UndefineSpaceSpecial(
   18489  6       NV_UndefineSpaceSpecial_In      *in              // IN: input parameter list
   18490  7       )
   18491  8   {
   18492  9       TPM_RC            result;
   18493 10       NV_INDEX          nvIndex;
   18494 11
   18495 12       // The command needs NV update. Check if NV is available.
   18496 13       // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   18497 14       // this point
   18498 15       result = NvIsAvailable();
   18499 16       if(result != TPM_RC_SUCCESS)
   18500 17           return result;
   18501 18
   18502 19   // Input Validation
   18503 20
   18504 21       // Get NV index info
   18505 22       NvGetIndexInfo(in->nvIndex, &nvIndex);
   18506 23
   18507 24       // This operation only applies when the TPMA_NV_POLICY_DELETE attribute is SET
   18508 25       if(CLEAR == nvIndex.publicArea.attributes.TPMA_NV_POLICY_DELETE)
   18509 26           return TPM_RC_ATTRIBUTES + RC_NV_UndefineSpaceSpecial_nvIndex;
   18510 27
   18511 28   // Internal Data Update
   18512 29
   18513 30       // Call implementation dependent internal routine to delete NV index
   18514 31       NvDeleteEntity(in->nvIndex);
   18515 32
   18516 33       return TPM_RC_SUCCESS;
   18517 34   }
   18518 35   #endif // CC_NV_UndefineSpaceSpecial
   18519 
   18520 
   18521 
   18522 
   18523      Page 410                                    TCG Published                                 Family 2.0
   18524      October 30, 2014                     Copyright  TCG 2006-2014                Level 00 Revision 01.16
   18525 Trusted Platform Module Library                                                   Part 3: Commands
   18527 
   18528 
   18529 31.6   TPM2_NV_ReadPublic
   18530 
   18531 31.6.1 General Description
   18532 
   18533 This command is used to read the public area and Name of an NV Index. The public area of an Index is
   18534 not privacy-sensitive and no authorization is required to read this data.
   18535 
   18536 
   18537 
   18538 
   18539 Family 2.0                             TCG Published                                    Page 411
   18540 Level 00 Revision 01.16           Copyright  TCG 2006-2014                       October 30, 2014
   18541 Part 3: Commands                                                  Trusted Platform Module Library
   18543 
   18544 
   18545 
   18546 31.6.2 Command and Response
   18547 
   18548                        Table 203  TPM2_NV_ReadPublic Command
   18549  Type                     Name                Description
   18550 
   18551                                               TPM_ST_SESSIONS if an audit or encrypt session is
   18552  TPMI_ST_COMMAND_TAG      tag
   18553                                               present; otherwise, TPM_ST_NO_SESSIONS
   18554  UINT32                   commandSize
   18555  TPM_CC                   commandCode         TPM_CC_NV_ReadPublic
   18556 
   18557                                               the NV Index
   18558  TPMI_RH_NV_INDEX         nvIndex
   18559                                               Auth Index: None
   18560 
   18561 
   18562                        Table 204  TPM2_NV_ReadPublic Response
   18563  Type                     Name                Description
   18564  TPM_ST                   tag                 see clause 6
   18565  UINT32                   responseSize
   18566  TPM_RC                   responseCode
   18567 
   18568  TPM2B_NV_PUBLIC          nvPublic            the public area of the NV Index
   18569  TPM2B_NAME               nvName              the Name of the nvIndex
   18570 
   18571 
   18572 
   18573 
   18574 Page 412                             TCG Published                                  Family 2.0
   18575 October 30, 2014                Copyright  TCG 2006-2014                Level 00 Revision 01.16
   18576      Trusted Platform Module Library                                         Part 3: Commands
   18578 
   18579 
   18580 
   18581      31.6.3 Detailed Actions
   18582 
   18583  1   #include "InternalRoutines.h"
   18584  2   #include "NV_ReadPublic_fp.h"
   18585  3   #ifdef TPM_CC_NV_ReadPublic // Conditional expansion of this file
   18586  4   TPM_RC
   18587  5   TPM2_NV_ReadPublic(
   18588  6       NV_ReadPublic_In      *in,          // IN: input parameter list
   18589  7       NV_ReadPublic_Out     *out          // OUT: output parameter list
   18590  8       )
   18591  9   {
   18592 10       NV_INDEX         nvIndex;
   18593 11
   18594 12   // Command Output
   18595 13
   18596 14       // Get NV index info
   18597 15       NvGetIndexInfo(in->nvIndex, &nvIndex);
   18598 16
   18599 17       // Copy data to output
   18600 18       out->nvPublic.t.nvPublic = nvIndex.publicArea;
   18601 19
   18602 20       // Compute NV name
   18603 21       out->nvName.t.size = NvGetName(in->nvIndex, &out->nvName.t.name);
   18604 22
   18605 23       return TPM_RC_SUCCESS;
   18606 24   }
   18607 25   #endif // CC_NV_ReadPublic
   18608 
   18609 
   18610 
   18611 
   18612      Family 2.0                           TCG Published                           Page 413
   18613      Level 00 Revision 01.16           Copyright  TCG 2006-2014             October 30, 2014
   18614 Part 3: Commands                                                             Trusted Platform Module Library
   18616 
   18617 
   18618 31.7     TPM2_NV_Write
   18619 
   18620 31.7.1 General Description
   18621 
   18622 This command writes a value to an area in NV memory that was previously defined by
   18623 TPM2_NV_DefineSpace().
   18624 Proper authorizations are required for this command as determined by TPMA_NV_PPWRITE;
   18625 TPMA_NV_OWNERWRITE; TPMA_NV_AUTHWRITE; and, if TPMA_NV_POLICY_WRITE is SET, the
   18626 authPolicy of the NV Index.
   18627 If the TPMA_NV_WRITELOCKED attribute of the NV Index is SET, then the TPM shall return
   18628 TPM_RC_NV_LOCKED.
   18629 
   18630 NOTE 1          If authorization sessions are present, they are checked before checks to see if writes to the NV
   18631                 Index are locked.
   18632 
   18633 If TPMA_NV_COUNTER, TPMA_NV_BITS or TPMA_NV_EXTEND of the NV Index is SET, then the
   18634 TPM shall return TPM_RC_ATTRIBUTES.
   18635 If the size of the data parameter plus the offset parameter adds to a value that is greater than the size of
   18636 the NV Index data, the TPM shall return TPM_RC_NV_RANGE and not write any data to the NV Index.
   18637 If the TPMA_NV_WRITEALL attribute of the NV Index is SET, then the TPM shall return
   18638 TPM_RC_NV_RANGE if the size of the data parameter of the command is not the same as the data field
   18639 of the NV Index.
   18640 If all checks succeed, the TPM will merge the data.size octets of data.buffer value into the nvIndexdata
   18641 starting at nvIndexdata[offset]. If the NV memory is implemented with a technology that has endurance
   18642 limitations, the TPM shall check that the merged data is different from the current contents of the NV
   18643 Index and only perform a write to NV memory if they differ.
   18644 After successful completion of this command, TPMA_NV_WRITTEN for the NV Index will be SET.
   18645 
   18646 NOTE 2          Once SET, TPMA_NV_WRITTEN remains SET until the NV Index is undefined or the NV Index is
   18647                 cleared.
   18648 
   18649 
   18650 
   18651 
   18652 Page 414                                      TCG Published                                       Family 2.0
   18653 October 30, 2014                      Copyright  TCG 2006-2014                    Level 00 Revision 01.16
   18654 Trusted Platform Module Library                                                        Part 3: Commands
   18656 
   18657 
   18658 31.7.2 Command and Response
   18659 
   18660                               Table 205  TPM2_NV_Write Command
   18661  Type                         Name                 Description
   18662 
   18663  TPMI_ST_COMMAND_TAG          tag                  TPM_ST_SESSIONS
   18664  UINT32                       commandSize
   18665  TPM_CC                       commandCode          TPM_CC_NV_Write {NV}
   18666 
   18667                                                    handle indicating the source of the authorization value
   18668  TPMI_RH_NV_AUTH              @authHandle          Auth Index: 1
   18669                                                    Auth Role: USER
   18670                                                    the NV Index of the area to write
   18671  TPMI_RH_NV_INDEX             nvIndex
   18672                                                    Auth Index: None
   18673 
   18674  TPM2B_MAX_NV_BUFFER          data                 the data to write
   18675  UINT16                       offset               the offset into the NV Area
   18676 
   18677 
   18678                               Table 206  TPM2_NV_Write Response
   18679  Type                         Name                 Description
   18680 
   18681  TPM_ST                       tag                  see clause 6
   18682  UINT32                       responseSize
   18683  TPM_RC                       responseCode
   18684 
   18685 
   18686 
   18687 
   18688 Family 2.0                              TCG Published                                         Page 415
   18689 Level 00 Revision 01.16              Copyright  TCG 2006-2014                         October 30, 2014
   18690      Part 3: Commands                                                               Trusted Platform Module Library
   18692 
   18693 
   18694 
   18695      31.7.3 Detailed Actions
   18696 
   18697 1    #include "InternalRoutines.h"
   18698 2    #include "NV_Write_fp.h"
   18699 3    #ifdef TPM_CC_NV_Write // Conditional expansion of this file
   18700 4    #include "NV_spt_fp.h"
   18701 
   18702 
   18703      Error Returns                    Meaning
   18704 
   18705      TPM_RC_ATTRIBUTES                Index referenced by nvIndex has either TPMA_NV_BITS,
   18706                                       TPMA_NV_COUNTER, or TPMA_NV_EVENT attribute SET
   18707      TPM_RC_NV_AUTHORIZATION          the authorization was valid but the authorizing entity (authHandle) is
   18708                                       not allowed to write to the Index referenced by nvIndex
   18709      TPM_RC_NV_LOCKED                 Index referenced by nvIndex is write locked
   18710      TPM_RC_NV_RANGE                  if TPMA_NV_WRITEALL is SET then the write is not the size of the
   18711                                       Index referenced by nvIndex; otherwise, the write extends beyond the
   18712                                       limits of the Index
   18713 
   18714  5   TPM_RC
   18715  6   TPM2_NV_Write(
   18716  7       NV_Write_In       *in                 // IN: input parameter list
   18717  8       )
   18718  9   {
   18719 10       NV_INDEX          nvIndex;
   18720 11       TPM_RC            result;
   18721 12
   18722 13   // Input Validation
   18723 14
   18724 15       // Get NV index info
   18725 16       NvGetIndexInfo(in->nvIndex, &nvIndex);
   18726 17
   18727 18       // common access checks. NvWrtieAccessChecks() may return
   18728 19       // TPM_RC_NV_AUTHORIZATION or TPM_RC_NV_LOCKED
   18729 20       result = NvWriteAccessChecks(in->authHandle, in->nvIndex);
   18730 21       if(result != TPM_RC_SUCCESS)
   18731 22           return result;
   18732 23
   18733 24       // Bits index, extend index or counter index may not be updated by
   18734 25       // TPM2_NV_Write
   18735 26       if(   nvIndex.publicArea.attributes.TPMA_NV_COUNTER == SET
   18736 27          || nvIndex.publicArea.attributes.TPMA_NV_BITS == SET
   18737 28          || nvIndex.publicArea.attributes.TPMA_NV_EXTEND == SET)
   18738 29           return TPM_RC_ATTRIBUTES;
   18739 30
   18740 31       // Too much data
   18741 32       if((in->data.t.size + in->offset) > nvIndex.publicArea.dataSize)
   18742 33           return TPM_RC_NV_RANGE;
   18743 34
   18744 35       // If this index requires a full sized write, make sure that input range is
   18745 36       // full sized
   18746 37       if(   nvIndex.publicArea.attributes.TPMA_NV_WRITEALL == SET
   18747 38          && in->data.t.size < nvIndex.publicArea.dataSize)
   18748 39           return TPM_RC_NV_RANGE;
   18749 40
   18750 41   // Internal Data Update
   18751 42
   18752 43       // Perform the write. This called routine will SET the TPMA_NV_WRITTEN
   18753 44       // attribute if it has not already been SET. If NV isn't available, an error
   18754 45       // will be returned.
   18755 46       return NvWriteIndexData(in->nvIndex, &nvIndex, in->offset,
   18756 47                               in->data.t.size, in->data.t.buffer);
   18757 
   18758      Page 416                                      TCG Published                                          Family 2.0
   18759      October 30, 2014                     Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   18760      Trusted Platform Module Library                               Part 3: Commands
   18762 
   18763 48
   18764 49   }
   18765 50   #endif // CC_NV_Write
   18766 
   18767 
   18768 
   18769 
   18770      Family 2.0                           TCG Published                 Page 417
   18771      Level 00 Revision 01.16           Copyright  TCG 2006-2014   October 30, 2014
   18772 Part 3: Commands                                                            Trusted Platform Module Library
   18774 
   18775 
   18776 31.8     TPM2_NV_Increment
   18777 
   18778 31.8.1 General Description
   18779 
   18780 This command is used to increment the value in an NV Index that has TPMA_NV_COUNTER SET. The
   18781 data value of the NV Index is incremented by one.
   18782 
   18783 NOTE 1         The NV Index counter is an unsigned value.
   18784 
   18785 If TPMA_NV_COUNTER          is   not    SET   in   the   indicated   NV   Index,   the   TPM     shall   return
   18786 TPM_RC_ATTRIBUTES.
   18787 If TPMA_NV_WRITELOCKED is SET, the TPM shall return TPM_RC_NV_LOCKED.
   18788 If TPMA_NV_WRITTEN is CLEAR, it will be SET.
   18789 If TPMA_NV_ORDERLY is SET, and the difference between the volatile and non-volatile versions of this
   18790 field is greater than MAX_ORDERLY_COUNT, then the non-volatile version of the counter is updated.
   18791 
   18792 NOTE 2         If a TPM implements TPMA_NV_ORDERLY and an Index is defined with TPMA_NV_ORDERLY and
   18793                TPM_NV_COUNTER both SET, then in the Event of a non-orderly shutdown, the non-volatile value
   18794                for the counter Index will be advanced by MAX_ORDERLY_COUNT at the next TPM2_Startup().
   18795 
   18796 NOTE 3         An allowed implementation would keep a counter value in NV and a resettable counter in RAM. The
   18797                reported value of the NV Index would be the sum of the two values. When the RAM count increments
   18798                past the maximum allowed value (MAX_ORDERLY_COUNT), the non-volatile version of the count is
   18799                updated with the sum of the values and the RAM count is reset to zero.
   18800 
   18801 
   18802 
   18803 
   18804 Page 418                                      TCG Published                                      Family 2.0
   18805 October 30, 2014                       Copyright  TCG 2006-2014                   Level 00 Revision 01.16
   18806 Trusted Platform Module Library                                                       Part 3: Commands
   18808 
   18809 
   18810 31.8.2 Command and Response
   18811 
   18812                            Table 207  TPM2_NV_Increment Command
   18813  Type                         Name                Description
   18814 
   18815  TPMI_ST_COMMAND_TAG          tag                 TPM_ST_SESSIONS
   18816  UINT32                       commandSize
   18817  TPM_CC                       commandCode         TPM_CC_NV_Increment {NV}
   18818 
   18819                                                   handle indicating the source of the authorization value
   18820  TPMI_RH_NV_AUTH              @authHandle         Auth Index: 1
   18821                                                   Auth Role: USER
   18822                                                   the NV Index to increment
   18823  TPMI_RH_NV_INDEX             nvIndex
   18824                                                   Auth Index: None
   18825 
   18826 
   18827                            Table 208  TPM2_NV_Increment Response
   18828  Type                         Name                Description
   18829 
   18830  TPM_ST                       tag                 see clause 6
   18831  UINT32                       responseSize
   18832  TPM_RC                       responseCode
   18833 
   18834 
   18835 
   18836 
   18837 Family 2.0                             TCG Published                                         Page 419
   18838 Level 00 Revision 01.16             Copyright  TCG 2006-2014                         October 30, 2014
   18839      Part 3: Commands                                                       Trusted Platform Module Library
   18841 
   18842 
   18843 
   18844      31.8.3 Detailed Actions
   18845 
   18846 1    #include "InternalRoutines.h"
   18847 2    #include "NV_Increment_fp.h"
   18848 3    #ifdef TPM_CC_NV_Increment // Conditional expansion of this file
   18849 4    #include "NV_spt_fp.h"
   18850 
   18851 
   18852      Error Returns                   Meaning
   18853 
   18854      TPM_RC_ATTRIBUTES               NV index is not a counter
   18855      TPM_RC_NV_AUTHORIZATION         authorization failure
   18856      TPM_RC_NV_LOCKED                Index is write locked
   18857 
   18858  5   TPM_RC
   18859  6   TPM2_NV_Increment(
   18860  7       NV_Increment_In       *in                  // IN: input parameter list
   18861  8       )
   18862  9   {
   18863 10       TPM_RC            result;
   18864 11       NV_INDEX          nvIndex;
   18865 12       UINT64            countValue;
   18866 13
   18867 14   // Input Validation
   18868 15
   18869 16       // Common access checks, a TPM_RC_NV_AUTHORIZATION or TPM_RC_NV_LOCKED
   18870 17       // error may be returned at this point
   18871 18       result = NvWriteAccessChecks(in->authHandle, in->nvIndex);
   18872 19       if(result != TPM_RC_SUCCESS)
   18873 20           return result;
   18874 21
   18875 22       // Get NV index info
   18876 23       NvGetIndexInfo(in->nvIndex, &nvIndex);
   18877 24
   18878 25       // Make sure that this is a counter
   18879 26       if(nvIndex.publicArea.attributes.TPMA_NV_COUNTER != SET)
   18880 27           return TPM_RC_ATTRIBUTES + RC_NV_Increment_nvIndex;
   18881 28
   18882 29   // Internal Data Update
   18883 30
   18884 31       // If counter index is not been written, initialize it
   18885 32       if(nvIndex.publicArea.attributes.TPMA_NV_WRITTEN == CLEAR)
   18886 33           countValue = NvInitialCounter();
   18887 34       else
   18888 35           // Read NV data in native format for TPM CPU.
   18889 36           NvGetIntIndexData(in->nvIndex, &nvIndex, &countValue);
   18890 37
   18891 38       // Do the increment
   18892 39       countValue++;
   18893 40
   18894 41       // If this is an orderly counter that just rolled over, need to be able to
   18895 42       // write to NV to proceed. This check is done here, because NvWriteIndexData()
   18896 43       // does not see if the update is for counter rollover.
   18897 44       if(    nvIndex.publicArea.attributes.TPMA_NV_ORDERLY == SET
   18898 45           && (countValue & MAX_ORDERLY_COUNT) == 0)
   18899 46       {
   18900 47           result = NvIsAvailable();
   18901 48           if(result != TPM_RC_SUCCESS)
   18902 49               return result;
   18903 50
   18904 51           // Need to force an NV update
   18905 52           g_updateNV = TRUE;
   18906 
   18907 
   18908      Page 420                                     TCG Published                               Family 2.0
   18909      October 30, 2014                     Copyright  TCG 2006-2014               Level 00 Revision 01.16
   18910      Trusted Platform Module Library                                             Part 3: Commands
   18912 
   18913 53       }
   18914 54
   18915 55       // Write NV data back. A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may
   18916 56       // be returned at this point. If necessary, this function will set the
   18917 57       // TPMA_NV_WRITTEN attribute
   18918 58       return NvWriteIndexData(in->nvIndex, &nvIndex, 0, 8, &countValue);
   18919 59
   18920 60   }
   18921 61   #endif // CC_NV_Increment
   18922 
   18923 
   18924 
   18925 
   18926      Family 2.0                           TCG Published                               Page 421
   18927      Level 00 Revision 01.16           Copyright  TCG 2006-2014                 October 30, 2014
   18928 Part 3: Commands                                                              Trusted Platform Module Library
   18930 
   18931 
   18932 31.9     TPM2_NV_Extend
   18933 
   18934 31.9.1 General Description
   18935 
   18936 This command extends a value to an area in NV memory that was previously defined by
   18937 TPM2_NV_DefineSpace.
   18938 If TPMA_NV_EXTEND is not SET, then the TPM shall return TPM_RC_ATTRIBUTES.
   18939 Proper write authorizations are required for this command as determined by TPMA_NV_PPWRITE,
   18940 TPMA_NV_OWNERWRITE, TPMA_NV_AUTHWRITE, and the authPolicy of the NV Index.
   18941 After successful completion of this command, TPMA_NV_WRITTEN for the NV Index will be SET.
   18942 
   18943 NOTE 1           Once SET, TPMA_NV_WRITTEN remains SET until the NV Index is undefined, unless the
   18944                  TPMA_NV_CLEAR_STCLEAR attribute is SET and a TPM Reset or TPM Restart occurs.
   18945 
   18946 If the TPMA_NV_WRITELOCKED attribute of the NV Index is SET, then the TPM shall return
   18947 TPM_RC_NV_LOCKED.
   18948 
   18949 NOTE 2           If authorization sessions are present, they are checked before checks to see if writes to the NV
   18950                  Index are locked.
   18951 
   18952 The data.buffer parameter may be larger than the defined size of the NV Index.
   18953 The Index will be updated by:
   18954                        nvIndexdatanew  HnameAkg(nvIndexdataold || data.buffer)                           (39)
   18955 where
   18956          HnameAkg()                        the hash algorithm indicated in nvIndexnameAlg
   18957          nvIndexdata                      the value of the data field in the NV Index
   18958          data.buffer                       the data buffer of the command parameter
   18959 
   18960 NOTE 3           If TPMA_NV_WRITTEN is CLEAR, then nvIndexdata is a Zero Digest.
   18961 
   18962 
   18963 
   18964 
   18965 Page 422                                       TCG Published                                       Family 2.0
   18966 October 30, 2014                       Copyright  TCG 2006-2014                    Level 00 Revision 01.16
   18967 Trusted Platform Module Library                                                        Part 3: Commands
   18969 
   18970 
   18971 31.9.2 Command and Response
   18972 
   18973                              Table 209  TPM2_NV_Extend Command
   18974  Type                         Name                 Description
   18975 
   18976  TPMI_ST_COMMAND_TAG          tag                  TPM_ST_SESSIONS
   18977  UINT32                       commandSize
   18978  TPM_CC                       commandCode          TPM_CC_NV_Extend {NV}
   18979 
   18980                                                    handle indicating the source of the authorization value
   18981  TPMI_RH_NV_AUTH              @authHandle          Auth Index: 1
   18982                                                    Auth Role: USER
   18983                                                    the NV Index to extend
   18984  TPMI_RH_NV_INDEX             nvIndex
   18985                                                    Auth Index: None
   18986 
   18987  TPM2B_MAX_NV_BUFFER          data                 the data to extend
   18988 
   18989 
   18990                              Table 210  TPM2_NV_Extend Response
   18991  Type                         Name                 Description
   18992 
   18993  TPM_ST                       tag                  see clause 6
   18994  UINT32                       responseSize
   18995  TPM_RC                       responseCode
   18996 
   18997 
   18998 
   18999 
   19000 Family 2.0                              TCG Published                                         Page 423
   19001 Level 00 Revision 01.16              Copyright  TCG 2006-2014                         October 30, 2014
   19002      Part 3: Commands                                                          Trusted Platform Module Library
   19004 
   19005 
   19006 
   19007      31.9.3 Detailed Actions
   19008 
   19009 1    #include "InternalRoutines.h"
   19010 2    #include "NV_Extend_fp.h"
   19011 3    #ifdef TPM_CC_NV_Extend // Conditional expansion of this file
   19012 4    #include "NV_spt_fp.h"
   19013 
   19014 
   19015      Error Returns               Meaning
   19016 
   19017      TPM_RC_ATTRIBUTES           the TPMA_NV_EXTEND attribute is not SET in the Index referenced
   19018                                  by nvIndex
   19019      TPM_RC_NV_AUTHORIZATION     the authorization was valid but the authorizing entity (authHandle) is
   19020                                  not allowed to write to the Index referenced by nvIndex
   19021      TPM_RC_NV_LOCKED            the Index referenced by nvIndex is locked for writing
   19022 
   19023  5   TPM_RC
   19024  6   TPM2_NV_Extend(
   19025  7       NV_Extend_In      *in            // IN: input parameter list
   19026  8       )
   19027  9   {
   19028 10       TPM_RC                  result;
   19029 11       NV_INDEX                nvIndex;
   19030 12
   19031 13       TPM2B_DIGEST            oldDigest;
   19032 14       TPM2B_DIGEST            newDigest;
   19033 15       HASH_STATE              hashState;
   19034 16
   19035 17   // Input Validation
   19036 18
   19037 19       // Common access checks, NvWriteAccessCheck() may return TPM_RC_NV_AUTHORIZATION
   19038 20       // or TPM_RC_NV_LOCKED
   19039 21       result = NvWriteAccessChecks(in->authHandle, in->nvIndex);
   19040 22       if(result != TPM_RC_SUCCESS)
   19041 23           return result;
   19042 24
   19043 25       // Get NV index info
   19044 26       NvGetIndexInfo(in->nvIndex, &nvIndex);
   19045 27
   19046 28       // Make sure that this is an extend index
   19047 29       if(nvIndex.publicArea.attributes.TPMA_NV_EXTEND != SET)
   19048 30           return TPM_RC_ATTRIBUTES + RC_NV_Extend_nvIndex;
   19049 31
   19050 32       // If the Index is not-orderly, or if this is the first write, NV will
   19051 33       // need to be updated.
   19052 34       if(   nvIndex.publicArea.attributes.TPMA_NV_ORDERLY == CLEAR
   19053 35          || nvIndex.publicArea.attributes.TPMA_NV_WRITTEN == CLEAR)
   19054 36       {
   19055 37           // Check if NV is available. NvIsAvailable may return TPM_RC_NV_UNAVAILABLE
   19056 38           // TPM_RC_NV_RATE or TPM_RC_SUCCESS.
   19057 39           result = NvIsAvailable();
   19058 40           if(result != TPM_RC_SUCCESS)
   19059 41               return result;
   19060 42       }
   19061 43
   19062 44   // Internal Data Update
   19063 45
   19064 46       // Perform the write.
   19065 47       oldDigest.t.size = CryptGetHashDigestSize(nvIndex.publicArea.nameAlg);
   19066 48       pAssert(oldDigest.t.size <= sizeof(oldDigest.t.buffer));
   19067 49       if(nvIndex.publicArea.attributes.TPMA_NV_WRITTEN == SET)
   19068 50       {
   19069 
   19070      Page 424                                 TCG Published                                          Family 2.0
   19071      October 30, 2014                Copyright  TCG 2006-2014                           Level 00 Revision 01.16
   19072      Trusted Platform Module Library                                             Part 3: Commands
   19074 
   19075 51           NvGetIndexData(in->nvIndex, &nvIndex, 0,
   19076 52                          oldDigest.t.size, oldDigest.t.buffer);
   19077 53       }
   19078 54       else
   19079 55       {
   19080 56           MemorySet(oldDigest.t.buffer, 0, oldDigest.t.size);
   19081 57       }
   19082 58       // Start hash
   19083 59       newDigest.t.size = CryptStartHash(nvIndex.publicArea.nameAlg, &hashState);
   19084 60
   19085 61       // Adding old digest
   19086 62       CryptUpdateDigest2B(&hashState, &oldDigest.b);
   19087 63
   19088 64       // Adding new data
   19089 65       CryptUpdateDigest2B(&hashState, &in->data.b);
   19090 66
   19091 67       // Complete hash
   19092 68       CryptCompleteHash2B(&hashState, &newDigest.b);
   19093 69
   19094 70       // Write extended hash back.
   19095 71       // Note, this routine will SET the TPMA_NV_WRITTEN attribute if necessary
   19096 72       return NvWriteIndexData(in->nvIndex, &nvIndex, 0,
   19097 73                               newDigest.t.size, newDigest.t.buffer);
   19098 74   }
   19099 75   #endif // CC_NV_Extend
   19100 
   19101 
   19102 
   19103 
   19104      Family 2.0                           TCG Published                               Page 425
   19105      Level 00 Revision 01.16           Copyright  TCG 2006-2014                 October 30, 2014
   19106 Part 3: Commands                                                        Trusted Platform Module Library
   19108 
   19109 
   19110 31.10 TPM2_NV_SetBits
   19111 
   19112 31.10.1     General Description
   19113 
   19114 This command is used to SET bits in an NV Index that was created as a bit field. Any number of bits from
   19115 0 to 64 may be SET. The contents of data are ORed with the current contents of the NV Index starting at
   19116 offset.
   19117 If TPMA_NV_WRITTEN is not SET, then, for the purposes of this command, the NV Index is considered
   19118 to contain all zero bits and data is OR with that value.
   19119 If TPMA_NV_BITS is not SET, then the TPM shall return TPM_RC_ATTRIBUTES.
   19120 After successful completion of this command, TPMA_NV_WRITTEN for the NV Index will be SET.
   19121 
   19122 NOTE            TPMA_NV_WRITTEN will be SET even if no bits were SET.
   19123 
   19124 
   19125 
   19126 
   19127 Page 426                                    TCG Published                                  Family 2.0
   19128 October 30, 2014                    Copyright  TCG 2006-2014                 Level 00 Revision 01.16
   19129 Trusted Platform Module Library                                                         Part 3: Commands
   19131 
   19132 
   19133 31.10.2    Command and Response
   19134 
   19135                              Table 211  TPM2_NV_SetBits Command
   19136  Type                         Name                 Description
   19137 
   19138  TPMI_ST_COMMAND_TAG          tag                  TPM_ST_SESSIONS
   19139  UINT32                       commandSize
   19140  TPM_CC                       commandCode          TPM_CC_NV_SetBits {NV}
   19141 
   19142                                                    handle indicating the source of the authorization value
   19143  TPMI_RH_NV_AUTH              @authHandle          Auth Index: 1
   19144                                                    Auth Role: USER
   19145                                                    NV Index of the area in which the bit is to be set
   19146  TPMI_RH_NV_INDEX             nvIndex
   19147                                                    Auth Index: None
   19148 
   19149  UINT64                       bits                 the data to OR with the current contents
   19150 
   19151 
   19152                              Table 212  TPM2_NV_SetBits Response
   19153  Type                         Name                 Description
   19154 
   19155  TPM_ST                       tag                  see clause 6
   19156  UINT32                       responseSize
   19157  TPM_RC                       responseCode
   19158 
   19159 
   19160 
   19161 
   19162 Family 2.0                              TCG Published                                          Page 427
   19163 Level 00 Revision 01.16              Copyright  TCG 2006-2014                          October 30, 2014
   19164      Part 3: Commands                                                            Trusted Platform Module Library
   19166 
   19167 
   19168 
   19169      31.10.3    Detailed Actions
   19170 
   19171 1    #include "InternalRoutines.h"
   19172 2    #include "NV_SetBits_fp.h"
   19173 3    #ifdef TPM_CC_NV_SetBits // Conditional expansion of this file
   19174 4    #include "NV_spt_fp.h"
   19175 
   19176 
   19177      Error Returns                 Meaning
   19178 
   19179      TPM_RC_ATTRIBUTES             the TPMA_NV_BITS attribute is not SET in the Index referenced by
   19180                                    nvIndex
   19181      TPM_RC_NV_AUTHORIZATION       the authorization was valid but the authorizing entity (authHandle) is
   19182                                    not allowed to write to the Index referenced by nvIndex
   19183      TPM_RC_NV_LOCKED              the Index referenced by nvIndex is locked for writing
   19184 
   19185  5   TPM_RC
   19186  6   TPM2_NV_SetBits(
   19187  7       NV_SetBits_In     *in              // IN: input parameter list
   19188  8       )
   19189  9   {
   19190 10       TPM_RC            result;
   19191 11       NV_INDEX          nvIndex;
   19192 12       UINT64            oldValue;
   19193 13       UINT64            newValue;
   19194 14
   19195 15   // Input Validation
   19196 16
   19197 17       // Common access checks, NvWriteAccessCheck() may return TPM_RC_NV_AUTHORIZATION
   19198 18       // or TPM_RC_NV_LOCKED
   19199 19       // error may be returned at this point
   19200 20       result = NvWriteAccessChecks(in->authHandle, in->nvIndex);
   19201 21       if(result != TPM_RC_SUCCESS)
   19202 22           return result;
   19203 23
   19204 24       // Get NV index info
   19205 25       NvGetIndexInfo(in->nvIndex, &nvIndex);
   19206 26
   19207 27       // Make sure that this is a bit field
   19208 28       if(nvIndex.publicArea.attributes.TPMA_NV_BITS != SET)
   19209 29           return TPM_RC_ATTRIBUTES + RC_NV_SetBits_nvIndex;
   19210 30
   19211 31       // If index is not been written, initialize it
   19212 32       if(nvIndex.publicArea.attributes.TPMA_NV_WRITTEN == CLEAR)
   19213 33           oldValue = 0;
   19214 34       else
   19215 35           // Read index data
   19216 36           NvGetIntIndexData(in->nvIndex, &nvIndex, &oldValue);
   19217 37
   19218 38       // Figure out what the new value is going to be
   19219 39       newValue = oldValue | in->bits;
   19220 40
   19221 41       // If the Index is not-orderly and it has changed, or if this is the first
   19222 42       // write, NV will need to be updated.
   19223 43       if(    (    nvIndex.publicArea.attributes.TPMA_NV_ORDERLY == CLEAR
   19224 44               && newValue != oldValue)
   19225 45           || nvIndex.publicArea.attributes.TPMA_NV_WRITTEN == CLEAR)
   19226 46       {
   19227 47
   19228 48   // Internal Data Update
   19229 49           // Check if NV is available. NvIsAvailable may return TPM_RC_NV_UNAVAILABLE
   19230 50           // TPM_RC_NV_RATE or TPM_RC_SUCCESS.
   19231 
   19232      Page 428                                   TCG Published                                          Family 2.0
   19233      October 30, 2014                  Copyright  TCG 2006-2014                           Level 00 Revision 01.16
   19234      Trusted Platform Module Library                                              Part 3: Commands
   19236 
   19237 51           result = NvIsAvailable();
   19238 52           if(result != TPM_RC_SUCCESS)
   19239 53               return result;
   19240 54
   19241 55           // Write index data back. If necessary, this function will SET
   19242 56           // TPMA_NV_WRITTEN.
   19243 57           result = NvWriteIndexData(in->nvIndex, &nvIndex, 0, 8, &newValue);
   19244 58       }
   19245 59       return result;
   19246 60
   19247 61   }
   19248 62   #endif // CC_NV_SetBits
   19249 
   19250 
   19251 
   19252 
   19253      Family 2.0                           TCG Published                                Page 429
   19254      Level 00 Revision 01.16           Copyright  TCG 2006-2014                  October 30, 2014
   19255 Part 3: Commands                                                    Trusted Platform Module Library
   19257 
   19258 
   19259 31.11 TPM2_NV_WriteLock
   19260 
   19261 31.11.1    General Description
   19262 
   19263 If the TPMA_NV_WRITEDEFINE or TPMA_NV_WRITE_STCLEAR attributes of an NV location are SET,
   19264 then this command may be used to inhibit further writes of the NV Index.
   19265 Proper write authorization is required for this command as determined by TPMA_NV_PPWRITE,
   19266 TPMA_NV_OWNERWRITE, TPMA_NV_AUTHWRITE, and the authPolicy of the NV Index.
   19267 It is not an error if TPMA_NV_WRITELOCKED for the NV Index is already SET.
   19268 If neither TPMA_NV_WRITEDEFINE nor TPMA_NV_WRITE_STCLEAR of the NV Index is SET, then the
   19269 TPM shall return TPM_RC_ATTRIBUTES.
   19270 If the command is properly authorized and TPMA_NV_WRITE_STCLEAR or TPMA_NV_WRITEDEFINE
   19271 is SET, then the TPM shall SET TPMA_NV_WRITELOCKED for the NV Index.
   19272 TPMA_NV_WRITELOCKED will be clear on the next TPM2_Startup(TPM_SU_CLEAR) unless
   19273 TPMA_NV_WRITEDEFINE is SET or if TPM_NV_WRITTEN is CLEAR.
   19274 
   19275 
   19276 
   19277 
   19278 Page 430                                 TCG Published                                Family 2.0
   19279 October 30, 2014                  Copyright  TCG 2006-2014              Level 00 Revision 01.16
   19280 Trusted Platform Module Library                                                       Part 3: Commands
   19282 
   19283 
   19284 
   19285 31.11.2    Command and Response
   19286 
   19287                            Table 213  TPM2_NV_WriteLock Command
   19288  Type                         Name                Description
   19289 
   19290  TPMI_ST_COMMAND_TAG          tag                 TPM_ST_SESSIONS
   19291  UINT32                       commandSize
   19292  TPM_CC                       commandCode         TPM_CC_NV_WriteLock {NV}
   19293 
   19294                                                   handle indicating the source of the authorization value
   19295  TPMI_RH_NV_AUTH              @authHandle         Auth Index: 1
   19296                                                   Auth Role: USER
   19297                                                   the NV Index of the area to lock
   19298  TPMI_RH_NV_INDEX             nvIndex
   19299                                                   Auth Index: None
   19300 
   19301 
   19302                            Table 214  TPM2_NV_WriteLock Response
   19303  Type                         Name                Description
   19304 
   19305  TPM_ST                       tag                 see clause 6
   19306  UINT32                       responseSize
   19307  TPM_RC                       responseCode
   19308 
   19309 
   19310 
   19311 
   19312 Family 2.0                             TCG Published                                         Page 431
   19313 Level 00 Revision 01.16             Copyright  TCG 2006-2014                         October 30, 2014
   19314      Part 3: Commands                                                               Trusted Platform Module Library
   19316 
   19317 
   19318 
   19319      31.11.3    Detailed Actions
   19320 
   19321 1    #include "InternalRoutines.h"
   19322 2    #include "NV_WriteLock_fp.h"
   19323 3    #ifdef TPM_CC_NV_WriteLock // Conditional expansion of this file
   19324 4    #include "NV_spt_fp.h"
   19325 
   19326 
   19327      Error Returns                    Meaning
   19328 
   19329      TPM_RC_ATTRIBUTES                neither TPMA_NV_WRITEDEFINE nor
   19330                                       TPMA_NV_WRITE_STCLEAR is SET in Index referenced by
   19331                                       nvIndex
   19332      TPM_RC_NV_AUTHORIZATION          the authorization was valid but the authorizing entity (authHandle) is
   19333                                       not allowed to write to the Index referenced by nvIndex
   19334 
   19335  5   TPM_RC
   19336  6   TPM2_NV_WriteLock(
   19337  7       NV_WriteLock_In       *in                  // IN: input parameter list
   19338  8       )
   19339  9   {
   19340 10       TPM_RC            result;
   19341 11       NV_INDEX          nvIndex;
   19342 12
   19343 13   // Input Validation:
   19344 14
   19345 15       // Common write access checks, a TPM_RC_NV_AUTHORIZATION or TPM_RC_NV_LOCKED
   19346 16       // error may be returned at this point
   19347 17       result = NvWriteAccessChecks(in->authHandle, in->nvIndex);
   19348 18       if(result != TPM_RC_SUCCESS)
   19349 19       {
   19350 20           if(result == TPM_RC_NV_AUTHORIZATION)
   19351 21               return TPM_RC_NV_AUTHORIZATION;
   19352 22           // If write access failed because the index is already locked, then it is
   19353 23           // no error.
   19354 24           return TPM_RC_SUCCESS;
   19355 25       }
   19356 26
   19357 27       // Get NV index info
   19358 28       NvGetIndexInfo(in->nvIndex, &nvIndex);
   19359 29
   19360 30       // if neither TPMA_NV_WRITEDEFINE nor TPMA_NV_WRITE_STCLEAR is set, the index
   19361 31       // can not be write-locked
   19362 32       if(   nvIndex.publicArea.attributes.TPMA_NV_WRITEDEFINE == CLEAR
   19363 33          && nvIndex.publicArea.attributes.TPMA_NV_WRITE_STCLEAR == CLEAR)
   19364 34           return TPM_RC_ATTRIBUTES + RC_NV_WriteLock_nvIndex;
   19365 35
   19366 36   // Internal Data Update
   19367 37
   19368 38       // The command needs NV update. Check if NV is available.
   19369 39       // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   19370 40       // this point
   19371 41       result = NvIsAvailable();
   19372 42       if(result != TPM_RC_SUCCESS)
   19373 43           return result;
   19374 44
   19375 45       // Set the WRITELOCK attribute.
   19376 46       // Note: if TPMA_NV_WRITELOCKED were already SET, then the write access check
   19377 47       // above would have failed and this code isn't executed.
   19378 48       nvIndex.publicArea.attributes.TPMA_NV_WRITELOCKED = SET;
   19379 49
   19380 50       // Write index info back
   19381 51       NvWriteIndexInfo(in->nvIndex, &nvIndex);
   19382 
   19383      Page 432                                      TCG Published                                          Family 2.0
   19384      October 30, 2014                     Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   19385      Trusted Platform Module Library                               Part 3: Commands
   19387 
   19388 52
   19389 53       return TPM_RC_SUCCESS;
   19390 54   }
   19391 55   #endif // CC_NV_WriteLock
   19392 
   19393 
   19394 
   19395 
   19396      Family 2.0                           TCG Published                 Page 433
   19397      Level 00 Revision 01.16           Copyright  TCG 2006-2014   October 30, 2014
   19398 Part 3: Commands                                                             Trusted Platform Module Library
   19400 
   19401 
   19402 31.12 TPM2_NV_GlobalWriteLock
   19403 
   19404 31.12.1    General Description
   19405 
   19406 The command will SET TPMA_NV_WRITELOCKED                         for   all     indexes   that   have   their
   19407 TPMA_NV_GLOBALLOCK attribute SET.
   19408 If an Index has both TPMA_NV_WRITELOCKED and TPMA_NV_WRITEDEFINE SET, then this
   19409 command will permanently lock the NV Index for writing unless TPMA_NV_WRITTEN is CLEAR.
   19410 
   19411 NOTE           If an Index is defined with TPMA_NV_GLOBALLOCK SET, then the global lock does not apply until
   19412                the next time this command is executed.
   19413 
   19414 This command requires either platformAuth/platformPolicy or ownerAuth/ownerPolicy.
   19415 
   19416 
   19417 
   19418 
   19419 Page 434                                    TCG Published                                       Family 2.0
   19420 October 30, 2014                    Copyright  TCG 2006-2014                     Level 00 Revision 01.16
   19421 Trusted Platform Module Library                                               Part 3: Commands
   19423 
   19424 
   19425 
   19426 31.12.2    Command and Response
   19427 
   19428                         Table 215  TPM2_NV_GlobalWriteLock Command
   19429  Type                         Name                Description
   19430 
   19431  TPMI_ST_COMMAND_TAG          tag                 TPM_ST_SESSIONS
   19432  UINT32                       commandSize
   19433  TPM_CC                       commandCode         TPM_CC_NV_GlobalWriteLock
   19434 
   19435                                                   TPM_RH_OWNER or TPM_RH_PLATFORM+{PP}
   19436  TPMI_RH_PROVISION            @authHandle         Auth Index: 1
   19437                                                   Auth Role: USER
   19438 
   19439 
   19440                         Table 216  TPM2_NV_GlobalWriteLock Response
   19441  Type                         Name                Description
   19442  TPM_ST                       tag                 see clause 6
   19443  UINT32                       responseSize
   19444  TPM_RC                       responseCode
   19445 
   19446 
   19447 
   19448 
   19449 Family 2.0                             TCG Published                               Page 435
   19450 Level 00 Revision 01.16             Copyright  TCG 2006-2014                 October 30, 2014
   19451      Part 3: Commands                                                    Trusted Platform Module Library
   19453 
   19454 
   19455 
   19456      31.12.3      Detailed Actions
   19457 
   19458  1   #include "InternalRoutines.h"
   19459  2   #include "NV_GlobalWriteLock_fp.h"
   19460  3   #ifdef TPM_CC_NV_GlobalWriteLock // Conditional expansion of this file
   19461  4   TPM_RC
   19462  5   TPM2_NV_GlobalWriteLock(
   19463  6       NV_GlobalWriteLock_In       *in             // IN: input parameter list
   19464  7       )
   19465  8   {
   19466  9       TPM_RC           result;
   19467 10
   19468 11       // Input parameter is not reference in command action
   19469 12       in = NULL; // to silence compiler warnings.
   19470 13
   19471 14       // The command needs NV update. Check if NV is available.
   19472 15       // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   19473 16       // this point
   19474 17       result = NvIsAvailable();
   19475 18       if(result != TPM_RC_SUCCESS)
   19476 19           return result;
   19477 20
   19478 21   // Internal Data Update
   19479 22
   19480 23       // Implementation dependent method of setting the global lock
   19481 24       NvSetGlobalLock();
   19482 25
   19483 26       return TPM_RC_SUCCESS;
   19484 27   }
   19485 28   #endif // CC_NV_GlobalWriteLock
   19486 
   19487 
   19488 
   19489 
   19490      Page 436                                   TCG Published                              Family 2.0
   19491      October 30, 2014                      Copyright  TCG 2006-2014           Level 00 Revision 01.16
   19492 Trusted Platform Module Library                                                               Part 3: Commands
   19494 
   19495 
   19496 31.13 TPM2_NV_Read
   19497 
   19498 31.13.1    General Description
   19499 
   19500 This command reads a            value    from    an    area    in   NV    memory      previously     defined    by
   19501 TPM2_NV_DefineSpace().
   19502 Proper authorizations are required for this command as determined by TPMA_NV_PPREAD,
   19503 TPMA_NV_OWNERREAD, TPMA_NV_AUTHREAD, and the authPolicy of the NV Index.
   19504 If TPMA_NV_READLOCKED of the NV Index is SET, then the TPM shall return TPM_RC_NV_LOCKED.
   19505 
   19506 NOTE           If authorization sessions are present, they are checked before the read -lock status of the NV Index
   19507                is checked.
   19508 
   19509 If the size parameter plus the offset parameter adds to a value that is greater than the size of the NV
   19510 Index data area, the TPM shall return TPM_RC_NV_RANGE and not read any data from the NV Index.
   19511 If the NV Index has been defined but the TPMA_NV_WRITTEN attribute is CLEAR, then this command
   19512 shall return TPM_RC_NV_UINITIALIZED even if size is zero.
   19513 The data parameter in the response may be encrypted using parameter encryption.
   19514 
   19515 
   19516 
   19517 
   19518 Family 2.0                                  TCG Published                                            Page 437
   19519 Level 00 Revision 01.16               Copyright  TCG 2006-2014                              October 30, 2014
   19520 Part 3: Commands                                                  Trusted Platform Module Library
   19522 
   19523 
   19524 
   19525 31.13.2    Command and Response
   19526 
   19527                         Table 217  TPM2_NV_Read Command
   19528  Type                   Name                 Description
   19529 
   19530  TPMI_ST_COMMAND_TAG    tag                  TPM_ST_SESSIONS
   19531  UINT32                 commandSize
   19532  TPM_CC                 commandCode          TPM_CC_NV_Read
   19533 
   19534                                              the handle indicating the source of the authorization
   19535                                              value
   19536  TPMI_RH_NV_AUTH        @authHandle
   19537                                              Auth Index: 1
   19538                                              Auth Role: USER
   19539                                              the NV Index to be read
   19540  TPMI_RH_NV_INDEX       nvIndex
   19541                                              Auth Index: None
   19542 
   19543  UINT16                 size                 number of octets to read
   19544                                              octet offset into the area
   19545  UINT16                 offset               This value shall be less than or equal to the size of the
   19546                                              nvIndex data.
   19547 
   19548 
   19549                         Table 218  TPM2_NV_Read Response
   19550  Type                   Name                 Description
   19551 
   19552  TPM_ST                 tag                  see clause 6
   19553  UINT32                 responseSize
   19554  TPM_RC                 responseCode
   19555 
   19556  TPM2B_MAX_NV_BUFFER    data                 the data read
   19557 
   19558 
   19559 
   19560 
   19561 Page 438                            TCG Published                                       Family 2.0
   19562 October 30, 2014               Copyright  TCG 2006-2014                 Level 00 Revision 01.16
   19563      Trusted Platform Module Library                                                                 Part 3: Commands
   19565 
   19566 
   19567 
   19568      31.13.3    Detailed Actions
   19569 
   19570 1    #include "InternalRoutines.h"
   19571 2    #include "NV_Read_fp.h"
   19572 3    #ifdef TPM_CC_NV_Read // Conditional expansion of this file
   19573 4    #include "NV_spt_fp.h"
   19574 
   19575 
   19576      Error Returns                     Meaning
   19577 
   19578      TPM_RC_NV_AUTHORIZATION           the authorization was valid but the authorizing entity (authHandle) is
   19579                                        not allowed to read from the Index referenced by nvIndex
   19580      TPM_RC_NV_LOCKED                  the Index referenced by nvIndex is read locked
   19581      TPM_RC_NV_RANGE                   read range defined by size and offset is outside the range of the
   19582                                        Index referenced by nvIndex
   19583      TPM_RC_NV_UNINITIALIZED           the Index referenced by nvIndex has not been initialized (written)
   19584 
   19585  5   TPM_RC
   19586  6   TPM2_NV_Read(
   19587  7       NV_Read_In        *in,                 // IN: input parameter list
   19588  8       NV_Read_Out       *out                 // OUT: output parameter list
   19589  9       )
   19590 10   {
   19591 11       NV_INDEX          nvIndex;
   19592 12       TPM_RC            result;
   19593 13
   19594 14   // Input Validation
   19595 15
   19596 16       // Get NV index info
   19597 17       NvGetIndexInfo(in->nvIndex, &nvIndex);
   19598 18
   19599 19       // Common read access checks. NvReadAccessChecks() returns
   19600 20       // TPM_RC_NV_AUTHORIZATION, TPM_RC_NV_LOCKED, or TPM_RC_NV_UNINITIALIZED
   19601 21       // error may be returned at this point
   19602 22       result = NvReadAccessChecks(in->authHandle, in->nvIndex);
   19603 23       if(result != TPM_RC_SUCCESS)
   19604 24           return result;
   19605 25
   19606 26       // Too much data
   19607 27       if((in->size + in->offset) > nvIndex.publicArea.dataSize)
   19608 28           return TPM_RC_NV_RANGE;
   19609 29
   19610 30   // Command Output
   19611 31
   19612 32       // Set the return size
   19613 33       out->data.t.size = in->size;
   19614 34       // Perform the read
   19615 35       NvGetIndexData(in->nvIndex, &nvIndex, in->offset, in->size, out->data.t.buffer);
   19616 36
   19617 37       return TPM_RC_SUCCESS;
   19618 38   }
   19619 39   #endif // CC_NV_Read
   19620 
   19621 
   19622 
   19623 
   19624      Family 2.0                                   TCG Published                                               Page 439
   19625      Level 00 Revision 01.16               Copyright  TCG 2006-2014                                 October 30, 2014
   19626 Part 3: Commands                                                                 Trusted Platform Module Library
   19628 
   19629 
   19630 31.14 TPM2_NV_ReadLock
   19631 
   19632 31.14.1     General Description
   19633 
   19634 If TPMA_NV_READ_STCLEAR is SET in an Index, then this command may be used to prevent further
   19635 reads of the NV Index until the next TPM2_Startup (TPM_SU_CLEAR).
   19636 Proper authorizations are required for this command as determined by TPMA_NV_PPREAD,
   19637 TPMA_NV_OWNERREAD, TPMA_NV_AUTHREAD, and the authPolicy of the NV Index.
   19638 
   19639 NOTE            Only an entity that may read an Index is allowed to lock the NV Index for read.
   19640 
   19641 If the command is properly authorized and TPMA_NV_READ_STCLEAR of the NV Index is SET, then the
   19642 TPM shall SET TPMA_NV_READLOCKED for the NV Index. If TPMA_NV_READ_STCLEAR of the NV
   19643 Index is CLEAR, then the TPM shall return TPM_RC_ATTRIBUTES. TPMA_NV_READLOCKED will be
   19644 CLEAR by the next TPM2_Startup(TPM_SU_CLEAR).
   19645 It is not an error to use this command for an Index that is already locked for reading.
   19646 An Index that had not been written may be locked for reading.
   19647 
   19648 
   19649 
   19650 
   19651 Page 440                                       TCG Published                                       Family 2.0
   19652 October 30, 2014                       Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   19653 Trusted Platform Module Library                                                       Part 3: Commands
   19655 
   19656 
   19657 
   19658 31.14.2    Command and Response
   19659 
   19660                            Table 219  TPM2_NV_ReadLock Command
   19661  Type                         Name                Description
   19662 
   19663  TPMI_ST_COMMAND_TAG          tag                 TPM_ST_SESSIONS
   19664  UINT32                       commandSize
   19665  TPM_CC                       commandCode         TPM_CC_NV_ReadLock
   19666 
   19667                                                   the handle indicating the source of the authorization
   19668                                                   value
   19669  TPMI_RH_NV_AUTH              @authHandle
   19670                                                   Auth Index: 1
   19671                                                   Auth Role: USER
   19672                                                   the NV Index to be locked
   19673  TPMI_RH_NV_INDEX             nvIndex
   19674                                                   Auth Index: None
   19675 
   19676 
   19677                            Table 220  TPM2_NV_ReadLock Response
   19678  Type                         Name                Description
   19679 
   19680  TPM_ST                       tag                 see clause 6
   19681  UINT32                       responseSize
   19682  TPM_RC                       responseCode
   19683 
   19684 
   19685 
   19686 
   19687 Family 2.0                             TCG Published                                         Page 441
   19688 Level 00 Revision 01.16             Copyright  TCG 2006-2014                         October 30, 2014
   19689      Part 3: Commands                                                               Trusted Platform Module Library
   19691 
   19692 
   19693 
   19694      31.14.3     Detailed Actions
   19695 
   19696 1    #include "InternalRoutines.h"
   19697 2    #include "NV_ReadLock_fp.h"
   19698 3    #ifdef TPM_CC_NV_ReadLock // Conditional expansion of this file
   19699 4    #include "NV_spt_fp.h"
   19700 
   19701 
   19702      Error Returns                    Meaning
   19703 
   19704      TPM_RC_ATTRIBUTES                TPMA_NV_READ_STCLEAR is not SET so Index referenced by
   19705                                       nvIndex may not be write locked
   19706      TPM_RC_NV_AUTHORIZATION          the authorization was valid but the authorizing entity (authHandle) is
   19707                                       not allowed to read from the Index referenced by nvIndex
   19708 
   19709  5   TPM_RC
   19710  6   TPM2_NV_ReadLock(
   19711  7       NV_ReadLock_In    *in                 // IN: input parameter list
   19712  8       )
   19713  9   {
   19714 10       TPM_RC            result;
   19715 11       NV_INDEX          nvIndex;
   19716 12
   19717 13       // The command needs NV update. Check if NV is available.
   19718 14       // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   19719 15       // this point
   19720 16       result = NvIsAvailable();
   19721 17       if(result != TPM_RC_SUCCESS) return result;
   19722 18
   19723 19   // Input Validation
   19724 20
   19725 21       // Common read access checks. NvReadAccessChecks() returns
   19726 22       // TPM_RC_NV_AUTHORIZATION, TPM_RC_NV_LOCKED, or TPM_RC_NV_UNINITIALIZED
   19727 23       // error may be returned at this point
   19728 24       result = NvReadAccessChecks(in->authHandle, in->nvIndex);
   19729 25       if(result != TPM_RC_SUCCESS)
   19730 26       {
   19731 27           if(result == TPM_RC_NV_AUTHORIZATION)
   19732 28               return TPM_RC_NV_AUTHORIZATION;
   19733 29           // Index is already locked for write
   19734 30           else if(result == TPM_RC_NV_LOCKED)
   19735 31               return TPM_RC_SUCCESS;
   19736 32
   19737 33             // If NvReadAccessChecks return TPM_RC_NV_UNINITALIZED, then continue.
   19738 34             // It is not an error to read lock an uninitialized Index.
   19739 35       }
   19740 36
   19741 37       // Get NV index info
   19742 38       NvGetIndexInfo(in->nvIndex, &nvIndex);
   19743 39
   19744 40       // if TPMA_NV_READ_STCLEAR is not set, the index can not be read-locked
   19745 41       if(nvIndex.publicArea.attributes.TPMA_NV_READ_STCLEAR == CLEAR)
   19746 42           return TPM_RC_ATTRIBUTES + RC_NV_ReadLock_nvIndex;
   19747 43
   19748 44   // Internal Data Update
   19749 45
   19750 46       // Set the READLOCK attribute
   19751 47       nvIndex.publicArea.attributes.TPMA_NV_READLOCKED = SET;
   19752 48       // Write NV info back
   19753 49       NvWriteIndexInfo(in->nvIndex, &nvIndex);
   19754 50
   19755 51       return TPM_RC_SUCCESS;
   19756 52   }
   19757 
   19758      Page 442                                      TCG Published                                          Family 2.0
   19759      October 30, 2014                     Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   19760      Trusted Platform Module Library                               Part 3: Commands
   19762 
   19763 53   #endif // CC_NV_ReadLock
   19764 
   19765 
   19766 
   19767 
   19768      Family 2.0                           TCG Published                 Page 443
   19769      Level 00 Revision 01.16           Copyright  TCG 2006-2014   October 30, 2014
   19770 Part 3: Commands                                                                  Trusted Platform Module Library
   19772 
   19773 
   19774 31.15 TPM2_NV_ChangeAuth
   19775 
   19776 31.15.1     General Description
   19777 
   19778 This command allows the authorization secret for an NV Index to be changed.
   19779 If successful, the authorization secret (authValue) of the NV Index associated with nvIndex is changed.
   19780 This command requires that a policy session be used for authorization of nvIndex so that the ADMIN role
   19781 may be asserted and that commandCode in the policy session context shall be
   19782 TPM_CC_NV_ChangeAuth. That is, the policy must contain a specific authorization for changing the
   19783 authorization value of the referenced object.
   19784 
   19785 NOTE            The reason for this restriction is to ensure that the administrative actions on nvIndex require explicit
   19786                 approval while other commands may use policy that is not command -dependent.
   19787 
   19788 The size of the newAuth value may be no larger than the size of authorization indicated when the NV
   19789 Index was defined.
   19790 Since the NV Index authorization is changed before the response HMAC is calculated, the newAuth value
   19791 is used when generating the response HMAC key if required.                  See TPM 2.0 Part 4
   19792 ComputeResponseHMAC().
   19793 
   19794 
   19795 
   19796 
   19797 Page 444                                        TCG Published                                           Family 2.0
   19798 October 30, 2014                       Copyright  TCG 2006-2014                         Level 00 Revision 01.16
   19799 Trusted Platform Module Library                                                 Part 3: Commands
   19801 
   19802 
   19803 
   19804 31.15.2    Command and Response
   19805 
   19806                           Table 221  TPM2_NV_ChangeAuth Command
   19807 Type                          Name                  Description
   19808 
   19809 TPMI_ST_COMMAND_TAG           tag                   TPM_ST_SESSIONS
   19810 UINT32                        commandSize
   19811 TPM_CC                        commandCode           TPM_CC_NV_ChangeAuth {NV}
   19812 
   19813                                                     handle of the object
   19814 TPMI_RH_NV_INDEX              @nvIndex              Auth Index: 1
   19815                                                     Auth Role: ADMIN
   19816 
   19817 TPM2B_AUTH                    newAuth               new authorization value
   19818 
   19819 
   19820                           Table 222  TPM2_NV_ChangeAuth Response
   19821 Type                          Name                  Description
   19822 
   19823 TPM_ST                        tag                   see clause 6
   19824 UINT32                        responseSize
   19825 TPM_RC                        responseCode
   19826 
   19827 
   19828 
   19829 
   19830 Family 2.0                                 TCG Published                             Page 445
   19831 Level 00 Revision 01.16             Copyright  TCG 2006-2014                   October 30, 2014
   19832      Part 3: Commands                                                           Trusted Platform Module Library
   19834 
   19835 
   19836 
   19837      31.15.3    Detailed Actions
   19838 
   19839 1    #include "InternalRoutines.h"
   19840 2    #include "NV_ChangeAuth_fp.h"
   19841 3    #ifdef TPM_CC_NV_ChangeAuth // Conditional expansion of this file
   19842 
   19843 
   19844      Error Returns                 Meaning
   19845 
   19846      TPM_RC_SIZE                   newAuth size is larger than the digest size of the Name algorithm for
   19847                                    the Index referenced by 'nvIndex
   19848 
   19849  4   TPM_RC
   19850  5   TPM2_NV_ChangeAuth(
   19851  6       NV_ChangeAuth_In   *in                  // IN: input parameter list
   19852  7       )
   19853  8   {
   19854  9       TPM_RC         result;
   19855 10       NV_INDEX       nvIndex;
   19856 11
   19857 12   // Input Validation
   19858 13       // Check if NV is available. NvIsAvailable may return TPM_RC_NV_UNAVAILABLE
   19859 14       // TPM_RC_NV_RATE or TPM_RC_SUCCESS.
   19860 15       result = NvIsAvailable();
   19861 16       if(result != TPM_RC_SUCCESS) return result;
   19862 17
   19863 18       // Read index info from NV
   19864 19       NvGetIndexInfo(in->nvIndex, &nvIndex);
   19865 20
   19866 21       // Remove any trailing zeros that might have been added by the caller
   19867 22       // to obfuscate the size.
   19868 23       MemoryRemoveTrailingZeros(&(in->newAuth));
   19869 24
   19870 25       // Make sure that the authValue is no larger than the nameAlg of the Index
   19871 26       if(in->newAuth.t.size > CryptGetHashDigestSize(nvIndex.publicArea.nameAlg))
   19872 27           return TPM_RC_SIZE + RC_NV_ChangeAuth_newAuth;
   19873 28
   19874 29   // Internal Data Update
   19875 30       // Change auth
   19876 31       nvIndex.authValue = in->newAuth;
   19877 32       // Write index info back to NV
   19878 33       NvWriteIndexInfo(in->nvIndex, &nvIndex);
   19879 34
   19880 35       return TPM_RC_SUCCESS;
   19881 36   }
   19882 37   #endif // CC_NV_ChangeAuth
   19883 
   19884 
   19885 
   19886 
   19887      Page 446                                   TCG Published                                         Family 2.0
   19888      October 30, 2014                  Copyright  TCG 2006-2014                       Level 00 Revision 01.16
   19889 Trusted Platform Module Library                                                        Part 3: Commands
   19891 
   19892 
   19893 31.16 TPM2_NV_Certify
   19894 
   19895 31.16.1     General Description
   19896 
   19897 The purpose of this command is to certify the contents of an NV Index or portion of an NV Index.
   19898 If proper authorization for reading the NV Index is provided, the portion of the NV Index selected by size
   19899 and offset are included in an attestation block and signed using the key indicated by signHandle. The
   19900 attestation also includes size and offset so that the range of the data can be determined.
   19901 
   19902 NOTE 1          See 18.1 for description of how the signing scheme is selected.
   19903 
   19904 NOTE 2          If signHandle is TPM_RH_NULL, the TPMS_ATTEST structure is returned and signature is a NULL
   19905                 Signature.
   19906 
   19907 
   19908 
   19909 
   19910 Family 2.0                                   TCG Published                                    Page 447
   19911 Level 00 Revision 01.16                Copyright  TCG 2006-2014                       October 30, 2014
   19912 Part 3: Commands                                                       Trusted Platform Module Library
   19914 
   19915 
   19916 31.16.2    Command and Response
   19917 
   19918                        Table 223  TPM2_NV_Certify Command
   19919 Type                    Name                  Description
   19920 
   19921 TPMI_ST_COMMAND_TAG     tag                   TPM_ST_SESSIONS
   19922 UINT32                  commandSize
   19923 TPM_CC                  commandCode           TPM_CC_NV_Certify
   19924 
   19925                                               handle of the key used to sign the attestation structure
   19926 TPMI_DH_OBJECT+         @signHandle           Auth Index: 1
   19927                                               Auth Role: USER
   19928                                                   handle indicating the source of the authorization value
   19929                                                   for the NV Index
   19930  TPMI_RH_NV_AUTH        @authHandle
   19931                                                   Auth Index: 2
   19932                                                   Auth Role: USER
   19933                                                   Index for the area to be certified
   19934  TPMI_RH_NV_INDEX       nvIndex
   19935                                                   Auth Index: None
   19936 
   19937 TPM2B_DATA              qualifyingData        user-provided qualifying data
   19938                                               signing scheme to use if the scheme for signHandle is
   19939 TPMT_SIG_SCHEME+        inScheme
   19940                                               TPM_ALG_NULL
   19941  UINT16                 size                      number of octets to certify
   19942                                                   octet offset into the area
   19943  UINT16                 offset                    This value shall be less than or equal to the size of the
   19944                                                   nvIndex data.
   19945 
   19946 
   19947                        Table 224  TPM2_NV_Certify Response
   19948 Type                    Name                  Description
   19949 
   19950 TPM_ST                  tag                   see clause 6
   19951 UINT32                  responseSize
   19952 TPM_RC                  responseCode          .
   19953 
   19954 TPM2B_ATTEST            certifyInfo           the structure that was signed
   19955                                               the asymmetric signature over certifyInfo using the key
   19956 TPMT_SIGNATURE          signature
   19957                                               referenced by signHandle
   19958 
   19959 
   19960 
   19961 
   19962 Page 448                               TCG Published                                         Family 2.0
   19963 October 30, 2014               Copyright  TCG 2006-2014                        Level 00 Revision 01.16
   19964      Trusted Platform Module Library                                                                 Part 3: Commands
   19966 
   19967 
   19968 
   19969      31.16.3    Detailed Actions
   19970 
   19971 1    #include "InternalRoutines.h"
   19972 2    #include "Attest_spt_fp.h"
   19973 3    #include "NV_spt_fp.h"
   19974 4    #include "NV_Certify_fp.h"
   19975 5    #ifdef TPM_CC_NV_Certify // Conditional expansion of this file
   19976 
   19977 
   19978      Error Returns                     Meaning
   19979 
   19980      TPM_RC_NV_AUTHORIZATION           the authorization was valid but the authorizing entity (authHandle) is
   19981                                        not allowed to read from the Index referenced by nvIndex
   19982      TPM_RC_KEY                        signHandle does not reference a signing key
   19983      TPM_RC_NV_LOCKED                  Index referenced by nvIndex is locked for reading
   19984      TPM_RC_NV_RANGE                   offset plus size extends outside of the data range of the Index
   19985                                        referenced by nvIndex
   19986      TPM_RC_NV_UNINITIALIZED           Index referenced by nvIndex has not been written
   19987      TPM_RC_SCHEME                     inScheme is not an allowed value for the key definition
   19988 
   19989  6   TPM_RC
   19990  7   TPM2_NV_Certify(
   19991  8       NV_Certify_In     *in,                 // IN: input parameter list
   19992  9       NV_Certify_Out    *out                 // OUT: output parameter list
   19993 10       )
   19994 11   {
   19995 12       TPM_RC                    result;
   19996 13       NV_INDEX                  nvIndex;
   19997 14       TPMS_ATTEST               certifyInfo;
   19998 15
   19999 16       // Attestation command may cause the orderlyState to be cleared due to
   20000 17       // the reporting of clock info. If this is the case, check if NV is
   20001 18       // available first
   20002 19       if(gp.orderlyState != SHUTDOWN_NONE)
   20003 20       {
   20004 21           // The command needs NV update. Check if NV is available.
   20005 22           // A TPM_RC_NV_UNAVAILABLE or TPM_RC_NV_RATE error may be returned at
   20006 23           // this point
   20007 24           result = NvIsAvailable();
   20008 25           if(result != TPM_RC_SUCCESS)
   20009 26               return result;
   20010 27       }
   20011 28
   20012 29   // Input Validation
   20013 30
   20014 31       // Get NV index info
   20015 32       NvGetIndexInfo(in->nvIndex, &nvIndex);
   20016 33
   20017 34       // Common access checks. A TPM_RC_NV_AUTHORIZATION or TPM_RC_NV_LOCKED
   20018 35       // error may be returned at this point
   20019 36       result = NvReadAccessChecks(in->authHandle, in->nvIndex);
   20020 37       if(result != TPM_RC_SUCCESS)
   20021 38           return result;
   20022 39
   20023 40       // See if the range to be certified is out of the bounds of the defined
   20024 41       // Index
   20025 42       if((in->size + in->offset) > nvIndex.publicArea.dataSize)
   20026 43           return TPM_RC_NV_RANGE;
   20027 44
   20028 45   // Command Output
   20029 
   20030      Family 2.0                                   TCG Published                                               Page 449
   20031      Level 00 Revision 01.16               Copyright  TCG 2006-2014                                 October 30, 2014
   20032       Part 3: Commands                                                  Trusted Platform Module Library
   20034 
   20035  46
   20036  47      // Filling in attest information
   20037  48      // Common fields
   20038  49      // FillInAttestInfo can return TPM_RC_SCHEME or TPM_RC_KEY
   20039  50      result = FillInAttestInfo(in->signHandle,
   20040  51                                &in->inScheme,
   20041  52                                &in->qualifyingData,
   20042  53                                &certifyInfo);
   20043  54      if(result != TPM_RC_SUCCESS)
   20044  55      {
   20045  56          if(result == TPM_RC_KEY)
   20046  57              return TPM_RC_KEY + RC_NV_Certify_signHandle;
   20047  58          else
   20048  59              return RcSafeAddToResult(result, RC_NV_Certify_inScheme);
   20049  60      }
   20050  61      // NV certify specific fields
   20051  62      // Attestation type
   20052  63      certifyInfo.type = TPM_ST_ATTEST_NV;
   20053  64
   20054  65      // Get the name of the index
   20055  66      certifyInfo.attested.nv.indexName.t.size =
   20056  67          NvGetName(in->nvIndex, &certifyInfo.attested.nv.indexName.t.name);
   20057  68
   20058  69      // Set the return size
   20059  70      certifyInfo.attested.nv.nvContents.t.size = in->size;
   20060  71
   20061  72      // Set the offset
   20062  73      certifyInfo.attested.nv.offset = in->offset;
   20063  74
   20064  75      // Perform the read
   20065  76      NvGetIndexData(in->nvIndex, &nvIndex,
   20066  77                     in->offset, in->size,
   20067  78                     certifyInfo.attested.nv.nvContents.t.buffer);
   20068  79
   20069  80      // Sign attestation structure. A NULL signature will be returned if
   20070  81      // signHandle is TPM_RH_NULL. SignAttestInfo() may return TPM_RC_VALUE,
   20071  82      // TPM_RC_SCHEME or TPM_RC_ATTRUBUTES.
   20072  83      // Note: SignAttestInfo may return TPM_RC_ATTRIBUTES if the key is not a
   20073  84      // signing key but that was checked above. TPM_RC_VALUE would mean that the
   20074  85      // data to sign is too large but the data to sign is a digest
   20075  86      result = SignAttestInfo(in->signHandle,
   20076  87                              &in->inScheme,
   20077  88                              &certifyInfo,
   20078  89                              &in->qualifyingData,
   20079  90                              &out->certifyInfo,
   20080  91                              &out->signature);
   20081  92      if(result != TPM_RC_SUCCESS)
   20082  93          return result;
   20083  94
   20084  95      // orderly state should be cleared because of the reporting of clock info
   20085  96      // if signing happens
   20086  97      if(in->signHandle != TPM_RH_NULL)
   20087  98          g_clearOrderly = TRUE;
   20088  99
   20089 100       return TPM_RC_SUCCESS;
   20090 101   }
   20091 102   #endif // CC_NV_Certify
   20092 
   20093 
   20094 
   20095 
   20096       Page 450                              TCG Published                                 Family 2.0
   20097       October 30, 2014               Copyright  TCG 2006-2014               Level 00 Revision 01.16
   20098 
   20100