Debian Codegraph @

addons/auth_passkey/_vendor/webauthn/registration/verify_registration_response.py

raw symbols SCIP
1 import hashlib
2 from dataclasses import dataclass, asdict
3 from typing import List, Mapping, Optional, Union
4
5 from ...webauthn.helpers import (
6 aaguid_to_string,
7 bytes_to_base64url,
8 byteslike_to_bytes,
9 decode_credential_public_key,
10 parse_attestation_object,
11 parse_client_data_json,
12 parse_backup_flags,
13 parse_registration_credential_json,
14 )
15 from ...webauthn.helpers.cose import COSEAlgorithmIdentifier
16 from ...webauthn.helpers.exceptions import InvalidRegistrationResponse
17 from ...webauthn.helpers.structs import (
18 AttestationFormat,
19 ClientDataType,
20 CredentialDeviceType,
21 PublicKeyCredentialType,
22 RegistrationCredential,
23 TokenBindingStatus,
24 )
25 from .formats.android_key import verify_android_key
26 from .formats.android_safetynet import verify_android_safetynet
27 from .formats.apple import verify_apple
28 from .formats.fido_u2f import verify_fido_u2f
29 from .formats.packed import verify_packed
30 from .formats.tpm import verify_tpm
31 from .generate_registration_options import default_supported_pub_key_algs
32
33
34 @dataclass
35 class VerifiedRegistration:
36 """Information about a verified attestation of which an RP can make use.
37
38 Attributes:
39 `credential_id`: The generated credential's ID
40 `credential_public_key`: The generated credential's public key
41 `sign_count`: How many times the authenticator says the credential was used
42 `aaguid`: A 128-bit identifier indicating the type and vendor of the authenticator
43 `fmt`: The attestation format
44 `credential_type`: The literal string "public-key"
45 `user_verified`: Whether the user was verified by the authenticator
46 `attestation_object`: The raw attestation object for later scrutiny
47 """
48
49 credential_id: bytes
50 credential_public_key: bytes
51 sign_count: int
52 aaguid: str
53 fmt: AttestationFormat
54 credential_type: PublicKeyCredentialType
55 user_verified: bool
56 attestation_object: bytes
57 credential_device_type: CredentialDeviceType
58 credential_backed_up: bool
59
60
61 expected_token_binding_statuses = [
62 TokenBindingStatus.SUPPORTED,
63 TokenBindingStatus.PRESENT,
64 ]
65
66
67 def verify_registration_response(
68 *,
69 credential: Union[str, dict, RegistrationCredential],
70 expected_challenge: bytes,
71 expected_rp_id: str,
72 expected_origin: Union[str, List[str]],
73 require_user_verification: bool = False,
74 supported_pub_key_algs: List[COSEAlgorithmIdentifier] = default_supported_pub_key_algs,
75 pem_root_certs_bytes_by_fmt: Optional[Mapping[AttestationFormat, List[bytes]]] = None,
76 ) -> VerifiedRegistration:
77 """Verify an authenticator's response to navigator.credentials.create()
78
79 Args:
80 - `credential`: The value returned from `navigator.credentials.create()`. Can be either a
81 stringified JSON object, a plain dict, or an instance of RegistrationCredential
82 - `expected_challenge`: The challenge passed to the authenticator within the preceding
83 registration options.
84 - `expected_rp_id`: The Relying Party's unique identifier as specified in the precending
85 registration options.
86 - `expected_origin`: The domain, with HTTP protocol (e.g. "https://domain.here"), on which
87 the registration should have occurred. Can also be a list of expected origins.
88 - (optional) `require_user_verification`: Whether or not to require that the authenticator
89 verified the user.
90 - (optional) `supported_pub_key_algs`: A list of public key algorithm IDs the RP chooses to
91 restrict support to. Defaults to all supported algorithm IDs.
92 - (optional) `pem_root_certs_bytes_by_fmt`: A list of root certificates, in PEM format, to
93 be used to validate the certificate chains for specific attestation statement formats.
94
95 Returns:
96 Information about the authenticator and registration
97
98 Raises:
99 `helpers.exceptions.InvalidRegistrationResponse` if the response cannot be verified
100 """
101 if isinstance(credential, str) or isinstance(credential, dict):
102 credential = parse_registration_credential_json(credential)
103
104 verified = False
105
106 # FIDO-specific check
107 if bytes_to_base64url(credential.raw_id) != credential.id:
108 raise InvalidRegistrationResponse("id and raw_id were not equivalent")
109
110 # FIDO-specific check
111 if credential.type != PublicKeyCredentialType.PUBLIC_KEY:
112 raise InvalidRegistrationResponse(
113 f'Unexpected credential type "{credential.type}", expected "public-key"'
114 )
115
116 response = credential.response
117
118 client_data_bytes = byteslike_to_bytes(response.client_data_json)
119 attestation_object_bytes = byteslike_to_bytes(response.attestation_object)
120
121 client_data = parse_client_data_json(client_data_bytes)
122
123 if client_data.type != ClientDataType.WEBAUTHN_CREATE:
124 raise InvalidRegistrationResponse(
125 f'Unexpected client data type "{client_data.type}", expected "{ClientDataType.WEBAUTHN_CREATE}"'
126 )
127
128 if expected_challenge != client_data.challenge:
129 raise InvalidRegistrationResponse("Client data challenge was not expected challenge")
130
131 if isinstance(expected_origin, str):
132 if expected_origin != client_data.origin:
133 raise InvalidRegistrationResponse(
134 f'Unexpected client data origin "{client_data.origin}", expected "{expected_origin}"'
135 )
136 else:
137 try:
138 expected_origin.index(client_data.origin)
139 except ValueError:
140 raise InvalidRegistrationResponse(
141 f'Unexpected client data origin "{client_data.origin}", expected one of {expected_origin}'
142 )
143
144 if client_data.token_binding:
145 status = client_data.token_binding.status
146 if status not in expected_token_binding_statuses:
147 raise InvalidRegistrationResponse(
148 f'Unexpected token_binding status of "{status}", expected one of "{",".join(expected_token_binding_statuses)}"'
149 )
150
151 attestation_object = parse_attestation_object(attestation_object_bytes)
152
153 auth_data = attestation_object.auth_data
154
155 # Generate a hash of the expected RP ID for comparison
156 expected_rp_id_hash = hashlib.sha256()
157 expected_rp_id_hash.update(expected_rp_id.encode("utf-8"))
158 expected_rp_id_hash_bytes = expected_rp_id_hash.digest()
159
160 if auth_data.rp_id_hash != expected_rp_id_hash_bytes:
161 raise InvalidRegistrationResponse("Unexpected RP ID hash")
162
163 if not auth_data.flags.up:
164 raise InvalidRegistrationResponse("User was not present during attestation")
165
166 if require_user_verification and not auth_data.flags.uv:
167 raise InvalidRegistrationResponse(
168 "User verification is required but user was not verified during attestation"
169 )
170
171 if not auth_data.attested_credential_data:
172 raise InvalidRegistrationResponse("Authenticator did not provide attested credential data")
173
174 attested_credential_data = auth_data.attested_credential_data
175
176 if not attested_credential_data.credential_id:
177 raise InvalidRegistrationResponse("Authenticator did not provide a credential ID")
178
179 if not attested_credential_data.credential_public_key:
180 raise InvalidRegistrationResponse("Authenticator did not provide a credential public key")
181
182 if not attested_credential_data.aaguid:
183 raise InvalidRegistrationResponse("Authenticator did not provide an AAGUID")
184
185 decoded_credential_public_key = decode_credential_public_key(
186 attested_credential_data.credential_public_key
187 )
188
189 if decoded_credential_public_key.alg not in supported_pub_key_algs:
190 raise InvalidRegistrationResponse(
191 f'Unsupported credential public key alg "{decoded_credential_public_key.alg}", expected one of: {supported_pub_key_algs}'
192 )
193
194 # Prepare a list of possible root certificates for certificate chain validation
195 pem_root_certs_bytes: List[bytes] = []
196 if pem_root_certs_bytes_by_fmt:
197 custom_certs = pem_root_certs_bytes_by_fmt.get(attestation_object.fmt)
198 if custom_certs:
199 # Load any provided custom root certs
200 pem_root_certs_bytes.extend(custom_certs)
201
202 if attestation_object.fmt == AttestationFormat.NONE:
203 # A "none" attestation should not contain _anything_ in its attestation statement
204 any_att_stmt_fields_set = any(
205 [field is not None for field in asdict(attestation_object.att_stmt).values()]
206 )
207
208 if any_att_stmt_fields_set:
209 raise InvalidRegistrationResponse(
210 "None attestation had unexpected attestation statement"
211 )
212
213 # There's nothing else to verify, so mark the verification successful
214 verified = True
215 elif attestation_object.fmt == AttestationFormat.FIDO_U2F:
216 verified = verify_fido_u2f(
217 attestation_statement=attestation_object.att_stmt,
218 client_data_json=client_data_bytes,
219 rp_id_hash=auth_data.rp_id_hash,
220 credential_id=attested_credential_data.credential_id,
221 credential_public_key=attested_credential_data.credential_public_key,
222 aaguid=attested_credential_data.aaguid,
223 pem_root_certs_bytes=pem_root_certs_bytes,
224 )
225 elif attestation_object.fmt == AttestationFormat.PACKED:
226 verified = verify_packed(
227 attestation_statement=attestation_object.att_stmt,
228 attestation_object=attestation_object_bytes,
229 client_data_json=client_data_bytes,
230 credential_public_key=attested_credential_data.credential_public_key,
231 pem_root_certs_bytes=pem_root_certs_bytes,
232 )
233 elif attestation_object.fmt == AttestationFormat.TPM:
234 verified = verify_tpm(
235 attestation_statement=attestation_object.att_stmt,
236 attestation_object=attestation_object_bytes,
237 client_data_json=client_data_bytes,
238 credential_public_key=attested_credential_data.credential_public_key,
239 pem_root_certs_bytes=pem_root_certs_bytes,
240 )
241 elif attestation_object.fmt == AttestationFormat.APPLE:
242 verified = verify_apple(
243 attestation_statement=attestation_object.att_stmt,
244 attestation_object=attestation_object_bytes,
245 client_data_json=client_data_bytes,
246 credential_public_key=attested_credential_data.credential_public_key,
247 pem_root_certs_bytes=pem_root_certs_bytes,
248 )
249 elif attestation_object.fmt == AttestationFormat.ANDROID_SAFETYNET:
250 verified = verify_android_safetynet(
251 attestation_statement=attestation_object.att_stmt,
252 attestation_object=attestation_object_bytes,
253 client_data_json=client_data_bytes,
254 pem_root_certs_bytes=pem_root_certs_bytes,
255 )
256 elif attestation_object.fmt == AttestationFormat.ANDROID_KEY:
257 verified = verify_android_key(
258 attestation_statement=attestation_object.att_stmt,
259 attestation_object=attestation_object_bytes,
260 client_data_json=client_data_bytes,
261 credential_public_key=attested_credential_data.credential_public_key,
262 pem_root_certs_bytes=pem_root_certs_bytes,
263 )
264 else:
265 # Raise exception on an attestation format we're not prepared to verify
266 raise InvalidRegistrationResponse(
267 f'Unsupported attestation type "{attestation_object.fmt}"'
268 )
269
270 # If we got this far and still couldn't verify things then raise an error instead
271 # of simply returning False
272 if not verified:
273 raise InvalidRegistrationResponse("Attestation statement could not be verified")
274
275 parsed_backup_flags = parse_backup_flags(auth_data.flags)
276
277 return VerifiedRegistration(
278 credential_id=attested_credential_data.credential_id,
279 credential_public_key=attested_credential_data.credential_public_key,
280 sign_count=auth_data.sign_count,
281 aaguid=aaguid_to_string(attested_credential_data.aaguid),
282 fmt=attestation_object.fmt,
283 credential_type=credential.type,
284 user_verified=auth_data.flags.uv,
285 attestation_object=attestation_object_bytes,
286 credential_device_type=parsed_backup_flags.credential_device_type,
287 credential_backed_up=parsed_backup_flags.credential_backed_up,
288 )