# gpgtools specification Complete description of `python/src/gpgtools/gpgtools.py`. Change this file first, then tests, then code (SPEC items 6.11 and 6.12). Items are cited as `gpgtools spec item N.M`. - [1. Purpose](#1-purpose) - [2. Commands](#2-commands) - [3. initialize_yubikey behavior](#3-initialize_yubikey-behavior) - [4. send_pubkey behavior](#4-send_pubkey-behavior) - [5. Exit codes](#5-exit-codes) - [6. Runner contract and injectability](#6-runner-contract-and-injectability) - [7. Files written](#7-files-written) - [8. Testing approach](#8-testing-approach) - [9. References](#9-references) - [10. configure_ssh behavior](#10-configure_ssh-behavior) - [11. store_publickey behavior](#11-store_publickey-behavior) - [12. initialize behavior](#12-initialize-behavior) - [13. ssh-config-summary behavior](#13-ssh-config-summary-behavior) ## 1. Purpose - **1.1** gpgtools automates the YubiKey SSH flow documented in the owner's wiki guide (`~/repositories/vibe-wiki/wiki/queries/yubikey-ssh-guide.md`): `initialize_yubikey` covers guide steps 1-4 (fresh machine ready for GPG), `send_pubkey` covers steps 5-6 (key to a server). `store_publickey` covers the on-site bootstrap case (section 11): installing the key from the machine that access is being granted to. Guide step 7 (per-host `~/.ssh/config`) is out of scope. - **1.2** Hard constraint: the YubiKey's OpenPGP applet is never written - no `gpg --card-edit`, no `keytocard`, no applet reset. Only public card data is read; the card PIN is typed by its owner into pinentry, never passed through this script. - **1.3** The user's real GNUPGHOME is written only where section 7 says so; remote public-key imports go to a throwaway home (item 4.5). - **1.4** Standard library only; Python 3.11+ (SPEC item 9.6). ## 2. Commands - **2.1** `daedalus gpgtools` with no subcommand prints the overview of the subcommands and exits 0. - **2.2** `daedalus gpgtools initialize_yubikey [--dry-run] [--gnupg-home DIR]` - prepares this machine (section 3). - **2.3** `daedalus gpgtools send_pubkey (--yubikey | --url URL | --fingerprint FP | --pubkey LINE | --file PATH) [--no-verify] [--dry-run] you@server` - resolves one SSH public key, proves possession of the private half, appends it to the target (section 4). The five source flags are mutually exclusive and exactly one is required; `you@server` is required. - **2.4** `--dry-run` on either subcommand prints what would happen and writes nothing; on `send_pubkey` it resolves and prints the key but never verifies and never connects. - **2.5** `daedalus gpgtools configure_ssh --alias NAME [--hostname HOST] [--user USER] [--pubkey FILE] [--fallback FILE | --no-fallback] [--config PATH] [--dry-run]` - writes the per-host ssh client block (guide step 7); behavior in section 10. - **2.6** `daedalus gpgtools store_publickey (--yubikey | --url URL | --fingerprint FP | --pubkey LINE | --file PATH) [--authorized-keys FILE] [--dry-run]` - resolves one SSH public key and installs it into *this* machine's authorized_keys (section 11). The source flags are the send_pubkey set (items 4.1.1-4.1.5), mutually exclusive, exactly one required. - **2.7** `daedalus gpgtools initialize [--dry-run]` - checks that gnupg is ready on this machine and installs what is missing; the gnupg-only half of initialize_yubikey (section 12). - **2.8** `daedalus gpgtools ssh-config-summary [--config PATH]` - prints the table of gpg-enabled ssh logins found in the config (section 13); read-only. ## 3. initialize_yubikey behavior - **3.1** Step 1 - gnupg: the section 12 flow (item 12.1). When `gpg --version` fails, the package manager is detected (`shutil.which` over apt-get, dnf, pacman) and gnupg installed via `sudo`; no known manager is exit 3. A failed install is exit 2. - **3.2** Step 2 - card: `gpg --card-status` parsed for the `Application type`/`OpenPGP` markers; absent card (including gpg error text) is exit 4 with the pcscd hint `systemctl enable --now pcscd`. - **3.3** Card fields: serial (`Serial number`), authentication subkey presence (`Authentication key` with a non-`[none]` value), key URL (`URL of public key`, `[not set]` is None), keyring pairing (`General key info` non-`[none]`). - **3.4** Step 3 - public key: when unpaired and a URL exists, `gpg --fetch-keys `, then re-parse the card; still unpaired is exit 5. Unpaired without a URL is exit 6 with the manual-import hint. - **3.5** A missing `[A]` subkey logs a warning (SSH via gpg-agent will not work; GPG signing/decryption will) but is not an error. - **3.6** Step 4 - agent: the homedir is created at mode 700; `gpg-agent.conf` gains `enable-ssh-support` and, only when its key is absent, `default-cache-ttl 600` and `max-cache-ttl 7200`; existing lines, including user TTLs, are kept verbatim and never duplicated. `gpgconf --kill gpg-agent` restarts the agent. Exit 0. ## 4. send_pubkey behavior - **4.1** Sources (exactly one per run): - **4.1.1** `--yubikey`: the gpg ssh socket from `gpgconf --list-dirs agent-ssh-socket` (bare path or prefixed form), `SSH_AUTH_SOCK` set to it, `ssh-add -L`. No socket is exit 8 with the `initialize_yubikey` hint; no keys is exit 8 with "is the YubiKey plugged in?"; several keys refuses with the list and the `--pubkey` hint rather than guessing. - **4.1.2** `--url`: fetch the armored OpenPGP public key, convert via item 4.5. - **4.1.3** `--fingerprint`: normalize (strip spaces and `0x`, case-insensitive, exactly 40 hex chars, else exit 8); resolve through the store chain, first hit wins: local keyring (`gpg --export-ssh-key 0x`), then keys.openpgp.org VKS (`.../vks/v1/by-fingerprint/`), then keyserver.ubuntu.com (`.../pks/lookup?op=get&search=0x`). Every store result is fingerprint-checked before use; a mismatch skips the store. All exhausted is exit 8 naming the stores. - **4.1.4** `--pubkey`: the literal line, validated by item 4.2; exit 8 when invalid. - **4.1.5** `--file PATH`: a file holding the SSH public key line - typically `yubikey_auth.pub` carried on a USB stick (zero network, zero gpg). Every line is validated per item 4.2: no valid line is exit 8; several valid lines refuse listing them with the `--pubkey` hint (item 4.1.1 precedent) rather than guessing; an unreadable or missing file is exit 8. - **4.2** Key line validation: `ssh-(ed25519|rsa|dss|ecdsa-sha2-*) [comment]`, full line; anything else is rejected. - **4.3** Key material (type + base64, comment ignored) is the key's identity for deduplication and reporting. - **4.4** Proof of possession (default, skipped only with `--no-verify`): a random hex challenge is signed via `ssh-keygen -Y sign -U` (the private half - card, PIN prompt included - must sign) and verified via `ssh-keygen -Y verify` against the candidate line with an allowed_signers file. Any failure prints that nothing was sent and exits 10; the ssh target is never contacted. - **4.5** Remote conversion: armored keys are imported into a throwaway `--homedir` via `gpg --import`, fingerprints listed with `--list-keys --with-colons`, and the ssh line exported with `gpg --export-ssh-key 0x`. The real keyring is not touched; the throwaway home is removed afterwards. - **4.6** Send: `ssh you@server "cat ~/.ssh/authorized_keys 2>/dev/null"` to read, then - only when the key material is absent - append the line via stdin with perms forced (`mkdir -p`, `chmod 700 ~/.ssh`, `chmod 600 authorized_keys`). Present is reported, not re-appended. Any ssh failure is exit 7; nothing is appended on failure. - **4.7** Both ssh calls run without an interactive terminal: the target must be reachable with existing non-interactive credentials (agent, passphrase-less key, or ControlMaster socket). First contact to a brand-new server by password is out of scope - gain access once manually, then send the key. - **4.8** Output (identical in section 11): both resolve-and-store subcommands print the resolved key line, its source, and the SHA-256 hex digest of the key material (item 4.3) before acting, so the resolved value can be compared with the machine the key came from (or read over a phone). ## 5. Exit codes | Code | Meaning | | --- | --- | | 0 | success (initialize ready; send appended or already present) | | 2 | package install failed (initialize, initialize_yubikey) | | 3 | gpg missing and no known package manager (initialize, initialize_yubikey) | | 4 | no OpenPGP card found (initialize) | | 5 | public-key fetch did not pair the keyring (initialize) | | 6 | keyring unpaired and the card carries no URL (initialize) | | 7 | ssh to the target failed; nothing stored (send) | | 8 | no source resolved a usable key (send, store); pubkey file missing (configure) | | 10 | proof-of-possession verification failed; nothing sent (send) | | 11 | an unmanaged `Host ` exists in the config (configure) | ## 6. Runner contract and injectability - **6.1** Everything external goes through `run_command(cmd, input_text="", env=None) -> (code, stdout+stderr)`: env variables are merged over `os.environ`, `input_text` is piped to stdin, a missing binary returns `(127, ": not found")`. - **6.2** `initialize_yukikey(home, run_cmd)`, `verify_possession(line, workdir, run_cmd)`, `send_key(line, target, run_cmd)`, and the `source_*` functions accept the runner; `source_url`, `source_fingerprint`, and `cmd_send_pubkey` also accept a `fetch(url) -> bytes | None`. Tests inject fakes; defaults are `run_command` and `fetch_bytes` (urllib, 30 s timeout, None on any fetch error). - **6.3** ssh-keygen signature namespaces and identity are the constants `daedalus-gpgtools` and `daedalus@verify`. ## 7. Files written - **7.1** initialize: `/gpg-agent.conf` (merge per item 3.6); the homedir permissions set to 700. Nothing else. - **7.2** send: scratch dirs (throwaway GNUPGHOME, challenge workspace) are created under the system temp dir and removed in `finally`. The only persistent write is the target's `authorized_keys` append via ssh (item 4.6). - **7.3** store: the local `authorized_keys` (item 11.5) is the only persistent write; its parent gets mode 700, the file 600. Scratch rules of item 7.2 apply when remote sources resolve (item 4.5). ## 8. Testing approach - **8.1** Tests live in `python/tests/test_gpgtools.py` and never need hardware, a network, or an interactive terminal (SPEC item 6.6): all flows take an injected runner; fetchers and runners are fakes scripted per test by command prefix. - **8.2** Covered groups: card-status parsing (present/absent, no URL, no auth subkey, unpaired), config merge (empty, preserving, complete), manager mapping and detection, GNUPGHOME resolution, the initialize flow's success, failure, warning, and persistence branches and the standalone readiness/install/re-check branches (section 12), the five sources including the store chain and fingerprint mismatch, challenge sign/verify success and refusal, send idempotence by material, store: file sources, append, preservation, idempotence, perms, dry run, summary: block parsing (each field), key-id resolution and both id fallbacks, the empty and missing-config paths, and the CLI wiring, guards, and dry runs. - **8.3** The change order is spec item 6.12: this spec first, then failing tests, then the smallest implementation. ## 9. References - **9.1** The wiki guide behind items 1.1: `~/repositories/vibe-wiki/wiki/queries/yubikey-ssh-guide.md` (steps 1-13; automation notes in section 13). - **9.2** Repository rules: SPEC items 6.6 (tests), 6.9 (argcomplete opt-in after the parser), 9.8 (version bump). - **9.3** History: `CHANGELOG.md` entries 0.5.0, 0.6.0 (initialize/send), 0.7.0 (configure_ssh), 0.8.0 (--file source, store_publickey), 0.9.0 (initialize), 0.10.0 (init script), 0.11.0 (ssh-config-summary). ## 10. configure_ssh behavior - **10.1** The block is written into `--config` (default `~/.ssh/config`) between managed markers, one block per alias: ```text # BEGIN daedalus gpgtools: Host HostName User (omitted without --user) IdentityFile IdentityFile (omitted per item 10.4) IdentitiesOnly yes # END daedalus gpgtools: ``` - **10.2** Defaults: `--hostname` defaults to the alias itself; `--pubkey` defaults to `~/.ssh/yubikey_auth.pub`; `--fallback` defaults to `~/.ssh/id_ed25519`. - **10.3** Idempotence: a run that finds the alias's markers replaces the whole marked block with the newly built one; everything outside the markers is preserved byte-for-byte. Running twice with the same arguments changes nothing. - **10.4** The fallback `IdentityFile` is included only when its file exists and `--no-fallback` was not given; a missing explicit `--fallback FILE` logs a warning. - **10.5** Guards: a `--pubkey` file that does not exist is exit 8 with the derive hint; a `Host` line naming the same alias anywhere outside the managed markers is exit 11 (ssh would let the first match shadow the managed block). - **10.6** File hygiene: `~/.ssh` is created at mode 700 when missing; the config file is created at mode 600 when missing. - **10.7** `--dry-run` prints the block plus `creating`/`replacing`, and writes nothing. ## 11. store_publickey behavior - **11.1** Installs one SSH public key into the *current user's* `~/.ssh/authorized_keys` (`--authorized-keys FILE` overrides) on this machine - the machine the key will later grant access to. Use case: a server with ssh password authentication disabled that no key authorizes yet; you are logged in at its console and install the key from inside, so the machine holding the YubiKey can ssh in afterwards. It is the mirror of section 4: send pushes the key from where it is, store pulls it from where the access is. - **11.2** Sources: identical to items 4.1.1-4.1.5, one per run. On a bare server the realistic ones are `--pubkey` (typed at the console), `--file` (USB stick; needs no network and no gpg), and `--fingerprint` (store chain, needs gpg and network); `--yubikey` works when the card is plugged into this machine. An unresolvable source is exit 8 (item 5). - **11.3** There is no proof-of-possession step (item 4.4) and no `--no-verify` flag: the private half is, by design, elsewhere - this machine is the one being granted access, so nothing here could sign the challenge. Hardening instead: line validation (item 4.2), fingerprint-checked stores (item 4.1.3), and the identity block (item 11.4). - **11.4** Identity block: the resolved key line, its source, and the SHA-256 hex digest of the key material (item 4.3) are printed before writing (shared rule, item 4.8), so the value can be compared with the machine the key came from. - **11.5** Storage: the parent directory is created at mode 700 when missing and the authorized_keys file forced to mode 600, on every write. Existing entries are preserved verbatim - authorized_keys is a multi-key file; there is no mismatch guard on the rest, only the new key's absence is checked. - **11.6** Idempotence follows item 4.3: the line is appended only when its material is absent (comments ignored); already present is reported and exits 0. A missing trailing newline in an existing file is repaired, never glued into a key line. - **11.7** `--dry-run` prints the identity block plus `already present`/`creating` and writes nothing. - **11.8** No ssh is run and the only persistent write is item 11.5; remote sources keep item 4.5's throwaway-home rule (item 7.3). Exit codes: 0 stored or already present, 8 no source resolved a usable key. ## 12. initialize behavior - **12.1** `initialize` covers the gnupg half of item 3.1 only - no card, keyring, or agent expectations. `gpg --version` decides readiness: present prints the version line and exits 0. Missing runs manager detection and the `sudo` install (item 3.1's manager map); no known manager is exit 3, a failed install is exit 2. After a successful install the check re-runs once - still unusable is exit 2. - **12.2** `--dry-run` performs only the read-only `gpg --version`, prints what would happen (`already ready` with the version line, the install command it would run, or the install-manually message), installs nothing, and exits 0 in every dry-run case. - **12.3** `initialize_yubikey` runs this flow as its step 1 (item 3.1); a `-2`/`-3` return stops it before anything else. - **12.4** Intended use: the on-site companion to store_publickey (item 11) - on a machine without the YubiKey, run `initialize` first when a gpg-dependent source (`--fingerprint`, `--url`, `--yubikey`) is wanted. ## 13. ssh-config-summary behavior - **13.1** Scope: every marker-managed block (item 10.1) in `--config` (default `~/.ssh/config`) is one gpg-enabled login. The command never writes and never contacts any host; it reads only the config and the IdentityFiles the blocks name (`~` expanded). - **13.2** Output is one row per block with the columns `alias`, `hostname`, `user`, `key id`, `fallback`: hostname defaults to the alias when the block omits HostName; user prints `-` when absent (ssh's own default); fallback prints `-` when the block has no second IdentityFile. Columns are padded and separated by two spaces, like the daedalus script listing. - **13.3** Key id: taken from the block's *first* IdentityFile. `ssh-keygen -lf ` yields the SHA256 fingerprint; the row shows its first 8 chars after the `SHA256:` prefix (shorter values print in full). When ssh-keygen fails or is missing but the file is readable and holds a valid key line (item 4.2), the id falls back to the first 8 chars of the material digest (item 4.8) - both are stable per key. A missing or unreadable IdentityFile prints `-` for the id. - **13.4** No managed blocks - a missing config file counts - prints that fact with the `configure_ssh` hint and exits 0. - **13.5** Exit code is always 0; the command is read-only and has no failure modes that would leave anything half-done.