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:
cflmy committed 2026-11-20 15:01:49 +08:00
1 parent 9b001a33a5
commit b6fc18233d
22 files changed
+1886 -132

No files matched your search

+87 -9
View File
@@ -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"));