Skip to content

secrets: sandbox setup-secrets and lock down every unlisted entry - #48

Merged
seberm merged 4 commits into
bitcoinix:masterfrom
bobberb:setup-secrets-hardening
Oct 26, 2026
Merged

seberm merged 4 commits into
bitcoinix:masterfrom
bobberb:setup-secrets-hardening

Conversation

@bobberb

@bobberb bobberb commented Oct 15, 2026

Copy link
Copy Markdown
Collaborator

Problem

Two issues in modules/secrets/secrets.nix (#25):

  • setup-secrets runs as root with no systemd hardening, although it only creates, chowns and chmods files in secretsDir.
  • The pass that makes undeclared files root-only listed them with printf '%s\n' * and passed the list unquoted to chown/chmod with no --. Dotfiles were skipped and kept their owner and mode. A file named -x was parsed as an option, so the unit failed. A file named * was expanded again to every secret, which would all become root:root 440.

Change

  • setup-secrets uses nbLib.defaultHardening with these overrides:
    • PrivateUsers = false: chown to service users needs real uid mapping.
    • CapabilityBoundingSet = CAP_CHOWN CAP_FOWNER CAP_DAC_OVERRIDE.
    • PrivateNetwork = true, RestrictAddressFamilies = AF_UNIX.
    • ReadWritePaths = -<secretsDir>. The - prefix means a missing dir still gets the script's own "Secrets dir is missing" error instead of a namespace failure.
    • ReadOnlyPaths = /run /dev. ProtectSystem = strict does not cover these here:
      • /run: on systemd 260, adding ProtectKernelTunables, ProtectControlGroups, ProtectProc = invisible or ProcSubset = pid (all in defaultHardening) leaves /run, /run/keys and /run/wrappers writable.
      • /dev: PrivateDevices bind-mounts the host's /dev/shm, /dev/mqueue, /dev/hugepages and /dev/pts read-write.
      • Without this line, a declared secret symlinked into any of those paths got its target chowned and chmodded. With it, the unit fails with EROFS.
      • A secretsDir under /run still works, because ReadWritePaths can be nested in ReadOnlyPaths. Redirects to /dev/null still work too.
    • ProtectHome = read-only instead of true: systemd can't nest ReadWritePaths under an inaccessible /home, so true would break a secretsDir below /home.
    • With generateSecrets, an unsandboxed ExecStartPre=+mkdir -p -m 0700 <secretsDir> runs first, because ReadWritePaths can only bind a path that already exists. That command has fixed arguments.
  • Writable paths inside the unit, checked by probing every mount point from inside the sandbox:
    • secretsDir.
    • The unit's private /tmp and /var/tmp.
    • A no-op chown on the /proc root succeeds, but no file can be created there, and ProtectProc=invisible with ProcSubset=pid hides other processes.
    • The unit's own cgroup memory.pressure file.
  • The script now chmods the dir to 0700 right after chown root:, on every path. Before, this only happened with generateSecrets. A deployment that left the dir group- or world-writable could otherwise let someone add or swap entries while they are being processed.
    • While the unit runs, services can't read secrets. That was already the case with generateSecrets.
    • A failed run now leaves the dir 0700 without generateSecrets too, so the unit fails closed. With generateSecrets this was already the behavior. Every service then gets EACCES on its secrets until a run succeeds, not only the service whose secret is broken.
  • The lockdown pass walks find . -mindepth 1 -maxdepth 1 -print0, so dotfiles and names containing newlines are included. Every name is quoted and passed after --. Symlinks only get chown -h root:, because chmod would change their target. A link grants no access by itself. The comm/LC_COLLATE sort trick is gone. Membership in the declared list is now an exact string compare.
  • setupSecret (declared secrets) passes -- to chown/chmod as well.

Testing

New VM test setup-secrets, defined last in test/tests.py because each run makes the secrets dir 0700 until it succeeds. When it ran earlier, it made a still-starting lnd fail in default. The test is enabled in every scenario where setupSecrets is on. It checks:

  • the unit's ProtectSystem, PrivateNetwork, NoNewPrivileges and CapabilityBoundingSet;
  • that after a restart, -x, * and .dotfile (created as nobody:nogroup 666) end up root:root 440;
  • that an undeclared symlink becomes root:root while its target in /run stays nobody:nogroup 644;
  • that no other entry in /secrets changed owner or mode, and the dir is root:root 751;
  • for /run and /dev/shm in turn, that a declared secret replaced by a symlink to a file there makes the restart fail with Result=exit-code (not a start-limit hit; reset-failed runs before every restart), and that the target stays nobody:nogroup 644. After each case the secret is restored and /secrets is compared with its earlier state.
Run Result
ad hoc { services.lnd.enable = true; }, fix PASS
same, /dev removed from ReadOnlyPaths FAIL: the /run case passes, then the /dev/shm case's restart unexpectedly succeeded
same, ReadOnlyPaths removed entirely (earlier round) FAIL: restart unexpectedly succeeded
same, module at master (test kept) FAIL: ProtectSystem assertion
same, hardening kept, master lockdown pass FAIL: chown: invalid option -- 'x', unit fails
same, master lockdown pass, test reduced to dotfile only FAIL: .dotfile stays nobody:nogroup 666
probe from inside the unit (throwaway ExecStartPost, bitcoind): touch/chown on every mount point only secretsDir, private /tmp, /var/tmp, plus the no-op /proc chown and the unit's own memory.pressure listed above (the probe flagged those two, which is why its run ends with bad=1; neither can be reached through a symlinked secret)
ad hoc secretsDir = "/run/nbsec" (earlier round, before /dev was added) PASS
default PASS
netnsRegtest PASS
wireguard-lndconnect (wg genkey) PASS
clightning-replication (ssh-keygen) PASS
./test/shellcheck.sh PASS
shellcheck on the generated setup-secrets start script PASS
nix flake check --all-systems PASS
Separate attacker review, 3 rounds Round 1: /run writable in the sandbox, a symlinked secret's target there got chowned. Round 2: /dev/{shm,mqueue,hugepages,pts} writable, same attack. Both fixed with ReadOnlyPaths, each with a red/green test case. Round 3: PASS

Not covered

  • The read-only mounts protect symlink targets outside secretsDir, not every file outside it. An undeclared hardlink in secretsDir still reaches its inode, which then becomes root:root 440. This predates the PR, and planting a hardlink needs root.
  • Declared secrets still go through chown/chmod with symlinks followed, as before. If a declared secret is a symlink to a file outside secretsDir, the unit now fails with EROFS, where before it changed the target. I added no versioning.nix entry: this depends on what is on disk at runtime, so no eval-time condition can detect it.
  • Custom generateSecretsCmds that need the network, write outside secretsDir, or need W^X memory now fail. So does a permissions value with setuid or setgid bits (RestrictSUIDSGID). None of the in-tree modules do any of these.
  • With generateSecrets, a declared secret symlinked to /tmp/... dangles inside the private /tmp, so a fresh secret is written there and then discarded. This predates the PR and is harmless.
  • Subdirectories in secretsDir still get a non-recursive root: 0440, as before.
  • The /run and /dev gaps probably affect every service that uses defaultHardening. That needs a separate issue and is not fixed here.
  • Not run: full, regtest, hardened, trustedcoin. A reviewer ran hardened in an earlier round, and it passed.
  • Mounts the host creates while the unit runs (e.g. logind's /run/user/<uid>) arrive writable through mount propagation. Using that needs root to plant a symlink, within a sub-second window.
  • The same writable /run and /dev mounts probably exist in every unit that uses nbLib.defaultHardening. Not changed here; worth its own issue.

🤖 Generated with Claude Code

@ostermayer ostermayer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The sandbox matches what we did in d22c5da/c021a3e, and ReadOnlyPaths for /run and /dev is a gap we missed. Good.

One behaviour change worth calling out: chmod 0700 "$dir" at the start means a failed run (say one declared secret missing on a deploy) leaves the whole dir unreadable, so every service loses its secrets instead of just the one. Before this change the dir kept the 0751 from the previous run. Failing closed is defensible, but it should be stated in the commit message or the comment so the next person understands why a single missing secret takes the node down. Otherwise LGTM.

@bobberb

bobberb commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator Author

@ostermayer good point, done in 344a8e7. There's now a comment at the chmod 0700, and the commit message says it outright: a failed run (e.g. one declared secret missing) leaves the dir 0700, so every service loses its secrets, not only the one whose secret failed; before, the dir kept 0751 from the previous run. The commit also credits d22c5da and c021a3e.

@seberm seberm added area: modules modules/ and pkgs/lib.nix type: security Hardening or vulnerability (public-safe only) labels Oct 16, 2026
@bobberb
bobberb force-pushed the setup-secrets-hardening branch from 344a8e7 to 5050289 Compare October 17, 2026 22:52
@seberm
seberm force-pushed the setup-secrets-hardening branch from 5050289 to 871973c Compare October 23, 2026 11:57
@github-actions github-actions Bot added the area: ci .github/, test/, dev/ label Oct 23, 2026
@seberm
seberm force-pushed the setup-secrets-hardening branch from 871973c to c4dec55 Compare October 25, 2026 09:20
prusnak added a commit that referenced this pull request Oct 25, 2026
## Problem

#49: with `nbLib.defaultHardening`, `ProtectSystem = "strict"` leaves
`/run` writable, and `PrivateDevices` bind-mounts the host's `/dev/shm`,
`/dev/mqueue` and `/dev/hugepages` read-write.

- Non-root services (bitcoind, clightning, lnd, ...) could create files
in the host's `/dev/shm` and `/dev/mqueue`.
- `onion-addresses` runs as root with `CAP_DAC_OVERRIDE`, so it could
write anywhere in `/run`, including `/run/keys` and `/run/wrappers`.

## Change

- `pkgs/lib.nix`: `defaultHardening` gets `ReadOnlyPaths = [ "/run"
"/dev" ]`.
- `RuntimeDirectory` (lnd's `/run/lnd`), `StateDirectory` and
`ReadWritePaths` still nest inside it, also for a `dataDir` under
`/run`.
- Device nodes like `/dev/null` stay writable, and connecting to unix
sockets under `/run` still works (postgres, mysqld, `NOTIFY_SOCKET`). A
read-only mount doesn't block writes to device nodes or socket connects.
- A user-set `ReadOnlyPaths` on one of these services is merged with the
list; only `mkForce` drops it.
- New VM test `hardening-ro-paths`, enabled in every scenario:
- Eval: every service whose `SystemCallFilter` carries
`defaultHardening`'s blocklist entry must have `/run` and `/dev` in
`ReadOnlyPaths`. This catches a module that later overrides the attr. It
detects exactly the 15 services that use `defaultHardening` in `full`.
- Runtime: root tries to create a file in `/run`, `/run/keys`,
`/dev/shm`, `/dev/mqueue` and `/dev/hugepages` inside each service. Root
ignores file permissions, so only a read-only mount stops it, and any
error other than EROFS also fails the test.
- Running services: the probe runs in the service's mount namespace via
`nsenter`.
- Active oneshot services (`onion-addresses`): the test adds the probe
as `ExecStartPost` through a runtime drop-in in `/run/systemd/system`,
restarts the unit, reads the probe output by the unit's `InvocationID`,
then removes the drop-in.
- It runs before `backups`, which stops bitcoind and the services that
depend on it.
- `docs/configuration.md`: new section "Write to /run or /dev/shm from a
service hook". It says which paths are read-only, that a custom
`preStart`/`postStart`/`ExecStartPost` writing there fails with
`Read-only file system`, and the two ways around it: `ReadWritePaths`
(merged with the service's own list) or a `+` prefix. Suggested by
@ostermayer.

## Testing

| Run | Result |
|---|---|
| ad hoc `{ lnd, clightning, tor, onion service }`, fix | PASS, runtime
check covers bitcoind, clightning, lnd, onion-addresses |
| same, `pkgs/lib.nix` at master (test kept) | FAIL: `ReadOnlyPaths
lacks /run or /dev: {'bitcoind': [], 'clightning': [], 'lnd': [],
'onion-addresses': []}` |
| same, `pkgs/lib.nix` at master, eval check disabled | FAIL: `bitcoind:
writable inside the service: ['/run', '/run/keys', '/dev/shm',
'/dev/mqueue', '/dev/hugepages']` |
| same, fix, but `onion-addresses` given `ReadOnlyPaths = [ ]`, eval
check disabled | FAIL: `onion-addresses: ['nb-ro-probe: writable /run',
... /run/keys, /dev/shm, /dev/mqueue, /dev/hugepages]` |
| `default`, `netns`, `hardened` | PASS, runtime check covers 13
services: bitcoind, btcpayserver, clightning, clightning-rest, fulcrum,
lightning-loop, lightning-pool, liquidd, lnd, mempool, nbxplorer,
onion-addresses, rtl (electrs is stopped earlier by `stop-electrs`) |
| `full`, `regtest`, `netnsRegtest` | PASS, the same 13 plus electrs |
| `lndPruned` | PASS (bitcoind, lnd, onion-addresses) |
| `trustedcoin` | PASS (bitcoind, clightning) |
| `wireguard-lndconnect`, `clightning-replication` (own test scripts,
without `hardening-ro-paths`; replication covers sshfs and gocryptfs),
run on the same module change | PASS |
| First round, test placed after `backups` | `full` FAIL: `backups` had
stopped bitcoind, so `assert "bitcoind" in checked` failed. The other 9
passed. Moved the test before `backups`. |
| `default`, rebased on `master` (1528ecf), with the docs commit | PASS,
runtime check covers the same 13 services |
| `./test/shellcheck.sh` | PASS |
| `nix flake check --all-systems` | PASS |
| Separate attacker review of the change | PASS, 3 low findings, all
fixed: `/dev/hugepages` added to the probe, a service restarting
mid-check no longer fails the test, and oneshot services are now probed.
Also checked: a unit given `ReadWritePaths = [ "/dev/shm" ]` passes the
eval check and fails the runtime check; unix socket connect under `/run`
works; `onion-addresses` ends `Result=success`. |
| Second separate review, of the reworked test | PASS. Re-ran a half-fix
(bitcoind with `ReadWritePaths = [ "/run/keys" "/dev/shm" ]`): the
runtime check reports both. Fixed its findings: wait for journald before
reading the probe output, wait for `onion-addresses` before the check,
clean up the drop-in and probe file. |

## Not covered

- `charge-lnd` is a timer-run oneshot that is inactive when the test
runs, so only the eval check covers it.
- Custom user hooks in these services (`preStart`, `postStart`,
`ExecStartPost`) that write to `/run` or `/dev/shm` now fail with EROFS.
No in-tree module does this. `docs/configuration.md` documents it and
the workarounds.
- No `versioning.nix` entry: whether a config breaks depends on user
scripts, which no eval-time condition can see.
- Mounts the host creates under `/run` after a service started (e.g.
logind's `/run/user/<uid>`) can arrive writable through mount
propagation, as the #48 review found for `setup-secrets`. Not checked
here.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
@seberm

seberm commented Oct 25, 2026

Copy link
Copy Markdown
Contributor

Concept ACK, I welcome the hardening. But I want to be careful not to break existing deployments, because I'm not sure how all users manage their secrets.


Users with secretsSetupMethod = "manual" (and NixOps) are not affected, since setup-secrets doesn't run for them. Everyone with setupSecrets enabled is: the generateSecrets users (all our examples) and krops users. Among them, some may mix generated secrets with ones managed by sops-nix or agenix, and those are symlinked into /run. For these users the change must not break the deployment, or at least the migration must be clear and easy.

Two concerns:

1. Symlinked secrets now take the node down. With setupSecrets enabled, a secret placed into secretsDir by sops-nix (sops.secrets.<name>.path) or agenix (age.secrets.<name>.path) is a symlink into /run. With ReadOnlyPaths = /run, the chown on the target fails with EROFS:

chown: changing ownership of 'backup-encryption-env': Read-only file system

Fail-closed then leaves the dir 0700, so every service loses its secrets.

2. No versioning.nix entry. Fail-closed, the symlink failure, and the sandbox limits on custom generateSecretsCmds all break things at runtime. Our policy requires an entry, and condition = config.nix-bitcoin.setupSecrets matches exactly the affected users.

I prepared quick fixups in my fork. Please review them and cherry-pick what makes sense:

  • seberm/bitcoinix@89708f9: a symlinked declared secret is never changed, only checked. Its target must already have the declared owner and mode, otherwise the unit fails with a clear error. ReadOnlyPaths stays as a second barrier. Test cases are updated.
  • seberm/bitcoinix@b28ad14: a 0.1.3 versioning entry plus docs (upgrade notes and the secrets dir appendix).

With both, default passes. Without the first commit, the new test fails with the EROFS above.

@prusnak
prusnak force-pushed the setup-secrets-hardening branch from c4dec55 to e7ec8cd Compare October 25, 2026 22:20
@github-actions github-actions Bot added the area: docs docs/, README, examples/, SECURITY.md, book.toml, assets label Oct 25, 2026
@prusnak

prusnak commented Oct 25, 2026

Copy link
Copy Markdown
Contributor

rebased on top of master, add more docs and tests

bobberb and others added 3 commits October 25, 2026 23:41
setup-secrets ran as root with no systemd hardening, although it only
creates, chowns and chmods files in secretsDir. It now uses
nbLib.defaultHardening with the overrides it needs: real uid mapping
(PrivateUsers = false), CAP_CHOWN, CAP_FOWNER and CAP_DAC_OVERRIDE only,
no network, and secretsDir writable.

/run and /dev are also made read-only. ProtectSystem=strict does not
cover them here: on systemd 260, adding ProtectKernelTunables,
ProtectControlGroups, ProtectProc or ProcSubset (all in defaultHardening)
leaves /run writable, and PrivateDevices bind-mounts the host's
/dev/{shm,mqueue,hugepages,pts}. Without this, a declared secret
symlinked into one of them got its target chowned. Now symlink targets
outside secretsDir are read-only and the unit fails with EROFS instead.
Hardlinks still reach their inode; planting one needs root.

With generateSecrets, an unsandboxed `mkdir -p` in ExecStartPre creates
the dir first, because ReadWritePaths can only bind an existing path.

The pass that makes undeclared entries root-only listed them with
`printf '%s\n' *` and passed the list unquoted to chown/chmod. Dotfiles
were skipped, a name starting with `-` was parsed as an option (making
the unit fail), and a name with glob characters was expanded again
(a file named `*` expands to every secret, which would all become
root:root 440). It now walks `find -mindepth 1 -maxdepth 1 -print0`,
quotes every name and passes `--`. Symlinks only get `chown -h`, because
chmod would follow them to their target.

The dir is now 0700 while entries are processed, not only with
generateSecrets, so no one else can add or swap entries meanwhile. This
fails closed: a failed run (e.g. one declared secret is missing) now
leaves the dir 0700, so every service loses access to its secrets, not
only the service whose secret failed. Before, the dir kept its 0751 from
the previous run. A failed run with generateSecrets already left it
0700. A comment at the chmod says so.

The sandbox and the dotfile fix follow the secrets.nix parts of
ostermayer/nix-bitcoin@d22c5da and ostermayer/nix-bitcoin@c021a3e. The
unquoted names are a low finding in the ostermayer/nix-bitcoin security
audit (docs/security-audit-2026-08-14.md).

Fixes bitcoinix#25

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Assisted-by: Claude Code (Claude Opus 5.5)
Warn setup-secrets users at config version 0.1.3 about external secret
symlinks, custom generators, and failures that block all service access.
Document migration and recovery steps and the generator's sandbox limits.

Assisted-by: Codex (GPT-6)
Add a CI scenario that provisions secrets once before setup-secrets, with
generateSecrets disabled. Verify that a missing secret leaves the directory
root-only, blocks access to another readable secret, and that restoring the
file and rerunning setup restores permissions and access without changing
the secret contents.

Assisted-by: Codex (GPT-6)
@prusnak
prusnak force-pushed the setup-secrets-hardening branch from e7ec8cd to e446711 Compare October 25, 2026 22:44
@prusnak
prusnak requested a review from seberm October 25, 2026 23:02
prusnak
prusnak previously approved these changes Oct 25, 2026

@ostermayer ostermayer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I read e446711. The sandbox and the find -print0 loop fix both problems from #25, and the setup-secrets and setup-secrets-supplied tests cover the dotfile, the -x and * names, the undeclared symlink, and a declared symlink into /run and /dev/shm. The 0.1.3 versioning entry reaches exactly the users who run setup-secrets, and docs/upgrading.md tells them what to move before they deploy, so seberm's migration point looks covered to me.

One nit, no need to hold the merge for it: #51 put ReadOnlyPaths = [ "/run" "/dev" ] into defaultHardening yesterday, so the explicit line in secrets.nix is now a duplicate. The comment above it still explains why the paths matter, so it can stay as documentation or go.

Models: GLM 5.3 (max) reviewed the tree at e446711 and found nothing in the files this PR touches. Its three findings are in netns-isolation.nix, presets/enable-tor.nix and clightning-plugins/trustedcoin.nix. Codex (GPT-6 Astra, xhigh) graded them: one false positive and two confirmed at info and low, and I'll look at those separately. DeepSeek V4.1 Flash 1017 (max) timed out at the provider and gave no result.

…ening

nbLib.defaultHardening already sets ReadOnlyPaths = [ "/run" "/dev" ]
with the same reasoning, so the override and its comment only repeat it.

Assisted-by: Claude Code (Claude Opus 5.5)
@seberm

seberm commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

I pushed a small commit on top that drops the ReadOnlyPaths = [ "/run" "/dev" ] override and its comment from setup-secrets. defaultHardening already sets the same value, so the effective unit config doesn't change.

@seberm
seberm enabled auto-merge October 26, 2026 20:50
@seberm
seberm merged commit 4807721 into bitcoinix:master Oct 26, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: ci .github/, test/, dev/ area: docs docs/, README, examples/, SECURITY.md, book.toml, assets area: modules modules/ and pkgs/lib.nix type: security Hardening or vulnerability (public-safe only)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

secrets: setup-secrets runs as unsandboxed root, and the lockdown of unlisted files skips dotfiles

4 participants