Debian Codegraph @

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

raw symbols SCIP
1 import base64
2 from dataclasses import dataclass
3 import hashlib
4 import json
5 from typing import List
6
7 from cryptography import x509
8 from cryptography.exceptions import InvalidSignature
9 from cryptography.hazmat.backends import default_backend
10 from cryptography.x509.oid import NameOID
11
12 from ....webauthn.helpers.cose import COSEAlgorithmIdentifier
13 from ....webauthn.helpers import (
14 base64url_to_bytes,
15 parse_cbor,
16 validate_certificate_chain,
17 verify_safetynet_timestamp,
18 verify_signature,
19 )
20 from ....webauthn.helpers.exceptions import (
21 InvalidCertificateChain,
22 InvalidRegistrationResponse,
23 )
24 from ....webauthn.helpers.known_root_certs import globalsign_r2, globalsign_root_ca
25 from ....webauthn.helpers.structs import AttestationStatement
26
27
28 @dataclass
29 class SafetyNetJWSHeader:
30 """Properties in the Header of a SafetyNet JWS"""
31
32 alg: str
33 x5c: List[str]
34
35
36 @dataclass
37 class SafetyNetJWSPayload:
38 """Properties in the Payload of a SafetyNet JWS
39
40 Values below correspond to camelCased properties in the JWS itself. This class
41 handles converting the properties to Pythonic snake_case.
42 """
43
44 nonce: str
45 timestamp_ms: int
46 apk_package_name: str
47 apk_digest_sha256: str
48 cts_profile_match: bool
49 apk_certificate_digest_sha256: List[str]
50 basic_integrity: bool
51
52
53 def verify_android_safetynet(
54 *,
55 attestation_statement: AttestationStatement,
56 attestation_object: bytes,
57 client_data_json: bytes,
58 pem_root_certs_bytes: List[bytes],
59 verify_timestamp_ms: bool = True,
60 ) -> bool:
61 """Verify an "android-safetynet" attestation statement
62
63 See https://www.w3.org/TR/webauthn-2/#sctn-android-safetynet-attestation
64
65 Notes:
66 - `verify_timestamp_ms` is a kind of escape hatch specifically for enabling
67 testing of this method. Without this we can't use static responses in unit
68 tests because they'll always evaluate as expired. This flag can be removed
69 from this method if we ever figure out how to dynamically create
70 safetynet-formatted responses that can be immediately tested.
71 """
72
73 if not attestation_statement.ver:
74 # As of this writing, there is only one format of the SafetyNet response and
75 # ver is reserved for future use (so for now just make sure it's present)
76 raise InvalidRegistrationResponse("Attestation statement was missing version (SafetyNet)")
77
78 if not attestation_statement.response:
79 raise InvalidRegistrationResponse("Attestation statement was missing response (SafetyNet)")
80
81 # Begin peeling apart the JWS in the attestation statement response
82 jws = attestation_statement.response.decode("ascii")
83 jws_parts = jws.split(".")
84
85 if len(jws_parts) != 3:
86 raise InvalidRegistrationResponse("Response JWS did not have three parts (SafetyNet)")
87
88 header_json = json.loads(base64url_to_bytes(jws_parts[0]))
89 payload_json = json.loads(base64url_to_bytes(jws_parts[1]))
90
91 header = SafetyNetJWSHeader(
92 alg=header_json.get("alg", ""),
93 x5c=header_json.get("x5c", []),
94 )
95 payload = SafetyNetJWSPayload(
96 nonce=payload_json.get("nonce", ""),
97 timestamp_ms=payload_json.get("timestampMs", 0),
98 apk_package_name=payload_json.get("apkPackageName", ""),
99 apk_digest_sha256=payload_json.get("apkDigestSha256", ""),
100 cts_profile_match=payload_json.get("ctsProfileMatch", False),
101 apk_certificate_digest_sha256=payload_json.get("apkCertificateDigestSha256", []),
102 basic_integrity=payload_json.get("basicIntegrity", False),
103 )
104
105 signature_bytes_str: str = jws_parts[2]
106
107 # Verify that the nonce attribute in the payload of response is identical to the
108 # Base64 encoding of the SHA-256 hash of the concatenation of authenticatorData and
109 # clientDataHash.
110
111 # Extract attStmt bytes from attestation_object
112 attestation_dict = parse_cbor(attestation_object)
113 authenticator_data_bytes = attestation_dict["authData"]
114
115 # Generate a hash of client_data_json
116 client_data_hash = hashlib.sha256()
117 client_data_hash.update(client_data_json)
118 client_data_hash_bytes = client_data_hash.digest()
119
120 nonce_data = b"".join(
121 [
122 authenticator_data_bytes,
123 client_data_hash_bytes,
124 ]
125 )
126 # Start with a sha256 hash
127 nonce_data_hash = hashlib.sha256()
128 nonce_data_hash.update(nonce_data)
129 nonce_data_hash_bytes = nonce_data_hash.digest()
130 # Encode to base64
131 nonce_data_hash_bytes = base64.b64encode(nonce_data_hash_bytes)
132 # Finish by decoding to string
133 nonce_data_str = nonce_data_hash_bytes.decode("utf-8")
134
135 if payload.nonce != nonce_data_str:
136 raise InvalidRegistrationResponse("Payload nonce was not expected value (SafetyNet)")
137
138 # Verify that the SafetyNet response actually came from the SafetyNet service
139 # by following the steps in the SafetyNet online documentation.
140 x5c = [base64url_to_bytes(cert) for cert in header.x5c]
141
142 if not payload.cts_profile_match:
143 raise InvalidRegistrationResponse("Could not verify device integrity (SafetyNet)")
144
145 if verify_timestamp_ms:
146 try:
147 verify_safetynet_timestamp(payload.timestamp_ms)
148 except ValueError as err:
149 raise InvalidRegistrationResponse(f"{err} (SafetyNet)")
150
151 # Verify that the leaf certificate was issued to the hostname attest.android.com
152 attestation_cert = x509.load_der_x509_certificate(x5c[0], default_backend())
153 cert_common_name = attestation_cert.subject.get_attributes_for_oid(
154 NameOID.COMMON_NAME,
155 )[0]
156
157 if cert_common_name.value != "attest.android.com":
158 raise InvalidRegistrationResponse(
159 'Certificate common name was not "attest.android.com" (SafetyNet)'
160 )
161
162 # Validate certificate chain
163 try:
164 # Include known root certificates for this attestation format with whatever
165 # other certs were provided
166 pem_root_certs_bytes.append(globalsign_r2)
167 pem_root_certs_bytes.append(globalsign_root_ca)
168
169 validate_certificate_chain(
170 x5c=x5c,
171 pem_root_certs_bytes=pem_root_certs_bytes,
172 )
173 except InvalidCertificateChain as err:
174 raise InvalidRegistrationResponse(f"{err} (SafetyNet)")
175
176 # Verify signature
177 verification_data = f"{jws_parts[0]}.{jws_parts[1]}".encode("utf-8")
178 signature_bytes = base64url_to_bytes(signature_bytes_str)
179
180 if header.alg != "RS256":
181 raise InvalidRegistrationResponse(f"JWS header alg was not RS256: {header.alg} (SafetyNet")
182
183 # Get cert public key bytes
184 attestation_cert_pub_key = attestation_cert.public_key()
185
186 try:
187 verify_signature(
188 public_key=attestation_cert_pub_key,
189 signature_alg=COSEAlgorithmIdentifier.RSASSA_PKCS1_v1_5_SHA_256,
190 signature=signature_bytes,
191 data=verification_data,
192 )
193 except InvalidSignature:
194 raise InvalidRegistrationResponse(
195 "Could not verify attestation statement signature (Packed)"
196 )
197
198 return True