OWNER_HOSTS (homelab: hub.gabvdl.xyz) answers as the owner without Authelia, for the one device that can't be on the personal tailnet (the Orus Mac). On it the gate takes only the owner's __Host-aia_owner session (7 days, host-only, Strict) — no Remote-User, host token or guest cookie is anyone; without one only the sign-in answers. - remoteaccess/webauthn.py: WebAuthn checked by the hub on `cryptography` (challenge, exact origin, RP ID, user present + verified, signature, counter); a small CBOR reader for new passkeys; fuzzed (80k inputs). - passkeys added only through a one-time link made on the admin host (15 min, one use, hashed, fragment-borne); no mail fallback — Pocket ID was rejected because a mailed code there can enrol a passkey. - Settings → Security: Internet access off (drops every session, back on from the admin host only); pushes on every sign-in and passkey added. - machine paths (worker proxy tokens, tool proxy) refused there. - tests: test_remote_access.py (31), test_webauthn.py (7). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
233 lines
9.7 KiB
Python
233 lines
9.7 KiB
Python
"""Just enough WebAuthn for the owner's passkeys on the internet address — no
|
|
library: ``cryptography`` (already in the image) checks the signatures, and a
|
|
small CBOR reader takes the key out of a new passkey's attestation.
|
|
|
|
What is checked, every time (W3C WebAuthn L3 §7.1/§7.2): the ceremony type,
|
|
the challenge this server issued (once), the page's exact origin, the RP ID
|
|
hash, *user present* and *user verified* (the fingerprint / PIN, not just a
|
|
tap), and the signature with the key stored when the passkey was added.
|
|
Attestation is "none": a passkey is trusted because it was added through a
|
|
one-time link the owner made on the admin host, not because of its maker."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import hashlib
|
|
import hmac
|
|
import json
|
|
import struct
|
|
|
|
from cryptography.exceptions import InvalidSignature
|
|
from cryptography.hazmat.primitives import hashes, serialization
|
|
from cryptography.hazmat.primitives.asymmetric import ec, ed25519, padding, rsa
|
|
|
|
ES256, EDDSA, RS256 = -7, -8, -257
|
|
ALGS = (ES256, EDDSA, RS256)
|
|
|
|
# authenticator data flags
|
|
UP, UV, BE, BS, AT, ED = 0x01, 0x04, 0x08, 0x10, 0x40, 0x80
|
|
|
|
|
|
class WebAuthnError(ValueError):
|
|
pass
|
|
|
|
|
|
def b64u(b: bytes) -> str:
|
|
return base64.urlsafe_b64encode(b).rstrip(b"=").decode()
|
|
|
|
|
|
def unb64u(s: str) -> bytes:
|
|
try:
|
|
return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
|
|
except (ValueError, TypeError) as e:
|
|
raise WebAuthnError(f"bad base64url: {e}") from None
|
|
|
|
|
|
# ── CBOR (RFC 8949), the subset attestations use ─────────────────────────────
|
|
def _cbor(data: bytes, pos: int, depth: int = 0):
|
|
if depth > 8:
|
|
raise WebAuthnError("CBOR nested too deep")
|
|
if pos >= len(data):
|
|
raise WebAuthnError("CBOR truncated")
|
|
ib = data[pos]
|
|
major, info = ib >> 5, ib & 0x1F
|
|
pos += 1
|
|
if info < 24:
|
|
arg = info
|
|
elif info in (24, 25, 26, 27):
|
|
n = 1 << (info - 24)
|
|
if pos + n > len(data):
|
|
raise WebAuthnError("CBOR truncated")
|
|
arg = int.from_bytes(data[pos:pos + n], "big")
|
|
pos += n
|
|
else:
|
|
raise WebAuthnError("CBOR indefinite lengths are not used here")
|
|
if major == 0:
|
|
return arg, pos
|
|
if major == 1:
|
|
return -1 - arg, pos
|
|
if major in (2, 3):
|
|
if pos + arg > len(data):
|
|
raise WebAuthnError("CBOR truncated")
|
|
raw = data[pos:pos + arg]
|
|
if major == 2:
|
|
return raw, pos + arg
|
|
try:
|
|
return raw.decode("utf-8", "strict"), pos + arg
|
|
except UnicodeDecodeError:
|
|
raise WebAuthnError("CBOR text is not UTF-8") from None
|
|
if major == 4:
|
|
if arg > 64:
|
|
raise WebAuthnError("CBOR array too long")
|
|
out = []
|
|
for _ in range(arg):
|
|
v, pos = _cbor(data, pos, depth + 1)
|
|
out.append(v)
|
|
return out, pos
|
|
if major == 5:
|
|
if arg > 64:
|
|
raise WebAuthnError("CBOR map too long")
|
|
m = {}
|
|
for _ in range(arg):
|
|
k, pos = _cbor(data, pos, depth + 1)
|
|
if not isinstance(k, (int, str)) or isinstance(k, bool):
|
|
raise WebAuthnError("CBOR map key is not an int or a text")
|
|
v, pos = _cbor(data, pos, depth + 1)
|
|
m[k] = v
|
|
return m, pos
|
|
if major == 7 and info in (20, 21, 22):
|
|
return {20: False, 21: True, 22: None}[info], pos
|
|
raise WebAuthnError(f"CBOR major type {major} not used here")
|
|
|
|
|
|
def cbor_decode(data: bytes, pos: int = 0):
|
|
return _cbor(data, pos)
|
|
|
|
|
|
# ── keys ─────────────────────────────────────────────────────────────────────
|
|
def cose_to_spki(cose: dict) -> tuple[bytes, int]:
|
|
"""A COSE public key → (SubjectPublicKeyInfo DER, COSE alg)."""
|
|
try:
|
|
return _cose_to_spki(cose)
|
|
except (ValueError, TypeError, OverflowError) as e:
|
|
if isinstance(e, WebAuthnError):
|
|
raise
|
|
raise WebAuthnError(f"bad public key: {e}") from None
|
|
|
|
|
|
def _cose_to_spki(cose: dict) -> tuple[bytes, int]:
|
|
kty, alg = cose.get(1), cose.get(3)
|
|
if alg not in ALGS:
|
|
raise WebAuthnError(f"unsupported algorithm {alg!r}")
|
|
if kty == 2 and alg == ES256: # EC2, P-256
|
|
if cose.get(-1) != 1:
|
|
raise WebAuthnError("EC key is not P-256")
|
|
x, y = cose.get(-2), cose.get(-3)
|
|
if not (isinstance(x, bytes) and isinstance(y, bytes) and len(x) == len(y) == 32):
|
|
raise WebAuthnError("bad EC point")
|
|
key = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), b"\x04" + x + y)
|
|
elif kty == 1 and alg == EDDSA: # OKP, Ed25519
|
|
if cose.get(-1) != 6 or not isinstance(cose.get(-2), bytes):
|
|
raise WebAuthnError("OKP key is not Ed25519")
|
|
key = ed25519.Ed25519PublicKey.from_public_bytes(cose[-2])
|
|
elif kty == 3 and alg == RS256:
|
|
n, e = cose.get(-1), cose.get(-2)
|
|
if not (isinstance(n, bytes) and isinstance(e, bytes)) or len(n) < 256:
|
|
raise WebAuthnError("RSA key missing or under 2048 bits")
|
|
key = rsa.RSAPublicNumbers(int.from_bytes(e, "big"),
|
|
int.from_bytes(n, "big")).public_key()
|
|
else:
|
|
raise WebAuthnError(f"key type {kty!r} does not match algorithm {alg!r}")
|
|
return key.public_bytes(serialization.Encoding.DER,
|
|
serialization.PublicFormat.SubjectPublicKeyInfo), alg
|
|
|
|
|
|
def _verify_sig(spki: bytes, alg: int, sig: bytes, msg: bytes) -> None:
|
|
key = serialization.load_der_public_key(spki)
|
|
try:
|
|
if alg == ES256 and isinstance(key, ec.EllipticCurvePublicKey):
|
|
key.verify(sig, msg, ec.ECDSA(hashes.SHA256()))
|
|
elif alg == EDDSA and isinstance(key, ed25519.Ed25519PublicKey):
|
|
key.verify(sig, msg)
|
|
elif alg == RS256 and isinstance(key, rsa.RSAPublicKey):
|
|
key.verify(sig, msg, padding.PKCS1v15(), hashes.SHA256())
|
|
else:
|
|
raise WebAuthnError("stored key does not match its algorithm")
|
|
except InvalidSignature:
|
|
raise WebAuthnError("bad signature") from None
|
|
|
|
|
|
# ── the two ceremonies ───────────────────────────────────────────────────────
|
|
def _client_data(raw: bytes, kind: str, challenge: bytes, origin: str) -> None:
|
|
try:
|
|
cd = json.loads(raw)
|
|
except ValueError:
|
|
raise WebAuthnError("client data is not JSON") from None
|
|
if not isinstance(cd, dict) or cd.get("type") != kind:
|
|
raise WebAuthnError(f"not a {kind} ceremony")
|
|
if not hmac.compare_digest(unb64u(str(cd.get("challenge") or "")), challenge):
|
|
raise WebAuthnError("challenge mismatch")
|
|
if cd.get("origin") != origin:
|
|
raise WebAuthnError(f"wrong origin {cd.get('origin')!r}")
|
|
if cd.get("crossOrigin"):
|
|
raise WebAuthnError("cross-origin ceremony")
|
|
|
|
|
|
def _auth_data(ad: bytes, rp_id: str) -> tuple[int, int]:
|
|
"""(flags, sign count) once the RP ID hash and UP + UV check out."""
|
|
if len(ad) < 37:
|
|
raise WebAuthnError("authenticator data too short")
|
|
if not hmac.compare_digest(ad[:32], hashlib.sha256(rp_id.encode()).digest()):
|
|
raise WebAuthnError("RP ID mismatch")
|
|
flags = ad[32]
|
|
if not flags & UP:
|
|
raise WebAuthnError("user not present")
|
|
if not flags & UV:
|
|
raise WebAuthnError("user not verified")
|
|
return flags, struct.unpack(">I", ad[33:37])[0]
|
|
|
|
|
|
def verify_registration(*, attestation_object: bytes, client_data_json: bytes,
|
|
challenge: bytes, origin: str, rp_id: str,
|
|
credential_id: bytes) -> dict:
|
|
"""A new passkey → what to store (``id``, ``publicKey``, ``alg``,
|
|
``signCount``, ``aaguid``, ``synced``)."""
|
|
_client_data(client_data_json, "webauthn.create", challenge, origin)
|
|
att, _ = cbor_decode(attestation_object)
|
|
if not isinstance(att, dict) or not isinstance(att.get("authData"), bytes):
|
|
raise WebAuthnError("bad attestation object")
|
|
if att.get("fmt") != "none" and not isinstance(att.get("attStmt"), dict):
|
|
raise WebAuthnError("bad attestation statement")
|
|
ad = att["authData"]
|
|
flags, count = _auth_data(ad, rp_id)
|
|
if not flags & AT or len(ad) < 55:
|
|
raise WebAuthnError("no credential in the attestation")
|
|
aaguid = ad[37:53]
|
|
n = struct.unpack(">H", ad[53:55])[0]
|
|
cid = ad[55:55 + n]
|
|
if len(cid) != n or n == 0 or n > 1023:
|
|
raise WebAuthnError("bad credential id")
|
|
if not hmac.compare_digest(cid, credential_id):
|
|
raise WebAuthnError("credential id mismatch")
|
|
cose, _ = cbor_decode(ad, 55 + n)
|
|
if not isinstance(cose, dict):
|
|
raise WebAuthnError("bad credential public key")
|
|
spki, alg = cose_to_spki(cose)
|
|
return {"id": b64u(cid), "publicKey": b64u(spki), "alg": alg, "signCount": count,
|
|
"aaguid": aaguid.hex(), "synced": bool(flags & BE)}
|
|
|
|
|
|
def verify_assertion(*, cred: dict, authenticator_data: bytes, client_data_json: bytes,
|
|
signature: bytes, challenge: bytes, origin: str, rp_id: str) -> int:
|
|
"""A sign-in with stored passkey ``cred``; its new sign count."""
|
|
_client_data(client_data_json, "webauthn.get", challenge, origin)
|
|
_, count = _auth_data(authenticator_data, rp_id)
|
|
msg = authenticator_data + hashlib.sha256(client_data_json).digest()
|
|
_verify_sig(unb64u(cred["publicKey"]), int(cred["alg"]), signature, msg)
|
|
old = int(cred.get("signCount") or 0)
|
|
if (count or old) and count <= old:
|
|
# A counter that doesn't move forward: a cloned authenticator
|
|
# (synced passkeys report 0 throughout, which passes).
|
|
raise WebAuthnError("sign count went backwards")
|
|
return count
|