feat(worker): sandboxed decode child skeleton — rlimits, traced seccomp allowlist, pure-Rust decoders, libwebp in the child, parent RIFF check, musl image with test stage
This commit is contained in:
1 parent
2a38fa37b5
commit
3970cdca52
13 files changed
+1435
No files matched your search
@@ -0,0 +1,200 @@
|
||||
//! Confinement of the decode child (review Part IV.1), applied by the child itself from a
|
||||
//! single-threaded process before it reads any input. Three layers: an empty environment
|
||||
//! (cleared by the parent, checked in `decode`), rlimits on address space and CPU time, and
|
||||
//! a seccomp allowlist installed with TSYNC that kills the process on any other syscall.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt;
|
||||
|
||||
use seccompiler::{BpfProgram, SeccompAction, SeccompFilter, SeccompRule, TargetArch};
|
||||
|
||||
use crate::limits;
|
||||
|
||||
/// Syscalls the decode child makes once the filter is installed (static musl binary, x86_64).
|
||||
///
|
||||
/// Derived with `strace -f` over the fixture corpus at the caps (`crates/worker/scripts/
|
||||
/// derive-seccomp.sh`, run by the Dockerfile stage `test`, 2026-10-12: exactly these seven
|
||||
/// after the marker) and proven by running every fixture through the full sandbox. musl's
|
||||
/// mallocng used neither `brk` nor `mprotect`, and no `futex` appears in a single-threaded
|
||||
/// decode.
|
||||
pub const ALLOWED_SYSCALLS: &[(&str, i64)] = &[
|
||||
("read", libc::SYS_read),
|
||||
("write", libc::SYS_write),
|
||||
("mmap", libc::SYS_mmap),
|
||||
("munmap", libc::SYS_munmap),
|
||||
("mremap", libc::SYS_mremap),
|
||||
("exit_group", libc::SYS_exit_group),
|
||||
("getrandom", libc::SYS_getrandom),
|
||||
];
|
||||
|
||||
/// Syscalls of the abort path (`RLIMIT_AS` hit, allocation failure, panic = abort): what
|
||||
/// musl's `abort()` and Rust's alloc error handler need, proven by the sandbox test
|
||||
/// `the_address_space_limit_aborts_a_huge_allocation` (SIGABRT observed, not SIGSYS).
|
||||
pub const ABORT_PATH_SYSCALLS: &[(&str, i64)] = &[
|
||||
("rt_sigaction", libc::SYS_rt_sigaction),
|
||||
("rt_sigprocmask", libc::SYS_rt_sigprocmask),
|
||||
("getpid", libc::SYS_getpid),
|
||||
("gettid", libc::SYS_gettid),
|
||||
("tkill", libc::SYS_tkill),
|
||||
("tgkill", libc::SYS_tgkill),
|
||||
("exit", libc::SYS_exit),
|
||||
];
|
||||
|
||||
/// Resource limits of the child.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Limits {
|
||||
pub address_space_bytes: u64,
|
||||
pub cpu_seconds: u64,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
address_space_bytes: limits::CHILD_ADDRESS_SPACE_BYTES,
|
||||
cpu_seconds: limits::CHILD_CPU_SECONDS,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the sandbox could not be applied (the child exits `sandbox_failed`).
|
||||
#[derive(Debug)]
|
||||
pub enum SandboxError {
|
||||
NotSingleThreaded(usize),
|
||||
ProcStatusUnreadable,
|
||||
Rlimit(String),
|
||||
Seccomp(String),
|
||||
UnsupportedArchitecture,
|
||||
}
|
||||
|
||||
impl fmt::Display for SandboxError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::NotSingleThreaded(n) => write!(f, "process has {n} threads, expected 1"),
|
||||
Self::ProcStatusUnreadable => write!(f, "/proc/self/status unreadable"),
|
||||
Self::Rlimit(detail) => write!(f, "rlimit: {detail}"),
|
||||
Self::Seccomp(detail) => write!(f, "seccomp: {detail}"),
|
||||
Self::UnsupportedArchitecture => write!(f, "no seccomp filter for this architecture"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for SandboxError {}
|
||||
|
||||
/// Applies the three layers. `seccomp = false` keeps only the rlimits (the strace
|
||||
/// derivation run of the test stage); a release child always passes `true`.
|
||||
pub fn apply(limits: &Limits, seccomp: bool) -> Result<(), SandboxError> {
|
||||
ensure_single_thread()?;
|
||||
set_rlimits(limits)?;
|
||||
if seccomp {
|
||||
install_seccomp()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every syscall name the filter allows, for the derivation script and the tests.
|
||||
pub fn allowed_names() -> Vec<&'static str> {
|
||||
ALLOWED_SYSCALLS
|
||||
.iter()
|
||||
.chain(ABORT_PATH_SYSCALLS)
|
||||
.map(|(name, _)| *name)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Parses the `Threads:` line of a `/proc/<pid>/status` text.
|
||||
pub fn thread_count(status: &str) -> Option<usize> {
|
||||
status
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("Threads:"))
|
||||
.and_then(|value| value.trim().parse().ok())
|
||||
}
|
||||
|
||||
fn ensure_single_thread() -> Result<(), SandboxError> {
|
||||
let status = std::fs::read_to_string("/proc/self/status")
|
||||
.map_err(|_| SandboxError::ProcStatusUnreadable)?;
|
||||
match thread_count(&status) {
|
||||
Some(1) => Ok(()),
|
||||
Some(n) => Err(SandboxError::NotSingleThreaded(n)),
|
||||
None => Err(SandboxError::ProcStatusUnreadable),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_rlimits(limits: &Limits) -> Result<(), SandboxError> {
|
||||
rlimit::setrlimit(
|
||||
rlimit::Resource::AS,
|
||||
limits.address_space_bytes,
|
||||
limits.address_space_bytes,
|
||||
)
|
||||
.map_err(|error| SandboxError::Rlimit(format!("RLIMIT_AS: {error}")))?;
|
||||
// Soft limit first (SIGXCPU, observable), hard limit two seconds later (SIGKILL): with
|
||||
// soft == hard the kernel checks the hard limit first and the child dies by SIGKILL,
|
||||
// indistinguishable from the parent's own deadline kill.
|
||||
rlimit::setrlimit(
|
||||
rlimit::Resource::CPU,
|
||||
limits.cpu_seconds,
|
||||
limits.cpu_seconds + 2,
|
||||
)
|
||||
.map_err(|error| SandboxError::Rlimit(format!("RLIMIT_CPU: {error}")))
|
||||
}
|
||||
|
||||
/// Builds the BPF program: allow the listed syscalls, kill the process on anything else.
|
||||
pub fn build_filter() -> Result<BpfProgram, SandboxError> {
|
||||
let rules: BTreeMap<i64, Vec<SeccompRule>> = ALLOWED_SYSCALLS
|
||||
.iter()
|
||||
.chain(ABORT_PATH_SYSCALLS)
|
||||
.map(|(_, number)| (*number, Vec::new()))
|
||||
.collect();
|
||||
let filter = SeccompFilter::new(
|
||||
rules,
|
||||
SeccompAction::KillProcess,
|
||||
SeccompAction::Allow,
|
||||
target_arch()?,
|
||||
)
|
||||
.map_err(|error| SandboxError::Seccomp(error.to_string()))?;
|
||||
filter
|
||||
.try_into()
|
||||
.map_err(|error: seccompiler::BackendError| SandboxError::Seccomp(error.to_string()))
|
||||
}
|
||||
|
||||
fn install_seccomp() -> Result<(), SandboxError> {
|
||||
let program = build_filter()?;
|
||||
seccompiler::apply_filter_all_threads(&program)
|
||||
.map_err(|error| SandboxError::Seccomp(error.to_string()))
|
||||
}
|
||||
|
||||
fn target_arch() -> Result<TargetArch, SandboxError> {
|
||||
if cfg!(target_arch = "x86_64") {
|
||||
Ok(TargetArch::x86_64)
|
||||
} else if cfg!(target_arch = "aarch64") {
|
||||
Ok(TargetArch::aarch64)
|
||||
} else {
|
||||
Err(SandboxError::UnsupportedArchitecture)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn thread_count_reads_the_status_line() {
|
||||
assert_eq!(thread_count("Name:\tx\nThreads:\t1\nSigQ:\t0/1\n"), Some(1));
|
||||
assert_eq!(thread_count("Threads:\t12\n"), Some(12));
|
||||
assert_eq!(thread_count("Name:\tx\n"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_filter_compiles() {
|
||||
let program = build_filter();
|
||||
assert!(program.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_file_or_process_syscall_is_allowed() {
|
||||
let names = allowed_names();
|
||||
for forbidden in [
|
||||
"open", "openat", "execve", "clone", "fork", "socket", "ptrace",
|
||||
] {
|
||||
assert!(!names.contains(&forbidden), "{forbidden} must stay denied");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user