fido2.client

Submodules

Exceptions

CtapError

Error returned from the Authenticator when a command fails.

ApduError

An Exception thrown when a response APDU doesn't have an OK (0x9000)

ClientError

Base error raised by clients.

PinRequiredError

Raised when a call cannot be completed without providing PIN.

Classes

ES256

A COSE formatted public key.

CtapDevice

CTAP-capable device.

APDU

APDU response codes.

Ctap1

Implementation of the CTAP1 specification.

AssertionResponse

Binary CBOR encoded assertion response.

Ctap2

Implementation of the CTAP2 specification.

Info

Binary CBOR encoded response data returned by the CTAP2 GET_INFO command.

AuthenticationExtensionProcessor

Processing state for a CTAP2 extension, for single use.

Ctap2Extension

Base class for CTAP2 extensions.

RegistrationExtensionProcessor

Processing state for a CTAP2 extension, for single use.

ClientPin

Implementation of the CTAP2 Client PIN API.

PinProtocol

Helper class that provides a standard way to create an ABC using

Aaguid

bytes(iterable_of_ints) -> bytes

AttestationConveyancePreference

Enum of strings for WebAuthn types.

AttestationObject

Binary CBOR encoded attestation object.

AuthenticationExtensionsClientOutputs

Holds extension output from a call to MakeCredential or GetAssertion.

AuthenticationResponse

Represents the AuthenticationResponse structure from the WebAuthn specification,

AuthenticatorAssertionResponse

A data class with members also accessible as a JSON-serializable Mapping.

AuthenticatorAttachment

Enum of strings for WebAuthn types.

AuthenticatorAttestationResponse

A data class with members also accessible as a JSON-serializable Mapping.

AuthenticatorSelectionCriteria

A data class with members also accessible as a JSON-serializable Mapping.

CollectedClientData

bytes(iterable_of_ints) -> bytes

PublicKeyCredentialCreationOptions

A data class with members also accessible as a JSON-serializable Mapping.

PublicKeyCredentialDescriptor

A data class with members also accessible as a JSON-serializable Mapping.

PublicKeyCredentialRequestOptions

A data class with members also accessible as a JSON-serializable Mapping.

PublicKeyCredentialType

Enum of strings for WebAuthn types.

RegistrationResponse

Represents the RegistrationResponse structure from the WebAuthn specification,

ResidentKeyRequirement

Enum of strings for WebAuthn types.

UserVerificationRequirement

Enum of strings for WebAuthn types.

AssertionSelection

GetAssertion result holding one or more assertions.

WebAuthnClient

Base class for a WebAuthn client, supporting registration and authentication.

UserInteraction

Provides user interaction to the Client.

ClientDataCollector

Provides client data and logic to the Client.

DefaultClientDataCollector

Default implementation of ClientDataProvider.

Fido2Client

WebAuthn-like client implementation.

Functions

verify_rp_id(rp_id, origin)

Checks if a Webauthn RP ID is usable for a given origin.

sha256(data)

Produces a SHA256 hash of the input.

Package Contents

class fido2.client.ES256[source]

Bases: CoseKey

A COSE formatted public key.

Parameters:

_ – The COSE key paramters.

Variables:

ALGORITHM – COSE algorithm identifier.

ALGORITHM = -7
verify(message, signature)[source]

Validates a digital signature over a given message.

Parameters:
  • message – The message which was signed.

  • signature – The signature to check.

classmethod from_cryptography_key(public_key)[source]

Converts a PublicKey object from Cryptography into a COSE key.

Parameters:

public_key – Either an EC or RSA public key.

Returns:

A CoseKey.

classmethod from_ctap1(data)[source]

Creates an ES256 key from a CTAP1 formatted public key byte string.

Parameters:

data – A 65 byte SECP256R1 public key.

Returns:

A ES256 key.

class fido2.client.CtapDevice[source]

Bases: abc.ABC

CTAP-capable device.

Subclasses of this should implement call(), as well as list_devices(), which should return a generator over discoverable devices.

property capabilities: int
Abstractmethod:

Return type:

int

Get device capabilities

abstractmethod call(cmd, data=b'', event=None, on_keepalive=None)[source]

Sends a command to the authenticator, and reads the response.

Parameters:
  • cmd (int) – The integer value of the command.

  • data (bytes) – The payload of the command.

  • event (threading.Event | None) – An optional threading.Event which can be used to cancel the invocation.

  • on_keepalive (Callable[[STATUS], None] | None) – An optional callback to handle keep-alive messages from the authenticator. The function is only called once for consecutive keep-alive messages with the same status.

Returns:

The response from the authenticator.

Return type:

bytes

close()[source]

Close the device, releasing any held resources.

Return type:

None

classmethod list_devices()[source]
Abstractmethod:

Return type:

Iterator[CtapDevice]

Generates instances of cls for discoverable devices.

exception fido2.client.CtapError(code)[source]

Bases: Exception

Error returned from the Authenticator when a command fails.

Parameters:

code (int)

class UNKNOWN_ERR[source]

Bases: int

CTAP error status code that is not recognized.

name = 'UNKNOWN_ERR'
property value: int
Return type:

int

class ERR[source]

Bases: enum.IntEnum

CTAP status codes.

https://fidoalliance.org/specs/fido-v2.1-rd-20201208/fido-client-to-authenticator-protocol-v2.1-rd-20201208.html#error-responses

SUCCESS = 0
INVALID_COMMAND = 1
INVALID_PARAMETER = 2
INVALID_LENGTH = 3
INVALID_SEQ = 4
TIMEOUT = 5
CHANNEL_BUSY = 6
LOCK_REQUIRED = 10
INVALID_CHANNEL = 11
CBOR_UNEXPECTED_TYPE = 17
INVALID_CBOR = 18
MISSING_PARAMETER = 20
LIMIT_EXCEEDED = 21
FP_DATABASE_FULL = 23
LARGE_BLOB_STORAGE_FULL = 24
CREDENTIAL_EXCLUDED = 25
PROCESSING = 33
INVALID_CREDENTIAL = 34
USER_ACTION_PENDING = 35
OPERATION_PENDING = 36
NO_OPERATIONS = 37
UNSUPPORTED_ALGORITHM = 38
OPERATION_DENIED = 39
KEY_STORE_FULL = 40
UNSUPPORTED_OPTION = 43
INVALID_OPTION = 44
KEEPALIVE_CANCEL = 45
NO_CREDENTIALS = 46
USER_ACTION_TIMEOUT = 47
NOT_ALLOWED = 48
PIN_INVALID = 49
PIN_BLOCKED = 50
PIN_AUTH_INVALID = 51
PIN_AUTH_BLOCKED = 52
PIN_NOT_SET = 53
PUAT_REQUIRED = 54
PIN_POLICY_VIOLATION = 55
PIN_TOKEN_EXPIRED = 56
REQUEST_TOO_LARGE = 57
ACTION_TIMEOUT = 58
UP_REQUIRED = 59
UV_BLOCKED = 60
INTEGRITY_FAILURE = 61
INVALID_SUBCOMMAND = 62
UV_INVALID = 63
UNAUTHORIZED_PERMISSION = 64
OTHER = 127
SPEC_LAST = 223
EXTENSION_FIRST = 224
EXTENSION_LAST = 239
VENDOR_FIRST = 240
VENDOR_LAST = 255
class fido2.client.APDU[source]

Bases: enum.IntEnum

APDU response codes.

OK = 36864
USE_NOT_SATISFIED = 27013
WRONG_DATA = 27264
exception fido2.client.ApduError(code, data=b'')[source]

Bases: Exception

An Exception thrown when a response APDU doesn’t have an OK (0x9000) status.

Parameters:
  • code (int) – APDU response code.

  • data (bytes) – APDU response body.

code
data = b''
class fido2.client.Ctap1(device)[source]

Implementation of the CTAP1 specification.

Parameters:

device (fido2.ctap.CtapDevice) – A CtapHidDevice handle supporting CTAP1.

class INS[source]

Bases: enum.IntEnum

Enum where members are also (and must be) ints

REGISTER = 1
AUTHENTICATE = 2
VERSION = 3
device
send_apdu(cla=0, ins=0, p1=0, p2=0, data=b'')[source]

Packs and sends an APDU for use in CTAP1 commands. This is a low-level method mainly used internally. Avoid calling it directly if possible, and use the get_version, register, and authenticate methods if possible instead.

Parameters:
  • cla (int) – The CLA parameter of the request.

  • ins (int) – The INS parameter of the request.

  • p1 (int) – The P1 parameter of the request.

  • p2 (int) – The P2 parameter of the request.

  • data (bytes) – The body of the request.

Returns:

The response APDU data of a successful request.

Raise:

ApduError

Return type:

bytes

get_version()[source]

Get the U2F version implemented by the authenticator. The only version specified is “U2F_V2”.

Returns:

A U2F version string.

Return type:

str

register(client_param, app_param)[source]

Register a new U2F credential.

Parameters:
  • client_param (bytes) – SHA256 hash of the ClientData used for the request.

  • app_param (bytes) – SHA256 hash of the app ID used for the request.

Returns:

The registration response from the authenticator.

Return type:

RegistrationData

authenticate(client_param, app_param, key_handle, check_only=False)[source]

Authenticate a previously registered credential.

Parameters:
  • client_param (bytes) – SHA256 hash of the ClientData used for the request.

  • app_param (bytes) – SHA256 hash of the app ID used for the request.

  • key_handle (bytes) – The binary key handle of the credential.

  • check_only (bool) – True to send a “check-only” request, which is used to determine if a key handle is known.

Returns:

The authentication response from the authenticator.

Return type:

SignatureData

class fido2.client.AssertionResponse[source]

Bases: _CborDataObject

Binary CBOR encoded assertion response.

Parameters:

_ – The binary representation of the assertion response.

Variables:
  • credential – The credential used for the assertion.

  • auth_data – The authenticator data part of the response.

  • signature – The digital signature of the assertion.

  • user – The user data of the credential.

  • number_of_credentials – The total number of responses available (only set for the first response, if > 1).

credential: Mapping[str, Any]
auth_data: fido2.webauthn.AuthenticatorData
signature: bytes
user: dict[str, Any] | None = None
number_of_credentials: int | None = None
user_selected: bool | None = None
large_blob_key: bytes | None = None
verify(client_param, public_key)[source]

Verify the digital signature of the response with regard to the client_param, using the given public key.

Parameters:
  • client_param (bytes) – SHA256 hash of the ClientData used for the request.

  • public_key (fido2.cose.CoseKey) – The public key of the credential, to verify.

classmethod from_ctap1(app_param, credential, authentication)[source]

Create an AssertionResponse from a CTAP1 SignatureData instance.

Parameters:
  • app_param (bytes) – SHA256 hash of the RP ID used for the CTAP1 request.

  • credential (Mapping[str, Any]) – Credential used for the CTAP1 request (from the allowList).

  • authentication – The CTAP1 signature data.

Returns:

The assertion response.

Return type:

AssertionResponse

class fido2.client.Ctap2(device, strict_cbor=True)[source]

Implementation of the CTAP2 specification.

Parameters:
  • device (fido2.ctap.CtapDevice) – A CtapHidDevice handle supporting CTAP2.

  • strict_cbor (bool) – Validate that CBOR returned from the Authenticator is canonical, defaults to True.

class CMD[source]

Bases: enum.IntEnum

Enum where members are also (and must be) ints

MAKE_CREDENTIAL = 1
GET_ASSERTION = 2
GET_INFO = 4
CLIENT_PIN = 6
RESET = 7
GET_NEXT_ASSERTION = 8
BIO_ENROLLMENT = 9
CREDENTIAL_MGMT = 10
SELECTION = 11
LARGE_BLOBS = 12
CONFIG = 13
BIO_ENROLLMENT_PRE = 64
CREDENTIAL_MGMT_PRE = 65
device
property info: Info

Get a cached Info object which can be used to determine capabilities.

Return type:

Info

Returns:

The response of calling GetAuthenticatorInfo.

send_cbor(cmd, data=None, *, event=None, on_keepalive=None)[source]

Sends a CBOR message to the device, and waits for a response.

Parameters:
  • cmd (int) – The command byte of the request.

  • data (Mapping[int, Any] | None) – The payload to send (to be CBOR encoded).

  • event (threading.Event | None) – Optional threading.Event used to cancel the request.

  • on_keepalive (Callable[[int], None] | None) – Optional function called when keep-alive is sent by the authenticator.

Return type:

Mapping[int, Any]

get_info()[source]

CTAP2 getInfo command.

Returns:

Information about the authenticator.

Return type:

Info

client_pin(pin_uv_protocol, sub_cmd, key_agreement=None, pin_uv_param=None, new_pin_enc=None, pin_hash_enc=None, permissions=None, permissions_rpid=None, *, event=None, on_keepalive=None)[source]

CTAP2 clientPin command, used for various PIN operations.

This method is not intended to be called directly. It is intended to be used by an instance of the PinProtocolV1 class.

Parameters:
  • pin_uv_protocol (int) – The PIN/UV protocol version to use.

  • sub_cmd (int) – A clientPin sub command.

  • key_agreement (Mapping[int, Any] | None) – The keyAgreement parameter.

  • pin_uv_param (bytes | None) – The pinAuth parameter.

  • new_pin_enc (bytes | None) – The newPinEnc parameter.

  • pin_hash_enc (bytes | None) – The pinHashEnc parameter.

  • permissions (int | None) – The permissions parameter.

  • permissions_rpid (str | None) – The permissions RPID parameter.

  • event (threading.Event | None) – Optional threading.Event used to cancel the request.

  • on_keepalive (Callable[[int], None] | None) – Optional callback function to handle keep-alive messages from the authenticator.

Returns:

The response of the command, decoded.

Return type:

Mapping[int, Any]

reset(*, event=None, on_keepalive=None)[source]

CTAP2 reset command, erases all credentials and PIN.

Parameters:
  • event (threading.Event | None) – Optional threading.Event object used to cancel the request.

  • on_keepalive (Callable[[int], None] | None) – Optional callback function to handle keep-alive messages from the authenticator.

Return type:

None

make_credential(client_data_hash, rp, user, key_params, exclude_list=None, extensions=None, options=None, pin_uv_param=None, pin_uv_protocol=None, enterprise_attestation=None, *, event=None, on_keepalive=None)[source]

CTAP2 makeCredential operation.

Parameters:
  • client_data_hash (bytes) – SHA256 hash of the ClientData.

  • rp (Mapping[str, Any]) – PublicKeyCredentialRpEntity parameters.

  • user (Mapping[str, Any]) – PublicKeyCredentialUserEntity parameters.

  • key_params (list[Mapping[str, Any]]) – List of acceptable credential types.

  • exclude_list (list[Mapping[str, Any]] | None) – Optional list of PublicKeyCredentialDescriptors.

  • extensions (Mapping[str, Any] | None) – Optional dict of extensions.

  • options (Mapping[str, Any] | None) – Optional dict of options.

  • pin_uv_param (bytes | None) – Optional PIN/UV auth parameter.

  • pin_uv_protocol (int | None) – The version of PIN/UV protocol used, if any.

  • enterprise_attestation (int | None) – Whether or not to request Enterprise Attestation.

  • event (threading.Event | None) – Optional threading.Event used to cancel the request.

  • on_keepalive (Callable[[int], None] | None) – Optional callback function to handle keep-alive messages from the authenticator.

Returns:

The new credential.

Return type:

AttestationResponse

get_assertion(rp_id, client_data_hash, allow_list=None, extensions=None, options=None, pin_uv_param=None, pin_uv_protocol=None, *, event=None, on_keepalive=None)[source]

CTAP2 getAssertion command.

Parameters:
  • rp_id (str) – The RP ID of the credential.

  • client_data_hash (bytes) – SHA256 hash of the ClientData used.

  • allow_list (list[Mapping[str, Any]] | None) – Optional list of PublicKeyCredentialDescriptors.

  • extensions (Mapping[str, Any] | None) – Optional dict of extensions.

  • options (Mapping[str, Any] | None) – Optional dict of options.

  • pin_uv_param (bytes | None) – Optional PIN/UV auth parameter.

  • pin_uv_protocol (int | None) – The version of PIN/UV protocol used, if any.

  • event (threading.Event | None) – Optional threading.Event used to cancel the request.

  • on_keepalive (Callable[[int], None] | None) – Optional callback function to handle keep-alive messages from the authenticator.

Returns:

The new assertion.

Return type:

AssertionResponse

get_next_assertion()[source]

CTAP2 getNextAssertion command.

Returns:

The next available assertion response.

Return type:

AssertionResponse

get_assertions(*args, **kwargs)[source]

Convenience method to get list of assertions.

See get_assertion and get_next_assertion for details.

Return type:

list[AssertionResponse]

credential_mgmt(sub_cmd, sub_cmd_params=None, pin_uv_protocol=None, pin_uv_param=None)[source]

CTAP2 credentialManagement command, used to manage resident credentials.

NOTE: This implements the current draft version of the CTAP2 specification and should be considered highly experimental.

This method is not intended to be called directly. It is intended to be used by an instance of the CredentialManagement class.

Parameters:
  • sub_cmd (int) – A CredentialManagement sub command.

  • sub_cmd_params (Mapping[int, Any] | None) – Sub command specific parameters.

  • pin_uv_protocol (int | None) – PIN/UV auth protocol version used.

  • pin_uv_param (bytes | None) – PIN/UV Auth parameter.

Return type:

Mapping[int, Any]

bio_enrollment(modality=None, sub_cmd=None, sub_cmd_params=None, pin_uv_protocol=None, pin_uv_param=None, get_modality=None, *, event=None, on_keepalive=None)[source]

CTAP2 bio enrollment command. Used to provision/enumerate/delete bio enrollments in the authenticator.

NOTE: This implements the current draft version of the CTAP2 specification and should be considered highly experimental.

This method is not intended to be called directly. It is intended to be used by an instance of the BioEnrollment class.

Parameters:
  • modality (int | None) – The user verification modality being used.

  • sub_cmd (int | None) – A BioEnrollment sub command.

  • sub_cmd_params (Mapping[int, Any] | None) – Sub command specific parameters.

  • pin_uv_protocol (int | None) – PIN/UV protocol version used.

  • pin_uv_param (bytes | None) – PIN/UV auth param.

  • get_modality (bool | None) – Get the user verification type modality.

  • event (threading.Event | None)

  • on_keepalive (Callable[[int], None] | None)

Return type:

Mapping[int, Any]

selection(*, event=None, on_keepalive=None)[source]

CTAP2 authenticator selection command.

This command allows the platform to let a user select a certain authenticator by asking for user presence.

Parameters:
  • event (threading.Event | None) – Optional threading.Event used to cancel the request.

  • on_keepalive (Callable[[int], None] | None) – Optional callback function to handle keep-alive messages from the authenticator.

Return type:

None

large_blobs(offset, get=None, set=None, length=None, pin_uv_param=None, pin_uv_protocol=None)[source]

CTAP2 authenticator large blobs command.

This command is used to read and write the large blob array.

This method is not intended to be called directly. It is intended to be used by an instance of the LargeBlobs class.

Parameters:
  • offset (int) – The offset of where to start reading/writing data.

  • get (int | None) – Optional (max) length of data to read.

  • set (bytes | None) – Optional data to write.

  • length (int | None) – Length of the payload in set.

  • pin_uv_protocol (int | None) – PIN/UV protocol version used.

  • pin_uv_param (bytes | None) – PIN/UV auth param.

Return type:

Mapping[int, Any]

config(sub_cmd, sub_cmd_params=None, pin_uv_protocol=None, pin_uv_param=None)[source]

CTAP2 authenticator config command.

This command is used to configure various authenticator features through the use of its subcommands.

This method is not intended to be called directly. It is intended to be used by an instance of the Config class.

Parameters:
  • sub_cmd (int) – A Config sub command.

  • sub_cmd_params (Mapping[int, Any] | None) – Sub command specific parameters.

  • pin_uv_protocol (int | None) – PIN/UV auth protocol version used.

  • pin_uv_param (bytes | None) – PIN/UV Auth parameter.

Return type:

Mapping[int, Any]

class fido2.client.Info[source]

Bases: _CborDataObject

Binary CBOR encoded response data returned by the CTAP2 GET_INFO command.

See: https://fidoalliance.org/specs/fido-v2.2-rd-20230321/fido-client-to-authenticator-protocol-v2.2-rd-20230321.html#authenticatorGetInfo for descriptions of these fields.

Note that while many fields are optional when returned by the authenticator, this dataclass uses defaults to represent a missing value such as empty lists or dicts, or the integer value 0. These are used rather than None for omitted values as long as this can be done without introducing any practical ambiguity. This also means that several of these fields may have a 0 value even if the specification states that they should be non-zero when returned from the authenticator.

Parameters:

_ – The binary content of the Info data.

versions: list[str]
extensions: list[str] = []
aaguid: fido2.webauthn.Aaguid
options: dict[str, bool]
max_msg_size: int = 1024
pin_uv_protocols: list[int] = []
max_creds_in_list: int = 0
max_cred_id_length: int = 0
transports: list[str] = []
algorithms: list[dict[str, Any]] = []
max_large_blob: int = 0
force_pin_change: bool = False
min_pin_length: int = 4
firmware_version: int = 0
max_cred_blob_length: int = 0
max_rpids_for_min_pin: int = 0
preferred_platform_uv_attempts: int = 0
uv_modality: int = 0
certifications: dict
remaining_disc_creds: int | None = None
vendor_prototype_config_commands: list[int] = []
attestation_formats: list[str] = ['packed']
uv_count_since_pin: int | None = None
long_touch_for_reset: bool = False
enc_identifier: bytes | None = None
transports_for_reset: list[str] = []
pin_complexity_policy: bool | None = None
pin_complexity_policy_url: bytes | None = None
max_pin_length: int = 63
get_identifier(pin_token)[source]

Decrypt the device identifier using a persistent PUAT.

Parameters:

pin_token (bytes)

Return type:

bytes | None

class fido2.client.AuthenticationExtensionProcessor(permissions=ClientPin.PERMISSION(0), inputs=None, outputs=None)[source]

Bases: ExtensionProcessor

Processing state for a CTAP2 extension, for single use.

The ExtensionProcessor holds state and logic for client processing of an extension, for an authentication (GetAssertion) call.

Parameters:
  • permissions (fido2.ctap2.pin.ClientPin.PERMISSION) – PinUvAuthToken permissions required by the extension.

  • inputs (dict[str, Any] | None) – Default authenticator inputs, if prepare_inputs is not overridden.

  • outputs (dict[str, Any] | None) – Default client outputs, if prepare_outputs is not overridden.

prepare_inputs(selected, pin_token)[source]

Prepare authenticator extension inputs, to be passed to the Authenenticator.

Parameters:
Return type:

dict[str, Any] | None

prepare_outputs(response, pin_token)[source]

Prepare client extension outputs, to be returned to the caller.

Parameters:
Return type:

dict[str, Any] | None

class fido2.client.Ctap2Extension[source]

Bases: abc.ABC

Base class for CTAP2 extensions.

As of python-fido2 1.2 these instances can be used for multiple requests and should be invoked via the make_credential and get_assertion methods. Subclasses are instantiated for a single request, if the Authenticator supports the extension.

abstractmethod is_supported(ctap)[source]

Whether or not the extension is supported by the authenticator.

Parameters:

ctap (fido2.ctap2.base.Ctap2)

Return type:

bool

make_credential(ctap, options, pin_protocol)[source]

Start client extension processing for registration.

Parameters:
Return type:

RegistrationExtensionProcessor | None

get_assertion(ctap, options, pin_protocol)[source]

Start client extension processing for authentication.

Parameters:
Return type:

AuthenticationExtensionProcessor | None

class fido2.client.RegistrationExtensionProcessor(permissions=ClientPin.PERMISSION(0), inputs=None, outputs=None)[source]

Bases: ExtensionProcessor

Processing state for a CTAP2 extension, for single use.

The ExtensionProcessor holds state and logic for client processing of an extension, for a registration (MakeCredential) call.

Parameters:
  • permissions (fido2.ctap2.pin.ClientPin.PERMISSION) – PinUvAuthToken permissions required by the extension.

  • inputs (dict[str, Any] | None) – Default authenticator inputs, if prepare_inputs is not overridden.

  • outputs (dict[str, Any] | None) – Default client outputs, if prepare_outputs is not overridden.

prepare_inputs(pin_token)[source]

Prepare authenticator extension inputs, to be passed to the Authenenticator.

Parameters:

pin_token (bytes | None)

Return type:

dict[str, Any] | None

prepare_outputs(response, pin_token)[source]

Prepare client extension outputs, to be returned to the caller.

Parameters:
Return type:

dict[str, Any] | None

class fido2.client.ClientPin(ctap, protocol=None)[source]

Implementation of the CTAP2 Client PIN API.

Parameters:
  • ctap (fido2.ctap2.base.Ctap2) – An instance of a CTAP2 object.

  • protocol (PinProtocol | None) – An optional instance of a PinUvAuthProtocol object. If None is provided then the latest protocol supported by both library and Authenticator will be used.

PROTOCOLS
class CMD[source]

Bases: enum.IntEnum

Enum where members are also (and must be) ints

GET_PIN_RETRIES = 1
GET_KEY_AGREEMENT = 2
SET_PIN = 3
CHANGE_PIN = 4
GET_TOKEN_USING_PIN_LEGACY = 5
GET_TOKEN_USING_UV = 6
GET_UV_RETRIES = 7
GET_TOKEN_USING_PIN = 9
class RESULT[source]

Bases: enum.IntEnum

Enum where members are also (and must be) ints

KEY_AGREEMENT = 1
PIN_UV_TOKEN = 2
PIN_RETRIES = 3
POWER_CYCLE_STATE = 4
UV_RETRIES = 5
class PERMISSION[source]

Bases: enum.IntFlag

Support for integer-based Flags

MAKE_CREDENTIAL = 1
GET_ASSERTION = 2
CREDENTIAL_MGMT = 4
BIO_ENROLL = 8
LARGE_BLOB_WRITE = 16
AUTHENTICATOR_CFG = 32
PERSISTENT_CREDENTIAL_MGMT = 64
static is_supported(info)[source]

Checks if ClientPin functionality is supported.

Note that the ClientPin function is still usable without support for client PIN functionality, as UV token may still be supported.

static is_token_supported(info)[source]

Checks if pinUvAuthToken is supported.

ctap
get_pin_token(pin, permissions=None, permissions_rpid=None)[source]

Get a PIN/UV token from the authenticator using PIN.

Parameters:
  • pin (str) – The PIN of the authenticator.

  • permissions (ClientPin | None) – The permissions to associate with the token.

  • permissions_rpid (str | None) – The permissions RPID to associate with the token.

Returns:

A PIN/UV token.

Return type:

bytes

get_uv_token(permissions=None, permissions_rpid=None, event=None, on_keepalive=None)[source]

Get a PIN/UV token from the authenticator using built-in UV.

Parameters:
  • permissions (ClientPin | None) – The permissions to associate with the token.

  • permissions_rpid (str | None) – The permissions RPID to associate with the token.

  • event (threading.Event | None) – An optional threading.Event which can be used to cancel the invocation.

  • on_keepalive (Callable[[int], None] | None) – An optional callback to handle keep-alive messages from the authenticator. The function is only called once for consecutive keep-alive messages with the same status.

Returns:

A PIN/UV token.

Return type:

bytes

get_pin_retries()[source]

Get the number of PIN retries remaining.

Returns:

A tuple of the number of PIN attempts remaining until the

Return type:

tuple[int, int | None]

authenticator is locked, and the power cycle state, if available.

get_uv_retries()[source]

Get the number of UV retries remaining.

Returns:

A tuple of the number of UV attempts remaining until the

Return type:

int

authenticator is locked, and the power cycle state, if available.

set_pin(pin)[source]

Set the PIN of the autenticator.

This only works when no PIN is set. To change the PIN when set, use change_pin.

Parameters:

pin (str) – A PIN to set.

Return type:

None

change_pin(old_pin, new_pin)[source]

Change the PIN of the authenticator.

This only works when a PIN is already set. If no PIN is set, use set_pin.

Parameters:
  • old_pin (str) – The currently set PIN.

  • new_pin (str) – The new PIN to set.

Return type:

None

class fido2.client.PinProtocol[source]

Bases: abc.ABC

Helper class that provides a standard way to create an ABC using inheritance.

VERSION: ClassVar[int]
abstractmethod encapsulate(peer_cose_key)[source]

Generates an encapsulation of the public key. Returns the message to transmit and the shared secret.

Parameters:

peer_cose_key (fido2.cose.CoseKey)

Return type:

tuple[Mapping[int, Any], bytes]

abstractmethod encrypt(key, plaintext)[source]

Encrypts data

Parameters:
Return type:

bytes

abstractmethod decrypt(key, ciphertext)[source]

Decrypts encrypted data

Parameters:
Return type:

bytes

abstractmethod authenticate(key, message)[source]

Computes a MAC of the given message.

Parameters:
Return type:

bytes

abstractmethod validate_token(token)[source]

Validates that a token is well-formed. Returns the token, or if invalid, raises a ValueError.

Parameters:

token (bytes)

Return type:

bytes

fido2.client.verify_rp_id(rp_id, origin)[source]

Checks if a Webauthn RP ID is usable for a given origin.

Parameters:
  • rp_id (str) – The RP ID to validate.

  • origin (str) – The origin of the request.

Returns:

True if the RP ID is usable by the origin, False if not.

Return type:

bool

fido2.client.sha256(data)[source]

Produces a SHA256 hash of the input.

Parameters:

data (bytes) – The input data to hash.

Returns:

The resulting hash.

Return type:

bytes

class fido2.client.Aaguid(data)[source]

Bases: bytes

bytes(iterable_of_ints) -> bytes bytes(string, encoding[, errors]) -> bytes bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer bytes(int) -> bytes object of size given by the parameter initialized with null bytes bytes() -> empty bytes object

Construct an immutable array of bytes from:
  • an iterable yielding integers in range(256)

  • a text string encoded using the specified encoding

  • any object implementing the buffer API.

  • an integer

Parameters:

data (bytes)

classmethod parse(value)[source]
Parameters:

value (str)

Return type:

Aaguid

NONE: Aaguid
class fido2.client.AttestationConveyancePreference[source]

Bases: _StringEnum

Enum of strings for WebAuthn types.

Unrecognized values are treated as missing.

NONE = 'none'
INDIRECT = 'indirect'
DIRECT = 'direct'
ENTERPRISE = 'enterprise'
class fido2.client.AttestationObject(_)[source]

Bases: bytes

Binary CBOR encoded attestation object.

Parameters:

_ (bytes) – The binary representation of the attestation object.

Variables:
  • fmt – The type of attestation used.

  • auth_data – The attested authenticator data.

  • att_statement – The attestation statement.

fmt: str
auth_data: AuthenticatorData
att_stmt: Mapping[str, Any]
classmethod create(fmt, auth_data, att_stmt)[source]
Parameters:
Return type:

AttestationObject

classmethod from_ctap1(app_param, registration)[source]

Create an AttestationObject from a CTAP1 RegistrationData instance.

Parameters:
  • app_param (bytes) – SHA256 hash of the RP ID used for the CTAP1 request.

  • registration (RegistrationData) – The CTAP1 registration data.

Returns:

The attestation object, using the “fido-u2f” format.

Return type:

AttestationObject

class fido2.client.AuthenticationExtensionsClientOutputs(outputs={})[source]

Bases: 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.

Parameters:

outputs (Mapping[str, Any])

class fido2.client.AuthenticationResponse[source]

Bases: fido2.utils._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
raw_id: bytes
response: AuthenticatorAssertionResponse
authenticator_attachment: AuthenticatorAttachment | None = None
client_extension_results: AuthenticationExtensionsClientOutputs
type: PublicKeyCredentialType
classmethod from_dict(data)[source]
class fido2.client.AuthenticatorAssertionResponse[source]

Bases: fido2.utils._JsonDataObject

A data class with members also accessible as a JSON-serializable Mapping.

client_data: CollectedClientData
authenticator_data: AuthenticatorData
signature: bytes
user_handle: bytes | None = None
class fido2.client.AuthenticatorAttachment[source]

Bases: _StringEnum

Enum of strings for WebAuthn types.

Unrecognized values are treated as missing.

PLATFORM = 'platform'
CROSS_PLATFORM = 'cross-platform'
class fido2.client.AuthenticatorAttestationResponse[source]

Bases: fido2.utils._JsonDataObject

A data class with members also accessible as a JSON-serializable Mapping.

client_data: CollectedClientData
attestation_object: AttestationObject
class fido2.client.AuthenticatorSelectionCriteria[source]

Bases: fido2.utils._JsonDataObject

A data class with members also accessible as a JSON-serializable Mapping.

authenticator_attachment: AuthenticatorAttachment | None = None
resident_key: ResidentKeyRequirement | None = None
user_verification: UserVerificationRequirement | None = None
require_resident_key: bool | None = False
class fido2.client.CollectedClientData(_)[source]

Bases: bytes

bytes(iterable_of_ints) -> bytes bytes(string, encoding[, errors]) -> bytes bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer bytes(int) -> bytes object of size given by the parameter initialized with null bytes bytes() -> empty bytes object

Construct an immutable array of bytes from:
  • an iterable yielding integers in range(256)

  • a text string encoded using the specified encoding

  • any object implementing the buffer API.

  • an integer

Parameters:

_ (bytes)

class TYPE[source]

Bases: str, enum.Enum

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to ‘utf-8’. errors defaults to ‘strict’.

CREATE = 'webauthn.create'
GET = 'webauthn.get'
type: str
challenge: bytes
origin: str
cross_origin: bool = False
classmethod create(type, challenge, origin, cross_origin=False, **kwargs)[source]
Parameters:
Return type:

CollectedClientData

property b64: str
Return type:

str

property hash: bytes
Return type:

bytes

class fido2.client.PublicKeyCredentialCreationOptions[source]

Bases: fido2.utils._JsonDataObject

A data class with members also accessible as a JSON-serializable Mapping.

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
class fido2.client.PublicKeyCredentialDescriptor[source]

Bases: fido2.utils._JsonDataObject

A data class with members also accessible as a JSON-serializable Mapping.

type: PublicKeyCredentialType
id: bytes
transports: Sequence[AuthenticatorTransport] | None = None
class fido2.client.PublicKeyCredentialRequestOptions[source]

Bases: fido2.utils._JsonDataObject

A data class with members also accessible as a JSON-serializable Mapping.

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
class fido2.client.PublicKeyCredentialType[source]

Bases: _StringEnum

Enum of strings for WebAuthn types.

Unrecognized values are treated as missing.

PUBLIC_KEY = 'public-key'
class fido2.client.RegistrationResponse[source]

Bases: fido2.utils._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
raw_id: bytes
response: AuthenticatorAttestationResponse
authenticator_attachment: AuthenticatorAttachment | None = None
client_extension_results: AuthenticationExtensionsClientOutputs
type: PublicKeyCredentialType
classmethod from_dict(data)[source]
class fido2.client.ResidentKeyRequirement[source]

Bases: _StringEnum

Enum of strings for WebAuthn types.

Unrecognized values are treated as missing.

REQUIRED = 'required'
PREFERRED = 'preferred'
DISCOURAGED = 'discouraged'
class fido2.client.UserVerificationRequirement[source]

Bases: _StringEnum

Enum of strings for WebAuthn types.

Unrecognized values are treated as missing.

REQUIRED = 'required'
PREFERRED = 'preferred'
DISCOURAGED = 'discouraged'
exception fido2.client.ClientError(code, cause=None)[source]

Bases: Exception

Base error raised by clients.

class ERR[source]

Bases: enum.IntEnum

Error codes for ClientError.

OTHER_ERROR = 1
BAD_REQUEST = 2
CONFIGURATION_UNSUPPORTED = 3
DEVICE_INELIGIBLE = 4
TIMEOUT = 5
code
cause = None
exception fido2.client.PinRequiredError(code=ClientError.ERR.BAD_REQUEST, cause='PIN required but not provided')[source]

Bases: ClientError

Raised when a call cannot be completed without providing PIN.

class fido2.client.AssertionSelection(client_data, assertions, extension_results={})[source]

GetAssertion result holding one or more assertions.

Since multiple assertions may be retured by Fido2Client.get_assertion, this result is returned which can be used to select a specific response to get.

Parameters:
get_assertions()[source]

Get the raw AssertionResponses available to inspect before selecting one.

Return type:

Sequence[fido2.ctap2.AssertionResponse]

get_response(index)[source]

Get a single response.

Parameters:

index (int)

Return type:

fido2.webauthn.AuthenticationResponse

class fido2.client.WebAuthnClient[source]

Bases: abc.ABC

Base class for a WebAuthn client, supporting registration and authentication.

abstractmethod make_credential(options, event=None)[source]

Creates a credential.

Parameters:
Return type:

fido2.webauthn.RegistrationResponse

abstractmethod get_assertion(options, event=None)[source]

Get an assertion.

Parameters:
Return type:

AssertionSelection

class fido2.client.UserInteraction[source]

Provides user interaction to the Client.

Users of Fido2Client should subclass this to implement asking the user to perform specific actions, such as entering a PIN or touching their

prompt_up()[source]

Called when the authenticator is awaiting a user presence check.

Return type:

None

request_pin(permissions, rp_id)[source]

Called when the client requires a PIN from the user.

Should return a PIN, or None/Empty to cancel.

Parameters:
Return type:

str | None

request_uv(permissions, rp_id)[source]

Called when the client is about to request UV from the user.

Should return True if allowed, or False to cancel.

Parameters:
Return type:

bool

class fido2.client.ClientDataCollector[source]

Bases: abc.ABC

Provides client data and logic to the Client.

Users should subclass this to implement custom behavior for determining the origin, validating the RP ID, and providing client data for a request.

abstractmethod collect_client_data(options)[source]

Called when the client is preparing a request.

Should return a CollectedClientData object with the client data for the request, as well as the RP ID of the credential.

Parameters:

options (fido2.webauthn.PublicKeyCredentialCreationOptions | fido2.webauthn.PublicKeyCredentialRequestOptions)

Return type:

tuple[fido2.webauthn.CollectedClientData, str]

class fido2.client.DefaultClientDataCollector(origin, verify=verify_rp_id)[source]

Bases: ClientDataCollector

Default implementation of ClientDataProvider.

This implementation uses a fixed origin, it can be subclassed to customize specific behavior.

Parameters:
get_rp_id(options, origin)[source]

Get the RP ID for the given options and origin.

Parameters:
Return type:

str

verify_rp_id(rp_id, origin)[source]

Verify the RP ID for the given origin.

Parameters:
Return type:

None

get_request_type(options)[source]

Get the request type for the given options.

Return type:

str

collect_client_data(options)[source]

Called when the client is preparing a request.

Should return a CollectedClientData object with the client data for the request, as well as the RP ID of the credential.

class fido2.client.Fido2Client(device, client_data_collector, user_interaction=UserInteraction(), extensions=_DEFAULT_EXTENSIONS)[source]

Bases: WebAuthnClient

WebAuthn-like client implementation.

The client allows registration and authentication of WebAuthn credentials against an Authenticator using CTAP (1 or 2).

Parameters:
property info: fido2.ctap2.Info
Return type:

fido2.ctap2.Info

selection(event=None)[source]
Parameters:

event (threading.Event | None)

Return type:

None

make_credential(options, event=None)[source]

Creates a credential.

Parameters:
Return type:

fido2.webauthn.RegistrationResponse

get_assertion(options, event=None)[source]

Get an assertion.

Parameters:
Return type:

AssertionSelection