aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-12-01 01:59:16 +0000
committertv <tv@krebsco.de>2026-12-01 01:59:16 +0000
commit2af90fd35ea8a0aafb9156653f5b28cbac4e1677 (patch)
treec2eceb7e2dae9625bb4e5a994e13151e11fd44d4 /src
parent5804d2b952ebead3d9bc238fc8db20af6563fddc (diff)
enstate: validators and renderers in a sandboxHEADmaster
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.
Diffstat (limited to 'src')
-rw-r--r--src/main.rs20
-rw-r--r--src/migrate.rs2
-rw-r--r--src/plan.rs4
-rw-r--r--src/program.rs63
-rw-r--r--src/store.rs18
-rw-r--r--src/view.rs8
6 files changed, 100 insertions, 15 deletions
diff --git a/src/main.rs b/src/main.rs
index 9133cb3..2df4c78 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -41,6 +41,13 @@ const OPTIONS: &[OptionSpec] = &[
"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,
"UNIT",
@@ -76,6 +83,7 @@ struct Settings {
schema: Option<PathBuf>,
systemctl: Option<PathBuf>,
unit: Option<String>,
+ sandbox: Option<String>,
}
const COMMANDS: &[(&str, &str)] = &[
@@ -253,7 +261,12 @@ fn run() -> Result<ExitCode> {
.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<P
Role::Validator,
&validator.name,
&given,
- &store.scratch(),
+ &store.runner(),
) {
Ok(outcome) => outcome,
Err(error) => match error.downcast::<ProgramFailed>() {
@@ -353,7 +353,7 @@ pub fn plan(schema: &Schema, store: &Store, submission: &Submission) -> Result<P
entries.insert(channel, &candidate);
for (name, view_spec) in schema.views_of(Some(channel)) {
let secret = schema.view_is_secret(view_spec);
- let rendered = match view::render(schema, name, view_spec, &entries, &store.scratch()) {
+ let rendered = match view::render(schema, name, view_spec, &entries, &store.runner()) {
Ok(rendered) => rendered,
Err(error) => match error.downcast::<ProgramFailed>() {
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<PathBuf>,
+}
+
+/// 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<Outcome> {
+ 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<BTreeMap<PathBuf, Vec<u8>>> {
}
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<String, (String, Vec<u8>)>;
pub struct Store {
pub state: PathBuf,
pub run: PathBuf,
+ /// bubblewrap, for running programs in a sandbox (`program::Runner`).
+ pub sandbox: Option<PathBuf>,
}
#[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<PathBuf>) -> 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<Option<Scratch>> {
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())?;