"""Prepare a machine for YubiKey-backed GPG and SSH (guide steps 1-4). Runs the fresh-machine flow from the llm-wiki guide (wiki/queries/yubikey-ssh-guide.md, section 13): install gnupg, check the card, fetch the public key from the card's URL, and configure gpg-agent's SSH support. ``send_pubkey`` covers guide steps 5-6 for one server: resolve the SSH public key from one of four sources, prove possession of the private half with a challenge signature, then append the line to the target's authorized_keys. Run via daedalus: ``daedalus gpgtools initialize_yukikey`` or ``daedalus gpgtools send_pubkey --yubikey you@server``. """ from __future__ import annotations import argparse import dataclasses import logging import os import pathlib import re import secrets import shutil import subprocess import sys import tempfile import urllib.error import urllib.request try: from argcomplete import autocomplete except ImportError: # pragma: no cover - completion off without argcomplete autocomplete = None LOGGER = logging.getLogger(__name__) EXIT_OK = 0 EXIT_INSTALL_FAILED = 2 EXIT_NO_GPG = 3 EXIT_NO_CARD = 4 EXIT_FETCH_FAILED = 5 EXIT_NO_URL = 6 EXIT_TARGET = 7 EXIT_NO_KEY = 8 EXIT_VERIFY_FAILED = 10 SENT_APPENDED = 0 SENT_PRESENT = 1 VERIFY_NAMESPACE = "daedalus-gpgtools" MANAGER_COMMANDS = { "apt-get": ["sudo", "apt-get", "install", "-y", "gnupg"], "dnf": ["sudo", "dnf", "install", "-y", "gnupg2"], "pacman": ["sudo", "pacman", "--noconfirm", "-S", "gnupg"], } CARD_FIELD_LABELS = ("Serial number", "Authentication key", "URL of public key", "General key info") VKS_URL = "https://keys.openpgp.org/vks/v1/by-fingerprint/{fp}" UBUNTU_KS_URL = "https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x{fp}" SSH_PUBKEY_PATTERN = re.compile( r"^ssh-(?:ed25519|rsa|dss|ecdsa-sha2-[a-z0-9-]+) " r"[A-Za-z0-9+/=]+(?: .*)?$") FINGERPRINT_PATTERN = re.compile(r"^[0-9A-Fa-f]{40}$") @dataclasses.dataclass(frozen=True) class CardStatus: """What `gpg --card-status` says about the plugged card. Args: present: an OpenPGP card answered at all. serial: card serial number, or None. has_auth_subkey: the card holds an `[A]` subkey. key_url: the card's public-key URL, or None. keyring_paired: the public key is in this machine's keyring. """ present: bool serial: str | None has_auth_subkey: bool key_url: str | None keyring_paired: bool def parse_card_status(text: str) -> CardStatus: """Parse `gpg --card-status` output into a CardStatus. Args: text: combined stdout/stderr of `gpg --card-status`. Returns: CardStatus with present=False when no card answered. """ fields: dict[str, str] = {} for line in text.splitlines(): stripped = line.strip() for label in CARD_FIELD_LABELS: if stripped.startswith(label) and ":" in stripped: value = stripped.split(":", 1)[1].strip() if value and value != "[none]" and value != "[not set]": fields[label] = value present = "Application type" in text and "OpenPGP" in text return CardStatus( present=present, serial=fields.get("Serial number"), has_auth_subkey="Authentication key" in fields, key_url=fields.get("URL of public key"), keyring_paired="General key info" in fields, ) def merge_agent_config(existing: str) -> str: """Return the agent config with ssh support enabled. Keeps every existing line; adds `enable-ssh-support` and the two cache TTL defaults only when the key is not configured. Args: existing: current gpg-agent.conf text, or "". Returns: New full config text, newline-terminated. """ lines = [line.strip() for line in existing.splitlines() if line.strip()] if not any(line == "enable-ssh-support" for line in lines): lines.append("enable-ssh-support") for key, default in (("default-cache-ttl", "600"), ("max-cache-ttl", "7200")): if not any(line.startswith(key + " ") for line in lines): lines.append(f"{key} {default}") return "\n".join(lines) + "\n" def install_command(manager: str) -> list[str] | None: """Return the install command for a package manager, or None. Args: manager: one of "apt-get", "dnf", "pacman". Returns: The full command including sudo, or None when unknown. """ return MANAGER_COMMANDS.get(manager) def detect_package_manager() -> str | None: """Return the first known package manager on PATH, or None.""" for manager in MANAGER_COMMANDS: if shutil.which(manager): return manager return None def gnupg_home() -> pathlib.Path: """Return the active GnuPG home (GNUPGHOME or ~/.gnupg).""" env_home = os.environ.get("GNUPGHOME") if env_home: return pathlib.Path(env_home) return pathlib.Path.home() / ".gnupg" def run_command(cmd: list[str], input_text: str = "", env: dict[str, str] | None = None) -> tuple[int, str]: """Run a command, return (exit code, combined output). Args: cmd: command and arguments. input_text: text piped to the command's stdin. env: extra environment variables merged over os.environ. Returns: (returncode, stdout+stderr), or (127, message) when the binary does not exist. """ child_env = {**os.environ, **(env or {})} try: result = subprocess.run(cmd, capture_output=True, text=True, check=False, input=input_text or None, env=child_env) except FileNotFoundError: return 127, f"{' '.join(cmd)}: not found" return result.returncode, (result.stdout or "") + (result.stderr or "") def initialize_yubikey(home: pathlib.Path, run_cmd=None) -> int: """Bring a fresh machine to 'ready for GPG' state (steps 1-4). Args: home: the GnuPG home directory to configure. run_cmd: command runner, ``(cmd) -> (code, output)``; defaults to run_command. Injected by tests. Returns: Exit code: 0 ready, 2 install failed, 3 no gpg and no manager, 4 no card, 5 fetch failed, 6 no URL to fetch. """ if run_cmd is None: run_cmd = run_command code, _output = run_cmd(["gpg", "--version"]) if code != 0: manager = detect_package_manager() command = manager and install_command(manager) if command is None: LOGGER.error("gpg is missing and no known package manager " "was found; install gnupg manually") return EXIT_NO_GPG LOGGER.info("installing gnupg via %s", manager) code, output = run_cmd(command) if code != 0: LOGGER.error("package install failed: %s", output.strip()) return EXIT_INSTALL_FAILED code, output = run_cmd(["gpg", "--card-status"]) info = parse_card_status(output) if not info.present: LOGGER.error("no OpenPGP card found; plug the YubiKey in and " "retry (pcscd may need: systemctl enable --now pcscd)") return EXIT_NO_CARD LOGGER.info("card present, serial %s", info.serial) if not info.keyring_paired: if info.key_url is None: LOGGER.error("public key not in the keyring and the card " "carries no URL; import it with gpg " "--locate-keys or gpg --import") return EXIT_NO_URL LOGGER.info("fetching public key from %s", info.key_url) code, output = run_cmd(["gpg", "--fetch-keys", info.key_url]) _code, after = run_cmd(["gpg", "--card-status"]) if parse_card_status(after).keyring_paired is False: LOGGER.error("fetch did not pair the keyring: %s", output.strip()) return EXIT_FETCH_FAILED else: LOGGER.info("public key already in the keyring") if not info.has_auth_subkey: LOGGER.warning("card has no [A] subkey; SSH via gpg-agent " "will not work, GPG signing/decryption will") home.mkdir(mode=0o700, parents=True, exist_ok=True) home.chmod(0o700) config = home / "gpg-agent.conf" existing = config.read_text(encoding="utf-8") if config.exists() else "" config.write_text(merge_agent_config(existing), encoding="utf-8") LOGGER.info("wrote %s", config) run_cmd(["gpgconf", "--kill", "gpg-agent"]) LOGGER.info("gpg-agent restarted; machine ready for GPG. Next " "(ssh, server-specific): derive the key with " "ssh-add -L and deploy it per host") return EXIT_OK class SendPubkeyError(Exception): """A send_pubkey source could not resolve a usable public key.""" def validate_pubkey_line(line: str) -> bool: """True when line is a well-formed SSH public key line. Args: line: candidate public key line. Returns: True for ``ssh- [comment]`` shapes. """ return bool(SSH_PUBKEY_PATTERN.fullmatch(line.strip())) def normalize_fingerprint(text: str) -> str | None: """Return a fingerprint as 40 uppercase hex chars, or None. Args: text: fingerprint with optional 0x prefix and spaces. """ stripped = text.strip().replace(" ", "") if stripped[:2] in ("0x", "0X"): stripped = stripped[2:] return stripped.upper() if FINGERPRINT_PATTERN.fullmatch(stripped) else None def keyserver_urls(fingerprint: str) -> list[str]: """Return the store chain for a fingerprint, first hit wins. Args: fingerprint: 40 uppercase hex chars. Returns: VKS first, then keyserver.ubuntu.com. """ return [VKS_URL.format(fp=fingerprint), UBUNTU_KS_URL.format(fp=fingerprint)] def fetch_bytes(url: str) -> bytes | None: """Download a URL, return the body, or None on failure. Args: url: address of an armored OpenPGP public key. """ try: with urllib.request.urlopen(url, timeout=30) as response: return response.read() except (urllib.error.URLError, ValueError): return None def agent_ssh_env(run_cmd) -> dict[str, str]: """Return the SSH_AUTH_SOCK env pointing at gpg-agent. Args: run_cmd: command runner. Raises: SendPubkeyError: gpg is not initialized (no agent). """ code, output = run_cmd(["gpgconf", "--list-dirs", "agent-ssh-socket"]) text = output.strip() if text.startswith("agent-ssh-socket:"): text = text.split(":", 1)[1].strip() socket_path = text if text.startswith("/") else "" if code != 0 or not socket_path: raise SendPubkeyError("gpg ssh agent not found; run " "daedalus gpgtools initialize_yubikey first") return {"SSH_AUTH_SOCK": socket_path} def source_yubikey(run_cmd) -> tuple[str, str]: """Resolve the key from the plugged YubiKey via gpg-agent. Args: run_cmd: command runner. Returns: (ssh public key line, source description). Raises: SendPubkeyError: no agent, or the agent holds several keys. """ try: env = agent_ssh_env(run_cmd) except SendPubkeyError as err: raise SendPubkeyError(str(err)) from err code, output = run_cmd(["ssh-add", "-L"], env=env) lines = [line.strip() for line in output.splitlines() if line.strip()] if code != 0 or not lines: raise SendPubkeyError("agent holds no ssh keys; is the YubiKey " "plugged in?") if len(lines) > 1: raise SendPubkeyError("agent holds several keys; pass the exact " "line with --pubkey:\n" + "\n".join(lines)) return lines[0], "gpg-agent (YubiKey)" def source_pubkey(line: str) -> tuple[str, str]: """Resolve a literal SSH public key line. Args: line: the exact line to send. Returns: (the line, source description). Raises: SendPubkeyError: the line is not a valid ssh key. """ if not validate_pubkey_line(line): raise SendPubkeyError(f"not a valid ssh public key line: {line!r}") return line.strip(), "literal --pubkey" def _gpg_line_for_armor(armor: bytes, run_cmd, fingerprint: str | None = None) -> str | None: """Convert armored OpenPGP key(s) to the SSH line, or None. Imports into a throwaway GNUPG home - the real keyring is never touched - checks the fingerprint when given, and exports the authentication subkey via gpg --export-ssh-key. """ home = tempfile.mkdtemp(prefix="daedalus-gpgtools-") try: code, _ = run_cmd(["gpg", "--homedir", home, "--import"], input_text=armor.decode("utf-8", "replace")) if code != 0: return None code, output = run_cmd(["gpg", "--homedir", home, "--list-keys", "--with-colons"]) if code != 0: return None found = [row.split(":")[1] for row in output.splitlines() if row.startswith("fpr:")] if fingerprint: if fingerprint.upper() not in [f.upper() for f in found]: return None export_id = "0x" + fingerprint.upper() elif found: export_id = "0x" + found[0] else: return None code, output = run_cmd(["gpg", "--homedir", home, "--export-ssh-key", export_id]) line = output.strip() if code == 0 and validate_pubkey_line(line): return line return None finally: shutil.rmtree(home, ignore_errors=True) def source_url(url: str, run_cmd, fetch) -> tuple[str, str]: """Resolve the SSH line from a URL holding an armored key. Args: url: address of the armored OpenPGP public key. run_cmd: command runner. fetch: ``(url) -> bytes | None`` fetcher. Returns: (ssh public key line, the url as source description). Raises: SendPubkeyError: fetch or conversion failed. """ armor = fetch(url) if not armor: raise SendPubkeyError(f"could not fetch {url}") line = _gpg_line_for_armor(armor, run_cmd) if line is None: raise SendPubkeyError(f"no usable ([A] subkey) public key at {url}") return line, url def source_fingerprint(fingerprint: str, run_cmd, fetch) -> tuple[str, str]: """Resolve a fingerprint through the store chain. Order: local keyring, keys.openpgp.org VKS, keyserver.ubuntu.com. A store returning a different fingerprint is skipped. Args: fingerprint: hex fingerprint, any spacing/case. run_cmd: command runner. fetch: ``(url) -> bytes | None`` fetcher. Returns: (ssh public key line, source description). Raises: SendPubkeyError: no store had the fingerprint. """ fp = normalize_fingerprint(fingerprint) if fp is None: raise SendPubkeyError(f"not a 40-hex fingerprint: {fingerprint!r}") code, output = run_cmd(["gpg", "--export-ssh-key", "0x" + fp]) line = output.strip() if code == 0 and validate_pubkey_line(line): return line, "local keyring" for url in keyserver_urls(fp): armor = fetch(url) if not armor: continue line = _gpg_line_for_armor(armor, run_cmd, fp) if line is not None: return line, url raise SendPubkeyError(f"no store had fingerprint {fp} (local " "keyring, keys.openpgp.org, " "keyserver.ubuntu.com)") def verify_possession(line: str, workdir: pathlib.Path, run_cmd) -> bool: """Prove the private half of line is usable: sign a challenge. Writes the candidate public key, a random challenge, and an allowed_signers file in workdir, asks the ssh agent to sign the challenge with -U (PIN prompts go to the user), and verifies the signature against the candidate line. Args: line: candidate ssh public key. workdir: scratch directory for the artifacts. run_cmd: command runner. Returns: True when the private key signed and the signature verified; False on any failure. """ candidate = workdir / "candidate.pub" challenge_path = workdir / "challenge" allowed = workdir / "allowed_signers" challenge = secrets.token_hex(32) candidate.write_text(line + "\n", encoding="utf-8") challenge_path.write_text(challenge, encoding="utf-8") allowed.write_text(f"daedalus@verify {line}\n", encoding="utf-8") try: env = agent_ssh_env(run_cmd) except SendPubkeyError: env = None code, _ = run_cmd(["ssh-keygen", "-Y", "sign", "-U", "-f", str(candidate), "-n", VERIFY_NAMESPACE, str(challenge_path)], env=env) if code != 0: return False sig_path = pathlib.Path(str(challenge_path) + ".sig") if not sig_path.exists(): return False code, _ = run_cmd(["ssh-keygen", "-Y", "verify", "-f", str(allowed), "-I", "daedalus@verify", "-n", VERIFY_NAMESPACE, "-s", str(sig_path)], input_text=challenge) return code == 0 def _key_material(line: str) -> str: """Type and base64 of a public key line - comments are annotations.""" return " ".join(line.split()[:2]) def send_key(line: str, target: str, run_cmd) -> int: """Append one public key line to target's authorized_keys. Reads the server's authorized_keys first (idempotence by key material, ignoring comments), then appends the line over stdin only when absent. Args: line: validated ssh public key line. target: ``user@server`` ssh target. run_cmd: command runner (the real one passes through ssh). Returns: SENT_APPENDED, SENT_PRESENT, or EXIT_TARGET on ssh failure. """ code, output = run_cmd(["ssh", target, "cat ~/.ssh/authorized_keys 2>/dev/null"]) if code != 0: return EXIT_TARGET material = _key_material(line.strip()) if material in [_key_material(row) for row in output.splitlines()]: return SENT_PRESENT code, _ = run_cmd(["ssh", target, "mkdir -p ~/.ssh && chmod 700 ~/.ssh && " "touch ~/.ssh/authorized_keys && " "chmod 600 ~/.ssh/authorized_keys && " "cat >> ~/.ssh/authorized_keys"], input_text=line.strip() + "\n") if code != 0: return EXIT_TARGET return SENT_APPENDED def cmd_send_pubkey(args: argparse.Namespace, run_cmd=None, fetch=None) -> int: """send_pubkey subcommand: resolve, verify, append. Args: args: parsed arguments (source, target, flags). run_cmd: command runner; defaults to run_command. fetch: ``(url) -> bytes | None``; defaults to fetch_bytes. Returns: Exit code (EXIT_OK, EXIT_NO_KEY, EXIT_VERIFY_FAILED, EXIT_TARGET). """ if run_cmd is None: run_cmd = run_command if fetch is None: fetch = fetch_bytes try: if args.yubikey: line, source = source_yubikey(run_cmd) elif args.url: line, source = source_url(args.url, run_cmd, fetch) elif args.fingerprint: line, source = source_fingerprint(args.fingerprint, run_cmd, fetch) else: line, source = source_pubkey(args.pubkey) except SendPubkeyError as err: LOGGER.error("%s", err) return EXIT_NO_KEY print(f"public key : {line}") print(f"source : {source}") print(f"target : {args.target}") if args.dry_run: print("dry run: nothing verified, nothing sent") return EXIT_OK if not args.no_verify: workdir = pathlib.Path(tempfile.mkdtemp(prefix="daedalus-verify-")) try: if not verify_possession(line, workdir, run_cmd): print("verification FAILED: no private key could sign for " "this public key; nothing sent (use --no-verify to " "skip on purpose)") return EXIT_VERIFY_FAILED finally: shutil.rmtree(workdir, ignore_errors=True) print("verification ok: private key proved possession") else: print("verification skipped (--no-verify)") status = send_key(line, args.target, run_cmd) if status == SENT_PRESENT: print(f"key already present on {args.target}; nothing changed") return EXIT_OK if status != SENT_APPENDED: print(f"ssh to {args.target} failed; key NOT stored on the server") return EXIT_TARGET print(f"appended the public key to {args.target} authorized_keys") return EXIT_OK def parse_args(argv: list[str] | None) -> argparse.Namespace: """Parse gpgtools command-line arguments.""" parser = argparse.ArgumentParser( prog="gpgtools", description="YubiKey GPG/SSH helpers (fresh-machine flow)", ) subparsers = parser.add_subparsers(dest="command") init = subparsers.add_parser( "initialize_yubikey", help="install gnupg, check the card, fetch the public " "key, configure gpg-agent SSH support (steps 1-4)", ) init.add_argument("--dry-run", action="store_true", help="print the plan, change nothing") init.add_argument("--gnupg-home", type=pathlib.Path, default=None, help="GnuPG home to configure " "(default GNUPGHOME or ~/.gnupg)") send = subparsers.add_parser( "send_pubkey", help="resolve an SSH public key (guide steps 5-6), prove " "possession of the private half, append it to a server's " "authorized_keys", ) sources = send.add_mutually_exclusive_group(required=True) sources.add_argument("--yubikey", action="store_true", help="take the key from the plugged YubiKey " "(gpg-agent ssh socket)") sources.add_argument("--url", metavar="URL", help="URL of an armored OpenPGP public key") sources.add_argument("--fingerprint", metavar="FP", help="OpenPGP fingerprint; searched in the " "local keyring, keys.openpgp.org, " "keyserver.ubuntu.com") sources.add_argument("--pubkey", metavar="LINE", help="the literal ssh public key line") send.add_argument("--no-verify", action="store_true", help="skip the proof-of-possession signature " "(explicit risk acceptance)") send.add_argument("--dry-run", action="store_true", help="resolve and print the key, verify and send " "nothing") send.add_argument("target", metavar="you@server", help="ssh target that receives the key") if autocomplete is not None: # pragma: no cover - needs argcomplete autocomplete(parser) return parser.parse_args(argv) def main(argv: list[str] | None = None) -> int: """CLI entry point; return the exit code. Args: argv: argument list; None means sys.argv[1:]. """ args = parse_args(argv) logging.basicConfig(level=logging.INFO, format="%(levelname)-5s %(message)s") if args.command == "send_pubkey": return cmd_send_pubkey(args, run_command, fetch_bytes) if args.command == "initialize_yubikey": if args.dry_run: print("plan: install gnupg if missing -> check card -> " "fetch public key from the card's URL -> write " "gpg-agent.conf (enable-ssh-support) + chmod 700 " "-> restart gpg-agent") return EXIT_OK return initialize_yubikey(home=args.gnupg_home or gnupg_home(), run_cmd=run_command) print("gpgtools: YubiKey GPG/SSH helpers") print(" daedalus gpgtools initialize_yubikey [--dry-run] " "[--gnupg-home DIR]") print(" daedalus gpgtools send_pubkey [--yubikey | --url URL | " "--fingerprint FP | --pubkey LINE] [--no-verify] [--dry-run] " "you@server") return EXIT_OK if __name__ == "__main__": sys.exit(main())