FIDO2 硬件密钥认证实现
implementing-hardware-security-key-authentication
使用 python-fido2 库构建 FIDO2/WebAuthn 依赖方服务器,涵盖注册与认证仪式、YubiKey 注册、常驻密钥(可发现凭证/passkey)工作流以及用户验证策略。适用于实现抗网络钓鱼的硬件安全密钥多因素认证(MFA)、构建 WebAuthn 依赖方、为员工批量注册 YubiKey,或将基于密码的认证迁移到 passkey。
- License 许可
- Apache-2.0
- 最近更新
- 2026-08-31
- Stars
- ★ 3.6w
- Forks
- 4.4k
01 前言 Front Matter
- name
- implementing-hardware-security-key-authentication
- tags
- [ "FIDO2", "WebAuthn", "hardware-security-key", "YubiKey", "passkeys", "passwordless-authentication", "CTAP2" ]
- author
- mukul975
- domain
- cybersecurity
- license
- Apache-2.0
- version
- 1.0.0
- nist_csf
- [ "PR.AA-01", "PR.AA-02", "PR.AA-05" ]
- subdomain
- identity-and-access-management
- description
- Builds a FIDO2/WebAuthn relying party server with the python-fido2 library, covering registration and authentication ceremonies, YubiKey enrollment, resident key (discoverable credential/passkey) workflows, and user verification policies. Use when implementing phishing-resistant MFA with hardware security keys, building a WebAuthn relying party, enrolling YubiKeys for a workforce, or migrating password-based authentication to passkeys.
- nist_ai_rmf
- [ "MEASURE-2.7", "MEASURE-2.5", "GOVERN-6.1", "MAP-5.1" ]
- mitre_attack
- [ "T1078", "T1190", "T1059", "T1003", "T1110" ]
- atlas_techniques
- [ "AML.T0051", "AML.T0054", "AML.T0056" ]
02 资源文件 3
- 许可证LICENSE11.0 KB
- 参考文档references/api-reference.md6.3 KB
- 脚本scripts/agent.py37.9 KB
03 SKILL.md 正文
Implementing Hardware Security Key Authentication
When to Use
- Deploying phishing-resistant multi-factor authentication (MFA) using FIDO2 hardware security keys for high-value accounts (administrators, developers, privileged users)
- Building a WebAuthn relying party server that supports both roaming authenticators (USB/NFC security keys) and platform authenticators (Windows Hello, Touch ID, Android biometrics)
- Migrating an existing password-based authentication system to support passkeys (discoverable credentials) as a primary or secondary authentication factor
- Enrolling YubiKey devices for an organization's workforce, including PIN setup, credential registration, and backup key provisioning
- Implementing passwordless authentication flows that comply with NIST SP 800-63B AAL3 (authenticator assurance level 3) requirements
Do not use without HTTPS in production (WebAuthn requires a secure origin), for systems where users cannot physically access a USB/NFC port, or as the sole authentication factor without a recovery mechanism for lost keys.
Prerequisites
- Python 3.10+ with
fido2(python-fido2 >= 2.0.0),flask, andcryptographylibraries installed - HTTPS-enabled web server (WebAuthn API requires secure context; localhost is exempt for development)
- FIDO2-compatible hardware security key (YubiKey 5 Series, SoloKeys, Titan Security Key) or platform authenticator
- Modern web browser supporting the WebAuthn API (Chrome 67+, Firefox 60+, Safari 14+, Edge 79+)
- Understanding of public key cryptography, challenge-response protocols, and HTTP session management
Workflow
Step 1: Relying Party Server Configuration
Configure the WebAuthn relying party (RP) identity and server:
- Define RP identity: Create a
PublicKeyCredentialRpEntitywith the relying party name (display name shown to users) and RP ID (the effective domain of the application). The RP ID must be a registrable domain suffix of the origin -- for example,example.comis valid forhttps://auth.example.combutother.comis not. - Initialize Fido2Server: Instantiate the
Fido2Serverclass from the python-fido2 library with the RP entity. The server handles challenge generation, attestation verification, and assertion validation. - Configure attestation preference: Set the attestation conveyance preference to control whether the server requests proof of the authenticator's identity:
none: No attestation requested (simplest, recommended for most deployments)indirect: Attestation may be provided but CA may anonymize itdirect: Full attestation chain from the authenticator's manufacturerenterprise: Device-identifying attestation for managed environments
- Session management: Configure server-side sessions to store WebAuthn state between the begin and complete phases of registration/authentication ceremonies. Use secure, httponly cookies with SameSite=Strict.
- Credential storage: Design the database schema to store credential records:
credential_id(binary),public_key(COSE key),sign_count(uint32 for clone detection),user_id,created_at,last_used,display_name, andtransports(USB, NFC, BLE, internal).
Step 2: Registration Ceremony (Credential Creation)
Implement the WebAuthn registration flow to create new credentials:
- Begin registration: Call
server.register_begin()with the user entity (PublicKeyCredentialUserEntitycontaining user ID, username, and display name), the list of existing credentials for the user (to prevent duplicate registration), and options foruser_verificationandauthenticator_attachment. - Authenticator selection criteria:
authenticator_attachment: cross-platformrestricts to roaming authenticators (USB/NFC keys)authenticator_attachment: platformrestricts to built-in authenticators (Touch ID, Windows Hello)- Omitting this field allows both types
resident_key: requiredforces creation of a discoverable credential (passkey) stored on the authenticatoruser_verification: requiredenforces PIN or biometric verification on the authenticator
- Client-side ceremony: The browser calls
navigator.credentials.create()with the options from the server. The authenticator generates a new key pair, stores the private key in its secure element, and returns the public key, credential ID, attestation object, and client data JSON. - Complete registration: Call
server.register_complete()with the saved state and the client response. The server verifies the attestation signature, extracts the credential public key and ID, and returnsAuthenticatorDatacontaining the credential data to store. - Store credential: Persist the
credential_data(containscredential_id,public_keyas COSE key, andsign_count) to the database associated with the user account.
Step 3: Authentication Ceremony (Assertion)
Implement the WebAuthn authentication flow to verify credentials:
- Begin authentication: Call
server.authenticate_begin()with the list of registered credentials for the user (or omit for discoverable credential flows where the authenticator identifies the user). Setuser_verificationbased on the assurance level required. - Client-side assertion: The browser calls
navigator.credentials.get()with the server options. The authenticator locates the matching credential, performs user verification if required, increments the signature counter, and signs the challenge with the private key. - Complete authentication: Call
server.authenticate_complete()with the saved state, registered credentials, and the client response. The server verifies the assertion signature against the stored public key and validates the signature counter has incremented (clone detection). - Update sign count: After successful authentication, update the stored
sign_countfor the credential. If the new sign count is not greater than the stored value, the key may have been cloned -- flag this as a security event. - Discoverable credential flow: For passwordless authentication, the user does not need to enter a username first. The authenticator presents all discoverable credentials for the RP ID, and the selected credential's
userHandleidentifies the user.
Step 4: YubiKey Enrollment and Management
Implement organizational YubiKey provisioning workflows:
- PIN initialization: Before first use, a YubiKey requires a FIDO2 PIN (minimum 4 characters, 8 retries before lockout). Guide users through PIN setup using the Yubico Authenticator application or programmatically via the CTAP2
clientPincommand. - Primary key enrollment: Register the user's primary YubiKey with their account. Store the credential with a user-friendly label (e.g., "USB-A YubiKey - Office") and the authenticator's AAGUID for device identification.
- Backup key enrollment: Require users to register at least two security keys. The backup key should be stored separately (home, safety deposit box). Both keys must be registered to the same account so either can authenticate.
- Key attestation verification: For enterprise deployments, verify the attestation certificate chain to confirm the key is a genuine YubiKey from Yubico. Compare the AAGUID against Yubico's published values to identify the exact model.
- Key lifecycle management: Implement administrative functions to list a user's registered keys, revoke compromised keys, force re-enrollment, and audit key usage patterns (last authentication time, total authentications).
Step 5: Passkey Migration Strategy
Plan and execute migration from passwords to passkeys:
- Phased rollout: Begin with voluntary passkey enrollment alongside existing password authentication. Track adoption metrics (percentage of users with passkeys, percentage of logins using passkeys vs. passwords).
- Credential upgrade flow: When a user authenticates with a password, prompt them to register a passkey. Present the WebAuthn registration dialog immediately after successful password login to minimize friction.
- Cross-device passkeys: Support synced passkeys (passkeys stored in platform credential managers like iCloud Keychain, Google Password Manager, or 1Password) for users who do not have hardware security keys. These provide phishing resistance without requiring dedicated hardware.
- Account recovery: Design recovery flows for users who lose all their security keys:
- Recovery codes generated at enrollment time (printed, stored in password manager)
- Supervised re-enrollment by an administrator after identity verification
- Temporary time-limited password login with mandatory key re-enrollment
- Never allow recovery via email or SMS alone, as these defeat the phishing resistance
- Password deprecation timeline: After passkey adoption exceeds the target threshold, enforce passkey-only authentication for high-privilege accounts first, then expand to all accounts. Maintain password as a fallback during the transition window.
- Monitoring and metrics: Track registration success rates, authentication failure rates (wrong key, timeout, cancelled), mean time to authenticate, and the ratio of passkey to password logins.
Key Concepts
| Term | Definition |
|---|---|
| FIDO2 | An umbrella term for the combination of the W3C WebAuthn API and the FIDO Alliance CTAP2 protocol, enabling passwordless and phishing-resistant authentication using public key cryptography |
| WebAuthn | The W3C Web Authentication API that allows web applications to create and use public key credentials via navigator.credentials.create() (registration) and navigator.credentials.get() (authentication) |
| CTAP2 | Client to Authenticator Protocol version 2; the protocol used by the browser (client) to communicate with external authenticators over USB, NFC, or BLE |
| Relying Party (RP) | The web application or service that requests authentication; identified by its RP ID (a domain) and RP name (display string) |
| Discoverable Credential (Passkey) | A credential stored on the authenticator that can be enumerated without the RP providing a credential ID, enabling username-less authentication flows |
| Attestation | Cryptographic proof from the authenticator about its identity and properties; used by the RP to verify the authenticator model and manufacturer |
| AAGUID | Authenticator Attestation Globally Unique Identifier; a 128-bit value identifying the authenticator model (e.g., all YubiKey 5 NFC devices share the same AAGUID) |
| Sign Count | A monotonically increasing counter maintained by the authenticator and included in each assertion; used by the RP to detect cloned authenticators |
| User Verification (UV) | Local authentication on the authenticator itself (PIN, fingerprint, face recognition) that proves the person holding the authenticator is the legitimate owner |
Tools & Systems
- python-fido2: Yubico's official Python library (v2.0+) providing
Fido2Serverfor relying party implementation andCtapHidDevice/Fido2Clientfor direct authenticator communication over USB - YubiKey 5 Series: Yubico hardware security keys supporting FIDO2/CTAP2, U2F, PIV, OpenPGP, and OTP; available in USB-A, USB-C, NFC, and Nano form factors
- py_webauthn: Duo Labs' Python WebAuthn library providing
generate_registration_options(),verify_registration_response(),generate_authentication_options(), andverify_authentication_response()functions - Yubico Authenticator: Desktop and mobile application for managing YubiKey FIDO2 credentials, setting PINs, and viewing registered accounts
- WebAuthn.io / demo.yubico.com: Online testing tools for verifying WebAuthn registration and authentication flows against real authenticators
Common Scenarios
Scenario: Deploying FIDO2 MFA for a Development Team
Context: A software company wants to replace TOTP-based MFA with hardware security keys for its 50-person development team. Developers have root access to production infrastructure and are high-value targets for phishing attacks. The company has standardized on YubiKey 5 NFC.
Approach:
- Provision YubiKey 5 NFC keys (2 per developer: primary + backup) and distribute in tamper-evident packaging with initial PIN setup instructions
- Deploy the WebAuthn relying party server integrated with the company's SSO (OAuth 2.0 / OpenID Connect) provider, configured with
authenticator_attachment: cross-platformanduser_verification: required - Run enrollment sessions where each developer registers both keys to their account, with attestation verification confirming genuine YubiKey 5 NFC AAGUIDs
- Configure the SSO provider to require FIDO2 as the second factor for all developer accounts, with a 30-day grace period where TOTP remains available
- Implement a self-service portal for key management: view registered keys, register replacement keys, and report lost/stolen keys (which triggers immediate credential revocation and re-enrollment)
- After the grace period, disable TOTP for developer accounts. Monitor authentication logs for any fallback attempts and provide 1:1 support for remaining holdouts
- Achieve 100% FIDO2 adoption for the development team, reducing phishing risk to near-zero for production infrastructure access
Pitfalls:
- Not requiring backup key enrollment, leading to account lockouts when a single key is lost
- Setting
user_verification: discouragedwhich allows anyone who physically possesses the key to authenticate without a PIN - Forgetting to validate the sign counter, missing cloned key attacks
- Not supporting NFC for developers who primarily work from tablets or phones
- Allowing TOTP as a permanent fallback, which undermines the phishing resistance of the FIDO2 deployment
Scenario: Implementing Passwordless Login for a Customer-Facing Application
Context: An e-commerce platform wants to offer passkey-based passwordless login to its 2 million users as an alternative to passwords, reducing account takeover from credential stuffing and phishing.
Approach:
- Implement WebAuthn with
resident_key: requiredto create discoverable credentials that enable username-less login - Support both platform authenticators (Touch ID, Windows Hello, Android biometrics) and roaming authenticators (security keys) by omitting
authenticator_attachment - Add a "Sign in with a passkey" button to the login page that triggers
navigator.credentials.get()with an emptyallowCredentialslist, prompting the authenticator to present available passkeys - After successful passkey creation, prompt users to create a passkey on a second device for redundancy
- Maintain password login as a fallback during the rollout period, with a persistent prompt encouraging passkey setup after each password login
- Track metrics: passkey registration rate (target 30% in first quarter), passkey vs. password login ratio, authentication failure rates, and account takeover incidents
- After 6 months, offer incentives (extended session duration, reduced CAPTCHA) for users who switch to passkey-only authentication
Pitfalls:
- Not handling the case where a user's platform authenticator (e.g., laptop Touch ID) is unavailable and they need cross-device authentication via QR code
- Assuming all users have biometric-capable devices; some will need to fall back to PIN-based verification
- Not implementing proper account recovery for users who lose access to all registered passkeys
- Ignoring browser compatibility gaps, particularly in older Safari versions on iOS
Output Format
## FIDO2 Deployment Report
**Application**: auth.example.com
**RP ID**: example.com
**Date**: 2026-03-19
### Enrollment Summary
- **Total Users**: 50
- **Users with Primary Key**: 50 (100%)
- **Users with Backup Key**: 47 (94%)
- **Authenticator Models**: YubiKey 5 NFC (48), YubiKey 5C NFC (2)
### Authentication Metrics (Last 30 Days)
- **Total Authentications**: 12,847
- **FIDO2 Authentications**: 12,203 (95.0%)
- **TOTP Fallback**: 644 (5.0%) -- grace period active
- **Mean Authentication Time**: 2.3 seconds
- **Authentication Failures**: 127 (0.99%)
- User cancelled: 89
- Timeout: 23
- Invalid signature: 12
- Sign count regression (possible clone): 3
### Security Events
- **Lost Key Reports**: 2
- User A: primary key lost 2026-03-12, revoked, backup promoted, new backup enrolled
- User B: backup key damaged 2026-03-15, revoked, replacement enrolled
### Credential Details
| User | Key Label | AAGUID | Registered | Last Used | Sign Count |
|------|-----------|--------|------------|-----------|------------|
| alice | YubiKey Primary | 2fc0579f... | 2026-02-15 | 2026-03-19 | 847 |
| alice | YubiKey Backup | 2fc0579f... | 2026-02-15 | 2026-03-01 | 12 |
| bob | YubiKey Primary | 2fc0579f... | 2026-02-16 | 2026-03-19 | 631 |
04 同仓库更多 Skills
SLSA 构建来源验证
verifying-build-provenance-with-slsa-sigstore
使用 Sigstore 的 cosign(verify、verify-attestation、verify-blob-attestation)和 slsa-verifier(verify-artifact)验证工件签名和 SLSA 来源(provenance),强制校验 keyless OIDC 构建者身份和源仓库是否符合 SLSA Build 级别。适用于 CI/CD 中部署工件前、消费第三方证明时、建立 SLSA Build L3 管道,或在事件响应或准入控制期间确认来源的场景。
TPM 测量启动验证
validating-tpm-measured-boot-attestation
使用 tpm2-tools 验证 TPM 2.0 测量启动(measured boot)的完整性和远程证明:读取 PCR(tpm2_pcrread)、重放启动事件日志、生成并检查签名报价(tpm2_quote/tpm2_checkquote),以及将机密封印(seal)到 PCR 策略。适用于确认系统已启动可信固件/内核以实现零信任(Zero Trust)设备状态、通过 PCR 漂移检测启动链篡改,或构建黄金值基线用于机群(fleet)证明。
备份完整性验证
validating-backup-integrity-for-recovery
通过加密哈希验证、自动化恢复测试、损坏检测和可恢复性检查来验证备份完整性,确认备份对于灾难恢复和勒索软件响应是可靠的。适用于在依赖备份进行恢复之前、构建备份后验证管道、审计备份基础设施以满足合规要求,或检查不可变/air-gapped(气隙)备份是否存在静默损坏或篡改的场景。
KAPE Windows 取证收集
triaging-windows-with-kape
运行 KAPE(Kroll Artifact Parser and Extractor),通过 Targets 收集目标取证工件(注册表配置单元、$MFT、事件日志、prefetch、浏览器数据),并使用封装 Eric Zimmerman 的 EZ Tools(PECmd、MFTECmd、RECmd)的 Modules 进行解析。适用于事件遏制/分诊早期阶段——此时完整磁盘镜像不切实际,但需要快速获得可采信、可解析的 Windows 工件集,包括大规模远程收集。
SSVC 漏洞优先级分诊
triaging-vulnerabilities-with-ssvc-framework
使用 CISA 的 Stakeholder-Specific Vulnerability Categorization(SSVC,利益相关方特定漏洞分类)决策树对漏洞进行分诊和优先级排序,权衡利用状态(通过 CISA KEV 目录和 FIRST EPSS API)、技术影响、自动化程度和任务普遍性,输出 Track/Track*/Attend/Act 决策。适用于对漏洞扫描结果(OpenVAS、Nessus、Qualys)进行优先级排序以制定修复计划,而不局限于原始 CVSS 分数的场景。
安全事件初步分诊
triaging-security-incident
使用 NIST SP 800-61r3 和 SANS PICERL 框架对安全事件进行初步分诊,分类事件类型、按业务影响分配优先级,并路由到相应的响应团队。适用于 SIEM/EDR 告警需要人工分类、并发告警必须确定优先级,或用户报告或威胁情报 IOC 匹配需要初步事件分类的场景。