pywarp 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pywarp/__init__.py ADDED
@@ -0,0 +1,22 @@
1
+ # mypy: implicit-reexport
2
+ """
3
+ See https://www.w3.org/TR/webauthn-3/#sctn-api
4
+ """
5
+
6
+ from .attestation import FIDOU2FAttestationStatement
7
+ from .credentials import Credential
8
+ from .exceptions import (
9
+ AttestationError,
10
+ AuthenticatorDataError,
11
+ CertificateTrustError,
12
+ ChallengeError,
13
+ ClientDataError,
14
+ CredentialError,
15
+ ExtensionVerificationError,
16
+ MetadataVerificationError,
17
+ SignatureVerificationError,
18
+ VerificationError,
19
+ )
20
+ from .prf import PRFInputs, PRFOutputs, PRFValues
21
+ from .rp import AuthenticationOptions, CredentialIdentity, RegistrationOptions, RelyingPartyManager
22
+ from .trust import CertificateTrust
pywarp/_cbor.py ADDED
@@ -0,0 +1,33 @@
1
+ """Decoder settings for WebAuthn's CTAP2 CBOR profile."""
2
+
3
+ from io import BytesIO
4
+ from typing import NoReturn
5
+
6
+ import cbor2
7
+
8
+ MAX_FIELD_BYTES = 64 * 1024
9
+ MAX_EXTENSION_BYTES = 16 * 1024
10
+ MAX_COSE_KEY_BYTES = 4 * 1024
11
+
12
+
13
+ class _RejectTags(dict[int, cbor2.SemanticDecoderCallback]):
14
+ def __missing__(self, tag: int) -> NoReturn:
15
+ # cbor2 consults this mapping before dispatching even its built-in tags.
16
+ raise cbor2.CBORDecodeError(f"CBOR tag {tag} is forbidden in WebAuthn")
17
+
18
+
19
+ def load_cbor(stream: BytesIO, *, max_bytes: int, max_depth: int = 4, string_keys_only: bool = False) -> object:
20
+ """Read one item within its byte budget, leaving any following item in the stream."""
21
+ start = stream.tell()
22
+ window = BytesIO(stream.read(max_bytes))
23
+ stream.seek(start)
24
+ value = cbor2.load(
25
+ window,
26
+ semantic_decoders=_RejectTags(),
27
+ max_depth=max_depth,
28
+ allow_duplicate_keys=False,
29
+ allow_indefinite=False,
30
+ strict_hashable_types=string_keys_only,
31
+ )
32
+ stream.seek(start + window.tell())
33
+ return value
pywarp/android.py ADDED
@@ -0,0 +1,155 @@
1
+ """Android key attestation certificate schema and WebAuthn §8.4 verification."""
2
+
3
+ from typing import Annotated
4
+
5
+ from cryptography import x509
6
+ from cryptography.hazmat import asn1
7
+
8
+ from .attestation import _decode_extension, certificate_path, verify_certificate_signature
9
+ from .authenticators import AuthenticatorData
10
+ from .credentials import Credential
11
+ from .exceptions import AttestationError
12
+ from .trust import CertificateTrust
13
+
14
+ _KEY_DESCRIPTION = x509.ObjectIdentifier("1.3.6.1.4.1.11129.2.1.17")
15
+
16
+
17
+ @asn1.sequence
18
+ class _RootOfTrust:
19
+ verified_boot_key: bytes
20
+ device_locked: bool
21
+ verified_boot_state: asn1.TLV
22
+ verified_boot_hash: bytes
23
+
24
+
25
+ # https://source.android.com/docs/security/features/keystore/attestation
26
+ @asn1.sequence
27
+ class _AuthorizationList:
28
+ purpose: Annotated[asn1.SetOf[int] | None, asn1.Explicit(1)] = None
29
+ algorithm: Annotated[int | None, asn1.Explicit(2)] = None
30
+ key_size: Annotated[int | None, asn1.Explicit(3)] = None
31
+ block_mode: Annotated[asn1.SetOf[int] | None, asn1.Explicit(4)] = None
32
+ digest: Annotated[asn1.SetOf[int] | None, asn1.Explicit(5)] = None
33
+ padding: Annotated[asn1.SetOf[int] | None, asn1.Explicit(6)] = None
34
+ caller_nonce: Annotated[asn1.Null | None, asn1.Explicit(7)] = None
35
+ min_mac_length: Annotated[int | None, asn1.Explicit(8)] = None
36
+ ec_curve: Annotated[int | None, asn1.Explicit(10)] = None
37
+ ml_dsa_variant: Annotated[int | None, asn1.Explicit(11)] = None
38
+ rsa_public_exponent: Annotated[int | None, asn1.Explicit(200)] = None
39
+ mgf_digest: Annotated[asn1.SetOf[int] | None, asn1.Explicit(203)] = None
40
+ rollback_resistance: Annotated[asn1.Null | None, asn1.Explicit(303)] = None
41
+ early_boot_only: Annotated[asn1.Null | None, asn1.Explicit(305)] = None
42
+ active_date_time: Annotated[int | None, asn1.Explicit(400)] = None
43
+ origination_expire_date_time: Annotated[int | None, asn1.Explicit(401)] = None
44
+ usage_expire_date_time: Annotated[int | None, asn1.Explicit(402)] = None
45
+ usage_count_limit: Annotated[int | None, asn1.Explicit(405)] = None
46
+ user_secure_id: Annotated[int | None, asn1.Explicit(502)] = None
47
+ no_auth_required: Annotated[asn1.Null | None, asn1.Explicit(503)] = None
48
+ user_auth_type: Annotated[int | None, asn1.Explicit(504)] = None
49
+ auth_timeout: Annotated[int | None, asn1.Explicit(505)] = None
50
+ allow_while_on_body: Annotated[asn1.Null | None, asn1.Explicit(506)] = None
51
+ trusted_user_presence_required: Annotated[asn1.Null | None, asn1.Explicit(507)] = None
52
+ trusted_confirmation_required: Annotated[asn1.Null | None, asn1.Explicit(508)] = None
53
+ unlocked_device_required: Annotated[asn1.Null | None, asn1.Explicit(509)] = None
54
+ all_applications: Annotated[asn1.Null | None, asn1.Explicit(600)] = None
55
+ application_id: Annotated[bytes | None, asn1.Explicit(601)] = None
56
+ creation_date_time: Annotated[int | None, asn1.Explicit(701)] = None
57
+ origin: Annotated[int | None, asn1.Explicit(702)] = None
58
+ root_of_trust: Annotated[_RootOfTrust | None, asn1.Explicit(704)] = None
59
+ os_version: Annotated[int | None, asn1.Explicit(705)] = None
60
+ os_patch_level: Annotated[int | None, asn1.Explicit(706)] = None
61
+ attestation_application_id: Annotated[bytes | None, asn1.Explicit(709)] = None
62
+ attestation_id_brand: Annotated[bytes | None, asn1.Explicit(710)] = None
63
+ attestation_id_device: Annotated[bytes | None, asn1.Explicit(711)] = None
64
+ attestation_id_product: Annotated[bytes | None, asn1.Explicit(712)] = None
65
+ attestation_id_serial: Annotated[bytes | None, asn1.Explicit(713)] = None
66
+ attestation_id_imei: Annotated[bytes | None, asn1.Explicit(714)] = None
67
+ attestation_id_meid: Annotated[bytes | None, asn1.Explicit(715)] = None
68
+ attestation_id_manufacturer: Annotated[bytes | None, asn1.Explicit(716)] = None
69
+ attestation_id_model: Annotated[bytes | None, asn1.Explicit(717)] = None
70
+ vendor_patch_level: Annotated[int | None, asn1.Explicit(718)] = None
71
+ boot_patch_level: Annotated[int | None, asn1.Explicit(719)] = None
72
+ device_unique_attestation: Annotated[asn1.Null | None, asn1.Explicit(720)] = None
73
+ attestation_id_second_imei: Annotated[bytes | None, asn1.Explicit(723)] = None
74
+ module_hash: Annotated[bytes | None, asn1.Explicit(724)] = None
75
+
76
+
77
+ @asn1.sequence
78
+ class _KeyDescription:
79
+ attestation_version: int
80
+ attestation_security_level: asn1.TLV
81
+ keymaster_version: int
82
+ keymaster_security_level: asn1.TLV
83
+ challenge: bytes
84
+ unique_id: bytes
85
+ software_enforced: _AuthorizationList
86
+ hardware_enforced: _AuthorizationList
87
+
88
+
89
+ def _validate_description(encoded: bytes, *, client_data_hash: bytes) -> None:
90
+ description = _decode_extension(_KeyDescription, data=encoded)
91
+ if description.challenge != client_data_hash:
92
+ raise AttestationError("Android attestation challenge differs from the client data hash")
93
+ # cryptography represents ASN.1 ENUMERATED using a TLV.
94
+ for level in (description.attestation_security_level, description.keymaster_security_level):
95
+ if level.tag_bytes != b"\x0a" or bytes(level.data) not in (b"\x00", b"\x01", b"\x02"):
96
+ raise AttestationError("Invalid Android attestation security level")
97
+ lists = (description.software_enforced, description.hardware_enforced)
98
+ for auth in lists:
99
+ if auth.all_applications is not None:
100
+ raise AttestationError("Android credential permits all applications")
101
+ if auth.root_of_trust is not None:
102
+ state = auth.root_of_trust.verified_boot_state
103
+ if state.tag_bytes != b"\x0a" or bytes(state.data) not in (b"\x00", b"\x01", b"\x02", b"\x03"):
104
+ raise AttestationError("Invalid Android verified boot state")
105
+ if {auth.origin for auth in lists if auth.origin is not None} != {0}:
106
+ raise AttestationError("Android credential was not generated by the keystore")
107
+ if {p for auth in lists if auth.purpose is not None for p in auth.purpose.as_list()} != {2}:
108
+ raise AttestationError("Android credential is not restricted to signing")
109
+
110
+
111
+ def verify_android_key(
112
+ statement: dict[str, object],
113
+ *,
114
+ auth_data: AuthenticatorData,
115
+ client_data_hash: bytes,
116
+ trust: CertificateTrust | None,
117
+ ) -> Credential:
118
+ credential = auth_data.credential
119
+ algorithm, signature = statement.get("alg"), statement.get("sig")
120
+ if (
121
+ trust is None
122
+ or credential is None
123
+ or statement.keys() != {"x5c", "alg", "sig"}
124
+ or type(algorithm) is not int
125
+ or not isinstance(signature, bytes)
126
+ ):
127
+ raise AttestationError("Invalid or untrusted Android key attestation")
128
+ chain = certificate_path(statement)
129
+ leaf = chain[0]
130
+ if leaf.public_key() != credential.public_key.cryptography_key:
131
+ raise AttestationError("Android attestation certificate differs from the credential public key")
132
+ verify_certificate_signature(
133
+ leaf, algorithm=algorithm, signature=signature, signed_data=auth_data.raw_auth_data + client_data_hash
134
+ )
135
+ verified_chain = trust.verify(chain)
136
+ # verify() checked the intermediates. Android requires a status check for every certificate.
137
+ if len(verified_chain) > 1:
138
+ trust._require_good_status(leaf, issuer=verified_chain[1])
139
+ root = verified_chain[-1]
140
+ trust._require_good_status(root, issuer=root)
141
+ # Only the first key description issued by the trusted attestation hierarchy is authoritative.
142
+ for issuer in verified_chain[1:]:
143
+ try:
144
+ issuer.extensions.get_extension_for_oid(_KEY_DESCRIPTION)
145
+ except x509.ExtensionNotFound:
146
+ continue
147
+ raise AttestationError("Android attestation is subordinate to an attested key")
148
+ try:
149
+ extension = leaf.extensions.get_extension_for_oid(_KEY_DESCRIPTION)
150
+ except x509.ExtensionNotFound as exc:
151
+ raise AttestationError("Missing Android key description") from exc
152
+ if not isinstance(extension.value, x509.UnrecognizedExtension):
153
+ raise AttestationError("Invalid Android key description")
154
+ _validate_description(extension.value.value, client_data_hash=client_data_hash)
155
+ return credential
pywarp/attestation.py ADDED
@@ -0,0 +1,178 @@
1
+ from dataclasses import dataclass
2
+ from typing import TypeVar
3
+
4
+ from cryptography import x509
5
+ from cryptography.hazmat import asn1
6
+ from cryptography.hazmat.primitives import hashes
7
+ from cryptography.hazmat.primitives.asymmetric import ec, ed448, ed25519, padding, rsa
8
+
9
+ from .authenticators import AuthenticatorData
10
+ from .cose import Algorithms, KeyTypes, MLDSAPublicKeyTypes
11
+ from .credentials import Credential
12
+ from .exceptions import AttestationError, _signature_errors
13
+ from .trust import CertificateTrust, _load_certificate
14
+
15
+ _FIDO_AAGUID_EXTENSION_OID = x509.ObjectIdentifier("1.3.6.1.4.1.45724.1.1.4")
16
+
17
+
18
+ @_signature_errors()
19
+ def verify_certificate_signature(
20
+ certificate: x509.Certificate, *, algorithm: int, signature: bytes, signed_data: bytes
21
+ ) -> None:
22
+ key = certificate.public_key()
23
+ ec_algorithms: dict[int, tuple[type[ec.EllipticCurve], type[hashes.HashAlgorithm]]] = {
24
+ -7: (ec.SECP256R1, hashes.SHA256),
25
+ -35: (ec.SECP384R1, hashes.SHA384),
26
+ -36: (ec.SECP521R1, hashes.SHA512),
27
+ }
28
+ if isinstance(key, ec.EllipticCurvePublicKey) and algorithm in ec_algorithms:
29
+ curve, digest = ec_algorithms[algorithm]
30
+ if not isinstance(key.curve, curve):
31
+ raise AttestationError("Attestation curve does not match the algorithm")
32
+ key.verify(signature, signed_data, ec.ECDSA(digest()))
33
+ elif isinstance(key, rsa.RSAPublicKey) and algorithm in (-257, -258, -259, -37, -38, -39):
34
+ rsa_hashes: dict[int, type[hashes.HashAlgorithm]] = {
35
+ -257: hashes.SHA256,
36
+ -258: hashes.SHA384,
37
+ -259: hashes.SHA512,
38
+ -37: hashes.SHA256,
39
+ -38: hashes.SHA384,
40
+ -39: hashes.SHA512,
41
+ }
42
+ rsa_digest = rsa_hashes[algorithm]()
43
+ scheme = (
44
+ padding.PSS(padding.MGF1(rsa_digest), rsa_digest.digest_size)
45
+ if algorithm in (-37, -38, -39)
46
+ else padding.PKCS1v15()
47
+ )
48
+ key.verify(signature, signed_data, scheme, rsa_digest)
49
+ elif isinstance(key, ed25519.Ed25519PublicKey) and algorithm in (-8, -19):
50
+ key.verify(signature, signed_data)
51
+ elif isinstance(key, ed448.Ed448PublicKey) and algorithm == -53:
52
+ key.verify(signature, signed_data)
53
+ elif algorithm in MLDSAPublicKeyTypes and isinstance(key, MLDSAPublicKeyTypes[algorithm]):
54
+ key.verify(signature, signed_data)
55
+ else:
56
+ raise AttestationError("Unsupported attestation algorithm for the certificate key")
57
+
58
+
59
+ def certificate_path(statement: dict[str, object]) -> list[x509.Certificate]:
60
+ path = statement.get("x5c")
61
+ if not isinstance(path, list) or not path or not all(isinstance(cert, bytes) for cert in path):
62
+ raise AttestationError("Missing attestation certificate path")
63
+ return [_load_certificate(cert) for cert in path]
64
+
65
+
66
+ _T = TypeVar("_T")
67
+
68
+
69
+ def _decode_extension(schema: type[_T], *, data: bytes) -> _T:
70
+ try:
71
+ return asn1.decode_der(schema, data)
72
+ except ValueError as exc:
73
+ raise AttestationError("Invalid DER attestation extension") from exc
74
+
75
+
76
+ def validate_aaguid(certificate: x509.Certificate, *, aaguid: bytes | None) -> None:
77
+ try:
78
+ extension = certificate.extensions.get_extension_for_oid(_FIDO_AAGUID_EXTENSION_OID)
79
+ except x509.ExtensionNotFound:
80
+ return
81
+ if extension.critical or not isinstance(extension.value, x509.UnrecognizedExtension):
82
+ raise AttestationError("Invalid attestation AAGUID extension")
83
+ if _decode_extension(bytes, data=extension.value.value) != aaguid:
84
+ raise AttestationError("The attestation certificate AAGUID differs from the authenticator AAGUID")
85
+
86
+
87
+ def verify_packed(
88
+ statement: dict[str, object],
89
+ *,
90
+ auth_data: AuthenticatorData,
91
+ client_data_hash: bytes,
92
+ allow_self: bool,
93
+ trust: CertificateTrust | None,
94
+ ) -> Credential:
95
+ credential = auth_data.credential
96
+ algorithm, signature = statement.get("alg"), statement.get("sig")
97
+ if credential is None or type(algorithm) is not int or not isinstance(signature, bytes):
98
+ raise AttestationError("Invalid packed attestation statement")
99
+ data = auth_data.raw_auth_data + client_data_hash
100
+ if "x5c" not in statement:
101
+ if not allow_self or statement.keys() != {"alg", "sig"} or credential.public_key.algorithm != algorithm:
102
+ raise AttestationError("Invalid or disallowed self attestation")
103
+ credential.verify(signature, signed_data=data)
104
+ return credential
105
+ if trust is None or statement.keys() != {"alg", "sig", "x5c"}:
106
+ raise AttestationError("Invalid or untrusted packed attestation")
107
+ chain = certificate_path(statement)
108
+ certificate = chain[0]
109
+ subject = certificate.subject
110
+ if certificate.version != x509.Version.v3 or any(
111
+ not subject.get_attributes_for_oid(oid)
112
+ for oid in (x509.NameOID.COUNTRY_NAME, x509.NameOID.ORGANIZATION_NAME, x509.NameOID.COMMON_NAME)
113
+ ):
114
+ raise AttestationError("Invalid packed attestation certificate subject or version")
115
+ units = subject.get_attributes_for_oid(x509.NameOID.ORGANIZATIONAL_UNIT_NAME)
116
+ if len(units) != 1 or units[0].value != "Authenticator Attestation":
117
+ raise AttestationError("Invalid packed attestation organizational unit")
118
+ try:
119
+ ca = certificate.extensions.get_extension_for_class(x509.BasicConstraints).value.ca
120
+ except x509.ExtensionNotFound as exc:
121
+ raise AttestationError("Missing packed attestation basic constraints") from exc
122
+ if ca:
123
+ raise AttestationError("A packed attestation leaf cannot be a CA")
124
+ validate_aaguid(certificate, aaguid=auth_data.aaguid)
125
+ verify_certificate_signature(certificate, algorithm=algorithm, signature=signature, signed_data=data)
126
+ trust.verify(chain)
127
+ return credential
128
+
129
+
130
+ @dataclass(frozen=True)
131
+ class ValidatedAttestation:
132
+ type: str
133
+ trust_path: tuple[x509.Certificate, ...]
134
+ credential: Credential
135
+
136
+
137
+ class AttestationStatement:
138
+ validated_attestation = ValidatedAttestation
139
+
140
+
141
+ class FIDOU2FAttestationStatement(AttestationStatement):
142
+ def __init__(self, att_stmt: dict[str, object], *, trust: CertificateTrust) -> None:
143
+ self.att_stmt = att_stmt
144
+ self.trust = trust
145
+ if (
146
+ set(att_stmt) != {"x5c", "sig"}
147
+ or not isinstance(att_stmt["x5c"], list)
148
+ or len(att_stmt["x5c"]) != 1
149
+ or not isinstance(att_stmt["x5c"][0], bytes)
150
+ or not isinstance(att_stmt["sig"], bytes)
151
+ ):
152
+ raise AttestationError("U2F attestation requires a single certificate")
153
+ der_cert = att_stmt["x5c"][0]
154
+ self.att_cert = _load_certificate(der_cert)
155
+ public_key = self.att_cert.public_key()
156
+ if not isinstance(public_key, ec.EllipticCurvePublicKey) or not isinstance(public_key.curve, ec.SECP256R1):
157
+ raise AttestationError("The U2F attestation certificate must contain a P-256 public key")
158
+ self.cert_public_key = public_key
159
+ self.signature = att_stmt["sig"]
160
+
161
+ def validate(
162
+ self, authenticator_data: AuthenticatorData, *, rp_id_hash: bytes, client_data_hash: bytes
163
+ ) -> ValidatedAttestation:
164
+ # See https://www.w3.org/TR/webauthn-3/#sctn-fido-u2f-attestation, "Verification procedure"
165
+ credential = authenticator_data.credential
166
+ if credential is None or credential.id is None:
167
+ raise AttestationError("Missing attested credential or credential ID")
168
+ key = credential.public_key
169
+ if key.key_type != KeyTypes.EC2 or key.algorithm != Algorithms.ES256 or key.ec_id != 1:
170
+ raise AttestationError("U2F credentials require an ES256 key on P-256")
171
+ if len(credential.public_key.x) != 32 or len(credential.public_key.y) != 32:
172
+ raise AttestationError("U2F public key coordinates must each be 32 bytes")
173
+ public_key_u2f = b"\x04" + credential.public_key.x + credential.public_key.y
174
+ verification_data = b"\x00" + rp_id_hash + client_data_hash + credential.id + public_key_u2f
175
+ with _signature_errors():
176
+ self.cert_public_key.verify(self.signature, verification_data, ec.ECDSA(hashes.SHA256()))
177
+ chain = self.trust.verify([self.att_cert])
178
+ return self.validated_attestation(type="Basic", trust_path=tuple(chain), credential=credential)
@@ -0,0 +1,56 @@
1
+ import struct
2
+ from io import BytesIO
3
+
4
+ import cbor2
5
+
6
+ from ._cbor import MAX_EXTENSION_BYTES, MAX_FIELD_BYTES, load_cbor
7
+ from .credentials import Credential
8
+ from .exceptions import AuthenticatorDataError
9
+
10
+
11
+ class AuthenticatorData:
12
+ def __init__(self, auth_data: bytes) -> None:
13
+ self.raw_auth_data = auth_data
14
+ if len(auth_data) < 37:
15
+ raise AuthenticatorDataError("Incomplete authenticator data")
16
+ if len(auth_data) > MAX_FIELD_BYTES:
17
+ raise AuthenticatorDataError("Authenticator data exceeds the size limit")
18
+ self.rp_id_hash: bytes
19
+ self.signature_counter: int
20
+ self.rp_id_hash, flag_byte, self.signature_counter = struct.unpack(">32s1sI", auth_data[:37])
21
+ flags = [bool(int(i)) for i in format(ord(flag_byte), "08b")]
22
+ (
23
+ self.extension_data_included,
24
+ self.attested_credential_data_included,
25
+ _,
26
+ backed_up,
27
+ backup_eligible,
28
+ self.user_verified,
29
+ _,
30
+ self.user_present,
31
+ ) = flags
32
+ if backed_up and not backup_eligible:
33
+ raise AuthenticatorDataError("Backup state requires backup eligibility")
34
+ self.credential: Credential | None = None
35
+ self.aaguid: bytes | None = None
36
+ remaining = BytesIO(auth_data[37:])
37
+ if self.attested_credential_data_included:
38
+ header = remaining.read(18)
39
+ if len(header) != 18:
40
+ raise AuthenticatorDataError("Incomplete attested credential data")
41
+ self.aaguid, credential_id_length = struct.unpack(">16sH", header)
42
+ if not 1 <= credential_id_length <= 1023:
43
+ raise AuthenticatorDataError("Credential ID must be between 1 and 1023 bytes")
44
+ credential_id = remaining.read(credential_id_length)
45
+ if len(credential_id) != credential_id_length:
46
+ raise AuthenticatorDataError("Incomplete credential ID")
47
+ self.credential = Credential(credential_id, credential_public_key=remaining)
48
+ if self.extension_data_included:
49
+ try:
50
+ extensions = load_cbor(remaining, max_bytes=MAX_EXTENSION_BYTES)
51
+ except cbor2.CBORDecodeError as exc:
52
+ raise AuthenticatorDataError("Invalid authenticator extensions") from exc
53
+ if not isinstance(extensions, dict) or not all(isinstance(key, str) for key in extensions):
54
+ raise AuthenticatorDataError("Expected a map of authenticator extension outputs")
55
+ if remaining.read(1):
56
+ raise AuthenticatorDataError("Unexpected trailing authenticator data")