Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for "direct" attestation #12

Open
wants to merge 2 commits into
base: devel
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 80 additions & 11 deletions soft_webauthn.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,18 @@
applications
"""

import datetime
import json
import os
from base64 import urlsafe_b64encode
from struct import pack
from typing import Dict, Union

from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import NameOID
from fido2 import cbor
from fido2.cose import ES256
from fido2.utils import sha256
Expand Down Expand Up @@ -47,16 +50,18 @@ def cred_as_attested(self):
return AttestedCredentialData.create(
self.aaguid,
self.credential_id,
ES256.from_cryptography_key(self.private_key.public_key()))
ES256.from_cryptography_key(self.private_key.public_key())
)

def create(self, options: Union[CredentialCreationOptions, Dict], origin: str):
"""create credential and return PublicKeyCredential object aka attestation"""

if {'alg': -7, 'type': 'public-key'} not in options['publicKey']['pubKeyCredParams']:
raise ValueError('Requested pubKeyCredParams does not contain supported type')

if ('attestation' in options['publicKey']) and (options['publicKey']['attestation'] not in [None, 'none']):
raise ValueError('Only none attestation supported')
attestation_type = options['publicKey'].get('attestation', 'none')
if attestation_type not in ['none', 'direct', 'indirect']:
raise ValueError('Only none, direct, and indirect attestation supported')

# prepare new key
self.cred_init(options['publicKey']['rp']['id'], options['publicKey']['user']['id'])
Expand All @@ -73,13 +78,9 @@ def create(self, options: Union[CredentialCreationOptions, Dict], origin: str):
sign_count = pack('>I', self.sign_count)
credential_id_length = pack('>H', len(self.credential_id))
cose_key = cbor.encode(ES256.from_cryptography_key(self.private_key.public_key()))
attestation_object = {
'authData':
rp_id_hash + flags + sign_count
+ self.aaguid + credential_id_length + self.credential_id + cose_key,
'fmt': 'none',
'attStmt': {}
}
authenticator_data = rp_id_hash + flags + sign_count + self.aaguid \
+ credential_id_length + self.credential_id + cose_key
attestation_object = self._get_attestation_object(attestation_type, client_data, authenticator_data)

return {
'id': urlsafe_b64encode(self.credential_id),
Expand All @@ -91,6 +92,74 @@ def create(self, options: Union[CredentialCreationOptions, Dict], origin: str):
'type': 'public-key'
}

def _get_attestation_object(self, attestation_type, client_data, authenticator_data):
"""get attestation object for attestation_type, also supports direct/indirect with Chromium published key"""

# indirect is allowed to return same as direct
if attestation_type in ['direct', 'indirect']:
# Generate attestation certificate and private key
att_cert, att_priv_key = self._generate_attestation_certificate_and_key()

# Create a signature using the attestation private key
client_data_hash = sha256(json.dumps(client_data).encode('utf-8'))
signature = att_priv_key.sign(authenticator_data + client_data_hash, ec.ECDSA(hashes.SHA256()))

# Update the attestation object with packed attestation format
attestation_object = {
'authData': authenticator_data,
'fmt': 'packed',
'attStmt': {
'alg': -7, # ES256
'sig': signature,
'x5c': [att_cert.public_bytes(serialization.Encoding.DER)]
}
}
else:
# 'none' attestation
attestation_object = {
'authData': authenticator_data,
'fmt': 'none',
'attStmt': {}
}

return attestation_object

@staticmethod
def _generate_attestation_certificate_and_key():
"""Get a private key for the attestation certificate"""

# Using the example attestation private key from the U2F spec at
# https://fidoalliance.org/specs/fido-u2f-v1.2-ps-20170411/fido-u2f-raw-message-formats-v1.2-ps-20170411.html#registration-example
# As used by Chromium: https://github.com/chromium/chromium/blob/22fb7b6/device/fido/virtual_fido_device.cc#L37
# If you would like to instead generate your own private key, you can use the following code:
# attestation_private_key = ec.generate_private_key(ec.SECP256R1(), default_backend())

key_hex = "f3fccc0d00d8031954f90864d43c247f4bf5f0665c6b50cc17749a27d1cf7664"
attestation_private_key = ec.derive_private_key(int(key_hex, 16), ec.SECP256R1())

# Generate a self-signed attestation certificate
subject = issuer = x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, "US"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Soft-WebAuthn"),
x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, "Authenticator Attestation"),
x509.NameAttribute(NameOID.COMMON_NAME, "softwebauthn.example.com"),
])
attestation_certificate = x509.CertificateBuilder().subject_name(
subject
).issuer_name(
issuer
).public_key(
attestation_private_key.public_key()
).serial_number(
x509.random_serial_number()
).not_valid_before(
datetime.datetime.utcnow()
).not_valid_after(
datetime.datetime.utcnow() + datetime.timedelta(days=365*20)
).sign(attestation_private_key, hashes.SHA256(), default_backend())

return attestation_certificate, attestation_private_key

def get(self, options: Union[CredentialRequestOptions, Dict], origin: str):
"""get authentication credential aka assertion"""

Expand Down
26 changes: 25 additions & 1 deletion tests/test_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,30 @@ def test_create():
assert device.rp_id == 'example.org'


def test_create_direct_attestation():
"""test for internal class check"""

device = SoftWebauthnDevice()
pkcco = copy.deepcopy(PKCCO)
pkcco['publicKey']['attestation'] = 'direct'
attestation = device.create(pkcco, 'https://example.org')
assert attestation
assert device.private_key
assert device.rp_id == 'example.org'


def test_create_indirect_attestation():
"""test that indirect returns same as direct (as allowed by spec))"""

device = SoftWebauthnDevice()
pkcco = copy.deepcopy(PKCCO)
pkcco['publicKey']['attestation'] = 'indirect'
attestation = device.create(pkcco, 'https://example.org')
assert attestation
assert device.private_key
assert device.rp_id == 'example.org'


def test_create_not_supported_type():
"""test for internal class check"""

Expand All @@ -74,7 +98,7 @@ def test_create_not_supported_attestation():

device = SoftWebauthnDevice()
pkcco = copy.deepcopy(PKCCO)
pkcco['publicKey']['attestation'] = 'direct'
pkcco['publicKey']['attestation'] = 'enterprise'

with pytest.raises(ValueError):
device.create(pkcco, 'https://example.org')
Expand Down