CNSA-276-FP/test2.py

85 lines
2.6 KiB
Python
Raw Normal View History

2024-04-30 20:59:17 -04:00
from fido2.hid import CtapHidDevice
from fido2.server import Fido2Server
from fido2.webauthn import PublicKeyCredentialRpEntity, UserVerificationRequirement, PublicKeyCredentialUserEntity, \
PublicKeyCredentialCreationOptions
from fido2.client import Fido2Client
import os
# Initialize the FIDO2 server
rp = PublicKeyCredentialRpEntity("example.com", "Example Corporation")
server = Fido2Server(rp)
# User information
user_id = os.urandom(32)
user = PublicKeyCredentialUserEntity("testuser", b"Example Corporation")
# Create a registration request
registration_data = PublicKeyCredentialCreationOptions(rp, user, os.urandom(32), rp)
state = server.register_begin(user,
challenge=os.urandom(32),
user_verification=UserVerificationRequirement.PREFERRED)
# List FIDO devices
devices = list(CtapHidDevice.list_devices())
if not devices:
print("No FIDO devices found")
exit(1)
# Select the first device (you could add logic to choose a device)
device = devices[0]
print("Using device:", device)
# Simulate client processing and generate a response (normally done in browser)
client = Fido2Client(device, "https://example.com")
attestation_object, client_data = client.make_credential(registration_data)
# Setup Relying Party
rp = PublicKeyCredentialRpEntity("example.com", name="Example Corporation")
server = Fido2Server(rp)
# User information
user_id = os.urandom(32)
user = {"id": user_id, "name": "user@example.com", "displayName": "Example User"}
# Create a registration request
registration_data, state = server.register_begin({
"id": user_id,
"name": user['name'],
"displayName": user['displayName']
},
challenge=os.urandom(32),
user_verification="preferred")
# Use the client to create a credential
attestation_object, client_data = client.make_credential(registration_data)
# Complete registration
authenticator_data = server.register_complete(
state,
client_data,
attestation_object
)
print("Registration complete")
print("Authenticator data:", authenticator_data.credential_data)
# Authentication process
auth_data, state = server.authenticate_begin(user_id)
# Simulate client processing and generate a response
assertion = client.get_assertion(auth_data["publicKey"])
assertion_response = assertion.get_response(0)
# Complete authentication
credentials, user_handle = server.authenticate_complete(
state,
auth_data["allowCredentials"],
assertion_response.client_data,
assertion_response.authenticator_data,
assertion_response.signature
)
print("Authentication complete")
print("User handle:", user_handle)
print("Credentials:", credentials)