Debian Codegraph @

addons/auth_passkey/_vendor/webauthn/registration/formats/tpm.py

raw symbols SCIP
1 from typing import List
2
3 import cbor2
4 from cryptography import x509
5 from cryptography.exceptions import InvalidSignature
6 from cryptography.hazmat.backends import default_backend
7 from cryptography.x509 import (
8 ExtendedKeyUsage,
9 GeneralName,
10 Name,
11 SubjectAlternativeName,
12 Version,
13 BasicConstraints,
14 )
15 from cryptography.x509.extensions import ExtensionNotFound
16 from cryptography.x509.oid import ExtensionOID
17
18 from ....webauthn.helpers import (
19 decode_credential_public_key,
20 hash_by_alg,
21 parse_cbor,
22 validate_certificate_chain,
23 verify_signature,
24 )
25 from ....webauthn.helpers.decode_credential_public_key import (
26 DecodedEC2PublicKey,
27 DecodedRSAPublicKey,
28 )
29 from ....webauthn.helpers.exceptions import (
30 InvalidCertificateChain,
31 InvalidRegistrationResponse,
32 )
33 from ....webauthn.helpers.structs import AttestationStatement
34 from ....webauthn.helpers.tpm import parse_cert_info, parse_pub_area
35 from ....webauthn.helpers.tpm.structs import (
36 TPM_ALG_COSE_ALG_MAP,
37 TPM_ECC_CURVE_COSE_CRV_MAP,
38 TPM_MANUFACTURERS,
39 TPMPubAreaParametersECC,
40 TPMPubAreaParametersRSA,
41 )
42
43
44 def verify_tpm(
45 *,
46 attestation_statement: AttestationStatement,
47 attestation_object: bytes,
48 client_data_json: bytes,
49 credential_public_key: bytes,
50 pem_root_certs_bytes: List[bytes],
51 ) -> bool:
52 """Verify a "tpm" attestation statement
53
54 See https://www.w3.org/TR/webauthn-2/#sctn-tpm-attestation
55 """
56 if not attestation_statement.cert_info:
57 raise InvalidRegistrationResponse("Attestation statement was missing certInfo (TPM)")
58
59 if not attestation_statement.pub_area:
60 raise InvalidRegistrationResponse("Attestation statement was missing pubArea (TPM)")
61
62 if not attestation_statement.alg:
63 raise InvalidRegistrationResponse("Attestation statement was missing alg (TPM)")
64
65 if not attestation_statement.x5c:
66 raise InvalidRegistrationResponse("Attestation statement was missing x5c (TPM)")
67
68 if not attestation_statement.sig:
69 raise InvalidRegistrationResponse("Attestation statement was missing sig (TPM)")
70
71 att_stmt_ver = attestation_statement.ver
72 if att_stmt_ver != "2.0":
73 raise InvalidRegistrationResponse(
74 f'Attestation statement ver "{att_stmt_ver}" was not "2.0" (TPM)'
75 )
76
77 # Validate the certificate chain
78 try:
79 validate_certificate_chain(
80 x5c=attestation_statement.x5c,
81 pem_root_certs_bytes=pem_root_certs_bytes,
82 )
83 except InvalidCertificateChain as err:
84 raise InvalidRegistrationResponse(f"{err} (TPM)")
85
86 # Verify that the public key specified by the parameters and unique fields of
87 # pubArea is identical to the credentialPublicKey in the attestedCredentialData
88 # in authenticatorData.
89 pub_area = parse_pub_area(attestation_statement.pub_area)
90 decoded_public_key = decode_credential_public_key(credential_public_key)
91
92 if isinstance(pub_area.parameters, TPMPubAreaParametersRSA):
93 if not isinstance(decoded_public_key, DecodedRSAPublicKey):
94 raise InvalidRegistrationResponse(
95 "Public key was not RSA key as indicated in pubArea (TPM)"
96 )
97
98 if pub_area.unique.value != decoded_public_key.n:
99 unique_hex = pub_area.unique.value.hex()
100 pub_key_n_hex = decoded_public_key.n.hex()
101 raise InvalidRegistrationResponse(
102 f'PubArea unique "{unique_hex}" was not same as public key modulus "{pub_key_n_hex}" (TPM)'
103 )
104
105 pub_area_exponent = int.from_bytes(pub_area.parameters.exponent, "big")
106 if pub_area_exponent == 0:
107 # "When zero, indicates that the exponent is the default of 2^16 + 1"
108 pub_area_exponent = 65537
109
110 pub_key_exponent = int.from_bytes(decoded_public_key.e, "big")
111
112 if pub_area_exponent != pub_key_exponent:
113 raise InvalidRegistrationResponse(
114 f'PubArea exponent "{pub_area_exponent}" was not same as public key exponent "{pub_key_exponent}" (TPM)'
115 )
116 elif isinstance(pub_area.parameters, TPMPubAreaParametersECC):
117 if not isinstance(decoded_public_key, DecodedEC2PublicKey):
118 raise InvalidRegistrationResponse(
119 "Public key was not ECC key as indicated in pubArea (TPM)"
120 )
121
122 pubKeyCoords = b"".join([decoded_public_key.x, decoded_public_key.y])
123 if pub_area.unique.value != pubKeyCoords:
124 unique_hex = pub_area.unique.value.hex()
125 pub_key_xy_hex = pubKeyCoords.hex()
126 raise InvalidRegistrationResponse(
127 f'Unique "{unique_hex}" was not same as public key [x,y] "{pub_key_xy_hex}" (TPM)'
128 )
129
130 pub_area_crv = TPM_ECC_CURVE_COSE_CRV_MAP[pub_area.parameters.curve_id]
131 if pub_area_crv != decoded_public_key.crv:
132 raise InvalidRegistrationResponse(
133 f'PubArea curve ID "{pub_area_crv}" was not same as public key crv "{decoded_public_key.crv}" (TPM)'
134 )
135 else:
136 pub_area_param_type = type(pub_area.parameters)
137 raise InvalidRegistrationResponse(
138 f'Unsupported pub_area.parameters "{pub_area_param_type}" (TPM)'
139 )
140
141 # Validate that certInfo is valid:
142 cert_info = parse_cert_info(attestation_statement.cert_info)
143
144 # Verify that magic is set to TPM_GENERATED_VALUE.
145 # a.k.a. 0xff544347
146 magic_int = int.from_bytes(cert_info.magic, "big")
147 if magic_int != int(0xFF544347):
148 raise InvalidRegistrationResponse(
149 f'CertInfo magic "{magic_int}" was not TPM_GENERATED_VALUE 4283712327 (0xff544347) (TPM)'
150 )
151
152 # Concatenate authenticatorData and clientDataHash to form attToBeSigned.
153 attestation_dict = parse_cbor(attestation_object)
154 authenticator_data_bytes: bytes = attestation_dict["authData"]
155 client_data_hash = hash_by_alg(client_data_json)
156 att_to_be_signed = b"".join(
157 [
158 authenticator_data_bytes,
159 client_data_hash,
160 ]
161 )
162
163 # Verify that extraData is set to the hash of attToBeSigned using the hash algorithm employed in "alg".
164 att_to_be_signed_hash = hash_by_alg(att_to_be_signed, attestation_statement.alg)
165 if cert_info.extra_data != att_to_be_signed_hash:
166 raise InvalidRegistrationResponse(
167 "PubArea extra data did not match hash of auth data and client data (TPM)"
168 )
169
170 # Verify that attested contains a TPMS_CERTIFY_INFO structure as specified in
171 # [TPMv2-Part2] section 10.12.3, whose name field contains a valid Name for
172 # pubArea, as computed using the algorithm in the nameAlg field of pubArea using
173 # the procedure specified in [TPMv2-Part1] section 16.
174 pub_area_hash = hash_by_alg(
175 attestation_statement.pub_area,
176 TPM_ALG_COSE_ALG_MAP[pub_area.name_alg],
177 )
178
179 attested_name = b"".join(
180 [
181 cert_info.attested.name_alg_bytes,
182 pub_area_hash,
183 ]
184 )
185
186 if attested_name != cert_info.attested.name:
187 raise InvalidRegistrationResponse(
188 "CertInfo attested name did not match PubArea hash (TPM)"
189 )
190
191 # Verify the sig is a valid signature over certInfo using the attestation
192 # public key in aikCert with the algorithm specified in alg.
193 attestation_cert_bytes = attestation_statement.x5c[0]
194 attestation_cert = x509.load_der_x509_certificate(attestation_cert_bytes, default_backend())
195 attestation_cert_pub_key = attestation_cert.public_key()
196
197 try:
198 verify_signature(
199 public_key=attestation_cert_pub_key,
200 signature_alg=attestation_statement.alg,
201 signature=attestation_statement.sig,
202 data=attestation_statement.cert_info,
203 )
204 except InvalidSignature:
205 raise InvalidRegistrationResponse("Could not verify attestation statement signature (TPM)")
206
207 # Verify that aikCert meets the requirements in § 8.3.1 TPM Attestation Statement
208 # Certificate Requirements.
209 # https://w3c.github.io/webauthn/#sctn-tpm-cert-requirements
210
211 # Version MUST be set to 3.
212 if attestation_cert.version != Version.v3:
213 raise InvalidRegistrationResponse(
214 f'Certificate Version "{attestation_cert.version}" was not "{Version.v3}"" Constraints CA was not False (TPM)'
215 )
216
217 # Subject field MUST be set to empty.
218 if len(attestation_cert.subject) > 0:
219 raise InvalidRegistrationResponse(
220 f'Certificate Subject "{attestation_cert.subject}" was not empty (TPM)'
221 )
222
223 # Start extensions analysis
224 cert_extensions = attestation_cert.extensions
225
226 # The Subject Alternative Name extension MUST be set as defined in
227 # [TPMv2-EK-Profile] section 3.2.9.
228 try:
229 # Ignore mypy because we're casting to a known type
230 ext_subject_alt_name: SubjectAlternativeName = cert_extensions.get_extension_for_oid(
231 ExtensionOID.SUBJECT_ALTERNATIVE_NAME
232 ).value # type: ignore[assignment]
233 except ExtensionNotFound:
234 raise InvalidRegistrationResponse(
235 f"Certificate missing extension {ExtensionOID.SUBJECT_ALTERNATIVE_NAME} (TPM)"
236 )
237
238 # `type(tcg_at_tpm_values)` return "<class 'cryptography.x509.name.Name'>" so ignore mypy
239 tcg_at_tpm_values: Name = ext_subject_alt_name.get_values_for_type(GeneralName)[0] # type: ignore[arg-type, assignment]
240 tcg_at_tpm_manufacturer = None
241 tcg_at_tpm_model = None
242 tcg_at_tpm_version = None
243 for obj in tcg_at_tpm_values:
244 oid = obj.oid.dotted_string
245 if oid == "2.23.133.2.1":
246 tcg_at_tpm_manufacturer = str(obj.value)
247 elif oid == "2.23.133.2.2":
248 tcg_at_tpm_model = obj.value
249 elif oid == "2.23.133.2.3":
250 tcg_at_tpm_version = obj.value
251
252 if not tcg_at_tpm_manufacturer or not tcg_at_tpm_model or not tcg_at_tpm_version:
253 raise InvalidRegistrationResponse(
254 f"Certificate Subject Alt Name was invalid value {tcg_at_tpm_values} (TPM)",
255 )
256
257 try:
258 TPM_MANUFACTURERS[tcg_at_tpm_manufacturer]
259 except KeyError:
260 raise InvalidRegistrationResponse(
261 f'Unrecognized TPM Manufacturer "{tcg_at_tpm_manufacturer}" (TPM)'
262 )
263
264 # The Extended Key Usage extension MUST contain the OID 2.23.133.8.3
265 # ("joint-iso-itu-t(2) internationalorganizations(23) 133 tcg-kp(8)
266 # tcg-kp-AIKCertificate(3)").
267 try:
268 # Ignore mypy because we're casting to a known type
269 ext_extended_key_usage: ExtendedKeyUsage = cert_extensions.get_extension_for_oid(
270 ExtensionOID.EXTENDED_KEY_USAGE
271 ).value # type: ignore[assignment]
272 except ExtensionNotFound:
273 raise InvalidRegistrationResponse(
274 f"Certificate missing extension {ExtensionOID.EXTENDED_KEY_USAGE} (TPM)"
275 )
276
277 ext_key_usage_oid = ext_extended_key_usage[0].dotted_string
278
279 if ext_key_usage_oid != "2.23.133.8.3":
280 raise InvalidRegistrationResponse(
281 f'Certificate Extended Key Usage OID "{ext_key_usage_oid}" was not "2.23.133.8.3" (TPM)'
282 )
283
284 try:
285 # Ignore mypy because we're casting to a known type
286 ext_basic_constraints: BasicConstraints = cert_extensions.get_extension_for_oid(
287 ExtensionOID.BASIC_CONSTRAINTS
288 ).value # type: ignore[assignment]
289 except ExtensionNotFound:
290 raise InvalidRegistrationResponse(
291 f"Certificate missing extension {ExtensionOID.BASIC_CONSTRAINTS} (TPM)"
292 )
293
294 # The Basic Constraints extension MUST have the CA component set to false.
295 if ext_basic_constraints.ca is not False:
296 raise InvalidRegistrationResponse("Certificate Basic Constraints CA was not False (TPM)")
297
298 # If aikCert contains an extension with OID 1.3.6.1.4.1.45724.1.1.4
299 # (id-fido-gen-ce-aaguid) verify that the value of this extension matches the
300 # aaguid in authenticatorData.
301 # TODO: Implement this later if we can find a TPM that returns something here
302 # try:
303 # fido_gen_ce_aaguid = cert_extensions.get_extension_for_oid(
304 # ObjectIdentifier("1.3.6.1.4.1.45724.1.1.4")
305 # )
306 # except ExtensionNotFound:
307 # pass
308
309 return True