Last active
December 24, 2024 13:38
-
-
Save itsjfx/b4612d90c210d0a1c77de606a87311ad to your computer and use it in GitHub Desktop.
an example of a python fido2 webauthn client wrapping webauthn.io. fork of https://github.com/Yubico/python-fido2/blob/main/examples/credential.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# Copyright (c) 2024 Yubico AB | |
# All rights reserved. | |
# | |
# Redistribution and use in source and binary forms, with or | |
# without modification, are permitted provided that the following | |
# conditions are met: | |
# | |
# 1. Redistributions of source code must retain the above copyright | |
# notice, this list of conditions and the following disclaimer. | |
# 2. Redistributions in binary form must reproduce the above | |
# copyright notice, this list of conditions and the following | |
# disclaimer in the documentation and/or other materials provided | |
# with the distribution. | |
# | |
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS | |
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE | |
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, | |
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, | |
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; | |
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | |
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT | |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN | |
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE | |
# POSSIBILITY OF SUCH DAMAGE. | |
""" | |
Connects to the first FIDO device found (starts from USB, then looks into NFC), | |
creates a new credential for it, and authenticates the credential. | |
This works with both FIDO 2.0 devices as well as with U2F devices. | |
On Windows, the native WebAuthn API will be used. | |
""" | |
import string | |
import random | |
import requests | |
import logging | |
import sys | |
from fido2.hid import CtapHidDevice | |
from fido2.client import Fido2Client, WindowsClient, UserInteraction, ClientError | |
from fido2.webauthn import PublicKeyCredentialDescriptor | |
from fido2.utils import websafe_decode, websafe_encode | |
from getpass import getpass | |
import ctypes | |
# FIDO2 | |
try: | |
from fido2.pcsc import CtapPcscDevice | |
except ImportError: | |
CtapPcscDevice = None | |
# Handle user interaction via CLI prompts | |
class CliInteraction(UserInteraction): | |
def __init__(self): | |
self._pin = None | |
def prompt_up(self): | |
logging.info('Touch your authenticator device now ...') | |
def request_pin(self, permissions, rd_id): | |
if not self._pin: | |
self._pin = getpass("Enter PIN: ") | |
return self._pin | |
def request_uv(self, permissions, rd_id): | |
logging.info('User Verification required.') | |
return True | |
def enumerate_devices(): | |
for dev in CtapHidDevice.list_devices(): | |
yield dev | |
if CtapPcscDevice: | |
for dev in CtapPcscDevice.list_devices(): | |
yield dev | |
def get_client(**kwargs): | |
"""Locate a CTAP device suitable for use. | |
If running on Windows as non-admin, the predicate check will be skipped and | |
a webauthn.dll based client will be returned. | |
Extra kwargs will be passed to the constructor of Fido2Client. | |
""" | |
if WindowsClient.is_available() and not ctypes.windll.shell32.IsUserAnAdmin(): | |
# Use the Windows WebAuthn API if available, and we're not running as admin | |
return WindowsClient("https://example.com") | |
# Locate a device | |
for device in enumerate_devices(): | |
# Set up a FIDO 2 client using the origin https://example.com | |
client = Fido2Client( | |
device=device, | |
user_interaction=CliInteraction(), | |
**kwargs, | |
) | |
# Check if it is suitable for use | |
if client: | |
return client | |
raise ValueError("No suitable Authenticator found!") | |
# webauthn.io | |
def generate_random_string(length=32): | |
characters = string.ascii_letters + string.digits | |
return ''.join(random.choices(characters, k=length)) | |
COOKIES = { | |
'csrftoken': generate_random_string(32), | |
'sessionid': generate_random_string(32), | |
} | |
session = requests.Session() | |
def response_hook(request, *args, **kwargs): | |
try: | |
request.raise_for_status() | |
except: | |
logging.error('Failed %s request to %s', request.request.method, request.request.url) | |
logging.error('%s', request.text) | |
raise | |
session.hooks = {'response': response_hook} | |
def get_options(username): | |
data = { | |
'username': username, | |
'user_verification': 'required', | |
} | |
response = session.post('https://webauthn.io/authentication/options', cookies=COOKIES, json=data) | |
return response.json() | |
def respond(username, result): | |
data = { | |
'username': username, | |
'response': { | |
'authenticatorAttachment': 'cross-platform', | |
'clientExtensionResults': {}, | |
'id': websafe_encode(result['credentialId']), | |
'rawId': websafe_encode(result['credentialId']), | |
'type': 'public-key', | |
'response': { | |
'clientDataJSON': websafe_encode(result['clientDataJSON']), | |
'authenticatorData': websafe_encode(result['authenticatorData']), | |
'signature': websafe_encode(result['signature']), | |
'userHandle': websafe_encode(result['userHandle']), | |
}, | |
}, | |
} | |
response = session.post('https://webauthn.io/authentication/verification', cookies=COOKIES, json=data) | |
return response.json() | |
def main(username): | |
client = get_client(origin='https://webauthn.io') | |
logging.info('Getting options from webauthn.io') | |
options = get_options(username) | |
request_options = { | |
'rpId': options['rpId'], | |
'challenge': websafe_decode(options['challenge']), | |
'timeout': 600000, | |
'allowCredentials': [PublicKeyCredentialDescriptor(type=cred['type'], id=websafe_decode(cred['id']), transports=cred['transports']) for cred in options['allowCredentials']], | |
'userVerification': options['userVerification'], | |
} | |
logging.debug('Requesting to sign challenge: %s with key(s): %s', options['challenge'], options['allowCredentials']) | |
result = client.get_assertion(request_options) | |
result = result.get_response(0) | |
logging.info('Received credential from device') | |
logging.debug('Credential result: %s', result) | |
logging.info('Responding to webauthn.io') | |
response = respond(username, result) | |
logging.info('Received response: %s', response) | |
assert response['verified'] == True | |
if __name__ == '__main__': | |
import argparse | |
parser = argparse.ArgumentParser() | |
parser.add_argument('username') | |
parser.add_argument('-l', '--log', choices=('debug', 'info', 'warning', 'error', 'critical'), default='info', help="Logging level (default: %(default)s)") | |
args = parser.parse_args() | |
logging.basicConfig(level=getattr(logging, args.log.upper()), format='%(levelname)s\t%(message)s') | |
try: | |
sys.exit(main(args.username)) | |
except ClientError as e: | |
logging.error('FIDO2 error: %s', e.cause) | |
logging.debug(e, exc_info=True) | |
sys.exit(1) | |
except KeyboardInterrupt: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment