From 2af90fd35ea8a0aafb9156653f5b28cbac4e1677 Mon Sep 17 00:00:00 2001 From: tv Date: Tue, 1 Dec 2026 01:59:16 +0000 Subject: enstate: validators and renderers in a sandbox By bubblewrap: everything read-only but OUT (and IN bound again after a fresh /tmp), a new /dev and /proc, namespaces of their own (no network), no capabilities, a new session, gone with the receptor. The setting sandbox is bwrap (found in the receptor's PATH, as the programs' environment is empty), or none; the module sets its bubblewrap. The tests run their programs in it where bubblewrap can make one (not in Nix's build sandbox), and a test checks that a program can't write outside OUT, nor into IN, and has no network nor environment. --- README.md | 5 ++- nix/module.nix | 2 + share/bash-completion/completions/enstate | 17 +++++---- src/main.rs | 20 +++++++++- src/migrate.rs | 2 +- src/plan.rs | 4 +- src/program.rs | 63 +++++++++++++++++++++++++++---- src/store.rs | 18 +++++++++ src/view.rs | 8 ++-- tests/common/mod.rs | 25 +++++++++++- tests/receptor.rs | 49 ++++++++++++++++++++++++ 11 files changed, 188 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 241ad31..568d842 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,10 @@ Bash completion is [share/bash-completion/completions/enstate](share/bash-completion/completions/enstate), which the package installs. -Not yet: converters, derived slots and steps; a sandbox for programs. +Validators and renderers run in a sandbox, by bubblewrap (the setting +`sandbox`, `none` for none). + +Not yet: converters, derived slots and steps. ```sh cargo build diff --git a/nix/module.nix b/nix/module.nix index a273d45..10623d1 100644 --- a/nix/module.nix +++ b/nix/module.nix @@ -144,6 +144,8 @@ let run-dir = cfg.runDir; # Started again by --apply if it failed (for want of the state, at boot). unit = "enstate.service"; + # Validators and renderers run in it. + sandbox = "${pkgs.bubblewrap}/bin/bwrap"; }; enstate = lib.getExe cfg.package; diff --git a/share/bash-completion/completions/enstate b/share/bash-completion/completions/enstate index 2900ba1..b0f827e 100644 --- a/share/bash-completion/completions/enstate +++ b/share/bash-completion/completions/enstate @@ -7,7 +7,7 @@ _enstate() { local commands="--plan --apply --stage --status --materialize --migrate --pack" # the settings, and those each command uses local general="--config --unset --print-config" - local settings="$general --state-dir --run-dir --schema --unit" + local settings="$general --state-dir --run-dir --schema --sandbox --unit" local store="$general --state-dir --run-dir --schema" local i w cmd= path= used=" " # bash splits --option=VALUE into --option, =, VALUE @@ -21,7 +21,7 @@ _enstate() { case $w in --plan | --apply | --stage | --status | --materialize | --migrate | --pack) cmd=${w#--} ;; - --out | --config | --unset | --state-dir | --run-dir | --schema | --unit) + --out | --config | --unset | --state-dir | --run-dir | --schema | --sandbox | --unit) used="$used$w " # its value, written apart or with = if [ "${COMP_WORDS[i+1]}" = = ]; then i=$((i + 2)); else i=$((i + 1)); fi ;; @@ -31,18 +31,19 @@ _enstate() { esac done case $prev in - --config | --schema) COMPREPLY=($(compgen -f -- "$cur")); return ;; + --config | --schema | --sandbox) COMPREPLY=($(compgen -f -- "$cur")); return ;; --state-dir | --run-dir | --out) COMPREPLY=($(compgen -d -- "$cur")); return ;; - --unset) COMPREPLY=($(compgen -W "state-dir run-dir schema unit" -- "$cur")); return ;; + --unset) COMPREPLY=($(compgen -W "state-dir run-dir schema sandbox unit" -- "$cur")); return ;; --unit) COMPREPLY=(); return ;; esac local options case $cmd in "") options="$commands -h --help $settings" ;; - plan | stage) options="--json $store" ;; - apply) options="--json $store --unit" ;; - status | materialize) options="--json $store" ;; - migrate) options="--json --dry-run $store" ;; + plan | stage) options="--json $store --sandbox" ;; + apply) options="--json $store --sandbox --unit" ;; + status) options="--json $store" ;; + materialize) options="--json $store --sandbox" ;; + migrate) options="--json --dry-run $store --sandbox" ;; pack) options="--out $general --schema" ;; esac local o candidates= diff --git a/src/main.rs b/src/main.rs index 9133cb3..2df4c78 100644 --- a/src/main.rs +++ b/src/main.rs @@ -40,6 +40,13 @@ const OPTIONS: &[OptionSpec] = &[ Some("/etc/enstate/schema.json"), "The schema of the running generation; for --pack, one to check the source list against", ), + option( + "sandbox", + Kind::Text, + "PATH", + Some("bwrap"), + "bubblewrap, to run validators and renderers in a sandbox; none runs them without one", + ), option( "unit", Kind::Text, @@ -76,6 +83,7 @@ struct Settings { schema: Option, systemctl: Option, unit: Option, + sandbox: Option, } const COMMANDS: &[(&str, &str)] = &[ @@ -253,7 +261,12 @@ fn run() -> Result { .run_dir .as_deref() .unwrap_or(Path::new("/run/enstate")), - ); + ) + .with_sandbox(match settings.sandbox.as_deref() { + Some("none") => None, + Some(bwrap) => Some(PathBuf::from(bwrap)), + None => Some(PathBuf::from("bwrap")), + }); let schema_path = settings .schema .unwrap_or_else(|| PathBuf::from("/etc/enstate/schema.json")); @@ -641,6 +654,11 @@ fn uses(command: &str, setting: &str) -> bool { // Reactions run. "systemctl" => matches!(command, "apply" | "migrate"), "unit" => command == "apply", + // Programs run. + "sandbox" => matches!( + command, + "plan" | "apply" | "stage" | "materialize" | "migrate" + ), _ => true, } } diff --git a/src/migrate.rs b/src/migrate.rs index ca1e6b5..5b97d27 100644 --- a/src/migrate.rs +++ b/src/migrate.rs @@ -205,7 +205,7 @@ pub fn put_views( let mut outcomes = Vec::new(); for (name, view_spec) in schema.views_of(None) { let secret = schema.view_is_secret(view_spec); - let rendered = view::render(schema, name, view_spec, &entries, &store.scratch()) + let rendered = view::render(schema, name, view_spec, &entries, &store.runner()) .with_context(|| format!("view {name}"))?; let installed = store.installed_view(name); let (change, files) = view::compare( diff --git a/src/plan.rs b/src/plan.rs index 12c91b6..495d67c 100644 --- a/src/plan.rs +++ b/src/plan.rs @@ -278,7 +278,7 @@ pub fn plan(schema: &Schema, store: &Store, submission: &Submission) -> Result

outcome, Err(error) => match error.downcast::() { @@ -353,7 +353,7 @@ pub fn plan(schema: &Schema, store: &Store, submission: &Submission) -> Result

rendered, Err(error) => match error.downcast::() { Ok(failed) => { diff --git a/src/program.rs b/src/program.rs index 8c4a565..ca3575c 100644 --- a/src/program.rs +++ b/src/program.rs @@ -5,8 +5,9 @@ //! empty. Objections are JSON lines on standard output; an exit status but 0 is a //! failure. //! -//! `IN` is read-only (for its owner, as root ignores modes). Not yet: a sandbox (no -//! network, nothing writable but `OUT`). +//! In a sandbox (`Runner`), by bubblewrap: everything read-only but `OUT`, no network, +//! namespaces of its own, no capabilities. `IN` is read-only (for its owner) also +//! without. use std::collections::BTreeMap; use std::path::{Path, PathBuf}; @@ -68,15 +69,26 @@ pub struct Outcome { pub out: Scratch, } -/// Runs `program` as `role`, named `name` (a view's or validator's), on `given`, in a -/// scratch directory below `scratch`. +/// Where and how programs run: their scratch directories, and the sandbox. +#[derive(Debug, Clone)] +pub struct Runner { + pub scratch: PathBuf, + /// bubblewrap (`bwrap`), to run programs in a sandbox: everything read-only but + /// `OUT`, no network, namespaces of their own, no capabilities. None runs them as + /// they are. + pub sandbox: Option, +} + +/// Runs `program` as `role`, named `name` (a view's or validator's), on `given`, by +/// `runner`. pub fn run( program: &Path, role: Role, name: &str, given: &Given, - scratch: &Path, + runner: &Runner, ) -> Result { + let scratch = runner.scratch.as_path(); let what = format!("{} {name} ({})", role_name(role), program.display()); let input = Scratch::new(scratch, "in-")?; let out = Scratch::new(scratch, "out-")?; @@ -105,10 +117,34 @@ pub fn run( } input.set_modes(0o400)?; let program = std::path::absolute(program).unwrap_or_else(|_| program.to_owned()); - let output = Command::new(&program) + let mut command = match &runner.sandbox { + None => { + let mut command = Command::new(&program); + command.current_dir(input.path()); + command + } + Some(bwrap) => { + // By name, from our PATH: the command's environment is empty. + let mut command = Command::new(in_path(bwrap)); + command + .args(["--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc"]) + .args(["--tmpfs", "/tmp"]) + // After /tmp, in case they are below it. + .arg("--ro-bind") + .args([input.path(), input.path()]) + .arg("--bind") + .args([out.path(), out.path()]) + .args(["--unshare-all", "--die-with-parent", "--new-session"]) + .args(["--cap-drop", "ALL", "--chdir"]) + .arg(input.path()) + .arg("--") + .arg(&program); + command + } + }; + let output = command .arg(input.path()) .arg(out.path()) - .current_dir(input.path()) .env_clear() .stdin(Stdio::null()) .output() @@ -199,3 +235,16 @@ pub fn files_below(dir: &Path) -> Result>> { } Ok(files) } + +/// `program`, if it is a name without a directory, as found in `PATH`; else as it is. +fn in_path(program: &Path) -> PathBuf { + if program.components().count() != 1 { + return program.to_owned(); + } + std::env::var_os("PATH") + .iter() + .flat_map(std::env::split_paths) + .map(|dir| dir.join(program)) + .find(|path| path.is_file()) + .unwrap_or_else(|| program.to_owned()) +} diff --git a/src/store.rs b/src/store.rs index 9de62d3..c6d4d6c 100644 --- a/src/store.rs +++ b/src/store.rs @@ -35,6 +35,8 @@ pub type Kept = std::collections::BTreeMap)>; pub struct Store { pub state: PathBuf, pub run: PathBuf, + /// bubblewrap, for running programs in a sandbox (`program::Runner`). + pub sandbox: Option, } #[derive(Debug, Clone)] @@ -71,6 +73,7 @@ impl Store { Self { state: absolute(state), run: absolute(run), + sandbox: None, } } @@ -98,6 +101,20 @@ impl Store { self.run.join("tmp") } + /// How programs run: their scratch directories, and the sandbox. + pub fn runner(&self) -> crate::program::Runner { + crate::program::Runner { + scratch: self.scratch(), + sandbox: self.sandbox.clone(), + } + } + + /// The store, its programs run in a sandbox by `bwrap` (bubblewrap), or not. + pub fn with_sandbox(mut self, bwrap: Option) -> Self { + self.sandbox = bwrap; + self + } + fn channel_dir(&self, channel: &str) -> PathBuf { self.state.join("channels").join(channel) } @@ -261,6 +278,7 @@ impl Store { Ok(Store { state: dir.to_owned(), run: self.run.clone(), + sandbox: self.sandbox.clone(), }) } diff --git a/src/view.rs b/src/view.rs index bd4b8f5..b7ddc35 100644 --- a/src/view.rs +++ b/src/view.rs @@ -17,7 +17,7 @@ use crate::scratch::Scratch; /// would be, the others as they are. pub type Entries<'a> = BTreeMap<&'a str, &'a Content>; -/// Renders the view `name` from `entries` into scratch below `scratch`; nothing if a +/// Renders the view `name` from `entries` into scratch, by `runner`; nothing if a /// required slot it is made from is unfilled, or it is an entry's own and that entry /// isn't there. pub fn render( @@ -25,7 +25,7 @@ pub fn render( name: &str, view: &ViewSpec, entries: &Entries, - scratch: &Path, + runner: &program::Runner, ) -> Result> { let entry = |address: &Address| { entries @@ -45,7 +45,7 @@ pub fn render( let Some(bytes) = entry(address) else { return Ok(None); }; - let out = Scratch::new(scratch, "view-")?; + let out = Scratch::new(&runner.scratch, "view-")?; crate::content::write_file(&out.path().join(&address.slot), bytes, 0o600)?; Ok(Some(out)) } @@ -66,7 +66,7 @@ pub fn render( }) .collect(), }; - let outcome = program::run(renderer, Role::Renderer, name, &given, scratch)?; + let outcome = program::run(renderer, Role::Renderer, name, &given, runner)?; // What it can't render, it fails on; and it may write regular files and // directories only. program::files_below(outcome.out.path())?; diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 3af1c88..6c04191 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -28,7 +28,7 @@ impl Host { } pub fn store(&self) -> Store { - Store::new(&self.root.join("state"), &self.root.join("run")) + Store::new(&self.root.join("state"), &self.root.join("run")).with_sandbox(bwrap()) } /// A shell script, with the tests' PATH (programs get an empty environment). @@ -146,3 +146,26 @@ impl Host { .map(|snapshot| snapshot.id) } } + +/// bubblewrap, if it can make a sandbox here (not in Nix's build sandbox, say): the +/// tests' programs run in it then. +pub fn bwrap() -> Option { + static BWRAP: std::sync::OnceLock> = std::sync::OnceLock::new(); + BWRAP + .get_or_init(|| { + let works = std::process::Command::new("bwrap") + .args([ + "--ro-bind", + "/", + "/", + "--unshare-all", + "--die-with-parent", + "true", + ]) + .stderr(std::process::Stdio::null()) + .status() + .is_ok_and(|status| status.success()); + works.then(|| PathBuf::from("bwrap")) + }) + .clone() +} diff --git a/tests/receptor.rs b/tests/receptor.rs index f8417a3..fb99497 100644 --- a/tests/receptor.rs +++ b/tests/receptor.rs @@ -499,6 +499,10 @@ remove = true fn command_line() { let host = Host::new("cli"); let _ = host.schema(secrets_schema(&host)); + let sandbox = match common::bwrap() { + Some(bwrap) => format!("--sandbox={}", bwrap.display()), + None => "--sandbox=none".to_owned(), + }; let enstate = |arguments: &[&str]| { let output = Command::new(env!("CARGO_BIN_EXE_enstate")) .args(arguments) @@ -513,6 +517,12 @@ fn command_line() { .contains(&"--apply") .then(|| format!("--systemctl={}", host.systemctl().display())), ) + .args( + ["--plan", "--apply", "--stage", "--materialize", "--migrate"] + .iter() + .any(|command| arguments.contains(command)) + .then(|| sandbox.clone()), + ) .output() .unwrap(); ( @@ -588,6 +598,7 @@ fn command_line() { "--state-dir=state", "--run-dir=run", "--schema=schema.json", + &sandbox, ]) .output() .unwrap(); @@ -595,3 +606,41 @@ fn command_line() { assert_eq!(output.status.code(), Some(0), "{stdout}"); assert!(stdout.contains("nothing changes"), "{stdout}"); } + +/// In the sandbox, a program can write only to OUT, has no network but loopback, and +/// an empty environment. +#[test] +fn programs_in_a_sandbox() { + if common::bwrap().is_none() { + eprintln!("bubblewrap can't make a sandbox here: skipped"); + return; + } + let host = Host::new("sandbox"); + let escaped = host.root.join("escaped"); + // An objection for each thing it could do that it shouldn't. + let nosy = host.program( + "nosy", + &format!( + r#"object() {{ printf '{{"address": "secrets/a", "message": "%s"}}\n' "$1"; }} +if touch {escaped} 2>/dev/null; then object "wrote outside OUT"; fi +if touch "$1/x" 2>/dev/null; then object "wrote into IN"; fi +touch "$2/x" || object "couldn't write into OUT" +if [ "$(awk 'NR > 2 {{ print $1 }}' /proc/net/dev)" != "lo:" ]; then object "has a network"; fi +if env | grep -v '^PWD=\|^SHLVL=\|^_=\|^OLDPWD=' | grep -q .; then object "has an environment"; fi"#, + escaped = escaped.display() + ), + ); + let schema = host.schema(json!({ + "schema": 1, + "channels": { "secrets": { "slots": { "a": { "type": "application/octet-stream" } } } }, + "validators": { "nosy": { "slots": ["secrets/a"], "program": nosy } } + })); + let submission = host.submission( + "a", + json!({ "channel": "secrets", "items": [{ "address": "secrets/a", "op": "set" }] }), + &[("secrets/a", b"A")], + ); + let plan = host.plan(&schema.0, &submission); + assert!(plan.accepted, "{plan:?}"); + assert!(!escaped.exists()); +} -- cgit v1.3.1