Repository navigation
secrets: sandbox setup-secrets and lock down every unlisted entry - #48
Conversation
ostermayer
left a comment
There was a problem hiding this comment.
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.
8c3ff91 to
344a8e7
Compare
|
@ostermayer good point, done in 344a8e7. There's now a comment at the |
344a8e7 to
5050289
Compare
5050289 to
871973c
Compare
871973c to
c4dec55
Compare
## 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)
|
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 Two concerns: 1. Symlinked secrets now take the node down. With Fail-closed then leaves the dir 2. No I prepared quick fixups in my fork. Please review them and cherry-pick what makes sense:
With both, |
c4dec55 to
e7ec8cd
Compare
|
rebased on top of master, add more docs and tests |
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)
e7ec8cd to
e446711
Compare
ostermayer
left a comment
There was a problem hiding this comment.
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)
|
I pushed a small commit on top that drops the |
Problem
Two issues in
modules/secrets/secrets.nix(#25):setup-secretsruns as root with no systemd hardening, although it only creates, chowns and chmods files insecretsDir.printf '%s\n' *and passed the list unquoted tochown/chmodwith no--. Dotfiles were skipped and kept their owner and mode. A file named-xwas parsed as an option, so the unit failed. A file named*was expanded again to every secret, which would all becomeroot:root 440.Change
setup-secretsusesnbLib.defaultHardeningwith 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 = strictdoes not cover these here:/run: on systemd 260, addingProtectKernelTunables,ProtectControlGroups,ProtectProc = invisibleorProcSubset = pid(all indefaultHardening) leaves/run,/run/keysand/run/wrapperswritable./dev:PrivateDevicesbind-mounts the host's/dev/shm,/dev/mqueue,/dev/hugepagesand/dev/ptsread-write.secretsDirunder/runstill works, becauseReadWritePathscan be nested inReadOnlyPaths. Redirects to/dev/nullstill work too.ProtectHome = read-onlyinstead oftrue: systemd can't nestReadWritePathsunder an inaccessible/home, sotruewould break asecretsDirbelow/home.generateSecrets, an unsandboxedExecStartPre=+mkdir -p -m 0700 <secretsDir>runs first, becauseReadWritePathscan only bind a path that already exists. That command has fixed arguments.secretsDir./tmpand/var/tmp./procroot succeeds, but no file can be created there, andProtectProc=invisiblewithProcSubset=pidhides other processes.memory.pressurefile.0700right afterchown root:, on every path. Before, this only happened withgenerateSecrets. A deployment that left the dir group- or world-writable could otherwise let someone add or swap entries while they are being processed.generateSecrets.0700withoutgenerateSecretstoo, so the unit fails closed. WithgenerateSecretsthis was already the behavior. Every service then gets EACCES on its secrets until a run succeeds, not only the service whose secret is broken.find . -mindepth 1 -maxdepth 1 -print0, so dotfiles and names containing newlines are included. Every name is quoted and passed after--. Symlinks only getchown -h root:, because chmod would change their target. A link grants no access by itself. Thecomm/LC_COLLATEsort 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 intest/tests.pybecause each run makes the secrets dir0700until it succeeds. When it ran earlier, it made a still-startinglndfail indefault. The test is enabled in every scenario wheresetupSecretsis on. It checks:ProtectSystem,PrivateNetwork,NoNewPrivilegesandCapabilityBoundingSet;-x,*and.dotfile(created asnobody:nogroup 666) end uproot:root 440;root:rootwhile its target in/runstaysnobody:nogroup 644;/secretschanged owner or mode, and the dir isroot:root 751;/runand/dev/shmin turn, that a declared secret replaced by a symlink to a file there makes the restart fail withResult=exit-code(not a start-limit hit;reset-failedruns before every restart), and that the target staysnobody:nogroup 644. After each case the secret is restored and/secretsis compared with its earlier state.{ services.lnd.enable = true; }, fix/devremoved fromReadOnlyPaths/runcase passes, then the/dev/shmcase's restart unexpectedly succeededReadOnlyPathsremoved entirely (earlier round)ProtectSystemassertionchown: invalid option -- 'x', unit fails.dotfilestaysnobody:nogroup 666ExecStartPost, bitcoind): touch/chown on every mount pointsecretsDir, private/tmp,/var/tmp, plus the no-op/procchown and the unit's ownmemory.pressurelisted above (the probe flagged those two, which is why its run ends withbad=1; neither can be reached through a symlinked secret)secretsDir = "/run/nbsec"(earlier round, before/devwas added)defaultnetnsRegtestwireguard-lndconnect(wg genkey)clightning-replication(ssh-keygen)./test/shellcheck.shsetup-secretsstart scriptnix flake check --all-systems/runwritable in the sandbox, a symlinked secret's target there got chowned. Round 2:/dev/{shm,mqueue,hugepages,pts}writable, same attack. Both fixed withReadOnlyPaths, each with a red/green test case. Round 3: PASSNot covered
secretsDir, not every file outside it. An undeclared hardlink insecretsDirstill reaches its inode, which then becomesroot:root 440. This predates the PR, and planting a hardlink needs root.secretsDir, the unit now fails with EROFS, where before it changed the target. I added noversioning.nixentry: this depends on what is on disk at runtime, so no eval-time condition can detect it.generateSecretsCmdsthat need the network, write outsidesecretsDir, or need W^X memory now fail. So does apermissionsvalue with setuid or setgid bits (RestrictSUIDSGID). None of the in-tree modules do any of these.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.secretsDirstill get a non-recursiveroot: 0440, as before./runand/devgaps probably affect every service that usesdefaultHardening. That needs a separate issue and is not fixed here.full,regtest,hardened,trustedcoin. A reviewer ranhardenedin an earlier round, and it passed./run/user/<uid>) arrive writable through mount propagation. Using that needs root to plant a symlink, within a sub-second window./runand/devmounts probably exist in every unit that usesnbLib.defaultHardening. Not changed here; worth its own issue.🤖 Generated with Claude Code