Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions crates/weaver-sandbox/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,14 @@ thiserror.workspace = true

[dev-dependencies]
anyhow = { workspace = true }
cap-std.workspace = true
libtest-mimic = "0.8"
rstest.workspace = true
rstest-bdd.workspace = true
rstest-bdd-macros.workspace = true
tempfile.workspace = true

[[test]]
name = "sandbox_child_probe"
path = "tests/sandbox_child_probe.rs"
harness = false
14 changes: 9 additions & 5 deletions crates/weaver-sandbox/src/profile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,11 @@ pub enum NetworkPolicy {
///
/// The profile defaults to a restrictive configuration: networking and the
/// environment are disabled, and only standard Linux runtime library roots are
/// whitelisted for read access. Callers must explicitly list the executables
/// and data paths a sandboxed process requires.
/// mounted read-only with executable mappings. Callers must explicitly list
/// the initial executables and data paths a sandboxed process requires.
#[derive(Debug, Clone)]
pub struct SandboxProfile {
runtime_paths: Vec<PathBuf>,
read_only_paths: Vec<PathBuf>,
read_write_paths: Vec<PathBuf>,
executable_paths: Vec<PathBuf>,
Expand All @@ -47,8 +48,8 @@ pub struct SandboxProfile {
}

impl SandboxProfile {
/// Creates a profile with Linux runtime library paths whitelisted for
/// read-only access.
/// Creates a profile with Linux runtime library paths mounted read-only
/// with executable mappings.
///
/// ```
/// use weaver_sandbox::SandboxProfile;
Expand All @@ -61,7 +62,8 @@ impl SandboxProfile {
#[must_use]
pub fn new() -> Self {
Self {
read_only_paths: linux_runtime_roots(),
runtime_paths: linux_runtime_roots(),
read_only_paths: Vec::new(),
read_write_paths: Vec::new(),
executable_paths: Vec::new(),
read_only_paths_canon: OnceCell::new(),
Expand Down Expand Up @@ -125,6 +127,8 @@ impl SandboxProfile {
self.canonicalised_paths(&self.read_only_paths_canon, &self.read_only_paths)
}

pub(crate) fn runtime_paths(&self) -> &[PathBuf] { &self.runtime_paths }

pub(crate) fn read_write_paths_canonicalised(
&self,
) -> Result<&Vec<PathBuf>, crate::SandboxError> {
Expand Down
44 changes: 34 additions & 10 deletions crates/weaver-sandbox/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@

use std::{io, path::PathBuf};

/// Returns standard Linux library paths that should be readable by default.
/// Returns existing Linux runtime roots using their original path spellings.
///
/// Birdcage needs the original spelling of symlinked roots such as `/lib64`
/// when it recreates the dynamic loader's path inside the sandbox.
#[must_use]
pub fn linux_runtime_roots() -> Vec<PathBuf> {
#[cfg(target_os = "linux")]
{
use std::{fs, path::Path};
use std::path::Path;

let candidates = [
"/lib",
Expand All @@ -21,14 +24,9 @@ pub fn linux_runtime_roots() -> Vec<PathBuf> {
];
candidates
.iter()
.filter_map(|path| {
let candidate = Path::new(path);
if candidate.exists() {
fs::canonicalize(candidate).ok()
} else {
None
}
})
.map(Path::new)
.filter(|candidate| candidate.exists())
.map(Path::to_path_buf)
.collect()
}

Expand Down Expand Up @@ -60,3 +58,29 @@ pub fn thread_count() -> io::Result<usize> {
Ok(1)
}
}

#[cfg(test)]
mod tests {
//! Executable runtime defaults retain the paths Birdcage must recreate.

#[cfg(target_os = "linux")]
#[test]
fn linux_runtime_roots_preserve_existing_aliases() {
let roots = super::linux_runtime_roots();
for alias in ["/lib", "/lib64"] {
let path = std::path::Path::new(alias);
if path.exists() && path.is_symlink() {
assert!(
roots.iter().any(|root| root == path),
"runtime root {alias} must retain its original spelling"
);
}
}
}

#[cfg(not(target_os = "linux"))]
#[test]
fn runtime_roots_are_linux_only() {
assert!(super::linux_runtime_roots().is_empty());
}
}
41 changes: 41 additions & 0 deletions crates/weaver-sandbox/src/sandbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,11 @@ impl Sandbox {
let read_write = self.profile.read_write_paths_canonicalised()?;
let executables = self.profile.executable_paths_canonicalised()?;

// Keep original aliases: Birdcage recreates paths such as `/lib64`
// inside the sandbox when mounting their canonical targets.
for path in self.profile.runtime_paths() {
exceptions.push(Exception::ExecuteAndRead(path.clone()));
}
for path in read_only {
exceptions.push(Exception::Read(path.clone()));
}
Expand Down Expand Up @@ -189,3 +194,39 @@ fn rebuild_from_existing_ancestor(path: &Path) -> Result<PathBuf, SandboxError>

Ok(base.join(tail))
}

#[cfg(all(
test,
target_os = "linux",
any(target_arch = "x86_64", target_arch = "aarch64")
))]
mod tests {
//! Exact initial-command authorization stays separate from runtime mounts.

use std::path::Path;

use super::Sandbox;
use crate::{SandboxError, SandboxProfile};

#[test]
fn runtime_loader_is_not_an_initial_command_grant() {
let sandbox = Sandbox::new(SandboxProfile::new());
#[cfg(target_arch = "x86_64")]
let program = Path::new("/lib64/ld-linux-x86-64.so.2");
#[cfg(target_arch = "aarch64")]
let program = Path::new("/lib/ld-linux-aarch64.so.1");
assert!(
program.exists(),
"host dynamic loader must exist for this test"
);
let canonical_program =
Sandbox::canonical_program(program).expect("host loader must canonicalize");
let error = sandbox
.ensure_program_whitelisted(&canonical_program)
.expect_err("runtime mount must not authorize an initial command");
assert!(
matches!(error, SandboxError::ExecutableNotAuthorised { program: denied } if denied == canonical_program),
"runtime root must stay outside caller executable allowlist"
);
}
}
10 changes: 6 additions & 4 deletions crates/weaver-sandbox/src/tests/unit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,18 @@ use std::path::PathBuf;
use crate::profile::{EnvironmentPolicy, NetworkPolicy, SandboxProfile};

#[test]
fn profile_whitelists_linux_runtime_roots() {
fn profile_keeps_linux_runtime_roots_separate_from_caller_paths() {
let profile = SandboxProfile::new();
if cfg!(target_os = "linux") {
assert!(
!profile.read_only_paths().is_empty(),
"linux runtime roots should be whitelisted by default"
!profile.runtime_paths().is_empty(),
"linux runtime roots should be mounted by default"
);
} else {
assert!(profile.read_only_paths().is_empty());
assert!(profile.runtime_paths().is_empty());
}
assert!(profile.read_only_paths_canonicalised().expect("read paths").is_empty());
assert!(profile.executable_paths_canonicalised().expect("executable paths").is_empty());
}

#[test]
Expand Down
155 changes: 155 additions & 0 deletions crates/weaver-sandbox/tests/sandbox_child_probe.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
//! Verify a directly launched sandboxed command in a single-threaded child.

#[cfg(target_os = "linux")]
use std::{ffi::OsStr, io::Write as _, process::Command};

#[cfg(target_os = "linux")]
use anyhow::{Context as _, Result, ensure};
#[cfg(target_os = "linux")]
use cap_std::{ambient_authority, fs::Dir};
use libtest_mimic::Arguments;
#[cfg(target_os = "linux")]
use libtest_mimic::Trial;
#[cfg(target_os = "linux")]
use weaver_sandbox::{Sandbox, SandboxCommand, SandboxProfile, process::Stdio};

#[cfg(target_os = "linux")]
const CHILD_ARGUMENT: &str = "--weaver-sandbox-probe-child";
#[cfg(target_os = "linux")]
const MARKERS: [&str; 2] = ["KEEP_ME=present-λ", "DROP_ME=remove-me-東京"];

fn main() {
#[cfg(target_os = "linux")]
if std::env::args_os().any(|argument| argument == OsStr::new(CHILD_ARGUMENT)) {
if let Err(error) = run_child_probe() {
let _diagnostic = writeln!(std::io::stderr().lock(), "child probe failed: {error:#}");
std::process::exit(1);
}
return;
}

let trials = {
#[cfg(target_os = "linux")]
{
vec![Trial::test(
"sandbox::full_environment_in_single_thread_child",
|| run_mimic_trial().map_err(|error| format!("{error:#}").into()),
)]
}
#[cfg(not(target_os = "linux"))]
{
Vec::new()
}
};
libtest_mimic::run(&Arguments::from_args(), trials).exit();
}

#[cfg(target_os = "linux")]
fn run_mimic_trial() -> Result<()> {
require_markers_absent("before child")?;

let executable = std::env::current_exe().context("locate current test executable")?;
let child = Command::new(executable)
.arg(CHILD_ARGUMENT)
.env_clear()
.env("KEEP_ME", "present-λ")
.env("DROP_ME", "remove-me-東京")
.output()
.context("run single-threaded child")?;
ensure!(
child.status.success(),
"child failed: {}; stderr: {}",
child.status,
String::from_utf8_lossy(&child.stderr)
);
let child_thread_line =
std::str::from_utf8(&child.stdout).context("decode worker thread evidence")?;
ensure!(
child_thread_line.split_whitespace().eq(["Threads:", "1"]),
"unexpected worker thread evidence: {child_thread_line}"
);
std::io::stdout()
.lock()
.write_all(&child.stdout)
.context("report verified worker thread count")?;

require_markers_absent("after child")
}

#[cfg(target_os = "linux")]
fn run_child_probe() -> Result<()> {
let process_dir = Dir::open_ambient_dir("/proc/self", ambient_authority())
.context("open own procfs directory")?;
let status = process_dir
.read_to_string("status")
.context("read own status")?;
let thread_line = status
.lines()
.find(|line| line.starts_with("Threads:"))
.context("find thread count")?;
ensure!(
thread_line.split_whitespace().nth(1) == Some("1"),
"child is not single-threaded: {thread_line}"
);

let profile = SandboxProfile::new()
.allow_executable("/usr/bin/env")
.allow_full_environment();
let mut command = SandboxCommand::new("/usr/bin/env");
command.stdout(Stdio::piped());
let output = Sandbox::new(profile)
.spawn(command)
.context("spawn public sandbox command")?
.wait_with_output()
.context("wait for sandboxed env")?;
ensure!(
output.status.success(),
"sandboxed env failed: {}",
output.status
);
require_markers_present(&output.stdout, "sandboxed env")?;

let restored = Command::new("/usr/bin/env")
.output()
.context("run unsandboxed env after spawn")?;
ensure!(
restored.status.success(),
"restored env failed: {}",
restored.status
);
require_markers_present(&restored.stdout, "restored env")?;
writeln!(std::io::stdout().lock(), "{thread_line}").context("report worker thread evidence")?;
Ok(())
}

#[cfg(target_os = "linux")]
fn require_markers_present(output: &[u8], label: &str) -> Result<()> {
let text = String::from_utf8(output.to_vec()).context("decode env output")?;
for marker in MARKERS {
ensure!(
text.lines().any(|line| line == marker),
"{label} lacks {marker}"
);
}
Ok(())
}

#[cfg(target_os = "linux")]
fn require_markers_absent(label: &str) -> Result<()> {
let output = Command::new("/usr/bin/env")
.output()
.context("inspect mimic process environment")?;
ensure!(
output.status.success(),
"mimic env failed: {}",
output.status
);
let text = String::from_utf8(output.stdout).context("decode mimic env")?;
for marker in MARKERS {
ensure!(
!text.lines().any(|line| line == marker),
"mimic process contains {marker} {label}"
);
}
Ok(())
}
Loading
Loading