Input Validation and Error Handling - FeitianTech/postquantum-webauthn-platform GitHub Wiki
Input Validation and Error Handling
Table of Contents
- Introduction
- CBOR Message Validation
- WebAuthn Parameter Validation
- Route Handler Input Sanitization
- Secure Error Handling Practices
- Exception Handling in Authentication Flows
- Attestation Statement Validation
- Security Event Logging
- Best Practices and Recommendations
Introduction
The Post-Quantum WebAuthn Platform implements comprehensive input validation and secure error handling mechanisms to protect against various attack vectors while maintaining robust functionality. This documentation covers the validation of CBOR-encoded CTAP2 messages, WebAuthn ceremony parameters, user input sanitization in route handlers, and secure error handling practices that prevent information leakage.
The platform employs multiple layers of validation including protocol-level CBOR parsing, WebAuthn parameter verification, input sanitization at the route level, and structured error handling with appropriate logging. These mechanisms work together to provide defense-in-depth protection against malformed inputs, injection attacks, and malicious authenticator responses.
CBOR Message Validation
CBOR Implementation Security
The CBOR (Concise Binary Object Representation) implementation in fido2/cbor.py provides robust validation against malformed inputs and buffer overflow conditions through careful parsing and boundary checking.
flowchart TD
A["CBOR Input"] --> B["decode() Function"]
B --> C{"Valid CBOR?"}
C --> |Yes| D["Parse Successfully"]
C --> |No| E["Raise ValueError"]
D --> F["Validate Length"]
F --> G{"Correct Length?"}
G --> |Yes| H["Return Parsed Data"]
G --> |No| I["Raise ValueError"]
E --> J["Generic Error Response"]
I --> J
Diagram sources
Buffer Overflow Protection
The CBOR implementation includes several mechanisms to prevent buffer overflow conditions:
- Length Validation: The
decode()function ensures that no extraneous data follows the encoded object - Type Safety: Strict type checking prevents incorrect data interpretation
- Boundary Checking: All integer values are validated against their expected ranges
- Memory Management: Proper cleanup and resource management
Section sources
CBOR Type Validation
The implementation supports a minimal subset of CBOR types required for FIDO 2 CTAP, with strict validation:
classDiagram
class CborType {
+Union[int, bool, str, bytes, Sequence, Mapping]
}
class SerializationFunctions {
+dump_int(data, mt) bytes
+dump_bool(data) bytes
+dump_list(data) bytes
+dump_dict(data) bytes
+dump_bytes(data) bytes
+dump_text(data) bytes
}
class DeserializationFunctions {
+load_int(ai, data) Tuple[int, bytes]
+load_bool(ai, data) Tuple[bool, bytes]
+load_bytes(ai, data) Tuple[bytes, bytes]
+load_text(ai, data) Tuple[str, bytes]
+load_array(ai, data) Tuple[Sequence, bytes]
+load_map(ai, data) Tuple[Mapping, bytes]
}
CborType --> SerializationFunctions
CborType --> DeserializationFunctions
Diagram sources
Section sources
WebAuthn Parameter Validation
Challenge Length Validation
The WebAuthn implementation enforces strict validation of challenge parameters to ensure cryptographic strength and prevent replay attacks.
sequenceDiagram
participant Client as "Client Request"
participant Validator as "Parameter Validator"
participant WebAuthn as "WebAuthn Module"
participant Logger as "Security Logger"
Client->>Validator : Submit challenge parameter
Validator->>Validator : Check challenge length
Validator->>Validator : Validate format
alt Challenge Valid
Validator->>WebAuthn : Pass validation
WebAuthn->>Client : Accept challenge
else Challenge Invalid
Validator->>Logger : Log security event
Validator->>Client : Return error 400
end
Diagram sources
RP ID Format Validation
The platform implements comprehensive RP (Relying Party) ID validation to prevent domain spoofing and ensure proper isolation:
| Validation Type | Requirement | Implementation |
|---|---|---|
| Format | Valid hostname/domain | determine_rp_id() function |
| Length | Minimum 1 character | String validation |
| Characters | Alphanumeric and dots | Character set restriction |
| Case Sensitivity | Lowercase normalization | Automatic conversion |
Public Key Parameter Validation
Public key parameters undergo rigorous validation to ensure cryptographic correctness:
flowchart TD
A["Public Key Input"] --> B["Algorithm Validation"]
B --> C{"Supported Algorithm?"}
C --> |Yes| D["Key Format Check"]
C --> |No| E["Reject Algorithm"]
D --> F{"Valid Format?"}
F --> |Yes| G["Cryptographic Validation"]
F --> |No| H["Reject Format"]
G --> I{"Valid Key?"}
I --> |Yes| J["Accept Key"]
I --> |No| K["Reject Key"]
E --> L["Error Response"]
H --> L
K --> L
Diagram sources
Section sources
Route Handler Input Sanitization
Advanced Route Validation
The advanced route handlers implement comprehensive input validation with multiple layers of protection:
classDiagram
class AdvancedValidation {
+_validate_binary_value(value) bytes
+_validate_credential_parameters(params) bool
+_sanitize_user_input(input) str
+_check_allowed_keys(obj, keys) bool
}
class InputSanitization {
+_coerce_bytes(value) bytes
+_coerce_optional_bool(value) bool
+_select_first(mapping, keys) Any
+_normalize_algorithm_name(name) str
}
class ErrorHandling {
+_handle_validation_error(error) dict
+_log_security_event(event) void
+_return_error_response(status, message) Response
}
AdvancedValidation --> InputSanitization
AdvancedValidation --> ErrorHandling
Diagram sources
Binary Value Validation
The platform implements strict binary value validation to prevent injection attacks:
| Validation Method | Purpose | Implementation |
|---|---|---|
| Base64 Decoding | Validate encoding format | Multiple decoder attempts |
| Hexadecimal Validation | Check hex format | Regex pattern matching |
| Length Constraints | Enforce minimum sizes | Boundary checking |
| Format Detection | Auto-detect input format | Format-specific parsers |
JSON Payload Validation
JSON payloads undergo comprehensive validation to prevent injection attacks:
sequenceDiagram
participant Request as "HTTP Request"
participant Parser as "JSON Parser"
participant Validator as "Payload Validator"
participant Sanitizer as "Input Sanitizer"
participant Logger as "Security Logger"
Request->>Parser : JSON Payload
Parser->>Validator : Parse JSON
Validator->>Validator : Check structure
Validator->>Validator : Validate types
Validator->>Sanitizer : Sanitize inputs
Sanitizer->>Sanitizer : Remove dangerous chars
alt Valid Payload
Sanitizer->>Request : Process request
else Invalid Payload
Sanitizer->>Logger : Log validation failure
Sanitizer->>Request : Return error 400
end
Diagram sources
Section sources
Secure Error Handling Practices
Information Leakage Prevention
The platform implements strict error handling to prevent information leakage about internal system state:
flowchart TD
A["Error Occurs"] --> B["Generic Error Message"]
B --> C["Log Security Event"]
C --> D["Return Standardized Response"]
D --> E["Client Receives Generic Error"]
F["Sensitive Error"] --> G["Generic Wrapper"]
G --> H["Standardized Format"]
H --> I["Client Safety"]
Standardized Error Responses
All error responses follow a consistent format to prevent information disclosure:
| Error Field | Content | Example |
|---|---|---|
error |
Generic error message | "Invalid request format" |
status |
HTTP status code | 400, 404, 500 |
timestamp |
Error occurrence time | ISO 8601 format |
request_id |
Unique request identifier | UUID format |
Exception Handling Patterns
The platform uses consistent exception handling patterns across all route handlers:
sequenceDiagram
participant Route as "Route Handler"
participant Exception as "Exception Handler"
participant Logger as "Security Logger"
participant Response as "Error Response"
Route->>Route : Process request
Route->>Exception : Exception occurs
Exception->>Logger : Log security event
Exception->>Exception : Catch specific exceptions
Exception->>Response : Generate generic response
Response->>Route : Return standardized error
Diagram sources
Section sources
Exception Handling in Authentication Flows
Registration Flow Error Handling
The registration flow implements comprehensive error handling for authentication ceremonies:
classDiagram
class RegistrationHandler {
+register_begin() Response
+register_complete() Response
+_validate_registration_data() bool
+_handle_attestation_errors() dict
+_log_registration_attempt() void
}
class AuthenticationHandler {
+authenticate_begin() Response
+authenticate_complete() Response
+_validate_assertion_data() bool
+_handle_authentication_errors() dict
+_log_authentication_attempt() void
}
class ErrorHandler {
+_generic_error_handler() dict
+_security_event_logger() void
+_rate_limit_check() bool
}
RegistrationHandler --> ErrorHandler
AuthenticationHandler --> ErrorHandler
Diagram sources
Authentication Flow Validation
Authentication flows include multiple validation checkpoints:
| Validation Stage | Checks Performed | Error Handling |
|---|---|---|
| Challenge Validation | Length, format, uniqueness | Immediate rejection |
| Signature Verification | Cryptographic validity | Graceful failure |
| Counter Validation | Monotonic increase | Session termination |
| RP ID Verification | Domain matching | Access denial |
State Management in Error Conditions
The platform maintains proper state management during error conditions:
stateDiagram-v2
[*] --> Initializing
Initializing --> Validating : Start ceremony
Validating --> Processing : Valid inputs
Validating --> Error : Invalid inputs
Processing --> Success : Complete successfully
Processing --> Error : Processing failed
Error --> Cleanup : Handle error
Cleanup --> [*] : Clean up state
Success --> [*] : Finalize
Diagram sources
Section sources
Attestation Statement Validation
Malicious Authenticator Protection
The platform implements comprehensive validation of attestation statements to protect against malicious authenticators:
flowchart TD
A["Attestation Statement"] --> B["Format Validation"]
B --> C{"Valid Format?"}
C --> |Yes| D["Signature Verification"]
C --> |No| E["Reject Statement"]
D --> F{"Valid Signature?"}
F --> |Yes| G["Certificate Chain Validation"]
F --> |No| H["Signature Failure"]
G --> I{"Chain Valid?"}
I --> |Yes| J["Root Certificate Check"]
I --> |No| K["Chain Failure"]
J --> L{"Trusted Root?"}
L --> |Yes| M["Accept Attestation"]
L --> |No| N["Root Failure"]
E --> O["Security Log"]
H --> O
K --> O
N --> O
O --> P["Error Response"]
Diagram sources
Certificate Validation
Certificate validation includes multiple security checks:
| Validation Step | Purpose | Implementation |
|---|---|---|
| Certificate Format | Ensure valid X.509 format | ASN.1 parsing |
| Signature Verification | Validate certificate signatures | Cryptographic verification |
| Chain Completeness | Verify complete certificate chain | Path validation |
| Trust Anchor Verification | Check against trusted roots | Root store comparison |
| Expiration Checking | Ensure certificates are valid | Date validation |
Algorithm Validation
Cryptographic algorithm validation prevents downgrade attacks:
classDiagram
class AlgorithmValidator {
+validate_algorithm(algorithm) bool
+check_minimum_strength(algorithm) bool
+verify_post_quantum(algorithm) bool
+log_unsupported_algorithm(algorithm) void
}
class SupportedAlgorithms {
+PQC_ALGORITHMS Set~int~
+CLASSICAL_ALGORITHMS Set~int~
+LEGACY_ALGORITHMS Set~int~
}
class SecurityPolicy {
+minimum_strength int
+allowed_algorithms Set~int~
+block_legacy bool
}
AlgorithmValidator --> SupportedAlgorithms
AlgorithmValidator --> SecurityPolicy
Diagram sources
Section sources
Security Event Logging
Structured Logging Implementation
The platform implements comprehensive security event logging to track potential attacks and system anomalies:
sequenceDiagram
participant Handler as "Route Handler"
participant Logger as "Security Logger"
participant Storage as "Log Storage"
participant Monitor as "Security Monitor"
Handler->>Logger : Log security event
Logger->>Logger : Format event data
Logger->>Storage : Store structured log
Storage->>Monitor : Trigger alerts
Monitor->>Monitor : Analyze patterns
Log Content Structure
Security logs include comprehensive information for forensic analysis:
| Field | Description | Example |
|---|---|---|
timestamp |
Event occurrence time | 2024-01-15T10:30:45Z |
event_type |
Type of security event | "INVALID_CHALLENGE" |
source_ip |
Client IP address | 192.168.1.100 |
request_id |
Unique request identifier | UUID |
user_agent |
Client user agent | Browser fingerprint |
payload |
Request payload details | Sanitized request data |
Rate Limiting and Anomaly Detection
The platform implements rate limiting and anomaly detection:
flowchart TD
A["Incoming Request"] --> B["Rate Limiter"]
B --> C{"Within Limits?"}
C --> |Yes| D["Process Request"]
C --> |No| E["Block Request"]
D --> F["Monitor for Anomalies"]
F --> G{"Anomalous Pattern?"}
G --> |Yes| H["Alert Security Team"]
G --> |No| I["Continue Monitoring"]
E --> J["Log Blocking Event"]
H --> K["Security Incident"]
I --> L["Normal Operation"]
Section sources
Best Practices and Recommendations
Input Validation Guidelines
- Defense in Depth: Implement multiple layers of validation
- Fail Safe: Always fail on validation errors rather than attempting to recover
- Consistent Error Handling: Use standardized error responses across all endpoints
- Logging: Log all validation failures for security monitoring
Security Hardening Recommendations
- Regular Updates: Keep all dependencies updated to latest secure versions
- Monitoring: Implement comprehensive monitoring for validation failures
- Incident Response: Establish procedures for responding to validation bypass attempts
- Testing: Regularly test validation mechanisms with fuzzing tools
Performance Considerations
- Validation Order: Place cheapest validations first
- Caching: Cache validation results where appropriate
- Resource Limits: Implement limits on processing resources
- Timeouts: Set reasonable timeouts for validation operations
The Post-Quantum WebAuthn Platform demonstrates comprehensive input validation and secure error handling through its layered approach to security. By validating inputs at multiple levels, implementing robust error handling, and maintaining detailed security logs, the platform provides strong protection against various attack vectors while maintaining usability and performance.