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. --- src/main.rs | 20 ++++++++++++++++++- src/migrate.rs | 2 +- src/plan.rs | 4 ++-- src/program.rs | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++------- src/store.rs | 18 +++++++++++++++++ src/view.rs | 8 ++++---- 6 files changed, 100 insertions(+), 15 deletions(-) (limited to 'src') 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())?; -- cgit v1.3.1