feat(sandbox): implement probe-gated Linux strict isolation (ADR-0021)
Strict mode now re-executes the CLI inside a Bubblewrap supervisor with user/mount/PID/net/UTS/IPC namespaces, no-new-privs, all capabilities dropped, a read-only /project, private /proc and /dev, rlimits, output capture and wall-clock process-group cleanup. The child verifies PID 1, NoNewPrivs, empty CapEff, an unshared uid map and loopback-only networking before project code. - PlatformCapabilities::detect runs a real bwrap probe; no probe, no strict - strict L1 supports pure Marqdo + Math; Foreign/ABI/worker/kernel/grants/trace are rejected with exit 2 before sandboxing - forged MARQDO_STRICT_ACTIVE is rejected; missing bwrap fails closed - add adversarial helper, 7-test escape/resource matrix, seeded security lane script and self-hosted security workflow - executed G-C lane as uid 1000 in a disposable Ubuntu 26.04 VM: 7/7 PASS plus positive CLI and refusal matrix; evidence in docs/evidence - ADR-0021, spec/security.md, STATUS/COMPATIBILITY/README/CHANGELOG updated; ADR-0019 remains for non-Linux/fail-closed rules
This commit is contained in:
1 parent
9b001a33a5
commit
b6fc18233d
22 files changed
+1886
-132
No files matched your search
+102
-1
@@ -59,6 +59,31 @@ impl SandboxSettings {
|
||||
})
|
||||
}
|
||||
|
||||
/// Reject strict-mode requests that this L1 isolation level does not
|
||||
/// support. Strict currently covers pure Marqdo and native Math only;
|
||||
/// granting Foreign, ABI plugins, tools or trace files would require
|
||||
/// extending the supervisor contract first.
|
||||
pub fn strict_preflight(&self) -> Result<(), String> {
|
||||
let requested = self.allow_foreign
|
||||
|| !self.allow_read.is_empty()
|
||||
|| !self.allow_write.is_empty()
|
||||
|| !self.allow_plugin.is_empty()
|
||||
|| !self.plugins.is_empty()
|
||||
|| self.trust_native_plugin
|
||||
|| !self.kernels.is_empty()
|
||||
|| self.trace_file.is_some();
|
||||
if requested {
|
||||
return Err(
|
||||
"strict mode currently supports pure Marqdo and native Math only; \
|
||||
--allow-read/--allow-write/--allow-foreign/--allow-plugin/--plugin/\
|
||||
--trust-native-plugin/--kernel/--trace-file are rejected. Use \
|
||||
--mode project for those capabilities."
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Build the effective capability set.
|
||||
pub fn capabilities(&self) -> Result<Capabilities, String> {
|
||||
let mode = self.sandbox_mode()?;
|
||||
@@ -91,7 +116,10 @@ impl SandboxSettings {
|
||||
}
|
||||
Ok(capabilities)
|
||||
}
|
||||
SandboxMode::Strict => Ok(Capabilities::project()),
|
||||
SandboxMode::Strict => {
|
||||
self.strict_preflight()?;
|
||||
Ok(Capabilities::project())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -625,6 +653,43 @@ fn resolve_link(
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-execute this CLI inside the strict Linux supervisor.
|
||||
fn launch_strict_process(
|
||||
project_root: &Path,
|
||||
document: Option<&Path>,
|
||||
settings: &SandboxSettings,
|
||||
) -> i32 {
|
||||
let program = match std::env::current_exe() {
|
||||
Ok(path) => path,
|
||||
Err(error) => {
|
||||
eprintln!("error: cannot locate the marqdo executable: {error}");
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
let args: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
|
||||
let output_limit = settings
|
||||
.max_output
|
||||
.unwrap_or(1024 * 1024)
|
||||
.min(64 * 1024 * 1024);
|
||||
let timeout = Duration::from_secs(settings.timeout.unwrap_or(30));
|
||||
let command = marqdo_sandbox::StrictHostCommand {
|
||||
program: &program,
|
||||
args: &args,
|
||||
project_root,
|
||||
document,
|
||||
original_document: document,
|
||||
output_limit,
|
||||
timeout,
|
||||
};
|
||||
match marqdo_sandbox::launch_strict(&command) {
|
||||
Ok(code) => code,
|
||||
Err(error) => {
|
||||
eprintln!("error: {error}");
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `marqdo run` / `marqdo call`.
|
||||
pub fn execute(
|
||||
file: Option<&Path>,
|
||||
@@ -676,6 +741,42 @@ pub fn execute(
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
if mode == SandboxMode::Strict {
|
||||
if let Err(error) = settings.strict_preflight() {
|
||||
if json {
|
||||
output::print_json(&json!({"success": false, "error": error}));
|
||||
} else {
|
||||
eprintln!("error: {error}");
|
||||
}
|
||||
return 2;
|
||||
}
|
||||
if marqdo_sandbox::marker_present() {
|
||||
// We were re-executed by the supervisor: validate the marker set
|
||||
// before running any project code.
|
||||
if let Err(reason) = marqdo_sandbox::verify_active() {
|
||||
if json {
|
||||
output::print_json(&json!({
|
||||
"success": false,
|
||||
"error": format!("strict isolation verification failed: {reason}"),
|
||||
}));
|
||||
} else {
|
||||
eprintln!("error: strict isolation verification failed: {reason}");
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
} else {
|
||||
let platform = PlatformCapabilities::detect();
|
||||
if let Err(error) = marqdo_sandbox::enforce(mode, &platform) {
|
||||
if json {
|
||||
output::print_json(&json!({"success": false, "error": error.to_string()}));
|
||||
} else {
|
||||
eprintln!("error: {error}");
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
return launch_strict_process(&project.root, file, settings);
|
||||
}
|
||||
}
|
||||
let platform = PlatformCapabilities::detect();
|
||||
if let Err(error) = marqdo_sandbox::enforce(mode, &platform) {
|
||||
if json {
|
||||
|
||||
@@ -331,11 +331,42 @@ fn examples_run_end_to_end_including_foreign_when_available() {
|
||||
);
|
||||
}
|
||||
|
||||
fn strict_is_available(root: &Path) -> bool {
|
||||
let hello = root.join("examples").join("hello.mq.md");
|
||||
let output = cli(
|
||||
root,
|
||||
&["inspect", hello.to_str().unwrap(), "--platform", "--json"],
|
||||
);
|
||||
if !output.status.success() {
|
||||
return false;
|
||||
}
|
||||
let value = json_stdout(&output);
|
||||
value["platform"]["strict"]["state"] == "available"
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_mode_refuses_without_isolation() {
|
||||
fn strict_mode_enforces_isolation_or_refuses_closed() {
|
||||
let root = repo_root();
|
||||
let hello = root.join("examples").join("hello.mq.md");
|
||||
let output = cli(&root, &["run", hello.to_str().unwrap(), "--mode", "strict"]);
|
||||
if strict_is_available(&root) {
|
||||
assert_exit(&output, 0, "strict mode must succeed when the gate passes");
|
||||
assert_eq!(stdout_text(&output), "你好,Marqdo\n");
|
||||
// External execution surfaces are rejected at the strict L1 boundary.
|
||||
let foreign = cli(
|
||||
&root,
|
||||
&[
|
||||
"run",
|
||||
hello.to_str().unwrap(),
|
||||
"--mode",
|
||||
"strict",
|
||||
"--allow-foreign",
|
||||
],
|
||||
);
|
||||
assert_exit(&foreign, 2, "strict must reject foreign grants");
|
||||
assert!(stderr_text(&foreign).contains("strict mode currently supports"));
|
||||
return;
|
||||
}
|
||||
assert_exit(
|
||||
&output,
|
||||
1,
|
||||
@@ -763,7 +794,7 @@ fn runtime_error_in_imported_module_reports_that_module() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn platform_reports_strict_unavailable_until_security_gate_passes() {
|
||||
fn platform_reports_strict_capability_truthfully() {
|
||||
let root = repo_root();
|
||||
let hello = root.join("examples").join("hello.mq.md");
|
||||
let output = cli(
|
||||
@@ -773,17 +804,27 @@ fn platform_reports_strict_unavailable_until_security_gate_passes() {
|
||||
assert_exit(&output, 0, "inspect --platform");
|
||||
let value = json_stdout(&output);
|
||||
let strict = &value["platform"]["strict"];
|
||||
assert_eq!(
|
||||
strict["state"], "unavailable",
|
||||
"strict must stay unavailable until the ADR-0019 security gate passes: {strict}"
|
||||
);
|
||||
assert!(
|
||||
strict["reason"]
|
||||
.as_str()
|
||||
.map(|reason| !reason.trim().is_empty())
|
||||
.unwrap_or(false),
|
||||
"unavailable strict needs an actionable reason: {strict}"
|
||||
);
|
||||
match strict["state"].as_str() {
|
||||
Some("available") => {
|
||||
assert!(
|
||||
strict["mechanism"]
|
||||
.as_str()
|
||||
.map(|mechanism| mechanism.contains("bubblewrap"))
|
||||
.unwrap_or(false),
|
||||
"available strict needs the real mechanism: {strict}"
|
||||
);
|
||||
}
|
||||
Some("unavailable") => {
|
||||
assert!(
|
||||
strict["reason"]
|
||||
.as_str()
|
||||
.map(|reason| !reason.trim().is_empty())
|
||||
.unwrap_or(false),
|
||||
"unavailable strict needs an actionable reason: {strict}"
|
||||
);
|
||||
}
|
||||
other => panic!("unexpected strict state: {other:?} ({strict})"),
|
||||
}
|
||||
assert_eq!(value["platform"]["worker_processes"], true);
|
||||
}
|
||||
|
||||
|
||||
@@ -11,3 +11,6 @@ authors.workspace = true
|
||||
[dependencies]
|
||||
serde = { workspace = true }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = { workspace = true }
|
||||
|
||||
@@ -5,8 +5,16 @@
|
||||
//! provide OS-level isolation: a cooperative in-process check is not a sandbox
|
||||
//! (blueprint section 9). This crate is deliberately honest about that.
|
||||
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub use linux::{marker_present, probe, verify_active, StrictOutcome};
|
||||
|
||||
/// Execution mode requested on the command line.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
@@ -103,21 +111,29 @@ impl PlatformCapabilities {
|
||||
/// security contract. The isolated worker transport is implemented, but a
|
||||
/// plain child process is not an OS sandbox.
|
||||
pub fn detect() -> Self {
|
||||
let reason = if cfg!(target_os = "linux") {
|
||||
"no OS isolation adapter (namespaces/seccomp/cgroups) is implemented in this build"
|
||||
let strict = if cfg!(target_os = "linux") {
|
||||
match linux::probe() {
|
||||
Ok(mechanism) => StrictIsolation::Available { mechanism },
|
||||
Err(reason) => StrictIsolation::Unavailable { reason },
|
||||
}
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"no verified macOS sandbox adapter is implemented in this build"
|
||||
StrictIsolation::Unavailable {
|
||||
reason: "no verified macOS sandbox adapter is implemented in this build"
|
||||
.to_string(),
|
||||
}
|
||||
} else if cfg!(target_os = "windows") {
|
||||
"no verified Windows job-object/appcontainer adapter is implemented in this build"
|
||||
StrictIsolation::Unavailable {
|
||||
reason: "no verified Windows job-object/appcontainer adapter is implemented in this build".to_string(),
|
||||
}
|
||||
} else {
|
||||
"platform isolation is not implemented for this target"
|
||||
StrictIsolation::Unavailable {
|
||||
reason: "platform isolation is not implemented for this target".to_string(),
|
||||
}
|
||||
};
|
||||
Self {
|
||||
os: std::env::consts::OS.to_string(),
|
||||
arch: std::env::consts::ARCH.to_string(),
|
||||
strict: StrictIsolation::Unavailable {
|
||||
reason: reason.to_string(),
|
||||
},
|
||||
strict,
|
||||
worker_processes: true,
|
||||
}
|
||||
}
|
||||
@@ -131,6 +147,11 @@ pub enum SandboxError {
|
||||
/// Explanation from [`PlatformCapabilities`].
|
||||
reason: String,
|
||||
},
|
||||
/// The strict supervisor could not launch, verify or supervise the child.
|
||||
LaunchFailed {
|
||||
/// Actionable explanation.
|
||||
message: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl std::fmt::Display for SandboxError {
|
||||
@@ -140,6 +161,9 @@ impl std::fmt::Display for SandboxError {
|
||||
f,
|
||||
"refusing to run in strict mode: {reason}. Strict mode requires verified OS-level isolation and never falls back to an unrestricted process."
|
||||
),
|
||||
SandboxError::LaunchFailed { message } => {
|
||||
write!(f, "strict isolation failed: {message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -150,6 +174,10 @@ impl std::error::Error for SandboxError {}
|
||||
pub fn enforce(mode: SandboxMode, platform: &PlatformCapabilities) -> Result<(), SandboxError> {
|
||||
match mode {
|
||||
SandboxMode::Strict => {
|
||||
#[cfg(target_os = "linux")]
|
||||
if verify_active().is_ok() {
|
||||
return Ok(());
|
||||
}
|
||||
if platform.strict.is_available() {
|
||||
Ok(())
|
||||
} else {
|
||||
@@ -164,6 +192,49 @@ pub fn enforce(mode: SandboxMode, platform: &PlatformCapabilities) -> Result<(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A command to execute inside the strict Linux sandbox.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StrictHostCommand<'a> {
|
||||
/// Program bound read-only into the sandbox and executed.
|
||||
pub program: &'a Path,
|
||||
/// Arguments passed to the program.
|
||||
pub args: &'a [std::ffi::OsString],
|
||||
/// Project directory mounted read-only at `/project`.
|
||||
pub project_root: &'a Path,
|
||||
/// Entry document as passed on the command line; rewritten to the sandbox
|
||||
/// path. `None` keeps the CLI default (index.mq.md).
|
||||
pub document: Option<&'a Path>,
|
||||
/// Original document token to replace in `args` (same value as `document`
|
||||
/// when present).
|
||||
pub original_document: Option<&'a Path>,
|
||||
/// Combined per-stream output cap in bytes.
|
||||
pub output_limit: usize,
|
||||
/// Wall-clock budget for the supervised process tree.
|
||||
pub timeout: Duration,
|
||||
}
|
||||
|
||||
/// Launch a command inside the strict sandbox (Linux only).
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn launch_strict(command: &StrictHostCommand<'_>) -> Result<i32, SandboxError> {
|
||||
linux::launch(command)
|
||||
}
|
||||
|
||||
/// Launch a command inside the strict sandbox and return its captured outcome.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn launch_strict_capture(
|
||||
command: &StrictHostCommand<'_>,
|
||||
) -> Result<linux::StrictOutcome, SandboxError> {
|
||||
linux::launch_capture(command)
|
||||
}
|
||||
|
||||
/// Launch a command inside the strict sandbox (unsupported elsewhere).
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub fn launch_strict(_command: &StrictHostCommand<'_>) -> Result<i32, SandboxError> {
|
||||
Err(SandboxError::StrictUnavailable {
|
||||
reason: "strict OS isolation is only implemented on Linux".to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -178,7 +249,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn strict_refuses_when_isolation_is_unavailable() {
|
||||
let platform = PlatformCapabilities::detect();
|
||||
let platform = PlatformCapabilities {
|
||||
os: "test".to_string(),
|
||||
arch: "test".to_string(),
|
||||
strict: StrictIsolation::Unavailable {
|
||||
reason: "test host has no verified isolation".to_string(),
|
||||
},
|
||||
worker_processes: true,
|
||||
};
|
||||
let result = enforce(SandboxMode::Strict, &platform);
|
||||
assert!(result.is_err());
|
||||
assert!(format!("{}", result.unwrap_err()).contains("strict"));
|
||||
|
||||
@@ -0,0 +1,477 @@
|
||||
//! Linux strict-isolation supervisor.
|
||||
//!
|
||||
//! The mechanism is Bubblewrap (`bwrap`) plus a small trusted supervisor in
|
||||
//! this process:
|
||||
//!
|
||||
//! * user, mount, PID, network, UTS, IPC and cgroup namespaces
|
||||
//! (`--unshare-all --as-pid-1`);
|
||||
//! * a read-only view of the runtime libraries, the project root and the
|
||||
//! program itself; no host `/etc`, `/root`, `$HOME` or other projects;
|
||||
//! * a tmpfs `/tmp`, a private `/proc` and a minimal `/dev`;
|
||||
//! * `no_new_privs`, all capabilities dropped, empty environment;
|
||||
//! * hard rlimits for CPU, address space, file size, file descriptors,
|
||||
//! processes, stack and core dumps;
|
||||
//! * a wall-clock supervisor with process-group cleanup and bounded captured
|
||||
//! output.
|
||||
//!
|
||||
//! Bubblewrap is a construction mechanism, not a certificate: [`probe`] runs
|
||||
//! a real sandbox smoke test at runtime and strict is reported unavailable if
|
||||
//! the host cannot create the namespaces. The sandboxed process additionally
|
||||
//! verifies its own markers (`PID 1`, `NoNewPrivs`, unshared uid map, no
|
||||
//! non-loopback interface) before executing user code.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::fs;
|
||||
use std::io::{self, Read, Write};
|
||||
use std::os::unix::process::{CommandExt, ExitStatusExt};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, Command, ExitStatus, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::{SandboxError, StrictHostCommand};
|
||||
|
||||
/// Environment variable that marks a re-executed strict child.
|
||||
pub const ACTIVE_ENV: &str = "MARQDO_STRICT_ACTIVE";
|
||||
|
||||
/// Path of the program inside the sandbox.
|
||||
const SANDBOX_PROGRAM: &str = "/run/marqdo-program";
|
||||
|
||||
/// Candidate absolute Bubblewrap paths. `PATH` lookup is deliberately avoided
|
||||
/// so a project-local binary cannot impersonate the supervisor tool.
|
||||
const BWRAP_PATHS: [&str; 3] = ["/usr/bin/bwrap", "/bin/bwrap", "/usr/local/bin/bwrap"];
|
||||
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const MAX_STACK_BYTES: u64 = 8 * 1024 * 1024;
|
||||
const MAX_ADDRESS_SPACE: u64 = 512 * 1024 * 1024;
|
||||
const MAX_PROCESSES: u64 = 64;
|
||||
const MAX_OPEN_FILES: u64 = 64;
|
||||
|
||||
fn bwrap_path() -> Option<PathBuf> {
|
||||
BWRAP_PATHS
|
||||
.iter()
|
||||
.map(PathBuf::from)
|
||||
.find(|path| path.is_file())
|
||||
}
|
||||
|
||||
/// Probe the real availability of the strict mechanism.
|
||||
pub fn probe() -> Result<String, String> {
|
||||
let bwrap = bwrap_path().ok_or_else(|| {
|
||||
"bubblewrap (`bwrap`) is not installed; install it or use project mode".to_string()
|
||||
})?;
|
||||
let version = bwrap_version(&bwrap)?;
|
||||
let mut command = Command::new(&bwrap);
|
||||
command
|
||||
.args(common_args())
|
||||
.args(["--", "/bin/true"])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.map_err(|error| format!("cannot start the bubblewrap probe: {error}"))?;
|
||||
let status = wait_with_deadline(&mut child, PROBE_TIMEOUT)?;
|
||||
let mut stderr = String::new();
|
||||
if let Some(mut pipe) = child.stderr.take() {
|
||||
let _ = pipe.read_to_string(&mut stderr);
|
||||
}
|
||||
if !status.success() {
|
||||
return Err(format!(
|
||||
"bubblewrap cannot create the required namespaces: {}",
|
||||
stderr.trim()
|
||||
));
|
||||
}
|
||||
Ok(format!(
|
||||
"bubblewrap {version} (user/mount/PID/net/UTS/IPC namespaces + no-new-privs + rlimits)"
|
||||
))
|
||||
}
|
||||
|
||||
fn bwrap_version(bwrap: &Path) -> Result<String, String> {
|
||||
let output = Command::new(bwrap)
|
||||
.arg("--version")
|
||||
.stdin(Stdio::null())
|
||||
.output()
|
||||
.map_err(|error| format!("cannot run `{}`: {error}", bwrap.display()))?;
|
||||
if !output.status.success() {
|
||||
return Err("`bwrap --version` failed".to_string());
|
||||
}
|
||||
let text = String::from_utf8_lossy(&output.stdout);
|
||||
let version = text
|
||||
.lines()
|
||||
.next()
|
||||
.unwrap_or("")
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.unwrap_or("unknown")
|
||||
.to_string();
|
||||
Ok(version)
|
||||
}
|
||||
|
||||
fn common_args() -> Vec<OsString> {
|
||||
let mut args: Vec<OsString> = [
|
||||
"--unshare-all",
|
||||
"--as-pid-1",
|
||||
"--die-with-parent",
|
||||
"--new-session",
|
||||
"--cap-drop",
|
||||
"ALL",
|
||||
"--clearenv",
|
||||
"--setenv",
|
||||
"PATH",
|
||||
"/usr/bin:/bin",
|
||||
"--setenv",
|
||||
"HOME",
|
||||
"/tmp",
|
||||
"--setenv",
|
||||
"LANG",
|
||||
"C.UTF-8",
|
||||
"--proc",
|
||||
"/proc",
|
||||
"--dev",
|
||||
"/dev",
|
||||
"--tmpfs",
|
||||
"/tmp",
|
||||
"--dir",
|
||||
"/run",
|
||||
]
|
||||
.into_iter()
|
||||
.map(OsString::from)
|
||||
.collect();
|
||||
for directory in ["/usr", "/bin", "/sbin", "/lib", "/lib64"] {
|
||||
let path = Path::new(directory);
|
||||
if path.exists() {
|
||||
args.extend([
|
||||
OsString::from("--ro-bind"),
|
||||
OsString::from(directory),
|
||||
OsString::from(directory),
|
||||
]);
|
||||
}
|
||||
}
|
||||
if Path::new("/etc/ld.so.cache").is_file() {
|
||||
args.extend([
|
||||
OsString::from("--ro-bind"),
|
||||
OsString::from("/etc/ld.so.cache"),
|
||||
OsString::from("/etc/ld.so.cache"),
|
||||
]);
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
/// Verify that this process really is the strict child created by [`launch`].
|
||||
pub fn verify_active() -> Result<(), String> {
|
||||
if std::env::var(ACTIVE_ENV).ok().as_deref() != Some("1") {
|
||||
return Err("strict active marker is absent".to_string());
|
||||
}
|
||||
// `--as-pid-1` makes the supervised program PID 1 in its own PID namespace.
|
||||
let pid = unsafe { libc::getpid() };
|
||||
if pid != 1 {
|
||||
return Err(format!(
|
||||
"strict child is not PID 1 in a private PID namespace (pid {pid})"
|
||||
));
|
||||
}
|
||||
let status = fs::read_to_string("/proc/self/status")
|
||||
.map_err(|error| format!("cannot read /proc/self/status: {error}"))?;
|
||||
if !status.lines().any(|line| line == "NoNewPrivs:\t1") {
|
||||
return Err("strict child does not have no_new_privs set".to_string());
|
||||
}
|
||||
let effective = status
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("CapEff:\t"))
|
||||
.unwrap_or("");
|
||||
if effective.bytes().any(|byte| byte != b'0') {
|
||||
return Err("strict child still has effective capabilities".to_string());
|
||||
}
|
||||
let uid_map = fs::read_to_string("/proc/self/uid_map")
|
||||
.map_err(|error| format!("cannot read uid_map: {error}"))?;
|
||||
let unshared = uid_map.lines().any(|line| {
|
||||
let fields: Vec<&str> = line.split_whitespace().collect();
|
||||
!(fields.len() == 3 && fields[0] == "0" && fields[1] == "0" && fields[2] == "4294967295")
|
||||
});
|
||||
if !unshared {
|
||||
return Err("strict child did not create a private user namespace".to_string());
|
||||
}
|
||||
let interfaces = fs::read_to_string("/proc/net/dev")
|
||||
.map_err(|error| format!("cannot read /proc/net/dev: {error}"))?;
|
||||
let non_loopback = interfaces.lines().skip(2).any(|line| {
|
||||
let name = line.split(':').next().unwrap_or("").trim();
|
||||
!name.is_empty() && name != "lo"
|
||||
});
|
||||
if non_loopback {
|
||||
return Err("strict child still has a non-loopback network interface".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the current process claims to be a strict child. The marker alone
|
||||
/// is not trusted; callers must use [`verify_active`].
|
||||
pub fn marker_present() -> bool {
|
||||
std::env::var(ACTIVE_ENV).ok().as_deref() == Some("1")
|
||||
}
|
||||
|
||||
/// Result of one supervised strict execution.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StrictOutcome {
|
||||
/// Process exit code when the program exited normally.
|
||||
pub exit_code: Option<i32>,
|
||||
/// Terminating signal, when the program was killed by the supervisor,
|
||||
/// a resource limit or the kernel.
|
||||
pub signal: Option<i32>,
|
||||
/// Captured stdout (bounded by the output limit).
|
||||
pub stdout: Vec<u8>,
|
||||
/// Captured stderr (bounded by the output limit).
|
||||
pub stderr: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Launch `command` inside the strict sandbox and return its exit code,
|
||||
/// forwarding captured output to this process's stdout/stderr.
|
||||
pub fn launch(command: &StrictHostCommand<'_>) -> Result<i32, SandboxError> {
|
||||
let outcome = run(command)?;
|
||||
let mut stdout = io::stdout().lock();
|
||||
let _ = stdout.write_all(&outcome.stdout);
|
||||
let _ = stdout.flush();
|
||||
let mut stderr = io::stderr().lock();
|
||||
let _ = stderr.write_all(&outcome.stderr);
|
||||
let _ = stderr.flush();
|
||||
finish(outcome)
|
||||
}
|
||||
|
||||
/// Launch `command` and return its captured outcome without forwarding it.
|
||||
/// Used by the adversarial security lane.
|
||||
pub fn launch_capture(command: &StrictHostCommand<'_>) -> Result<StrictOutcome, SandboxError> {
|
||||
run(command)
|
||||
}
|
||||
|
||||
fn finish(outcome: StrictOutcome) -> Result<i32, SandboxError> {
|
||||
if let Some(code) = outcome.exit_code {
|
||||
return Ok(code);
|
||||
}
|
||||
let signal = outcome.signal.unwrap_or_default();
|
||||
let message = match signal {
|
||||
libc::SIGXCPU => "strict child exceeded its CPU budget".to_string(),
|
||||
libc::SIGXFSZ => "strict child exceeded its output budget".to_string(),
|
||||
libc::SIGKILL => "strict child was killed by the resource supervisor".to_string(),
|
||||
other => format!("strict child terminated by signal {other}"),
|
||||
};
|
||||
Err(SandboxError::LaunchFailed { message })
|
||||
}
|
||||
|
||||
fn run(command: &StrictHostCommand<'_>) -> Result<StrictOutcome, SandboxError> {
|
||||
if command.project_root == Path::new("/") {
|
||||
return Err(SandboxError::LaunchFailed {
|
||||
message: "strict mode refuses to expose the host root as the project".to_string(),
|
||||
});
|
||||
}
|
||||
let project_root =
|
||||
fs::canonicalize(command.project_root).map_err(|error| SandboxError::LaunchFailed {
|
||||
message: format!(
|
||||
"cannot resolve the strict project root `{}`: {error}",
|
||||
command.project_root.display()
|
||||
),
|
||||
})?;
|
||||
// The document (when supplied) must be inside the project root. It is
|
||||
// rewritten to the sandbox path, so the host's absolute layout never leaks
|
||||
// into the child and no other directory needs to be mounted.
|
||||
let document = match command.document {
|
||||
Some(document) => {
|
||||
let absolute =
|
||||
fs::canonicalize(document).map_err(|error| SandboxError::LaunchFailed {
|
||||
message: format!("cannot resolve strict document: {error}"),
|
||||
})?;
|
||||
let relative =
|
||||
absolute
|
||||
.strip_prefix(&project_root)
|
||||
.map_err(|_| SandboxError::LaunchFailed {
|
||||
message: format!(
|
||||
"strict document `{}` is outside the project root `{}`",
|
||||
absolute.display(),
|
||||
project_root.display()
|
||||
),
|
||||
})?;
|
||||
Some(Path::new("/project").join(relative))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
probe().map_err(|reason| SandboxError::LaunchFailed { message: reason })?;
|
||||
let bwrap = bwrap_path().ok_or_else(|| SandboxError::LaunchFailed {
|
||||
message: "bubblewrap disappeared after the probe".to_string(),
|
||||
})?;
|
||||
|
||||
let mut args = common_args();
|
||||
args.extend([
|
||||
OsString::from("--ro-bind"),
|
||||
project_root.as_os_str().to_os_string(),
|
||||
OsString::from("/project"),
|
||||
OsString::from("--ro-bind"),
|
||||
command.program.as_os_str().to_os_string(),
|
||||
OsString::from(SANDBOX_PROGRAM),
|
||||
OsString::from("--setenv"),
|
||||
OsString::from(ACTIVE_ENV),
|
||||
OsString::from("1"),
|
||||
OsString::from("--chdir"),
|
||||
OsString::from("/project"),
|
||||
OsString::from("--"),
|
||||
OsString::from(SANDBOX_PROGRAM),
|
||||
]);
|
||||
// Rewrite the document argument to its `/project/...` sandbox path. The
|
||||
// CLI passed the original token, so replace exactly that token; all other
|
||||
// arguments (flags, function name, typed --arg values) are unchanged.
|
||||
let mut replaced = document.is_none();
|
||||
for argument in command.args {
|
||||
if let Some(document) = &document {
|
||||
if Path::new(argument) == command.original_document.unwrap_or(Path::new("")) {
|
||||
args.push(document.as_os_str().to_os_string());
|
||||
replaced = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
args.push(argument.clone());
|
||||
}
|
||||
if !replaced {
|
||||
return Err(SandboxError::LaunchFailed {
|
||||
message: "strict launcher could not rewrite the document argument".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let stdout = CaptureFile::create("stdout")?;
|
||||
let stderr = CaptureFile::create("stderr")?;
|
||||
let limit = command.output_limit.max(1024) as u64;
|
||||
let timeout = command.timeout;
|
||||
let cpu_limit = timeout.as_secs().saturating_add(2).max(1);
|
||||
let mut supervisor = Command::new(&bwrap);
|
||||
supervisor
|
||||
.args(&args)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::from(stdout.reopen()?))
|
||||
.stderr(Stdio::from(stderr.reopen()?));
|
||||
// SAFETY: the closure only calls async-signal-safe libc functions
|
||||
// (`setpgid`, `setrlimit`) between fork and exec.
|
||||
unsafe {
|
||||
supervisor.pre_exec(move || {
|
||||
if libc::setpgid(0, 0) != 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
set_limit(libc::RLIMIT_CPU, cpu_limit, cpu_limit)?;
|
||||
set_limit(libc::RLIMIT_AS, MAX_ADDRESS_SPACE, MAX_ADDRESS_SPACE)?;
|
||||
set_limit(libc::RLIMIT_NOFILE, MAX_OPEN_FILES, MAX_OPEN_FILES)?;
|
||||
set_limit(libc::RLIMIT_NPROC, MAX_PROCESSES, MAX_PROCESSES)?;
|
||||
set_limit(libc::RLIMIT_FSIZE, limit, limit)?;
|
||||
set_limit(libc::RLIMIT_STACK, MAX_STACK_BYTES, MAX_STACK_BYTES)?;
|
||||
set_limit(libc::RLIMIT_CORE, 0, 0)?;
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
let mut child = supervisor
|
||||
.spawn()
|
||||
.map_err(|error| SandboxError::LaunchFailed {
|
||||
message: format!("cannot start the strict supervisor: {error}"),
|
||||
})?;
|
||||
|
||||
let status = match wait_with_deadline(&mut child, timeout) {
|
||||
Ok(status) => status,
|
||||
Err(message) => {
|
||||
let _ = unsafe { libc::kill(-(child.id() as i32), libc::SIGKILL) };
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
let _ = stdout.read_all();
|
||||
let _ = stderr.read_all();
|
||||
return Err(SandboxError::LaunchFailed { message });
|
||||
}
|
||||
};
|
||||
|
||||
Ok(StrictOutcome {
|
||||
exit_code: status.code(),
|
||||
signal: status.signal(),
|
||||
stdout: stdout.read_all()?,
|
||||
stderr: stderr.read_all()?,
|
||||
})
|
||||
}
|
||||
|
||||
fn set_limit(resource: libc::__rlimit_resource_t, soft: u64, hard: u64) -> io::Result<()> {
|
||||
let limit = libc::rlimit {
|
||||
rlim_cur: soft as libc::rlim_t,
|
||||
rlim_max: hard as libc::rlim_t,
|
||||
};
|
||||
if unsafe { libc::setrlimit(resource, &limit) } != 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn wait_with_deadline(child: &mut Child, timeout: Duration) -> Result<ExitStatus, String> {
|
||||
let deadline = Instant::now() + timeout;
|
||||
loop {
|
||||
if let Some(status) = child
|
||||
.try_wait()
|
||||
.map_err(|error| format!("cannot wait for the strict child: {error}"))?
|
||||
{
|
||||
return Ok(status);
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return Err(format!(
|
||||
"strict child exceeded its wall-clock budget of {} second(s)",
|
||||
timeout.as_secs()
|
||||
));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
}
|
||||
|
||||
struct CaptureFile {
|
||||
path: PathBuf,
|
||||
file: Option<fs::File>,
|
||||
}
|
||||
|
||||
impl CaptureFile {
|
||||
fn create(tag: &str) -> Result<Self, SandboxError> {
|
||||
let nanos = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|duration| duration.as_nanos())
|
||||
.unwrap_or(0);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"marqdo-strict-{tag}-{}-{nanos}",
|
||||
std::process::id()
|
||||
));
|
||||
let file = fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&path)
|
||||
.map_err(|error| SandboxError::LaunchFailed {
|
||||
message: format!("cannot create strict capture file: {error}"),
|
||||
})?;
|
||||
Ok(Self {
|
||||
path,
|
||||
file: Some(file),
|
||||
})
|
||||
}
|
||||
|
||||
fn reopen(&self) -> Result<fs::File, SandboxError> {
|
||||
self.file
|
||||
.as_ref()
|
||||
.ok_or_else(|| SandboxError::LaunchFailed {
|
||||
message: "strict capture file is closed".to_string(),
|
||||
})?
|
||||
.try_clone()
|
||||
.map_err(|error| SandboxError::LaunchFailed {
|
||||
message: format!("cannot clone strict capture file: {error}"),
|
||||
})
|
||||
}
|
||||
|
||||
fn read_all(&self) -> Result<Vec<u8>, SandboxError> {
|
||||
let mut file = fs::File::open(&self.path).map_err(|error| SandboxError::LaunchFailed {
|
||||
message: format!("cannot read strict capture file: {error}"),
|
||||
})?;
|
||||
let mut bytes = Vec::new();
|
||||
file.read_to_end(&mut bytes)
|
||||
.map_err(|error| SandboxError::LaunchFailed {
|
||||
message: format!("cannot read strict capture file: {error}"),
|
||||
})?;
|
||||
Ok(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for CaptureFile {
|
||||
fn drop(&mut self) {
|
||||
drop(self.file.take());
|
||||
let _ = fs::remove_file(&self.path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
//! Adversarial Linux strict-isolation lane.
|
||||
//!
|
||||
//! These tests launch a native helper through the **same** `marqdo-sandbox`
|
||||
//! supervisor used by `marqdo run --mode strict`, then exercise direct
|
||||
//! syscalls for filesystem, network, process, privilege and resource escapes.
|
||||
//!
|
||||
//! They require a host where [`marqdo_sandbox::probe`] succeeds (Bubblewrap
|
||||
//! plus permitted user/mount/PID/net namespaces). On an incapable host they
|
||||
//! are skipped **unless** `MARQDO_REQUIRE_STRICT_SECURITY=1` is set, which the
|
||||
//! G-C security lane must set so a missing mechanism can never count as a
|
||||
//! pass.
|
||||
//!
|
||||
//! The helper path can be supplied with `MARQDO_SECURITY_HELPER` (used when
|
||||
//! running this test binary inside the disposable security VM). Otherwise the
|
||||
//! test compiles `tests/security/escape_helper.c` with `cc`.
|
||||
#![cfg(target_os = "linux")]
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
use marqdo_sandbox::{launch_strict_capture, probe, StrictHostCommand, StrictOutcome};
|
||||
|
||||
fn required() -> bool {
|
||||
std::env::var("MARQDO_REQUIRE_STRICT_SECURITY")
|
||||
.ok()
|
||||
.as_deref()
|
||||
== Some("1")
|
||||
}
|
||||
|
||||
fn helper() -> Option<PathBuf> {
|
||||
if let Ok(path) = std::env::var("MARQDO_SECURITY_HELPER") {
|
||||
let path = PathBuf::from(path);
|
||||
assert!(path.is_file(), "MARQDO_SECURITY_HELPER does not exist");
|
||||
return Some(path);
|
||||
}
|
||||
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/security/escape_helper.c");
|
||||
let output = std::env::temp_dir().join(format!(
|
||||
"marqdo-escape-helper-{}{}",
|
||||
std::process::id(),
|
||||
std::env::consts::EXE_SUFFIX
|
||||
));
|
||||
let status = Command::new("cc")
|
||||
.args(["-O2", "-o"])
|
||||
.arg(&output)
|
||||
.arg(&source)
|
||||
.status()
|
||||
.ok()?;
|
||||
if !status.success() {
|
||||
return None;
|
||||
}
|
||||
Some(output)
|
||||
}
|
||||
|
||||
fn setup() -> Option<(PathBuf, PathBuf, PathBuf)> {
|
||||
if let Err(reason) = probe() {
|
||||
if required() {
|
||||
panic!("G-C security lane requires strict isolation but probe failed: {reason}");
|
||||
}
|
||||
eprintln!("skipping strict security lane: {reason}");
|
||||
return None;
|
||||
}
|
||||
let helper = match helper() {
|
||||
Some(helper) => helper,
|
||||
None => {
|
||||
if required() {
|
||||
panic!("G-C security lane could not build or find escape_helper");
|
||||
}
|
||||
eprintln!("skipping strict security lane: no escape helper/cc");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let project = std::env::temp_dir().join(format!("marqdo-security-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&project);
|
||||
fs::create_dir_all(&project).expect("create security project");
|
||||
fs::write(project.join("allowed.txt"), "allowed\n").expect("write allowed file");
|
||||
// A host-only path that is not mounted into the sandbox for any user. The
|
||||
// sandbox has no `$HOME`, so attempting to write here must fail.
|
||||
let home = std::env::var_os("HOME")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from("/home"));
|
||||
let outside = home.join(format!("marqdo-escape-{}", std::process::id()));
|
||||
let _ = fs::remove_file(&outside);
|
||||
Some((helper, project, outside))
|
||||
}
|
||||
|
||||
fn run(helper: &Path, project: &Path, outside: &Path, mode: &str) -> StrictOutcome {
|
||||
let args = vec![OsString::from(mode), outside.as_os_str().to_os_string()];
|
||||
let command = StrictHostCommand {
|
||||
program: helper,
|
||||
args: &args,
|
||||
project_root: project,
|
||||
document: None,
|
||||
original_document: None,
|
||||
output_limit: 64 * 1024,
|
||||
timeout: Duration::from_secs(3),
|
||||
};
|
||||
launch_strict_capture(&command).unwrap_or_else(|error| panic!("{mode}: {error}"))
|
||||
}
|
||||
|
||||
fn text(outcome: &StrictOutcome) -> String {
|
||||
String::from_utf8_lossy(&outcome.stdout).to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_child_identity_is_unprivileged_and_namespaced() {
|
||||
let Some((helper, project, outside)) = setup() else {
|
||||
return;
|
||||
};
|
||||
let outcome = run(&helper, &project, &outside, "alive");
|
||||
assert_eq!(outcome.exit_code, Some(0), "{}", text(&outcome));
|
||||
let output = text(&outcome);
|
||||
assert!(
|
||||
output.contains("uid=1000") || output.contains("uid=1001"),
|
||||
"{output}"
|
||||
);
|
||||
assert!(
|
||||
!output.contains("uid=0 "),
|
||||
"strict child ran as root: {output}"
|
||||
);
|
||||
assert!(
|
||||
output.contains("pid=1"),
|
||||
"strict child is not PID 1: {output}"
|
||||
);
|
||||
assert!(output.contains("NoNewPrivs:\t1"), "{output}");
|
||||
let cap_eff = output
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("CapEff:"))
|
||||
.unwrap_or("")
|
||||
.trim();
|
||||
assert!(
|
||||
cap_eff.bytes().all(|byte| byte == b'0'),
|
||||
"strict child kept capabilities: {cap_eff}"
|
||||
);
|
||||
let _ = fs::remove_dir_all(&project);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_child_cannot_read_host_files_but_reads_the_project() {
|
||||
let Some((helper, project, outside)) = setup() else {
|
||||
return;
|
||||
};
|
||||
let outcome = run(&helper, &project, &outside, "read");
|
||||
let output = text(&outcome);
|
||||
assert!(output.contains("read_project_allowed=OK"), "{output}");
|
||||
for key in ["read_etc_shadow", "read_root_key", "read_home_key"] {
|
||||
assert!(output.contains(&format!("{key}=DENIED")), "{key}: {output}");
|
||||
assert!(!output.contains(&format!("{key}=LEAK")), "{key}: {output}");
|
||||
}
|
||||
let _ = fs::remove_dir_all(&project);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_child_cannot_write_outside_or_into_the_project() {
|
||||
let Some((helper, project, outside)) = setup() else {
|
||||
return;
|
||||
};
|
||||
let outcome = run(&helper, &project, &outside, "write");
|
||||
let output = text(&outcome);
|
||||
assert!(output.contains("write_outside=DENIED"), "{output}");
|
||||
assert!(output.contains("write_project=DENIED"), "{output}");
|
||||
assert!(output.contains("write_tmp=WROTE"), "{output}");
|
||||
assert!(
|
||||
!outside.exists(),
|
||||
"strict child created a host file at {}",
|
||||
outside.display()
|
||||
);
|
||||
let _ = fs::remove_dir_all(&project);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_child_cannot_escape_via_proc_or_privileges() {
|
||||
let Some((helper, project, outside)) = setup() else {
|
||||
return;
|
||||
};
|
||||
let proc = run(&helper, &project, &outside, "proc");
|
||||
let output = text(&proc);
|
||||
assert!(output.contains("proc_pid1_root_etc=DENIED"), "{output}");
|
||||
assert!(
|
||||
output.contains("inherited_fds_above_stdio=NONE"),
|
||||
"{output}"
|
||||
);
|
||||
let privileges = run(&helper, &project, &outside, "priv");
|
||||
let output = text(&privileges);
|
||||
assert!(output.contains("setuid_root=DENIED"), "{output}");
|
||||
assert!(output.contains("mount_tmpfs=DENIED"), "{output}");
|
||||
assert!(!output.contains("setuid_root=OK"), "{output}");
|
||||
assert!(!output.contains("mount_tmpfs=OK"), "{output}");
|
||||
let _ = fs::remove_dir_all(&project);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_child_cannot_reach_the_network() {
|
||||
let Some((helper, project, outside)) = setup() else {
|
||||
return;
|
||||
};
|
||||
let outcome = run(&helper, &project, &outside, "net");
|
||||
let output = text(&outcome);
|
||||
assert!(!output.contains("CONNECTED"), "{output}");
|
||||
assert!(output.contains("socket_ipv4=DENIED"), "{output}");
|
||||
assert!(output.contains("socket_raw=DENIED"), "{output}");
|
||||
let _ = fs::remove_dir_all(&project);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_supervisor_enforces_fd_and_process_limits() {
|
||||
let Some((helper, project, outside)) = setup() else {
|
||||
return;
|
||||
};
|
||||
let fds = run(&helper, &project, &outside, "fds");
|
||||
let output = text(&fds);
|
||||
assert!(output.contains("fd_limit=BOUNDED"), "{output}");
|
||||
let count: usize = output
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("open_fds="))
|
||||
.and_then(|value| value.parse().ok())
|
||||
.unwrap_or(usize::MAX);
|
||||
assert!(count <= 64, "strict child opened {count} fds");
|
||||
|
||||
let forks = run(&helper, &project, &outside, "fork");
|
||||
let output = text(&forks);
|
||||
assert!(output.contains("process_limit=BOUNDED"), "{output}");
|
||||
let forked: usize = output
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("forked="))
|
||||
.and_then(|value| value.parse().ok())
|
||||
.unwrap_or(usize::MAX);
|
||||
assert!(forked < 200, "strict child forked {forked} processes");
|
||||
let _ = fs::remove_dir_all(&project);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_supervisor_enforces_memory_cpu_and_output_limits() {
|
||||
let Some((helper, project, outside)) = setup() else {
|
||||
return;
|
||||
};
|
||||
let memory = run(&helper, &project, &outside, "mem");
|
||||
let output = text(&memory);
|
||||
assert!(
|
||||
!output.contains("malloc_768m=OK"),
|
||||
"768 MiB allocation escaped the memory limit: {output}"
|
||||
);
|
||||
|
||||
let args = vec![OsString::from("cpu")];
|
||||
let command = StrictHostCommand {
|
||||
program: &helper,
|
||||
args: &args,
|
||||
project_root: &project,
|
||||
document: None,
|
||||
original_document: None,
|
||||
output_limit: 64 * 1024,
|
||||
timeout: Duration::from_secs(2),
|
||||
};
|
||||
let cpu = launch_strict_capture(&command).expect_err("CPU loop must be stopped");
|
||||
let message = cpu.to_string();
|
||||
assert!(
|
||||
message.contains("wall-clock") || message.contains("CPU"),
|
||||
"unexpected CPU failure: {message}"
|
||||
);
|
||||
|
||||
let output_limit = launch_strict_capture(&StrictHostCommand {
|
||||
program: &helper,
|
||||
args: &[OsString::from("output")],
|
||||
project_root: &project,
|
||||
document: None,
|
||||
original_document: None,
|
||||
output_limit: 64 * 1024,
|
||||
timeout: Duration::from_secs(3),
|
||||
})
|
||||
.expect("output helper should be captured, not spawn-failed");
|
||||
assert!(
|
||||
output_limit.signal == Some(libc::SIGXFSZ) || output_limit.exit_code != Some(0),
|
||||
"output limit was not enforced: signal={:?} exit={:?}",
|
||||
output_limit.signal,
|
||||
output_limit.exit_code
|
||||
);
|
||||
assert!(
|
||||
output_limit.stdout.len() <= 64 * 1024,
|
||||
"captured {} bytes beyond the limit",
|
||||
output_limit.stdout.len()
|
||||
);
|
||||
// The helper cannot always report after the file hits RLIMIT_FSIZE: the
|
||||
// report itself would exceed the limit. A non-zero exit, a terminating
|
||||
// signal, and a bounded capture are the observable contract.
|
||||
let written = output_limit
|
||||
.stdout
|
||||
.windows(b"output_4m=WRITTEN".len())
|
||||
.any(|window| window == b"output_4m=WRITTEN");
|
||||
assert!(!written, "the helper reported writing 4 MiB");
|
||||
let _ = fs::remove_dir_all(&project);
|
||||
}
|
||||
Reference in new issue
Block a user