-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtpm_attestation.py
More file actions
1638 lines (1429 loc) · 60.7 KB
/
tpm_attestation.py
File metadata and controls
1638 lines (1429 loc) · 60.7 KB
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
from pathlib import Path
import base64
import hashlib
import hmac
import logging
import os
import struct
from datetime import datetime, timezone
from dataclasses import dataclass
from typing import Optional
from asn1crypto import algos as a_algos
from asn1crypto import cms as a_cms
from asn1crypto import core as a_core
from asn1crypto import csr as a_csr
from cryptography import x509
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes, padding as sym_padding, serialization
from utils import _signature_algo_for_ca_key, _sign_tbs_with_ca_key, _tbs_signed_attrs
from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
logger = logging.getLogger("adcs.tpm_attestation")
OID_MS_ENROLL_EK_INFO = "1.3.6.1.4.1.311.21.23"
OID_MS_ENROLL_AIK_INFO = "1.3.6.1.4.1.311.21.39"
OID_MS_ENROLL_KSP_NAME = "1.3.6.1.4.1.311.21.25"
OID_MS_ENROLL_ATTESTATION_STATEMENT = "1.3.6.1.4.1.311.21.33"
OID_MS_ENROLL_ATTESTATION_STATEMENT_LEGACY = "1.3.6.1.4.1.311.21.24"
OID_CMC_STATUS_INFO = "1.3.6.1.5.5.7.7.1"
OID_MS_CMC_CHALLENGE_WRAPPER = "1.3.6.1.4.1.311.10.10.1"
OID_ENROLL_KSP_NAME = "1.3.6.1.4.1.311.21.25"
OID_ENROLL_CAXCHGCERT_HASH = "1.3.6.1.4.1.311.21.27"
OID_ENROLL_ATTESTATION_CHALLENGE = "1.3.6.1.4.1.311.21.28"
OID_ENROLL_ENCRYPTION_ALGORITHM = "1.3.6.1.4.1.311.21.29"
OID_ID_CCT_PKI_RESPONSE = "1.3.6.1.5.5.7.12.3"
OID_ID_SIGNED_DATA = "1.2.840.113549.1.7.2"
TPM2_ST_ATTEST_CERTIFY = 0x8017
TPM2_ST_ATTEST_QUOTE = 0x8018
TPM2_ST_ATTEST_CREATION = 0x801A
TPMA_OBJECT_FIXEDTPM = 0x00000002
TPMA_OBJECT_FIXEDPARENT = 0x00000010
TPMA_OBJECT_SENSITIVEDATAORIGIN = 0x00000020
TPMA_OBJECT_USERWITHAUTH = 0x00000040
TPMA_OBJECT_ADMINWITHPOLICY = 0x00000080
TPMA_OBJECT_NODA = 0x00000400
TPMA_OBJECT_RESTRICTED = 0x00010000
TPMA_OBJECT_DECRYPT = 0x00020000
TPMA_OBJECT_SIGN = 0x00040000
TPM2_ALG_RSA = 0x0001
TPM2_ALG_ECC = 0x0023
TPM2_ALG_SHA1 = 0x0004
TPM2_ALG_SHA256 = 0x000B
TPM2_ALG_SHA384 = 0x000C
TPM2_ALG_SHA512 = 0x000D
TPM2_ALG_NULL = 0x0010
TPM2_ALG_RSASSA = 0x0014
TPM2_ALG_RSAPSS = 0x0016
TPM2_ALG_ECDSA = 0x0018
TPM2_ALG_ECDAA = 0x001A
TPM2_ALG_SM2 = 0x001B
TPM2_ALG_ECSCHNORR = 0x001C
TPM2_ECC_NIST_P256 = 0x0003
TPM2_ECC_NIST_P384 = 0x0004
TPM2_GENERATED_VALUE = 0xFF544347
@dataclass
class AttestationData:
magic: int
attest_type: int
qualified_signer: bytes
extra_data: bytes
clock_info: bytes
firmware_version: int
certified_name: bytes = b""
certified_qname: bytes = b""
creation_name: bytes = b""
creation_hash: bytes = b""
pcr_selection: bytes = b""
pcr_digest: bytes = b""
raw: bytes = b""
@dataclass
class TPMAttestationBundle:
"""Microsoft PKCS#10 TPM attestation attributes extracted from a request.
This module intentionally supports only the Microsoft ADCS/PKCS#10
attestation flow. Microsoft keyAttestation still verifies the TPM
ST_ATTEST_CERTIFY structure where required.
"""
ms_attestation_statement_raw: Optional[bytes] = None
ms_attestation_blob_raw: Optional[bytes] = None
ms_ek_info_raw: Optional[bytes] = None
ms_aik_info_raw: Optional[bytes] = None
ms_ksp_name: Optional[str] = None
ms_ksp_name_raw: Optional[bytes] = None
# EK material recovered from Microsoft EK_INFO. This is still Microsoft-only
# state, not a generic attestation mode.
ek_cert_der: Optional[bytes] = None
ms_ek_info_decrypted_raw: Optional[bytes] = None
ms_embedded_certificates_der: Optional[list[bytes]] = None
class TPMAttestationError(Exception):
pass
class _Reader:
def __init__(self, data: bytes):
self._data = data
self._pos = 0
def raw(self, length: int) -> bytes:
if self._pos + length > len(self._data):
raise TPMAttestationError(
f"Parser overrun: need {length} bytes at offset {self._pos}, only {len(self._data) - self._pos} remaining"
)
chunk = self._data[self._pos:self._pos + length]
self._pos += length
return chunk
def u8(self) -> int:
return struct.unpack(">B", self.raw(1))[0]
def u16(self) -> int:
return struct.unpack(">H", self.raw(2))[0]
def u32(self) -> int:
return struct.unpack(">I", self.raw(4))[0]
def u64(self) -> int:
return struct.unpack(">Q", self.raw(8))[0]
def tpm2b(self) -> bytes:
return self.raw(self.u16())
def tell(self) -> int:
return self._pos
def _tpm2b(data: bytes) -> bytes:
return struct.pack(">H", len(data)) + data
def _tpm_alg_to_hash(alg: int) -> str:
mapping = {
TPM2_ALG_SHA1: "sha1",
TPM2_ALG_SHA256: "sha256",
TPM2_ALG_SHA384: "sha384",
TPM2_ALG_SHA512: "sha512",
}
if alg not in mapping:
raise TPMAttestationError(f"Unsupported TPM hash algorithm: {alg:#06x}")
return mapping[alg]
def _tpm_alg_name(alg: int) -> str:
mapping = {
TPM2_ALG_RSA: "rsa",
TPM2_ALG_ECC: "ecc",
TPM2_ALG_SHA1: "sha1",
TPM2_ALG_SHA256: "sha256",
TPM2_ALG_SHA384: "sha384",
TPM2_ALG_SHA512: "sha512",
TPM2_ALG_NULL: "null",
TPM2_ALG_RSASSA: "rsassa",
TPM2_ALG_RSAPSS: "rsapss",
TPM2_ALG_ECDSA: "ecdsa",
TPM2_ALG_ECDAA: "ecdaa",
TPM2_ALG_SM2: "sm2",
TPM2_ALG_ECSCHNORR: "ecschnorr",
}
return mapping.get(alg, f"unknown_{alg:#06x}")
def _tpm_alg_to_hash_obj(alg: int):
mapping = {
TPM2_ALG_SHA1: hashes.SHA1(),
TPM2_ALG_SHA256: hashes.SHA256(),
TPM2_ALG_SHA384: hashes.SHA384(),
TPM2_ALG_SHA512: hashes.SHA512(),
}
if alg not in mapping:
raise TPMAttestationError(f"Unsupported TPM hash algorithm: {alg:#06x}")
return mapping[alg]
@dataclass
class TPMPublicKey:
alg_type: int
name_alg: int
object_attr: int
auth_policy: bytes
rsa_key_bits: int = 0
rsa_exponent: int = 0
rsa_modulus: bytes = b""
ecc_curve: int = 0
ecc_x: bytes = b""
ecc_y: bytes = b""
_raw_bytes: bytes | None = None
def to_cryptography_public_key(self):
if self.alg_type == TPM2_ALG_RSA:
exponent = self.rsa_exponent or 65537
modulus = int.from_bytes(self.rsa_modulus, "big")
return rsa.RSAPublicNumbers(exponent, modulus).public_key()
if self.alg_type == TPM2_ALG_ECC:
x = int.from_bytes(self.ecc_x, "big")
y = int.from_bytes(self.ecc_y, "big")
_curve_map = {
TPM2_ECC_NIST_P256: ec.SECP256R1(),
TPM2_ECC_NIST_P384: ec.SECP384R1(),
}
if self.ecc_curve not in _curve_map:
raise TPMAttestationError(
f"Unsupported TPM ECC curve: {self.ecc_curve:#06x}"
)
return ec.EllipticCurvePublicNumbers(x, y, _curve_map[self.ecc_curve]).public_key()
raise TPMAttestationError(f"Unsupported TPM key algorithm: {self.alg_type:#06x}")
def compute_name(self) -> bytes:
raw = self._raw_bytes if self._raw_bytes is not None else self._marshal()
digest = hashlib.new(_tpm_alg_to_hash(self.name_alg), raw).digest()
return struct.pack(">H", self.name_alg) + digest
def _marshal(self) -> bytes:
out = struct.pack(">HHI", self.alg_type, self.name_alg, self.object_attr)
out += _tpm2b(self.auth_policy)
if self.alg_type == TPM2_ALG_RSA:
out += struct.pack(">HHHhI", TPM2_ALG_NULL, TPM2_ALG_NULL, self.rsa_key_bits, TPM2_ALG_NULL, self.rsa_exponent)
out += _tpm2b(self.rsa_modulus)
elif self.alg_type == TPM2_ALG_ECC:
out += struct.pack(">HHHH", TPM2_ALG_NULL, TPM2_ALG_NULL, self.ecc_curve, TPM2_ALG_NULL)
out += _tpm2b(self.ecc_x)
out += _tpm2b(self.ecc_y)
return out
def parse_tpms_attest(raw: bytes) -> AttestationData:
r = _Reader(raw)
magic = r.u32()
attest_type = r.u16()
qualified_signer = r.tpm2b()
extra_data = r.tpm2b()
clock_info = r.raw(8)
reset_count = r.u32()
restart_count = r.u32()
safe = r.u8()
firmware_version = r.u64()
attest = AttestationData(
magic=magic,
attest_type=attest_type,
qualified_signer=qualified_signer,
extra_data=extra_data,
clock_info=clock_info + struct.pack(">II", reset_count, restart_count) + bytes([safe]),
firmware_version=firmware_version,
raw=raw,
)
if attest_type == TPM2_ST_ATTEST_CERTIFY:
attest.certified_name = r.tpm2b()
attest.certified_qname = r.tpm2b()
elif attest_type == TPM2_ST_ATTEST_CREATION:
attest.creation_name = r.tpm2b()
attest.creation_hash = r.tpm2b()
elif attest_type == TPM2_ST_ATTEST_QUOTE:
count = r.u32()
selection = b""
for _ in range(count):
hash_alg = r.u16()
sel_size = r.u8()
selection += struct.pack(">HB", hash_alg, sel_size) + r.raw(sel_size)
attest.pcr_selection = struct.pack(">I", count) + selection
attest.pcr_digest = r.tpm2b()
return attest
def parse_tpmt_public(raw: bytes) -> TPMPublicKey:
r = _Reader(raw)
alg_type = r.u16()
name_alg = r.u16()
object_attr = r.u32()
auth_policy = r.tpm2b()
out = TPMPublicKey(alg_type=alg_type, name_alg=name_alg, object_attr=object_attr, auth_policy=auth_policy)
if alg_type == TPM2_ALG_RSA:
r.u16() # symmetric
scheme = r.u16()
if scheme in (TPM2_ALG_RSASSA, TPM2_ALG_RSAPSS):
r.u16()
out.rsa_key_bits = r.u16()
out.rsa_exponent = r.u32()
out.rsa_modulus = r.tpm2b()
elif alg_type == TPM2_ALG_ECC:
r.u16() # symmetric
scheme = r.u16()
if scheme in (TPM2_ALG_ECDSA, TPM2_ALG_ECDAA, TPM2_ALG_SM2, TPM2_ALG_ECSCHNORR):
r.u16()
out.ecc_curve = r.u16()
r.u16() # kdf
out.ecc_x = r.tpm2b()
out.ecc_y = r.tpm2b()
else:
raise TPMAttestationError(f"Unsupported TPMT_PUBLIC algorithm: {alg_type:#06x}")
out._raw_bytes = raw[:r.tell()]
return out
def _verify_tpm_signature(data: bytes, sig_raw: bytes, pub_key: TPMPublicKey):
r = _Reader(sig_raw)
sig_alg = r.u16()
hash_alg = r.u16()
hash_obj = _tpm_alg_to_hash_obj(hash_alg)
crypto_key = pub_key.to_cryptography_public_key()
if sig_alg in (TPM2_ALG_RSASSA, TPM2_ALG_RSAPSS):
sig_bytes = r.tpm2b()
try:
if sig_alg == TPM2_ALG_RSASSA:
crypto_key.verify(sig_bytes, data, padding.PKCS1v15(), hash_obj)
else:
crypto_key.verify(
sig_bytes,
data,
padding.PSS(mgf=padding.MGF1(hash_obj), salt_length=padding.PSS.MAX_LENGTH),
hash_obj,
)
except InvalidSignature as exc:
raise TPMAttestationError("TPM signature verification failed") from exc
return
if sig_alg == TPM2_ALG_ECDSA:
from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature
r_int = int.from_bytes(r.raw(r.u16()), "big")
s_int = int.from_bytes(r.raw(r.u16()), "big")
try:
crypto_key.verify(encode_dss_signature(r_int, s_int), data, ec.ECDSA(hash_obj))
except InvalidSignature as exc:
raise TPMAttestationError("ECDSA signature verification failed") from exc
return
raise TPMAttestationError(f"Unsupported signature algorithm: {sig_alg:#06x}")
def _verify_microsoft_key_attestation_signature(data: bytes, signature: bytes, aik_pub: TPMPublicKey):
"""Verify the MS-WCCE keyAttestation signature.
MS-WCCE stores the keyAttestation.signature field as an opaque signature
byte array, not as a marshalled TPMT_SIGNATURE in all Windows outputs.
First accept TPMT_SIGNATURE for compatibility, then fall back to raw
signatures produced by the Microsoft Platform Crypto Provider.
"""
try:
_verify_tpm_signature(data, signature, aik_pub)
return
except Exception as first_error:
last_error = first_error
crypto_key = aik_pub.to_cryptography_public_key()
hash_algs = []
if aik_pub.name_alg in (TPM2_ALG_SHA1, TPM2_ALG_SHA256, TPM2_ALG_SHA384, TPM2_ALG_SHA512):
hash_algs.append(_tpm_alg_to_hash_obj(aik_pub.name_alg))
for alg in (TPM2_ALG_SHA256, TPM2_ALG_SHA384, TPM2_ALG_SHA512, TPM2_ALG_SHA1):
obj = _tpm_alg_to_hash_obj(alg)
if all(obj.name != existing.name for existing in hash_algs):
hash_algs.append(obj)
if aik_pub.alg_type == TPM2_ALG_RSA:
for hash_obj in hash_algs:
try:
crypto_key.verify(signature, data, padding.PKCS1v15(), hash_obj)
return
except Exception as exc:
last_error = exc
try:
crypto_key.verify(
signature,
data,
padding.PSS(mgf=padding.MGF1(hash_obj), salt_length=padding.PSS.MAX_LENGTH),
hash_obj,
)
return
except Exception as exc:
last_error = exc
if aik_pub.alg_type == TPM2_ALG_ECC:
from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature
# Some providers emit DER ECDSA directly.
for hash_obj in hash_algs:
try:
crypto_key.verify(signature, data, ec.ECDSA(hash_obj))
return
except Exception as exc:
last_error = exc
# Others emit fixed-width r||s.
if len(signature) % 2 == 0:
half = len(signature) // 2
der_sig = encode_dss_signature(
int.from_bytes(signature[:half], "big"),
int.from_bytes(signature[half:], "big"),
)
for hash_obj in hash_algs:
try:
crypto_key.verify(der_sig, data, ec.ECDSA(hash_obj))
return
except Exception as exc:
last_error = exc
raise TPMAttestationError("Microsoft keyAttestation signature verification failed") from last_error
def _check_aik_attributes(aik: TPMPublicKey):
required = (
TPMA_OBJECT_RESTRICTED
| TPMA_OBJECT_SIGN
| TPMA_OBJECT_FIXEDTPM
| TPMA_OBJECT_FIXEDPARENT
| TPMA_OBJECT_SENSITIVEDATAORIGIN
)
if aik.object_attr & required != required:
raise TPMAttestationError(
"AIK must have RESTRICTED|SIGN|FIXEDTPM|FIXEDPARENT|"
f"SENSITIVEDATAORIGIN attributes set. Got TPMA_OBJECT={aik.object_attr:#010x}"
)
if aik.object_attr & TPMA_OBJECT_DECRYPT:
raise TPMAttestationError("AIK must NOT have the DECRYPT attribute (it must be a signing-only key)")
def tpm_object_attributes_to_dict(object_attr: int) -> dict:
"""Return user-facing TPMA_OBJECT flags for callback policy decisions."""
return {
"raw": int(object_attr),
"raw_hex": f"{object_attr:#010x}",
"fixed_tpm": bool(object_attr & TPMA_OBJECT_FIXEDTPM),
"fixed_parent": bool(object_attr & TPMA_OBJECT_FIXEDPARENT),
"sensitive_data_origin": bool(object_attr & TPMA_OBJECT_SENSITIVEDATAORIGIN),
"user_with_auth": bool(object_attr & TPMA_OBJECT_USERWITHAUTH),
"admin_with_policy": bool(object_attr & TPMA_OBJECT_ADMINWITHPOLICY),
"no_da": bool(object_attr & TPMA_OBJECT_NODA),
"restricted": bool(object_attr & TPMA_OBJECT_RESTRICTED),
"decrypt": bool(object_attr & TPMA_OBJECT_DECRYPT),
"sign_encrypt": bool(object_attr & TPMA_OBJECT_SIGN),
}
def _check_key_policy(
key: TPMPublicKey,
require_fixed_tpm: bool,
require_fixed_parent: bool,
require_restricted: bool,
require_sensitive_data_origin: bool = True,
):
errors = []
if require_fixed_tpm and not (key.object_attr & TPMA_OBJECT_FIXEDTPM):
errors.append("FIXEDTPM not set")
if require_fixed_parent and not (key.object_attr & TPMA_OBJECT_FIXEDPARENT):
errors.append("FIXEDPARENT not set")
if require_sensitive_data_origin and not (key.object_attr & TPMA_OBJECT_SENSITIVEDATAORIGIN):
errors.append("SENSITIVEDATAORIGIN not set")
if require_restricted and not (key.object_attr & TPMA_OBJECT_RESTRICTED):
errors.append("RESTRICTED not set")
if errors:
raise TPMAttestationError("Certified key does not meet policy: " + "; ".join(errors))
def _decode_any_string(value) -> Optional[str]:
try:
native = getattr(value, "native", None)
if isinstance(native, str):
return native
except Exception:
pass
try:
data = value.dump() if hasattr(value, "dump") else bytes(value)
except Exception:
return None
for typ in (a_core.BMPString, a_core.UTF8String, a_core.PrintableString, a_core.TeletexString):
try:
return typ.load(data).native
except Exception:
pass
for encoding in ("utf-16-le", "utf-16-be", "utf-8", "latin1"):
try:
return data.decode(encoding).rstrip("\x00")
except Exception:
pass
return None
def _load_private_key_from_pem(value, password=None):
if value is None:
raise ValueError("Missing PEM private key")
if isinstance(value, bytes):
data = value
elif isinstance(value, str):
data = value.encode("utf-8") if "-----BEGIN " in value else Path(value).read_bytes()
else:
raise TypeError(f"Unsupported private key input type: {type(value).__name__}")
if isinstance(password, str):
password = password.encode("utf-8")
return serialization.load_pem_private_key(data, password=password)
def _decrypt_cms_enveloped_data(content_info_der: bytes, recipient_cert_der: Optional[bytes], recipient_key) -> bytes:
def _unwrap(blob: bytes) -> bytes:
if not blob:
raise ValueError("Empty CMS blob")
if blob[0] == 0x30:
return blob
if blob[0] == 0x31:
class _AnySet(a_core.SetOf):
_child_spec = a_core.Any
values = _AnySet.load(blob)
if not values:
raise ValueError("Empty SET for CMS attribute value")
first = values[0]
if hasattr(first, "dump"):
return first.dump()
parsed = getattr(first, "parsed", None)
if parsed is not None and hasattr(parsed, "dump"):
return parsed.dump()
raise ValueError("Could not unwrap CMS ContentInfo from SET")
raise ValueError(f"Unsupported CMS wrapper tag: 0x{blob[0]:02x}")
def _hash_from_name_or_oid(value):
mapping = {
"sha1": hashes.SHA1(),
"sha224": hashes.SHA224(),
"sha256": hashes.SHA256(),
"sha384": hashes.SHA384(),
"sha512": hashes.SHA512(),
"1.3.14.3.2.26": hashes.SHA1(),
"2.16.840.1.101.3.4.2.4": hashes.SHA224(),
"2.16.840.1.101.3.4.2.1": hashes.SHA256(),
"2.16.840.1.101.3.4.2.2": hashes.SHA384(),
"2.16.840.1.101.3.4.2.3": hashes.SHA512(),
}
if value not in mapping:
raise NotImplementedError(f"Unsupported OAEP hash algorithm: {value}")
return mapping[value]
ci = a_cms.ContentInfo.load(_unwrap(content_info_der))
if ci["content_type"].native != "enveloped_data":
raise ValueError("Expected CMS EnvelopedData")
env = ci["content"]
eci = env["encrypted_content_info"]
enc_alg = eci["content_encryption_algorithm"]
enc_name = enc_alg["algorithm"].native
enc_params = enc_alg["parameters"]
encrypted_content = eci["encrypted_content"].native
if encrypted_content is None:
raise ValueError("CMS EnvelopedData has no encrypted content")
recipient_serial = None
if recipient_cert_der:
recipient_serial = x509.load_der_x509_certificate(recipient_cert_der).serial_number
cek = None
for ri in env["recipient_infos"]:
if ri.name != "ktri":
continue
ktri = ri.chosen
rid = ktri["rid"]
if rid.name != "issuer_and_serial_number":
continue
serial = int(rid.chosen["serial_number"].native)
if recipient_serial is not None and serial != recipient_serial:
continue
key_alg_field = ktri["key_encryption_algorithm"]["algorithm"]
key_alg = getattr(key_alg_field, "dotted", None) or key_alg_field.native
encrypted_key = ktri["encrypted_key"].native
if key_alg in ("rsa", "rsaes_pkcs1v15", "1.2.840.113549.1.1.1"):
raise ValueError("Insecure CMS key transport algorithm RSAES-PKCS1-v1_5 is not accepted")
elif key_alg in ("rsaes_oaep", "1.2.840.113549.1.1.7"):
oaep_params = ktri["key_encryption_algorithm"]["parameters"]
hash_alg = hashes.SHA1()
mgf_hash_alg = hashes.SHA1()
label = None
if oaep_params is not None:
native = oaep_params.native or {}
hash_info = native.get("hash_algorithm") if isinstance(native, dict) else None
if hash_info and hash_info.get("algorithm"):
hash_alg = _hash_from_name_or_oid(hash_info["algorithm"])
mgf_info = native.get("mask_gen_algorithm") if isinstance(native, dict) else None
if mgf_info:
mgf_params = mgf_info.get("parameters")
if mgf_params and mgf_params.get("algorithm"):
mgf_hash_alg = _hash_from_name_or_oid(mgf_params["algorithm"])
p_source = native.get("p_source_algorithm") if isinstance(native, dict) else None
if p_source:
psrc_params = p_source.get("parameters")
if isinstance(psrc_params, bytes) and psrc_params:
label = psrc_params
cek = recipient_key.decrypt(
encrypted_key,
padding.OAEP(mgf=padding.MGF1(mgf_hash_alg), algorithm=hash_alg, label=label),
)
else:
raise ValueError(f"Unsupported CMS key encryption algorithm: {key_alg}")
break
if cek is None:
raise ValueError("Could not decrypt CMS EnvelopedData with provided KET certificate/private key")
params = enc_params.native if enc_params is not None else None
if enc_name in ("aes128_cbc", "aes192_cbc", "aes256_cbc"):
cipher = Cipher(algorithms.AES(cek), modes.CBC(params))
elif enc_name == "tripledes_3key":
raise ValueError("Insecure CMS content encryption algorithm 3DES is not accepted")
else:
raise ValueError(f"Unsupported CMS content encryption algorithm: {enc_name}")
dec = cipher.decryptor()
padded = dec.update(encrypted_content) + dec.finalize()
unpadder = sym_padding.PKCS7(cipher.algorithm.block_size).unpadder()
return unpadder.update(padded) + unpadder.finalize()
def _find_der_certificates_in_blob(blob: bytes) -> list[bytes]:
certs = []
i = 0
while i < len(blob) - 4:
if blob[i] != 0x30:
i += 1
continue
first_len = blob[i + 1]
header_len = 2
if first_len & 0x80:
num_len = first_len & 0x7F
if num_len == 0 or i + 2 + num_len > len(blob):
i += 1
continue
total_len = int.from_bytes(blob[i + 2:i + 2 + num_len], "big")
header_len = 2 + num_len
else:
total_len = first_len
end = i + header_len + total_len
if end > len(blob):
i += 1
continue
candidate = blob[i:end]
try:
x509.load_der_x509_certificate(candidate)
certs.append(candidate)
i = end
except Exception:
i += 1
return certs
def decrypt_microsoft_ek_info(ek_info_raw: bytes, ket_cert_der: Optional[bytes], ket_private_key) -> dict:
if not ek_info_raw:
raise ValueError("ek_info_raw is empty")
value = a_core.Any.load(ek_info_raw)
content_info_der = None
for candidate in (getattr(value, "parsed", None), value):
if candidate is None:
continue
try:
items = list(candidate)
if items:
first = items[0]
content_info_der = first.dump() if hasattr(first, "dump") else bytes(first)
break
except Exception:
pass
try:
content_info_der = candidate.dump() if hasattr(candidate, "dump") else bytes(candidate)
break
except Exception:
pass
if content_info_der is None:
raise ValueError("Could not locate CMS EnvelopedData in ek_info_raw")
decrypted = _decrypt_cms_enveloped_data(content_info_der, ket_cert_der, ket_private_key)
certs = _find_der_certificates_in_blob(decrypted)
return {
"decrypted_raw": decrypted,
"ek_cert_der": certs[0] if certs else None,
"embedded_certificates_der": certs,
}
def extract_microsoft_key_attestation_attributes_from_csr_der(csr_der: bytes) -> Optional[dict]:
req = a_csr.CertificationRequest.load(csr_der)
interesting = {
OID_MS_ENROLL_EK_INFO,
OID_MS_ENROLL_AIK_INFO,
OID_MS_ENROLL_KSP_NAME,
OID_MS_ENROLL_ATTESTATION_STATEMENT,
OID_MS_ENROLL_ATTESTATION_STATEMENT_LEGACY,
}
def _extract_first_attribute_value(values_field):
try:
return values_field[0]
except Exception:
pass
parsed = getattr(values_field, "parsed", None)
if parsed is not None:
try:
return parsed[0]
except Exception:
pass
try:
return list(values_field)[0]
except Exception:
return values_field
def _raw_bytes(value_obj):
try:
if isinstance(value_obj, a_core.OctetString):
return bytes(value_obj.native)
except Exception:
pass
try:
return value_obj.dump()
except Exception:
pass
try:
return bytes(value_obj)
except Exception:
pass
try:
native = getattr(value_obj, "native", None)
if isinstance(native, bytes):
return native
except Exception:
pass
return None
result = {
"ek_info_raw": None,
"aik_info_raw": None,
"attestation_statement_raw": None,
"attestation_blob_raw": None,
"ksp_name": None,
"ksp_name_raw": None,
"found": False,
}
for attr in req["certification_request_info"]["attributes"]:
try:
oid = attr["type"].dotted
except Exception:
continue
if oid not in interesting:
continue
value_obj = _extract_first_attribute_value(attr["values"])
raw = _raw_bytes(value_obj)
if raw is None:
continue
if oid == OID_MS_ENROLL_EK_INFO:
result["ek_info_raw"] = raw
elif oid == OID_MS_ENROLL_AIK_INFO:
result["aik_info_raw"] = raw
elif oid == OID_MS_ENROLL_ATTESTATION_STATEMENT:
try:
result["attestation_statement_raw"] = a_core.OctetString.load(raw).native
except Exception:
result["attestation_statement_raw"] = raw
elif oid == OID_MS_ENROLL_ATTESTATION_STATEMENT_LEGACY:
try:
result["attestation_blob_raw"] = a_core.OctetString.load(raw).native
except Exception:
result["attestation_blob_raw"] = raw
elif oid == OID_MS_ENROLL_KSP_NAME:
result["ksp_name_raw"] = raw
result["ksp_name"] = _decode_any_string(value_obj)
result["found"] = True
return result if result["found"] else None
def extract_tpm_bundle_from_pkcs10_der(csr_der: bytes) -> Optional[TPMAttestationBundle]:
ms_attrs = extract_microsoft_key_attestation_attributes_from_csr_der(csr_der)
if ms_attrs is None:
return None
return TPMAttestationBundle(
ms_attestation_statement_raw=ms_attrs.get("attestation_statement_raw"),
ms_attestation_blob_raw=ms_attrs.get("attestation_blob_raw"),
ms_ek_info_raw=ms_attrs.get("ek_info_raw"),
ms_aik_info_raw=ms_attrs.get("aik_info_raw"),
ms_ksp_name=ms_attrs.get("ksp_name"),
ms_ksp_name_raw=ms_attrs.get("ksp_name_raw"),
)
def extract_tpm_bundle_from_cmc(p7_der: bytes) -> Optional[TPMAttestationBundle]:
from utils import exct_csr_from_cmc
csr_der, _body_part_id, _info = exct_csr_from_cmc(p7_der)
return extract_tpm_bundle_from_pkcs10_der(csr_der)
def pem_cert_to_der(cert_pem_text: str) -> bytes:
cert = x509.load_pem_x509_certificate(cert_pem_text.encode("utf-8"))
return cert.public_bytes(serialization.Encoding.DER)
def try_extract_first_cert_from_blob(blob: bytes) -> Optional[bytes]:
certs = _find_der_certificates_in_blob(blob)
return certs[0] if certs else None
def extract_ek_pub_from_decrypted_ek_info(
decrypted_ek_info: bytes,
*,
embedded_certificates_der=None,
ek_cert_der: Optional[bytes] = None,
):
class _AnySequence(a_core.SequenceOf):
_child_spec = a_core.Any
try:
seq = _AnySequence.load(decrypted_ek_info)
if seq:
first_der = seq[0].dump()
try:
return serialization.load_der_public_key(first_der)
except Exception:
pass
except Exception:
pass
cert_der = ek_cert_der
if cert_der is None and embedded_certificates_der:
for item in embedded_certificates_der:
if item:
cert_der = item
break
if cert_der is None:
cert_der = try_extract_first_cert_from_blob(decrypted_ek_info)
if cert_der is None:
raise ValueError("Could not locate an EK SubjectPublicKeyInfo or certificate inside decrypted EK_INFO")
return x509.load_der_x509_certificate(cert_der).public_key()
def _unwrap_first_set_value_der(blob: bytes) -> bytes:
if not blob:
raise ValueError("Empty DER blob")
if blob[0] == 0x30:
return blob
if blob[0] == 0x31:
class _AnySet(a_core.SetOf):
_child_spec = a_core.Any
values = _AnySet.load(blob)
if not values:
raise ValueError("Empty SET OF wrapper")
first = values[0]
if hasattr(first, "dump"):
return first.dump()
parsed = getattr(first, "parsed", None)
if parsed is not None and hasattr(parsed, "dump"):
return parsed.dump()
raise ValueError("Could not unwrap first value from SET OF")
raise ValueError(f"Unsupported DER wrapper tag 0x{blob[0]:02x}")
def extract_content_encryption_algorithm_oid_from_ek_info(ms_ek_info_raw: bytes) -> str:
ci = a_cms.ContentInfo.load(_unwrap_first_set_value_der(ms_ek_info_raw))
if ci["content_type"].native != "enveloped_data":
raise ValueError(f"Expected EnvelopedData in EK_INFO, got {ci['content_type'].native!r}")
return ci["content"]["encrypted_content_info"]["content_encryption_algorithm"]["algorithm"].dotted
def extract_encryption_algorithm_for_challenge_response(ms_ek_info_raw: bytes) -> str:
return extract_content_encryption_algorithm_oid_from_ek_info(ms_ek_info_raw)
class OrderedCertificateSet(a_cms.CertificateSet):
def _set_contents(self, force=False):
if self.children is None:
self._parse_children()
self._contents = b"".join(child.dump(force=force) for child in self)
self._header = None
if self._trailer != b"":
self._trailer = b""
class BodyPartID(a_core.Integer):
pass
class MsWrappedHeader(a_core.Sequence):
_fields = [("bodyPartID", BodyPartID)]
class MsWrappedAttr(a_core.Sequence):
_fields = [("oid", a_core.ObjectIdentifier), ("values", a_core.SetOf, {"spec": a_core.Any})]
class MsWrappedAttrs(a_core.SetOf):
_child_spec = MsWrappedAttr
class MsChallengeWrapper(a_core.Sequence):
_fields = [("version", a_core.Integer), ("header", MsWrappedHeader), ("attrs", MsWrappedAttrs)]
class TaggedAttribute(a_core.Sequence):
_fields = [("bodyPartID", BodyPartID), ("attrType", a_core.ObjectIdentifier), ("attrValues", a_core.SetOf, {"spec": a_core.Any})]
class TaggedAttributes(a_core.SequenceOf):
_child_spec = TaggedAttribute
class TaggedContentInfo(a_core.Sequence):
_fields = [("bodyPartID", BodyPartID), ("contentInfo", a_cms.ContentInfo)]
class TaggedContentInfos(a_core.SequenceOf):
_child_spec = TaggedContentInfo
class OtherMsgs(a_core.SequenceOf):
_child_spec = a_core.Any
class BodyList(a_core.SequenceOf):
_child_spec = a_core.Integer
class PendInfo(a_core.Sequence):
_fields = [("pendToken", a_core.OctetString), ("pendTime", a_core.GeneralizedTime)]
class CMCStatusInfo(a_core.Sequence):
_fields = [("cMCStatus", a_core.Integer), ("bodyList", BodyList), ("statusString", a_core.UTF8String), ("otherInfo", PendInfo)]
class ResponseBody(a_core.Sequence):
_fields = [("controlSequence", TaggedAttributes), ("cmsSequence", TaggedContentInfos), ("otherMsgSequence", OtherMsgs)]
def _as_any_from_der(der: bytes) -> a_core.Any:
return a_core.Any.load(der)
def build_cmc_pending_status_info(*, request_id: int, status_string: str = "En attente de traitement", pend_time=None, body_part_id: int = 1) -> bytes:
if pend_time is None:
pend_time = datetime.now(timezone.utc)
pend_time = pend_time.replace(microsecond=pend_time.microsecond // 1000 * 1000)
token_len = max(1, (int(request_id).bit_length() + 7) // 8)
value = CMCStatusInfo(
{
"cMCStatus": 3,
"bodyList": [body_part_id],
"statusString": status_string,
"otherInfo": {
"pendToken": int(request_id).to_bytes(token_len, byteorder="big", signed=False),
"pendTime": pend_time,
},
}
)
return value.dump()
def build_encryption_algorithm_attr_value(algorithm_oid: str) -> bytes:
return a_algos.AlgorithmIdentifier({"algorithm": algorithm_oid, "parameters": a_core.Null()}).dump()
def build_ms_challenge_wrapper_value(
*,
encryption_algorithm_oid: str,
aik_info_hash: bytes | None,
ksp_name: str,
tach_blob: bytes,
inner_body_part_id: int = 1,
) -> bytes:
attrs = [
MsWrappedAttr(
{
"oid": a_core.ObjectIdentifier(OID_ENROLL_ENCRYPTION_ALGORITHM),
"values": [_as_any_from_der(build_encryption_algorithm_attr_value(encryption_algorithm_oid))],
}
)
]
if aik_info_hash is not None:
attrs.append(
MsWrappedAttr(
{
"oid": a_core.ObjectIdentifier(OID_ENROLL_CAXCHGCERT_HASH),
"values": [_as_any_from_der(a_core.OctetString(aik_info_hash).dump())],
}
)
)
attrs.extend(
[
MsWrappedAttr(
{
"oid": a_core.ObjectIdentifier(OID_ENROLL_KSP_NAME),
"values": [_as_any_from_der(a_core.BMPString(ksp_name).dump())],
}
),
MsWrappedAttr(
{
"oid": a_core.ObjectIdentifier(OID_ENROLL_ATTESTATION_CHALLENGE),