From e98bb36c93ef5f38908cad62f2f7347837e337a9 Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Wed, 11 Nov 2026 21:00:37 +1100 Subject: [PATCH 1/8] fido: per-user passkey agent (aurora-passkeyd) behind vault = user aurora-fidod can forward each CTAP2 request to the passkey agent of seat0's active user instead of answering from /var/lib/aurora-fido. The agent runs as the user, keeps that user's credential records and calls /dev/sep-key as the user. The two speak a small CBOR protocol on a SOCK_SEQPACKET socket in the user's runtime dir (request, keepalive 'user present', cancel, response); both sides check the peer's uid. With no active local user or no agent, getInfo still answers and everything else is refused. U2F is not forwarded in this mode. The agent's vault key needs a key under the user's own key bag (sep-key interface 4); until that kernel interface exists the agent refuses to start instead of keeping a host-readable key. Default stays vault = system. Tests: tests/test_agent.py (10, stub enclave: passkey register + username-less sign-in through the agent, user isolation, no active user, agent down, wrong peer uid both ways, cancel and disconnect reach the enclave wait, interface-4 refusal). Co-Authored-By: Claude Opus 5.5 --- .gitignore | 2 + docs/fido.md | 26 +++- fido/90-aurora-passkeyd.preset | 3 + fido/Makefile | 14 +- fido/aurora-fido.conf | 4 + fido/aurora-passkeyd.in | 9 ++ fido/aurora-passkeyd.service | 20 +++ fido/aurora_fido/agent.py | 234 +++++++++++++++++++++++++++++++++ fido/aurora_fido/agentproto.py | 58 ++++++++ fido/aurora_fido/daemon.py | 21 ++- fido/aurora_fido/remote.py | 118 +++++++++++++++++ fido/tests/test_agent.py | 212 +++++++++++++++++++++++++++++ 12 files changed, 714 insertions(+), 7 deletions(-) create mode 100644 fido/90-aurora-passkeyd.preset create mode 100644 fido/aurora-passkeyd.in create mode 100644 fido/aurora-passkeyd.service create mode 100644 fido/aurora_fido/agent.py create mode 100644 fido/aurora_fido/agentproto.py create mode 100644 fido/aurora_fido/remote.py create mode 100644 fido/tests/test_agent.py diff --git a/.gitignore b/.gitignore index 7cee743..f813824 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,5 @@ __pycache__/ /fido/aurora-fido /luks/aurora-sep-fde /luks/pam_aurora_sep_fde.so +/fido/aurora-passkeyd +/fido/aurora-passkeyd.service.out diff --git a/docs/fido.md b/docs/fido.md index a4baa0a..b0ce93e 100644 --- a/docs/fido.md +++ b/docs/fido.md @@ -153,6 +153,30 @@ available when per-user, password-keyed key bags land (below). token with the credential-management permission takes a touch when it is issued. +### Per-user credentials (preview, `vault = user`) + +With `[authenticator] vault = user`, aurora-fidod keeps only the uhid device +and the CTAPHID framing. It forwards each CTAP2 request to `aurora-passkeyd` +(a user unit) of the user who owns the active local session on seat0, the +same user the hidraw `uaccess` ACL follows. That agent keeps the user's +credential records in `$XDG_DATA_HOME/aurora-passkeys` and makes the +`/dev/sep-key` calls as the user. + +- The two talk over `$XDG_RUNTIME_DIR/aurora-passkeys/ctap.sock` + (SOCK_SEQPACKET): one request per connection, with "user present" + keepalives and cancel passed both ways. +- aurora-fidod checks that the socket's peer is that user. The agent accepts + only root (aurora-fidod) and its own user. +- With no active local user, or no agent running, nothing is signed: + getInfo still answers, and every other command gets + `CTAP2_ERR_OPERATION_DENIED`. +- U2F is not forwarded in this mode. + +The agent's vault key is sealed to a key under the user's own key bag +(`/dev/sep-key` interface 4). So the records cannot be read while the user +is logged out, and the credential keys sign for nobody else, root included. +On a kernel without interface 4 the agent refuses to start. + ### Existing credentials (migration from 0.1) aurora-fido 0.1 checked the touch in the daemon (fprintd, or a polkit @@ -326,7 +350,7 @@ security key. ## Tests - make -C fido check # unit tests, no root, no hardware + make -C fido check # unit tests, no root, no hardware (agent tests: Linux) sudo make -C fido check-uhid # real uhid device: libfido2, OpenSSH, pam_u2f, cryptenroll make -C fido test/aurora-fido-seal && sudo make -C fido check-seal diff --git a/fido/90-aurora-passkeyd.preset b/fido/90-aurora-passkeyd.preset new file mode 100644 index 0000000..1bf6045 --- /dev/null +++ b/fido/90-aurora-passkeyd.preset @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: MIT +# Per-user passkey agent: opt in, installed off (see [authenticator] vault in aurora-fido.conf). +disable aurora-passkeyd.service diff --git a/fido/Makefile b/fido/Makefile index 4d69e4f..84315e5 100644 --- a/fido/Makefile +++ b/fido/Makefile @@ -15,17 +15,19 @@ PREFIX ?= /usr LIBEXECDIR ?= $(PREFIX)/libexec/aurora-fido PYDIR ?= $(PREFIX)/lib/aurora-fido UNITDIR ?= $(PREFIX)/lib/systemd/system +USERUNITDIR ?= $(PREFIX)/lib/systemd/user UDEVRULESDIR ?= $(PREFIX)/lib/udev/rules.d SYSCONFDIR ?= /etc DOCDIR ?= $(PREFIX)/share/doc/aurora-fido BINDIR ?= $(PREFIX)/bin PRESETDIR ?= $(PREFIX)/lib/systemd/system-preset +USERPRESETDIR ?= $(PREFIX)/lib/systemd/user-preset SEAL := aurora-fido-seal SRC := aurora-fido-seal.c ../luks/sep-seal.c ../luks/sep-seal.h PY := $(wildcard aurora_fido/*.py) -all: $(SEAL) aurora-fidod aurora-fido aurora-fido.service.out +all: $(SEAL) aurora-fidod aurora-fido aurora-passkeyd aurora-fido.service.out aurora-passkeyd.service.out $(SEAL): $(SRC) $(CC) $(CFLAGS) $(DEPS_CFLAGS) -fPIE -pie -Wl,-z,relro,-z,now -o $@ \ @@ -39,11 +41,11 @@ test/$(SEAL): $(SRC) # Generated from the install paths: always regenerated (FORCE), so that # `make install LIBEXECDIR=...` after a plain `make` never ships stale paths. -aurora-fidod aurora-fido: %: %.in FORCE +aurora-fidod aurora-fido aurora-passkeyd: %: %.in FORCE sed -e 's|@PYDIR@|$(PYDIR)|' -e 's|@LIBEXECDIR@|$(LIBEXECDIR)|' -e 's|@DOCDIR@|$(DOCDIR)|' $< > $@ chmod 755 $@ -aurora-fido.service.out: aurora-fido.service FORCE +aurora-fido.service.out aurora-passkeyd.service.out: %.service.out: %.service FORCE sed 's|@LIBEXECDIR@|$(LIBEXECDIR)|' $< > $@ FORCE: @@ -51,6 +53,7 @@ FORCE: # Unit tests: no root, no hardware (software keys with a scripted enclave touch). check: $(PYTHON) tests/test_ctap.py + $(PYTHON) tests/test_agent.py # As root: the real uhid device with libfido2, OpenSSH, pam_u2f, cryptenroll. check-uhid: @@ -63,6 +66,9 @@ check-seal: test/$(SEAL) install: all install -Dm755 aurora-fidod $(DESTDIR)$(LIBEXECDIR)/aurora-fidod install -Dm755 aurora-fido $(DESTDIR)$(BINDIR)/aurora-fido + install -Dm755 aurora-passkeyd $(DESTDIR)$(LIBEXECDIR)/aurora-passkeyd + install -Dm644 aurora-passkeyd.service.out $(DESTDIR)$(USERUNITDIR)/aurora-passkeyd.service + install -Dm644 90-aurora-passkeyd.preset $(DESTDIR)$(USERPRESETDIR)/90-aurora-passkeyd.preset install -Dm644 90-aurora-fido.preset $(DESTDIR)$(PRESETDIR)/90-aurora-fido.preset install -Dm755 $(SEAL) $(DESTDIR)$(LIBEXECDIR)/$(SEAL) for f in $(PY); do install -Dm644 $$f $(DESTDIR)$(PYDIR)/$$f; done @@ -72,6 +78,6 @@ install: all install -Dm644 ../docs/fido.md $(DESTDIR)$(DOCDIR)/fido.md clean: - rm -rf $(SEAL) test aurora-fidod aurora-fido aurora-fido.service.out aurora_fido/__pycache__ tests/__pycache__ + rm -rf $(SEAL) test aurora-fidod aurora-fido aurora-passkeyd aurora-fido.service.out aurora-passkeyd.service.out aurora_fido/__pycache__ tests/__pycache__ .PHONY: all check check-uhid check-seal install clean FORCE diff --git a/fido/aurora-fido.conf b/fido/aurora-fido.conf index 56ac232..59d8e17 100644 --- a/fido/aurora-fido.conf +++ b/fido/aurora-fido.conf @@ -33,6 +33,10 @@ attestation = self max_resident = 256 # Answer CTAP1/U2F requests too. u2f = yes +# Whose credentials: "system" keeps them in /var/lib/aurora-fido. "user" (preview) +# forwards each request to the passkey agent of the user active on seat0 +# (aurora-passkeyd, a user unit); it needs /dev/sep-key interface 4, and has no U2F. +vault = system [keys] # Where credential keys live: the Secure Enclave (/dev/sep-key), always. diff --git a/fido/aurora-passkeyd.in b/fido/aurora-passkeyd.in new file mode 100644 index 0000000..b5e9662 --- /dev/null +++ b/fido/aurora-passkeyd.in @@ -0,0 +1,9 @@ +#!/usr/bin/python3 -I +# SPDX-License-Identifier: MIT +# aurora-passkeyd: one user's passkeys, kept and used as that user (per-user vault mode). +import sys + +sys.path.insert(0, "@PYDIR@") +from aurora_fido import agent # noqa: E402 + +sys.exit(agent.main()) diff --git a/fido/aurora-passkeyd.service b/fido/aurora-passkeyd.service new file mode 100644 index 0000000..f7e971c --- /dev/null +++ b/fido/aurora-passkeyd.service @@ -0,0 +1,20 @@ +# SPDX-License-Identifier: MIT +# User unit. Used when aurora-fido.conf has [authenticator] vault = user: +# aurora-fidod (system) forwards each request to this agent of the active user. +[Unit] +Description=Aurora passkeys (this user's Secure Enclave credentials) +Documentation=file:///usr/share/doc/aurora-fido/fido.md + +[Service] +Type=simple +ExecStart=@LIBEXECDIR@/aurora-passkeyd +Restart=on-failure +RestartSec=5 +UMask=0077 +PrivateNetwork=yes +RestrictAddressFamilies=AF_UNIX +LockPersonality=yes +NoNewPrivileges=yes + +[Install] +WantedBy=default.target diff --git a/fido/aurora_fido/agent.py b/fido/aurora_fido/agent.py new file mode 100644 index 0000000..f041f1e --- /dev/null +++ b/fido/aurora_fido/agent.py @@ -0,0 +1,234 @@ +# SPDX-License-Identifier: MIT +"""aurora-passkeyd: one user's passkeys and security-key credentials. + +Runs as the user (systemd --user). aurora-fidod keeps the uhid device and +the CTAPHID framing and forwards each CTAP2 request here (remote.py, +agentproto.py). This process owns: +- the user's credential records (in $XDG_DATA_HOME/aurora-passkeys); +- the CTAP2 logic (ctap2.Authenticator, unchanged); +- the calls to /dev/sep-key, which it makes as the user. + +On the target kernel (sep-key interface 4) the credential keys are created +under the user's own key bag, and the enclave refuses them to every other +uid, root included (docs/passkeys/DESIGN.md 4.1, 4.2). + +The vault key that wraps credential IDs and records is sealed to a key in +the user's bag. That key needs the bag unlocked, but no touch, so records +are unreadable while the user is logged out. This needs interface 4. On an +older kernel the agent refuses to start: it never falls back to a key the +host holds. +""" + +import argparse +import logging +import os +import pwd +import signal +import socket +import sys +import threading + +from . import __version__, agentproto, cbor, ctap2, daemon +from .errors import ERR_CHANNEL_BUSY +from .backend import BackendError, open_backend + +log = logging.getLogger("aurora-passkeys") + +SEP_KEY_IFACE_USER_BAG = 4 + + +def data_dir(): + base = os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share") + return os.path.join(base, "aurora-passkeys") + + +def runtime_socket(): + rd = os.environ.get("XDG_RUNTIME_DIR") or "/run/user/%d" % os.getuid() + return os.path.join(rd, "aurora-passkeys", "ctap.sock") + + +class UserBagSecret: + """The vault key, sealed to a no-touch key under the user's key bag. + + Placeholder until sep-key interface 4 (SEP_KEY_CREATE_USER_BAG_ONLY: + a key under the caller's bag whose list needs the bag unlocked, no + credential). Until then it refuses; it never keeps a host-readable key. + """ + + def __init__(self, backend, state_dir): + self.backend = backend + self.state_dir = state_dir + + def _need_iface(self): + if getattr(self.backend, "version", 0) < SEP_KEY_IFACE_USER_BAG: + raise BackendError( + "per-user passkeys need /dev/sep-key interface 4 (keys under your own key " + "bag); this kernel has interface %s" % getattr(self.backend, "version", "?")) + raise BackendError("interface 4 vault key: not implemented yet") + + def load(self): + self._need_iface() + + def new(self): + self._need_iface() + + +def per_user_info(resp): + """getInfo from the agent: no U2F_V2 (U2F is not forwarded to agents).""" + if resp[:1] != b"\x00": + return resp + info = cbor.decode(resp[1:]) + info[1] = [v for v in info.get(1, []) if v != "U2F_V2"] + return b"\x00" + cbor.encode(info) + + +class AgentServer: + """Serves CTAP2 requests from aurora-fidod on a Unix SEQPACKET socket. + + allowed_uids: peers that may send requests, normally root (aurora-fidod) + and the user (`aurora-passkeys` tools). Same-user processes can already + open the hidraw node, so allowing them here grants nothing new. + """ + + def __init__(self, auth, path, allowed_uids): + self.auth = auth + self.path = path + self.allowed = set(allowed_uids) + self.sock = None + self.stop = threading.Event() + self.lock = threading.Lock() # one CTAP request at a time, as a key does + + def bind(self): + d = os.path.dirname(self.path) + os.makedirs(d, mode=0o700, exist_ok=True) + os.chmod(d, 0o700) + try: + os.unlink(self.path) + except FileNotFoundError: + pass + s = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET) + s.bind(self.path) + os.chmod(self.path, 0o600) + s.listen(4) + s.settimeout(0.2) + self.sock = s + return self + + def serve_forever(self): + while not self.stop.is_set(): + try: + conn, _ = self.sock.accept() + except socket.timeout: + continue + except OSError: + if self.stop.is_set(): + break + raise + threading.Thread(target=self._conn, args=(conn,), name="agent-conn", + daemon=True).start() + + def close(self): + self.stop.set() + if self.sock: + self.sock.close() + try: + os.unlink(self.path) + except OSError: + pass + + def _conn(self, conn): + with conn: + try: + uid = agentproto.peer_uid(conn) + if uid not in self.allowed: + log.warning("refused a request from uid %d", uid) + return + msg = agentproto.recv(conn) + if msg is None or msg["t"] != "req": + return + self._request(conn, msg["d"]) + except (OSError, agentproto.ProtocolError) as e: + log.info("request ended: %s", e) + + def _request(self, conn, data): + cancel = threading.Event() + send_lock = threading.Lock() + + def up_needed(): + with send_lock: + try: + agentproto.send(conn, {"t": "up"}) + except OSError: + cancel.set() + + def reader(): + # A cancel message, or fidod going away, cancels the request. + try: + while not cancel.is_set(): + m = agentproto.recv(conn) + if m is None or m["t"] == "cancel": + cancel.set() + except (OSError, agentproto.ProtocolError): + cancel.set() + + threading.Thread(target=reader, name="agent-read", daemon=True).start() + if not self.lock.acquire(timeout=1.0): + resp = bytes([ERR_CHANNEL_BUSY]) + else: + try: + resp = self.auth.handle(data, ctap2.Ctx(cancel, up_needed)) + finally: + self.lock.release() + if data[:1] == bytes([ctap2.CMD_GET_INFO]): + resp = per_user_info(resp) + with send_lock: + agentproto.send(conn, {"t": "resp", "d": resp}) + + +def build_agent(cfg, state_dir, backend, secret, user_name): + """The authenticator for one user (no U2F: not forwarded to agents yet).""" + cfg.set("touchid", "user", user_name) + policy, note = daemon.resolve_policy(cfg, backend.flags_supported) + user = daemon.enclave_user(cfg, backend, state_dir, policy) + auth, _u2f = daemon.build(cfg, state_dir, backend, user, secret, policy) + return auth, note + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="aurora-passkeyd") + ap.add_argument("--config", default=daemon.CONFIG) + ap.add_argument("--state-dir", default=None) + ap.add_argument("--socket", default=None) + ap.add_argument("-v", "--verbose", action="store_true") + a = ap.parse_args(argv) + logging.basicConfig(level=logging.DEBUG if a.verbose else logging.INFO, + format="%(message)s") + if os.geteuid() == 0: + log.error("aurora-passkeyd runs as the user whose passkeys it keeps, not as root") + return 1 + name = pwd.getpwuid(os.getuid()).pw_name + state_dir = a.state_dir or data_dir() + os.umask(0o077) + os.makedirs(state_dir, mode=0o700, exist_ok=True) + cfg = daemon.load_config(a.config) + try: + backend = open_backend(cfg.get("keys", "store")) + auth, note = build_agent(cfg, state_dir, backend, UserBagSecret(backend, state_dir), name) + except (BackendError, ValueError, OSError) as e: + log.error("%s", e) + return 1 + if note: + log.info("%s", note) + srv = AgentServer(auth, a.socket or runtime_socket(), {0, os.getuid()}).bind() + for s in (signal.SIGTERM, signal.SIGINT): + signal.signal(s, lambda *_: srv.stop.set()) + log.info("aurora-passkeyd %s ready for %s", __version__, name) + try: + srv.serve_forever() + finally: + srv.close() + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/fido/aurora_fido/agentproto.py b/fido/aurora_fido/agentproto.py new file mode 100644 index 0000000..a36393a --- /dev/null +++ b/fido/aurora_fido/agentproto.py @@ -0,0 +1,58 @@ +# SPDX-License-Identifier: MIT +"""The wire between aurora-fidod (system, owns the uhid device) and +aurora-passkeyd (one per user, owns that user's credentials). + +One CTAP2 request is one connection on a SOCK_SEQPACKET Unix socket. Every +message is one packet that holds one CBOR map; key "t" names the message: + + fidod -> agent {"t": "req", "d": } + fidod -> agent {"t": "cancel"} the browser cancelled (CTAPHID_CANCEL) + agent -> fidod {"t": "up"} waiting for the user (keepalive UPNEEDED) + agent -> fidod {"t": "resp", "d": } + +If fidod closes the connection, that counts as a cancel. The agent never +trusts the peer for anything but framing. Signing still needs the enclave's +own Touch ID or password check. Peers are checked with SO_PEERCRED on both +sides (peer_uid). +""" + +import socket +import struct + +from . import cbor + +MAX_PACKET = 16384 # a CTAP2 message is at most 7609 bytes; room for framing + + +class ProtocolError(Exception): + pass + + +def send(sock, msg): + data = cbor.encode(msg) + if len(data) > MAX_PACKET: + raise ProtocolError("message too large") + sock.send(data) + + +def recv(sock): + """One message, or None when the peer closed the connection.""" + data = sock.recv(MAX_PACKET) + if not data: + return None + try: + msg = cbor.decode(data) + except cbor.CBORError as e: + raise ProtocolError("bad message: %s" % e) from None + if not isinstance(msg, dict) or not isinstance(msg.get("t"), str): + raise ProtocolError("bad message") + if msg["t"] in ("req", "resp") and not isinstance(msg.get("d"), bytes): + raise ProtocolError("message without data") + return msg + + +def peer_uid(sock): + """The uid of the process at the other end (SO_PEERCRED).""" + creds = sock.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i")) + _pid, uid, _gid = struct.unpack("3i", creds) + return uid diff --git a/fido/aurora_fido/daemon.py b/fido/aurora_fido/daemon.py index 47d64bc..5abc78a 100644 --- a/fido/aurora_fido/daemon.py +++ b/fido/aurora_fido/daemon.py @@ -33,7 +33,10 @@ DEFAULTS = { "touchid": {"user": "auto", "timeout": "30", "max_tries": "3", "notify": "yes", "policy": "auto"}, - "authenticator": {"attestation": "self", "max_resident": "256", "u2f": "yes"}, + "authenticator": {"attestation": "self", "max_resident": "256", "u2f": "yes", + # system: credentials in STATE_DIR (0.2). user: each request goes to + # the passkey agent (aurora-passkeyd) of seat0's active user. + "vault": "system"}, "keys": {"store": "auto"}, } # Settings of aurora-fido 0.1 that no longer mean anything: the enclave @@ -208,7 +211,7 @@ def serve(auth, u, device_factory, run_dir=None, info=None): for s in (signal.SIGTERM, signal.SIGINT): signal.signal(s, lambda *_: stop.set()) log.info("security key ready (keys: %s, Touch ID checked by the Secure Enclave)", - auth.backend.name) + getattr(getattr(auth, "backend", None), "name", "per-user agents")) write_status(run_dir, dict(info or {}, pid=os.getpid(), ready=True)) try: hid.run(stop) @@ -224,6 +227,18 @@ def serve(auth, u, device_factory, run_dir=None, info=None): log.info("security key removed") +def serve_per_user(run_dir): + """The uhid device only; each user's aurora-passkeyd keeps and uses their credentials.""" + from .remote import RemoteAuthenticator + from .uhid import UhidDevice + status = {"version": __version__, "vault": "user", "keys": "sep-key", + "enforcement": "enclave", "u2f": False, + "keys_detail": "each user's passkey agent (aurora-passkeyd) keeps that user's " + "credentials; requests go to seat0's active user"} + serve(RemoteAuthenticator(), None, lambda: UhidDevice(name=DEVICE_NAME), run_dir, status) + return 0 + + POLICY_TEXT = { "touchid-or-password": "Touch ID, or your password checked by the Secure Enclave " "when Touch ID does not match, is locked or unavailable", @@ -251,6 +266,8 @@ def main(argv=None): if cfg.has_option(sec, key) and key not in DEFAULTS.get(sec, {}): log.warning("[%s] %s in %s has no effect any more: the Secure Enclave always " "checks the touch", sec, key, a.config) + if cfg.get("authenticator", "vault") == "user": + return serve_per_user(a.run_dir) try: backend = open_backend(cfg.get("keys", "store")) policy, note = resolve_policy(cfg, backend.flags_supported) diff --git a/fido/aurora_fido/remote.py b/fido/aurora_fido/remote.py new file mode 100644 index 0000000..a45e20f --- /dev/null +++ b/fido/aurora_fido/remote.py @@ -0,0 +1,118 @@ +# SPDX-License-Identifier: MIT +"""aurora-fidod's side of per-user credentials: forward each CTAP2 request to +the passkey agent of the user who owns the active local session on seat0. + +The uhid hidraw node's `uaccess` ACL follows the same logind state, so the +requests a browser sends reach the agent of the person sitting at the Mac. +When no local user is active, or that user's agent is not running, nothing +is signed. getInfo is still answered, from the last agent reply or from a +fixed description, so that browsers keep showing the key. Every other +command gets CTAP2_ERR_OPERATION_DENIED. +""" + +import logging +import os +import socket +import threading + +from . import agentproto, cbor, ctap2, touchid +from .errors import ERR_OPERATION_DENIED + +log = logging.getLogger("aurora-fido") + + +def agent_socket(uid): + return "/run/user/%d/aurora-passkeys/ctap.sock" % uid + + +def static_info(): + """getInfo when no agent answers: the same versions and AAGUID, no credentials. + U2F is not forwarded to agents (yet), so per-user mode never offers U2F_V2.""" + info = {1: ["FIDO_2_0", "FIDO_2_1"], 3: ctap2.AAGUID, + 4: {"rk": True, "up": True, "uv": True, "plat": False}, + 5: 7609} + return b"\x00" + cbor.encode(info) + + +class RemoteAuthenticator: + """Has the same handle(data, ctx) as ctap2.Authenticator; ctaphid.CtapHid uses it unchanged.""" + + def __init__(self, active_uid=None, socket_path=agent_socket, timeout=90.0): + self.active_uid = active_uid or self._seat_uid + self.socket_path = socket_path + self.timeout = timeout + self._info = None + self.lock = threading.Lock() + + @staticmethod + def _seat_uid(): + u = touchid.seat_user() + return u[1] if u else None + + def _connect(self, uid): + s = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET) + s.settimeout(self.timeout) + try: + s.connect(self.socket_path(uid)) + # The socket lives in the user's runtime dir, but check who answers: + # only that user's own agent (never another user's process) may serve. + if agentproto.peer_uid(s) != uid: + raise PermissionError("agent socket for uid %d served by another uid" % uid) + except BaseException: + s.close() + raise + return s + + def handle(self, data, ctx=None): + ctx = ctx or ctap2.Ctx() + is_info = data[:1] == bytes([ctap2.CMD_GET_INFO]) + uid = self.active_uid() + if uid is None: + log.info("no active local session on seat0: request refused") + return self._fallback(is_info) + try: + s = self._connect(uid) + except (OSError, PermissionError) as e: + log.info("passkey agent of uid %d not reachable (%s): request refused", uid, e) + return self._fallback(is_info) + with s: + try: + return self._exchange(s, data, ctx, is_info) + except (OSError, agentproto.ProtocolError) as e: + log.warning("passkey agent of uid %d failed: %s", uid, e) + return self._fallback(is_info) + + def _exchange(self, s, data, ctx, is_info): + agentproto.send(s, {"t": "req", "d": data}) + done = threading.Event() + + def watch_cancel(): + while not done.is_set(): + if ctx.cancel.wait(0.05): + try: + agentproto.send(s, {"t": "cancel"}) + except OSError: + pass + return + + threading.Thread(target=watch_cancel, name="agent-cancel", daemon=True).start() + try: + while True: + msg = agentproto.recv(s) + if msg is None: + raise agentproto.ProtocolError("agent closed the connection") + if msg["t"] == "up": + ctx.on_up_needed() + elif msg["t"] == "resp": + if is_info and msg["d"][:1] == b"\x00": + self._info = msg["d"] + return msg["d"] + else: + raise agentproto.ProtocolError("unexpected %r" % msg["t"]) + finally: + done.set() + + def _fallback(self, is_info): + if is_info: + return self._info or static_info() + return bytes([ERR_OPERATION_DENIED]) diff --git a/fido/tests/test_agent.py b/fido/tests/test_agent.py new file mode 100644 index 0000000..c51246a --- /dev/null +++ b/fido/tests/test_agent.py @@ -0,0 +1,212 @@ +# SPDX-License-Identifier: MIT +"""Per-user agent tests: aurora-fidod's RemoteAuthenticator -> aurora-passkeyd, +on the stub enclave (tests/stub.py). Linux only (SOCK_SEQPACKET, SO_PEERCRED). + +Run from fido/: python3 tests/test_agent.py +""" + +import os +import socket +import sys +import tempfile +import threading +import time +import unittest + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from aurora_fido import agent, cbor, ctap2, daemon, remote # noqa: E402 +from aurora_fido import errors as E # noqa: E402 +from aurora_fido.backend import BackendError # noqa: E402 +import stub # noqa: E402 +from stub import FileSecret, StubKeyBackend # noqa: E402 +from test_ctap import CDH, parse_auth_data # noqa: E402 + +UID = os.getuid() + + +class Agent: + """One user's aurora-passkeyd on the stub enclave, in a temp dir.""" + + def __init__(self, root, name, allowed=None, mode=stub.MATCH): + self.state = os.path.join(root, name, "state") + os.makedirs(self.state, mode=0o700) + self.backend = StubKeyBackend(mode=mode) + cfg = daemon.load_config(None) + cfg.set("touchid", "notify", "no") + self.auth, _ = agent.build_agent(cfg, self.state, self.backend, + FileSecret(os.path.join(root, name, "vault")), "root") + self.path = os.path.join(root, name, "run", "ctap.sock") + self.srv = agent.AgentServer(self.auth, self.path, + {UID} if allowed is None else allowed).bind() + self.t = threading.Thread(target=self.srv.serve_forever, daemon=True) + self.t.start() + + def close(self): + self.srv.close() + self.t.join(2) + + +class Fidod: + """aurora-fidod's side: RemoteAuthenticator with a scripted seat.""" + + def __init__(self, sockets): + self.active = None + self.sockets = sockets # uid -> socket path + self.auth = remote.RemoteAuthenticator( + active_uid=lambda: self.active, + socket_path=lambda uid: self.sockets.get(uid, "/nonexistent/ctap.sock"), + timeout=10) + + def call(self, cmd, params=None, ctx=None): + data = bytes([cmd]) + (cbor.encode(params) if params is not None else b"") + r = self.auth.handle(data, ctx) + return r[0], (cbor.decode(r[1:]) if len(r) > 1 else None) + + def make(self, rp="example.com", uid=b"user-1", rk=True, ctx=None): + return self.call(ctap2.CMD_MAKE_CREDENTIAL, { + 1: CDH, 2: {"id": rp, "name": "Example"}, + 3: {"id": uid, "name": "ryan", "displayName": "Ryan"}, + 4: [{"type": "public-key", "alg": -7}], 7: {"rk": rk}}, ctx) + + def ga(self, rp="example.com", allow=None): + p = {1: rp, 2: CDH} + if allow: + p[3] = [{"type": "public-key", "id": c} for c in allow] + return self.call(ctap2.CMD_GET_ASSERTION, p) + + +class AgentTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.agents = [] + + def tearDown(self): + for a in self.agents: + a.close() + self.tmp.cleanup() + + def agent(self, name, **kw): + a = Agent(self.tmp.name, name, **kw) + self.agents.append(a) + return a + + def test_info_through_agent_has_no_u2f(self): + a = self.agent("u") + f = Fidod({UID: a.path}) + f.active = UID + st, info = f.call(ctap2.CMD_GET_INFO) + self.assertEqual(st, 0) + self.assertNotIn("U2F_V2", info[1]) + self.assertIn("FIDO_2_1", info[1]) + self.assertEqual(info[3], ctap2.AAGUID) + self.assertTrue(info[4]["rk"]) + + def test_passkey_register_and_usernameless_sign_in(self): + a = self.agent("u") + f = Fidod({UID: a.path}) + f.active = UID + st, mc = f.make(rk=True) + self.assertEqual(st, 0) + ad = parse_auth_data(mc[2]) + self.assertTrue(ad["flags"] & ctap2.FLAG_UV) + self.assertEqual(a.auth.store.count(), 1) # the record is in this user's dir + st, r = f.ga() # no allow list: discoverable + self.assertEqual(st, 0) + self.assertEqual(r[1]["id"], ad["cred_id"]) + self.assertEqual(r[4]["id"], b"user-1") + self.assertTrue(ctap2.verify_es256(ad["point"], r[2] + CDH, r[3])) + self.assertGreaterEqual(a.backend.signs, 2) # attestation + assertion, both "enclave" + + def test_users_do_not_see_each_other(self): + a, b = self.agent("a"), self.agent("b") + f = Fidod({UID: a.path}) + f.active = UID + st, mc = f.make(rk=True) + self.assertEqual(st, 0) + cid = parse_auth_data(mc[2])["cred_id"] + f.sockets[UID] = b.path # another user's agent at the seat + st, _ = f.ga() + self.assertEqual(st, E.ERR_NO_CREDENTIALS) + st, _ = f.ga(allow=[cid]) # a's ID does not open in b's vault + self.assertEqual(st, E.ERR_NO_CREDENTIALS) + self.assertEqual(b.backend.signs, 0) + + def test_no_active_user(self): + a = self.agent("u") + f = Fidod({UID: a.path}) + f.active = None + st, _ = f.make() + self.assertEqual(st, E.ERR_OPERATION_DENIED) + st, info = f.call(ctap2.CMD_GET_INFO) + self.assertEqual(st, 0) + self.assertNotIn("U2F_V2", info[1]) + self.assertEqual(a.backend.creates, 0) + + def test_agent_down_uses_cached_info(self): + a = self.agent("u") + f = Fidod({UID: a.path}) + f.active = UID + st, info = f.call(ctap2.CMD_GET_INFO) + a.close() + self.agents.remove(a) + st2, info2 = f.call(ctap2.CMD_GET_INFO) + self.assertEqual((st2, info2), (st, info)) + st, _ = f.make() + self.assertEqual(st, E.ERR_OPERATION_DENIED) + + def test_socket_served_by_another_uid_is_refused(self): + a = self.agent("u") + f = Fidod({UID + 1: a.path}) # seat says uid+1, socket answers as UID + f.active = UID + 1 + st, _ = f.make() + self.assertEqual(st, E.ERR_OPERATION_DENIED) + self.assertEqual(a.backend.creates, 0) + + def test_agent_refuses_unlisted_peer(self): + a = self.agent("u", allowed={UID + 1}) + f = Fidod({UID: a.path}) + f.active = UID + st, _ = f.make() + self.assertEqual(st, E.ERR_OPERATION_DENIED) + self.assertEqual(a.backend.creates, 0) + + def test_cancel_reaches_the_enclave_wait(self): + a = self.agent("u", mode=stub.WAIT) + f = Fidod({UID: a.path}) + f.active = UID + ups = [] + ctx = ctap2.Ctx(threading.Event(), lambda: ups.append(time.monotonic())) + threading.Timer(0.5, ctx.cancel.set).start() + t0 = time.monotonic() + st, _ = f.make(ctx=ctx) + self.assertEqual(st, E.ERR_KEEPALIVE_CANCEL) + self.assertLess(time.monotonic() - t0, 5) + self.assertTrue(ups, "UPNEEDED keepalive was not relayed") + self.assertEqual(a.backend.signs, 0) + + def test_fidod_disconnect_cancels(self): + a = self.agent("u", mode=stub.WAIT) + s = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET) + s.connect(a.path) + from aurora_fido import agentproto + agentproto.send(s, {"t": "req", "d": bytes([ctap2.CMD_SELECTION])}) + self.assertEqual(agentproto.recv(s)["t"], "up") + s.close() + deadline = time.monotonic() + 5 + while a.srv.lock.locked() and time.monotonic() < deadline: + time.sleep(0.05) + self.assertFalse(a.srv.lock.locked()) + self.assertEqual(a.backend.signs, 0) + + def test_vault_key_needs_interface_4(self): + class Old: + version = 3 + with self.assertRaises(BackendError) as c: + agent.UserBagSecret(Old(), self.tmp.name).load() + self.assertIn("interface 4", str(c.exception)) + + +if __name__ == "__main__": + unittest.main() From 72313f644e54c00c3abfd74336574bf9b63c5c70 Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Wed, 11 Nov 2026 21:04:03 +1100 Subject: [PATCH 2/8] fido: per-site policy for new credentials in the passkey agent aurora-passkeyd reads ~/.config/aurora-passkeys/sites.conf (site = policy, longest suffix on a label boundary wins) and the authenticator uses that policy's CREATE flags for the new key, so the enclave enforces it. A rule the kernel cannot make refuses the registration instead of making a weaker key; malformed lines are skipped with a warning. Tests: rule matching, the key made with the rule's flags and still signing, refusal without a weaker key when the kernel lacks the flag. Co-Authored-By: Claude Opus 5.5 --- docs/fido.md | 8 ++++++ fido/aurora_fido/agent.py | 55 ++++++++++++++++++++++++++++++++++++--- fido/aurora_fido/ctap2.py | 18 ++++++++++--- fido/tests/stub.py | 1 + fido/tests/test_agent.py | 41 ++++++++++++++++++++++++++--- 5 files changed, 113 insertions(+), 10 deletions(-) diff --git a/docs/fido.md b/docs/fido.md index b0ce93e..cdee1ee 100644 --- a/docs/fido.md +++ b/docs/fido.md @@ -177,6 +177,14 @@ The agent's vault key is sealed to a key under the user's own key bag is logged out, and the credential keys sign for nobody else, root included. On a kernel without interface 4 the agent refuses to start. +**Per-site rules.** `~/.config/aurora-passkeys/sites.conf` holds lines of +the form `site = policy`, for example `bank.example = touchid-current`. A rule +covers the site and every name under it, and the longest match wins. The +rule is written into the new credential's access-control list, so the +enclave enforces it. Changing a rule affects new credentials only. If the +kernel cannot make the key a rule asks for, the registration is refused +(`CTAP2_ERR_UNSUPPORTED_OPTION`); a weaker key is never made instead. + ### Existing credentials (migration from 0.1) aurora-fido 0.1 checked the touch in the daemon (fprintd, or a polkit diff --git a/fido/aurora_fido/agent.py b/fido/aurora_fido/agent.py index f041f1e..7808b57 100644 --- a/fido/aurora_fido/agent.py +++ b/fido/aurora_fido/agent.py @@ -28,7 +28,7 @@ import sys import threading -from . import __version__, agentproto, cbor, ctap2, daemon +from . import __version__, agentproto, cbor, creds, ctap2, daemon from .errors import ERR_CHANNEL_BUSY from .backend import BackendError, open_backend @@ -42,6 +42,53 @@ def data_dir(): return os.path.join(base, "aurora-passkeys") +def config_dir(): + base = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config") + return os.path.join(base, "aurora-passkeys") + + +class SitePolicy: + """Per-site rules for new credentials: ~/.config/aurora-passkeys/sites.conf + + # site = policy (the site and every name under it) + bank.example = touchid-current + corp.example = touchid-any + + The longest matching site wins; no match keeps the default policy. The + rule is written into the new key's access-control list, so the enclave + enforces it; a changed rule affects new credentials only (macOS behaviour). + A malformed line is skipped with a warning, never widened. + """ + + def __init__(self, path): + self.rules = {} + try: + with open(path, encoding="utf-8") as f: + lines = f.read().splitlines() + except FileNotFoundError: + return + for n, line in enumerate(lines, 1): + line = line.split("#", 1)[0].strip() + if not line: + continue + site, sep, pol = (x.strip() for x in line.partition("=")) + site = site.lower().rstrip(".") + if not sep or not site or pol not in creds.POLICIES: + log.warning("%s:%d: ignored (want 'site = %s')", path, n, + " | ".join(sorted(creds.POLICIES))) + continue + self.rules[site] = creds.POLICIES[pol] + + def __call__(self, rp_id): + rp_id = rp_id.lower().rstrip(".") + best = None + for site, pol in self.rules.items(): + if (rp_id == site or rp_id.endswith("." + site)) and ( + best is None or len(site) > len(best[0])): + best = site, pol + return best[1] if best else None + + def runtime_socket(): rd = os.environ.get("XDG_RUNTIME_DIR") or "/run/user/%d" % os.getuid() return os.path.join(rd, "aurora-passkeys", "ctap.sock") @@ -185,12 +232,13 @@ def reader(): agentproto.send(conn, {"t": "resp", "d": resp}) -def build_agent(cfg, state_dir, backend, secret, user_name): +def build_agent(cfg, state_dir, backend, secret, user_name, sites=None): """The authenticator for one user (no U2F: not forwarded to agents yet).""" cfg.set("touchid", "user", user_name) policy, note = daemon.resolve_policy(cfg, backend.flags_supported) user = daemon.enclave_user(cfg, backend, state_dir, policy) auth, _u2f = daemon.build(cfg, state_dir, backend, user, secret, policy) + auth.policy_for = sites return auth, note @@ -213,7 +261,8 @@ def main(argv=None): cfg = daemon.load_config(a.config) try: backend = open_backend(cfg.get("keys", "store")) - auth, note = build_agent(cfg, state_dir, backend, UserBagSecret(backend, state_dir), name) + auth, note = build_agent(cfg, state_dir, backend, UserBagSecret(backend, state_dir), name, + SitePolicy(os.path.join(config_dir(), "sites.conf"))) except (BackendError, ValueError, OSError) as e: log.error("%s", e) return 1 diff --git a/fido/aurora_fido/ctap2.py b/fido/aurora_fido/ctap2.py index 69a11c9..1fe5a75 100644 --- a/fido/aurora_fido/ctap2.py +++ b/fido/aurora_fido/ctap2.py @@ -130,11 +130,15 @@ def _options(params, key): class Authenticator: def __init__(self, backend, user, vault, store, counter, attestation="self", new_vault=None, clock=time.monotonic, - policy=POLICY_TOUCHID_ANY, on_legacy=lambda rp_id, why: None): + policy=POLICY_TOUCHID_ANY, on_legacy=lambda rp_id, why: None, + policy_for=None): self.backend = backend self.user = user # enclave.EnclaveUser: every approval self.policy = policy # for new credentials (config [touchid] policy) self.flags = POLICY_FLAGS[policy] + # rp_id -> policy for that site's new credentials, or None for the default + # (per-site rules, aurora-passkeyd); the enclave enforces whichever is chosen. + self.policy_for = policy_for self.on_legacy = on_legacy # a refused pre-enclave credential was presented self.vault = vault self.store = store @@ -381,13 +385,21 @@ def make_credential(self, p, ctx): # The new key, with the enclave's access-control list. It signs # nothing without a finger, so making it needs no approval; the # approval is its first signature below. - handle, point = self.backend.create(self.flags) + policy, flags = self.policy, self.flags + site = self.policy_for(rp_id) if self.policy_for else None + if site is not None and site != policy: + policy, flags = site, POLICY_FLAGS[site] + if flags & ~self.backend.flags_supported: + # Never a weaker key than the site's rule asks for. + log.warning("site rule for %s asks for a policy this kernel cannot make", rp_id) + raise CtapError(ERR_UNSUPPORTED_OPTION, "site policy") + handle, point = self.backend.create(flags) sealed = None if hmac_secret: # CredRandomWithUV || CredRandomWithoutUV, released by the # enclave only together with a touch-approved signature. sealed = self.backend.seal(handle, os.urandom(64)) - cred = Credential(handle, cred_protect or 1, self.policy, sealed) + cred = Credential(handle, cred_protect or 1, policy, sealed) cred_id = self.vault.wrap(rp_hash, cred, ID_MAX_CTAP2) ext_out = {} diff --git a/fido/tests/stub.py b/fido/tests/stub.py index 9245025..3662beb 100644 --- a/fido/tests/stub.py +++ b/fido/tests/stub.py @@ -57,6 +57,7 @@ def create(self, flags, gated=True): handle = (b"STUB" + bytes([_GATED if gated else 0]) + nonce + self._aead.encrypt(nonce, scalar, b"stub") + b"\0" * self.handle_pad) self.creates += 1 + self.last_flags = flags return handle, self._point(priv) def gated(self, handle): diff --git a/fido/tests/test_agent.py b/fido/tests/test_agent.py index c51246a..c990f73 100644 --- a/fido/tests/test_agent.py +++ b/fido/tests/test_agent.py @@ -16,7 +16,7 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from aurora_fido import agent, cbor, ctap2, daemon, remote # noqa: E402 +from aurora_fido import agent, cbor, creds, ctap2, daemon, remote # noqa: E402 from aurora_fido import errors as E # noqa: E402 from aurora_fido.backend import BackendError # noqa: E402 import stub # noqa: E402 @@ -29,14 +29,15 @@ class Agent: """One user's aurora-passkeyd on the stub enclave, in a temp dir.""" - def __init__(self, root, name, allowed=None, mode=stub.MATCH): + def __init__(self, root, name, allowed=None, mode=stub.MATCH, sites=None, flags_supported=0x3): self.state = os.path.join(root, name, "state") os.makedirs(self.state, mode=0o700) - self.backend = StubKeyBackend(mode=mode) + self.backend = StubKeyBackend(mode=mode, flags_supported=flags_supported) cfg = daemon.load_config(None) cfg.set("touchid", "notify", "no") self.auth, _ = agent.build_agent(cfg, self.state, self.backend, - FileSecret(os.path.join(root, name, "vault")), "root") + FileSecret(os.path.join(root, name, "vault")), "root", + sites) self.path = os.path.join(root, name, "run", "ctap.sock") self.srv = agent.AgentServer(self.auth, self.path, {UID} if allowed is None else allowed).bind() @@ -200,6 +201,38 @@ def test_fidod_disconnect_cancels(self): self.assertFalse(a.srv.lock.locked()) self.assertEqual(a.backend.signs, 0) + def test_site_policy_is_written_into_the_key(self): + conf = os.path.join(self.tmp.name, "sites.conf") + with open(conf, "w") as f: + f.write("# rules\nbank.example = touchid-current\nexample = touchid-any\n" + "bad line\nweak.example = nothing\n") + sites = agent.SitePolicy(conf) + self.assertEqual(sites("login.BANK.example."), creds.POLICY_TOUCHID_CURRENT) + self.assertEqual(sites("shop.example"), creds.POLICY_TOUCHID_ANY) + self.assertIsNone(sites("notbank.example.org")) + self.assertIsNone(sites("weak.example.com")) + a = self.agent("u", sites=sites) + f = Fidod({UID: a.path}) + f.active = UID + st, mc = f.make(rp="login.bank.example") + self.assertEqual(st, 0) + self.assertEqual(a.backend.last_flags, creds.POLICY_FLAGS[creds.POLICY_TOUCHID_CURRENT]) + st, r = f.ga(rp="login.bank.example") + self.assertEqual(st, 0) # the credential signs as usual + + def test_site_policy_the_kernel_cannot_make_is_refused(self): + conf = os.path.join(self.tmp.name, "sites.conf") + with open(conf, "w") as f: + f.write("bank.example = touchid-current\n") + a = self.agent("u", sites=agent.SitePolicy(conf), flags_supported=0x2) + f = Fidod({UID: a.path}) + f.active = UID + st, _ = f.make(rp="bank.example") + self.assertEqual(st, E.ERR_UNSUPPORTED_OPTION) + self.assertEqual(a.backend.creates, 0) # no weaker key was made + st, _ = f.make(rp="other.example") + self.assertEqual(st, 0) + def test_vault_key_needs_interface_4(self): class Old: version = 3 From 53e7ee07a9ca1a13d4338b100acbd73196827dbe Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Wed, 11 Nov 2026 21:06:14 +1100 Subject: [PATCH 3/8] fido: native front-end for a credentials portal (provider.py) The methods a platform-authenticator portal calls (credentialsd's proposed Provider1): get_info, list_credentials (display metadata from the vault, no enclave operation), make_credential and get_assertion on the same ctap2.Authenticator, so both front-ends share one vault and every signature stays an enclave-checked touch. The provider checks that the rp id is the origin's host or a parent of it over https before anything reaches the enclave, and maps CTAP status to WebAuthn DOMException names. The D-Bus binding comes separately. Tests: tests/test_provider.py (7, stub enclave). Co-Authored-By: Claude Opus 5.5 --- fido/Makefile | 1 + fido/aurora_fido/provider.py | 121 +++++++++++++++++++++++++++++++++++ fido/tests/test_provider.py | 100 +++++++++++++++++++++++++++++ 3 files changed, 222 insertions(+) create mode 100644 fido/aurora_fido/provider.py create mode 100644 fido/tests/test_provider.py diff --git a/fido/Makefile b/fido/Makefile index 84315e5..6ac600e 100644 --- a/fido/Makefile +++ b/fido/Makefile @@ -54,6 +54,7 @@ FORCE: check: $(PYTHON) tests/test_ctap.py $(PYTHON) tests/test_agent.py + $(PYTHON) tests/test_provider.py # As root: the real uhid device with libfido2, OpenSSH, pam_u2f, cryptenroll. check-uhid: diff --git a/fido/aurora_fido/provider.py b/fido/aurora_fido/provider.py new file mode 100644 index 0000000..9e76039 --- /dev/null +++ b/fido/aurora_fido/provider.py @@ -0,0 +1,121 @@ +# SPDX-License-Identifier: MIT +"""The native (platform authenticator) front-end of the passkey agent. + +These are the methods a credentials portal (credentialsd's proposed +Provider1 interface; docs/passkeys/CREDENTIALSD-PROVIDER.md) calls instead +of CTAP over hidraw. They sit on the same ctap2.Authenticator, so both +front-ends share one vault and one set of rules: every signature is still an +enclave-checked touch inside SEP_KEY_SIGN. The D-Bus binding is a thin layer +on top of this and is not here yet. + +Inputs are WebAuthn-shaped (rp/user dicts, a client data hash the portal +computed from the origin), and errors are WebAuthn DOMException names. +""" + +import hashlib +from urllib.parse import urlsplit + +from . import cbor, ctap2 +from . import errors as E + + +class ProviderError(Exception): + """name: a WebAuthn DOMException name (NotAllowedError, InvalidStateError, ...).""" + + def __init__(self, name, message=""): + super().__init__(message or name) + self.name = name + + +# CTAP status -> DOMException name (WebAuthn L3, "authenticatorMakeCredential"/ +# "authenticatorGetAssertion" error handling). +_DOM = { + E.ERR_CREDENTIAL_EXCLUDED: "InvalidStateError", + E.ERR_UNSUPPORTED_ALGORITHM: "NotSupportedError", + E.ERR_UNSUPPORTED_OPTION: "NotSupportedError", + E.ERR_KEY_STORE_FULL: "QuotaExceededError", +} + + +def rp_id_matches_origin(rp_id, origin): + """rp_id must be the origin's host or a parent domain of it, over https + (http only for localhost). The portal checks the registrable-domain + rule; this is the provider's own check, not a replacement for it.""" + try: + u = urlsplit(origin) + except ValueError: + return False + host = (u.hostname or "").lower().rstrip(".") + rp = (rp_id or "").lower().rstrip(".") + if not host or not rp: + return False + if u.scheme != "https" and not (u.scheme == "http" and host == "localhost"): + return False + return host == rp or host.endswith("." + rp) + + +class Provider: + def __init__(self, auth): + self.auth = auth + + def _call(self, cmd, params, ctx): + r = self.auth.handle(bytes([cmd]) + cbor.encode(params), ctx or ctap2.Ctx()) + if r[0] != 0: + raise ProviderError(_DOM.get(r[0], "NotAllowedError"), "CTAP status 0x%02x" % r[0]) + return cbor.decode(r[1:]) if len(r) > 1 else {} + + @staticmethod + def _check_origin(rp_id, origin): + if not rp_id_matches_origin(rp_id, origin): + raise ProviderError("SecurityError", "rp id %r is not valid for %r" % (rp_id, origin)) + + def get_info(self): + info = self.auth.get_info({}, None) + return {"aaguid": info[3], "name": "Aurora Passwords", + "algorithms": [a["alg"] for a in info[0x0A]], + "extensions": list(info[2]), "uv": ["biometric"], + "locked": False, "rk_remaining": info[0x14]} + + def list_credentials(self, rp_id, allow=()): + """Display metadata only: no enclave operation, no touch.""" + rp_hash = hashlib.sha256(rp_id.encode()).digest() + out = [] + for rec in self.auth.store.for_rp(rp_hash): + out.append({"id": rec["credId"], "user_handle": rec["userId"], + "user_name": rec.get("userName") or "", + "display_name": rec.get("displayName") or "", + "created": rec.get("created", 0)}) + known = {c["id"] for c in out} + for cid in allow or (): + if cid not in known and self.auth.vault.unwrap(rp_hash, cid) is not None: + out.append({"id": cid, "user_handle": b"", "user_name": "", + "display_name": "", "created": 0}) + return out + + def make_credential(self, cdh, rp, user, params, exclude=(), options=None, ctx=None): + o = dict(options or {}) + self._check_origin(rp.get("id"), o.get("origin", "")) + p = {1: cdh, 2: {k: v for k, v in rp.items() if k in ("id", "name")}, + 3: {k: v for k, v in user.items() if k in ("id", "name", "displayName")}, + 4: [{"type": "public-key", "alg": a} for a in params], + 7: {"rk": bool(o.get("rk", True))}} + if exclude: + p[5] = [{"type": "public-key", "id": c} for c in exclude] + if o.get("extensions"): + p[6] = o["extensions"] + r = self._call(ctap2.CMD_MAKE_CREDENTIAL, p, ctx) + att = {"fmt": r[1], "attStmt": r[3], "authData": r[2]} + return {"attestation_object": cbor.encode(att), "transports": ["internal"], + "extensions": r.get(6, {})} + + def get_assertion(self, cdh, rp_id, credential_id, options=None, ctx=None): + o = dict(options or {}) + self._check_origin(rp_id, o.get("origin", "")) + p = {1: rp_id, 2: cdh, 3: [{"type": "public-key", "id": credential_id}]} + if o.get("extensions"): + p[4] = o["extensions"] + r = self._call(ctap2.CMD_GET_ASSERTION, p, ctx) + if r[1]["id"] != credential_id: + raise ProviderError("UnknownError", "the authenticator answered for another credential") + return {"authenticator_data": r[2], "signature": r[3], + "user_handle": r.get(4, {}).get("id", b""), "extensions": {}} diff --git a/fido/tests/test_provider.py b/fido/tests/test_provider.py new file mode 100644 index 0000000..961735e --- /dev/null +++ b/fido/tests/test_provider.py @@ -0,0 +1,100 @@ +# SPDX-License-Identifier: MIT +"""Native front-end (provider.py) on the stub enclave. + +Run from fido/: python3 tests/test_provider.py +""" + +import hashlib +import os +import sys +import threading +import unittest + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from aurora_fido import cbor, ctap2 # noqa: E402 +from aurora_fido.provider import Provider, ProviderError, rp_id_matches_origin # noqa: E402 +import stub # noqa: E402 +from test_ctap import CDH, Rig, parse_auth_data # noqa: E402 + +RP = {"id": "example.com", "name": "Example"} +USER = {"id": b"user-1", "name": "ryan", "displayName": "Ryan"} +ORIGIN = {"origin": "https://login.example.com"} + + +class ProviderTest(unittest.TestCase): + def setUp(self): + self.rig = Rig() + self.p = Provider(self.rig.auth) + + def tearDown(self): + self.rig.close() + + def make(self, **kw): + return self.p.make_credential(CDH, RP, USER, [-7], options=dict(ORIGIN, **kw)) + + def test_origin_rule(self): + ok = [("example.com", "https://example.com"), ("example.com", "https://a.b.example.com"), + ("localhost", "http://localhost:8080")] + bad = [("example.com", "http://example.com"), ("example.com", "https://notexample.com"), + ("a.example.com", "https://example.com"), ("example.com", ""), + ("com", "https://example.co")] + for rp, o in ok: + self.assertTrue(rp_id_matches_origin(rp, o), (rp, o)) + for rp, o in bad: + self.assertFalse(rp_id_matches_origin(rp, o), (rp, o)) + + def test_register_list_and_sign_in(self): + r = self.make() + att = cbor.decode(r["attestation_object"]) + ad = parse_auth_data(att["authData"]) + self.assertEqual(ad["rp_hash"], hashlib.sha256(b"example.com").digest()) + lst = self.p.list_credentials("example.com") + self.assertEqual(len(lst), 1) + self.assertEqual((lst[0]["id"], lst[0]["user_name"]), (ad["cred_id"], "ryan")) + signs = self.rig.backend.signs + self.p.list_credentials("example.com") + self.assertEqual(self.rig.backend.signs, signs) # listing touches nothing + a = self.p.get_assertion(CDH, "example.com", ad["cred_id"], ORIGIN) + self.assertTrue(ctap2.verify_es256(ad["point"], a["authenticator_data"] + CDH, + a["signature"])) + self.assertEqual(a["user_handle"], b"user-1") + self.assertEqual(self.p.list_credentials("other.com"), []) + + def test_wrong_origin_is_refused_before_the_enclave(self): + with self.assertRaises(ProviderError) as c: + self.p.make_credential(CDH, RP, USER, [-7], options={"origin": "https://evil.test"}) + self.assertEqual(c.exception.name, "SecurityError") + self.assertEqual(self.rig.backend.creates, 0) + + def test_no_match_is_not_allowed(self): + cid = parse_auth_data(cbor.decode(self.make()["attestation_object"])["authData"])["cred_id"] + self.rig.mode = stub.NO_MATCH + with self.assertRaises(ProviderError) as c: + self.p.get_assertion(CDH, "example.com", cid, ORIGIN) + self.assertEqual(c.exception.name, "NotAllowedError") + + def test_excluded_is_invalid_state(self): + cid = parse_auth_data(cbor.decode(self.make()["attestation_object"])["authData"])["cred_id"] + with self.assertRaises(ProviderError) as c: + self.p.make_credential(CDH, RP, USER, [-7], exclude=[cid], options=ORIGIN) + self.assertEqual(c.exception.name, "InvalidStateError") + + def test_cancel(self): + self.rig.mode = stub.WAIT + ctx = ctap2.Ctx(threading.Event()) + threading.Timer(0.3, ctx.cancel.set).start() + with self.assertRaises(ProviderError) as c: + self.p.make_credential(CDH, RP, USER, [-7], options=ORIGIN, ctx=ctx) + self.assertEqual(c.exception.name, "NotAllowedError") + self.assertEqual(self.rig.backend.signs, 0) + + def test_info(self): + i = self.p.get_info() + self.assertEqual(i["aaguid"], ctap2.AAGUID) + self.assertIn(-7, i["algorithms"]) + + +if __name__ == "__main__": + unittest.main() From 4b2b181544457e5bcfd282b163bba7da4a427b1d Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:32:41 +1100 Subject: [PATCH 4/8] fido: passkey agent on sep-key interface 4: keys and vault key under the user's bag, enclave-checked password backend: SEP_KEY_CREATE_USER (a .userPresence key, or with flags 0 a key with no list that works only while the bag is unlocked), SEP_KEY_SIGN_PASSWORD and SEP_KEY_UNSEAL_PASSWORD, version-2 handles (uid), BagLocked and PasswordRefused errors; our copy of the password in the request buffer is zeroed after the call. UserBagBackend gives a user's agent only .userPresence keys under that user's bag and refuses handles of other uids, so a site rule asking for a biometric-only key is refused there. agent: the vault key is 64 random bytes sealed to a no-list key under the user's bag (vault.key); it opens with no touch while the bag is unlocked and not at all while it is locked. The agent needs interface 4 and refuses to start otherwise. enclave/ctap2/provider: a request may carry the user's password (native front-end only; CTAP has no route while clientPIN stays off): the enclave checks it instead of a touch, one call, no retries, a wrong password is CTAP2_ERR_PIN_INVALID (provider reason 'wrong-password'), a locked bag is OPERATION_DENIED. The provider wipes the password bytearray after the call. Tests (stub with a user bag): user-presence key under the bag, plain vault key reopens across an agent restart, locked bag refuses everything and the vault key, password route (sign, wrong password counted, wiped buffer), biometric site rule refused, another uid's handle refused. make check: 61 + 18 + 7. Struct sizes and ioctl numbers checked against the interface-4 header (2128/2428/2648). Co-Authored-By: Claude Opus 5.5 --- fido/aurora_fido/agent.py | 63 ++++++++--- fido/aurora_fido/backend.py | 204 +++++++++++++++++++++++++++++++++-- fido/aurora_fido/ctap2.py | 20 +++- fido/aurora_fido/enclave.py | 45 ++++++-- fido/aurora_fido/provider.py | 44 +++++++- fido/tests/stub.py | 64 ++++++++++- fido/tests/test_agent.py | 123 +++++++++++++++++++-- 7 files changed, 510 insertions(+), 53 deletions(-) diff --git a/fido/aurora_fido/agent.py b/fido/aurora_fido/agent.py index 7808b57..e60c8db 100644 --- a/fido/aurora_fido/agent.py +++ b/fido/aurora_fido/agent.py @@ -30,7 +30,7 @@ from . import __version__, agentproto, cbor, creds, ctap2, daemon from .errors import ERR_CHANNEL_BUSY -from .backend import BackendError, open_backend +from .backend import BackendError, BagLocked, UserBagBackend, open_backend, user_handle_uid log = logging.getLogger("aurora-passkeys") @@ -95,29 +95,54 @@ def runtime_socket(): class UserBagSecret: - """The vault key, sealed to a no-touch key under the user's key bag. - - Placeholder until sep-key interface 4 (SEP_KEY_CREATE_USER_BAG_ONLY: - a key under the caller's bag whose list needs the bag unlocked, no - credential). Until then it refuses; it never keeps a host-readable key. + """The vault key (64 bytes that wrap credential IDs and records), sealed + to a key with no list under the user's own key bag (interface 4, + SEP_KEY_CREATE_USER with flags 0). + + The enclave opens it with no touch and no password, but only while the + bag is unlocked (the user logged in with their password). Root cannot + open it while the user is logged out, and nothing host-readable is kept. + File vault.key: CBOR {1: key handle, 2: sealed vault key}. """ - def __init__(self, backend, state_dir): - self.backend = backend - self.state_dir = state_dir + FILE = "vault.key" + + def __init__(self, sep, uid, state_dir): + self.sep = sep + self.uid = uid + self.path = os.path.join(state_dir, self.FILE) def _need_iface(self): - if getattr(self.backend, "version", 0) < SEP_KEY_IFACE_USER_BAG: + if not getattr(self.sep, "can_password", False): raise BackendError( "per-user passkeys need /dev/sep-key interface 4 (keys under your own key " - "bag); this kernel has interface %s" % getattr(self.backend, "version", "?")) - raise BackendError("interface 4 vault key: not implemented yet") + "bag, variant-5 key store); this kernel has interface %s" + % getattr(self.sep, "version", "?")) - def load(self): + def new(self): self._need_iface() + handle, _point = self.sep.create_user(self.uid, False) + secret = os.urandom(64) + sealed = self.sep.seal(handle, secret) + if self.sep.unseal(handle, sealed) != secret: + raise BackendError("the enclave did not give the vault key back") + creds.atomic_write(self.path, cbor.encode({1: handle, 2: sealed})) + log.info("made the vault key (sealed under your key bag)") + return secret - def new(self): + def load(self): self._need_iface() + try: + with open(self.path, "rb") as f: + rec = cbor.decode(f.read(8192)) + except FileNotFoundError: + return self.new() + if not (isinstance(rec, dict) and isinstance(rec.get(1), bytes) + and isinstance(rec.get(2), bytes)): + raise BackendError("%s is damaged" % self.path) + if user_handle_uid(rec[1]) != self.uid: + raise BackendError("%s belongs to another user" % self.path) + return self.sep.unseal(rec[1], rec[2]) def per_user_info(resp): @@ -259,10 +284,16 @@ def main(argv=None): os.umask(0o077) os.makedirs(state_dir, mode=0o700, exist_ok=True) cfg = daemon.load_config(a.config) + uid = os.getuid() try: - backend = open_backend(cfg.get("keys", "store")) - auth, note = build_agent(cfg, state_dir, backend, UserBagSecret(backend, state_dir), name, + sep = open_backend(cfg.get("keys", "store")) + secret = UserBagSecret(sep, uid, state_dir) + secret._need_iface() + auth, note = build_agent(cfg, state_dir, UserBagBackend(sep, uid), secret, name, SitePolicy(os.path.join(config_dir(), "sites.conf"))) + except BagLocked as e: + log.error("%s; aurora-passkeyd starts again when you log in", e) + return 1 except (BackendError, ValueError, OSError) as e: log.error("%s", e) return 1 diff --git a/fido/aurora_fido/backend.py b/fido/aurora_fido/backend.py index 49cde4c..0143df6 100644 --- a/fido/aurora_fido/backend.py +++ b/fido/aurora_fido/backend.py @@ -58,6 +58,15 @@ class EnclaveCancelled(BackendError): """The waiting signature was cancelled (SEP_KEY_CANCEL).""" +class BagLocked(BackendError): + """The enclave refuses a key under the user's key bag: the bag is locked + (logged out, suspended) or is not this OS install's.""" + + +class PasswordRefused(BackendError): + """The enclave refused the password; it counted the try.""" + + class KeyBackend: name = "abstract" #: CREATE flags this backend offers (SEP_KEY_CREATE_*). @@ -97,6 +106,21 @@ def cancel(self): def public(self, handle): raise NotImplementedError + # -- interface 4: keys under a user's key bag ------------------------------------ + + def create_user(self, uid, presence): + """(handle, point) of a key under uid's bag: presence=True makes a + .userPresence key (Touch ID or the bag's password), False a key with no + list that works only while the bag is unlocked.""" + raise BackendError("this kernel cannot make keys under a user's key bag") + + def sign_password(self, handle, digest, password): + """Like sign(), with the bag's password checked by the enclave instead of a touch.""" + raise BackendError("this kernel cannot check a password in the enclave") + + def unseal_password(self, handle, sealed, password): + raise BackendError("this kernel cannot check a password in the enclave") + def _ioc(direction, magic, nr, size): return direction << 30 | size << 16 | magic << 8 | nr @@ -115,6 +139,13 @@ def _ioc(direction, magic, nr, size): # struct sep_key_seal, for SEAL (secret in, sealed out) and UNSEAL (sealed in, # secret out): flags, handle_len, secret_len, sealed_len, secret, sealed, handle _SEAL = struct.Struct(f" HANDLE_HEADER_USER + and handle[:4] == SEP_MAGIC and handle[4] == HANDLE_VERSION_USER + and handle[5] & HANDLE_FLAG_USER_BAG): + return struct.unpack(" 5 and bool(handle[5] & HANDLE_FLAG_BIOMETRY)) @@ -196,7 +254,12 @@ def __init__(self, path="/dev/sep-key"): self.handle_max = min(handle_max, _HANDLE_MAX) @staticmethod - def _error(e): + def _error(e, user=False, password=False): + if user and e.errno == EKEYREJECTED: + return BagLocked("the enclave refused the key: your key bag is locked " + "(log in again) or belongs to another install") + if password and e.errno == errno.EACCES: + return PasswordRefused("the enclave refused the password") if e.errno in (errno.EINVAL, EKEYREJECTED): return InvalidHandle(e.strerror) if e.errno == errno.EACCES: @@ -207,11 +270,11 @@ def _error(e): return EnclaveCancelled("cancelled") return BackendError(e.strerror) - def _call(self, req, buf): + def _call(self, req, buf, user=False, password=False): try: fcntl.ioctl(self.fd, req, buf, True) except OSError as e: - raise self._error(e) from e + raise self._error(e, user, password) from e def gated(self, handle): return is_gated_handle(handle) @@ -238,7 +301,7 @@ def sign(self, handle, digest): if len(digest) != DIGEST_LEN: raise ValueError("digest must be 32 bytes") buf = bytearray(_SIGN.pack(0, len(handle), digest, 0, b"", handle)) - self._call(IOC_SIGN, buf) + self._call(IOC_SIGN, buf, user=user_handle_uid(handle) is not None) _f, _n, _d, sig_len, sig, _h = _SIGN.unpack(buf) if not 0 < sig_len <= _SIG_MAX: raise BackendError("malformed sign reply") @@ -251,7 +314,7 @@ def unseal(self, handle, sealed): if not 0 < len(sealed) <= _SEALED_MAX: raise InvalidHandle("sealed secret length") buf = bytearray(_SEAL.pack(0, len(handle), 0, len(sealed), b"", sealed, handle)) - self._call(IOC_UNSEAL, buf) + self._call(IOC_UNSEAL, buf, user=user_handle_uid(handle) is not None) _f, _n, secret_len, _sl, secret, _s, _h = _SEAL.unpack(buf) if not 0 < secret_len <= _SECRET_MAX: raise BackendError("malformed unseal reply") @@ -264,7 +327,7 @@ def seal(self, handle, secret): if not 0 < len(secret) <= _SECRET_MAX: raise ValueError("secret length") buf = bytearray(_SEAL.pack(0, len(handle), len(secret), 0, secret, b"", handle)) - self._call(IOC_SEAL, buf) + self._call(IOC_SEAL, buf, user=user_handle_uid(handle) is not None) _f, _n, _sl, sealed_len, _s, sealed, _h = _SEAL.unpack(buf) if not 0 < sealed_len <= _SEALED_MAX: raise BackendError("malformed seal reply") @@ -281,9 +344,134 @@ def cancel(self): def public(self, handle): self._check(handle) buf = bytearray(_PUBLIC.pack(0, len(handle), b"", b"", handle)) - self._call(IOC_PUBLIC, buf) + self._call(IOC_PUBLIC, buf, user=user_handle_uid(handle) is not None) return _PUBLIC.unpack(buf)[2] + # -- interface 4 --------------------------------------------------------------------- + + def _need_password_iface(self): + if not self.can_password: + raise BackendError("this kernel's /dev/sep-key has no keys under a user's key " + "bag (interface 4, variant-5 key store)") + + def create_user(self, uid, presence): + self._need_password_iface() + flags = CREATE_USER_PRESENCE if presence else 0 + buf = bytearray(_CREATE_USER.pack(flags, uid, 0, b"", b"", b"")) + self._call(IOC_CREATE_USER, buf, user=True) + _f, _u, n, point, _r, handle = _CREATE_USER.unpack(buf) + if not 0 < n <= self.handle_max or point[0] != 4: + raise BackendError("malformed create reply") + handle = handle[:n] + if user_handle_uid(handle) != uid or is_gated_handle(handle) != presence: + raise BackendError("the kernel made a key other than the one asked for") + return handle, point + + @staticmethod + def _password(password): + if not 0 < len(password) <= _PASSWORD_MAX: + raise PasswordRefused("password length") + return bytes(password) + + def sign_password(self, handle, digest, password): + self._need_password_iface() + self._check(handle) + if len(digest) != DIGEST_LEN: + raise ValueError("digest must be 32 bytes") + pw = self._password(password) + buf = bytearray(_SIGN_PASSWORD.pack(0, len(handle), digest, 0, b"", handle, + len(pw), 0, pw)) + try: + self._call(IOC_SIGN_PASSWORD, buf, user=True, password=True) + f = _SIGN_PASSWORD.unpack(buf) + finally: + buf[_SIGN.size:] = bytes(len(buf) - _SIGN.size) # our copy of the password + sig_len, sig = f[3], f[4] + if not 0 < sig_len <= _SIG_MAX: + raise BackendError("malformed sign reply") + return sig[:sig_len] + + def unseal_password(self, handle, sealed, password): + self._need_password_iface() + self._check(handle) + if not 0 < len(sealed) <= _SEALED_MAX: + raise InvalidHandle("sealed secret length") + pw = self._password(password) + buf = bytearray(_SEAL_PASSWORD.pack(0, len(handle), 0, len(sealed), b"", sealed, + handle, len(pw), 0, pw)) + try: + self._call(IOC_UNSEAL_PASSWORD, buf, user=True, password=True) + f = _SEAL_PASSWORD.unpack(buf) + finally: + buf[_SEAL.size:] = bytes(len(buf) - _SEAL.size) + secret_len, secret = f[2], f[4] + if not 0 < secret_len <= _SECRET_MAX: + raise BackendError("malformed unseal reply") + return secret[:secret_len] + + +class UserBagBackend(KeyBackend): + """Credential keys under one user's key bag (interface 4), for that user's agent. + + Every credential key is a .userPresence key (Touch ID, or the bag's + password checked by the enclave): that is the only kind a user's own + process may make. Policies that need a biometric-only list are not + offered here (flags_supported), so a site rule asking for one is refused, + never weakened. + """ + + name = "sep-key (your key bag)" + flags_supported = CREATE_USER_PRESENCE + + def __init__(self, sep, uid): + self.sep = sep + self.uid = uid + self.can_unseal = sep.can_unseal + self.can_cancel = sep.can_cancel + self.can_password = True + self.pin_reboot_proof = sep.pin_reboot_proof + self.version = sep.version + + def create(self, flags): + if flags != CREATE_USER_PRESENCE: + raise BackendError("keys under your key bag are Touch ID or password keys " + "(.userPresence) only") + return self.sep.create_user(self.uid, True) + + def gated(self, handle): + return is_gated_handle(handle) and user_handle_uid(handle) == self.uid + + def _mine(self, handle): + if user_handle_uid(handle) != self.uid: + raise InvalidHandle("not a key under this user's bag") + + def sign(self, handle, digest): + self._mine(handle) + return self.sep.sign(handle, digest) + + def sign_password(self, handle, digest, password): + self._mine(handle) + return self.sep.sign_password(handle, digest, password) + + def seal(self, handle, secret): + self._mine(handle) + return self.sep.seal(handle, secret) + + def unseal(self, handle, sealed): + self._mine(handle) + return self.sep.unseal(handle, sealed) + + def unseal_password(self, handle, sealed, password): + self._mine(handle) + return self.sep.unseal_password(handle, sealed, password) + + def cancel(self): + self.sep.cancel() + + def public(self, handle): + self._mine(handle) + return self.sep.public(handle) + STORES = ("auto", "sep-key") diff --git a/fido/aurora_fido/ctap2.py b/fido/aurora_fido/ctap2.py index 1fe5a75..4f391ff 100644 --- a/fido/aurora_fido/ctap2.py +++ b/fido/aurora_fido/ctap2.py @@ -71,9 +71,14 @@ class Ctx: """Per-request context from the transport.""" - def __init__(self, cancel=None, on_up_needed=lambda: None): + def __init__(self, cancel=None, on_up_needed=lambda: None, password=None): self.cancel = cancel or threading.Event() self.on_up_needed = on_up_needed + # The user's login password for this one request (a bytearray the caller + # wipes), from the native front-end only: the enclave checks it in place + # of a touch for keys under the user's bag. CTAP has no route for it while + # clientPIN stays off. + self.password = password def _rp_hash(rp_id): @@ -233,6 +238,8 @@ def _outcome(self, ctx, result, request): raise CtapError(ERR_KEEPALIVE_CANCEL, "cancelled") if result == touchid.TIMEOUT: raise CtapError(ERR_USER_ACTION_TIMEOUT, "no touch") + if result == "wrong-password": # enclave.WRONG_PASSWORD + raise CtapError(ERR_PIN_INVALID, "the enclave refused the password") raise CtapError(ERR_OPERATION_DENIED, f"Touch ID: {result}") def ask(self, ctx, prompt, request=None): @@ -242,7 +249,8 @@ def ask(self, ctx, prompt, request=None): just refused is refused again at once (REFUSAL_REPLAY_WINDOW). """ self._replayed_refusal(prompt, request) - result = self.user.verify(prompt, ctx.cancel, ctx.on_up_needed) + result = self.user.verify(prompt, ctx.cancel, ctx.on_up_needed, + getattr(ctx, "password", None)) self._outcome(ctx, result, request) return "touchid" @@ -260,13 +268,17 @@ def _gated(self, ctx, prompt, cred, op, request=None): def _gated_sign(self, ctx, prompt, cred, msg, request=None): """The credential's signature over msg: the enclave waits for the finger.""" digest = hashlib.sha256(msg).digest() + pw = getattr(ctx, "password", None) return self._gated(ctx, prompt, cred, - lambda *a: self.user.sign(cred.handle, digest, *a), request) + lambda *a: self.user.sign(cred.handle, digest, *a, password=pw), + request) def _gated_unseal(self, ctx, prompt, cred, request=None): """The credential's sealed hmac-secret CredRandom pair, released after a match.""" + pw = getattr(ctx, "password", None) return self._gated(ctx, prompt, cred, - lambda *a: self.user.unseal(cred.handle, cred.sealed, *a), request) + lambda *a: self.user.unseal(cred.handle, cred.sealed, *a, + password=pw), request) def _probe_sign(self, msg): return self._probe_key.sign(msg, ec.ECDSA(hashes.SHA256())) diff --git a/fido/aurora_fido/enclave.py b/fido/aurora_fido/enclave.py index 7424a93..02e0b0d 100644 --- a/fido/aurora_fido/enclave.py +++ b/fido/aurora_fido/enclave.py @@ -33,14 +33,17 @@ from cryptography.hazmat.primitives.asymmetric.utils import Prehashed from . import cbor, creds, touchid -from .backend import (BackendError, EnclaveCancelled, EnclaveRefused, EnclaveTimeout, - InvalidHandle) +from .backend import (BackendError, BagLocked, EnclaveCancelled, EnclaveRefused, + EnclaveTimeout, InvalidHandle, PasswordRefused) log = logging.getLogger("aurora-fido") PRESENCE_FILE = "presence.key" # The kernel waits about a minute for a finger; a CANCEL ends it sooner. ENCLAVE_WAIT = 60.0 +# Results besides touchid.MATCH / NO_MATCH / TIMEOUT / CANCELLED: +WRONG_PASSWORD = "wrong-password" # the enclave refused the password (and counted it) +BAG_LOCKED = "bag-locked" # the user's key bag is locked: nothing under it works def verify_digest(point, digest, der_sig): @@ -146,26 +149,52 @@ def _prompt(self, op, prompt, cancel, waiting): return touchid.TIMEOUT, None except EnclaveCancelled: return touchid.CANCELLED, None + except BagLocked as e: + log.info("%s: %s", prompt.title(), e) + return BAG_LOCKED, None return touchid.NO_MATCH, None finally: self.notifier.close(note) - def sign(self, handle, digest, prompt, cancel, waiting=lambda: None): - """(result, DER signature): the enclave signs after it saw a match.""" + def _with_password(self, op, prompt): + """(result, value) of one enclave call that checks the bag's password itself. + + No retries here: every wrong password counts in the enclave, and the + caller decides whether to ask again.""" + with self.lock: + try: + return touchid.MATCH, op() + except PasswordRefused: + log.info("%s: the enclave refused the password", prompt.title()) + return WRONG_PASSWORD, None + except BagLocked as e: + log.info("%s: %s", prompt.title(), e) + return BAG_LOCKED, None + + def sign(self, handle, digest, prompt, cancel, waiting=lambda: None, password=None): + """(result, DER signature): the enclave signs after it saw a match, or + after it checked password (keys under the user's bag only).""" + if password is not None: + return self._with_password( + lambda: self.backend.sign_password(handle, digest, password), prompt) return self._prompt(lambda: self.backend.sign(handle, digest), prompt, cancel, waiting) - def unseal(self, handle, sealed, prompt, cancel, waiting=lambda: None): - """(result, secret): the enclave releases a sealed secret after a match.""" + def unseal(self, handle, sealed, prompt, cancel, waiting=lambda: None, password=None): + """(result, secret): the enclave releases a sealed secret after a match + (or after it checked password).""" + if password is not None: + return self._with_password( + lambda: self.backend.unseal_password(handle, sealed, password), prompt) return self._prompt(lambda: self.backend.unseal(handle, sealed), prompt, cancel, waiting) - def verify(self, prompt, cancel, waiting=lambda: None): + def verify(self, prompt, cancel, waiting=lambda: None, password=None): """A Touch ID approval for something that signs nothing: the presence key.""" for renew in (False, True): handle, point = self.presence_key(renew) nonce = os.urandom(32) try: - result, sig = self.sign(handle, nonce, prompt, cancel, waiting) + result, sig = self.sign(handle, nonce, prompt, cancel, waiting, password) except InvalidHandle: # touchid-current: the enrolled fingers changed, the enclave # retired the old presence key. Make a new one once. diff --git a/fido/aurora_fido/provider.py b/fido/aurora_fido/provider.py index 9e76039..46f5b69 100644 --- a/fido/aurora_fido/provider.py +++ b/fido/aurora_fido/provider.py @@ -22,9 +22,12 @@ class ProviderError(Exception): """name: a WebAuthn DOMException name (NotAllowedError, InvalidStateError, ...).""" - def __init__(self, name, message=""): + def __init__(self, name, message="", reason=None): super().__init__(message or name) self.name = name + # Finer cause for the portal UI: "wrong-password" (ask again; the enclave + # counted the try), else None. + self.reason = reason # CTAP status -> DOMException name (WebAuthn L3, "authenticatorMakeCredential"/ @@ -59,7 +62,9 @@ def __init__(self, auth): self.auth = auth def _call(self, cmd, params, ctx): - r = self.auth.handle(bytes([cmd]) + cbor.encode(params), ctx or ctap2.Ctx()) + r = self.auth.handle(bytes([cmd]) + cbor.encode(params), ctx) + if r[0] == E.ERR_PIN_INVALID: + raise ProviderError("NotAllowedError", "wrong password", "wrong-password") if r[0] != 0: raise ProviderError(_DOM.get(r[0], "NotAllowedError"), "CTAP status 0x%02x" % r[0]) return cbor.decode(r[1:]) if len(r) > 1 else {} @@ -73,7 +78,9 @@ def get_info(self): info = self.auth.get_info({}, None) return {"aaguid": info[3], "name": "Aurora Passwords", "algorithms": [a["alg"] for a in info[0x0A]], - "extensions": list(info[2]), "uv": ["biometric"], + "extensions": list(info[2]), + "uv": ["biometric"] + (["password"] if getattr(self.auth.backend, + "can_password", False) else []), "locked": False, "rk_remaining": info[0x14]} def list_credentials(self, rp_id, allow=()): @@ -92,7 +99,28 @@ def list_credentials(self, rp_id, allow=()): "display_name": "", "created": 0}) return out - def make_credential(self, cdh, rp, user, params, exclude=(), options=None, ctx=None): + @staticmethod + def _ctx(ctx, password): + ctx = ctx or ctap2.Ctx() + ctx.password = password + return ctx + + @staticmethod + def _wipe(password): + if isinstance(password, bytearray): + password[:] = bytes(len(password)) + + def make_credential(self, cdh, rp, user, params, exclude=(), options=None, ctx=None, + password=None): + """password: the user's login password (bytearray, wiped here) for the + enclave to check instead of a touch; None = Touch ID.""" + try: + return self._make(cdh, rp, user, params, exclude, options, + self._ctx(ctx, password)) + finally: + self._wipe(password) + + def _make(self, cdh, rp, user, params, exclude, options, ctx): o = dict(options or {}) self._check_origin(rp.get("id"), o.get("origin", "")) p = {1: cdh, 2: {k: v for k, v in rp.items() if k in ("id", "name")}, @@ -108,7 +136,13 @@ def make_credential(self, cdh, rp, user, params, exclude=(), options=None, ctx=N return {"attestation_object": cbor.encode(att), "transports": ["internal"], "extensions": r.get(6, {})} - def get_assertion(self, cdh, rp_id, credential_id, options=None, ctx=None): + def get_assertion(self, cdh, rp_id, credential_id, options=None, ctx=None, password=None): + try: + return self._get(cdh, rp_id, credential_id, options, self._ctx(ctx, password)) + finally: + self._wipe(password) + + def _get(self, cdh, rp_id, credential_id, options, ctx): o = dict(options or {}) self._check_origin(rp_id, o.get("origin", "")) p = {1: rp_id, 2: cdh, 3: [{"type": "public-key", "id": credential_id}]} diff --git a/fido/tests/stub.py b/fido/tests/stub.py index 3662beb..833b929 100644 --- a/fido/tests/stub.py +++ b/fido/tests/stub.py @@ -22,8 +22,10 @@ from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat from cryptography.exceptions import InvalidTag -from aurora_fido.backend import (EnclaveCancelled, EnclaveRefused, EnclaveTimeout, - InvalidHandle, KeyBackend) +import struct + +from aurora_fido.backend import (BagLocked, EnclaveCancelled, EnclaveRefused, EnclaveTimeout, + InvalidHandle, KeyBackend, PasswordRefused) MATCH, NO_MATCH, TIMEOUT, WAIT = "match", "no-match", "timeout", "wait" # Handle layout: "STUB" | gated flag | nonce[12] | AES-GCM(scalar) (48) | pad @@ -37,7 +39,7 @@ class StubKeyBackend(KeyBackend): name = "software-stub (TEST ONLY)" def __init__(self, key=None, handle_pad=0, mode=MATCH, flags_supported=0x3, - can_unseal=True, can_cancel=True): + can_unseal=True, can_cancel=True, can_password=True, bag_password=b"pw"): self._aead = AESGCM(key or secrets.token_bytes(32)) self.handle_pad = handle_pad # make handles longer, like a big SEP record self.mode = mode @@ -47,6 +49,14 @@ def __init__(self, key=None, handle_pad=0, mode=MATCH, flags_supported=0x3, self.signs = 0 # signatures the "enclave" made self.touches = 0 # touch waits the "enclave" ran self.creates = 0 + # Interface 4 stand-in: one user key bag (any uid), its password and lock. + self.can_password = can_password + self.version = 4 if can_password else 3 + self.pin_reboot_proof = False + self.bag_password = bag_password + self.bag_locked = False + self.password_failures = 0 + self.password_signs = 0 self._cancel = threading.Event() self.lock = threading.Lock() @@ -60,7 +70,28 @@ def create(self, flags, gated=True): self.last_flags = flags return handle, self._point(priv) + # Interface 4: a SEPK version-2 header (as the kernel writes it) around a stub handle. + def create_user(self, uid, presence): + if not self.can_password: + raise AssertionError("create_user on a stub without interface 4") + if self.bag_locked: + raise BagLocked("bag locked") + inner, point = self.create(0x4 if presence else 0, gated=presence) + flags = 0x04 if presence else 0x0C + return (b"SEPK" + bytes([2, flags, 0, 0]) + struct.pack(" 16: + return handle[16:], handle[5] + return handle, None + def gated(self, handle): + inner, uflags = self._user(handle) + if uflags is not None: + return uflags == 0x04 return isinstance(handle, bytes) and handle[:4] == b"STUB" and len(handle) > 4 \ and bool(handle[4] & _GATED) @@ -69,6 +100,7 @@ def _point(priv): return priv.public_key().public_bytes(Encoding.X962, PublicFormat.UncompressedPoint) def _priv(self, handle): + handle, _ = self._user(handle) if handle[:4] != b"STUB" or len(handle) < 5 + 12 + 48: raise InvalidHandle("not a stub handle") try: @@ -87,6 +119,8 @@ def _next_mode(self, handle): def _touch(self, handle): """The scripted enclave match for a gated key; raises like the kernel.""" + if self._user(handle)[1] is not None and self.bag_locked: + raise BagLocked("bag locked") if not self.gated(handle): return with self.lock: @@ -128,6 +162,30 @@ def unseal(self, handle, sealed): except InvalidTag as e: raise InvalidHandle("sealed for another key") from e + def _password(self, handle, password): + if self._user(handle)[1] != 0x04: + raise InvalidHandle("password calls take .userPresence keys under a user bag") + if self.bag_locked: + raise BagLocked("bag locked") + if bytes(password) != self.bag_password: + self.password_failures += 1 + raise PasswordRefused("wrong password") + + def sign_password(self, handle, digest, password): + priv = self._priv(handle) + self._password(handle, password) + self.signs += 1 + self.password_signs += 1 + return priv.sign(digest, ec.ECDSA(Prehashed(hashes.SHA256()))) + + def unseal_password(self, handle, sealed, password): + self._priv(handle) + self._password(handle, password) + try: + return AESGCM(self._seal_key(handle)).decrypt(sealed[:12], sealed[12:], b"seal") + except InvalidTag as e: + raise InvalidHandle("sealed for another key") from e + def cancel(self): if self.can_cancel: self._cancel.set() diff --git a/fido/tests/test_agent.py b/fido/tests/test_agent.py index c990f73..d151951 100644 --- a/fido/tests/test_agent.py +++ b/fido/tests/test_agent.py @@ -5,6 +5,7 @@ Run from fido/: python3 tests/test_agent.py """ +import hashlib import os import socket import sys @@ -16,9 +17,10 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from aurora_fido import agent, cbor, creds, ctap2, daemon, remote # noqa: E402 +from aurora_fido import agent, backend, cbor, creds, ctap2, daemon, remote # noqa: E402 from aurora_fido import errors as E # noqa: E402 -from aurora_fido.backend import BackendError # noqa: E402 +from aurora_fido.backend import BackendError, BagLocked, UserBagBackend # noqa: E402 +from aurora_fido.provider import Provider, ProviderError # noqa: E402 import stub # noqa: E402 from stub import FileSecret, StubKeyBackend # noqa: E402 from test_ctap import CDH, parse_auth_data # noqa: E402 @@ -29,15 +31,20 @@ class Agent: """One user's aurora-passkeyd on the stub enclave, in a temp dir.""" - def __init__(self, root, name, allowed=None, mode=stub.MATCH, sites=None, flags_supported=0x3): + def __init__(self, root, name, allowed=None, mode=stub.MATCH, sites=None, flags_supported=0x3, + userbag=False, backend=None): self.state = os.path.join(root, name, "state") - os.makedirs(self.state, mode=0o700) - self.backend = StubKeyBackend(mode=mode, flags_supported=flags_supported) + os.makedirs(self.state, mode=0o700, exist_ok=True) + self.backend = backend or StubKeyBackend(mode=mode, flags_supported=flags_supported) cfg = daemon.load_config(None) cfg.set("touchid", "notify", "no") - self.auth, _ = agent.build_agent(cfg, self.state, self.backend, - FileSecret(os.path.join(root, name, "vault")), "root", - sites) + if userbag: # interface 4: credentials and the vault key under the user's bag + keys = UserBagBackend(self.backend, UID) + secret = agent.UserBagSecret(self.backend, UID, self.state) + else: + keys = self.backend + secret = FileSecret(os.path.join(root, name, "vault")) + self.auth, _ = agent.build_agent(cfg, self.state, keys, secret, "root", sites) self.path = os.path.join(root, name, "run", "ctap.sock") self.srv = agent.AgentServer(self.auth, self.path, {UID} if allowed is None else allowed).bind() @@ -237,9 +244,107 @@ def test_vault_key_needs_interface_4(self): class Old: version = 3 with self.assertRaises(BackendError) as c: - agent.UserBagSecret(Old(), self.tmp.name).load() + agent.UserBagSecret(Old(), UID, self.tmp.name).load() self.assertIn("interface 4", str(c.exception)) +class UserBagTest(unittest.TestCase): + """Interface 4: keys and the vault key under the user's own key bag.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.agents = [] + + def tearDown(self): + for a in self.agents: + a.close() + self.tmp.cleanup() + + def agent(self, name="u", **kw): + a = Agent(self.tmp.name, name, userbag=True, **kw) + self.agents.append(a) + f = Fidod({UID: a.path}) + f.active = UID + return a, f + + def test_passkey_is_a_user_presence_key_under_the_bag(self): + a, f = self.agent() + st, mc = f.make() + self.assertEqual(st, 0) + self.assertEqual(a.auth.policy, creds.POLICY_TOUCHID_OR_PASSWORD) + cred = a.auth.vault.unwrap(hashlib.sha256(b"example.com").digest(), + parse_auth_data(mc[2])["cred_id"]) + self.assertEqual(backend.user_handle_uid(cred.handle), UID) + self.assertTrue(backend.is_gated_handle(cred.handle)) + self.assertTrue(os.path.exists(os.path.join(a.state, "vault.key"))) + st, _ = f.ga() + self.assertEqual(st, 0) + + def test_vault_key_is_a_plain_bag_key_and_reopens(self): + a, f = self.agent() + self.assertEqual(f.make()[0], 0) + with open(os.path.join(a.state, "vault.key"), "rb") as fh: + rec = cbor.decode(fh.read()) + self.assertTrue(backend.is_user_plain_handle(rec[1])) + self.assertFalse(backend.is_gated_handle(rec[1])) # never a credential key + a.close() + self.agents.remove(a) + b, f2 = self.agent(backend=a.backend) # agent restart, same enclave + st, r = f2.ga() + self.assertEqual(st, 0) # records open again + + def test_locked_bag_refuses_everything(self): + a, f = self.agent() + self.assertEqual(f.make()[0], 0) + signs = a.backend.signs + a.backend.bag_locked = True + st, _ = f.ga() + self.assertEqual(st, E.ERR_OPERATION_DENIED) + self.assertEqual(a.backend.signs, signs) + with self.assertRaises(BagLocked): + agent.UserBagSecret(a.backend, UID, a.state).load() # no vault key while locked + a.backend.bag_locked = False + self.assertEqual(f.ga()[0], 0) + + def test_password_route_through_the_native_front_end(self): + a, f = self.agent(mode=stub.NO_MATCH) # no finger at all + p = Provider(a.auth) + o = {"origin": "https://example.com"} + pw = bytearray(b"pw") + r = p.make_credential(CDH, {"id": "example.com"}, {"id": b"u1", "name": "r"}, [-7], + options=o, password=pw) + self.assertEqual(pw, bytearray(2)) # wiped + cid = parse_auth_data(cbor.decode(r["attestation_object"])["authData"])["cred_id"] + a2 = p.get_assertion(CDH, "example.com", cid, o, password=bytearray(b"pw")) + self.assertTrue(a2["signature"]) + self.assertEqual(a.backend.password_signs, 2) + before = a.backend.signs + with self.assertRaises(ProviderError) as c: + p.get_assertion(CDH, "example.com", cid, o, password=bytearray(b"nope")) + self.assertEqual(c.exception.reason, "wrong-password") + self.assertEqual(a.backend.password_failures, 1) # counted by the "enclave" + self.assertEqual(a.backend.signs, before) + with self.assertRaises(ProviderError): # and no finger: refused + p.get_assertion(CDH, "example.com", cid, o) + self.assertIn("password", p.get_info()["uv"]) + + def test_biometric_only_site_rule_is_refused_under_the_bag(self): + conf = os.path.join(self.tmp.name, "sites.conf") + with open(conf, "w") as fh: + fh.write("bank.example = touchid-current\n") + a, f = self.agent(sites=agent.SitePolicy(conf)) + st, _ = f.make(rp="bank.example") + self.assertEqual(st, E.ERR_UNSUPPORTED_OPTION) + self.assertEqual(f.make(rp="other.example")[0], 0) + + def test_another_users_handle_is_refused(self): + a, _ = self.agent() + mine = UserBagBackend(a.backend, UID) + h, _p = a.backend.create_user(UID + 1, True) + with self.assertRaises(backend.InvalidHandle): + mine.sign(h, b"\0" * 32) + self.assertFalse(mine.gated(h)) + + if __name__ == "__main__": unittest.main() From 2d4bcd4ecff721de5bc2d8bf96f8e0b2a2923889 Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:33:29 +1100 Subject: [PATCH 5/8] docs: fido: per-user mode on interface 4 (keys and vault key under the user's bag, password route, device access) Co-Authored-By: Claude Opus 5.5 --- docs/fido.md | 38 ++++++++++++++++++++++++++++++-------- 1 file changed, 30 insertions(+), 8 deletions(-) diff --git a/docs/fido.md b/docs/fido.md index cdee1ee..d432bdf 100644 --- a/docs/fido.md +++ b/docs/fido.md @@ -172,18 +172,40 @@ credential records in `$XDG_DATA_HOME/aurora-passkeys` and makes the `CTAP2_ERR_OPERATION_DENIED`. - U2F is not forwarded in this mode. -The agent's vault key is sealed to a key under the user's own key bag -(`/dev/sep-key` interface 4). So the records cannot be read while the user -is logged out, and the credential keys sign for nobody else, root included. -On a kernel without interface 4 the agent refuses to start. +**Keys under your key bag (interface 4).** The agent needs `/dev/sep-key` +interface 4 (variant-5 key store: the Neo and the M4 Pro) and refuses to +start without it. + +- **Credential keys** are `.userPresence` keys under the user's own key bag, + the bag whose secret is the login password. The enclave approves one of + these keys after a Touch ID match or after it has checked that password + itself. Root can ask the kernel to sign with such a key, but the enclave + still waits for the touch or the password. Nothing works while the bag is + locked (logged out, suspended). +- **The vault key**, 64 bytes that wrap credential IDs and records, is + sealed to a key with no list under the same bag (`vault.key`). It opens + with no touch while the bag is unlocked, and not at all while it is + locked. So the agent cannot start, and nobody can read the records, until + the user logs in. The running agent keeps the vault key in memory until it + exits; systemd stops user units at logout unless lingering is on. +- **The password route** exists only on the native front-end (`provider.py`, + for a credentials portal). A request may carry the login password, and the + enclave checks it in place of a touch: one call, no retries, and each + wrong password counts in the enclave (`CTAP2_ERR_PIN_INVALID`). CTAP over + hidraw has no route for it while clientPIN stays off. +- **Access to the device:** `/dev/sep-key` is root-only by default. For + per-user mode, give the user (or a group) access to it. The kernel lets a + non-root caller use only keys under that caller's own bag. **Per-site rules.** `~/.config/aurora-passkeys/sites.conf` holds lines of -the form `site = policy`, for example `bank.example = touchid-current`. A rule -covers the site and every name under it, and the longest match wins. The -rule is written into the new credential's access-control list, so the +the form `site = policy`, for example `bank.example = touchid-or-password`. A +rule covers the site and every name under it, and the longest match wins. +The rule is written into the new credential's access-control list, so the enclave enforces it. Changing a rule affects new credentials only. If the kernel cannot make the key a rule asks for, the registration is refused -(`CTAP2_ERR_UNSUPPORTED_OPTION`); a weaker key is never made instead. +(`CTAP2_ERR_UNSUPPORTED_OPTION`); a weaker key is never made instead. Under a +user's bag the kernel makes `.userPresence` keys only, so biometric-only +rules (`touchid-any`, `touchid-current`) are refused there. ### Existing credentials (migration from 0.1) From 87485a04dede15143a6f50cc036bd9098c8adcac Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:40:18 +1100 Subject: [PATCH 6/8] fido: passkey agent: native front-end on the session bus (org.aurora.Passkeys1) dbus_provider.py binds provider.py with jeepney: GetInfo, ListCredentials, MakeCredential, GetAssertion, Cancel and the UserActionNeeded signal on org.aurora.Passkeys.Provider1 at /org/aurora/Passkeys1. options carry the origin and, optionally, password_fd (a memfd or pipe holding the login password, read once and wiped) for the enclave to check instead of a touch; errors are org.aurora.Passkeys.Error., a wrong password is ...WrongPassword. Callers: the session's own uid, and with [native] portal_names only the current owner of one of those names. Cancel works only from the connection that started the request. aurora-passkeyd starts it when jeepney and a session bus are there (--no-dbus to skip). Tests: tests/test_dbus_provider.py on a private bus (dbus-run-session; skipped without jeepney): introspection, info, touch register/list/sign-in, wrong origin, password by fd (wrong counted, right signs), cancel from the right connection only, portal-name gate. Co-Authored-By: Claude Opus 5.5 --- fido/Makefile | 3 + fido/aurora-fido.conf | 8 + fido/aurora_fido/agent.py | 31 ++++ fido/aurora_fido/dbus_provider.py | 275 ++++++++++++++++++++++++++++++ fido/tests/test_dbus_provider.py | 163 ++++++++++++++++++ 5 files changed, 480 insertions(+) create mode 100644 fido/aurora_fido/dbus_provider.py create mode 100644 fido/tests/test_dbus_provider.py diff --git a/fido/Makefile b/fido/Makefile index 6ac600e..6d54258 100644 --- a/fido/Makefile +++ b/fido/Makefile @@ -55,6 +55,9 @@ check: $(PYTHON) tests/test_ctap.py $(PYTHON) tests/test_agent.py $(PYTHON) tests/test_provider.py + if command -v dbus-run-session >/dev/null 2>&1; then \ + dbus-run-session -- $(PYTHON) tests/test_dbus_provider.py; \ + else $(PYTHON) tests/test_dbus_provider.py; fi # As root: the real uhid device with libfido2, OpenSSH, pam_u2f, cryptenroll. check-uhid: diff --git a/fido/aurora-fido.conf b/fido/aurora-fido.conf index 59d8e17..8aaee15 100644 --- a/fido/aurora-fido.conf +++ b/fido/aurora-fido.conf @@ -42,3 +42,11 @@ vault = system # Where credential keys live: the Secure Enclave (/dev/sep-key), always. # "auto" and "sep-key" mean the same; there is no other store. store = auto + +[native] +# Per-user mode only: aurora-passkeyd also serves the native (platform +# authenticator) front-end on the session bus as org.aurora.Passkeys1. +# Bus names allowed to call it, separated by spaces (a credentials portal). +# Empty: any process of the user, which can reach the security key through +# hidraw anyway. +portal_names = diff --git a/fido/aurora_fido/agent.py b/fido/aurora_fido/agent.py index e60c8db..402167e 100644 --- a/fido/aurora_fido/agent.py +++ b/fido/aurora_fido/agent.py @@ -272,6 +272,7 @@ def main(argv=None): ap.add_argument("--config", default=daemon.CONFIG) ap.add_argument("--state-dir", default=None) ap.add_argument("--socket", default=None) + ap.add_argument("--no-dbus", action="store_true", help="no session-bus front-end") ap.add_argument("-v", "--verbose", action="store_true") a = ap.parse_args(argv) logging.basicConfig(level=logging.DEBUG if a.verbose else logging.INFO, @@ -300,6 +301,7 @@ def main(argv=None): if note: log.info("%s", note) srv = AgentServer(auth, a.socket or runtime_socket(), {0, os.getuid()}).bind() + dbus = None if a.no_dbus else start_dbus(auth, cfg) for s in (signal.SIGTERM, signal.SIGINT): signal.signal(s, lambda *_: srv.stop.set()) log.info("aurora-passkeyd %s ready for %s", __version__, name) @@ -307,8 +309,37 @@ def main(argv=None): srv.serve_forever() finally: srv.close() + if dbus: + dbus.close() return 0 +def start_dbus(auth, cfg): + """The native front-end on the session bus (org.aurora.Passkeys1), if possible. + + [native] portal_names: bus names allowed to call it (a credentials portal); + empty = any process of this user, which can already reach the security key + through hidraw, so it grants nothing new.""" + try: + from . import dbus_provider + from .provider import Provider + except ImportError as e: + log.info("no D-Bus front-end (%s)", e) + return None + names = cfg.get("native", "portal_names", fallback="").split() + try: + svc = dbus_provider.ProviderService(Provider(auth), allow_names=names) + if not svc.request_name(): + log.warning("%s is taken; no D-Bus front-end", dbus_provider.BUS_NAME) + svc.close() + return None + except (OSError, KeyError) as e: + log.info("no session bus (%s); no D-Bus front-end", e) + return None + threading.Thread(target=svc.serve_forever, name="passkeys-dbus", daemon=True).start() + log.info("native front-end on the session bus as %s", dbus_provider.BUS_NAME) + return svc + + if __name__ == "__main__": sys.exit(main()) diff --git a/fido/aurora_fido/dbus_provider.py b/fido/aurora_fido/dbus_provider.py new file mode 100644 index 0000000..09d011b --- /dev/null +++ b/fido/aurora_fido/dbus_provider.py @@ -0,0 +1,275 @@ +# SPDX-License-Identifier: MIT +"""D-Bus binding of the native front-end (provider.py) on the session bus. + +Interface org.aurora.Passkeys.Provider1 at /org/aurora/Passkeys1, bus name +org.aurora.Passkeys1: the provider a credentials portal (credentialsd's +proposed Provider1, docs/passkeys/CREDENTIALSD-PROVIDER.md) calls for the +"internal" transport. + + GetInfo() -> a{sv} + ListCredentials(s rp_id, aay allow) -> aa{sv} + MakeCredential(u req, ay cdh, a{sv} rp, a{sv} user, ai algs, aay exclude, a{sv} options) -> a{sv} + GetAssertion(u req, ay cdh, s rp_id, ay credential_id, a{sv} options) -> a{sv} + Cancel(u req) + signal UserActionNeeded(u req, s kind, a{sv} detail) kind: "touch" + +options: "origin" s (required), "top_origin" s, "rk" b, "extensions" a{sv}, +"password_fd" h: a memfd (or pipe) holding the user's login password, which +the enclave checks in place of a touch. It is read once, then the buffer is wiped. +Errors are org.aurora.Passkeys.Error., for example +org.aurora.Passkeys.Error.NotAllowedError; a wrong password is +org.aurora.Passkeys.Error.WrongPassword. + +Callers: only the session's own uid, and, when allow_names is set, only the +current owner of one of those bus names (the portal). Every signature is +still an enclave-checked touch or password; this layer decides nothing. +""" + +import logging +import os +import threading + +from jeepney import (DBusAddress, HeaderFields, MessageType, new_error, new_method_return, + new_signal) +from jeepney.bus_messages import message_bus +from jeepney.io.blocking import open_dbus_connection + +from . import ctap2 +from .provider import ProviderError + +log = logging.getLogger("aurora-passkeys") + +BUS_NAME = "org.aurora.Passkeys1" +PATH = "/org/aurora/Passkeys1" +IFACE = "org.aurora.Passkeys.Provider1" +ERR = "org.aurora.Passkeys.Error." +MAX_PASSWORD = 256 + +INTROSPECT = f""" + + + + + + + + + + + + + + + + + + + + +""" + + +# -- a{sv} <-> Python ------------------------------------------------------------------------ + +def variant(v): + if isinstance(v, bool): + return ("b", v) + if isinstance(v, int): + return ("x", v) + if isinstance(v, str): + return ("s", v) + if isinstance(v, (bytes, bytearray)): + return ("ay", bytes(v)) + if isinstance(v, dict): + return ("a{sv}", asv(v)) + if isinstance(v, (list, tuple)): + if all(isinstance(x, str) for x in v): + return ("as", list(v)) + if all(isinstance(x, (bytes, bytearray)) for x in v): + return ("aay", [bytes(x) for x in v]) + if all(isinstance(x, int) and not isinstance(x, bool) for x in v): + return ("ax", list(v)) + return ("av", [variant(x) for x in v]) + raise TypeError("no D-Bus type for %r" % type(v)) + + +def asv(d): + return {str(k): variant(v) for k, v in d.items()} + + +def unvariant(d): + """a{sv} from jeepney ({k: (sig, value)}) -> plain dict; nested a{sv} too.""" + out = {} + for k, (sig, v) in d.items(): + out[k] = unvariant(v) if sig == "a{sv}" else v + return out + + +def read_password(fd): + """The password from a file descriptor (FileDescriptor or int), as a bytearray.""" + raw = fd.to_raw_fd() if hasattr(fd, "to_raw_fd") else int(fd) + try: + try: + os.lseek(raw, 0, os.SEEK_SET) + except OSError: + pass # a pipe + buf = bytearray(MAX_PASSWORD + 1) + n = 0 + while n < len(buf): + k = os.readv(raw, [memoryview(buf)[n:]]) + if k == 0: + break + n += k + finally: + os.close(raw) + if not 0 < n <= MAX_PASSWORD: + buf[:] = bytes(len(buf)) + raise ProviderError("NotAllowedError", "password length") + pw = buf[:n] + buf[:] = bytes(len(buf)) + return pw + + +# -- the service ---------------------------------------------------------------------------- + +class ProviderService: + def __init__(self, provider, bus="SESSION", allow_names=(), uid=None): + self.provider = provider + self.conn = open_dbus_connection(bus=bus, enable_fds=True) + self.query = open_dbus_connection(bus=bus) # for caller checks only + self.allow_names = tuple(allow_names) + self.uid = os.getuid() if uid is None else uid + self.send_lock = threading.Lock() + self.query_lock = threading.Lock() + self.requests = {} # (sender, req) -> Ctx + self.req_lock = threading.Lock() + self.stop = threading.Event() + self.emitter = DBusAddress(PATH, interface=IFACE) + + def request_name(self, name=BUS_NAME): + """Own name on the serving connection (before serve_forever starts).""" + reply = self.conn.send_and_get_reply(message_bus.RequestName(name, 4)) # DO_NOT_QUEUE + return reply.body[0] == 1 # PRIMARY_OWNER + + def _send(self, msg): + with self.send_lock: + self.conn.send(msg) + + def _caller_ok(self, sender): + with self.query_lock: + uid = self.query.send_and_get_reply(message_bus.GetConnectionUnixUser(sender)).body[0] + if uid != self.uid: + return False + if not self.allow_names: + return True + for name in self.allow_names: + r = self.query.send_and_get_reply(message_bus.GetNameOwner(name)) + if r.header.message_type == MessageType.method_return and r.body[0] == sender: + return True + return False + + def serve_forever(self): + while not self.stop.is_set(): + try: + msg = self.conn.receive(timeout=0.5) + except TimeoutError: + continue + except (OSError, ConnectionResetError): + if self.stop.is_set(): + break + raise + h = msg.header + if h.message_type != MessageType.method_call: + continue + threading.Thread(target=self._dispatch, args=(msg,), name="passkeys-dbus", + daemon=True).start() + + def close(self): + self.stop.set() + for c in (self.conn, self.query): + try: + c.close() + except OSError: + pass + + def _dispatch(self, msg): + h = msg.header.fields + iface, member = h.get(HeaderFields.interface), h.get(HeaderFields.member) + sender, path = h.get(HeaderFields.sender), h.get(HeaderFields.path) + try: + if path != PATH: + raise ProviderError("UnknownObject", "no object at %s" % path) + if iface == "org.freedesktop.DBus.Introspectable" and member == "Introspect": + self._send(new_method_return(msg, "s", (INTROSPECT,))) + return + if iface not in (IFACE, None): + raise ProviderError("UnknownMethod", "%s.%s" % (iface, member)) + if not self._caller_ok(sender): + log.warning("refused %s from %s", member, sender) + raise ProviderError("NotAllowedError", "caller not allowed") + fn = getattr(self, "m_" + (member or ""), None) + if fn is None: + raise ProviderError("UnknownMethod", member or "") + sig, body = fn(sender, *msg.body) + self._send(new_method_return(msg, sig, body)) + except ProviderError as e: + name = "WrongPassword" if e.reason == "wrong-password" else e.name + self._send(new_error(msg, ERR + name, "s", (str(e),))) + except Exception as e: # never kill the bus loop + log.exception("%s failed", member) + self._send(new_error(msg, ERR + "UnknownError", "s", (str(e),))) + + # -- methods --------------------------------------------------------------------------- + + def m_GetInfo(self, sender): + return "a{sv}", (asv(self.provider.get_info()),) + + def m_ListCredentials(self, sender, rp_id, allow): + return "aa{sv}", ([asv(c) for c in self.provider.list_credentials(rp_id, allow)],) + + def _ctx(self, sender, req): + ctx = ctap2.Ctx(threading.Event(), lambda: self._send(new_signal( + self.emitter, "UserActionNeeded", "usa{sv}", (req, "touch", {})))) + with self.req_lock: + if (sender, req) in self.requests: + raise ProviderError("InvalidStateError", "request id in use") + self.requests[(sender, req)] = ctx + return ctx + + def _done(self, sender, req): + with self.req_lock: + self.requests.pop((sender, req), None) + + @staticmethod + def _options(options): + o = unvariant(options) + fd = o.pop("password_fd", None) + return o, (read_password(fd) if fd is not None else None) + + def m_MakeCredential(self, sender, req, cdh, rp, user, algs, exclude, options): + o, pw = self._options(options) + ctx = self._ctx(sender, req) + try: + r = self.provider.make_credential(bytes(cdh), unvariant(rp), unvariant(user), list(algs), + list(exclude), o, ctx, password=pw) + finally: + self._done(sender, req) + return "a{sv}", (asv(r),) + + def m_GetAssertion(self, sender, req, cdh, rp_id, credential_id, options): + o, pw = self._options(options) + ctx = self._ctx(sender, req) + try: + r = self.provider.get_assertion(bytes(cdh), rp_id, bytes(credential_id), o, ctx, + password=pw) + finally: + self._done(sender, req) + return "a{sv}", (asv(r),) + + def m_Cancel(self, sender, req): + with self.req_lock: + ctx = self.requests.get((sender, req)) + if ctx is not None: + ctx.cancel.set() + return "", () diff --git a/fido/tests/test_dbus_provider.py b/fido/tests/test_dbus_provider.py new file mode 100644 index 0000000..604bc62 --- /dev/null +++ b/fido/tests/test_dbus_provider.py @@ -0,0 +1,163 @@ +# SPDX-License-Identifier: MIT +"""D-Bus binding of the native front-end, on a private session bus and the stub enclave. + +Run from fido/: dbus-run-session -- python3 tests/test_dbus_provider.py +Skipped without jeepney or a session bus. +""" + +import hashlib +import os +import sys +import tempfile +import threading +import time +import unittest + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +try: + from jeepney import DBusAddress, MessageType, new_method_call + from jeepney.bus_messages import message_bus + from jeepney.io.blocking import open_dbus_connection + from aurora_fido import dbus_provider as dp + HAVE = bool(os.environ.get("DBUS_SESSION_BUS_ADDRESS")) +except ImportError: + HAVE = False + +from aurora_fido import agent, cbor, ctap2, daemon # noqa: E402 +from aurora_fido.backend import UserBagBackend # noqa: E402 +from aurora_fido.provider import Provider # noqa: E402 +import stub # noqa: E402 +from test_ctap import CDH, parse_auth_data # noqa: E402 + +UID = os.getuid() +ORIGIN = {"origin": ("s", "https://example.com")} +RP = {"id": ("s", "example.com"), "name": ("s", "Example")} +USER = {"id": ("ay", b"user-1"), "name": ("s", "ryan")} + + +@unittest.skipUnless(HAVE, "needs jeepney and a session bus (dbus-run-session)") +class DbusProviderTest(unittest.TestCase): + def setUp(self, allow_names=()): + self.tmp = tempfile.TemporaryDirectory() + self.backend = stub.StubKeyBackend() + cfg = daemon.load_config(None) + cfg.set("touchid", "notify", "no") + state = os.path.join(self.tmp.name, "state") + os.makedirs(state) + self.auth, _ = agent.build_agent(cfg, state, UserBagBackend(self.backend, UID), + agent.UserBagSecret(self.backend, UID, state), "root") + self.svc = dp.ProviderService(Provider(self.auth), allow_names=allow_names) + self.assertTrue(self.svc.request_name()) + self.t = threading.Thread(target=self.svc.serve_forever, daemon=True) + self.t.start() + self.client = open_dbus_connection(bus="SESSION", enable_fds=True) + self.addr = DBusAddress(dp.PATH, bus_name=dp.BUS_NAME, interface=dp.IFACE) + + def tearDown(self): + self.client.close() + self.svc.close() + self.t.join(2) + self.tmp.cleanup() + + def call(self, member, sig=None, body=(), conn=None): + r = (conn or self.client).send_and_get_reply( + new_method_call(self.addr, member, sig, body), timeout=30) + if r.header.message_type == MessageType.error: + from jeepney import HeaderFields + return r.header.fields[HeaderFields.error_name], r.body + return None, r.body + + def make(self, options=ORIGIN, req=1): + return self.call("MakeCredential", "uaya{sv}a{sv}aiaaya{sv}", + (req, CDH, RP, USER, [-7], [], options)) + + def memfd(self, data): + fd = os.memfd_create("pw") + os.write(fd, data) + return fd + + def test_introspect_and_info(self): + r = self.client.send_and_get_reply(new_method_call( + DBusAddress(dp.PATH, bus_name=dp.BUS_NAME, interface="org.freedesktop.DBus.Introspectable"), + "Introspect")) + self.assertIn(dp.IFACE, r.body[0]) + err, (info,) = self.call("GetInfo") + self.assertIsNone(err) + self.assertEqual(info["aaguid"], ("ay", ctap2.AAGUID)) + self.assertIn("password", info["uv"][1]) + + def test_register_list_sign_in_with_touch(self): + err, (r,) = self.make() + self.assertIsNone(err, r) + att = cbor.decode(r["attestation_object"][1]) + ad = parse_auth_data(att["authData"]) + err, (lst,) = self.call("ListCredentials", "saay", ("example.com", [])) + self.assertEqual(len(lst), 1) + self.assertEqual(lst[0]["id"], ("ay", ad["cred_id"])) + err, (a,) = self.call("GetAssertion", "uaysaya{sv}", (2, CDH, "example.com", ad["cred_id"], ORIGIN)) + self.assertIsNone(err, a) + self.assertTrue(ctap2.verify_es256(ad["point"], a["authenticator_data"][1] + CDH, + a["signature"][1])) + + def test_wrong_origin(self): + err, _ = self.make({"origin": ("s", "https://evil.test")}) + self.assertEqual(err, dp.ERR + "SecurityError") + self.assertEqual(self.backend.creates, 1) # only the vault key + + def test_password_by_fd(self): + self.backend.mode = stub.NO_MATCH # nobody touches + err, _ = self.make(dict(ORIGIN, password_fd=("h", self.memfd(b"nope")))) + self.assertEqual(err, dp.ERR + "WrongPassword") + self.assertEqual(self.backend.password_failures, 1) + err, (r,) = self.make(dict(ORIGIN, password_fd=("h", self.memfd(b"pw"))), req=3) + self.assertIsNone(err, r) + self.assertEqual(self.backend.password_signs, 1) + + def test_cancel(self): + self.backend.mode = stub.WAIT + out = {} + th = threading.Thread(target=lambda: out.update(r=self.make(req=7))) + th.start() + time.sleep(0.5) + other = open_dbus_connection(bus="SESSION") + try: + # Cancel only works from the connection that started the request. + self.call("Cancel", "u", (7,), conn=other) + time.sleep(0.3) + self.assertTrue(th.is_alive()) + self.call("Cancel", "u", (7,)) + finally: + other.close() + th.join(10) + self.assertEqual(out["r"][0], dp.ERR + "NotAllowedError") + self.assertEqual(self.backend.signs, 0) + + +@unittest.skipUnless(HAVE, "needs jeepney and a session bus (dbus-run-session)") +class DbusAllowNamesTest(DbusProviderTest): + def setUp(self): + super().setUp(allow_names=("org.example.Portal",)) + + def test_only_the_portal(self): + err, _ = self.call("GetInfo") + self.assertEqual(err, dp.ERR + "NotAllowedError") + self.client.send_and_get_reply(message_bus.RequestName("org.example.Portal", 4)) + err, _ = self.call("GetInfo") + self.assertIsNone(err) + + # The inherited tests run without owning the portal name: all refused. + def _refused(self): + err, _ = self.call("GetInfo") + self.assertEqual(err, dp.ERR + "NotAllowedError") + + test_introspect_and_info = _refused + test_register_list_sign_in_with_touch = _refused + test_wrong_origin = _refused + test_password_by_fd = _refused + test_cancel = _refused + + +if __name__ == "__main__": + unittest.main() From 01289983bc231d8d53fc9016b5ee44276f00c1bd Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:41:00 +1100 Subject: [PATCH 7/8] fido: remote: keep the last getInfo per user The cached reply counts that user's passkeys (remainingDiscoverableCredentials); another user at the seat without a running agent gets the fixed description. Co-Authored-By: Claude Opus 5.5 --- fido/aurora_fido/remote.py | 18 +++++++++--------- fido/tests/test_agent.py | 3 +++ 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/fido/aurora_fido/remote.py b/fido/aurora_fido/remote.py index a45e20f..c5f6c5e 100644 --- a/fido/aurora_fido/remote.py +++ b/fido/aurora_fido/remote.py @@ -41,7 +41,7 @@ def __init__(self, active_uid=None, socket_path=agent_socket, timeout=90.0): self.active_uid = active_uid or self._seat_uid self.socket_path = socket_path self.timeout = timeout - self._info = None + self._info = {} # uid -> last getInfo reply (per user: it counts their passkeys) self.lock = threading.Lock() @staticmethod @@ -69,20 +69,20 @@ def handle(self, data, ctx=None): uid = self.active_uid() if uid is None: log.info("no active local session on seat0: request refused") - return self._fallback(is_info) + return self._fallback(is_info, None) try: s = self._connect(uid) except (OSError, PermissionError) as e: log.info("passkey agent of uid %d not reachable (%s): request refused", uid, e) - return self._fallback(is_info) + return self._fallback(is_info, uid) with s: try: - return self._exchange(s, data, ctx, is_info) + return self._exchange(s, data, ctx, is_info, uid) except (OSError, agentproto.ProtocolError) as e: log.warning("passkey agent of uid %d failed: %s", uid, e) - return self._fallback(is_info) + return self._fallback(is_info, uid) - def _exchange(self, s, data, ctx, is_info): + def _exchange(self, s, data, ctx, is_info, uid): agentproto.send(s, {"t": "req", "d": data}) done = threading.Event() @@ -105,14 +105,14 @@ def watch_cancel(): ctx.on_up_needed() elif msg["t"] == "resp": if is_info and msg["d"][:1] == b"\x00": - self._info = msg["d"] + self._info[uid] = msg["d"] return msg["d"] else: raise agentproto.ProtocolError("unexpected %r" % msg["t"]) finally: done.set() - def _fallback(self, is_info): + def _fallback(self, is_info, uid): if is_info: - return self._info or static_info() + return self._info.get(uid) or static_info() return bytes([ERR_OPERATION_DENIED]) diff --git a/fido/tests/test_agent.py b/fido/tests/test_agent.py index d151951..8c93a1f 100644 --- a/fido/tests/test_agent.py +++ b/fido/tests/test_agent.py @@ -163,6 +163,9 @@ def test_agent_down_uses_cached_info(self): self.assertEqual((st2, info2), (st, info)) st, _ = f.make() self.assertEqual(st, E.ERR_OPERATION_DENIED) + f.active = UID + 1 # another user, no agent: not a's info + st3, info3 = f.call(ctap2.CMD_GET_INFO) + self.assertEqual(info3, cbor.decode(remote.static_info()[1:])) def test_socket_served_by_another_uid_is_refused(self): a = self.agent("u") From 4af8fa2ea493a108cd3d3102e7781d6464c0d11a Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Thu, 12 Nov 2026 00:17:26 +1100 Subject: [PATCH 8/8] fido: passkey agent: open the vault per request VaultGate unseals the vault key from the user's bag at the start of each request (one enclave key exchange, no touch), across the CTAP socket and the native front-end, and closes the vault when the request ends. The key is in memory only during a request and only while the bag is unlocked: after logout or a bag lock the next request finds the vault closed (getInfo still answers; everything else is denied, the provider reports reason 'locked'). Test: the vault is closed after a request; with the bag locked getInfo works, getAssertion is denied and list_credentials is refused; after the unlock both work again. Co-Authored-By: Claude Opus 5.5 --- docs/fido.md | 5 ++- fido/aurora_fido/agent.py | 84 +++++++++++++++++++++++++++++++++--- fido/aurora_fido/provider.py | 34 ++++++++++++--- fido/tests/test_agent.py | 29 +++++++++++-- 4 files changed, 132 insertions(+), 20 deletions(-) diff --git a/docs/fido.md b/docs/fido.md index d432bdf..3ec0088 100644 --- a/docs/fido.md +++ b/docs/fido.md @@ -186,8 +186,9 @@ start without it. sealed to a key with no list under the same bag (`vault.key`). It opens with no touch while the bag is unlocked, and not at all while it is locked. So the agent cannot start, and nobody can read the records, until - the user logs in. The running agent keeps the vault key in memory until it - exits; systemd stops user units at logout unless lingering is on. + the user logs in. The agent unseals the vault key at the start of each + request and drops it at the end, so it is in memory only during a request + and only while the bag is unlocked. Python frees the key but cannot zero it. - **The password route** exists only on the native front-end (`provider.py`, for a credentials portal). A request may carry the login password, and the enclave checks it in place of a touch: one call, no retries, and each diff --git a/fido/aurora_fido/agent.py b/fido/aurora_fido/agent.py index 402167e..6950e6d 100644 --- a/fido/aurora_fido/agent.py +++ b/fido/aurora_fido/agent.py @@ -20,6 +20,7 @@ """ import argparse +import contextlib import logging import os import pwd @@ -29,7 +30,7 @@ import threading from . import __version__, agentproto, cbor, creds, ctap2, daemon -from .errors import ERR_CHANNEL_BUSY +from .errors import ERR_CHANNEL_BUSY, ERR_OPERATION_DENIED from .backend import BackendError, BagLocked, UserBagBackend, open_backend, user_handle_uid log = logging.getLogger("aurora-passkeys") @@ -145,6 +146,63 @@ def load(self): return self.sep.unseal(rec[1], rec[2]) +class LockedVault: + """Stands in for the vault between requests: nothing opens without the vault key.""" + + def __init__(self, state_dir): + self.state_dir = state_dir + self.handles_dir = os.path.join(state_dir, "handles") + + def _locked(self, *_a, **_k): + raise BackendError("the vault is closed (your key bag is locked)") + + wrap = unwrap = seal_record = open_record = _locked + + +class VaultGate: + """Opens the vault for one request and closes it again. + + The vault key is unsealed from the user's bag at the start of every + request (one enclave key exchange, no touch) and the vault is dropped when + the request ends. So the key is in this process's memory only during a + request, and only while the bag is unlocked: once the user logs out or the + bag locks, the next request cannot open it. (Python frees the key but + cannot zero it.) One request at a time, across every front-end. + """ + + def __init__(self, auth, secret, state_dir, max_rk): + self.auth = auth + self.secret = secret + self.state_dir = state_dir + self.max_rk = max_rk + self.lock = threading.Lock() + self._close() + + def _close(self): + v = LockedVault(self.state_dir) + self.auth.vault = v + self.auth.store = creds.ResidentStore(v, self.state_dir, self.max_rk) + + @contextlib.contextmanager + def open(self): + """Yields True with the vault open, or False when the bag is locked.""" + with self.lock: + try: + master = self.secret.load() + except BagLocked as e: + log.info("vault stays closed: %s", e) + yield False + return + v = creds.Vault(self.state_dir, master) + del master + self.auth.vault = v + self.auth.store = creds.ResidentStore(v, self.state_dir, self.max_rk) + try: + yield True + finally: + self._close() + + def per_user_info(resp): """getInfo from the agent: no U2F_V2 (U2F is not forwarded to agents).""" if resp[:1] != b"\x00": @@ -162,8 +220,9 @@ class AgentServer: open the hidraw node, so allowing them here grants nothing new. """ - def __init__(self, auth, path, allowed_uids): + def __init__(self, auth, path, allowed_uids, gate=None): self.auth = auth + self.gate = gate # VaultGate: the vault is open only per request self.path = path self.allowed = set(allowed_uids) self.sock = None @@ -248,7 +307,7 @@ def reader(): resp = bytes([ERR_CHANNEL_BUSY]) else: try: - resp = self.auth.handle(data, ctap2.Ctx(cancel, up_needed)) + resp = self._handle(data, ctap2.Ctx(cancel, up_needed)) finally: self.lock.release() if data[:1] == bytes([ctap2.CMD_GET_INFO]): @@ -257,6 +316,16 @@ def reader(): agentproto.send(conn, {"t": "resp", "d": resp}) + def _handle(self, data, ctx): + if self.gate is None: + return self.auth.handle(data, ctx) + with self.gate.open() as ok: + # getInfo needs no vault (it only counts the records); the rest does. + if ok or data[:1] == bytes([ctap2.CMD_GET_INFO]): + return self.auth.handle(data, ctx) + return bytes([ERR_OPERATION_DENIED]) + + def build_agent(cfg, state_dir, backend, secret, user_name, sites=None): """The authenticator for one user (no U2F: not forwarded to agents yet).""" cfg.set("touchid", "user", user_name) @@ -300,8 +369,9 @@ def main(argv=None): return 1 if note: log.info("%s", note) - srv = AgentServer(auth, a.socket or runtime_socket(), {0, os.getuid()}).bind() - dbus = None if a.no_dbus else start_dbus(auth, cfg) + gate = VaultGate(auth, secret, state_dir, cfg.getint("authenticator", "max_resident")) + srv = AgentServer(auth, a.socket or runtime_socket(), {0, os.getuid()}, gate).bind() + dbus = None if a.no_dbus else start_dbus(auth, cfg, gate) for s in (signal.SIGTERM, signal.SIGINT): signal.signal(s, lambda *_: srv.stop.set()) log.info("aurora-passkeyd %s ready for %s", __version__, name) @@ -314,7 +384,7 @@ def main(argv=None): return 0 -def start_dbus(auth, cfg): +def start_dbus(auth, cfg, gate=None): """The native front-end on the session bus (org.aurora.Passkeys1), if possible. [native] portal_names: bus names allowed to call it (a credentials portal); @@ -328,7 +398,7 @@ def start_dbus(auth, cfg): return None names = cfg.get("native", "portal_names", fallback="").split() try: - svc = dbus_provider.ProviderService(Provider(auth), allow_names=names) + svc = dbus_provider.ProviderService(Provider(auth, gate), allow_names=names) if not svc.request_name(): log.warning("%s is taken; no D-Bus front-end", dbus_provider.BUS_NAME) svc.close() diff --git a/fido/aurora_fido/provider.py b/fido/aurora_fido/provider.py index 46f5b69..2098906 100644 --- a/fido/aurora_fido/provider.py +++ b/fido/aurora_fido/provider.py @@ -12,6 +12,7 @@ computed from the origin), and errors are WebAuthn DOMException names. """ +import contextlib import hashlib from urllib.parse import urlsplit @@ -58,8 +59,20 @@ def rp_id_matches_origin(rp_id, origin): class Provider: - def __init__(self, auth): + def __init__(self, auth, gate=None): self.auth = auth + self.gate = gate # agent.VaultGate: open the vault per call, if given + + @contextlib.contextmanager + def _open(self, need_vault=True): + """The vault open for this call (VaultGate); yields whether it opened.""" + if self.gate is None: + yield True + return + with self.gate.open() as ok: + if not ok and need_vault: + raise ProviderError("NotAllowedError", "your key bag is locked", "locked") + yield ok def _call(self, cmd, params, ctx): r = self.auth.handle(bytes([cmd]) + cbor.encode(params), ctx) @@ -75,16 +88,21 @@ def _check_origin(rp_id, origin): raise ProviderError("SecurityError", "rp id %r is not valid for %r" % (rp_id, origin)) def get_info(self): - info = self.auth.get_info({}, None) + with self._open(need_vault=False) as ok: + info = self.auth.get_info({}, None) return {"aaguid": info[3], "name": "Aurora Passwords", "algorithms": [a["alg"] for a in info[0x0A]], "extensions": list(info[2]), "uv": ["biometric"] + (["password"] if getattr(self.auth.backend, "can_password", False) else []), - "locked": False, "rk_remaining": info[0x14]} + "locked": not ok, "rk_remaining": info[0x14]} def list_credentials(self, rp_id, allow=()): - """Display metadata only: no enclave operation, no touch.""" + """Display metadata only: no touch and no credential key operation.""" + with self._open(): + return self._list(rp_id, allow) + + def _list(self, rp_id, allow): rp_hash = hashlib.sha256(rp_id.encode()).digest() out = [] for rec in self.auth.store.for_rp(rp_hash): @@ -115,8 +133,9 @@ def make_credential(self, cdh, rp, user, params, exclude=(), options=None, ctx=N """password: the user's login password (bytearray, wiped here) for the enclave to check instead of a touch; None = Touch ID.""" try: - return self._make(cdh, rp, user, params, exclude, options, - self._ctx(ctx, password)) + with self._open(): + return self._make(cdh, rp, user, params, exclude, options, + self._ctx(ctx, password)) finally: self._wipe(password) @@ -138,7 +157,8 @@ def _make(self, cdh, rp, user, params, exclude, options, ctx): def get_assertion(self, cdh, rp_id, credential_id, options=None, ctx=None, password=None): try: - return self._get(cdh, rp_id, credential_id, options, self._ctx(ctx, password)) + with self._open(): + return self._get(cdh, rp_id, credential_id, options, self._ctx(ctx, password)) finally: self._wipe(password) diff --git a/fido/tests/test_agent.py b/fido/tests/test_agent.py index 8c93a1f..d259be6 100644 --- a/fido/tests/test_agent.py +++ b/fido/tests/test_agent.py @@ -38,6 +38,7 @@ def __init__(self, root, name, allowed=None, mode=stub.MATCH, sites=None, flags_ self.backend = backend or StubKeyBackend(mode=mode, flags_supported=flags_supported) cfg = daemon.load_config(None) cfg.set("touchid", "notify", "no") + self.gate = None if userbag: # interface 4: credentials and the vault key under the user's bag keys = UserBagBackend(self.backend, UID) secret = agent.UserBagSecret(self.backend, UID, self.state) @@ -45,9 +46,11 @@ def __init__(self, root, name, allowed=None, mode=stub.MATCH, sites=None, flags_ keys = self.backend secret = FileSecret(os.path.join(root, name, "vault")) self.auth, _ = agent.build_agent(cfg, self.state, keys, secret, "root", sites) + if userbag: # as aurora-passkeyd runs: the vault is open only per request + self.gate = agent.VaultGate(self.auth, secret, self.state, 4) self.path = os.path.join(root, name, "run", "ctap.sock") self.srv = agent.AgentServer(self.auth, self.path, - {UID} if allowed is None else allowed).bind() + {UID} if allowed is None else allowed, self.gate).bind() self.t = threading.Thread(target=self.srv.serve_forever, daemon=True) self.t.start() @@ -275,8 +278,9 @@ def test_passkey_is_a_user_presence_key_under_the_bag(self): st, mc = f.make() self.assertEqual(st, 0) self.assertEqual(a.auth.policy, creds.POLICY_TOUCHID_OR_PASSWORD) - cred = a.auth.vault.unwrap(hashlib.sha256(b"example.com").digest(), - parse_auth_data(mc[2])["cred_id"]) + with a.gate.open(): + cred = a.auth.vault.unwrap(hashlib.sha256(b"example.com").digest(), + parse_auth_data(mc[2])["cred_id"]) self.assertEqual(backend.user_handle_uid(cred.handle), UID) self.assertTrue(backend.is_gated_handle(cred.handle)) self.assertTrue(os.path.exists(os.path.join(a.state, "vault.key"))) @@ -311,7 +315,7 @@ def test_locked_bag_refuses_everything(self): def test_password_route_through_the_native_front_end(self): a, f = self.agent(mode=stub.NO_MATCH) # no finger at all - p = Provider(a.auth) + p = Provider(a.auth, a.gate) o = {"origin": "https://example.com"} pw = bytearray(b"pw") r = p.make_credential(CDH, {"id": "example.com"}, {"id": b"u1", "name": "r"}, [-7], @@ -331,6 +335,23 @@ def test_password_route_through_the_native_front_end(self): p.get_assertion(CDH, "example.com", cid, o) self.assertIn("password", p.get_info()["uv"]) + def test_vault_is_open_only_during_a_request(self): + a, f = self.agent() + self.assertEqual(f.make()[0], 0) + self.assertIsInstance(a.auth.vault, agent.LockedVault) # closed again + a.backend.bag_locked = True + st, info = f.call(ctap2.CMD_GET_INFO) # needs no vault + self.assertEqual(st, 0) + self.assertEqual(f.ga()[0], E.ERR_OPERATION_DENIED) + p = Provider(a.auth, a.gate) + with self.assertRaises(ProviderError) as c: + p.list_credentials("example.com") # the names stay sealed too + self.assertEqual(c.exception.reason, "locked") + self.assertTrue(p.get_info()["locked"]) + a.backend.bag_locked = False + self.assertEqual(len(p.list_credentials("example.com")), 1) + self.assertEqual(f.ga()[0], 0) + def test_biometric_only_site_rule_is_refused_under_the_bag(self): conf = os.path.join(self.tmp.name, "sites.conf") with open(conf, "w") as fh: