//! Confinement of the decode and verify children (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` and `verify`), 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, SeccompCmpArgLen, SeccompCmpOp, SeccompCondition, SeccompFilter, SeccompRule, TargetArch, }; use crate::limits; /// Syscalls the decode and verify children make 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` there, and no `futex` appears in a /// single-threaded child. The verify child at the caps (2026-11-01) adds `brk`: mallocng /// grows its heap for the core's many small allocations; it only moves the program break, /// bounded by `RLIMIT_AS`. pub const ALLOWED_SYSCALLS: &[(&str, i64)] = &[ ("read", libc::SYS_read), ("write", libc::SYS_write), ("brk", libc::SYS_brk), ("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()?; disable_core_dumps()?; set_rlimits(limits)?; if seccomp { install_seccomp()?; } Ok(()) } /// No core dump of the child: a dump would hold the uploaded photo (personal data) and /// could fill the VPS disk (SIGABRT under `RLIMIT_AS`, SIGSYS, SIGXCPU all dump by default). /// `PR_SET_DUMPABLE 0` is the kernel-side stop, `RLIMIT_CORE 0` the belt. #[allow(unsafe_code)] fn disable_core_dumps() -> Result<(), SandboxError> { /// prctl reads its variadic arguments as unsigned long: the flag value and the /// arguments an option ignores are passed at that width. const NOT_DUMPABLE: libc::c_ulong = 0; const UNUSED: libc::c_ulong = 0; // SAFETY: prctl is a variadic FFI reading its extra arguments as unsigned long; for // PR_SET_DUMPABLE the kernel uses the first one (the new flag) and ignores the other // three, passed at that width: no pointer, no memory of this process involved, and only // this process's flag changes. The return code is checked below. let rc = unsafe { libc::prctl(libc::PR_SET_DUMPABLE, NOT_DUMPABLE, UNUSED, UNUSED, UNUSED) }; if rc != 0 { return Err(SandboxError::Rlimit("PR_SET_DUMPABLE".to_owned())); } // SAFETY: PR_GET_DUMPABLE reads this process's flag and ignores the extra arguments, // passed as unsigned-long zeros. The result is the flag (0 expected) or -1 on failure: // any non-zero value is refused below. let dumpable = unsafe { libc::prctl(libc::PR_GET_DUMPABLE, UNUSED, UNUSED, UNUSED, UNUSED) }; if dumpable != 0 { return Err(SandboxError::Rlimit(format!( "PR_GET_DUMPABLE = {dumpable}" ))); } rlimit::setrlimit(rlimit::Resource::CORE, 0, 0) .map_err(|error| SandboxError::Rlimit(format!("RLIMIT_CORE: {error}"))) } /// 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//status` text. pub fn thread_count(status: &str) -> Option { 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. /// /// Argument filters on the abort path and on `mmap`: `tkill`/`tgkill` may only send SIGABRT /// to this very process (the child is single-threaded, so tid == pid), never a signal to the /// keyed parent or a sibling; `mmap` may not map executable memory. pub fn build_filter() -> Result { let pid = u64::from(std::process::id()); let sigabrt = u64::try_from(libc::SIGABRT).unwrap_or(6); let prot_exec = u64::try_from(libc::PROT_EXEC).unwrap_or(4); let mut rules: BTreeMap> = ALLOWED_SYSCALLS .iter() .chain(ABORT_PATH_SYSCALLS) .map(|(_, number)| (*number, Vec::new())) .collect(); let seccomp_err = |error: seccompiler::BackendError| SandboxError::Seccomp(error.to_string()); let eq = |index: u8, value: u64| { SeccompCondition::new(index, SeccompCmpArgLen::Qword, SeccompCmpOp::Eq, value) .map_err(seccomp_err) }; rules.insert( libc::SYS_tkill, vec![SeccompRule::new(vec![eq(0, pid)?, eq(1, sigabrt)?]).map_err(seccomp_err)?], ); rules.insert( libc::SYS_tgkill, vec![ SeccompRule::new(vec![eq(0, pid)?, eq(1, pid)?, eq(2, sigabrt)?]) .map_err(seccomp_err)?, ], ); let no_exec = SeccompCondition::new( 2, SeccompCmpArgLen::Qword, SeccompCmpOp::MaskedEq(prot_exec), 0, ) .map_err(seccomp_err)?; rules.insert( libc::SYS_mmap, vec![SeccompRule::new(vec![no_exec]).map_err(seccomp_err)?], ); let filter = SeccompFilter::new( rules, SeccompAction::KillProcess, SeccompAction::Allow, target_arch()?, ) .map_err(|error| SandboxError::Seccomp(error.to_string()))?; filter.try_into().map_err(seccomp_err) } 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 { 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"); } } }