-
Notifications
You must be signed in to change notification settings - Fork 161
/
Tpm.py
2601 lines (2292 loc) · 117 KB
/
Tpm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
* Copyright(c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
* See the LICENSE file in the project root for full license information.
"""
"""
* This file is automatically generated from the TPM 2.0 rev. 1.62 specification documents.
* Do not edit it directly.
"""
from .TpmBase import *
class Tpm(TpmBase):
def Startup(self, startupType):
""" TPM2_Startup() is always preceded by _TPM_Init, which is the
physical indication that TPM initialization is necessary because of a
system-wide reset. TPM2_Startup() is only valid after _TPM_Init.
Additional TPM2_Startup() commands are not allowed after it has
completed successfully. If a TPM requires TPM2_Startup() and another
command is received, or if the TPM receives TPM2_Startup() when it is
not required, the TPM shall return TPM_RC_INITIALIZE.
Args:
startupType (TPM_SU): TPM_SU_CLEAR or TPM_SU_STATE
"""
req = TPM2_Startup_REQUEST(startupType)
respBuf = self.dispatchCommand(TPM_CC.Startup, req)
return self.processResponse(respBuf)
# Startup()
def Shutdown(self, shutdownType):
""" This command is used to prepare the TPM for a power cycle. The
shutdownType parameter indicates how the subsequent TPM2_Startup() will
be processed.
Args:
shutdownType (TPM_SU): TPM_SU_CLEAR or TPM_SU_STATE
"""
req = TPM2_Shutdown_REQUEST(shutdownType)
respBuf = self.dispatchCommand(TPM_CC.Shutdown, req)
return self.processResponse(respBuf)
# Shutdown()
def SelfTest(self, fullTest):
""" This command causes the TPM to perform a test of its capabilities.
If the fullTest is YES, the TPM will test all functions. If fullTest =
NO, the TPM will only test those functions that have not previously been
tested.
Args:
fullTest (int): YES if full test to be performed
NO if only test of untested functions required
"""
req = TPM2_SelfTest_REQUEST(fullTest)
respBuf = self.dispatchCommand(TPM_CC.SelfTest, req)
return self.processResponse(respBuf)
# SelfTest()
def IncrementalSelfTest(self, toTest):
""" This command causes the TPM to perform a test of the selected algorithms.
Args:
toTest (TPM_ALG_ID[]): List of algorithms that should be tested
Returns:
toDoList - List of algorithms that need testing
"""
req = TPM2_IncrementalSelfTest_REQUEST(toTest)
respBuf = self.dispatchCommand(TPM_CC.IncrementalSelfTest, req)
res = self.processResponse(respBuf, IncrementalSelfTestResponse)
return res.toDoList if res else None
# IncrementalSelfTest()
def GetTestResult(self):
""" This command returns manufacturer-specific information regarding the
results of a self-test and an indication of the test status.
Returns:
outData - Test result data
contains manufacturer-specific information
testResult - TBD
"""
req = TPM2_GetTestResult_REQUEST()
respBuf = self.dispatchCommand(TPM_CC.GetTestResult, req)
return self.processResponse(respBuf, GetTestResultResponse)
# GetTestResult()
def StartAuthSession(self, tpmKey, bind, nonceCaller, encryptedSalt, sessionType, symmetric, authHash):
""" This command is used to start an authorization session using
alternative methods of establishing the session key (sessionKey). The
session key is then used to derive values used for authorization and for
encrypting parameters.
Args:
tpmKey (TPM_HANDLE): Handle of a loaded decrypt key used to encrypt salt
may be TPM_RH_NULL
Auth Index: None
bind (TPM_HANDLE): Entity providing the authValue
may be TPM_RH_NULL
Auth Index: None
nonceCaller (bytes): Initial nonceCaller, sets nonceTPM size for the
session
shall be at least 16 octets
encryptedSalt (bytes): Value encrypted according to the type of tpmKey
If tpmKey is TPM_RH_NULL, this shall be the Empty Buffer.
sessionType (TPM_SE): Indicates the type of the session; simple HMAC
or policy (including a trial policy)
symmetric (TPMT_SYM_DEF): The algorithm and key size for parameter
encryption
may select TPM_ALG_NULL
authHash (TPM_ALG_ID): Hash algorithm to use for the session
Shall be a hash algorithm supported by the TPM and not TPM_ALG_NULL
Returns:
handle - Handle for the newly created session
nonceTPM - The initial nonce from the TPM, used in the computation
of the sessionKey
"""
req = TPM2_StartAuthSession_REQUEST(tpmKey, bind, nonceCaller, encryptedSalt, sessionType, symmetric, authHash)
respBuf = self.dispatchCommand(TPM_CC.StartAuthSession, req)
return self.processResponse(respBuf, StartAuthSessionResponse)
# StartAuthSession()
def PolicyRestart(self, sessionHandle):
""" This command allows a policy authorization session to be returned to
its initial state. This command is used after the TPM returns
TPM_RC_PCR_CHANGED. That response code indicates that a policy will fail
because the PCR have changed after TPM2_PolicyPCR() was executed.
Restarting the session allows the authorizations to be replayed because
the session restarts with the same nonceTPM. If the PCR are valid for
the policy, the policy may then succeed.
Args:
sessionHandle (TPM_HANDLE): The handle for the policy session
"""
req = TPM2_PolicyRestart_REQUEST(sessionHandle)
respBuf = self.dispatchCommand(TPM_CC.PolicyRestart, req)
return self.processResponse(respBuf)
# PolicyRestart()
def Create(self, parentHandle, inSensitive, inPublic, outsideInfo, creationPCR):
""" This command is used to create an object that can be loaded into a
TPM using TPM2_Load(). If the command completes successfully, the TPM
will create the new object and return the objects creation data
(creationData), its public area (outPublic), and its encrypted sensitive
area (outPrivate). Preservation of the returned data is the
responsibility of the caller. The object will need to be loaded
(TPM2_Load()) before it may be used. The only difference between the
inPublic TPMT_PUBLIC template and the outPublic TPMT_PUBLIC object is in
the unique field.
Args:
parentHandle (TPM_HANDLE): Handle of parent for new object
Auth Index: 1
Auth Role: USER
inSensitive (TPMS_SENSITIVE_CREATE): The sensitive data
inPublic (TPMT_PUBLIC): The public template
outsideInfo (bytes): Data that will be included in the creation data
for this object to provide permanent, verifiable linkage between
this object and some object owner data
creationPCR (TPMS_PCR_SELECTION[]): PCR that will be used in
creation data
Returns:
outPrivate - The private portion of the object
outPublic - The public portion of the created object
creationData - Contains a TPMS_CREATION_DATA
creationHash - Digest of creationData using nameAlg of outPublic
creationTicket - Ticket used by TPM2_CertifyCreation() to validate
that the creation data was produced by the TPM
"""
req = TPM2_Create_REQUEST(parentHandle, inSensitive, inPublic, outsideInfo, creationPCR)
respBuf = self.dispatchCommand(TPM_CC.Create, req)
return self.processResponse(respBuf, CreateResponse)
# Create()
def Load(self, parentHandle, inPrivate, inPublic):
""" This command is used to load objects into the TPM. This command is
used when both a TPM2B_PUBLIC and TPM2B_PRIVATE are to be loaded. If
only a TPM2B_PUBLIC is to be loaded, the TPM2_LoadExternal command is used.
Args:
parentHandle (TPM_HANDLE): TPM handle of parent key; shall not be a
reserved handle
Auth Index: 1
Auth Role: USER
inPrivate (TPM2B_PRIVATE): The private portion of the object
inPublic (TPMT_PUBLIC): The public portion of the object
Returns:
handle - Handle of type TPM_HT_TRANSIENT for the loaded object
"""
req = TPM2_Load_REQUEST(parentHandle, inPrivate, inPublic)
respBuf = self.dispatchCommand(TPM_CC.Load, req)
res = self.processResponse(respBuf, LoadResponse)
return res.handle if res else None
# Load()
def LoadExternal(self, inPrivate, inPublic, hierarchy):
""" This command is used to load an object that is not a Protected
Object into the TPM. The command allows loading of a public area or both
a public and sensitive area.
Args:
inPrivate (TPMT_SENSITIVE): The sensitive portion of the object (optional)
inPublic (TPMT_PUBLIC): The public portion of the object
hierarchy (TPM_HANDLE): Hierarchy with which the object area is associated
Returns:
handle - Handle of type TPM_HT_TRANSIENT for the loaded object
"""
req = TPM2_LoadExternal_REQUEST(inPrivate, inPublic, hierarchy)
respBuf = self.dispatchCommand(TPM_CC.LoadExternal, req)
res = self.processResponse(respBuf, LoadExternalResponse)
return res.handle if res else None
# LoadExternal()
def ReadPublic(self, objectHandle):
""" This command allows access to the public area of a loaded object.
Args:
objectHandle (TPM_HANDLE): TPM handle of an object
Auth Index: None
Returns:
outPublic - Structure containing the public area of an object
name - Name of the object
qualifiedName - The Qualified Name of the object
"""
req = TPM2_ReadPublic_REQUEST(objectHandle)
respBuf = self.dispatchCommand(TPM_CC.ReadPublic, req)
return self.processResponse(respBuf, ReadPublicResponse)
# ReadPublic()
def ActivateCredential(self, activateHandle, keyHandle, credentialBlob, secret):
""" This command enables the association of a credential with an object
in a way that ensures that the TPM has validated the parameters of the
credentialed object.
Args:
activateHandle (TPM_HANDLE): Handle of the object associated with
certificate in credentialBlob
Auth Index: 1
Auth Role: ADMIN
keyHandle (TPM_HANDLE): Loaded key used to decrypt the
TPMS_SENSITIVE in credentialBlob
Auth Index: 2
Auth Role: USER
credentialBlob (TPMS_ID_OBJECT): The credential
secret (bytes): KeyHandle algorithm-dependent encrypted seed that
protects credentialBlob
Returns:
certInfo - The decrypted certificate information
the data should be no larger than the size of the digest
of the nameAlg associated with keyHandle
"""
req = TPM2_ActivateCredential_REQUEST(activateHandle, keyHandle, credentialBlob, secret)
respBuf = self.dispatchCommand(TPM_CC.ActivateCredential, req)
res = self.processResponse(respBuf, ActivateCredentialResponse)
return res.certInfo if res else None
# ActivateCredential()
def MakeCredential(self, handle, credential, objectName):
""" This command allows the TPM to perform the actions required of a
Certificate Authority (CA) in creating a TPM2B_ID_OBJECT containing an
activation credential.
Args:
handle (TPM_HANDLE): Loaded public area, used to encrypt the
sensitive area containing the credential key
Auth Index: None
credential (bytes): The credential information
objectName (bytes): Name of the object to which the credential applies
Returns:
credentialBlob - The credential
secret - Handle algorithm-dependent data that wraps the key that
encrypts credentialBlob
"""
req = TPM2_MakeCredential_REQUEST(handle, credential, objectName)
respBuf = self.dispatchCommand(TPM_CC.MakeCredential, req)
return self.processResponse(respBuf, MakeCredentialResponse)
# MakeCredential()
def Unseal(self, itemHandle):
""" This command returns the data in a loaded Sealed Data Object.
Args:
itemHandle (TPM_HANDLE): Handle of a loaded data object
Auth Index: 1
Auth Role: USER
Returns:
outData - Unsealed data
Size of outData is limited to be no more than 128 octets.
"""
req = TPM2_Unseal_REQUEST(itemHandle)
respBuf = self.dispatchCommand(TPM_CC.Unseal, req)
res = self.processResponse(respBuf, UnsealResponse)
return res.outData if res else None
# Unseal()
def ObjectChangeAuth(self, objectHandle, parentHandle, newAuth):
""" This command is used to change the authorization secret for a
TPM-resident object.
Args:
objectHandle (TPM_HANDLE): Handle of the object
Auth Index: 1
Auth Role: ADMIN
parentHandle (TPM_HANDLE): Handle of the parent
Auth Index: None
newAuth (bytes): New authorization value
Returns:
outPrivate - Private area containing the new authorization value
"""
req = TPM2_ObjectChangeAuth_REQUEST(objectHandle, parentHandle, newAuth)
respBuf = self.dispatchCommand(TPM_CC.ObjectChangeAuth, req)
res = self.processResponse(respBuf, ObjectChangeAuthResponse)
return res.outPrivate if res else None
# ObjectChangeAuth()
def CreateLoaded(self, parentHandle, inSensitive, inPublic):
""" This command creates an object and loads it in the TPM. This command
allows creation of any type of object (Primary, Ordinary, or Derived)
depending on the type of parentHandle. If parentHandle references a
Primary Seed, then a Primary Object is created; if parentHandle
references a Storage Parent, then an Ordinary Object is created; and if
parentHandle references a Derivation Parent, then a Derived Object is
generated.
Args:
parentHandle (TPM_HANDLE): Handle of a transient storage key, a
persistent storage key, TPM_RH_ENDORSEMENT, TPM_RH_OWNER,
TPM_RH_PLATFORM+{PP}, or TPM_RH_NULL
Auth Index: 1
Auth Role: USER
inSensitive (TPMS_SENSITIVE_CREATE): The sensitive data, see TPM 2.0
Part 1 Sensitive Values
inPublic (bytes): The public template
Returns:
handle - Handle of type TPM_HT_TRANSIENT for created object
outPrivate - The sensitive area of the object (optional)
outPublic - The public portion of the created object
name - The name of the created object
"""
req = TPM2_CreateLoaded_REQUEST(parentHandle, inSensitive, inPublic)
respBuf = self.dispatchCommand(TPM_CC.CreateLoaded, req)
return self.processResponse(respBuf, CreateLoadedResponse)
# CreateLoaded()
def Duplicate(self, objectHandle, newParentHandle, encryptionKeyIn, symmetricAlg):
""" This command duplicates a loaded object so that it may be used in a
different hierarchy. The new parent key for the duplicate may be on the
same or different TPM or TPM_RH_NULL. Only the public area of
newParentHandle is required to be loaded.
Args:
objectHandle (TPM_HANDLE): Loaded object to duplicate
Auth Index: 1
Auth Role: DUP
newParentHandle (TPM_HANDLE): Shall reference the public area of an
asymmetric key
Auth Index: None
encryptionKeyIn (bytes): Optional symmetric encryption key
The size for this key is set to zero when the TPM is to generate
the key. This parameter may be encrypted.
symmetricAlg (TPMT_SYM_DEF_OBJECT): Definition for the symmetric
algorithm to be used for the inner wrapper
may be TPM_ALG_NULL if no inner wrapper is applied
Returns:
encryptionKeyOut - If the caller provided an encryption key or if
symmetricAlg was TPM_ALG_NULL, then this will be
the Empty Buffer; otherwise, it shall contain the
TPM-generated, symmetric encryption key for the
inner wrapper.
duplicate - Private area that may be encrypted by encryptionKeyIn;
and may be doubly encrypted
outSymSeed - Seed protected by the asymmetric algorithms of new
parent (NP)
"""
req = TPM2_Duplicate_REQUEST(objectHandle, newParentHandle, encryptionKeyIn, symmetricAlg)
respBuf = self.dispatchCommand(TPM_CC.Duplicate, req)
return self.processResponse(respBuf, DuplicateResponse)
# Duplicate()
def Rewrap(self, oldParent, newParent, inDuplicate, name, inSymSeed):
""" This command allows the TPM to serve in the role as a Duplication
Authority. If proper authorization for use of the oldParent is provided,
then an HMAC key and a symmetric key are recovered from inSymSeed and
used to integrity check and decrypt inDuplicate. A new protection seed
value is generated according to the methods appropriate for newParent
and the blob is re-encrypted and a new integrity value is computed. The
re-encrypted blob is returned in outDuplicate and the symmetric key
returned in outSymKey.
Args:
oldParent (TPM_HANDLE): Parent of object
Auth Index: 1
Auth Role: User
newParent (TPM_HANDLE): New parent of the object
Auth Index: None
inDuplicate (TPM2B_PRIVATE): An object encrypted using symmetric key
derived from inSymSeed
name (bytes): The Name of the object being rewrapped
inSymSeed (bytes): The seed for the symmetric key and HMAC key
needs oldParent private key to recover the seed and generate the
symmetric key
Returns:
outDuplicate - An object encrypted using symmetric key derived from
outSymSeed
outSymSeed - Seed for a symmetric key protected by newParent
asymmetric key
"""
req = TPM2_Rewrap_REQUEST(oldParent, newParent, inDuplicate, name, inSymSeed)
respBuf = self.dispatchCommand(TPM_CC.Rewrap, req)
return self.processResponse(respBuf, RewrapResponse)
# Rewrap()
def Import(self, parentHandle, encryptionKey, objectPublic, duplicate, inSymSeed, symmetricAlg):
""" This command allows an object to be encrypted using the symmetric
encryption values of a Storage Key. After encryption, the object may be
loaded and used in the new hierarchy. The imported object (duplicate)
may be singly encrypted, multiply encrypted, or unencrypted.
Args:
parentHandle (TPM_HANDLE): The handle of the new parent for the object
Auth Index: 1
Auth Role: USER
encryptionKey (bytes): The optional symmetric encryption key used as
the inner wrapper for duplicate
If symmetricAlg is TPM_ALG_NULL, then this parameter shall be
the Empty Buffer.
objectPublic (TPMT_PUBLIC): The public area of the object to be imported
This is provided so that the integrity value for duplicate and
the object attributes can be checked.
NOTE Even if the integrity value of the object is not checked on
input, the object Name is required to create the integrity value
for the imported object.
duplicate (TPM2B_PRIVATE): The symmetrically encrypted duplicate
object that may contain an inner symmetric wrapper
inSymSeed (bytes): The seed for the symmetric key and HMAC key
inSymSeed is encrypted/encoded using the algorithms of newParent.
symmetricAlg (TPMT_SYM_DEF_OBJECT): Definition for the symmetric
algorithm to use for the inner wrapper
If this algorithm is TPM_ALG_NULL, no inner wrapper is present
and encryptionKey shall be the Empty Buffer.
Returns:
outPrivate - The sensitive area encrypted with the symmetric key of
parentHandle
"""
req = TPM2_Import_REQUEST(parentHandle, encryptionKey, objectPublic, duplicate, inSymSeed, symmetricAlg)
respBuf = self.dispatchCommand(TPM_CC.Import, req)
res = self.processResponse(respBuf, ImportResponse)
return res.outPrivate if res else None
# Import()
def RSA_Encrypt(self, keyHandle, message, inScheme, label):
""" This command performs RSA encryption using the indicated padding
scheme according to IETF RFC 8017. If the scheme of keyHandle is
TPM_ALG_NULL, then the caller may use inScheme to specify the padding
scheme. If scheme of keyHandle is not TPM_ALG_NULL, then inScheme shall
either be TPM_ALG_NULL or be the same as scheme (TPM_RC_SCHEME).
Args:
keyHandle (TPM_HANDLE): Reference to public portion of RSA key to
use for encryption
Auth Index: None
message (bytes): Message to be encrypted
NOTE 1 The data type was chosen because it limits the overall
size of the input to no greater than the size of the largest RSA
public key. This may be larger than allowed for keyHandle.
inScheme (TPMU_ASYM_SCHEME): The padding scheme to use if scheme
associated with keyHandle is TPM_ALG_NULL
One of: TPMS_KEY_SCHEME_ECDH, TPMS_KEY_SCHEME_ECMQV,
TPMS_SIG_SCHEME_RSASSA, TPMS_SIG_SCHEME_RSAPSS,
TPMS_SIG_SCHEME_ECDSA, TPMS_SIG_SCHEME_ECDAA,
TPMS_SIG_SCHEME_SM2, TPMS_SIG_SCHEME_ECSCHNORR,
TPMS_ENC_SCHEME_RSAES, TPMS_ENC_SCHEME_OAEP, TPMS_SCHEME_HASH,
TPMS_NULL_ASYM_SCHEME.
label (bytes): Optional label L to be associated with the message
Size of the buffer is zero if no label is present
NOTE 2 See description of label above.
Returns:
outData - Encrypted output
"""
req = TPM2_RSA_Encrypt_REQUEST(keyHandle, message, inScheme, label)
respBuf = self.dispatchCommand(TPM_CC.RSA_Encrypt, req)
res = self.processResponse(respBuf, RSA_EncryptResponse)
return res.outData if res else None
# RSA_Encrypt()
def RSA_Decrypt(self, keyHandle, cipherText, inScheme, label):
""" This command performs RSA decryption using the indicated padding
scheme according to IETF RFC 8017 ((PKCS#1).
Args:
keyHandle (TPM_HANDLE): RSA key to use for decryption
Auth Index: 1
Auth Role: USER
cipherText (bytes): Cipher text to be decrypted
NOTE An encrypted RSA data block is the size of the public modulus.
inScheme (TPMU_ASYM_SCHEME): The padding scheme to use if scheme
associated with keyHandle is TPM_ALG_NULL
One of: TPMS_KEY_SCHEME_ECDH, TPMS_KEY_SCHEME_ECMQV,
TPMS_SIG_SCHEME_RSASSA, TPMS_SIG_SCHEME_RSAPSS,
TPMS_SIG_SCHEME_ECDSA, TPMS_SIG_SCHEME_ECDAA,
TPMS_SIG_SCHEME_SM2, TPMS_SIG_SCHEME_ECSCHNORR,
TPMS_ENC_SCHEME_RSAES, TPMS_ENC_SCHEME_OAEP, TPMS_SCHEME_HASH,
TPMS_NULL_ASYM_SCHEME.
label (bytes): Label whose association with the message is to be verified
Returns:
message - Decrypted output
"""
req = TPM2_RSA_Decrypt_REQUEST(keyHandle, cipherText, inScheme, label)
respBuf = self.dispatchCommand(TPM_CC.RSA_Decrypt, req)
res = self.processResponse(respBuf, RSA_DecryptResponse)
return res.message if res else None
# RSA_Decrypt()
def ECDH_KeyGen(self, keyHandle):
""" This command uses the TPM to generate an ephemeral key pair (de, Qe
where Qe [de]G). It uses the private ephemeral key and a loaded public
key (QS) to compute the shared secret value (P [hde]QS).
Args:
keyHandle (TPM_HANDLE): Handle of a loaded ECC key public area.
Auth Index: None
Returns:
zPoint - Results of P h[de]Qs
pubPoint - Generated ephemeral public point (Qe)
"""
req = TPM2_ECDH_KeyGen_REQUEST(keyHandle)
respBuf = self.dispatchCommand(TPM_CC.ECDH_KeyGen, req)
return self.processResponse(respBuf, ECDH_KeyGenResponse)
# ECDH_KeyGen()
def ECDH_ZGen(self, keyHandle, inPoint):
""" This command uses the TPM to recover the Z value from a public point
(QB) and a private key (ds). It will perform the multiplication of the
provided inPoint (QB) with the private key (ds) and return the
coordinates of the resultant point (Z = (xZ , yZ) [hds]QB; where h is
the cofactor of the curve).
Args:
keyHandle (TPM_HANDLE): Handle of a loaded ECC key
Auth Index: 1
Auth Role: USER
inPoint (TPMS_ECC_POINT): A public key
Returns:
outPoint - X and Y coordinates of the product of the multiplication
Z = (xZ , yZ) [hdS]QB
"""
req = TPM2_ECDH_ZGen_REQUEST(keyHandle, inPoint)
respBuf = self.dispatchCommand(TPM_CC.ECDH_ZGen, req)
res = self.processResponse(respBuf, ECDH_ZGenResponse)
return res.outPoint if res else None
# ECDH_ZGen()
def ECC_Parameters(self, curveID):
""" This command returns the parameters of an ECC curve identified by
its TCG-assigned curveID.
Args:
curveID (TPM_ECC_CURVE): Parameter set selector
Returns:
parameters - ECC parameters for the selected curve
"""
req = TPM2_ECC_Parameters_REQUEST(curveID)
respBuf = self.dispatchCommand(TPM_CC.ECC_Parameters, req)
res = self.processResponse(respBuf, ECC_ParametersResponse)
return res.parameters if res else None
# ECC_Parameters()
def ZGen_2Phase(self, keyA, inQsB, inQeB, inScheme, counter):
""" This command supports two-phase key exchange protocols. The command
is used in combination with TPM2_EC_Ephemeral(). TPM2_EC_Ephemeral()
generates an ephemeral key and returns the public point of that
ephemeral key along with a numeric value that allows the TPM to
regenerate the associated private key.
Args:
keyA (TPM_HANDLE): Handle of an unrestricted decryption key ECC
The private key referenced by this handle is used as dS,A
Auth Index: 1
Auth Role: USER
inQsB (TPMS_ECC_POINT): Other partys static public key (Qs,B =
(Xs,B, Ys,B))
inQeB (TPMS_ECC_POINT): Other party's ephemeral public key (Qe,B =
(Xe,B, Ye,B))
inScheme (TPM_ALG_ID): The key exchange scheme
counter (int): Value returned by TPM2_EC_Ephemeral()
Returns:
outZ1 - X and Y coordinates of the computed value (scheme dependent)
outZ2 - X and Y coordinates of the second computed value (scheme dependent)
"""
req = TPM2_ZGen_2Phase_REQUEST(keyA, inQsB, inQeB, inScheme, counter)
respBuf = self.dispatchCommand(TPM_CC.ZGen_2Phase, req)
return self.processResponse(respBuf, ZGen_2PhaseResponse)
# ZGen_2Phase()
def ECC_Encrypt(self, keyHandle, plainText, inScheme):
""" This command performs ECC encryption as described in Part 1, Annex D.
Args:
keyHandle (TPM_HANDLE): Reference to public portion of ECC key to
use for encryption
Auth Index: None
plainText (bytes): Plaintext to be encrypted
inScheme (TPMU_KDF_SCHEME): The KDF to use if scheme associated with
keyHandle is TPM_ALG_NULL
One of: TPMS_KDF_SCHEME_MGF1, TPMS_KDF_SCHEME_KDF1_SP800_56A,
TPMS_KDF_SCHEME_KDF2, TPMS_KDF_SCHEME_KDF1_SP800_108,
TPMS_SCHEME_HASH, TPMS_NULL_KDF_SCHEME.
Returns:
C1 - The public ephemeral key used for ECDH
C2 - The data block produced by the XOR process
C3 - The integrity value
"""
req = TPM2_ECC_Encrypt_REQUEST(keyHandle, plainText, inScheme)
respBuf = self.dispatchCommand(TPM_CC.ECC_Encrypt, req)
return self.processResponse(respBuf, ECC_EncryptResponse)
# ECC_Encrypt()
def ECC_Decrypt(self, keyHandle, C1, C2, C3, inScheme):
""" This command performs ECC decryption.
Args:
keyHandle (TPM_HANDLE): ECC key to use for decryption
Auth Index: 1
Auth Role: USER
C1 (TPMS_ECC_POINT): The public ephemeral key used for ECDH
C2 (bytes): The data block produced by the XOR process
C3 (bytes): The integrity value
inScheme (TPMU_KDF_SCHEME): The KDF to use if scheme associated with
keyHandle is TPM_ALG_NULL
One of: TPMS_KDF_SCHEME_MGF1, TPMS_KDF_SCHEME_KDF1_SP800_56A,
TPMS_KDF_SCHEME_KDF2, TPMS_KDF_SCHEME_KDF1_SP800_108,
TPMS_SCHEME_HASH, TPMS_NULL_KDF_SCHEME.
Returns:
plainText - Decrypted output
"""
req = TPM2_ECC_Decrypt_REQUEST(keyHandle, C1, C2, C3, inScheme)
respBuf = self.dispatchCommand(TPM_CC.ECC_Decrypt, req)
res = self.processResponse(respBuf, ECC_DecryptResponse)
return res.plainText if res else None
# ECC_Decrypt()
def EncryptDecrypt(self, keyHandle, decrypt, mode, ivIn, inData):
""" NOTE 1 This command is deprecated, and TPM2_EncryptDecrypt2() is
preferred. This should be reflected in platform-specific specifications.
Args:
keyHandle (TPM_HANDLE): The symmetric key used for the operation
Auth Index: 1
Auth Role: USER
decrypt (int): If YES, then the operation is decryption; if NO, the
operation is encryption
mode (TPM_ALG_ID): Symmetric encryption/decryption mode
this field shall match the default mode of the key or be TPM_ALG_NULL.
ivIn (bytes): An initial value as required by the algorithm
inData (bytes): The data to be encrypted/decrypted
Returns:
outData - Encrypted or decrypted output
ivOut - Chaining value to use for IV in next round
"""
req = TPM2_EncryptDecrypt_REQUEST(keyHandle, decrypt, mode, ivIn, inData)
respBuf = self.dispatchCommand(TPM_CC.EncryptDecrypt, req)
return self.processResponse(respBuf, EncryptDecryptResponse)
# EncryptDecrypt()
def EncryptDecrypt2(self, keyHandle, inData, decrypt, mode, ivIn):
""" This command is identical to TPM2_EncryptDecrypt(), except that the
inData parameter is the first parameter. This permits inData to be
parameter encrypted.
Args:
keyHandle (TPM_HANDLE): The symmetric key used for the operation
Auth Index: 1
Auth Role: USER
inData (bytes): The data to be encrypted/decrypted
decrypt (int): If YES, then the operation is decryption; if NO, the
operation is encryption
mode (TPM_ALG_ID): Symmetric mode
this field shall match the default mode of the key or be TPM_ALG_NULL.
ivIn (bytes): An initial value as required by the algorithm
Returns:
outData - Encrypted or decrypted output
ivOut - Chaining value to use for IV in next round
"""
req = TPM2_EncryptDecrypt2_REQUEST(keyHandle, inData, decrypt, mode, ivIn)
respBuf = self.dispatchCommand(TPM_CC.EncryptDecrypt2, req)
return self.processResponse(respBuf, EncryptDecrypt2Response)
# EncryptDecrypt2()
def Hash(self, data, hashAlg, hierarchy):
""" This command performs a hash operation on a data buffer and returns
the results.
Args:
data (bytes): Data to be hashed
hashAlg (TPM_ALG_ID): Algorithm for the hash being computed shall
not be TPM_ALG_NULL
hierarchy (TPM_HANDLE): Hierarchy to use for the ticket (TPM_RH_NULL
allowed)
Returns:
outHash - Results
validation - Ticket indicating that the sequence of octets used to
compute outDigest did not start with TPM_GENERATED_VALUE
will be a NULL ticket if the digest may not be signed
with a restricted key
"""
req = TPM2_Hash_REQUEST(data, hashAlg, hierarchy)
respBuf = self.dispatchCommand(TPM_CC.Hash, req)
return self.processResponse(respBuf, HashResponse)
# Hash()
def HMAC(self, handle, buffer, hashAlg):
""" This command performs an HMAC on the supplied data using the
indicated hash algorithm.
Args:
handle (TPM_HANDLE): Handle for the symmetric signing key providing
the HMAC key
Auth Index: 1
Auth Role: USER
buffer (bytes): HMAC data
hashAlg (TPM_ALG_ID): Algorithm to use for HMAC
Returns:
outHMAC - The returned HMAC in a sized buffer
"""
req = TPM2_HMAC_REQUEST(handle, buffer, hashAlg)
respBuf = self.dispatchCommand(TPM_CC.HMAC, req)
res = self.processResponse(respBuf, HMACResponse)
return res.outHMAC if res else None
# HMAC()
def MAC(self, handle, buffer, inScheme):
""" This command performs an HMAC or a block cipher MAC on the supplied
data using the indicated algorithm.
Args:
handle (TPM_HANDLE): Handle for the symmetric signing key providing
the MAC key
Auth Index: 1
Auth Role: USER
buffer (bytes): MAC data
inScheme (TPM_ALG_ID): Algorithm to use for MAC
Returns:
outMAC - The returned MAC in a sized buffer
"""
req = TPM2_MAC_REQUEST(handle, buffer, inScheme)
respBuf = self.dispatchCommand(TPM_CC.MAC, req)
res = self.processResponse(respBuf, MACResponse)
return res.outMAC if res else None
# MAC()
def GetRandom(self, bytesRequested):
""" This command returns the next bytesRequested octets from the random
number generator (RNG).
Args:
bytesRequested (int): Number of octets to return
Returns:
randomBytes - The random octets
"""
req = TPM2_GetRandom_REQUEST(bytesRequested)
respBuf = self.dispatchCommand(TPM_CC.GetRandom, req)
res = self.processResponse(respBuf, GetRandomResponse)
return res.randomBytes if res else None
# GetRandom()
def StirRandom(self, inData):
""" This command is used to add "additional information" to the RNG state.
Args:
inData (bytes): Additional information
"""
req = TPM2_StirRandom_REQUEST(inData)
respBuf = self.dispatchCommand(TPM_CC.StirRandom, req)
return self.processResponse(respBuf)
# StirRandom()
def HMAC_Start(self, handle, auth, hashAlg):
""" This command starts an HMAC sequence. The TPM will create and
initialize an HMAC sequence structure, assign a handle to the sequence,
and set the authValue of the sequence object to the value in auth.
Args:
handle (TPM_HANDLE): Handle of an HMAC key
Auth Index: 1
Auth Role: USER
auth (bytes): Authorization value for subsequent use of the sequence
hashAlg (TPM_ALG_ID): The hash algorithm to use for the HMAC
Returns:
handle - A handle to reference the sequence
"""
req = TPM2_HMAC_Start_REQUEST(handle, auth, hashAlg)
respBuf = self.dispatchCommand(TPM_CC.HMAC_Start, req)
res = self.processResponse(respBuf, HMAC_StartResponse)
return res.handle if res else None
# HMAC_Start()
def MAC_Start(self, handle, auth, inScheme):
""" This command starts a MAC sequence. The TPM will create and
initialize a MAC sequence structure, assign a handle to the sequence,
and set the authValue of the sequence object to the value in auth.
Args:
handle (TPM_HANDLE): Handle of a MAC key
Auth Index: 1
Auth Role: USER
auth (bytes): Authorization value for subsequent use of the sequence
inScheme (TPM_ALG_ID): The algorithm to use for the MAC
Returns:
handle - A handle to reference the sequence
"""
req = TPM2_MAC_Start_REQUEST(handle, auth, inScheme)
respBuf = self.dispatchCommand(TPM_CC.MAC_Start, req)
res = self.processResponse(respBuf, MAC_StartResponse)
return res.handle if res else None
# MAC_Start()
def HashSequenceStart(self, auth, hashAlg):
""" This command starts a hash or an Event Sequence. If hashAlg is an
implemented hash, then a hash sequence is started. If hashAlg is
TPM_ALG_NULL, then an Event Sequence is started. If hashAlg is neither
an implemented algorithm nor TPM_ALG_NULL, then the TPM shall return
TPM_RC_HASH.
Args:
auth (bytes): Authorization value for subsequent use of the sequence
hashAlg (TPM_ALG_ID): The hash algorithm to use for the hash sequence
An Event Sequence starts if this is TPM_ALG_NULL.
Returns:
handle - A handle to reference the sequence
"""
req = TPM2_HashSequenceStart_REQUEST(auth, hashAlg)
respBuf = self.dispatchCommand(TPM_CC.HashSequenceStart, req)
res = self.processResponse(respBuf, HashSequenceStartResponse)
return res.handle if res else None
# HashSequenceStart()
def SequenceUpdate(self, sequenceHandle, buffer):
""" This command is used to add data to a hash or HMAC sequence. The
amount of data in buffer may be any size up to the limits of the TPM.
Args:
sequenceHandle (TPM_HANDLE): Handle for the sequence object
Auth Index: 1
Auth Role: USER
buffer (bytes): Data to be added to hash
"""
req = TPM2_SequenceUpdate_REQUEST(sequenceHandle, buffer)
respBuf = self.dispatchCommand(TPM_CC.SequenceUpdate, req)
return self.processResponse(respBuf)
# SequenceUpdate()
def SequenceComplete(self, sequenceHandle, buffer, hierarchy):
""" This command adds the last part of data, if any, to a hash/HMAC
sequence and returns the result.
Args:
sequenceHandle (TPM_HANDLE): Authorization for the sequence
Auth Index: 1
Auth Role: USER
buffer (bytes): Data to be added to the hash/HMAC
hierarchy (TPM_HANDLE): Hierarchy of the ticket for a hash
Returns:
result - The returned HMAC or digest in a sized buffer
validation - Ticket indicating that the sequence of octets used to
compute outDigest did not start with TPM_GENERATED_VALUE
This is a NULL Ticket when the sequence is HMAC.
"""
req = TPM2_SequenceComplete_REQUEST(sequenceHandle, buffer, hierarchy)
respBuf = self.dispatchCommand(TPM_CC.SequenceComplete, req)
return self.processResponse(respBuf, SequenceCompleteResponse)
# SequenceComplete()
def EventSequenceComplete(self, pcrHandle, sequenceHandle, buffer):
""" This command adds the last part of data, if any, to an Event
Sequence and returns the result in a digest list. If pcrHandle
references a PCR and not TPM_RH_NULL, then the returned digest list is
processed in the same manner as the digest list input parameter to
TPM2_PCR_Extend(). That is, if a bank contains a PCR associated with
pcrHandle, it is extended with the associated digest value from the list.
Args:
pcrHandle (TPM_HANDLE): PCR to be extended with the Event data
Auth Index: 1
Auth Role: USER
sequenceHandle (TPM_HANDLE): Authorization for the sequence
Auth Index: 2
Auth Role: USER
buffer (bytes): Data to be added to the Event
Returns:
results - List of digests computed for the PCR
"""
req = TPM2_EventSequenceComplete_REQUEST(pcrHandle, sequenceHandle, buffer)
respBuf = self.dispatchCommand(TPM_CC.EventSequenceComplete, req)
res = self.processResponse(respBuf, EventSequenceCompleteResponse)
return res.results if res else None
# EventSequenceComplete()
def Certify(self, objectHandle, signHandle, qualifyingData, inScheme):
""" The purpose of this command is to prove that an object with a
specific Name is loaded in the TPM. By certifying that the object is
loaded, the TPM warrants that a public area with a given Name is
self-consistent and associated with a valid sensitive area. If a relying
party has a public area that has the same Name as a Name certified with
this command, then the values in that public area are correct.
Args:
objectHandle (TPM_HANDLE): Handle of the object to be certified
Auth Index: 1
Auth Role: ADMIN
signHandle (TPM_HANDLE): Handle of the key used to sign the
attestation structure
Auth Index: 2
Auth Role: USER
qualifyingData (bytes): User provided qualifying data
inScheme (TPMU_SIG_SCHEME): Signing scheme to use if the scheme for
signHandle is TPM_ALG_NULL
One of: TPMS_SIG_SCHEME_RSASSA, TPMS_SIG_SCHEME_RSAPSS,
TPMS_SIG_SCHEME_ECDSA, TPMS_SIG_SCHEME_ECDAA,
TPMS_SIG_SCHEME_SM2, TPMS_SIG_SCHEME_ECSCHNORR,
TPMS_SCHEME_HMAC, TPMS_SCHEME_HASH, TPMS_NULL_SIG_SCHEME.
Returns:
certifyInfo - The structure that was signed
signature - The asymmetric signature over certifyInfo using the key
referenced by signHandle
"""
req = TPM2_Certify_REQUEST(objectHandle, signHandle, qualifyingData, inScheme)
respBuf = self.dispatchCommand(TPM_CC.Certify, req)
return self.processResponse(respBuf, CertifyResponse)
# Certify()
def CertifyCreation(self, signHandle, objectHandle, qualifyingData, creationHash, inScheme, creationTicket):
""" This command is used to prove the association between an object and
its creation data. The TPM will validate that the ticket was produced by
the TPM and that the ticket validates the association between a loaded
public area and the provided hash of the creation data (creationHash).
Args:
signHandle (TPM_HANDLE): Handle of the key that will sign the
attestation block
Auth Index: 1
Auth Role: USER
objectHandle (TPM_HANDLE): The object associated with the creation data
Auth Index: None
qualifyingData (bytes): User-provided qualifying data
creationHash (bytes): Hash of the creation data produced by
TPM2_Create() or TPM2_CreatePrimary()
inScheme (TPMU_SIG_SCHEME): Signing scheme to use if the scheme for
signHandle is TPM_ALG_NULL
One of: TPMS_SIG_SCHEME_RSASSA, TPMS_SIG_SCHEME_RSAPSS,
TPMS_SIG_SCHEME_ECDSA, TPMS_SIG_SCHEME_ECDAA,
TPMS_SIG_SCHEME_SM2, TPMS_SIG_SCHEME_ECSCHNORR,
TPMS_SCHEME_HMAC, TPMS_SCHEME_HASH, TPMS_NULL_SIG_SCHEME.
creationTicket (TPMT_TK_CREATION): Ticket produced by TPM2_Create()
or TPM2_CreatePrimary()
Returns:
certifyInfo - The structure that was signed
signature - The signature over certifyInfo
"""
req = TPM2_CertifyCreation_REQUEST(signHandle, objectHandle, qualifyingData, creationHash, inScheme, creationTicket)
respBuf = self.dispatchCommand(TPM_CC.CertifyCreation, req)
return self.processResponse(respBuf, CertifyCreationResponse)
# CertifyCreation()
def Quote(self, signHandle, qualifyingData, inScheme, PCRselect):
""" This command is used to quote PCR values.