Skip to content

fix(security): harden key file writes and honor RSA key size - #372

Merged
inureyes merged 5 commits into
mainfrom
fix/issue-371-harden-keygen-writes
Dec 4, 2026
Merged

inureyes merged 5 commits into
mainfrom
fix/issue-371-harden-keygen-writes

Conversation

@inureyes

@inureyes inureyes commented Dec 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Hardens how bssh-keygen and bssh-server gen-host-key write key files, and makes RSA -b/--bits take effect. Covers items 1 to 4 of #371 plus the follow-up items 5 to 7 added in the issue thread.

Key file publication (keygen::files)

  • Private keys are never written into an existing inode. The staging helpers from the security-key path now live in a shared keygen::files module (security_key re-exports kept). Every software generator and gen-host-key stages each file in a fresh 0600 file in the destination directory, syncs it, publishes it, and then fsyncs the directory. Overwriting a 0644 key now yields 0600.
  • bssh-keygen checks both the private and .pub paths with symlink_metadata before prompting. Symlinks (including dangling ones) and non-regular files are refused even with -y; the prompt names both files. gen-host-key refuses a non-regular output too.
  • Both halves are staged before either is published, so a public-key failure leaves no orphaned private key. When an existing pair is replaced, the public half is published first, so a .pub that cannot be saved leaves no new private key behind. Missing parent directories of -f are created 0700.
  • New keys are published without replacing anything: the answer from the overwrite check is carried into the write, so a file that appears after the check is refused instead of replaced. -y or a confirmed prompt still replaces. Public generate_* signatures are unchanged; overwrite-aware generate_with_overwrite variants back the CLI.
  • No-replace publishing works without hard links: renameat2(RENAME_NOREPLACE) on Linux, renamex_np(RENAME_EXCL) on macOS, MoveFileExW without replace on Windows, then hard_link, then a final check plus rename used only for unsupported-operation errors (race documented). Verified on a FAT32 volume, where the old code failed.
  • Staged files are tracked in a process-wide registry. SIGINT, SIGTERM, SIGHUP and SIGQUIT remove them before the process exits with the signal's default action; signals inherited as ignored stay ignored. On Linux, new keys are staged as unnamed O_TMPFILE inodes and published with linkat, so they never appear under a temporary name; when replacing, the file is briefly named before the rename. SIGKILL in that window, and Windows Ctrl+C, are not covered and are documented.

RSA key size

  • -b/--bits now takes effect: generation uses RsaKeypair::random(rng, bits) because PrivateKey::random always produced 4096 bits. gen-host-key validates with keygen::rsa::validate_bits (2048 to 16384). Default stays 4096.

Docs

  • CHANGELOG [Unreleased] Security and Bug Fixes entries; bssh-keygen.1 and bssh-server.8 describe the write, refusal, signal cleanup, and exit status behavior.

Changes during review

  • Public half published first when replacing a pair (implementation review found the private-first order could leave a new private key when .pub publication failed).
  • Docs corrected to state that O_TMPFILE keeps new keys unnamed but replacement briefly names the file; SIGQUIT added to cleanup; directory fsync after publish; the SIGTERM test now always reaps its child.

Test plan

  • New unit tests in src/keygen/mod.rs and src/keygen/files/tests.rs, new tests/keygen_file_safety_test.rs driving both binaries with a temporary HOME, and a new bssh-keygen binary test for a file created after confirmation. Tests that can run on the old code were shown to fail there (in a main / 763c144 worktree); the fallback-chain test was shown to fail with the fallback disabled; two tests are regression guards
  • SIGTERM between stage and publish (re-executed child process) leaves no .bssh-keygen-* file
  • Manual: FAT32 disk image, old no-replace publish fails with ENOTSUP, new code publishes and refuses a second write
  • Full local run on the final head: cargo test --lib, cargo test --tests -- --skip integration_test, cargo clippy --all-targets --all-features -- -D warnings
  • Linux, musl and Windows targets compile-checked for the keygen::files module; Linux paths execute in the ubuntu CI jobs; the Windows path is compile-checked only

Closes #371

Private keys were written into the existing inode with create+truncate, so overwriting a 0644 file left the new key 0644. The software path checked output.exists(), which is false for a dangling symlink, so keys were written through links, and the public half went through std::fs::write after the private key was already on disk.

The security-key staging helpers move from sk_files.rs to a shared keygen::files module (security_key re-exports unchanged). The ecdsa, ed25519 and rsa generators publish both halves through write_pair, and gen-host-key uses the new write_private: content is staged in a create_new 0600 file, synced, and renamed into place. bssh-keygen refuses symlinks and non-regular files at either path even with -y, the prompt names both files, and missing parent directories are created 0700.

RSA generation now uses RsaKeypair::random with the requested size, since PrivateKey::random always produced 4096 bits. gen-host-key validates --bits with keygen::rsa::validate_bits.

New unit tests in keygen and tests/keygen_file_safety_test.rs fail on the previous code and pass now.

Closes #371
@inureyes inureyes added status:review Under review type:bug Something isn't working priority:high High priority issue labels Dec 4, 2026
write_pair renamed the new private key into place before the public half. If the .pub rename then failed (a file locked on Windows, an entry owned by another user in a sticky directory, or a .pub replaced after the preflight check), the new private key stayed at <output> next to a stale public key, which #371 requires never to happen.

When replacing, the public half is now published first, so a .pub that cannot be saved leaves no new private key behind. Creating a new pair (security-key no-overwrite mode) keeps the private-first hard_link order. A unit test drives the publish step with an unreplaceable .pub and fails on the previous order.

Refs #371
@inureyes

inureyes commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Harden software key writes in bssh-keygen and bssh-server gen-host-key (temp-and-rename, symlink refusal at both halves, no orphaned private key, 0700 parent dirs) and make RSA -b/--bits take effect (#371).

Findings Addressed

  • Replacing a pair published the private key before the public key, so a .pub rename failure after the preflight check (Windows lock, sticky-dir ownership, race) left a new private key at <output>. The public half is now published first when replacing; unit test added (HIGH, 6e7d84f)

Remaining Items

  • Software-key CLI discards confirm_output's result and the generators always replace, so a file created at the output between the prompt and the write is replaced without a prompt. Same as before this PR; a regular file only, since links are re-checked (LOW), not fixed

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass (cargo test --lib keygen, --bin bssh-keygen, --test keygen_file_safety_test, clippy -D warnings)

@inureyes

inureyes commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

Security and performance review of the key file write path (head 6e7d84f). No CRITICAL or HIGH findings, so no fixes were pushed. cargo test --lib keygen (38), cargo test --lib security_key (126) and cargo test --test keygen_file_safety_test (9) pass locally.

What holds up

  • Final path TOCTOU: rename replaces the directory entry and hard_link fails with EEXIST on any existing entry, so a symlink swapped in after check_output is replaced or refused, never followed. The post-stage re-check is advisory only; the publish primitive carries the guarantee.
  • Temp files: create_new (O_CREAT|O_EXCL) never follows a planted link, names carry 128 random bits, and the Temporary guard removes them on every ? path and on panic (the release profile unwinds).
  • Public temp file is created 0644 and masked by umask, matching ssh-keygen. The private temp file is 0600 from creation.
  • Security-key path: same check_output and staging semantics as the old sk_files.rs; the only behavior change is public-first publish when replacing.

MEDIUM / LOW (not fixed)

  • LOW: an attacker who can write to the key directory can still swap the staged temp file before publish. Such an attacker can already replace the key files directly, so this is not a new boundary.
  • LOW: SIGINT or SIGKILL between staging and publish leaves a .bssh-keygen-<hex> file (0600, private key) in the key directory. Pre-existing for the security-key path since feat: add ECDSA key generation to bssh-keygen and default to P-384 #370.
  • LOW: software keys always publish with overwrite = true even when confirm_output returned Some(false), so a file created between the prompt and publish is replaced silently. Same as the old truncate behavior.
  • LOW: when replacing, a failed private publish leaves the new .pub next to the old private key. The error names it; the old order left the opposite mismatch.
  • LOW (pre-existing): the no-overwrite hard_link publish fails on filesystems without hard links (FAT/exFAT, some network mounts). Only the security-key path uses it, after the authenticator has already enrolled.
  • LOW (pre-existing): an existing parent directory is never tightened, symlinks in intermediate path components are followed as in ssh-keygen, and the directory is created before the overwrite prompt.
  • Report only: bssh-server gen-host-key -t rsa --bits 16384 can take minutes of CPU on the runtime thread. It is an operator-run CLI with no remote trigger, so this is not a DoS vector.
  • Windows: rename-over-existing and create_new work there; files inherit the directory ACL as they did before this change.

The review-driven change publishes the public half first when an existing pair is replaced, so a failure cannot leave a new private key beside an old public key. The bssh-keygen man page security notes and the CHANGELOG Security entry for #371 now state this.

Validation: cargo fmt --check, cargo clippy --lib --tests --bins -D warnings, cargo test --lib keygen, cargo test --bin bssh-keygen, cargo test --test keygen_file_safety_test all pass.

Refs #371
@inureyes inureyes added status:done Completed and removed status:review Under review labels Dec 4, 2026
@inureyes inureyes added status:in-progress Currently being worked on and removed status:done Completed labels Dec 4, 2026
A `.bssh-keygen-<hex>` file holding the private key stayed in the key directory when `bssh-keygen` or `bssh-server gen-host-key` was interrupted between staging and publishing. Named staged files are now tracked in a process-wide registry, and both binaries (only the gen-host-key subcommand of bssh-server) install a signal-hook thread that removes them on SIGINT, SIGTERM, and SIGHUP, then terminates with the signal's default action. Inherited ignored signals stay ignored. On Linux, staging uses `O_TMPFILE` and publishes with `linkat`, so no name exists until publish; it falls back to a named file where unsupported.

The software generators published in overwrite mode even when `confirm_output` found nothing, so a file created in between was replaced. The CLI now passes that result through the new `keygen::generate_with_overwrite`; the existing `generate_*` functions keep replacing as before.

No-replace publishing needed hard links, which FAT and exFAT lack. It now tries `renameat2(RENAME_NOREPLACE)` on Linux, `renamex_np(RENAME_EXCL)` on macOS, or `MoveFileExW` without replace on Windows, then `hard_link`, then, only on unsupported-operation errors, a checked rename with a documented race.

The CHANGELOG Security entries and the bssh-keygen(1) and bssh-server(8) pages describe the cleanup, the no-replace publish, and the remaining SIGKILL and Windows Ctrl+C gaps.

Tested with the keygen, security_key, bssh-keygen, bssh-server, and keygen_file_safety_test targets, a SIGTERM test that re-runs itself as a child, a FAT disk image, and a cross-target check of the files module for Linux and Windows.

Refs #371
@inureyes

inureyes commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

Security and performance review of 97438d7 (items 5-7 of #371): no CRITICAL or HIGH findings, so no fixes were pushed.

Checked and found sound:

  • FFI: every CString and UTF-16 buffer is a named local that outlives its call, and last_os_error() is read before those locals drop. linkat borrows the live &File, so the /proc/self/fd/N descriptor cannot be closed or reused during the call. sigaction is only queried, with a zeroed MaybeUninit.
  • Copy fallback: it reads from the open descriptor after rewind, never through a path. The copy is created with O_CREAT|O_EXCL using the inode's mode (0600 or narrower after umask), so a planted symlink is refused.
  • Attacker-writable or sticky directories: staged names carry 128 random bits and are created exclusively. renameat2, renamex_np, link, linkat, and rename never follow a symlink at the destination. With RENAME_NOREPLACE the kernel returns EEXIST before the sticky-bit check, so a planted file in /tmp ends the chain instead of falling through to the checked rename.
  • Signals: handlers are registered before the thread starts, so an early signal waits in signal-hook's pipe. Cleanup runs on a normal thread under the registry mutex, never in handler context. The registry holds at most four entries per pair, and Drop removes each one.
  • Performance: one fsync per staged file plus one stat of /proc/self/fd. The overwrite path on Linux adds one linkat. All negligible for a one-shot CLI.

LOW (not fixed):

  • After the first signal, the cleanup thread holds the registry until exit, and later SIGINT or SIGTERM are absorbed. If a rename or unlink hangs (for example on a stalled NFS mount), only SIGKILL ends the process.
  • SIGQUIT is not covered, so it leaves a named staged file and a core dump.
  • In the SIGTERM test, if the precondition assertion fails, the child is not killed and lingers for 30 seconds.
  • Pre-existing: there is no directory fsync after publishing, so a crash right after success can lose the new entry. Staging and publishing also resolve the directory by path rather than through a directory fd, as before this commit.
  • Pre-existing: bssh-server gen-host-key always replaces an existing host key without a prompt.

Refs #371

…sync

The O_TMPFILE wording overstated the guarantee: a new key stays unnamed until published, but when replacing a key (and in the copy fallback) the inode is briefly linked to a registered .bssh-keygen-<hex> name before the rename, which SIGKILL can leave behind. The CHANGELOG, bssh-keygen(1), bssh-server(8), and the files module doc now say so.

Interrupt cleanup also handles SIGQUIT, with the same removal and default action as SIGINT, SIGTERM, and SIGHUP.

The destination directory is fsynced after every successful publish on Unix (errors from filesystems that reject directory fsync are ignored), so both bssh-keygen and gen-host-key get it.

The SIGTERM cleanup test now wraps the child process in a guard that kills and reaps it on every failure path.

Validation:
- cargo fmt --check, cargo clippy --lib --tests --bins -- -D warnings: clean
- cargo test --lib keygen (46), --bin bssh-keygen (17), --test keygen_file_safety_test (9): pass

Refs #371
@inureyes inureyes added status:done Completed and removed status:in-progress Currently being worked on labels Dec 4, 2026
@inureyes
inureyes merged commit a7cf1f3 into main Dec 4, 2026
5 checks passed
@inureyes
inureyes deleted the fix/issue-371-harden-keygen-writes branch December 4, 2026 11:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority:high High priority issue status:done Completed type:bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix: harden bssh-keygen key file writes and honor RSA -b

1 participant