diff --git a/CHANGELOG.md b/CHANGELOG.md index 7eab478e0..73f1ce994 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 Storing into an undeclared name used to fail part-way through the store loop with `broker: Secret 'NAME' is not defined in profile 'default'`; that error now also names the fix (`add NAME --optional`, or re-run with `--declare`). +- `sudo-secretspec` builds and runs on NixOS (Linux). Per-OS paths, the service + identity rules and compile-time overrides (`SUDO_SECRETSPEC_SUDO`, + `SUDO_SECRETSPEC_BROKER_PATH`, `SUDO_SECRETSPEC_CONFIG_PATH`) live in one + `platform` module; macOS paths are unchanged. `add`, `set`, `get`, `run`, + `restore` and the other broker-backed commands work through the same + `sudo` + sudoers boundary. `install`, `uninstall`, `rollback` and `doctor` + are macOS-only and refuse on Linux, pointing at the NixOS module. +- A Nix flake (`flake.nix`) with `packages..sudo-secretspec` and + `nixosModules.default` (`services.sudo-secretspec`), which declares the + `sudo-secretspec` service user, the immutable broker store path (baked in at + compile time, not a `/run` symlink), the vault under `/var/lib`, the + root-owned `/etc/sudo-secretspec.toml` and the NOPASSWD sudoers rules. ### Fixed diff --git a/devenv.nix b/devenv.nix index 9e839157a..a590ede29 100644 --- a/devenv.nix +++ b/devenv.nix @@ -122,8 +122,9 @@ clippy.settings.offline = false; }; - # sudo-secretspec-cli is a macOS-only downstream companion and does not build - # on Linux; run its suite with `cargo test -p sudo-secretspec-cli` on macOS. + # sudo-secretspec-cli builds on Linux (see flake.nix), but its test suite is + # macOS-shaped (macOS paths, a real sudo and service accounts); run it with + # `cargo test -p sudo-secretspec-cli` on macOS. enterTest = '' cargo test --all --exclude sudo-secretspec-cli ''; diff --git a/docs/design/dann-deployment-threat-model.md b/docs/design/dann-deployment-threat-model.md new file mode 100644 index 000000000..7397db7ae --- /dev/null +++ b/docs/design/dann-deployment-threat-model.md @@ -0,0 +1,101 @@ +# Design note: the dann deployment threat model (H6 / M1) + +**Status:** decision recorded; the deployment wiring itself is the Wave 2 +workstream (site-dann NixOS module + sops). +**Date:** 2026-10-29 +**Scope:** `dann.dclark.us` (the site-dann NixOS host). Not upstream material. +**Prompted by:** adversary review findings H6 and M1 on the Linux port. + +This note records, honestly, what sudo-secretspec *is* and *is not* on dann, and +which secrets belong in its vault. It is the counterpart to +`privilege-boundary-and-packaging.md`, which assumes a macOS host where the +operator is a *non-root* user and the boundary is real. On dann that assumption +does not hold, and the design must say so rather than pretend otherwise. + +## What the boundary is not, on dann + +On the Mac the boundary is genuine: the operator is an unprivileged account, the +broker's NOPASSWD verbs are the only route to the vault, and every other +operation (install, uninstall, rollback, `source-restore-force`, +`source-destroy`) falls through to interactive Touch ID. + +On dann the same module cannot deliver that. The host is disposable and +operator-managed end to end: + +- `configuration.nix` grants `%wheel ALL=(ALL:ALL) NOPASSWD:SETENV: ALL`, and + places the operator in `wheel` with `wheelNeedsPassword = false`. The operator + is therefore **root-equivalent**: `sudo cat /var/lib/sudo-secretspec/…` reads + the vault directly, so **confidentiality against the operator is nil.** +- The audit ledger is service-owned, and root can re-chain it from genesis (the + chain has no external anchor), so **audit is not tamper-evident against the + operator.** +- sudoers applies tags last-match-wins, so the `SETENV` tag on the wheel rule + (`%wheel ALL=(ALL:ALL) NOPASSWD:SETENV: ALL`) wins for the operator regardless + of the module's own NOPASSWD grant lines (which carry no `SETENV` tag). The + real route is `sudo -u env VAR=… $BROKER …`, which reaches the broker + with caller-chosen variables that `purge_ambient_env` does not cover. This is + moot while the operator is root — which is the point — and it is a reason + never to deploy this pattern on a host where the operator is *not* already + root-equivalent. + +So on dann, sudo-secretspec provides exactly two things, and it is worth naming +them because they are the whole reason to run it there: + +1. **Reason-forcing friction.** A credential operation goes through a named + verb with a required `--reason`, recorded in the ledger, rather than a bare + `sudo cat`. It does not stop the operator from reading a secret; it makes the + act deliberate and legible. +2. **A convenience audit trail.** The ledger is a searchable record of *what was + read or written, when, and why*, which is a workflow convenience rather than + a security control on this host. + +This matches `configuration.nix`'s own honesty rule and the host's disposability +invariant: nothing on the box survives a rebuild, so nothing on it should be +treated as a tamper-proof record. + +## What goes in the vault (M1) + +The five AI-pool keys are **declarative**: sops → `environmentFiles` → Hermes's +`.env` at activation. Putting any of them in the vault would create a second, +mutable source of truth that a rebuild does not restore, and the two copies +would drift — a `sudo-secretspec set` "rotation" would never reach Hermes, which +keeps reading the sops value, while the operator believes the key rotated. +Bridging the vault into `/run/secrets` (or Hermes's env) would make the +NOPASSWD `source-set` writer a confused deputy for another service's +credential. + +**Decision:** the pool keys stay sops-only. Nothing is bridged between the vault +and `/run/secrets`. + +The minimum vault set is the secrets **the entity itself mutates at runtime or +uses interactively, which no NixOS service consumes**: + +| Secret | Where it lives | Why | +| --- | --- | --- | +| `GITHUB_TOKEN` | sops, `owner = "dann"; mode = "0400"` | Static; no runtime mutation. Reproducible from sops. | +| Gmail OAuth **refresh token** | vault | Rotates, so it needs a mutable store. | +| Gmail OAuth client id/secret | sops | Configuration, not high-value. | +| Google account **password** | **the Mac only** | Enables account recovery and 2FA changes; the refresh token already covers Gmail. | + +A static secret with no runtime mutation gets the same protection from sops, so +the vault exists for the refresh token — or, more precisely, it exists for the +reason/audit UX described above, and the refresh token is the one secret that +genuinely needs its mutable store. + +Two consequences, recorded so they are not re-litigated: + +- **Back up the vault, or accept re-auth after a reinstall.** The refresh token + is the one piece of vault state a rebuild does not restore. +- **No Google password on the VPS, ever.** It is the account-recovery and 2FA + key, and its presence would convert a disposable box into a credential the + operator must treat as if it were the Mac. + +## Tamper-evidence, if it is ever wanted + +None of this is a boundary, and the ledger is not tamper-evident against a +root-equivalent operator. If tamper-evidence *does* matter at some point, the +cheap next step is to ship `audit-verify`'s tip hash off-host on a schedule +(e.g. via `fleet-watch`), which gives the chain an external anchor and makes +retrospective tampering detectable. That is deliberately **not** in scope for +the port; it is recorded here as the known upgrade path rather than discovered +again later. diff --git a/flake.nix b/flake.nix new file mode 100644 index 000000000..ad1254b98 --- /dev/null +++ b/flake.nix @@ -0,0 +1,37 @@ +{ + description = "sudo-secretspec: privilege-separated SecretSpec companion (NixOS module + package)"; + + inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + + outputs = + { self, nixpkgs }: + let + systems = [ + "x86_64-linux" + "aarch64-linux" + "aarch64-darwin" + "x86_64-darwin" + ]; + forAllSystems = f: nixpkgs.lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system}); + in + { + packages = forAllSystems (pkgs: rec { + sudo-secretspec = pkgs.callPackage ./nix/package.nix { }; + default = sudo-secretspec; + }); + + nixosModules.default = import ./nix/module.nix self; + nixosModules.sudo-secretspec = self.nixosModules.default; + + # The VM test boots a NixOS machine and drives sudo, so it is Linux-only + # (needs QEMU) and runs in CI, not on a macOS dev box. Evaluating it also + # forces the module's import-from-derivation, so CI must set + # `allow-import-from-derivation = true`. + checks = nixpkgs.lib.genAttrs [ "x86_64-linux" "aarch64-linux" ] (system: { + sudo-secretspec-vm = import ./nix/test.nix { + pkgs = nixpkgs.legacyPackages.${system}; + inherit self; + }; + }); + }; +} diff --git a/nix/module.nix b/nix/module.nix new file mode 100644 index 000000000..233977af6 --- /dev/null +++ b/nix/module.nix @@ -0,0 +1,247 @@ +# NixOS module for the sudo-secretspec privilege boundary. +# +# The boundary is `sudo` + a NOPASSWD sudoers rule; there is no daemon. This +# module is the declarative equivalent of what `sudo-secretspec install` does +# on macOS (`install.rs`): service account, protected config, vault directory, +# sudoers policy. The imperative `install`/`uninstall`/`rollback`/`doctor` +# commands refuse on Linux and point here. +# +# `doctor` — and its drift/layout checks — is a macOS-only diagnostic. Its +# checks are macOS-shaped (a real `/bin/ls`, a `sudoers.d` `#include` line, +# root-owned `/etc/static`, Homebrew paths) and have no NixOS equivalent, so +# the Linux binary refuses it via `platform::lifecycle_refusal`. The declared +# boundary has no drift checker instead: the broker is an immutable store path +# (not a mutable `/run` symlink), and `systemd.tmpfiles` re-asserts the vault +# owner/mode and the config file owner/mode on every activation, so the +# equivalent guarantee is "a rebuild is the only way anything changes". +self: +{ + config, + lib, + pkgs, + ... +}: + +let + cfg = config.services.sudo-secretspec; + inherit (lib) mkOption mkEnableOption mkIf types; + + # Single source of truth: the paths compiled into the package. + # + # `broker` is the `libexec/` copy in the store — a distinct regular file from + # the public client at `bin/`, so `main`'s canonical-path identity check can + # tell the NOPASSWD broker apart from the operator's client. The flake bakes + # `platform::BROKER_PATH` to exactly this store path (`SUDO_SECRETSPEC_BROKER_PATH` + # in package.nix), so `broker` here and the path `print-sudoers` emits agree. + broker = "${cfg.package}/libexec/sudo-secretspec"; + configPath = cfg.package.passthru.configPath; + + # The sudoers policy is emitted by the same binary that enforces it, through + # the hidden `print-sudoers` subcommand (`install.rs::linux_sudoers_text`). + # Import-from-derivation means the module's sudoers text and the compiled-in + # broker path can never drift apart: when the package changes, the text is + # regenerated from the new binary. `OPERATOR`/`SERVICE_USER` reach the command + # as derivation env, never through shell interpolation, so a hostile operator + # or service-user string cannot break out of the builder command. + sudoersText = pkgs.runCommand "sudo-secretspec-sudoers" + { + OPERATOR = cfg.operator; + SERVICE_USER = cfg.serviceUser; + } + ''"${cfg.package}/bin/sudo-secretspec" print-sudoers \ + --operator "$OPERATOR" --service-user "$SERVICE_USER" > "$out"''; + + identity = "[a-z_][a-z0-9_-]{0,30}"; # config.rs `valid_service_identity` (Linux) + tomlFormat = pkgs.formats.toml { }; + + # Keys are exactly `config.rs`'s `Config` (`deny_unknown_fields`). `engine` + # and `audit_helper` are required by the parser; on a single-binary install + # both name the privileged binary. + configFile = tomlFormat.generate "sudo-secretspec.toml" ( + { + engine = broker; + audit_helper = broker; + vault = cfg.vault; + vault_realpath = cfg.vault; + service_user = cfg.serviceUser; + service_group = cfg.serviceGroup; + profile = cfg.profile; + } + // lib.optionalAttrs (cfg.declarations != null) { declarations = "${cfg.declarations}"; } + ); + manifest = "${cfg.vault}/secretspec.toml"; +in +{ + options.services.sudo-secretspec = { + enable = mkEnableOption "the sudo-secretspec privilege boundary (sudo + sudoers, no daemon)"; + + package = mkOption { + type = types.package; + default = self.packages.${pkgs.stdenv.hostPlatform.system}.sudo-secretspec; + defaultText = lib.literalExpression "sudo-secretspec.packages.\${system}.sudo-secretspec"; + description = '' + The companion build. It must be compiled with the Linux path overrides + (the flake's package is); the broker and config paths are read from it. + ''; + }; + + operator = mkOption { + type = types.str; + description = '' + User granted the NOPASSWD rules for the unattended broker verbs. No + default: the operator must be named explicitly, and it must be a + declared, non-root, non-service user (asserted below). The name is + formatted verbatim into the sudoers text, so it is constrained to a + single plain principal. + ''; + }; + + serviceUser = mkOption { + type = types.str; + default = "sudo-secretspec"; + description = "System user that owns the vault and runs the broker."; + }; + + serviceGroup = mkOption { + type = types.str; + default = "sudo-secretspec"; + description = "Primary group of the service user."; + }; + + vault = mkOption { + type = types.str; + default = "/var/lib/sudo-secretspec"; + description = '' + Vault directory. Must be a direct child of `/var/lib`: the broker + refuses any other location (`config.rs`). + ''; + }; + + profile = mkOption { + type = types.str; + default = "default"; + description = "Manifest profile the broker resolves secrets from."; + }; + + declarations = mkOption { + type = types.nullOr types.path; + default = null; + description = '' + Tracked declarations file (a `secretspec.toml`). It is recorded in the + protected config for `template-check`, and copied into the vault as + `secretspec.toml` if the vault has none yet. The runtime manifest is + never overwritten afterwards: `add`/`undeclare` edit it in place. + When null the manifest must be provided by hand; the broker refuses + to run without one. + ''; + }; + }; + + config = mkIf cfg.enable { + assertions = [ + { + assertion = config.security.sudo.enable; + message = "services.sudo-secretspec needs security.sudo.enable (the boundary is sudo)."; + } + { + assertion = lib.hasPrefix "/etc/" configPath; + message = "sudo-secretspec: the package's config path (${configPath}) must live under /etc."; + } + { + # A direct child of /var/lib, named by a plain lowercase token. The + # regex (anchored by `builtins.match`) rules out traversal (`..`), + # nested paths, and a `nixos`/`systemd`/`private` collision — those are + # system state directories that a re-owning tmpfiles rule must never + # touch. + assertion = + builtins.match "/var/lib/[a-z0-9_][a-z0-9_.-]*" cfg.vault != null + && !(builtins.elem (builtins.baseNameOf cfg.vault) [ "nixos" "systemd" "private" ]); + message = "services.sudo-secretspec.vault must be a direct child of /var/lib with a plain name (not nixos, systemd, or private)."; + } + { + assertion = + builtins.match identity cfg.serviceUser != null + && builtins.match identity cfg.serviceGroup != null + && cfg.serviceUser != "root" + && !(builtins.elem cfg.serviceGroup [ + "root" + "wheel" + "adm" + "keys" + "systemd-journal" + "nixbld" + ]); + message = "services.sudo-secretspec: serviceUser/serviceGroup must match ${identity}, not be root, and serviceGroup must not be a privileged system group (wheel, adm, keys, systemd-journal, nixbld)."; + } + { + assertion = builtins.match "[A-Za-z][A-Za-z0-9_-]{0,63}" cfg.profile != null; + message = "services.sudo-secretspec.profile must be a plain profile name (letters, digits, `_`, `-`)."; + } + { + # The operator name is formatted verbatim into the sudoers text, so it + # must be a single plain principal — and one that cannot be confused + # with a sudoers keyword (`ALL`, `root`) or the service account. It must + # also be a declared user so a typo cannot silently grant the verbs to a + # name that never exists. + assertion = + builtins.match identity cfg.operator != null + && cfg.operator != "ALL" + && cfg.operator != "root" + && cfg.operator != cfg.serviceUser + && builtins.hasAttr cfg.operator config.users.users; + message = "services.sudo-secretspec.operator must be a declared, non-root, non-service user matching ${identity} (and not `ALL`)."; + } + ]; + + users.groups.${cfg.serviceGroup} = { }; + users.users.${cfg.serviceUser} = { + isSystemUser = true; + group = cfg.serviceGroup; + description = "sudo-secretspec broker"; + home = "/var/empty"; + shell = "${pkgs.shadow}/bin/nologin"; + }; + + environment.systemPackages = [ cfg.package ]; + + # Root-owned, mode 0444, a real file (a `mode` other than "symlink" makes + # the etc builder copy rather than link): the broker reads it as the + # service user and it is the boundary's control plane. + environment.etc.${lib.removePrefix "/etc/" configPath} = { + source = configFile; + mode = "0444"; + user = "root"; + group = "root"; + }; + + systemd.tmpfiles.rules = [ + # `d` re-asserts owner and mode on an existing directory every run; the + # broker refuses anything but 0700 owned by the service user. + "d ${cfg.vault} 0700 ${cfg.serviceUser} ${cfg.serviceGroup} -" + ] + ++ lib.optionals (cfg.declarations != null) [ + # Seed only: `C` never overwrites, and `add`/`undeclare` mutate this file. + "C ${manifest} 0600 ${cfg.serviceUser} ${cfg.serviceGroup} - ${cfg.declarations}" + # The broker requires exactly 0600, service-user owned. + "z ${manifest} 0600 ${cfg.serviceUser} ${cfg.serviceGroup} -" + ]; + + # The whole policy — the `Defaults!` line *and* the operator's NOPASSWD + # grant lines — comes from `sudoersText`, the IFD derivation that runs the + # binary's own `print-sudoers`. `security.sudo.extraConfig` is + # `types.lines`, merged by plain `concatStringsSep "\n"` with no + # `sortProperties` pass, so `mkOrder`/`mkAfter` carry no weight here; what + # actually orders it is nixpkgs' `sudo.nix`, which appends `extraConfig` + # LAST — after the stock `%wheel` `extraRules` block. sudoers is + # last-match-wins, so these grants are the final lines and take effect over + # `%wheel`'s password prompt. The only residual is ordering against a + # *second* module that also sets `extraConfig`: nixpkgs emits both in the + # order its `concatStringsSep` sees them, and whichever lands later wins. + # That is an availability-only risk (a later rule could re-prompt for a + # verb), never an escalation — it cannot add a grant this module did not + # already emit. There is no `timestamp_timeout=0` line and no `doctor` grant + # on Linux: the former has no client path to attach to, the latter refuses + # on Linux. + security.sudo.extraConfig = builtins.readFile sudoersText; + }; +} diff --git a/nix/package.nix b/nix/package.nix new file mode 100644 index 000000000..11e1b6425 --- /dev/null +++ b/nix/package.nix @@ -0,0 +1,83 @@ +# sudo-secretspec-cli, built from this workspace. +# +# Build helper: nixpkgs' `rustPlatform.buildRustPackage` with `cargoLock`. +# Cargo.lock has no git dependencies, so no `outputHashes` are needed, and the +# flake keeps a single input (nixpkgs) rather than adding crane/naersk, which +# would each be one more pinned input guarding a privilege boundary. +# +# On Linux the three platform paths are baked into the binary at compile time +# (see `sudo-secretspec-cli/src/platform.rs`); on macOS the defaults apply +# untouched, so a Nix-built macOS binary behaves exactly like the Homebrew one. +{ + lib, + stdenv, + rustPlatform, + pkg-config, + sqlite, + # NixOS has no /usr/bin/sudo: the setuid wrapper lives in /run/wrappers/bin. + sudoPath ? "/run/wrappers/bin/sudo", + # Root-owned 0444 file written by the NixOS module. + configPath ? "/etc/sudo-secretspec.toml", +}: + +rustPlatform.buildRustPackage { + pname = "sudo-secretspec"; + version = (builtins.fromTOML (builtins.readFile ../Cargo.toml)).workspace.package.version; + + src = lib.cleanSourceWith { + src = ../.; + filter = + path: type: + lib.cleanSourceFilter path type + && !(builtins.elem (baseNameOf path) [ + "target" + "node_modules" + ".devenv" + ".direnv" + ]); + }; + + cargoLock.lockFile = ../Cargo.lock; + + # The workspace has seven members; only the companion is wanted here. + cargoBuildFlags = [ + "--package" + "sudo-secretspec-cli" + ]; + + # The suite is macOS-shaped (macOS paths, a real `sudo`, service accounts) + # and needs a host it can mutate; it runs in CI, not in the Nix sandbox. + doCheck = false; + + nativeBuildInputs = [ pkg-config ]; + # The companion links the system SQLite (see FORK-AI.md: not `bundled`). + buildInputs = [ sqlite ]; + + env = lib.optionalAttrs stdenv.hostPlatform.isLinux { + SUDO_SECRETSPEC_SUDO = sudoPath; + # The broker path is the store path of the `libexec/` copy, baked at build + # time. There is deliberately no `/run` symlink: a sudoers rule on a + # mutable symlink could be repointed, whereas the store path is immutable. + SUDO_SECRETSPEC_BROKER_PATH = "${builtins.placeholder "out"}/libexec/sudo-secretspec"; + SUDO_SECRETSPEC_CONFIG_PATH = configPath; + }; + + # The public client and the privileged broker must be DIFFERENT paths. + # `main` refuses everything but `__broker`/`doctor` when + # canonicalize(current_exe()) == canonicalize(BROKER_PATH), so that the + # NOPASSWD path cannot serve `install`/`rollback`. If the broker path were + # `bin/sudo-secretspec`, the operator's own client would resolve to the same + # store path and refuse every command. A second copy under `libexec/` keeps + # the two identities apart without changing that check. + postInstall = '' + install -D -m755 "$out/bin/sudo-secretspec" "$out/libexec/sudo-secretspec" + ''; + + passthru = { inherit sudoPath configPath; }; + + meta = { + description = "Privilege-separated SecretSpec companion (sudo + sudoers boundary)"; + mainProgram = "sudo-secretspec"; + platforms = lib.platforms.unix; + }; +} diff --git a/nix/test.nix b/nix/test.nix new file mode 100644 index 000000000..1abea5265 --- /dev/null +++ b/nix/test.nix @@ -0,0 +1,124 @@ +# NixOS VM test for the declared sudo-secretspec boundary. +# +# Boots a minimal NixOS machine with the module enabled and an operator user +# `dann` (deliberately NOT in `wheel`, so the module's sudoers policy is the +# only thing granting him anything), then asserts the boundary: +# +# * exactly the ten mediated broker verbs and `audit-verify` are NOPASSWD — +# 11 grant lines, each naming the broker once; +# * no blanket `NOPASSWD: ALL` grant sneaks in; +# * the broker's `Defaults!` line is exactly as emitted (env_reset, HOME +# pinned, /run/current-system secure_path, umask 0077, always_set_home); +# * the authenticated commands (`source-restore-force`, `source-destroy`) and +# the macOS-only diagnostic (`doctor`) are NOT NOPASSWD — sudo demands a +# password for them; +# * the Linux policy carries no macOS `timestamp_timeout=0` client line. +# +# The runtime assertions run as the operator, never as root: root is exempt from +# the NOPASSWD restriction, so `sudo -n -u ...` from root would always +# exec the broker regardless of grant. `sudo -u dann sudo -n ...` drops to the +# operator first, where `-n` (non-interactive) succeeds iff the verb is granted +# and otherwise fails with "a password is required". +# +# A granted verb is exercised with a real `--*` argument (`--client vmtest`, +# what the public client appends): the grant is ` __broker --*`, +# so a bare `` with no argument does not match the glob. `audit-verify` +# is granted exactly (no glob) and takes no argument. `source-restore --all` +# matches the `--*` glob, so sudo does NOT prompt — but the broker must refuse +# the mass restore itself (exit 2); with `declarations = null` the broker bails +# at manifest load before that guard, so here we assert only "no password +# demanded + non-zero exit", the exact refusal being a Rust unit test. +# +# This is a `testers.nixosTest`: it needs a hypervisor (QEMU), so it only runs on Linux +# and only in CI (Forgejo/Hyades), not on a macOS dev box. The module's +# import-from-derivation (the `print-sudoers` runCommand) also requires +# `allow-import-from-derivation = true` when evaluating the flake. +{ + pkgs, + self, +}: pkgs.testers.nixosTest { + name = "sudo-secretspec"; + + nodes.machine = { + imports = [ self.nixosModules.default ]; + + services.sudo-secretspec = { + enable = true; + operator = "dann"; + # No declarations: the vault/manager is out of scope for this test, which + # is only about the sudoers boundary. The broker never actually runs a + # credential operation here. + declarations = null; + }; + + users.users.dann = { + isNormalUser = true; + description = "operator (test)"; + }; + }; + + testScript = + { nodes, ... }: + '' + # The broker store path is interpolated by Nix into this line as a Python + # string literal (not a Nix `let` binding), so the f-strings below can use + # it. A Nix `let` value would never reach the Python script: `{broker}` + # here is Python syntax, not Nix interpolation. + broker = "${nodes.machine.config.services.sudo-secretspec.package}/libexec/sudo-secretspec" + + start_all() + machine.wait_for_unit("multi-user.target") + + # ---- the emitted policy, verbatim ------------------------------------ + # `security.sudo.extraConfig` lands in /etc/sudoers, appended LAST (after + # the `%wheel` extraRules block in /etc/sudoers.d), so our NOPASSWD grants + # win on last-match-wins. + sudoers = machine.succeed("cat /etc/sudoers") + + broker_lines = [l for l in sudoers.splitlines() if "__broker" in l] + assert len(broker_lines) == 11, f"expected 11 broker grant lines, got {len(broker_lines)}\n{sudoers}" + assert all("NOPASSWD:" in l for l in broker_lines), f"broker grants must all be NOPASSWD:\n{sudoers}" + assert not any("NOPASSWD: ALL" in l for l in broker_lines), f"no blanket grant may exist:\n{sudoers}" + + # The exact broker Defaults! line: env_reset, HOME pinned, the + # /run/current-system secure_path, umask 0077, always_set_home. + expected_defaults = f'Defaults!{broker} env_reset,env_keep-="HOME",secure_path=/run/current-system/sw/bin:/run/wrappers/bin,umask=0077,always_set_home' + assert expected_defaults in sudoers, f"missing/incorrect broker Defaults! line:\n{sudoers}" + + # No macOS-only client line, no doctor grant. + assert "timestamp_timeout=0" not in sudoers, "Linux policy must not set timestamp_timeout=0" + assert " doctor" not in sudoers, "Linux policy must not grant doctor" + + # ---- runtime: each mediated verb is NOPASSWD with a --* argument ------ + for verb in [ + "source-add", "source-set", "source-delete", "source-undeclare", + "source-get", "source-check", "source-export", "source-template-check", + "source-schema", "source-restore", + ]: + out = machine.execute( + f"sudo -u dann sudo -n -u sudo-secretspec {broker} __broker {verb} --client vmtest 2>&1" + ) + assert "a password is required" not in out[1], f"{verb} demanded a password:\n{out[1]}" + + # audit-verify is granted exactly (no glob) and takes no argument. + out = machine.execute( + f"sudo -u dann sudo -n -u sudo-secretspec {broker} __broker audit-verify 2>&1" + ) + assert "a password is required" not in out[1], f"audit-verify demanded a password:\n{out[1]}" + + # source-restore --all matches the `--*` glob (sudo does NOT prompt), but + # the broker refuses the mass restore (exit 2). + out = machine.execute( + f"sudo -u dann sudo -n -u sudo-secretspec {broker} __broker source-restore --all --to 1 --client vmtest 2>&1" + ) + assert "a password is required" not in out[1], f"source-restore --all demanded a password:\n{out[1]}" + assert out[0] != 0, f"source-restore --all unexpectedly succeeded:\n{out[1]}" + + # ---- runtime: authenticated + diagnostic verbs are NOT NOPASSWD ------- + for forbidden in ["source-restore-force --all", "source-destroy --all", "doctor"]: + out = machine.execute( + f"sudo -u dann sudo -n -u sudo-secretspec {broker} __broker {forbidden} 2>&1" + ) + assert "a password is required" in out[1], f"{forbidden} was not password-gated:\n{out[1]}" + ''; +} diff --git a/sudo-secretspec-cli/Cargo.toml b/sudo-secretspec-cli/Cargo.toml index 227c0710e..214e2c67e 100644 --- a/sudo-secretspec-cli/Cargo.toml +++ b/sudo-secretspec-cli/Cargo.toml @@ -33,5 +33,7 @@ uuid.workspace = true [dev-dependencies] tempfile.workspace = true -[target.'cfg(target_os = "macos")'.dependencies] +# Every call site is POSIX (geteuid, getuid, umask, chown, lchown, isatty, +# getpwuid, getpwnam, getgrgid), identical on macOS and Linux. +[target.'cfg(unix)'.dependencies] libc = "0.2" \ No newline at end of file diff --git a/sudo-secretspec-cli/src/broker.rs b/sudo-secretspec-cli/src/broker.rs index 2f4822f88..dc848cbda 100644 --- a/sudo-secretspec-cli/src/broker.rs +++ b/sudo-secretspec-cli/src/broker.rs @@ -23,7 +23,7 @@ use crate::config::Config; // Paths // --------------------------------------------------------------------------- -const CONFIG_PATH: &str = "/usr/local/etc/sudo-secretspec.toml"; +const CONFIG_PATH: &str = crate::platform::CONFIG_PATH; // --------------------------------------------------------------------------- // Broker CLI (sub-parser for __broker) @@ -1133,6 +1133,20 @@ fn execute(broker: &Broker, cfg: &Config, reason_hash: &str) -> (u8, Vec "source-restore" | "source-restore-force" | "source-destroy" => { let op = broker.operation.as_str(); + // `--all` and `--force` on the *plain* `source-restore` verb are + // refused here. The NOPASSWD grant for the plain verb is a `--*` + // glob, which also matches `source-restore --all`/`--force`, so a + // caller who invokes sudo directly (not the client, which routes + // those flags to `source-restore-force`) could reach an unattended + // whole-vault restore through the NOPASSWD grant. The authorisation + // gate must be the sudoers verb, not client routing. + if op == "source-restore" && (broker.all || broker.force) { + eprintln!( + "broker: source-restore --all/--force must run through source-restore-force" + ); + return (2, vec![]); + } + let db_path = cfg.vault.join("secrets.db"); // `Connection::open` defaults to SQLITE_OPEN_CREATE, so on a fresh // vault these verbs used to *create* an empty, schema-less @@ -2266,7 +2280,7 @@ BETA = { description = "second", required = false } secrets.delete("ALPHA").unwrap(); secrets.delete("BETA").unwrap(); - let mut broker = broker_op("source-restore"); + let mut broker = broker_op("source-restore-force"); broker.all = true; broker.to = Some("2".into()); @@ -2279,6 +2293,38 @@ BETA = { description = "second", required = false } assert_eq!(live_value(&cfg, "BETA").as_deref(), Some("b1")); } + #[test] + fn plain_source_restore_refuses_all_and_force() { + // M2: the plain verb's NOPASSWD grant is a `--*` glob that also matches + // `--all`/`--force`, so a direct sudo caller could reach an unattended + // whole-vault restore. The broker must refuse, so the gate is the + // sudoers verb and not client routing. + let _guard = EXECUTE_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let (_vault, cfg) = execute_fixture(); + fixture_secrets(&cfg) + .set("ALPHA", Some("a1".into())) + .unwrap(); + + let mut all = broker_op("source-restore"); + all.all = true; + all.to = Some("1".into()); + assert_eq!( + execute(&all, &cfg, &fixture_reason()).0, + 2, + "source-restore --all must refuse on the plain verb" + ); + + let mut force = broker_op("source-restore"); + force.force = true; + force.name = Some("ALPHA".into()); + force.to = Some("1".into()); + assert_eq!( + execute(&force, &cfg, &fixture_reason()).0, + 2, + "source-restore --force must refuse on the plain verb" + ); + } + #[test] fn restore_requires_a_target_and_a_selector() { let _guard = EXECUTE_LOCK.lock().unwrap_or_else(|e| e.into_inner()); diff --git a/sudo-secretspec-cli/src/config.rs b/sudo-secretspec-cli/src/config.rs index 0ce625a2b..d46175e13 100644 --- a/sudo-secretspec-cli/src/config.rs +++ b/sudo-secretspec-cli/src/config.rs @@ -1,5 +1,7 @@ use std::path::{Path, PathBuf}; +use crate::platform; + use serde::Deserialize; use thiserror::Error; @@ -78,13 +80,15 @@ impl Config { return Err(ConfigError::Invalid("managed paths must not contain '..'")); } } - let vault_name = direct_child(&self.vault, Path::new("/var/db"))?; - let real_name = direct_child(&self.vault_realpath, Path::new("/private/var/db"))?; + let vault_name = direct_child(&self.vault, Path::new(platform::VAULT_PARENT))?; + let real_name = direct_child(&self.vault_realpath, Path::new(platform::VAULT_REAL_PARENT))?; if vault_name != real_name { return Err(ConfigError::Invalid("vault and resolved vault must match")); } - if !valid_service_identity(&self.service_user, true) - || !valid_service_identity(&self.service_group, false) + if !valid_service_identity( + &self.service_user, + platform::SERVICE_USER_REQUIRES_UNDERSCORE, + ) || !valid_service_identity(&self.service_group, false) { return Err(ConfigError::Invalid("invalid service identity")); } @@ -116,6 +120,16 @@ fn direct_child<'a>(path: &'a Path, parent: &Path) -> Result<&'a std::ffi::OsStr if components.next().is_some() { return Err(ConfigError::Invalid("vault must be one direct child")); } + // A `.` or `..` component slips past the "one direct child" check and would + // let a config author aim the vault at `/var/lib` itself (`.`) or its + // parent (`..`); the module's tmpfiles rule would then re-own a system + // state directory on every activation. Refuse the traversal components. + if matches!( + name, + std::path::Component::CurDir | std::path::Component::ParentDir + ) { + return Err(ConfigError::Invalid("vault name must not be '.' or '..'")); + } Ok(name.as_os_str()) } @@ -134,12 +148,19 @@ fn valid_profile_name(value: &str) -> bool { } fn valid_service_identity(value: &str, require_underscore: bool) -> bool { - if value.is_empty() || value.len() > 31 || (require_underscore && !value.starts_with('_')) { + // The superuser is never a service identity. macOS got this for free from + // the mandatory underscore; Linux has no such prefix, so say it outright. + if value == "root" + || value.is_empty() + || value.len() > 31 + || (require_underscore && !value.starts_with('_')) + { return false; } value.bytes().enumerate().all(|(index, byte)| match byte { b'a'..=b'z' | b'_' => true, b'0'..=b'9' => index > 0, + b'-' => platform::SERVICE_IDENTITY_ALLOWS_HYPHEN && index > 0, _ => false, }) } diff --git a/sudo-secretspec-cli/src/drift.rs b/sudo-secretspec-cli/src/drift.rs index 38acdb049..9b3dbe361 100644 --- a/sudo-secretspec-cli/src/drift.rs +++ b/sudo-secretspec-cli/src/drift.rs @@ -62,7 +62,7 @@ impl Layout { .engine .parent() .and_then(Path::parent) - .unwrap_or_else(|| Path::new("/usr/local")) + .unwrap_or_else(|| Path::new(crate::platform::PREFIX)) .to_path_buf(); let libexec = prefix.join("libexec"); let bin = prefix.join("bin"); @@ -83,7 +83,7 @@ impl Layout { checker: bin.join("sudo-secretspec"), retired: share.join("sudo-secretspec-retired.toml"), guidance: share.join("AI-GUIDANCE.md"), - sudoers: PathBuf::from("/private/etc/sudoers.d/sudo-secretspec"), + sudoers: PathBuf::from(crate::platform::SUDOERS_FILE), source_manifest: share.join("MANIFEST.sha256"), config: config_path, adopted_vault: cfg.adopted_vault, diff --git a/sudo-secretspec-cli/src/install.rs b/sudo-secretspec-cli/src/install.rs index cce0708f0..742fa97ea 100644 --- a/sudo-secretspec-cli/src/install.rs +++ b/sudo-secretspec-cli/src/install.rs @@ -13,6 +13,8 @@ use std::process::Command; use sha2::{Digest, Sha256}; use thiserror::Error; +use crate::platform; + /// Vault belonging to the retired `stayturgid` `_secretspec` wrapper. /// /// Adoptable, because a host that has only ever run the wrapper still keeps its @@ -24,15 +26,16 @@ const LEGACY_VAULT: &str = "/var/db/stayturgid-secrets"; const LEGACY_USER: &str = "_secretspec"; const LEGACY_GROUP: &str = "staff"; -pub(crate) const PREFIX: &str = "/usr/local"; -const CONFIG_PATH: &str = "/usr/local/etc/sudo-secretspec.toml"; -const SUDOERS_PATH: &str = "/private/etc/sudoers.d/sudo-secretspec"; +pub(crate) const PREFIX: &str = platform::PREFIX; +const CONFIG_PATH: &str = platform::CONFIG_PATH; +const SUDOERS_PATH: &str = platform::SUDOERS_FILE; /// Any file installed under here is a sudo policy and must be validated before /// it is allowed to take effect. -pub(crate) const SUDOERS_DIR: &str = "/private/etc/sudoers.d"; -const DEFAULT_VAULT: &str = "/var/db/sudo-secretspec"; -const DEFAULT_USER: &str = "_sudo_secretspec"; -const DEFAULT_GROUP: &str = "_sudo_secretspec"; +pub(crate) const SUDOERS_DIR: &str = platform::SUDOERS_DIR; +const SUDOERS_SECURE_PATH: &str = platform::SUDOERS_SECURE_PATH; +const DEFAULT_VAULT: &str = platform::DEFAULT_VAULT; +const DEFAULT_USER: &str = platform::DEFAULT_USER; +const DEFAULT_GROUP: &str = platform::DEFAULT_GROUP; /// Manifest profile assumed when the operator does not name one. const DEFAULT_PROFILE: &str = "default"; /// Directory-name prefix for rollback snapshots under `/libexec`. @@ -805,6 +808,43 @@ fn version_transition(previous: Option<&str>) -> String { } } +/// The mediated broker verbs granted NOPASSWD with a `--*` argument glob. +/// +/// `source-restore-force` and `source-destroy` are deliberately absent: with no +/// line they fall through to the operator's ordinary password-prompted sudo, +/// which is what makes them "authenticated" operations (see `main.rs`'s +/// `lifecycle_restore` and `lifecycle_destroy`). `audit-verify` is not here +/// either — it is granted below without the glob, since it takes no `--*` +/// argument. +pub const BROKER_VERBS: &[&str] = &[ + "source-add", + "source-set", + "source-delete", + "source-undeclare", + "source-get", + "source-check", + "source-export", + "source-template-check", + "source-schema", + "source-restore", +]; + +/// The operator's NOPASSWD grant lines for the mediated broker operations, for +/// one broker path. `audit-verify` is appended without a glob: it takes no +/// argument and is a read-only integrity check, not a credential operation. +fn operator_grant_lines(operator: &str, service_user: &str, broker: &str) -> String { + let mut lines = String::new(); + for verb in BROKER_VERBS { + lines.push_str(&format!( + "{operator} ALL=({service_user}) NOPASSWD: {broker} __broker {verb} --*\n" + )); + } + lines.push_str(&format!( + "{operator} ALL=({service_user}) NOPASSWD: {broker} __broker audit-verify\n" + )); + lines +} + /// Sudoers policy for the operator. /// /// The grant is deliberately per-subcommand. A blanket `sudo-secretspec *` @@ -855,28 +895,88 @@ fn version_transition(previous: Option<&str>) -> String { /// sudoers — from the single-name, forward-safe restore the NOPASSWD grant /// exists for. See `main.rs`'s `lifecycle_restore`. pub fn sudoers_text(operator: &str, service_user: &str) -> String { + let broker = format!("{PREFIX}/libexec/sudo-secretspec"); format!( - "Defaults!{prefix}/libexec/sudo-secretspec env_reset,env_keep-=\"HOME\",secure_path=/usr/bin:/bin:/usr/sbin:/sbin,umask=0077,always_set_home\n\ - Defaults!{prefix}/bin/sudo-secretspec timestamp_timeout=0\n\ - {operator} ALL=({service_user}) NOPASSWD: {prefix}/libexec/sudo-secretspec __broker source-add --*\n\ - {operator} ALL=({service_user}) NOPASSWD: {prefix}/libexec/sudo-secretspec __broker source-set --*\n\ - {operator} ALL=({service_user}) NOPASSWD: {prefix}/libexec/sudo-secretspec __broker source-delete --*\n\ - {operator} ALL=({service_user}) NOPASSWD: {prefix}/libexec/sudo-secretspec __broker source-undeclare --*\n\ - {operator} ALL=({service_user}) NOPASSWD: {prefix}/libexec/sudo-secretspec __broker source-get --*\n\ - {operator} ALL=({service_user}) NOPASSWD: {prefix}/libexec/sudo-secretspec __broker source-check --*\n\ - {operator} ALL=({service_user}) NOPASSWD: {prefix}/libexec/sudo-secretspec __broker source-export --*\n\ - {operator} ALL=({service_user}) NOPASSWD: {prefix}/libexec/sudo-secretspec __broker source-template-check --*\n\ - {operator} ALL=({service_user}) NOPASSWD: {prefix}/libexec/sudo-secretspec __broker source-schema --*\n\ - {operator} ALL=({service_user}) NOPASSWD: {prefix}/libexec/sudo-secretspec __broker audit-verify\n\ - {operator} ALL=({service_user}) NOPASSWD: {prefix}/libexec/sudo-secretspec __broker source-restore --*\n\ - {operator} ALL=(root) NOPASSWD: {prefix}/libexec/sudo-secretspec doctor\n\ - {operator} ALL=(root) NOPASSWD: {prefix}/libexec/sudo-secretspec doctor *\n", - prefix = PREFIX, + "Defaults!{broker} env_reset,env_keep-=\"HOME\",secure_path={secure_path},umask=0077,always_set_home\n\ + Defaults!{PREFIX}/bin/sudo-secretspec timestamp_timeout=0\n\ + {grants}\ + {operator} ALL=(root) NOPASSWD: {broker} doctor\n\ + {operator} ALL=(root) NOPASSWD: {broker} doctor *\n", + secure_path = SUDOERS_SECURE_PATH, + grants = operator_grant_lines(operator, service_user, &broker), operator = operator, - service_user = service_user, ) } +/// Sudoers policy for the declared (Linux/NixOS) boundary. +/// +/// The broker is [`platform::BROKER_PATH`], the store path baked in at compile +/// time by the flake's package. There is no public client path on Linux — no +/// `/usr/local/bin/sudo-secretspec` and no Touch ID — so the +/// `timestamp_timeout=0` client line and the `doctor` grants (a macOS-only +/// diagnostic) have nothing to attach to and are omitted. `doctor` refuses on +/// Linux anyway (`platform::lifecycle_refusal`), so granting it would name a +/// command that cannot run. +/// +/// Printed by the hidden `print-sudoers` subcommand and embedded by the NixOS +/// module via import-from-derivation, so the module's sudoers text and the +/// binary's own view of the broker path can never drift apart. +/// Whether a name is acceptable as the grantee of a Linux NOPASSWD sudoers +/// line (the operator) or as the service user the broker runs as. +/// +/// Same grammar as `config.rs::valid_service_identity` on Linux (a-z/`_` first, +/// then a-z/0-9/`_`/`-`, at most 31 chars), plus the sudoers principal cases +/// that helper does not cover: `ALL` is a sudoers keyword that grants every +/// account, and `root` is the superuser — neither may name the grantee of a +/// NOPASSWD line. The operator and service user are formatted verbatim into the +/// sudoers text (`operator_grant_lines`), so a config author who writes a group +/// (`%wheel`), a uid (`#1000`), a comma list, or a newline-injected rule would +/// emit a policy that `visudo -c` happily accepts; refuse them here so the IFD +/// build fails instead of silently widening the grant. +fn linux_identity_valid(value: &str) -> bool { + if value == "ALL" || value == "root" || value.is_empty() || value.len() > 31 { + return false; + } + value.bytes().enumerate().all(|(index, byte)| match byte { + b'a'..=b'z' | b'_' => true, + b'0'..=b'9' | b'-' => index > 0, + _ => false, + }) +} + +pub fn linux_sudoers_text(operator: &str, service_user: &str) -> Result { + if !linux_identity_valid(operator) { + return Err(format!( + "refusing to emit sudoers: operator {operator:?} is not a valid sudoers principal" + )); + } + if !linux_identity_valid(service_user) { + return Err(format!( + "refusing to emit sudoers: service user {service_user:?} is not a valid identity" + )); + } + Ok(format!( + "Defaults!{broker} env_reset,env_keep-=\"HOME\",secure_path={secure_path},umask=0077,always_set_home\n\ + {grants}", + broker = platform::BROKER_PATH, + secure_path = SUDOERS_SECURE_PATH, + grants = operator_grant_lines(operator, service_user, platform::BROKER_PATH), + )) +} + +/// The sudoers policy for the platform this binary was compiled for. +/// +/// The macOS installer (`install`) calls [`sudoers_text`]; the NixOS module and +/// the hidden `print-sudoers` subcommand call this so one function is the single +/// source of truth per platform. +pub fn sudoers_text_for_platform(operator: &str, service_user: &str) -> Result { + if platform::IS_MACOS { + Ok(sudoers_text(operator, service_user)) + } else { + linux_sudoers_text(operator, service_user) + } +} + /// Run the installer. Returns Ok(()) on success. pub fn run(req: InstallRequest) -> Result<(), InstallError> { require_root()?; @@ -1527,6 +1627,74 @@ mod tests { ); } + #[test] + fn linux_policy_grants_broker_verbs_only() { + // The declared boundary has no public client path (no Touch ID, no + // imperative installer), so the Linux text omits the `timestamp_timeout=0` + // client line and the macOS-only `doctor` grants, and grants exactly the + // mediated broker verbs plus the read-only `audit-verify`. The force and + // destroy verbs stay un-granted for the same reason as on macOS. + let text = linux_sudoers_text("dann", "sudo-secretspec").unwrap(); + for verb in BROKER_VERBS { + assert!( + text.contains(&format!( + "NOPASSWD: {} __broker {verb} --*\n", + platform::BROKER_PATH + )), + "missing grant for {verb}:\n{text}" + ); + } + assert!( + text.contains(&format!( + "NOPASSWD: {} __broker audit-verify\n", + platform::BROKER_PATH + )), + "audit-verify must keep its NOPASSWD grant:\n{text}" + ); + assert!( + !text.contains("timestamp_timeout=0"), + "Linux has no client path to attach timestamp_timeout=0 to:\n{text}" + ); + assert!( + !text.contains(" doctor"), + "doctor is a macOS-only diagnostic and must have no Linux grant:\n{text}" + ); + for absent in ["source-restore-force", "source-destroy"] { + assert!( + !text.contains(absent), + "{absent} must have no Linux grant:\n{text}" + ); + } + } + + #[test] + fn linux_sudoers_text_refuses_non_principal_identities() { + // M1: the operator and service user reach the sudoers text verbatim, so + // a config author who writes `ALL`, `root`, a group, a uid, or an + // injected rule would emit a policy that `visudo -c` happily accepts. + // Refuse anything that is not a single plain principal. + for bad in [ + "ALL", + "root", + "%wheel", + "dann, nginx", + "#1000", + "dann ALL=(ALL) NOPASSWD: ALL\ndann", + "Dann", + "-dann", + ] { + assert!( + linux_sudoers_text(bad, "sudo-secretspec").is_err(), + "operator {bad:?} must be refused" + ); + } + assert!( + linux_sudoers_text("dann", "ALL").is_err(), + "service user ALL must be refused" + ); + assert!(linux_sudoers_text("dann", "sudo-secretspec").is_ok()); + } + #[test] fn installing_from_the_installed_tree_itself_is_refused() { // The exact incident: the installed client infers `source_root` from diff --git a/sudo-secretspec-cli/src/lib.rs b/sudo-secretspec-cli/src/lib.rs index 07e2210db..3c52d7284 100644 --- a/sudo-secretspec-cli/src/lib.rs +++ b/sudo-secretspec-cli/src/lib.rs @@ -4,10 +4,11 @@ pub mod config; pub mod drift; pub mod history; pub mod install; +pub mod platform; pub mod rollback; pub mod uninstall; pub use drift::{ - AvailableBuild, Finding, InspectOptions, Layout, Report, inspect, load_config, media_candidates, - uid_for_user, + AvailableBuild, Finding, InspectOptions, Layout, Report, inspect, load_config, + media_candidates, uid_for_user, }; diff --git a/sudo-secretspec-cli/src/main.rs b/sudo-secretspec-cli/src/main.rs index c70655160..1b8ffcdd3 100644 --- a/sudo-secretspec-cli/src/main.rs +++ b/sudo-secretspec-cli/src/main.rs @@ -6,18 +6,10 @@ use std::process::Command; use clap::{Parser, Subcommand}; -/// Absolute path to sudo. Never resolve this through `PATH`: the caller -/// controls the environment, and a planted `sudo` earlier in `PATH` would -/// silently satisfy every broker call with forged values and no audit event. -const SUDO: &str = "/usr/bin/sudo"; - -/// Installed path of the privileged broker. The sudoers policy grants -/// NOPASSWD execution of this path, so when the running binary *is* this -/// path it may only serve the operations that policy is meant to expose. -const BROKER_PATH: &str = "/usr/local/libexec/sudo-secretspec"; - -/// Installed protected configuration, written by `install`. -const CONFIG_PATH: &str = "/usr/local/etc/sudo-secretspec.toml"; +// Absolute paths for `sudo`, the privileged broker and the protected config. +// They come from `platform` (per-OS defaults, compile-time overrides) and are +// never resolved through `PATH` or the caller's environment. +use sudo_secretspec_cli::platform::{self, BROKER_PATH, CONFIG_PATH, SUDO}; #[derive(Debug, Parser)] #[command( @@ -228,6 +220,21 @@ enum Cmd { #[arg(trailing_var_arg = true, allow_hyphen_values = true)] args: Vec, }, + /// Print the sudoers policy for this platform's boundary. + /// + /// Consumed by the NixOS module (import-from-derivation) so the module's + /// sudoers text and the compiled-in broker path cannot drift. Runs as the + /// public client, never through the broker, so it is outside the privileged + /// allowlist. Reads nothing, writes only stdout. + #[command(hide = true, name = "print-sudoers")] + PrintSudoers { + /// Operator granted the NOPASSWD broker rules. + #[arg(long)] + operator: String, + /// Service user the broker runs as. + #[arg(long)] + service_user: String, + }, } /// True when this process is the installed privileged broker, i.e. it was @@ -266,8 +273,9 @@ fn main() { { eprintln!( "sudo-secretspec: the privileged broker path serves only __broker and doctor;\n\ - run install/rollback through /usr/local/bin/sudo-secretspec so they require\n\ - interactive authentication" + run install/rollback through {} so they require\n\ + interactive authentication", + platform::CLIENT_PATH ); std::process::exit(2); } @@ -347,6 +355,7 @@ fn main() { ), Cmd::AuditVerify => audit_verify(), Cmd::Rollback { snapshot } => { + require_imperative_installer("rollback"); if unsafe { libc::geteuid() } != 0 { let status = Command::new(SUDO) .arg(self_exe()) @@ -372,6 +381,29 @@ fn main() { std::process::exit(code); } } + Cmd::PrintSudoers { + operator, + service_user, + } => { + match sudo_secretspec_cli::install::sudoers_text_for_platform(&operator, &service_user) + { + Ok(text) => print!("{text}"), + Err(message) => { + eprintln!("sudo-secretspec: {message}"); + std::process::exit(2); + } + } + } + } +} + +/// Boundary lifecycle (`install`, `uninstall`, `rollback`) and `doctor`'s +/// layout checks describe the macOS/Homebrew install. Anywhere else they +/// refuse, and say where the boundary is managed instead. +fn require_imperative_installer(command: &str) { + if let Some(message) = platform::lifecycle_refusal(command) { + eprintln!("sudo-secretspec: {message}"); + std::process::exit(2); } } @@ -504,6 +536,7 @@ fn run_install( profile: Option, non_interactive: bool, ) { + require_imperative_installer("install"); // Before anything else, and before elevating: an install that would copy // the installed boundary onto itself is refused here rather than after the // operator has authenticated. `install::run` repeats this check as root and @@ -645,6 +678,7 @@ fn run_uninstall( config: Option, non_interactive: bool, ) { + require_imperative_installer("uninstall"); // Confirm here, while still unprivileged and still attached to the // operator's terminal. The elevated re-exec below passes // `--non-interactive`, so this is the only place a prompt can happen — @@ -751,7 +785,7 @@ fn get_service_user() -> String { } else { // Fallback to the default if config is missing or unparseable. // It shouldn't get here because we only call this when installed. - "_sudo_secretspec".to_string() + platform::DEFAULT_USER.to_string() } } @@ -1067,6 +1101,7 @@ fn doctor( caller_path: Option, available_build: Option, ) { + require_imperative_installer("doctor"); // `sudo` replaces PATH with the policy's secure_path, so the shadow check // has to be told what the caller's PATH was before elevating. Trust the // ambient value only while still unprivileged. @@ -1079,10 +1114,7 @@ fn doctor( // NOPASSWD root `doctor` echoed an arbitrary file's contents. if !unprivileged { if let Some(cfg) = &config { - let is_default = match ( - Path::new(CONFIG_PATH).canonicalize(), - cfg.canonicalize(), - ) { + let is_default = match (Path::new(CONFIG_PATH).canonicalize(), cfg.canonicalize()) { (Ok(installed), Ok(given)) => installed == given, _ => false, }; diff --git a/sudo-secretspec-cli/src/platform.rs b/sudo-secretspec-cli/src/platform.rs new file mode 100644 index 000000000..64eaea734 --- /dev/null +++ b/sudo-secretspec-cli/src/platform.rs @@ -0,0 +1,163 @@ +//! Per-platform install layout and service-identity rules. +//! +//! Every path the boundary trusts lives here, in one place, so a reviewer can +//! read the whole platform surface at once. The defaults are chosen by +//! `target_os`; three of them can be replaced **at compile time** through an +//! environment variable read by `option_env!`: +//! +//! | variable | replaces | +//! |-----------------------------------|-----------------| +//! | `SUDO_SECRETSPEC_SUDO` | [`SUDO`] | +//! | `SUDO_SECRETSPEC_BROKER_PATH` | [`BROKER_PATH`] | +//! | `SUDO_SECRETSPEC_CONFIG_PATH` | [`CONFIG_PATH`] | +//! +//! Compile time, not run time, on purpose. These paths decide which binary the +//! public client hands to `sudo` and which file the root-adjacent broker +//! believes is its configuration; letting the *caller's* environment choose +//! either would hand the unprivileged side control of the boundary. A packager +//! (the NixOS flake does this) bakes them into the binary instead. +//! +//! The other constants are deliberately not overridable. The vault location is +//! validated against [`VAULT_PARENT`] by `config.rs`, so changing one without +//! the other would silently loosen that check; the install prefix, sudoers +//! directory and service identity only matter to the macOS installer, which +//! does not run anywhere else. +//! +//! macOS values are byte-identical to what `main.rs`, `broker.rs`, `install.rs` +//! and `drift.rs` hard-coded before this module existed. + +#[cfg(not(any(target_os = "macos", target_os = "linux")))] +compile_error!("sudo-secretspec-cli supports only macOS and Linux"); + +/// Reject an override that is not an absolute path, at compile time. +/// +/// A relative `SUDO` would be resolved through the caller's `PATH` at run time, +/// which is exactly what the absolute default exists to prevent. +const fn pick(override_value: Option<&'static str>, default: &'static str) -> &'static str { + match override_value { + Some(value) => { + let bytes = value.as_bytes(); + assert!( + !bytes.is_empty() && bytes[0] == b'/', + "SUDO_SECRETSPEC_* path overrides must be absolute" + ); + value + } + None => default, + } +} + +// --------------------------------------------------------------------------- +// macOS +// --------------------------------------------------------------------------- + +#[cfg(target_os = "macos")] +mod os { + pub const SUDO: &str = "/usr/bin/sudo"; + pub const PREFIX: &str = "/usr/local"; + pub const BROKER_PATH: &str = "/usr/local/libexec/sudo-secretspec"; + pub const CONFIG_PATH: &str = "/usr/local/etc/sudo-secretspec.toml"; + pub const SUDOERS_DIR: &str = "/private/etc/sudoers.d"; + pub const SUDOERS_FILE: &str = "/private/etc/sudoers.d/sudo-secretspec"; + /// `secure_path` for the broker's `Defaults!` line, so `sudo` cannot hand + /// the privileged process a caller-chosen `PATH`. + pub const SUDOERS_SECURE_PATH: &str = "/usr/bin:/bin:/usr/sbin:/sbin"; + pub const DEFAULT_VAULT: &str = "/var/db/sudo-secretspec"; + pub const VAULT_PARENT: &str = "/var/db"; + pub const VAULT_REAL_PARENT: &str = "/private/var/db"; + pub const DEFAULT_USER: &str = "_sudo_secretspec"; + pub const DEFAULT_GROUP: &str = "_sudo_secretspec"; + /// Where the installed public client lives, for operator-facing messages. + pub const CLIENT_PATH: &str = "/usr/local/bin/sudo-secretspec"; + /// macOS service accounts conventionally start with `_`. + pub const SERVICE_USER_REQUIRES_UNDERSCORE: bool = true; + pub const SERVICE_IDENTITY_ALLOWS_HYPHEN: bool = false; +} + +// --------------------------------------------------------------------------- +// Linux +// --------------------------------------------------------------------------- + +#[cfg(target_os = "linux")] +mod os { + pub const SUDO: &str = "/usr/bin/sudo"; + pub const PREFIX: &str = "/usr"; + pub const BROKER_PATH: &str = "/usr/libexec/sudo-secretspec"; + pub const CONFIG_PATH: &str = "/etc/sudo-secretspec.toml"; + pub const SUDOERS_DIR: &str = "/etc/sudoers.d"; + pub const SUDOERS_FILE: &str = "/etc/sudoers.d/sudo-secretspec"; + /// NixOS `secure_path`: the setuid `sudo` wrapper and the current system + /// profile. There is no `/usr/bin` on NixOS. + pub const SUDOERS_SECURE_PATH: &str = "/run/current-system/sw/bin:/run/wrappers/bin"; + pub const DEFAULT_VAULT: &str = "/var/lib/sudo-secretspec"; + pub const VAULT_PARENT: &str = "/var/lib"; + /// `/var/lib` is a real directory on Linux; there is no `/private` chain. + pub const VAULT_REAL_PARENT: &str = "/var/lib"; + pub const DEFAULT_USER: &str = "sudo-secretspec"; + pub const DEFAULT_GROUP: &str = "sudo-secretspec"; + /// The public client on NixOS lives in the current system profile; there is + /// no `/usr/bin`. + pub const CLIENT_PATH: &str = "/run/current-system/sw/bin/sudo-secretspec"; + /// Linux has no leading-underscore convention for service accounts. + pub const SERVICE_USER_REQUIRES_UNDERSCORE: bool = false; + pub const SERVICE_IDENTITY_ALLOWS_HYPHEN: bool = true; +} + +/// Absolute path to `sudo`; never resolved through `PATH`. +pub const SUDO: &str = pick(option_env!("SUDO_SECRETSPEC_SUDO"), os::SUDO); + +/// Installed path of the privileged broker. The sudoers policy grants NOPASSWD +/// execution of this path. +pub const BROKER_PATH: &str = pick(option_env!("SUDO_SECRETSPEC_BROKER_PATH"), os::BROKER_PATH); + +/// Installed protected configuration. +pub const CONFIG_PATH: &str = pick(option_env!("SUDO_SECRETSPEC_CONFIG_PATH"), os::CONFIG_PATH); + +pub const PREFIX: &str = os::PREFIX; +pub const SUDOERS_DIR: &str = os::SUDOERS_DIR; +pub const SUDOERS_FILE: &str = os::SUDOERS_FILE; +pub const SUDOERS_SECURE_PATH: &str = os::SUDOERS_SECURE_PATH; +pub const DEFAULT_VAULT: &str = os::DEFAULT_VAULT; +pub const VAULT_PARENT: &str = os::VAULT_PARENT; +pub const VAULT_REAL_PARENT: &str = os::VAULT_REAL_PARENT; +pub const DEFAULT_USER: &str = os::DEFAULT_USER; +pub const DEFAULT_GROUP: &str = os::DEFAULT_GROUP; +pub const CLIENT_PATH: &str = os::CLIENT_PATH; +pub const SERVICE_USER_REQUIRES_UNDERSCORE: bool = os::SERVICE_USER_REQUIRES_UNDERSCORE; +pub const SERVICE_IDENTITY_ALLOWS_HYPHEN: bool = os::SERVICE_IDENTITY_ALLOWS_HYPHEN; + +/// True where the imperative installer (`install`, `uninstall`, `rollback`) and +/// the macOS-shaped `doctor` layout checks are supported. +pub const IS_MACOS: bool = cfg!(target_os = "macos"); + +/// Refusal text for a boundary-lifecycle command on a platform that has no +/// imperative installer. `None` on macOS. +/// +/// Linux boundaries are declared, not installed: the NixOS module owns the +/// service account, the broker path, the vault directory, the config file and +/// the sudoers policy, and a rebuild is how any of them change. +#[must_use] +pub fn lifecycle_refusal(command: &str) -> Option { + if IS_MACOS { + return None; + } + Some(format!( + "`{command}` is not supported on this platform: the privilege boundary is managed \ + declaratively by the NixOS module (`nixosModules.default` of the sudo-secretspec \ + flake, option `services.sudo-secretspec`), not by an imperative installer. Change \ + the boundary by editing your NixOS configuration and rebuilding." + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn vault_lives_directly_under_its_parent() { + assert_eq!( + std::path::Path::new(DEFAULT_VAULT).parent(), + Some(std::path::Path::new(VAULT_PARENT)) + ); + } +} diff --git a/sudo-secretspec-cli/src/rollback.rs b/sudo-secretspec-cli/src/rollback.rs index 055741080..ec5ea9a6d 100644 --- a/sudo-secretspec-cli/src/rollback.rs +++ b/sudo-secretspec-cli/src/rollback.rs @@ -48,7 +48,10 @@ pub fn run(snapshot: &Path) -> Result<(), RollbackError> { require_root()?; let snapshot = fs::canonicalize(snapshot) .map_err(|e| RollbackError::Denied(format!("invalid snapshot path: {e}")))?; - let prefix = PathBuf::from("/usr/local/libexec/sudo-secretspec-rollback-"); + let prefix = PathBuf::from(format!( + "{}/libexec/sudo-secretspec-rollback-", + crate::install::PREFIX + )); if !snapshot .to_string_lossy() .starts_with(prefix.to_string_lossy().as_ref())