authentik.stages.authenticator_webauthn.tasks

MDS Helpers

  1"""MDS Helpers"""
  2
  3from base64 import b64decode
  4from functools import lru_cache
  5from json import loads
  6from pathlib import Path
  7
  8from cryptography import x509
  9from django.core.cache import cache
 10from django.db.transaction import atomic
 11from django.utils.translation import gettext_lazy as _
 12from dramatiq.actor import actor
 13from fido2.attestation import verify_x509_chain
 14from fido2.cose import CoseKey
 15from fido2.mds3 import MetadataBlobPayload, filter_revoked
 16from fido2.utils import websafe_decode
 17
 18from authentik.stages.authenticator_webauthn.models import (
 19    UNKNOWN_DEVICE_TYPE_AAGUID,
 20    WebAuthnDeviceType,
 21)
 22from authentik.tasks.middleware import CurrentTask
 23
 24CACHE_KEY_MDS_NO = "goauthentik.io/stages/authenticator_webauthn/mds_no"
 25AAGUID_BLOB_PATH = Path(__file__).parent / "mds" / "aaguid.json"
 26MDS_BLOB_PATH = Path(__file__).parent / "mds" / "blob.jwt"
 27MDS_CA_PATH = Path(__file__).parent / "mds" / "root-r3.crt"
 28
 29
 30@lru_cache
 31def mds_ca() -> bytes:
 32    """Cache MDS Signature CA, GlobalSign Root CA - R3"""
 33    with open(MDS_CA_PATH, mode="rb") as _raw_root:
 34        return _raw_root.read()
 35
 36
 37# fido2 requires these, but the FIDO Alliance publishes some statements without them.
 38# Fixed upstream in fido2 2.2.2; switch back to fido2.mds3.parse_blob once it is released.
 39MDS_STATEMENT_LIST_DEFAULTS = ("userVerificationDetails", "attachmentHint")
 40
 41
 42def parse_mds_blob(blob: bytes, trust_root: bytes) -> MetadataBlobPayload:
 43    """Verify an MDS3 blob's signature and parse it, tolerating statements without
 44    `userVerificationDetails` or `attachmentHint`."""
 45    message, signature_b64 = blob.rsplit(b".", 1)
 46    header, payload = (loads(websafe_decode(part)) for part in message.split(b"."))
 47
 48    chain = [b64decode(cert) for cert in header.get("x5c", [])] + [trust_root]
 49    verify_x509_chain(chain)
 50    leaf = x509.load_der_x509_certificate(chain[0])
 51    public_key = CoseKey.for_name(header["alg"]).from_cryptography_key(leaf.public_key())
 52    public_key.verify(message, websafe_decode(signature_b64))
 53
 54    for entry in payload.get("entries", []):
 55        statement = entry.get("metadataStatement")
 56        if statement is None:
 57            continue
 58        for key in MDS_STATEMENT_LIST_DEFAULTS:
 59            if statement.get(key) is None:
 60                statement[key] = []
 61
 62    return MetadataBlobPayload.from_dict(payload)
 63
 64
 65@actor(description=_("Background task to import FIDO Alliance MDS blob and AAGUIDs into database."))
 66def webauthn_mds_import(force=False):
 67    """Background task to import FIDO Alliance MDS blob and AAGUIDs into database"""
 68    self = CurrentTask.get_task()
 69    with open(MDS_BLOB_PATH, mode="rb") as _raw_blob:
 70        blob = parse_mds_blob(_raw_blob.read(), mds_ca())
 71    to_create_update = [
 72        WebAuthnDeviceType(
 73            aaguid=UNKNOWN_DEVICE_TYPE_AAGUID,
 74            description="authentik: Unknown devices",
 75        )
 76    ]
 77    to_delete = []
 78
 79    mds_no = cache.get(CACHE_KEY_MDS_NO)
 80    if mds_no != blob.no or force:
 81        for entry in blob.entries:
 82            aaguid = entry.aaguid
 83            if not aaguid:
 84                continue
 85            if not filter_revoked(entry):
 86                to_delete.append(str(aaguid))
 87                continue
 88            metadata = entry.metadata_statement
 89            to_create_update.append(
 90                WebAuthnDeviceType(
 91                    aaguid=str(aaguid),
 92                    description=metadata.description,
 93                    icon=metadata.icon,
 94                )
 95            )
 96    with atomic():
 97        WebAuthnDeviceType.objects.bulk_create(
 98            to_create_update,
 99            update_conflicts=True,
100            update_fields=["description", "icon"],
101            unique_fields=["aaguid"],
102        )
103        WebAuthnDeviceType.objects.filter(aaguid__in=to_delete).delete()
104    if mds_no != blob.no:
105        cache.set(CACHE_KEY_MDS_NO, blob.no)
106
107    with open(AAGUID_BLOB_PATH, mode="rb") as _raw_blob:
108        entries = loads(_raw_blob.read())
109    to_create_update = [
110        WebAuthnDeviceType(
111            aaguid=str(aaguid), description=details.get("name"), icon=details.get("icon_light")
112        )
113        for aaguid, details in entries.items()
114    ]
115    with atomic():
116        WebAuthnDeviceType.objects.bulk_create(
117            to_create_update,
118            update_conflicts=True,
119            update_fields=["description", "icon"],
120            unique_fields=["aaguid"],
121        )
122
123    self.info("Successfully imported FIDO Alliance MDS blobs and AAGUIDs.")
CACHE_KEY_MDS_NO = 'goauthentik.io/stages/authenticator_webauthn/mds_no'
AAGUID_BLOB_PATH = PosixPath('/home/runner/work/authentik/authentik/authentik/stages/authenticator_webauthn/mds/aaguid.json')
MDS_BLOB_PATH = PosixPath('/home/runner/work/authentik/authentik/authentik/stages/authenticator_webauthn/mds/blob.jwt')
MDS_CA_PATH = PosixPath('/home/runner/work/authentik/authentik/authentik/stages/authenticator_webauthn/mds/root-r3.crt')
@lru_cache
def mds_ca() -> bytes:
31@lru_cache
32def mds_ca() -> bytes:
33    """Cache MDS Signature CA, GlobalSign Root CA - R3"""
34    with open(MDS_CA_PATH, mode="rb") as _raw_root:
35        return _raw_root.read()

Cache MDS Signature CA, GlobalSign Root CA - R3

MDS_STATEMENT_LIST_DEFAULTS = ('userVerificationDetails', 'attachmentHint')
def parse_mds_blob(blob: bytes, trust_root: bytes) -> fido2.mds3.MetadataBlobPayload:
43def parse_mds_blob(blob: bytes, trust_root: bytes) -> MetadataBlobPayload:
44    """Verify an MDS3 blob's signature and parse it, tolerating statements without
45    `userVerificationDetails` or `attachmentHint`."""
46    message, signature_b64 = blob.rsplit(b".", 1)
47    header, payload = (loads(websafe_decode(part)) for part in message.split(b"."))
48
49    chain = [b64decode(cert) for cert in header.get("x5c", [])] + [trust_root]
50    verify_x509_chain(chain)
51    leaf = x509.load_der_x509_certificate(chain[0])
52    public_key = CoseKey.for_name(header["alg"]).from_cryptography_key(leaf.public_key())
53    public_key.verify(message, websafe_decode(signature_b64))
54
55    for entry in payload.get("entries", []):
56        statement = entry.get("metadataStatement")
57        if statement is None:
58            continue
59        for key in MDS_STATEMENT_LIST_DEFAULTS:
60            if statement.get(key) is None:
61                statement[key] = []
62
63    return MetadataBlobPayload.from_dict(payload)

Verify an MDS3 blob's signature and parse it, tolerating statements without userVerificationDetails or attachmentHint.

webauthn_mds_import = Actor(<function webauthn_mds_import>, queue_name='default', actor_name='webauthn_mds_import')

Background task to import FIDO Alliance MDS blob and AAGUIDs into database