implementing-hardware-security-key-authentication

mukul975/Anthropic-Cybersecurity-Skills

Аутентификация по аппаратным ключам FIDO2/WebAuthn.

Звёзды36 321
Авторmukul975
Установок54

Установка

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, and cryptography libraries 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 PublicKeyCredentialRpEntity with 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.com is valid for https://auth.example.com but other.com is not.
  • Initialize Fido2Server: Instantiate the Fido2Server class 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 it
    • direct: Full attestation chain from the authenticator's manufacturer
    • enterprise: 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, and transports (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 (PublicKeyCredentialUserEntity containing user ID, username, and display name), the list of existing credentials for the user (to prevent duplicate registration), and options for user_verification and authenticator_attachment.
  • Authenticator selection criteria:<!-- -->
    • authenticator_attachment: cross-platform restricts to roaming authenticators (USB/NFC keys)
    • authenticator_attachment: platform restricts to built-in authenticators (Touch ID, Windows Hello)
    • Omitting this field allows both types
    • resident_key: required forces creation of a discoverable credential (passkey) stored on the authenticator
    • user_verification: required enforces 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 returns AuthenticatorData containing the credential data to store.
  • Store credential: Persist the credential_data (contains credential_id, public_key as COSE key, and sign_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). Set user_verification based 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_count for 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 userHandle identifies 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 clientPin command.
  • 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

TermDefinition
FIDO2An 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
WebAuthnThe 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)
CTAP2Client 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
AttestationCryptographic proof from the authenticator about its identity and properties; used by the RP to verify the authenticator model and manufacturer
AAGUIDAuthenticator Attestation Globally Unique Identifier; a 128-bit value identifying the authenticator model (e.g., all YubiKey 5 NFC devices share the same AAGUID)
Sign CountA 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 Fido2Server for relying party implementation and CtapHidDevice/Fido2Client for 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(), and verify_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:

  1. Provision YubiKey 5 NFC keys (2 per developer: primary + backup) and distribute in tamper-evident packaging with initial PIN setup instructions
  2. Разверните сервер проверяющей стороны WebAuthn, интегрированный с SSO-провайдером компании (OAuth 2.0 / OpenID Connect), настроенным с authenticator_attachment: cross-platform и user_verification: required
  3. Проводите сессии регистрации, в которых каждый разработчик регистрирует оба ключа в своей учетной записи, при этом проверка аттестации подтверждает подлинные AAGUID YubiKey 5 NFC
  4. Настройте SSO-провайдер так, чтобы он требовал FIDO2 в качестве второго фактора для всех учетных записей разработчиков, с 30-дневным льготным периодом, в течение которого TOTP остается доступным
  5. Реализуйте портал самообслуживания для управления ключами: просмотр зарегистрированных ключей, регистрация сменных ключей и сообщение об утерянных/украденных ключах (что немедленно запускает отзыв учетных данных и повторную регистрацию)
  6. По истечении льготного периода отключите TOTP для учетных записей разработчиков. Отслеживайте журналы аутентификации на предмет попыток отката и оказывайте индивидуальную поддержку оставшимся
  7. Достигните 100% внедрения FIDO2 в команде разработчиков, снизив риск фишинга почти до нуля для доступа к производственной инфраструктуре

Подводные камни:

  • Отсутствие требования регистрации резервного ключа, что приводит к блокировке учетных записей при потере единственного ключа
  • Установка user_verification: discouraged что позволяет любому, кто физически владеет ключом, аутентифицироваться без PIN-кода
  • Забыли проверять счетчик подписи, пропуская атаки с клонированными ключами
  • Отсутствие поддержки NFC для разработчиков, которые в основном работают с планшетов или телефонов
  • Разрешение TOTP в качестве постоянного резервного варианта, что подрывает устойчивость развертывания FIDO2 к фишингу

Сценарий: реализация входа без пароля для клиентского приложения

Контекст: Платформа электронной коммерции хочет предложить вход без пароля на основе passkey своим 2 миллионам пользователей в качестве альтернативы паролям, снижая захват учетных записей в результате credential stuffing и фишинга.

Подход:

  1. Реализуйте WebAuthn с resident_key: required для создания обнаруживаемых учетных данных, позволяющих входить без имени пользователя
  2. Поддерживайте как платформенные аутентификаторы (Touch ID, Windows Hello, биометрия Android), так и роуминговые аутентификаторы (ключи безопасности), опуская authenticator_attachment
  3. Добавьте на страницу входа кнопку "Войти с помощью passkey", которая запускает navigator.credentials.get() с пустым allowCredentials списком, предлагая аутентификатору представить доступные passkey
  4. После успешного создания passkey предложите пользователям создать passkey на втором устройстве для резервирования
  5. Сохраняйте вход по паролю в качестве резервного варианта в период развертывания с постоянным приглашением настроить passkey после каждого входа по паролю
  6. Отслеживайте метрики: доля регистрации passkey (цель 30% в первом квартале), соотношение входов по passkey и по паролю, частоту ошибок аутентификации и инциденты захвата учетных записей
  7. Через 6 месяцев предложите стимулы (увеличенная длительность сессии, сниженная CAPTCHA) пользователям, которые перейдут на аутентификацию только по passkey

Подводные камни:

  • Не обрабатывается случай, когда платформенный аутентификатор пользователя (например, Touch ID на ноутбуке) недоступен и ему нужна кросс-устройственная аутентификация через QR-код
  • Предположение, что у всех пользователей есть устройства с поддержкой биометрии; некоторым потребуется откат к проверке по PIN-коду
  • Не реализовано надлежащее восстановление учетной записи для пользователей, потерявших доступ ко всем зарегистрированным passkey
  • Игнорирование пробелов в совместимости браузеров, особенно в старых версиях Safari на iOS

Формат вывода

## 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 |

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: implementing-hardware-security-key-authentication](https://darkplay.ru/ai/skills/mukul975-anthropic-cybersecurity-skills-implementing-hardware-security-key-authentication)

Описание

Реализует аутентификацию аппаратными ключами безопасности FIDO2/WebAuthn, включая

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

Code Revieweraffaan-m · Эксперт по ревью кода. Проактивно проверяет код на качество, безопасность и…
225 587 ★
Csharp Revieweraffaan-m · Ревьюер C#: конвенции .NET, async, безопасность, nullable-типы, производительность.
225 587 ★
Database Revieweraffaan-m · Специалист PostgreSQL: оптимизация запросов, схемы, безопасность, Supabase.
225 587 ★
Django Revieweraffaan-m · Ревьюер Django: ORM, DRF, миграции, безопасность и production-практики.
225 587 ★
Fastapi Revieweraffaan-m · Проверяет FastAPI-приложения: async, DI, Pydantic, безопасность, OpenAPI и тесты.
225 587 ★
Homelab Architectaffaan-m · Проектирует сети для дома и малой лаборатории с поэтапными изменениями и откатом.
225 587 ★
Java Revieweraffaan-m · Ревьюер Java для Spring Boot и Quarkus: архитектура, JPA, безопасность и конкурентность.
225 587 ★
Network Config Revieweraffaan-m · Проверяет конфигурации роутеров и свитчей: безопасность, ошибки и риски изменений.
225 587 ★
Php Revieweraffaan-m · Ревьюер PHP: PSR-12, типы, Eloquent, безопасность и производительность.
225 587 ★
Python Revieweraffaan-m · Ревьюер Python: PEP 8, идиомы, аннотации типов, безопасность и производительность.
225 587 ★

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации изображений

Генерация изображений

Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты

MagviMagvi
По запросу
5.0
DALL-E 3OpenAI
По подписке
5.0
SupaLabSupalab
По запросу
5.0
Freestyling.aiFreestyling
Есть бесплатный тариф
4.9
ArtGeneration.meArtgeneration
Есть бесплатный тариф
4.9
BigjpgBigjpg
По запросу
4.9
Художник от VKVK
Бесплатно
4.9
Wonderink — ИИ-книги
Есть бесплатный тариф
4.8
Avato AI12ai
По запросу
4.8
Virton AIVirton
По запросу
4.8