-
Notifications
You must be signed in to change notification settings - Fork 0
FIDO2 Protocol Implementation
- Introduction
- Architecture Overview
- CTAP2 Command Set
- CBOR Encoding/Decoding
- WebAuthn Data Model
- Extension Support
- Protocol Flows
- Error Handling
- Authenticator State Management
- Hardware vs Software Authenticators
- Implementation Details
- Testing and Validation
The FIDO2/CTAP2 protocol implementation provides a comprehensive framework for implementing WebAuthn standards in Python. This implementation supports both software and hardware authenticators through a unified interface, offering complete CTAP2 command coverage, CBOR-based message encoding, and extensive extension support.
The implementation is designed around the FIDO Alliance's Client-to-Authenticator Protocol (CTAP2) specification, providing robust support for modern authentication scenarios including biometric enrollment, PIN/UV authentication, large blob storage, and authenticator configuration.
The FIDO2 implementation follows a layered architecture that separates concerns between protocol handling, data modeling, and transport mechanisms.
graph TB
subgraph "Application Layer"
WebAuthn[WebAuthn API]
Extensions[Extension Handlers]
end
subgraph "Protocol Layer"
CTAP2[CTAP2 Base]
Commands[CTAP2 Commands]
CBOR[CBOR Encoder/Decoder]
end
subgraph "Transport Layer"
HID[HID Transport]
Platform[Platform Devices]
Hardware[Hardware Authenticators]
end
subgraph "Data Layer"
WebAuthnData[WebAuthn Data Models]
Attestation[Attestation Objects]
AuthenticatorData[Authenticator Data]
end
WebAuthn --> CTAP2
Extensions --> CTAP2
CTAP2 --> Commands
Commands --> CBOR
Commands --> HID
HID --> Platform
HID --> Hardware
WebAuthnData --> Attestation
WebAuthnData --> AuthenticatorData
CTAP2 --> WebAuthnData
Diagram sources
- fido2/ctap2/base.py
- fido2/webauthn.py
- fido2/cbor.py
Section sources
- fido2/ctap2/init.py
- fido2/webauthn.py
The implementation provides comprehensive support for all major CTAP2 commands, organized into functional categories for ease of use and maintenance.
| Command | Purpose | Implementation |
|---|---|---|
MAKE_CREDENTIAL |
Register new credentials | make_credential() |
GET_ASSERTION |
Authenticate using existing credentials | get_assertion() |
GET_INFO |
Retrieve authenticator capabilities | get_info() |
CLIENT_PIN |
Manage PIN/UV authentication | client_pin() |
RESET |
Erase all credentials and PIN | reset() |
GET_NEXT_ASSERTION |
Retrieve additional assertions | get_next_assertion() |
| Command | Purpose | Implementation |
|---|---|---|
BIO_ENROLLMENT |
Biometric enrollment management | bio_enrollment() |
CREDENTIAL_MGMT |
Resident credential management | credential_mgmt() |
LARGE_BLOBS |
Large blob storage operations | large_blobs() |
CONFIG |
Authenticator configuration | config() |
sequenceDiagram
participant Client as "Client Application"
participant CTAP2 as "CTAP2 Handler"
participant Device as "Authenticator Device"
participant CBOR as "CBOR Encoder"
Client->>CTAP2 : make_credential(rp, user, params)
CTAP2->>CBOR : encode command data
CBOR-->>CTAP2 : CBOR encoded payload
CTAP2->>Device : send_cbor(MAKE_CREDENTIAL, data)
Device-->>CTAP2 : CBOR response
CTAP2->>CBOR : decode response
CBOR-->>CTAP2 : decoded data
CTAP2-->>Client : AttestationResponse
Diagram sources
- fido2/ctap2/base.py
- fido2/cbor.py
Section sources
- fido2/ctap2/base.py
- fido2/ctap2/base.py
The CBOR (Concise Binary Object Representation) implementation provides efficient binary serialization for CTAP2 messages, supporting the subset of CBOR types required for FIDO2 functionality.
The implementation supports the following CBOR types:
| Type Category | Support Level | Description |
|---|---|---|
| Primitive Types | Full | Boolean, integers, text strings, byte strings |
| Collection Types | Full | Arrays, maps/dictionaries |
| Extended Types | Partial | Custom types for specific FIDO2 use cases |
flowchart TD
Start([Input Data]) --> TypeCheck{Determine Type}
TypeCheck --> |Boolean| BoolEncode[Dump Boolean]
TypeCheck --> |Integer| IntEncode[Dump Integer]
TypeCheck --> |String| TextEncode[Dump Text]
TypeCheck --> |Bytes| BytesEncode[Dump Bytes]
TypeCheck --> |Mapping| DictEncode[Dump Dictionary]
TypeCheck --> |Sequence| ListEncode[Dump List]
BoolEncode --> Serialize[Serialize to Bytes]
IntEncode --> Serialize
TextEncode --> Serialize
BytesEncode --> Serialize
DictEncode --> Serialize
ListEncode --> Serialize
Serialize --> Output([CBOR Byte String])
Diagram sources
- fido2/cbor.py
- fido2/cbor.py
The decoding process handles CBOR deserialization with validation for canonical form compliance:
flowchart TD
Input([CBOR Bytes]) --> Header[Parse Header Byte]
Header --> TypeClass{Type Class}
TypeClass --> |0| IntDecode[Load Integer]
TypeClass --> |1| NIntDecode[Load Negative Integer]
TypeClass --> |2| BytesDecode[Load Bytes]
TypeClass --> |3| TextDecode[Load Text]
TypeClass --> |4| ArrayDecode[Load Array]
TypeClass --> |5| MapDecode[Load Map]
TypeClass --> |7| BoolDecode[Load Boolean]
IntDecode --> Validate[Validate Canonical Form]
NIntDecode --> Validate
BytesDecode --> Validate
TextDecode --> Validate
ArrayDecode --> Validate
MapDecode --> Validate
BoolDecode --> Validate
Validate --> Output([Decoded Object])
Diagram sources
- fido2/cbor.py
- fido2/cbor.py
Section sources
- fido2/cbor.py
The WebAuthn data model implementation provides comprehensive support for all WebAuthn specification data structures, enabling seamless integration with web applications.
The creation options define the parameters for registering new credentials:
| Parameter | Type | Purpose |
|---|---|---|
rp |
PublicKeyCredentialRpEntity |
Relying party information |
user |
PublicKeyCredentialUserEntity |
User identity information |
challenge |
bytes |
Cryptographic challenge |
pub_key_cred_params |
Sequence[PublicKeyCredentialParameters] |
Accepted key types |
timeout |
Optional[int] |
Operation timeout |
exclude_credentials |
Optional[Sequence[PublicKeyCredentialDescriptor]] |
Credentials to exclude |
authenticator_selection |
Optional[AuthenticatorSelectionCriteria] |
Authenticator preferences |
attestation |
Optional[AttestationConveyancePreference] |
Attestation preference |
extensions |
Optional[Mapping[str, Any]] |
Extension parameters |
Authentication options for verifying existing credentials:
| Parameter | Type | Purpose |
|---|---|---|
challenge |
bytes |
Cryptographic challenge |
timeout |
Optional[int] |
Operation timeout |
rp_id |
Optional[str] |
Relying party identifier |
allow_credentials |
Optional[Sequence[PublicKeyCredentialDescriptor]] |
Allowed credentials |
user_verification |
Optional[UserVerificationRequirement] |
Verification requirement |
extensions |
Optional[Mapping[str, Any]] |
Extension parameters |
The authenticator data encapsulates authentication metadata:
classDiagram
class AuthenticatorData {
+bytes rp_id_hash
+FLAG flags
+int counter
+Optional~AttestedCredentialData~ credential_data
+Optional~Mapping~ extensions
+is_user_present() bool
+is_user_verified() bool
+is_backup_eligible() bool
+is_backed_up() bool
+is_attested() bool
+has_extension_data() bool
}
class FLAG {
UP : 0x01
UV : 0x04
BE : 0x08
BS : 0x10
AT : 0x40
ED : 0x80
}
class AttestedCredentialData {
+Aaguid aaguid
+bytes credential_id
+CoseKey public_key
+create(aaguid, cred_id, pubkey) AttestedCredentialData
+unpack_from(data) Tuple~AttestedCredentialData, bytes~
}
AuthenticatorData --> FLAG
AuthenticatorData --> AttestedCredentialData
Diagram sources
- fido2/webauthn.py
- fido2/webauthn.py
Section sources
- fido2/webauthn.py
- fido2/webauthn.py
The implementation provides comprehensive support for WebAuthn extensions, enabling advanced authentication scenarios beyond basic credential management.
Supports fingerprint enrollment and management:
| Feature | Capability |
|---|---|
| Enrollment | Multi-sample fingerprint capture |
| Template Management | CRUD operations on fingerprint templates |
| Sensor Information | Device capability discovery |
| Feedback | Real-time capture quality feedback |
Provides secure authentication mechanisms:
| Protocol Version | Features |
|---|---|
| PIN Protocol v1 | Basic PIN authentication |
| PIN Protocol v2 | Enhanced security with HKDF |
Enables storage of arbitrary data associated with credentials:
| Operation | Purpose |
|---|---|
| Read | Retrieve stored data |
| Write | Store new data |
| Delete | Remove existing data |
| Encryption | AES-GCM encryption with AEAD |
Allows runtime configuration of authenticator behavior:
| Setting | Control |
|---|---|
| Enterprise Attestation | Enable/disable enterprise attestation |
| Always UV | Require user verification for assertions |
| PIN Length Policy | Configure minimum PIN requirements |
classDiagram
class ExtensionProcessor {
<<abstract>>
+permissions ClientPin.PERMISSION
+prepare_inputs(pin_token) dict
+prepare_outputs(response, pin_token) dict
}
class RegistrationExtensionProcessor {
+prepare_inputs(pin_token) dict
+prepare_outputs(response, pin_token) dict
}
class AuthenticationExtensionProcessor {
+prepare_inputs(selected, pin_token) dict
+prepare_outputs(response, pin_token) dict
}
class HmacSecretExtension {
+NAME "hmac-secret"
+is_supported(ctap) bool
+make_credential(ctap, options, protocol) Processor
+get_assertion(ctap, options, protocol) Processor
}
class LargeBlobExtension {
+NAME "largeBlobKey"
+is_supported(ctap) bool
+make_credential(ctap, options, protocol) Processor
+get_assertion(ctap, options, protocol) Processor
}
ExtensionProcessor <|-- RegistrationExtensionProcessor
ExtensionProcessor <|-- AuthenticationExtensionProcessor
ExtensionProcessor <|-- HmacSecretExtension
ExtensionProcessor <|-- LargeBlobExtension
Diagram sources
- fido2/ctap2/extensions.py
- fido2/ctap2/extensions.py
Section sources
- fido2/ctap2/bio.py
- fido2/ctap2/pin.py
- fido2/ctap2/blob.py
- fido2/ctap2/config.py
The implementation supports complete authentication workflows from registration through authentication, with proper error handling and state management.
sequenceDiagram
participant Client as "Client Application"
participant Server as "Web Server"
participant Authenticator as "Authenticator"
participant Extensions as "Extension Handlers"
Client->>Server : Begin Registration
Server-->>Client : PublicKeyCredentialCreationOptions
Client->>Authenticator : make_credential(options)
Authenticator->>Extensions : Process Extensions
Extensions-->>Authenticator : Extension Results
Authenticator-->>Client : AttestationResponse
Client->>Server : Send Attestation
Server->>Server : Verify Attestation
Server-->>Client : Registration Complete
Diagram sources
- fido2/ctap2/base.py
- fido2/ctap2/extensions.py
sequenceDiagram
participant Client as "Client Application"
participant Server as "Web Server"
participant Authenticator as "Authenticator"
participant Extensions as "Extension Handlers"
Client->>Server : Begin Authentication
Server-->>Client : PublicKeyCredentialRequestOptions
Client->>Authenticator : get_assertion(options)
Authenticator->>Extensions : Process Extensions
Extensions-->>Authenticator : Extension Results
Authenticator-->>Client : AssertionResponse
Client->>Server : Send Assertion
Server->>Server : Verify Assertion
Server-->>Client : Authentication Complete
Diagram sources
- fido2/ctap2/base.py
- fido2/ctap2/extensions.py
Section sources
- tests/test_ctap2.py
The implementation provides comprehensive error handling through the CTAP2 error code system, with proper mapping to Python exceptions.
| Category | Range | Examples |
|---|---|---|
| Success | 0x00 | Operation completed successfully |
| Client Errors | 0x01-0x06 | Invalid parameters, timeouts |
| Authenticator Errors | 0x21-0x40 | User verification required, PIN errors |
| Vendor Errors | 0xF0-0xFF | Device-specific errors |
flowchart TD
CTAPError[CTAP Error Code] --> Success{Success?}
Success --> |0x00| SuccessOp[Operation Successful]
Success --> |Other| ErrorType{Error Type}
ErrorType --> |0x01-0x06| ClientError[Client Error]
ErrorType --> |0x21-0x40| AuthError[Authenticator Error]
ErrorType --> |0xF0-0xFF| VendorError[Vendor Error]
ClientError --> ClientException[CtapError.ERR]
AuthError --> AuthException[CtapError.ERR]
VendorError --> VendorException[CtapError.ERR]
Diagram sources
- fido2/ctap.py
The implementation follows consistent error handling patterns:
# Example error handling pattern
try:
response = ctap.make_credential(...)
except CtapError as e:
if e.code == CtapError.ERR.PIN_INVALID:
# Handle PIN authentication failure
pass
elif e.code == CtapError.ERR.USER_ACTION_TIMEOUT:
# Handle timeout scenarios
pass
else:
# Handle other errors
raiseSection sources
- fido2/ctap.py
The implementation manages authenticator state through the Info object and maintains counters for operation tracking.
| Component | Purpose | Management |
|---|---|---|
| Capabilities | Supported features | Retrieved via GET_INFO |
| Counters | Operation tracking | Incremented per operation |
| Permissions | Access control | Managed via PIN/UV tokens |
| Configuration | Runtime settings | Modified via CONFIG command |
Authenticator counters track operation history and prevent replay attacks:
stateDiagram-v2
[*] --> Initialized
Initialized --> Registration : make_credential()
Registration --> Assertion : get_assertion()
Assertion --> Registration : make_credential()
Assertion --> Assertion : get_next_assertion()
Assertion --> Reset : reset()
Reset --> Initialized : All data cleared
note right of Registration : Counter++ for each credential
note right of Assertion : Counter++ for each assertion
Diagram sources
- fido2/ctap2/base.py
Section sources
- fido2/ctap2/base.py
The implementation supports both hardware and software authenticators through a unified HID transport layer.
classDiagram
class CtapHidConnection {
<<abstract>>
+read_packet() bytes
+write_packet(data) void
+close() void
}
class FileCtapHidConnection {
+handle int
+descriptor HidDescriptor
+read_packet() bytes
+write_packet(data) void
+close() void
}
class WinCtapHidConnection {
+device_handle HANDLE
+read_packet() bytes
+write_packet(data) void
+close() void
}
class MacCtapHidConnection {
+io_service IOHIDDeviceRef
+read_packet() bytes
+write_packet(data) void
+close() void
}
CtapHidConnection <|-- FileCtapHidConnection
CtapHidConnection <|-- WinCtapHidConnection
CtapHidConnection <|-- MacCtapHidConnection
Diagram sources
- fido2/hid/base.py
| Platform | Implementation | Features |
|---|---|---|
| Windows | WinCtapHidConnection | Native HID API |
| macOS | MacCtapHidConnection | IOHIDManager |
| Linux | LinuxCtapHidConnection | libudev |
| FreeBSD | FreeBSDCtapHidConnection | HIDAPI |
| OpenBSD | OpenBsdCtapHidConnection | HIDAPI |
| NetBSD | NetBSDCtapHidConnection | HIDAPI |
Section sources
- fido2/hid/base.py
The implementation incorporates multiple security layers:
- Cryptographic Protocols: Support for multiple PIN/UV protocols with strong encryption
- Input Validation: Comprehensive validation of all inputs and responses
- Secure Memory Handling: Proper cleanup of sensitive data
- Canonical CBOR: Strict validation of CBOR encoding
| Optimization | Benefit | Implementation |
|---|---|---|
| Lazy Loading | Reduced memory usage | On-demand parsing |
| Batch Operations | Improved throughput | Bulk operations for large blobs |
| Connection Pooling | Reduced latency | Reuse of transport connections |
| Compression | Bandwidth savings | ZLIB compression for large blobs |
The modular design enables easy extension:
# Custom extension example
class CustomExtension(Ctap2Extension):
NAME = "custom-extension"
def is_supported(self, ctap):
return self.NAME in ctap.info.extensions
def make_credential(self, ctap, options, pin_protocol):
# Custom registration logic
pass
def get_assertion(self, ctap, options, pin_protocol):
# Custom authentication logic
passSection sources
- fido2/ctap2/extensions.py
The implementation includes comprehensive test coverage through the test suite.
| Test Area | Coverage | Purpose |
|---|---|---|
| Protocol Commands | All CTAP2 commands | Functional testing |
| Error Conditions | All error scenarios | Robustness testing |
| Extension Support | All extensions | Feature validation |
| Transport Layer | All platforms | Cross-platform compatibility |
| Data Validation | Input/output validation | Security testing |
Tests can be executed using the standard Python testing framework:
# Run CTAP2 tests
python -m unittest tests.test_ctap2
# Run extension tests
python -m unittest tests.test_bioenroll
python -m unittest tests.test_clientpin
python -m unittest tests.test_largeblobsSection sources
- tests/test_ctap2.py