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
|
# Copyright (c) 2018 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from __future__ import annotations
import json
import struct
from dataclasses import dataclass, field
from enum import Enum, EnumMeta, IntFlag, unique
from typing import Any, Mapping, Sequence, cast
from . import cbor
from .cose import ES256, CoseKey
from .utils import (
ByteBuffer,
_JsonDataObject,
sha256,
websafe_decode,
websafe_encode,
)
"""
Data classes based on the W3C WebAuthn specification (https://www.w3.org/TR/webauthn/).
See the specification for a description and details on their usage.
Most of these classes can be serialized to JSON-compatible dictionaries by passing them
to dict(), and then deserialized by calling DataClass.from_dict(data). For example:
user = PublicKeyCredentialUserEntity(id=b"1234", name="Alice")
data = dict(user)
# data is now a JSON-compatible dictionary, json.dumps(data) will work
user2 = PublicKeyCredentialUserEntity.from_dict(data)
assert user == user2
"""
# Binary types
class Aaguid(bytes):
def __init__(self, data: bytes):
if len(self) != 16:
raise ValueError("AAGUID must be 16 bytes")
def __bool__(self):
return self != Aaguid.NONE
def __str__(self):
h = self.hex()
return f"{h[:8]}-{h[8:12]}-{h[12:16]}-{h[16:20]}-{h[20:]}"
def __repr__(self):
return f"AAGUID({str(self)})"
@classmethod
def parse(cls, value: str) -> Aaguid:
return cls.fromhex(value.replace("-", ""))
NONE: Aaguid
# Special instance of AAGUID used when there is no AAGUID
Aaguid.NONE = Aaguid(b"\0" * 16)
@dataclass(init=False, frozen=True)
class AttestedCredentialData(bytes):
aaguid: Aaguid
credential_id: bytes
public_key: CoseKey
def __init__(self, _: bytes):
super().__init__()
parsed = AttestedCredentialData._parse(self)
object.__setattr__(self, "aaguid", parsed[0])
object.__setattr__(self, "credential_id", parsed[1])
object.__setattr__(self, "public_key", parsed[2])
if parsed[3]:
raise ValueError("Wrong length")
def __str__(self): # Override default implementation from bytes.
return repr(self)
@staticmethod
def _parse(data: bytes) -> tuple[bytes, bytes, CoseKey, bytes]:
"""Parse the components of an AttestedCredentialData from a binary
string, and return them.
:param data: A binary string containing an attested credential data.
:return: AAGUID, credential ID, public key, and remaining data.
"""
reader = ByteBuffer(data)
aaguid = Aaguid(reader.read(16))
cred_id = reader.read(reader.unpack(">H"))
pub_key, rest = cbor.decode_from(reader.read())
return aaguid, cred_id, CoseKey.parse(pub_key), rest
@classmethod
def create(
cls, aaguid: bytes, credential_id: bytes, public_key: CoseKey
) -> AttestedCredentialData:
"""Create an AttestedCredentialData by providing its components.
:param aaguid: The AAGUID of the authenticator.
:param credential_id: The binary ID of the credential.
:param public_key: A COSE formatted public key.
:return: The attested credential data.
"""
return cls(
aaguid
+ struct.pack(">H", len(credential_id))
+ credential_id
+ cbor.encode(public_key)
)
@classmethod
def unpack_from(cls, data: bytes) -> tuple[AttestedCredentialData, bytes]:
"""Unpack an AttestedCredentialData from a byte string, returning it and
any remaining data.
:param data: A binary string containing an attested credential data.
:return: The parsed AttestedCredentialData, and any remaining data from
the input.
"""
aaguid, cred_id, pub_key, rest = cls._parse(data)
return cls.create(aaguid, cred_id, pub_key), rest
@classmethod
def from_ctap1(cls, key_handle: bytes, public_key: bytes) -> AttestedCredentialData:
"""Create an AttestatedCredentialData from a CTAP1 RegistrationData instance.
:param key_handle: The CTAP1 credential key_handle.
:type key_handle: bytes
:param public_key: The CTAP1 65 byte public key.
:type public_key: bytes
:return: The credential data, using an all-zero AAGUID.
:rtype: AttestedCredentialData
"""
return cls.create(Aaguid.NONE, key_handle, ES256.from_ctap1(public_key))
@dataclass(init=False, frozen=True)
class AuthenticatorData(bytes):
"""Binary encoding of the authenticator data.
:param _: The binary representation of the authenticator data.
:ivar rp_id_hash: SHA256 hash of the RP ID.
:ivar flags: The flags of the authenticator data, see
AuthenticatorData.FLAG.
:ivar counter: The signature counter of the authenticator.
:ivar credential_data: Attested credential data, if available.
:ivar extensions: Authenticator extensions, if available.
"""
class FLAG(IntFlag):
"""Authenticator data flags
See https://www.w3.org/TR/webauthn/#sec-authenticator-data for details
"""
# Names used in WebAuthn
UP = 0x01
UV = 0x04
BE = 0x08
BS = 0x10
AT = 0x40
ED = 0x80
# Aliases (for historical purposes)
USER_PRESENT = 0x01
USER_VERIFIED = 0x04
BACKUP_ELIGIBILITY = 0x08
BACKUP_STATE = 0x10
ATTESTED = 0x40
EXTENSION_DATA = 0x80
rp_id_hash: bytes
flags: AuthenticatorData.FLAG
counter: int
credential_data: AttestedCredentialData | None
extensions: Mapping | None
def __init__(self, _: bytes):
super().__init__()
reader = ByteBuffer(self)
object.__setattr__(self, "rp_id_hash", reader.read(32))
object.__setattr__(self, "flags", reader.unpack("B"))
object.__setattr__(self, "counter", reader.unpack(">I"))
rest = reader.read()
if self.flags & AuthenticatorData.FLAG.AT:
credential_data, rest = AttestedCredentialData.unpack_from(rest)
else:
credential_data = None
object.__setattr__(self, "credential_data", credential_data)
if self.flags & AuthenticatorData.FLAG.ED:
extensions, rest = cbor.decode_from(rest)
else:
extensions = None
object.__setattr__(self, "extensions", extensions)
if rest:
raise ValueError("Wrong length")
def __str__(self): # Override default implementation from bytes.
return repr(self)
@classmethod
def create(
cls,
rp_id_hash: bytes,
flags: AuthenticatorData.FLAG,
counter: int,
credential_data: bytes = b"",
extensions: Mapping | None = None,
):
"""Create an AuthenticatorData instance.
:param rp_id_hash: SHA256 hash of the RP ID.
:param flags: Flags of the AuthenticatorData.
:param counter: Signature counter of the authenticator data.
:param credential_data: Authenticated credential data (only if attested
credential data flag is set).
:param extensions: Authenticator extensions (only if ED flag is set).
:return: The authenticator data.
"""
return cls(
rp_id_hash
+ struct.pack(">BI", flags, counter)
+ credential_data
+ (cbor.encode(extensions) if extensions is not None else b"")
)
def is_user_present(self) -> bool:
"""Return true if the User Present flag is set."""
return bool(self.flags & AuthenticatorData.FLAG.UP)
def is_user_verified(self) -> bool:
"""Return true if the User Verified flag is set."""
return bool(self.flags & AuthenticatorData.FLAG.UV)
def is_backup_eligible(self) -> bool:
"""Return true if the Backup Eligibility flag is set."""
return bool(self.flags & AuthenticatorData.FLAG.BE)
def is_backed_up(self) -> bool:
"""Return true if the Backup State flag is set."""
return bool(self.flags & AuthenticatorData.FLAG.BS)
def is_attested(self) -> bool:
"""Return true if the Attested credential data flag is set."""
return bool(self.flags & AuthenticatorData.FLAG.AT)
def has_extension_data(self) -> bool:
"""Return true if the Extenstion data flag is set."""
return bool(self.flags & AuthenticatorData.FLAG.ED)
@dataclass(init=False, frozen=True)
class AttestationObject(bytes): # , Mapping[str, Any]):
"""Binary CBOR encoded attestation object.
:param _: The binary representation of the attestation object.
:ivar fmt: The type of attestation used.
:ivar auth_data: The attested authenticator data.
:ivar att_statement: The attestation statement.
"""
fmt: str
auth_data: AuthenticatorData
att_stmt: Mapping[str, Any]
def __init__(self, _: bytes):
super().__init__()
data = cast(Mapping[str, Any], cbor.decode(bytes(self)))
object.__setattr__(self, "fmt", data["fmt"])
object.__setattr__(self, "auth_data", AuthenticatorData(data["authData"]))
object.__setattr__(self, "att_stmt", data["attStmt"])
def __str__(self): # Override default implementation from bytes.
return repr(self)
@classmethod
def create(
cls, fmt: str, auth_data: AuthenticatorData, att_stmt: Mapping[str, Any]
) -> AttestationObject:
return cls(
cbor.encode({"fmt": fmt, "authData": auth_data, "attStmt": att_stmt})
)
@classmethod
def from_ctap1(cls, app_param: bytes, registration) -> AttestationObject:
"""Create an AttestationObject from a CTAP1 RegistrationData instance.
:param app_param: SHA256 hash of the RP ID used for the CTAP1 request.
:type app_param: bytes
:param registration: The CTAP1 registration data.
:type registration: RegistrationData
:return: The attestation object, using the "fido-u2f" format.
:rtype: AttestationObject
"""
return cls.create(
"fido-u2f",
AuthenticatorData.create(
app_param,
AuthenticatorData.FLAG.AT | AuthenticatorData.FLAG.UP,
0,
AttestedCredentialData.from_ctap1(
registration.key_handle, registration.public_key
),
),
{"x5c": [registration.certificate], "sig": registration.signature},
)
@dataclass(init=False, frozen=True)
class CollectedClientData(bytes):
@unique
class TYPE(str, Enum):
CREATE = "webauthn.create"
GET = "webauthn.get"
_data: Mapping[str, Any]
type: str
challenge: bytes
origin: str
cross_origin: bool = False
def __init__(self, _: bytes):
super().__init__()
object.__setattr__(self, "_data", json.loads(self.decode()))
object.__setattr__(self, "type", self._data["type"])
object.__setattr__(self, "challenge", websafe_decode(self._data["challenge"]))
object.__setattr__(self, "origin", self._data["origin"])
object.__setattr__(self, "cross_origin", self._data.get("crossOrigin", False))
@classmethod
def create(
cls,
type: str,
challenge: bytes | str,
origin: str,
cross_origin: bool = False,
**kwargs,
) -> CollectedClientData:
if isinstance(challenge, bytes):
encoded_challenge = websafe_encode(challenge)
else:
encoded_challenge = challenge
return cls(
json.dumps(
{
"type": type,
"challenge": encoded_challenge,
"origin": origin,
"crossOrigin": cross_origin,
**kwargs,
},
separators=(",", ":"),
).encode()
)
def __str__(self): # Override default implementation from bytes.
return repr(self)
@property
def b64(self) -> str:
return websafe_encode(self)
@property
def hash(self) -> bytes:
return sha256(self)
class _StringEnumMeta(EnumMeta):
def _get_value(cls, value):
return None
def __call__(cls, value, *args, **kwargs):
try:
return super().__call__(value, *args, **kwargs)
except ValueError:
return cls._get_value(value)
class _StringEnum(str, Enum, metaclass=_StringEnumMeta):
"""Enum of strings for WebAuthn types.
Unrecognized values are treated as missing.
"""
@unique
class AttestationConveyancePreference(_StringEnum):
NONE = "none"
INDIRECT = "indirect"
DIRECT = "direct"
ENTERPRISE = "enterprise"
@unique
class UserVerificationRequirement(_StringEnum):
REQUIRED = "required"
PREFERRED = "preferred"
DISCOURAGED = "discouraged"
@unique
class ResidentKeyRequirement(_StringEnum):
REQUIRED = "required"
PREFERRED = "preferred"
DISCOURAGED = "discouraged"
@unique
class AuthenticatorAttachment(_StringEnum):
PLATFORM = "platform"
CROSS_PLATFORM = "cross-platform"
@unique
class AuthenticatorTransport(_StringEnum):
USB = "usb"
NFC = "nfc"
BLE = "ble"
HYBRID = "hybrid"
INTERNAL = "internal"
@unique
class PublicKeyCredentialType(_StringEnum):
PUBLIC_KEY = "public-key"
@unique
class PublicKeyCredentialHint(_StringEnum):
SECURITY_KEY = "security-key"
CLIENT_DEVICE = "client-device"
HYBRID = "hybrid"
def _as_cbor(data: _JsonDataObject) -> Mapping[str, Any]:
return {k: super(_JsonDataObject, data).__getitem__(k) for k in data}
@dataclass(eq=False, frozen=True, kw_only=True)
class PublicKeyCredentialRpEntity(_JsonDataObject):
name: str
id: str | None = None
@property
def id_hash(self) -> bytes | None:
"""Return SHA256 hash of the identifier."""
return sha256(self.id.encode("utf8")) if self.id else None
@dataclass(eq=False, frozen=True, kw_only=True)
class PublicKeyCredentialUserEntity(_JsonDataObject):
name: str
id: bytes
display_name: str | None = None
@dataclass(eq=False, frozen=True, kw_only=True)
class PublicKeyCredentialParameters(_JsonDataObject):
type: PublicKeyCredentialType
alg: int
@dataclass(eq=False, frozen=True, kw_only=True)
class PublicKeyCredentialDescriptor(_JsonDataObject):
type: PublicKeyCredentialType
id: bytes
transports: Sequence[AuthenticatorTransport] | None = None
@dataclass(eq=False, frozen=True, kw_only=True)
class AuthenticatorSelectionCriteria(_JsonDataObject):
authenticator_attachment: AuthenticatorAttachment | None = None
resident_key: ResidentKeyRequirement | None = None
user_verification: UserVerificationRequirement | None = None
require_resident_key: bool | None = False
def __post_init__(self):
super().__post_init__()
if self.resident_key is None:
object.__setattr__(
self,
"resident_key",
(
ResidentKeyRequirement.REQUIRED
if self.require_resident_key
else ResidentKeyRequirement.DISCOURAGED
),
)
object.__setattr__(
self,
"require_resident_key",
self.resident_key == ResidentKeyRequirement.REQUIRED,
)
@dataclass(eq=False, frozen=True, kw_only=True)
class PublicKeyCredentialCreationOptions(_JsonDataObject):
rp: PublicKeyCredentialRpEntity
user: PublicKeyCredentialUserEntity
challenge: bytes
pub_key_cred_params: Sequence[PublicKeyCredentialParameters]
timeout: int | None = None
exclude_credentials: Sequence[PublicKeyCredentialDescriptor] | None = None
authenticator_selection: AuthenticatorSelectionCriteria | None = None
hints: Sequence[PublicKeyCredentialHint] | None = None
attestation: AttestationConveyancePreference | None = None
attestation_formats: Sequence[str] | None = None
extensions: Mapping[str, Any] | None = None
@dataclass(eq=False, frozen=True, kw_only=True)
class PublicKeyCredentialRequestOptions(_JsonDataObject):
challenge: bytes
timeout: int | None = None
rp_id: str | None = None
allow_credentials: Sequence[PublicKeyCredentialDescriptor] | None = None
user_verification: UserVerificationRequirement | None = None
hints: Sequence[PublicKeyCredentialHint] | None = None
extensions: Mapping[str, Any] | None = None
@dataclass(eq=False, frozen=True, kw_only=True)
class AuthenticatorAttestationResponse(_JsonDataObject):
client_data: CollectedClientData = field(metadata=dict(name="clientDataJSON"))
attestation_object: AttestationObject
@dataclass(eq=False, frozen=True, kw_only=True)
class AuthenticatorAssertionResponse(_JsonDataObject):
client_data: CollectedClientData = field(metadata=dict(name="clientDataJSON"))
authenticator_data: AuthenticatorData
signature: bytes
user_handle: bytes | None = None
class AuthenticationExtensionsClientOutputs(Mapping[str, Any]):
"""Holds extension output from a call to MakeCredential or GetAssertion.
When accessed as a dict, all bytes values will be serialized to base64url encoding,
capable of being serialized to JSON.
When accessed using attributes, richer types will instead be returned.
"""
def __init__(self, outputs: Mapping[str, Any] = {}):
self._members = {k: v for k, v in outputs.items() if v is not None}
def __iter__(self):
return iter(self._members)
def __len__(self):
return len(self._members)
def __getitem__(self, key):
value = self._members[key]
if isinstance(value, bytes):
return websafe_encode(value)
elif isinstance(value, Mapping) and not isinstance(value, dict):
return dict(value)
return value
def __getattr__(self, key):
parts = key.split("_")
name = parts[0] + "".join(p.title() for p in parts[1:])
return self._members.get(name)
def __repr__(self):
return repr(dict(self))
@dataclass(eq=False, frozen=True, kw_only=True)
class RegistrationResponse(_JsonDataObject):
"""
Represents the RegistrationResponse structure from the WebAuthn specification,
with fields modeled after the JSON serialization.
Serializing this object to JSON can be done by using json.dumps(dict(response)).
See: https://www.w3.org/TR/webauthn-3/#dictdef-registrationresponsejson
"""
id: str = field(init=False)
raw_id: bytes
response: AuthenticatorAttestationResponse
authenticator_attachment: AuthenticatorAttachment | None = None
client_extension_results: AuthenticationExtensionsClientOutputs = field(
default_factory=AuthenticationExtensionsClientOutputs
)
type: PublicKeyCredentialType = PublicKeyCredentialType.PUBLIC_KEY
def __post_init__(self):
object.__setattr__(self, "id", websafe_encode(self.raw_id))
super().__post_init__()
@classmethod
def _parse_value(cls, t, value):
if t == Mapping[str, Any] | None:
# Don't convert extension_results
return value
return super()._parse_value(t, value)
@classmethod
def from_dict(cls, data):
if data and "id" in data:
data = dict(data)
credential_id = data.pop("id")
if credential_id != data["rawId"]:
raise ValueError("id does not match rawId")
return super().from_dict(data)
@dataclass(eq=False, frozen=True, kw_only=True)
class AuthenticationResponse(_JsonDataObject):
"""
Represents the AuthenticationResponse structure from the WebAuthn specification,
with fields modeled after the JSON serialization.
Serializing this object to JSON can be done by using json.dumps(dict(response)).
See: https://www.w3.org/TR/webauthn-3/#dictdef-authenticationresponsejson
"""
id: str = field(init=False)
raw_id: bytes
response: AuthenticatorAssertionResponse
authenticator_attachment: AuthenticatorAttachment | None = None
client_extension_results: AuthenticationExtensionsClientOutputs = field(
default_factory=AuthenticationExtensionsClientOutputs
)
type: PublicKeyCredentialType = PublicKeyCredentialType.PUBLIC_KEY
def __post_init__(self):
object.__setattr__(self, "id", websafe_encode(self.raw_id))
super().__post_init__()
@classmethod
def _parse_value(cls, t, value):
if t == Mapping[str, Any] | None:
# Don't convert extension_results
return value
return super()._parse_value(t, value)
@classmethod
def from_dict(cls, data):
if data and "id" in data:
data = dict(data)
credential_id = data.pop("id")
if credential_id != data["rawId"]:
raise ValueError("id does not match rawId")
return super().from_dict(data)
@dataclass(eq=False, frozen=True, kw_only=True)
class CredentialCreationOptions(_JsonDataObject):
public_key: PublicKeyCredentialCreationOptions
@dataclass(eq=False, frozen=True, kw_only=True)
class CredentialRequestOptions(_JsonDataObject):
public_key: PublicKeyCredentialRequestOptions
|