41c8b99bd6
- read-only: one row per marker-managed block in ~/.ssh/config (or --config PATH): alias, hostname, user, key id (first 8 chars of the identity's SHA256 fingerprint via ssh-keygen -lf, material digest as fallback), and the fallback identity's name - no managed blocks / missing config: fact + configure_ssh hint, exit 0 always (read-only command) - spec items 2.8 + section 13 first, then tests, then code (SPEC 6.12); 10 new tests (100 in test_gpgtools.py), registry description, README section, CHANGELOG 0.11.0, version pins Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
18 KiB
18 KiB
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
- 2. Commands
- 3. initialize_yubikey behavior
- 4. send_pubkey behavior
- 5. Exit codes
- 6. Runner contract and injectability
- 7. Files written
- 8. Testing approach
- 9. References
- 10. configure_ssh behavior
- 11. store_publickey behavior
- 12. initialize 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_yubikeycovers guide steps 1-4 (fresh machine ready for GPG),send_pubkeycovers steps 5-6 (key to a server).store_publickeycovers 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, nokeytocard, 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 gpgtoolswith 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@serveris required. - 2.4
--dry-runon either subcommand prints what would happen and writes nothing; onsend_pubkeyit 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 --versionfails, the package manager is detected (shutil.whichover apt-get, dnf, pacman) and gnupg installed viasudo; no known manager is exit 3. A failed install is exit 2. - 3.2 Step 2 - card:
gpg --card-statusparsed for theApplication type/OpenPGPmarkers; absent card (including gpg error text) is exit 4 with the pcscd hintsystemctl enable --now pcscd. - 3.3 Card fields: serial (
Serial number), authentication subkey presence (Authentication keywith a non-[none]value), key URL (URL of public key,[not set]is None), keyring pairing (General key infonon-[none]). - 3.4 Step 3 - public key: when unpaired and a URL exists,
gpg --fetch-keys <url>, 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.confgainsenable-ssh-supportand, only when its key is absent,default-cache-ttl 600andmax-cache-ttl 7200; existing lines, including user TTLs, are kept verbatim and never duplicated.gpgconf --kill gpg-agentrestarts the agent. Exit 0.
4. send_pubkey behavior
- 4.1 Sources (exactly one per run):
- 4.1.1
--yubikey: the gpg ssh socket fromgpgconf --list-dirs agent-ssh-socket(bare path or prefixed form),SSH_AUTH_SOCKset to it,ssh-add -L. No socket is exit 8 with theinitialize_yubikeyhint; no keys is exit 8 with "is the YubiKey plugged in?"; several keys refuses with the list and the--pubkeyhint 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 and0x, case-insensitive, exactly 40 hex chars, else exit 8); resolve through the store chain, first hit wins: local keyring (gpg --export-ssh-key 0x<FP>), then keys.openpgp.org VKS (.../vks/v1/by-fingerprint/<FP>), then keyserver.ubuntu.com (.../pks/lookup?op=get&search=0x<FP>). 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 - typicallyyubikey_auth.pubcarried 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--pubkeyhint (item 4.1.1 precedent) rather than guessing; an unreadable or missing file is exit 8.
- 4.1.1
- 4.2 Key line validation:
ssh-(ed25519|rsa|dss|ecdsa-sha2-*) <base64> [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 viassh-keygen -Y sign -U(the private half - card, PIN prompt included - must sign) and verified viassh-keygen -Y verifyagainst 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
--homedirviagpg --import, fingerprints listed with--list-keys --with-colons, and the ssh line exported withgpg --export-ssh-key 0x<FP>. 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 <alias> 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 overos.environ,input_textis piped to stdin, a missing binary returns(127, "<cmd>: not found"). - 6.2
initialize_yukikey(home, run_cmd),verify_possession(line, workdir, run_cmd),send_key(line, target, run_cmd), and thesource_*functions accept the runner;source_url,source_fingerprint, andcmd_send_pubkeyalso accept afetch(url) -> bytes | None. Tests inject fakes; defaults arerun_commandandfetch_bytes(urllib, 30 s timeout, None on any fetch error). - 6.3 ssh-keygen signature namespaces and identity are the
constants
daedalus-gpgtoolsanddaedalus@verify.
7. Files written
- 7.1 initialize:
<gnupg-home>/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'sauthorized_keysappend 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.pyand 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.mdentries 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:
# BEGIN daedalus gpgtools: <alias>
Host <alias>
HostName <hostname>
User <user> (omitted without --user)
IdentityFile <pubkey>
IdentityFile <fallback> (omitted per item 10.4)
IdentitiesOnly yes
# END daedalus gpgtools: <alias>
- 10.2 Defaults:
--hostnamedefaults to the alias itself;--pubkeydefaults to~/.ssh/yubikey_auth.pub;--fallbackdefaults 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
IdentityFileis included only when its file exists and--no-fallbackwas not given; a missing explicit--fallback FILElogs a warning. - 10.5 Guards: a
--pubkeyfile that does not exist is exit 8 with the derive hint; aHostline 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:
~/.sshis created at mode 700 when missing; the config file is created at mode 600 when missing. - 10.7
--dry-runprints the block pluscreating/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 FILEoverrides) 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);--yubikeyworks 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-verifyflag: 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-runprints the identity block plusalready present/creatingand 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
initializecovers the gnupg half of item 3.1 only - no card, keyring, or agent expectations.gpg --versiondecides readiness: present prints the version line and exits 0. Missing runs manager detection and thesudoinstall (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-runperforms only the read-onlygpg --version, prints what would happen (already readywith 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_yubikeyruns this flow as its step 1 (item 3.1); a-2/-3return 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
initializefirst 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 <file>yields the SHA256 fingerprint; the row shows its first 8 chars after theSHA256: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_sshhint 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.