Skip to content

FIDO2 Protocol Implementation

Rain Zhang edited this page Nov 6, 2025 · 2 revisions

FIDO2 Protocol Implementation

Table of Contents

  1. Introduction
  2. Architecture Overview
  3. CTAP2 Command Set
  4. CBOR Encoding/Decoding
  5. WebAuthn Data Model
  6. Extension Support
  7. Protocol Flows
  8. Error Handling
  9. Authenticator State Management
  10. Hardware vs Software Authenticators
  11. Implementation Details
  12. Testing and Validation

Introduction

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.

Architecture Overview

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
Loading

Diagram sources

  • fido2/ctap2/base.py
  • fido2/webauthn.py
  • fido2/cbor.py

Section sources

  • fido2/ctap2/init.py
  • fido2/webauthn.py

CTAP2 Command Set

The implementation provides comprehensive support for all major CTAP2 commands, organized into functional categories for ease of use and maintenance.

Core Commands

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()

Advanced Commands

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
Loading

Diagram sources

  • fido2/ctap2/base.py
  • fido2/cbor.py

Section sources

  • fido2/ctap2/base.py
  • fido2/ctap2/base.py

CBOR Encoding/Decoding

The CBOR (Concise Binary Object Representation) implementation provides efficient binary serialization for CTAP2 messages, supporting the subset of CBOR types required for FIDO2 functionality.

Supported Types

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

Encoding Process

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])
Loading

Diagram sources

  • fido2/cbor.py
  • fido2/cbor.py

Decoding Process

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])
Loading

Diagram sources

  • fido2/cbor.py
  • fido2/cbor.py

Section sources

  • fido2/cbor.py

WebAuthn Data Model

The WebAuthn data model implementation provides comprehensive support for all WebAuthn specification data structures, enabling seamless integration with web applications.

Core Data Structures

PublicKeyCredentialCreationOptions

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

PublicKeyCredentialRequestOptions

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

Authenticator Data Structure

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
Loading

Diagram sources

  • fido2/webauthn.py
  • fido2/webauthn.py

Section sources

  • fido2/webauthn.py
  • fido2/webauthn.py

Extension Support

The implementation provides comprehensive support for WebAuthn extensions, enabling advanced authentication scenarios beyond basic credential management.

Available Extensions

Biometric Enrollment (bio.py)

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

PIN/UV Authentication (pin.py)

Provides secure authentication mechanisms:

Protocol Version Features
PIN Protocol v1 Basic PIN authentication
PIN Protocol v2 Enhanced security with HKDF

Large Blob Storage (blob.py)

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

Authenticator Configuration (config.py)

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
Loading

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

Protocol Flows

The implementation supports complete authentication workflows from registration through authentication, with proper error handling and state management.

Registration Flow

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
Loading

Diagram sources

  • fido2/ctap2/base.py
  • fido2/ctap2/extensions.py

Authentication Flow

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
Loading

Diagram sources

  • fido2/ctap2/base.py
  • fido2/ctap2/extensions.py

Section sources

  • tests/test_ctap2.py

Error Handling

The implementation provides comprehensive error handling through the CTAP2 error code system, with proper mapping to Python exceptions.

Error Categories

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

Status Code Mapping

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]
Loading

Diagram sources

  • fido2/ctap.py

Error Handling Patterns

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
        raise

Section sources

  • fido2/ctap.py

Authenticator State Management

The implementation manages authenticator state through the Info object and maintains counters for operation tracking.

State Components

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

Counter Handling

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
Loading

Diagram sources

  • fido2/ctap2/base.py

Section sources

  • fido2/ctap2/base.py

Hardware vs Software Authenticators

The implementation supports both hardware and software authenticators through a unified HID transport layer.

Transport Abstraction

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
Loading

Diagram sources

  • fido2/hid/base.py

Platform Support

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

Implementation Details

Security Considerations

The implementation incorporates multiple security layers:

  1. Cryptographic Protocols: Support for multiple PIN/UV protocols with strong encryption
  2. Input Validation: Comprehensive validation of all inputs and responses
  3. Secure Memory Handling: Proper cleanup of sensitive data
  4. Canonical CBOR: Strict validation of CBOR encoding

Performance Optimizations

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

Extensibility

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
        pass

Section sources

  • fido2/ctap2/extensions.py

Testing and Validation

The implementation includes comprehensive test coverage through the test suite.

Test Coverage Areas

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

Test Execution

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_largeblobs

Section sources

  • tests/test_ctap2.py

Post-Quantum WebAuthn Platform

Getting Started

Architectural Foundations

Cryptography & Security

Authentication Platform

Core Protocol

Flows & Interfaces

Authenticator Capabilities

Server Platform

Frontend Platform

Architecture

Interaction & Utilities

Metadata Service (MDS)

Storage & Data Management

Data Models & Encoding

API Reference

Cross-Platform & HID

Operations & Troubleshooting

Glossary & References

Clone this wiki locally