From dc283c1d6c206245c9e0dafec8c426fe1423bdef Mon Sep 17 00:00:00 2001 From: Emilien Macchi Date: Tue, 3 Nov 2026 00:00:48 -0500 Subject: [PATCH 1/4] refactor(sandbox): prebuild seccomp filters before fork The workload pre_exec hooks ran in the forked child of a multithreaded process and compiled both seccomp filters there: BTreeMap rule building, seccompiler BPF compilation, and a debug! callsite whose output landed on the workload's own pipe or PTY. Post-fork allocation and tracing can deadlock when another thread holds the allocator or subscriber lock at fork time. Split seccomp::apply into a parent-side prepare(policy) that compiles the main and compatibility filters into BpfPrograms (with the socket-domain debug log moved into it), and a non-allocating PreparedSeccomp::install for the child that keeps set_no_new_privs and the filter order verbatim (compatibility first, then main). PreparedSandbox now carries the prebuilt programs instead of the SandboxPolicy it kept only so the child could rebuild them, so child-side compilation cannot be reintroduced. Bundle the prepared sandbox and the child self-protection program into a ChildSandboxInstall struct that replaces the cfg-gated positional parameters of pty::install_pre_exec* and is consumed by an install-only enforce in the forked child. seccomp::apply is removed with no remaining caller; the fresh-process paths keep using prepare plus install through sandbox::linux::enforce. Add a behavioral fork test that compiles the filters parent-side, installs them in the forked child in the enforce_capability_free order, and probes one role-specific outcome per filter (memfd_create EPERM for the main filter, pidfd_open ENOSYS for the compatibility filter, close_range with CLOSE_RANGE_UNSHARE EPERM for the child self-protection filter). Part of #5180 Signed-off-by: Emilien Macchi --- crates/openshell-sandbox/src/boundary_exec.rs | 8 +- crates/openshell-sandbox/src/process.rs | 20 +- crates/openshell-sandbox/src/pty.rs | 33 +--- .../src/sandbox/linux/mod.rs | 69 +++++-- .../src/sandbox/linux/seccomp.rs | 173 +++++++++++++++--- 5 files changed, 226 insertions(+), 77 deletions(-) diff --git a/crates/openshell-sandbox/src/boundary_exec.rs b/crates/openshell-sandbox/src/boundary_exec.rs index 8841048ba7..18c8da93c2 100644 --- a/crates/openshell-sandbox/src/boundary_exec.rs +++ b/crates/openshell-sandbox/src/boundary_exec.rs @@ -258,9 +258,7 @@ impl LocalBoundaryExec { self.policy.clone(), effective_workdir.map(str::to_string), #[cfg(target_os = "linux")] - prepared, - #[cfg(target_os = "linux")] - child_hardening, + crate::sandbox::linux::ChildSandboxInstall::new(prepared, child_hardening), ) .map_err(|error| BackendError::Process(error.to_string()))?; #[cfg(target_os = "linux")] @@ -398,9 +396,7 @@ impl LocalBoundaryExec { effective_workdir.map(str::to_string), slave_fd, #[cfg(target_os = "linux")] - prepared, - #[cfg(target_os = "linux")] - child_hardening, + crate::sandbox::linux::ChildSandboxInstall::new(prepared, child_hardening), ) .map_err(|error| BackendError::Process(error.to_string()))?; #[cfg(target_os = "linux")] diff --git a/crates/openshell-sandbox/src/process.rs b/crates/openshell-sandbox/src/process.rs index 4967d20086..db82d4afdc 100644 --- a/crates/openshell-sandbox/src/process.rs +++ b/crates/openshell-sandbox/src/process.rs @@ -616,18 +616,22 @@ impl ProcessHandle { let prepared_sandbox = prepare_child_sandbox(policy, workspace.root(), &runtime_read_only) .map_err(|err| miette::miette!("Failed to prepare sandbox: {err}"))?; #[cfg(target_os = "linux")] - let mut child_hardening = crate::linux::child_seccomp::prepare(std::process::id()) + let child_hardening = crate::linux::child_seccomp::prepare(std::process::id()) .map_err(|error| miette::miette!("prepare child self-protection filter: {error}"))?; + #[cfg(target_os = "linux")] + let child_install = + sandbox::linux::ChildSandboxInstall::new(prepared_sandbox, child_hardening); // Set up process group for signal handling (non-interactive mode only). // In interactive mode, we inherit the parent's process group to maintain // proper terminal control for shells and interactive programs. // SAFETY: pre_exec runs after fork but before exec in the child process. // setpgid and setns are async-signal-safe and safe to call in this context. { - // Wrap in Option so we can .take() it out of the FnMut closure. + // Rebind as mut so the FnMut closure can run the install, which + // takes the prepared sandbox out of its Option. // pre_exec is only called once (after fork, before exec). #[cfg(target_os = "linux")] - let mut prepared_sandbox = prepared_sandbox; + let mut child_install = child_install; #[allow(unsafe_code)] // SAFETY: pre_exec only registers the hook; the closure runs // post-fork and pre-exec in the child process, never in the @@ -646,13 +650,13 @@ impl ProcessHandle { harden_child_process().map_err(|err| std::io::Error::other(err.to_string()))?; // Phase 2 (as unprivileged user): Enforce the prepared - // Landlock ruleset via restrict_self() + apply seccomp. + // Landlock ruleset via restrict_self() and install the + // prebuilt seccomp filters. // restrict_self() does not require root. #[cfg(target_os = "linux")] - if let Some(prepared) = prepared_sandbox.take() { - sandbox::linux::enforce_capability_free(prepared, &mut child_hardening) - .map_err(|err| std::io::Error::other(err.to_string()))?; - } + child_install + .enforce() + .map_err(|err| std::io::Error::other(err.to_string()))?; Ok(()) }); diff --git a/crates/openshell-sandbox/src/pty.rs b/crates/openshell-sandbox/src/pty.rs index 003bfc62cf..2187ebf96d 100644 --- a/crates/openshell-sandbox/src/pty.rs +++ b/crates/openshell-sandbox/src/pty.rs @@ -60,13 +60,10 @@ pub fn install_pre_exec( policy: SandboxPolicy, _workdir: Option, slave_fd: RawFd, - #[cfg(target_os = "linux")] prepared: Option, - #[cfg(target_os = "linux")] child_hardening: crate::linux::child_seccomp::ChildHardeningProgram, + #[cfg(target_os = "linux")] install: crate::sandbox::linux::ChildSandboxInstall, ) -> anyhow::Result<()> { #[cfg(target_os = "linux")] - let mut prepared = prepared; - #[cfg(target_os = "linux")] - let mut child_hardening = child_hardening; + let mut install = install; // SAFETY: all allocations and policy compilation happened before spawn; // the hook performs only the audited child transition. unsafe { @@ -76,9 +73,7 @@ pub fn install_pre_exec( enter_sandbox( &policy, #[cfg(target_os = "linux")] - prepared.take(), - #[cfg(target_os = "linux")] - &mut child_hardening, + &mut install, ) }); } @@ -94,13 +89,10 @@ pub fn install_pre_exec_no_pty( command: &mut Command, policy: SandboxPolicy, _workdir: Option, - #[cfg(target_os = "linux")] prepared: Option, - #[cfg(target_os = "linux")] child_hardening: crate::linux::child_seccomp::ChildHardeningProgram, + #[cfg(target_os = "linux")] install: crate::sandbox::linux::ChildSandboxInstall, ) -> anyhow::Result<()> { #[cfg(target_os = "linux")] - let mut prepared = prepared; - #[cfg(target_os = "linux")] - let mut child_hardening = child_hardening; + let mut install = install; // SAFETY: all allocations and policy compilation happened before spawn; // the hook performs only the audited child transition. unsafe { @@ -111,9 +103,7 @@ pub fn install_pre_exec_no_pty( enter_sandbox( &policy, #[cfg(target_os = "linux")] - prepared.take(), - #[cfg(target_os = "linux")] - &mut child_hardening, + &mut install, ) }); } @@ -122,18 +112,15 @@ pub fn install_pre_exec_no_pty( fn enter_sandbox( policy: &SandboxPolicy, - #[cfg(target_os = "linux")] prepared: Option, - #[cfg(target_os = "linux")] - child_hardening: &mut crate::linux::child_seccomp::ChildHardeningProgram, + #[cfg(target_os = "linux")] install: &mut crate::sandbox::linux::ChildSandboxInstall, ) -> std::io::Result<()> { crate::process::harden_child_process() .map_err(|error| std::io::Error::other(error.to_string()))?; #[cfg(target_os = "linux")] - if let Some(prepared) = prepared { - crate::sandbox::linux::enforce_capability_free(prepared, child_hardening) - .map_err(|error| std::io::Error::other(error.to_string()))?; - } + install + .enforce() + .map_err(|error| std::io::Error::other(error.to_string()))?; #[cfg(not(target_os = "linux"))] crate::sandbox::apply(policy, None) diff --git a/crates/openshell-sandbox/src/sandbox/linux/mod.rs b/crates/openshell-sandbox/src/sandbox/linux/mod.rs index ef68c81f5c..e73458b4b8 100644 --- a/crates/openshell-sandbox/src/sandbox/linux/mod.rs +++ b/crates/openshell-sandbox/src/sandbox/linux/mod.rs @@ -14,36 +14,41 @@ use std::sync::Once; pub use landlock::require_abi as require_landlock_abi; /// Opaque handle to a prepared-but-not-yet-enforced sandbox. -/// Holds the Landlock ruleset with `PathFds` opened before child exec. +/// Holds the Landlock ruleset with `PathFds` opened before child exec, +/// plus both seccomp filters already compiled to BPF programs. pub struct PreparedSandbox { landlock: Vec, - policy: SandboxPolicy, + seccomp: seccomp::PreparedSeccomp, } /// Phase 1: Prepare sandbox restrictions with strict path opening. /// /// Opens configured paths as the calling identity and handles failures according -/// to the policy's Landlock compatibility mode. +/// to the policy's Landlock compatibility mode. Both seccomp filters are +/// compiled here as well, so the child never builds them after `fork`. /// The capability-free launch path uses [`prepare_capability_free`] instead. pub fn prepare(policy: &SandboxPolicy, workdir: Option<&str>) -> Result { let landlock = landlock::prepare(policy, workdir)?; + let seccomp = seccomp::prepare(policy)?; Ok(PreparedSandbox { landlock: landlock.into_iter().collect(), - policy: policy.clone(), + seccomp, }) } /// Phase 1 for already-unprivileged workloads. /// -/// Opens Landlock `PathFds` as the current workload UID. +/// Opens Landlock `PathFds` as the current workload UID and compiles the +/// seccomp filters. pub fn prepare_current_user( policy: &SandboxPolicy, workdir: Option<&str>, ) -> Result { let landlock = landlock::prepare_current_user(policy, workdir)?; + let seccomp = seccomp::prepare(policy)?; Ok(PreparedSandbox { landlock: landlock.into_iter().collect(), - policy: policy.clone(), + seccomp, }) } @@ -61,23 +66,21 @@ pub fn prepare_capability_free( ) -> Result { let baseline = landlock::prepare_capability_free_baseline()?; let user = landlock::prepare_current_user(policy, workdir)?; + let seccomp = seccomp::prepare(policy)?; let mut landlock = vec![baseline]; landlock.extend(user); - Ok(PreparedSandbox { - landlock, - policy: policy.clone(), - }) + Ok(PreparedSandbox { landlock, seccomp }) } /// Phase 2: Enforce prepared sandbox restrictions in the child before exec. /// -/// Calls `restrict_self()` for Landlock and applies seccomp filters. -/// Neither operation requires root privileges. +/// Calls `restrict_self()` for Landlock and installs the prebuilt seccomp +/// filters. Neither operation requires root privileges. pub fn enforce(prepared: PreparedSandbox) -> Result<()> { for ruleset in prepared.landlock { landlock::enforce(ruleset)?; } - seccomp::apply(&prepared.policy)?; + prepared.seccomp.install()?; Ok(()) } @@ -96,10 +99,48 @@ pub fn enforce_capability_free( child_hardening .install() .map_err(|error| miette::miette!("install child self-protection filter: {error}"))?; - seccomp::apply(&prepared.policy)?; + prepared.seccomp.install()?; Ok(()) } +/// Everything a spawned workload child installs between fork and exec. +/// +/// Bundles the prepared Landlock rulesets and prebuilt seccomp filters +/// ([`PreparedSandbox`]) with the same-UID child self-protection program so a +/// spawn surface cannot wire one without the other. All compilation and path +/// opening happens at construction, parent-side; the forked child only +/// installs. +pub struct ChildSandboxInstall { + prepared: Option, + child_hardening: crate::linux::child_seccomp::ChildHardeningProgram, +} + +impl ChildSandboxInstall { + /// Bundle a prepared sandbox (if any) with its child hardening program. + #[must_use] + pub fn new( + prepared: Option, + child_hardening: crate::linux::child_seccomp::ChildHardeningProgram, + ) -> Self { + Self { + prepared, + child_hardening, + } + } + + /// Enforce the bundled restrictions in the forked child before exec. + /// + /// A no-op when no sandbox was prepared, matching the previous optional + /// plumbing: the child hardening program is only installed alongside a + /// prepared sandbox. + pub(crate) fn enforce(&mut self) -> Result<()> { + let Some(prepared) = self.prepared.take() else { + return Ok(()); + }; + enforce_capability_free(prepared, &mut self.child_hardening) + } +} + /// Apply the supervisor seccomp prelude after privileged bootstrap completes. pub fn apply_supervisor_prelude() -> Result<()> { seccomp::apply_supervisor_prelude() diff --git a/crates/openshell-sandbox/src/sandbox/linux/seccomp.rs b/crates/openshell-sandbox/src/sandbox/linux/seccomp.rs index 2dbdb53428..0133628dac 100644 --- a/crates/openshell-sandbox/src/sandbox/linux/seccomp.rs +++ b/crates/openshell-sandbox/src/sandbox/linux/seccomp.rs @@ -72,15 +72,46 @@ pub fn apply_supervisor_prelude() -> Result<()> { Ok(()) } -pub fn apply(policy: &SandboxPolicy) -> Result<()> { +/// Both sandbox seccomp filters, compiled before `fork`. +/// +/// The forked child only runs [`PreparedSeccomp::install`]; all rule +/// building, BPF compilation, and logging happen parent-side. +pub struct PreparedSeccomp { + main: seccompiler::BpfProgram, + compatibility: seccompiler::BpfProgram, +} + +/// Compile both sandbox seccomp filters parent-side. +/// +/// This is the pre-fork half of the spawn path; the child installs the +/// returned programs with [`PreparedSeccomp::install`]. +pub fn prepare(policy: &SandboxPolicy) -> Result { let allow_inet = matches!(policy.network.mode, NetworkMode::Proxy | NetworkMode::Allow); - let main_filter = build_filter(allow_inet)?; - let compatibility_filter = build_compatibility_filter()?; + Ok(PreparedSeccomp { + main: build_filter(allow_inet)?, + compatibility: build_compatibility_filter()?, + }) +} - set_no_new_privs()?; - apply_runtime_filters(&main_filter, &compatibility_filter)?; +impl PreparedSeccomp { + /// Install the prebuilt filters in the required order. + /// + /// This runs in the forked child before `exec` and must stay free of + /// allocation, tracing, and OCSF emission on the success path. Only the + /// hard-error return may allocate (std's `pre_exec` machinery allocates + /// on `Err` anyway). + pub fn install(&self) -> Result<()> { + set_no_new_privs()?; + apply_runtime_filters(&self.main, &self.compatibility) + } +} - Ok(()) +fn allowed_socket_domains(allow_inet: bool) -> Vec { + let mut domains = vec![libc::AF_UNIX, libc::AF_NETLINK]; + if allow_inet { + domains.extend([libc::AF_INET, libc::AF_INET6]); + } + domains } fn build_filter(allow_inet: bool) -> Result { @@ -194,10 +225,7 @@ fn build_filter_rules(allow_inet: bool) -> Result // --- Socket domain allowlist --- // AF_NETLINK is narrowed further below: only NETLINK_ROUTE (protocol 0) // is allowed, for getifaddrs(3). - let mut allowed_domains = vec![libc::AF_UNIX, libc::AF_NETLINK]; - if allow_inet { - allowed_domains.extend([libc::AF_INET, libc::AF_INET6]); - } + let allowed_domains = allowed_socket_domains(allow_inet); debug!(?allowed_domains, "Restricting socket domains via seccomp"); add_socket_domain_allowlist(&mut rules, libc::SYS_socket, &allowed_domains)?; // socketpair(2) is only meaningful for AF_UNIX here; other families either @@ -389,10 +417,21 @@ fn add_masked_arg_rule( )] mod tests { use super::*; + use openshell_core::policy::{FilesystemPolicy, LandlockPolicy, NetworkPolicy, ProcessPolicy}; // These tests cover both filter construction (rule map shape and BPF // compilation) and selected runtime behavior on Linux via forked children. + fn test_policy(mode: NetworkMode) -> SandboxPolicy { + SandboxPolicy { + version: 1, + filesystem: FilesystemPolicy::default(), + network: NetworkPolicy { mode, proxy: None }, + landlock: LandlockPolicy::default(), + process: ProcessPolicy::default(), + } + } + #[test] fn build_filter_proxy_mode_compiles() { let filter = build_filter(true); @@ -630,12 +669,8 @@ mod tests { ); } - unsafe fn install_runtime_filters_in_child( - main_filter: &seccompiler::BpfProgram, - compatibility_filter: &seccompiler::BpfProgram, - ) { - libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); - if let Err(err) = apply_runtime_filters(main_filter, compatibility_filter) { + unsafe fn install_runtime_filters_in_child(prepared: &PreparedSeccomp) { + if let Err(err) = prepared.install() { let msg = format!("failed to install runtime seccomp filters: {err}\n"); libc::write(2, msg.as_ptr().cast(), msg.len()); libc::_exit(1); @@ -721,15 +756,14 @@ mod tests { #[test] fn behavioral_clone3_returns_enosys() { // clone3 uses a separate filter that returns ENOSYS (not EPERM) so - // glibc falls back to clone. - let main_filter = build_filter(true).unwrap(); - let compatibility_filter = build_compatibility_filter().unwrap(); - // Apply in the same order as apply(): compatibility filter first, main filter second. + // glibc falls back to clone. Compile parent-side with prepare() and + // install in the forked child, as the production spawn path does. + let prepared = prepare(&test_policy(NetworkMode::Proxy)).unwrap(); let pid = unsafe { libc::fork() }; assert!(pid >= 0, "fork failed"); if pid == 0 { unsafe { - install_runtime_filters_in_child(&main_filter, &compatibility_filter); + install_runtime_filters_in_child(&prepared); let ret = libc::syscall(libc::SYS_clone3, 0 as libc::c_ulong, 0 as libc::c_ulong); let errno = *libc::__errno_location(); if ret == -1 && errno == libc::ENOSYS { @@ -757,15 +791,14 @@ mod tests { #[test] fn behavioral_third_filter_install_blocked_after_startup() { - let main_filter = build_filter(true).unwrap(); - let compatibility_filter = build_compatibility_filter().unwrap(); + let prepared = prepare(&test_policy(NetworkMode::Proxy)).unwrap(); let third_filter = build_compatibility_filter().unwrap(); let pid = unsafe { libc::fork() }; assert!(pid >= 0, "fork failed"); if pid == 0 { unsafe { - install_runtime_filters_in_child(&main_filter, &compatibility_filter); + install_runtime_filters_in_child(&prepared); match apply_filter(&third_filter) { Err(seccompiler::Error::Seccomp(e)) if e.raw_os_error() == Some(libc::EPERM) => @@ -795,6 +828,92 @@ mod tests { ); } + #[test] + fn behavioral_prepared_filters_install_in_forked_child() { + // Reproduces the production child path for #5180: both filters are + // compiled in the parent via prepare(), and the forked child only + // installs them, child self-protection first, in the + // enforce_capability_free order. Each probe targets one filter's + // unique outcome so a subset install or an order swap fails the + // test instead of merely confirming "some filter is active". + const CLOSE_RANGE_UNSHARE: libc::c_ulong = 1 << 1; + let prepared = prepare(&test_policy(NetworkMode::Proxy)).unwrap(); + let mut child_hardening = crate::linux::child_seccomp::prepare(std::process::id()) + .expect("prepare child self-protection filter"); + + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed"); + if pid == 0 { + unsafe { + if let Err(err) = child_hardening.install() { + let msg = format!("failed to install child self-protection filter: {err}\n"); + libc::write(2, msg.as_ptr().cast(), msg.len()); + libc::_exit(1); + } + if let Err(err) = prepared.install() { + let msg = format!("failed to install prepared seccomp filters: {err}\n"); + libc::write(2, msg.as_ptr().cast(), msg.len()); + libc::_exit(1); + } + + // Main filter: memfd_create is blocked with EPERM only by + // the ordinary workload filter. + let ret = libc::syscall( + libc::SYS_memfd_create, + 0 as libc::c_ulong, + 0 as libc::c_ulong, + ); + let errno = *libc::__errno_location(); + if ret != -1 || errno != libc::EPERM { + let msg = format!( + "memfd_create: expected EPERM from the main filter, got ret={ret} errno={errno}\n" + ); + libc::write(2, msg.as_ptr().cast(), msg.len()); + libc::_exit(1); + } + + // Compatibility filter: pidfd_open is reported unavailable + // with ENOSYS, an errno the EPERM main filter cannot produce. + let ret = + libc::syscall(libc::SYS_pidfd_open, 1 as libc::c_ulong, 0 as libc::c_ulong); + let errno = *libc::__errno_location(); + if ret != -1 || errno != libc::ENOSYS { + let msg = format!( + "pidfd_open: expected ENOSYS from the compatibility filter, got ret={ret} errno={errno}\n" + ); + libc::write(2, msg.as_ptr().cast(), msg.len()); + libc::_exit(1); + } + + // Child self-protection filter: close_range with + // CLOSE_RANGE_UNSHARE is blocked with EPERM only here. + let ret = libc::syscall( + libc::SYS_close_range, + 3 as libc::c_ulong, + libc::c_ulong::from(u32::MAX), + CLOSE_RANGE_UNSHARE, + ); + let errno = *libc::__errno_location(); + if ret != -1 || errno != libc::EPERM { + let msg = format!( + "close_range(CLOSE_RANGE_UNSHARE): expected EPERM from the child self-protection filter, got ret={ret} errno={errno}\n" + ); + libc::write(2, msg.as_ptr().cast(), msg.len()); + libc::_exit(1); + } + + libc::_exit(0); + } + } + + let mut status: libc::c_int = 0; + unsafe { libc::waitpid(pid, &mut status, 0) }; + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "prepared filters must install in the forked child with every filter's role intact" + ); + } + #[test] fn behavioral_netlink_route_allowed() { // socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE=0) must succeed (not blocked). @@ -875,8 +994,10 @@ mod tests { const AF_KCM: i32 = 41; const AF_SMC: i32 = 43; if std::env::var_os(CHILD_MARKER).is_some() { - set_no_new_privs().expect("set no_new_privs"); - apply_filter(&build_filter(true).unwrap()).expect("apply proxy-mode filter"); + prepare(&test_policy(NetworkMode::Proxy)) + .expect("prepare proxy-mode sandbox filters") + .install() + .expect("install proxy-mode sandbox filters"); let create = |domain: i32, kind: socket2::Type| { socket2::Socket::new(socket2::Domain::from(domain), kind, None) .map(drop) From e10b1978424929d129719aca9b9c428e9cfbc769 Mon Sep 17 00:00:00 2001 From: Emilien Macchi Date: Tue, 3 Nov 2026 00:55:53 -0500 Subject: [PATCH 2/4] fix(sandbox): report Landlock best-effort failure from the parent On a best-effort Landlock failure, landlock::enforce emitted an OCSF DetectionFinding from the forked child between fork and exec, where format! allocations and the OCSF thread-local plus tracing dispatch can deadlock after fork of a multithreaded process, and where the emission was already unreliable because the child has no working tracing subscriber. Return the failure from landlock::enforce as a LandlockOutcome instead: Enforced, or Degraded with a cause extracted without allocation (the restrict_self errno, or an explicit NoErrno sentinel when the error chain carries no io::Error; the landlock crate's EINVAL-defaulting helper is deliberately avoided so the sentinel cannot conflate with a genuine EINVAL). hard_requirement failures keep returning Err through the existing spawn-error path. Spawn surfaces create a LandlockReportPipe (both ends CLOEXEC) before fork. The pre_exec closure captures only the raw write fd, never an OwnedFd: the Command moves onto the serialized workload launcher thread, and an owned write end dropped there would hold EOF hostage to launcher-thread scheduling. The forked child writes one fixed-size, async-signal-safe record per degraded ruleset before installing the child self-protection filter, so the write cannot block on the seccomp broker; the parent drops its own write end right after spawn returns (on success or failure) and drains to EOF on the spawning thread, emitting one finding per record through a builder shared with the fresh-process enforce path. Best-effort spawns still succeed. The report fd is a required parameter of ChildSandboxInstall, so a spawn surface that forgets to plumb it is a compile error. The finding keeps its uid, title, and High severity; the message and description are now errno-based because the child cannot format the landlock error across the pipe. Part of #5180 Signed-off-by: Emilien Macchi --- crates/openshell-sandbox/Cargo.toml | 2 +- crates/openshell-sandbox/src/boundary_exec.rs | 88 +- crates/openshell-sandbox/src/process.rs | 97 +- .../src/sandbox/linux/landlock.rs | 853 +++++++++++++++++- .../src/sandbox/linux/mod.rs | 305 ++++++- 5 files changed, 1285 insertions(+), 60 deletions(-) diff --git a/crates/openshell-sandbox/Cargo.toml b/crates/openshell-sandbox/Cargo.toml index 0ccc79af88..be0792b78c 100644 --- a/crates/openshell-sandbox/Cargo.toml +++ b/crates/openshell-sandbox/Cargo.toml @@ -67,7 +67,7 @@ tracing-subscriber = { workspace = true } [target.'cfg(unix)'.dependencies] libc = "0.2" -rustix = { workspace = true, features = ["termios", "fs", "process", "net", "event"] } +rustix = { workspace = true, features = ["termios", "fs", "process", "net", "event", "pipe"] } russh-sftp = "3.0" uuid = { workspace = true } diff --git a/crates/openshell-sandbox/src/boundary_exec.rs b/crates/openshell-sandbox/src/boundary_exec.rs index 18c8da93c2..693f2bc416 100644 --- a/crates/openshell-sandbox/src/boundary_exec.rs +++ b/crates/openshell-sandbox/src/boundary_exec.rs @@ -252,21 +252,32 @@ impl LocalBoundaryExec { #[cfg(target_os = "linux")] let child_hardening = crate::linux::child_seccomp::prepare(std::process::id()) .map_err(|error| BackendError::Process(error.to_string()))?; + #[cfg(target_os = "linux")] + let landlock_report = crate::sandbox::linux::LandlockReportPipe::new() + .map_err(|error| BackendError::Process(error.to_string()))?; + #[cfg(target_os = "linux")] + let landlock_report_fd = landlock_report.child_fd(); crate::pty::install_dedicated_process_group(&mut command); crate::pty::install_pre_exec_no_pty( &mut command, self.policy.clone(), effective_workdir.map(str::to_string), #[cfg(target_os = "linux")] - crate::sandbox::linux::ChildSandboxInstall::new(prepared, child_hardening), + crate::sandbox::linux::ChildSandboxInstall::new( + prepared, + child_hardening, + landlock_report_fd, + ), ) .map_err(|error| BackendError::Process(error.to_string()))?; #[cfg(target_os = "linux")] let mut child_registry = crate::managed_children::lock(); #[cfg(target_os = "linux")] - let mut child = - crate::process::spawn_std_command_with_workload_launcher(&self.launcher, command) - .map_err(|error| BackendError::Process(error.to_string()))?; + let mut child = landlock_report + .spawn_and_drain(|| { + crate::process::spawn_std_command_with_workload_launcher(&self.launcher, command) + }) + .map_err(|error| BackendError::Process(error.to_string()))?; #[cfg(not(target_os = "linux"))] let mut child = command .spawn() @@ -390,21 +401,32 @@ impl LocalBoundaryExec { #[cfg(target_os = "linux")] let child_hardening = crate::linux::child_seccomp::prepare(std::process::id()) .map_err(|error| BackendError::Process(error.to_string()))?; + #[cfg(target_os = "linux")] + let landlock_report = crate::sandbox::linux::LandlockReportPipe::new() + .map_err(|error| BackendError::Process(error.to_string()))?; + #[cfg(target_os = "linux")] + let landlock_report_fd = landlock_report.child_fd(); crate::pty::install_pre_exec( &mut command, self.policy.clone(), effective_workdir.map(str::to_string), slave_fd, #[cfg(target_os = "linux")] - crate::sandbox::linux::ChildSandboxInstall::new(prepared, child_hardening), + crate::sandbox::linux::ChildSandboxInstall::new( + prepared, + child_hardening, + landlock_report_fd, + ), ) .map_err(|error| BackendError::Process(error.to_string()))?; #[cfg(target_os = "linux")] let mut child_registry = crate::managed_children::lock(); #[cfg(target_os = "linux")] - let mut child = - crate::process::spawn_std_command_with_workload_launcher(&self.launcher, command) - .map_err(|error| BackendError::Process(error.to_string()))?; + let mut child = landlock_report + .spawn_and_drain(|| { + crate::process::spawn_std_command_with_workload_launcher(&self.launcher, command) + }) + .map_err(|error| BackendError::Process(error.to_string()))?; #[cfg(not(target_os = "linux"))] let mut child = command .spawn() @@ -1362,6 +1384,56 @@ mod tests { assert_eq!(runtime.registered_process_group_count(), 0); } + /// A failed spawn must return promptly with the Landlock report drain + /// already run. Every spawn surface drains through + /// `LandlockReportPipe::spawn_and_drain`, which drops the parent's write + /// end and drains on both spawn outcomes before the error is mapped, so + /// the error path cannot stall on a never-EOF pipe (a drain that never + /// drops the parent's write end blocks forever). Forcing a real + /// `restrict_self` degradation through this public + /// spawn API is not possible — the blocking seccomp filter used in the + /// landlock tests can only be installed in a forked child — so this pins + /// the closest observable contract: both spawn surfaces return the spawn + /// error instead of hanging. Each exec runs on a dedicated thread waited + /// with a channel timeout, so a stalled drain fails the test cleanly + /// instead of deadlocking the test runtime's shutdown. + #[test] + fn failed_exec_drains_the_landlock_report_pipe_before_returning() { + for pty in [false, true] { + let mut executor = executor(); + // Best-effort Landlock over a real path, so the forked child + // prepares and enforces a ruleset before the exec failure. + let root = tempfile::tempdir().unwrap(); + executor.policy.filesystem.read_only = vec![root.path().to_path_buf()]; + executor.policy.landlock.compatibility = + openshell_core::policy::LandlockCompatibility::BestEffort; + let spec = ExecSpec { + program: "/definitely/missing/openshell-exec".to_string(), + args: vec![], + shell: None, + runtime_helper: None, + env: vec![], + workdir: None, + pty, + }; + let (result_tx, result_rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("build exec runtime"); + let _ = result_tx.send(runtime.block_on(executor.exec(spec))); + }); + let result = result_rx + .recv_timeout(std::time::Duration::from_secs(10)) + .expect("exec must return instead of stalling on the Landlock report pipe"); + assert!( + matches!(result, Err(BackendError::Process(_))), + "the missing entrypoint must surface as the spawn error" + ); + } + } + #[tokio::test] async fn exec_records_its_launch_and_exit() { use openshell_sandbox_backend::boundary_protocol::{ExitStatusWire, ProcessEventKindWire}; diff --git a/crates/openshell-sandbox/src/process.rs b/crates/openshell-sandbox/src/process.rs index db82d4afdc..0fe9dd6690 100644 --- a/crates/openshell-sandbox/src/process.rs +++ b/crates/openshell-sandbox/src/process.rs @@ -618,9 +618,17 @@ impl ProcessHandle { #[cfg(target_os = "linux")] let child_hardening = crate::linux::child_seccomp::prepare(std::process::id()) .map_err(|error| miette::miette!("prepare child self-protection filter: {error}"))?; + // Landlock best-effort degradation is reported to this thread over a + // CLOEXEC pipe instead of being logged from the forked child. + let landlock_report = sandbox::linux::LandlockReportPipe::new() + .map_err(|error| miette::miette!("create Landlock report pipe: {error}"))?; + let landlock_report_fd = landlock_report.child_fd(); #[cfg(target_os = "linux")] - let child_install = - sandbox::linux::ChildSandboxInstall::new(prepared_sandbox, child_hardening); + let child_install = sandbox::linux::ChildSandboxInstall::new( + prepared_sandbox, + child_hardening, + landlock_report_fd, + ); // Set up process group for signal handling (non-interactive mode only). // In interactive mode, we inherit the parent's process group to maintain // proper terminal control for shells and interactive programs. @@ -663,14 +671,18 @@ impl ProcessHandle { } } + // The registry lock is held across spawn and the Landlock report + // drain so a child exiting during the drain is registered before + // the orphan reaper can consider it. + #[cfg(target_os = "linux")] + let mut child_registry = managed_children::lock(); // Name the program in the error: a bare "No such file or directory" // here is otherwise indistinguishable from a missing working directory // or interpreter, and is a common failure on images that lack the // requested shell/binary (e.g. bash on Alpine). #[cfg(target_os = "linux")] - let mut child_registry = managed_children::lock(); - #[cfg(target_os = "linux")] - let mut child = spawn_command_with_workload_launcher(launcher, cmd) + let mut child = landlock_report + .spawn_and_drain(|| spawn_command_with_workload_launcher(launcher, cmd)) .into_diagnostic() .wrap_err_with(|| format!("failed to spawn sandbox entrypoint process '{program}'"))?; #[cfg(not(target_os = "linux"))] @@ -1758,6 +1770,81 @@ mod tests { assert_eq!(probe_hardened_child(dumpable_flag_probe), 0); } + /// `ProcessHandle::spawn` must drain the Landlock report pipe after + /// `spawn` returns but before mapping the spawn error, so a failed spawn + /// still returns promptly instead of stalling on a never-EOF pipe (the + /// drain blocks forever if the parent's write end is never dropped). + /// Forcing a real `restrict_self` degradation through this + /// public spawn API is not possible — the blocking seccomp filter used + /// in the landlock tests can only be installed in a forked child — so + /// this pins the closest observable contract: the failed spawn returns + /// its entrypoint error rather than hanging. The spawn runs on a + /// dedicated thread waited with a channel timeout, so a stalled drain + /// fails the test cleanly instead of deadlocking a runtime shutdown. + #[cfg(target_os = "linux")] + #[test] + fn failed_spawn_drains_the_landlock_report_pipe_before_returning() { + if sandbox::linux::require_landlock_abi().is_err() { + return; + } + let (launcher, listener) = + crate::linux::workload_launcher::start().expect("start test workload launcher"); + std::thread::spawn(move || { + while let Ok(notification) = listener.receive() { + let syscall = i64::from(notification.syscall); + if syscall == libc::SYS_openat || syscall == libc::SYS_openat2 { + let _ = listener.respond_continue(notification.id); + } else { + #[cfg(target_arch = "x86_64")] + if syscall == libc::SYS_open { + let _ = listener.respond_continue(notification.id); + continue; + } + let _ = listener.respond_errno(notification.id, libc::EPERM); + } + } + }); + let root = tempfile::tempdir().unwrap(); + let mut policy = policy_with_process(ProcessPolicy::default()); + policy.filesystem.read_only = vec![root.path().to_path_buf()]; + policy.landlock = LandlockPolicy { + compatibility: openshell_core::policy::LandlockCompatibility::BestEffort, + }; + let provider_env = HashMap::new(); + let (result_tx, result_rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("build spawn runtime"); + let _entered = runtime.enter(); + let _ = result_tx.send(ProcessHandle::spawn( + &launcher, + "/definitely/missing/openshell-entrypoint", + &[], + &ResolvedWorkspace::default(), + false, + &policy, + None, + child_env::TlsEnvironmentMode::Override, + &provider_env, + false, + )); + }); + let result = result_rx + .recv_timeout(std::time::Duration::from_secs(10)) + .expect("spawn must return instead of stalling on the Landlock report pipe"); + let Err(error) = result else { + panic!("the missing entrypoint must fail the spawn"); + }; + assert!( + error + .to_string() + .contains("failed to spawn sandbox entrypoint"), + "the error must come from the entrypoint spawn, not an earlier step: {error}" + ); + } + #[test] #[cfg(target_os = "linux")] fn parse_pids_max_detects_limited_runtime() { diff --git a/crates/openshell-sandbox/src/sandbox/linux/landlock.rs b/crates/openshell-sandbox/src/sandbox/linux/landlock.rs index b695ccfc82..198fe5d2ee 100644 --- a/crates/openshell-sandbox/src/sandbox/linux/landlock.rs +++ b/crates/openshell-sandbox/src/sandbox/linux/landlock.rs @@ -6,18 +6,18 @@ #[cfg(test)] use landlock::PathFd; use landlock::{ - ABI, Access, AccessFs, BitFlags, CompatLevel, Compatible, PathBeneath, Ruleset, RulesetAttr, - RulesetCreatedAttr, + ABI, Access, AccessFs, BitFlags, CompatLevel, Compatible, PathBeneath, RestrictSelfError, + Ruleset, RulesetAttr, RulesetCreatedAttr, RulesetError, }; use miette::{IntoDiagnostic, Result}; use openshell_core::policy::{LandlockCompatibility, SandboxPolicy}; use std::collections::VecDeque; use std::ffi::OsString; -use std::os::fd::{AsFd, OwnedFd}; +use std::os::fd::{AsFd, AsRawFd, OwnedFd, RawFd}; use std::os::unix::ffi::OsStringExt; use std::path::Component; use std::path::{Path, PathBuf}; -use tracing::debug; +use tracing::{debug, warn}; /// Result of probing the kernel for Landlock support. #[derive(Debug)] @@ -413,6 +413,47 @@ fn prepare_with_path_open_mode( } } +/// Result of enforcing one prepared Landlock ruleset. +/// +/// A best-effort ruleset that fails to enforce does not abort the spawn: the +/// outcome carries the failure cause and the caller decides how to report it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LandlockOutcome { + /// `restrict_self()` applied the ruleset. + Enforced, + /// `restrict_self()` failed and the best-effort policy lets the child + /// continue without this ruleset's filesystem restrictions. + Degraded(DegradedCause), +} + +/// Why a best-effort enforcement degraded, as an errno or an explicit +/// no-errno sentinel. +/// +/// [`enforce`] runs in the forked child between fork and exec, where +/// formatting, boxing, or displaying the landlock error is forbidden (the +/// child may still exec the workload). The failure therefore crosses to the +/// reporting context as a bare errno — or [`DegradedCause::NoErrno`] when +/// the error chain carries no `io::Error`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DegradedCause { + /// The errno of the failing `prctl` or `landlock_restrict_self` call. + Errno(i32), + /// The failure carried no `io::Error` (compatibility or flag error). + NoErrno, +} + +impl std::fmt::Display for DegradedCause { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + // Rendered only where formatting is safe (parent-side OCSF + // findings and alarms), never between fork and exec, so + // io::Error's strerror rendering is fine here. + Self::Errno(errno) => write!(f, "{}", std::io::Error::from_raw_os_error(*errno)), + Self::NoErrno => write!(f, "no errno"), + } + } +} + /// Phase 2: Enforce a prepared Landlock ruleset by calling `restrict_self()`. /// /// The capability-free launch path calls this in the child before exec, already @@ -420,39 +461,275 @@ fn prepare_with_path_open_mode( /// it restricts the calling thread and its future children. /// /// Respects the same `best_effort` / `hard_requirement` compatibility as -/// [`prepare`]: if `restrict_self()` fails and the policy is `best_effort`, -/// the error is logged and the sandbox continues without Landlock. -pub fn enforce(prepared: PreparedRuleset) -> Result<()> { - let result = prepared.ruleset.restrict_self().into_diagnostic(); - if let Err(err) = result { - if matches!(prepared.compatibility, LandlockCompatibility::BestEffort) { - openshell_ocsf::ocsf_emit!( - openshell_ocsf::DetectionFindingBuilder::new(openshell_ocsf::ctx::ctx()) - .activity(openshell_ocsf::ActivityId::Open) - .severity(openshell_ocsf::SeverityId::High) - .confidence(openshell_ocsf::ConfidenceId::High) - .is_alert(true) - .finding_info( - openshell_ocsf::FindingInfo::new( - "landlock-enforce-failed", - "Landlock restrict_self Failed", - ) - .with_desc(&format!( - "Ruleset was prepared but restrict_self() failed: {err}. \ - Running WITHOUT filesystem restrictions. \ - Set landlock.compatibility to 'hard_requirement' to make this fatal." - )), - ) - .message(format!( - "Landlock restrict_self failed (best_effort): {err}" - )) - .build() - ); - return Ok(()); +/// [`prepare`]. A `hard_requirement` failure returns `Err` and may allocate +/// like any aborting error path. A `best_effort` failure returns +/// [`LandlockOutcome::Degraded`] built without formatting or logging: the +/// spawn surfaces forward it to the parent through a +/// [`LandlockReportPipe`]. Fresh-process callers that can format the error +/// use [`enforce_fresh`] instead. +pub fn enforce(prepared: PreparedRuleset) -> Result { + match restrict_self_with_compatibility(prepared) { + Ok(RestrictSelfOutcome::Enforced) => Ok(LandlockOutcome::Enforced), + Ok(RestrictSelfOutcome::Degraded { cause, .. }) => Ok(LandlockOutcome::Degraded(cause)), + Err(error) => Err(error).into_diagnostic(), + } +} + +/// Phase 2 for fresh processes: enforce and report a degradation with the +/// full error chain. +/// +/// This path serves callers that are not between fork and exec, where +/// formatting the landlock error and running the tracing subscriber are both +/// safe. A `best_effort` failure emits the shared `landlock-enforce-failed` +/// finding with the full error [`Display`](std::fmt::Display) as its detail +/// and then returns [`LandlockOutcome::Degraded`] like [`enforce`]. A +/// `hard_requirement` failure returns `Err` and may allocate like any +/// aborting error path. +pub fn enforce_fresh(prepared: PreparedRuleset) -> Result { + match restrict_self_with_compatibility(prepared) { + Ok(RestrictSelfOutcome::Enforced) => Ok(LandlockOutcome::Enforced), + Ok(RestrictSelfOutcome::Degraded { cause, error }) => { + super::emit_landlock_enforce_failed(cause, &error.to_string()); + Ok(LandlockOutcome::Degraded(cause)) + } + Err(error) => Err(error).into_diagnostic(), + } +} + +/// Outcome of the shared `restrict_self()` + compatibility core. +enum RestrictSelfOutcome { + Enforced, + /// A best-effort degradation: the non-allocating cause for the report + /// transports, plus the raw error for callers that can format it. + Degraded { + cause: DegradedCause, + error: RulesetError, + }, +} + +/// Call `restrict_self()` and apply the prepared compatibility mode. +/// +/// Shared by [`enforce`] and [`enforce_fresh`] so the two entry points cannot +/// diverge on which failures degrade. A `best_effort` failure returns +/// [`RestrictSelfOutcome::Degraded`] carrying the raw error alongside the +/// non-allocating cause; a `hard_requirement` failure returns the raw error. +fn restrict_self_with_compatibility( + prepared: PreparedRuleset, +) -> std::result::Result { + match prepared.ruleset.restrict_self() { + Ok(_) => Ok(RestrictSelfOutcome::Enforced), + Err(error) => { + if matches!(prepared.compatibility, LandlockCompatibility::BestEffort) { + Ok(RestrictSelfOutcome::Degraded { + cause: degraded_cause(&error), + error, + }) + } else { + Err(error) + } + } + } +} + +/// Extract the errno of a `restrict_self()` failure without allocating. +/// +/// The `SetNoNewPrivsCall` and `RestrictSelfCall` variants carry an +/// `io::Error`; compatibility and flag errors carry none, and future variants +/// are mapped to [`DegradedCause::NoErrno`]. The landlock crate's `Errno` +/// helper is deliberately avoided: it defaults unknown chains to `EINVAL`, +/// which would conflate the sentinel with a genuine `EINVAL`. +fn degraded_cause(error: &RulesetError) -> DegradedCause { + match error { + RulesetError::RestrictSelf( + RestrictSelfError::SetNoNewPrivsCall { source, .. } + | RestrictSelfError::RestrictSelfCall { source, .. }, + ) => errno_cause(source.raw_os_error()), + _ => DegradedCause::NoErrno, + } +} + +/// Map a possibly-missing errno to a [`DegradedCause`]. +/// +/// `None` must become the [`DegradedCause::NoErrno`] sentinel, never a +/// defaulted errno: the landlock crate's `Errno` helper defaults unknown +/// chains to `EINVAL`, which would conflate the sentinel with a genuine +/// `EINVAL`. Split out from [`degraded_cause`] because the landlock error +/// variants are `#[non_exhaustive]` and cannot be constructed in tests. +fn errno_cause(raw: Option) -> DegradedCause { + raw.map_or(DegradedCause::NoErrno, DegradedCause::Errno) +} + +/// Fixed size of one report record: a magic tag plus an errno-or-sentinel +/// payload. Both fields are native-endian because the pipe only ever crosses +/// `fork`, never machines. +const REPORT_RECORD_SIZE: usize = 8; +/// Magic tag starting every report record ("LLDF": Landlock Degraded +/// Finding). +const REPORT_RECORD_TAG: u32 = 0x4C4C_4446; +/// Record payload encoding [`DegradedCause::NoErrno`]. `i32::MIN` cannot +/// collide with a real errno. +const REPORT_NO_ERRNO: i32 = i32::MIN; + +/// CLOEXEC pipe carrying best-effort Landlock degradation records from the +/// forked child to the spawning parent. +/// +/// Created before spawn. The child side ([`LandlockReportFd`]) is captured by +/// the `pre_exec` closure; the parent side ([`LandlockReportDrain`]) owns +/// both ends and reports after spawn. One fixed-size record is written per +/// degraded ruleset — zero or more per spawn — and the parent drains to EOF, +/// so a future second best-effort ruleset keeps its signal. +pub struct LandlockReportPipe { + read: OwnedFd, + write: OwnedFd, +} + +impl LandlockReportPipe { + /// Create the report pipe with both ends close-on-exec. + /// + /// # Errors + /// + /// Returns the pipe creation error. + pub fn new() -> std::io::Result { + let (read, write) = rustix::pipe::pipe_with(rustix::pipe::PipeFlags::CLOEXEC) + .map_err(std::io::Error::from)?; + Ok(Self { read, write }) + } + + /// The raw write fd for the `pre_exec` closure to capture. + /// + /// Deliberately a bare fd number (`Copy`), never an [`OwnedFd`]: the + /// closure moves onto the serialized workload launcher thread inside the + /// `Command`, and an owned write end dropped there would hold EOF hostage + /// to launcher-thread scheduling and stall the parent's drain. + #[must_use] + pub fn child_fd(&self) -> LandlockReportFd { + LandlockReportFd(self.write.as_raw_fd()) + } + + /// Consume the pipe into the parent-side drain guard. + #[must_use] + pub fn into_drain(self) -> LandlockReportDrain { + LandlockReportDrain { + read: self.read, + write: Some(self.write), + } + } + + /// Run one spawn with the report-drain choreography every spawn surface + /// must follow. + /// + /// Executes `spawn`, then — on success or failure — drops the parent's + /// write end, drains the report pipe to EOF, and emits one finding per + /// degraded ruleset. The spawn result is handed back unchanged so the + /// caller maps errors only after the drain: mapping first would lose + /// findings from failed spawns, and skipping the write-end drop would + /// block the drain forever on a pipe that can never reach EOF. + pub fn spawn_and_drain(self, spawn: impl FnOnce() -> Result) -> Result { + let mut drain = self.into_drain(); + let result = spawn(); + drain.report_degradations(); + result + } +} + +/// Child-side handle to the report pipe's write end. +/// +/// A newtype around the raw fd so [`super::enforce_capability_free`] can +/// require it as a non-optional parameter: an unplumbed spawn site is a +/// compile error, not a silently dropped report. +#[derive(Clone, Copy)] +pub struct LandlockReportFd(RawFd); + +impl LandlockReportFd { + /// Record one degraded ruleset from between fork and exec. + /// + /// One fixed-size `write(2)` of tag + errno-or-sentinel. Best-effort by + /// design: a lost record only loses a log line, never a security + /// decision, so the result is ignored. + pub(crate) fn report_degraded(self, cause: DegradedCause) { + let mut record = [0_u8; REPORT_RECORD_SIZE]; + record[..4].copy_from_slice(&REPORT_RECORD_TAG.to_ne_bytes()); + let payload = match cause { + DegradedCause::Errno(errno) => errno, + DegradedCause::NoErrno => REPORT_NO_ERRNO, + }; + record[4..].copy_from_slice(&payload.to_ne_bytes()); + // SAFETY: the fd is a live pipe write end and write(2) is + // async-signal-safe. Callers between fork and exec rely on that. + #[allow(unsafe_code)] + unsafe { + libc::write(self.0, record.as_ptr().cast(), record.len()); + } + } +} + +/// Parent-side guard draining the report pipe after spawn. +/// +/// Owns the read end and the parent's duplicate of the write end. The drain +/// itself drops that duplicate before reading, so it can never block on the +/// parent's own write end; production spawn surfaces reach it through +/// [`LandlockReportPipe::spawn_and_drain`], which runs it on both spawn +/// outcomes. On drop, any end still held is simply closed. +pub struct LandlockReportDrain { + read: OwnedFd, + write: Option, +} + +impl LandlockReportDrain { + /// Drain records to EOF and emit one finding per degraded ruleset. + /// + /// Drops the parent's write end first: the forked child's inherited copy + /// is close-on-exec, so after that drop the read end sees EOF exactly + /// when the child execs or exits, and the drain can never block on a + /// write end still held in the parent. Runs on the spawning thread, + /// where the tracing subscriber works. Reading to EOF — never a single + /// read — keeps the decode correct for any number of records. Returns + /// the decoded causes. + pub fn report_degradations(&mut self) -> Vec { + self.write.take(); + let mut received = Vec::new(); + let mut scratch = [0_u8; REPORT_RECORD_SIZE]; + loop { + match rustix::io::read(&self.read, &mut scratch) { + Ok(0) => break, + Ok(count) => received.extend_from_slice(&scratch[..count]), + Err(rustix::io::Errno::INTR) => {} + Err(error) => { + // The drain runs in the parent, where tracing is safe. + // A truncated drain silently loses the "running without + // filesystem restrictions" signal, so name the errno. + warn!( + errno = error.raw_os_error(), + "Landlock report pipe read failed; degradation records may be truncated" + ); + break; + } + } + } + let causes = decode_degraded_causes(&received); + for cause in causes.iter().copied() { + // Only the errno-based rendering crossed the pipe; the child + // between fork and exec cannot format the full error chain. + super::emit_landlock_enforce_failed(cause, &cause.to_string()); } - return Err(err); + causes } - Ok(()) +} + +/// Decode whole report records; a trailing partial record — impossible under +/// the fixed-size write protocol — is ignored. +fn decode_degraded_causes(data: &[u8]) -> Vec { + data.chunks_exact(REPORT_RECORD_SIZE) + .filter(|record| record[..4] == REPORT_RECORD_TAG.to_ne_bytes()) + .map(|record| { + let mut errno_bytes = [0_u8; 4]; + errno_bytes.copy_from_slice(&record[4..]); + match i32::from_ne_bytes(errno_bytes) { + REPORT_NO_ERRNO => DegradedCause::NoErrno, + errno => DegradedCause::Errno(errno), + } + }) + .collect() } /// Tailor a rule's access mask to the inode referenced by its already-open FD. @@ -691,6 +968,9 @@ fn compat_level(level: &LandlockCompatibility) -> CompatLevel { #[cfg(test)] mod tests { use super::*; + use crate::sandbox::linux::test_support::{ + best_effort_policy, build_restrict_self_blocking_filter, + }; use openshell_core::policy::{FilesystemPolicy, LandlockPolicy, NetworkPolicy, ProcessPolicy}; fn hard_requirement_policy(read_only: Vec, read_write: Vec) -> SandboxPolicy { @@ -825,7 +1105,10 @@ mod tests { std::os::unix::fs::symlink(&private, root.path().join("private-alias")).unwrap(); let path = root.path().to_path_buf(); std::thread::spawn(move || { - enforce(prepare_capability_free_baseline_at(&path).unwrap()).unwrap(); + assert!(matches!( + enforce(prepare_capability_free_baseline_at(&path).unwrap()).unwrap(), + LandlockOutcome::Enforced + )); assert_eq!( std::fs::read(path.join("public/sentinel")).unwrap(), b"allowed" @@ -852,7 +1135,10 @@ mod tests { ); } let policy = hard_requirement_policy(vec![path.join("public")], Vec::new()); - enforce(prepare_current_user(&policy, None).unwrap().unwrap()).unwrap(); + assert!(matches!( + enforce(prepare_current_user(&policy, None).unwrap().unwrap()).unwrap(), + LandlockOutcome::Enforced + )); let read_only = std::ffi::CString::new(path.join("public/sentinel").as_os_str().as_encoded_bytes()) .unwrap(); @@ -1232,4 +1518,497 @@ mod tests { assert!(err.contains(&availability.to_string()), "{err}"); } } + + #[test] + #[allow(unsafe_code)] + fn report_pipe_transports_zero_one_and_many_records() { + for causes in [ + Vec::new(), + vec![DegradedCause::Errno(libc::EPERM)], + vec![ + DegradedCause::Errno(libc::EPERM), + DegradedCause::NoErrno, + DegradedCause::Errno(libc::EACCES), + ], + ] { + let pipe = LandlockReportPipe::new().expect("create report pipe"); + let child_fd = pipe.child_fd(); + let mut drain = pipe.into_drain(); + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed"); + if pid == 0 { + for cause in &causes { + child_fd.report_degraded(*cause); + } + unsafe { libc::_exit(0) }; + } + let mut status: libc::c_int = 0; + unsafe { libc::waitpid(pid, &raw mut status, 0) }; + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "record-writing child failed" + ); + assert_eq!( + drain.report_degradations(), + causes, + "drain must decode every record the child wrote" + ); + } + } + + #[test] + fn decode_degraded_causes_filters_malformed_records() { + fn record(tag: u32, payload: i32) -> [u8; REPORT_RECORD_SIZE] { + let mut record = [0_u8; REPORT_RECORD_SIZE]; + record[..4].copy_from_slice(&tag.to_ne_bytes()); + record[4..].copy_from_slice(&payload.to_ne_bytes()); + record + } + + // Empty input decodes to no causes. + assert_eq!(decode_degraded_causes(&[]), Vec::new()); + + // A well-formed record decodes to its cause. + assert_eq!( + decode_degraded_causes(&record(REPORT_RECORD_TAG, libc::EPERM)), + vec![DegradedCause::Errno(libc::EPERM)] + ); + + // A record with a wrong magic tag is dropped even when its payload + // would decode to a valid cause. + assert_eq!( + decode_degraded_causes(&record(0xDEAD_BEEF, libc::EPERM)), + Vec::new() + ); + + // A trailing partial record — shorter than one full record — is + // ignored, not mis-sliced into a cause. + let mut truncated = record(REPORT_RECORD_TAG, libc::EACCES).to_vec(); + truncated.extend_from_slice(&[0_u8; REPORT_RECORD_SIZE - 1]); + assert_eq!( + decode_degraded_causes(&truncated), + vec![DegradedCause::Errno(libc::EACCES)] + ); + + // Interleaved valid and invalid records keep only the valid ones, + // in order, and still ignore a partial tail. + let mut mixed = Vec::new(); + mixed.extend_from_slice(&record(0xDEAD_BEEF, libc::EACCES)); + mixed.extend_from_slice(&record(REPORT_RECORD_TAG, libc::EPERM)); + mixed.extend_from_slice(&record(0xDEAD_BEEF, libc::ENOENT)); + mixed.extend_from_slice(&record(REPORT_RECORD_TAG, REPORT_NO_ERRNO)); + mixed.extend_from_slice(&[0xAA]); + assert_eq!( + decode_degraded_causes(&mixed), + vec![DegradedCause::Errno(libc::EPERM), DegradedCause::NoErrno] + ); + } + + #[test] + #[allow(unsafe_code)] + fn report_drain_returns_promptly_when_command_drops_late() { + use std::os::unix::process::CommandExt as _; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Arc, mpsc}; + use std::time::Duration; + + let pipe = LandlockReportPipe::new().expect("create report pipe"); + let child_fd = pipe.child_fd(); + let mut drain = pipe.into_drain(); + + let release = Arc::new(AtomicBool::new(false)); + let helper_release = release.clone(); + let (result_tx, result_rx) = mpsc::sync_channel(1); + let helper = std::thread::spawn(move || { + let mut command = std::process::Command::new("true"); + // SAFETY: the hook performs one async-signal-safe write(2) of a + // fixed-size record; the CLOEXEC write end closes at exec. + #[allow(unsafe_code)] + unsafe { + command.pre_exec(move || { + child_fd.report_degraded(DegradedCause::Errno(libc::EPERM)); + Ok(()) + }); + } + let child = command.spawn(); + let _ = result_tx.send(child); + // Model the serialized workload launcher: the Command, holding + // the pre_exec closure state, is dropped only after the caller + // releases this thread. If the closure captured an owned write + // end, EOF — and the caller's drain — would wait for this drop. + while !helper_release.load(Ordering::Acquire) { + std::thread::sleep(Duration::from_millis(10)); + } + }); + + let mut child = result_rx + .recv() + .expect("helper spawn result") + .expect("spawn true"); + let (drain_tx, drain_rx) = mpsc::sync_channel(1); + std::thread::spawn(move || { + let _ = drain_tx.send(drain.report_degradations()); + }); + let reported = drain_rx + .recv_timeout(Duration::from_secs(2)) + .expect("drain must reach EOF without waiting for the helper's late Command drop"); + assert_eq!(reported, vec![DegradedCause::Errno(libc::EPERM)]); + release.store(true, Ordering::Release); + helper.join().expect("join helper thread"); + let _ = child.wait(); + } + + #[test] + #[allow(unsafe_code)] + fn report_drain_reports_records_written_before_a_later_hook_failure() { + use std::os::unix::process::CommandExt as _; + + let pipe = LandlockReportPipe::new().expect("create report pipe"); + let child_fd = pipe.child_fd(); + let mut drain = pipe.into_drain(); + + let mut command = std::process::Command::new("true"); + // SAFETY: the hook performs one async-signal-safe write(2) of a + // fixed-size record, then fails like any later pre_exec hook can. + #[allow(unsafe_code)] + unsafe { + command.pre_exec(move || { + child_fd.report_degraded(DegradedCause::Errno(libc::EPERM)); + Err(std::io::Error::from_raw_os_error(libc::EPERM)) + }); + } + let error = command + .spawn() + .expect_err("a failing pre_exec hook must fail the spawn"); + assert_eq!( + error.raw_os_error(), + Some(libc::EPERM), + "the hook's failure must be the spawn error" + ); + // Every spawn surface drains before mapping the spawn error, so a + // degradation that preceded a later hook failure is still reported + // instead of being dropped by the `?` propagation. + assert_eq!( + drain.report_degradations(), + vec![DegradedCause::Errno(libc::EPERM)], + "a record written before the hook failure must survive the failed spawn" + ); + } + + #[test] + #[allow(unsafe_code)] + fn enforce_best_effort_reports_degradation_through_the_pipe() { + if !matches!(probe_availability(), LandlockAvailability::Available { abi } if abi >= 3) { + eprintln!("skipping: Landlock unavailable or ABI < 3 on this host"); + return; + } + let root = tempfile::tempdir().unwrap(); + let policy = best_effort_policy(vec![root.path().to_path_buf()]); + let prepared = prepare(&policy, None) + .expect("prepare best-effort ruleset") + .expect("ruleset with one readable path"); + let pipe = LandlockReportPipe::new().expect("create report pipe"); + let child_fd = pipe.child_fd(); + let mut drain = pipe.into_drain(); + let filter = build_restrict_self_blocking_filter(); + + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed"); + if pid == 0 { + unsafe { + // Best-effort degradation keeps the spawn alive: enforce + // must return Ok(Degraded(Errno(EPERM))) without allocating, + // and the child must carry the cause to the parent. + libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); + seccompiler::apply_filter(&filter).expect("apply blocking filter"); + match enforce(prepared) { + Ok(LandlockOutcome::Degraded(DegradedCause::Errno(errno))) + if errno == libc::EPERM => + { + child_fd.report_degraded(DegradedCause::Errno(errno)); + libc::_exit(0); + } + Ok(LandlockOutcome::Degraded(cause)) => { + let msg = format!("unexpected degraded cause: {cause:?}\n"); + libc::write(2, msg.as_ptr().cast(), msg.len()); + libc::_exit(1); + } + Ok(LandlockOutcome::Enforced) => { + let msg = "expected restrict_self to fail with EPERM\n"; + libc::write(2, msg.as_ptr().cast(), msg.len()); + libc::_exit(2); + } + Err(error) => { + let msg = format!("best-effort enforce must not err: {error}\n"); + libc::write(2, msg.as_ptr().cast(), msg.len()); + libc::_exit(3); + } + } + } + } + let mut status: libc::c_int = 0; + unsafe { libc::waitpid(pid, &raw mut status, 0) }; + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "child must report a degraded best-effort ruleset, status {status}" + ); + assert_eq!( + drain.report_degradations(), + vec![DegradedCause::Errno(libc::EPERM)], + "the parent must decode the degradation the forked child reported" + ); + } + + #[test] + #[allow(unsafe_code)] + fn fresh_process_enforce_continues_past_a_degraded_ruleset() { + const CHILD_MARKER: &str = "OPENSHELL_TEST_FRESH_ENFORCE_DEGRADED_CHILD"; + if !matches!(probe_availability(), LandlockAvailability::Available { abi } if abi >= 3) { + eprintln!("skipping: Landlock unavailable or ABI < 3 on this host"); + return; + } + // The fresh-process enforce path emits OCSF and installs an + // irreversible seccomp filter, so run the probe in a fresh copy of + // this test binary rather than a forked child of the multithreaded + // test harness, where emission is forbidden. + if std::env::var_os(CHILD_MARKER).is_some() { + let root = tempfile::tempdir().unwrap(); + let outside = tempfile::tempdir().unwrap(); + std::fs::write(outside.path().join("sentinel"), b"outside the allowlist").unwrap(); + // Only `root` is allowlisted; `outside` staying reachable proves the + // degraded ruleset never applied. + let policy = best_effort_policy(vec![root.path().to_path_buf()]); + let prepared = crate::sandbox::linux::prepare(&policy, None) + .expect("prepare sandbox with one best-effort ruleset"); + assert_eq!(prepared.landlock.len(), 1, "expected exactly one ruleset"); + let filter = build_restrict_self_blocking_filter(); + + unsafe { + libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); + seccompiler::apply_filter(&filter).expect("apply blocking filter"); + } + // Fresh-process enforce: a degraded best-effort ruleset must not + // abort... + crate::sandbox::linux::enforce(prepared) + .expect("enforce must continue past a degraded ruleset"); + // ...the degradation must be real: restrict_self failed, so the + // path outside the allowlist stays reachable... + assert_eq!( + std::fs::read(outside.path().join("sentinel")) + .expect("read the path outside the allowlist"), + b"outside the allowlist".as_slice(), + "expected the degraded ruleset to leave the filesystem unrestricted" + ); + // ...and the prebuilt seccomp filters must still be installed: + // memfd_create is denied with EPERM only by the main filter. + let result = unsafe { libc::syscall(libc::SYS_memfd_create, 0, 0) }; + let errno = unsafe { *libc::__errno_location() }; + assert!( + result == -1 && errno == libc::EPERM, + "memfd_create: expected EPERM from the installed main filter" + ); + return; + } + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "sandbox::linux::landlock::tests::fresh_process_enforce_continues_past_a_degraded_ruleset", + "--nocapture", + ]) + .env(CHILD_MARKER, "1") + .status() + .expect("run isolated fresh-process enforce test"); + assert!( + status.success(), + "fresh-process enforce must return Ok on a degraded ruleset, keep the \ + filesystem open, and install the prebuilt seccomp filters" + ); + } + + #[test] + #[allow(unsafe_code)] + fn enforce_hard_requirement_errors_when_restrict_self_fails() { + if !matches!(probe_availability(), LandlockAvailability::Available { abi } if abi >= 3) { + eprintln!("skipping: Landlock unavailable or ABI < 3 on this host"); + return; + } + let root = tempfile::tempdir().unwrap(); + let policy = hard_requirement_policy(vec![root.path().to_path_buf()], Vec::new()); + let prepared = prepare(&policy, None) + .expect("prepare hard-requirement ruleset") + .expect("ruleset with one readable path"); + let filter = build_restrict_self_blocking_filter(); + + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed"); + if pid == 0 { + unsafe { + libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); + seccompiler::apply_filter(&filter).expect("apply blocking filter"); + match enforce(prepared) { + Err(_) => libc::_exit(0), + Ok(outcome) => { + let msg = format!("hard_requirement must err, got {outcome:?}\n"); + libc::write(2, msg.as_ptr().cast(), msg.len()); + libc::_exit(1); + } + } + } + } + let mut status: libc::c_int = 0; + unsafe { libc::waitpid(pid, &raw mut status, 0) }; + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "hard_requirement enforce must fail when restrict_self fails" + ); + } + + #[test] + #[allow(unsafe_code)] + fn enforce_capability_free_reports_every_degraded_ruleset_before_child_hardening() { + if !matches!(probe_availability(), LandlockAvailability::Available { abi } if abi >= 3) { + eprintln!("skipping: Landlock unavailable or ABI < 3 on this host"); + return; + } + let root = tempfile::tempdir().unwrap(); + let policy = best_effort_policy(vec![root.path().to_path_buf()]); + // Two best-effort rulesets: the report loop must continue past the + // first degradation instead of aborting the spawn. + let mut prepared = crate::sandbox::linux::prepare(&policy, None) + .expect("prepare sandbox with one best-effort ruleset"); + assert_eq!(prepared.landlock.len(), 1, "expected exactly one ruleset"); + prepared.landlock.push( + prepare(&policy, None) + .expect("prepare the second best-effort ruleset") + .expect("second ruleset over the same readable path"), + ); + let mut child_hardening = crate::linux::child_seccomp::prepare(std::process::id()) + .expect("prepare child self-protection filter"); + // Pre-installing the workload filters bans any further seccomp + // installation in the child, so child_hardening.install() fails with + // EPERM exactly as it would once the real filter stack is armed: the + // degradation records must already be on the pipe by then. + let workload_filters = crate::sandbox::linux::seccomp::prepare(&policy) + .expect("prepare workload seccomp filters"); + let pipe = LandlockReportPipe::new().expect("create report pipe"); + let child_fd = pipe.child_fd(); + let mut drain = pipe.into_drain(); + let filter = build_restrict_self_blocking_filter(); + + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed"); + if pid == 0 { + unsafe { + libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); + seccompiler::apply_filter(&filter).expect("apply blocking filter"); + if let Err(error) = workload_filters.install() { + let msg = format!("failed to pre-install workload filters: {error}\n"); + libc::write(2, msg.as_ptr().cast(), msg.len()); + libc::_exit(1); + } + if crate::sandbox::linux::enforce_capability_free( + prepared, + &mut child_hardening, + child_fd, + ) + .is_err() + { + // The install failed after the loop, so the + // self-protection filter must not be active: + // kill(getppid(), 0) names the prepared sandbox TGID + // and is denied with EPERM once it is. + if libc::kill(libc::getppid(), 0) == -1 { + let msg = "child self-protection filter must not be active after a failed install\n"; + libc::write(2, msg.as_ptr().cast(), msg.len()); + libc::_exit(3); + } + libc::_exit(0); + } else { + let msg = "child hardening installed despite the seccomp ban\n"; + libc::write(2, msg.as_ptr().cast(), msg.len()); + libc::_exit(2); + } + } + } + let mut status: libc::c_int = 0; + unsafe { libc::waitpid(pid, &raw mut status, 0) }; + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "child must write every degradation record before child hardening, status {status}" + ); + assert_eq!( + drain.report_degradations(), + vec![ + DegradedCause::Errno(libc::EPERM), + DegradedCause::Errno(libc::EPERM) + ], + "every degraded ruleset must be reported even when the later install fails" + ); + } + + #[test] + #[allow(unsafe_code)] + fn child_sandbox_install_without_prepared_sandbox_is_a_no_op() { + let pipe = LandlockReportPipe::new().expect("create report pipe"); + let child_fd = pipe.child_fd(); + let mut drain = pipe.into_drain(); + let child_hardening = crate::linux::child_seccomp::prepare(std::process::id()) + .expect("prepare child self-protection filter"); + let mut install = + crate::sandbox::linux::ChildSandboxInstall::new(None, child_hardening, child_fd); + + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed"); + if pid == 0 { + unsafe { + if let Err(error) = install.enforce() { + let msg = format!("no-op enforce must not fail: {error}\n"); + libc::write(2, msg.as_ptr().cast(), msg.len()); + libc::_exit(1); + } + // The child self-protection program must stay uninstalled: + // kill(getppid(), 0) names the prepared sandbox TGID and is + // denied with EPERM once that filter is active. + if libc::kill(libc::getppid(), 0) == -1 { + let msg = "child self-protection filter must stay uninstalled without a prepared sandbox\n"; + libc::write(2, msg.as_ptr().cast(), msg.len()); + libc::_exit(2); + } + libc::_exit(0); + } + } + let mut status: libc::c_int = 0; + unsafe { libc::waitpid(pid, &raw mut status, 0) }; + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "enforce without a prepared sandbox must return Ok and install nothing, status {status}" + ); + assert!( + drain.report_degradations().is_empty(), + "a no-op enforce must not write degradation records" + ); + } + + #[test] + fn degraded_cause_maps_non_io_failures_to_no_errno() { + use landlock::CreateRulesetError; + + // Guard the errno half too: a present raw errno must surface + // unchanged, not a defaulted one. + assert_eq!( + errno_cause(Some(libc::EPERM)), + DegradedCause::Errno(libc::EPERM) + ); + + // An io::Error with no OS errno must become the sentinel, never a + // defaulted errno. + assert_eq!(errno_cause(None), DegradedCause::NoErrno); + + // Non-io variants fall through the catch-all to the sentinel. The + // landlock crate marks the restrict_self variants + // #[non_exhaustive], so this unit variant is the one constructible + // from outside the crate. + let non_io = RulesetError::CreateRuleset(CreateRulesetError::MissingHandledAccess); + assert_eq!(degraded_cause(&non_io), DegradedCause::NoErrno); + } } diff --git a/crates/openshell-sandbox/src/sandbox/linux/mod.rs b/crates/openshell-sandbox/src/sandbox/linux/mod.rs index e73458b4b8..a7d98a1e7b 100644 --- a/crates/openshell-sandbox/src/sandbox/linux/mod.rs +++ b/crates/openshell-sandbox/src/sandbox/linux/mod.rs @@ -12,6 +12,7 @@ use std::path::PathBuf; use std::sync::Once; pub use landlock::require_abi as require_landlock_abi; +pub use landlock::{LandlockReportFd, LandlockReportPipe}; /// Opaque handle to a prepared-but-not-yet-enforced sandbox. /// Holds the Landlock ruleset with `PathFds` opened before child exec, @@ -75,10 +76,14 @@ pub fn prepare_capability_free( /// Phase 2: Enforce prepared sandbox restrictions in the child before exec. /// /// Calls `restrict_self()` for Landlock and installs the prebuilt seccomp -/// filters. Neither operation requires root privileges. +/// filters. Neither operation requires root privileges. Best-effort rulesets +/// that degrade are reported directly through the shared finding builder with +/// the full error chain: this path serves fresh processes (see `main.rs`), +/// never a forked child, so formatting the landlock error and the tracing +/// subscriber both work here. pub fn enforce(prepared: PreparedSandbox) -> Result<()> { for ruleset in prepared.landlock { - landlock::enforce(ruleset)?; + landlock::enforce_fresh(ruleset)?; } prepared.seccomp.install()?; Ok(()) @@ -89,12 +94,22 @@ pub fn enforce(prepared: PreparedSandbox) -> Result<()> { /// Landlock precedes sandbox-TGID self-protection. The ordinary workload /// filter is installed last. The final filter blocks any later seccomp /// installation, so this order is mandatory for capability-free children. +/// +/// A best-effort ruleset that degrades does not abort the spawn: its cause +/// is written to the report pipe as one fixed-size, async-signal-safe record +/// before the child self-protection filter is installed, so the `write(2)` +/// cannot block on the seccomp broker and the parent reports the finding +/// after spawn. pub fn enforce_capability_free( prepared: PreparedSandbox, child_hardening: &mut crate::linux::child_seccomp::ChildHardeningProgram, + report: LandlockReportFd, ) -> Result<()> { for ruleset in prepared.landlock { - landlock::enforce(ruleset)?; + match landlock::enforce(ruleset)? { + landlock::LandlockOutcome::Enforced => {} + landlock::LandlockOutcome::Degraded(cause) => report.report_degraded(cause), + } } child_hardening .install() @@ -106,25 +121,30 @@ pub fn enforce_capability_free( /// Everything a spawned workload child installs between fork and exec. /// /// Bundles the prepared Landlock rulesets and prebuilt seccomp filters -/// ([`PreparedSandbox`]) with the same-UID child self-protection program so a -/// spawn surface cannot wire one without the other. All compilation and path -/// opening happens at construction, parent-side; the forked child only -/// installs. +/// ([`PreparedSandbox`]) with the same-UID child self-protection program and +/// the Landlock report pipe's write end, so a spawn surface cannot wire one +/// without the other or silently drop the report channel. All compilation +/// and path opening happens at construction, parent-side; the forked child +/// only installs. pub struct ChildSandboxInstall { prepared: Option, child_hardening: crate::linux::child_seccomp::ChildHardeningProgram, + report: LandlockReportFd, } impl ChildSandboxInstall { - /// Bundle a prepared sandbox (if any) with its child hardening program. + /// Bundle a prepared sandbox (if any) with its child hardening program + /// and the Landlock report pipe's write end. #[must_use] pub fn new( prepared: Option, child_hardening: crate::linux::child_seccomp::ChildHardeningProgram, + report: LandlockReportFd, ) -> Self { Self { prepared, child_hardening, + report, } } @@ -137,7 +157,7 @@ impl ChildSandboxInstall { let Some(prepared) = self.prepared.take() else { return Ok(()); }; - enforce_capability_free(prepared, &mut self.child_hardening) + enforce_capability_free(prepared, &mut self.child_hardening, self.report) } } @@ -146,6 +166,90 @@ pub fn apply_supervisor_prelude() -> Result<()> { seccomp::apply_supervisor_prelude() } +/// Helpers shared by the `sandbox::linux` test modules. +#[cfg(test)] +pub(crate) mod test_support { + use openshell_core::policy::{ + FilesystemPolicy, LandlockCompatibility, LandlockPolicy, NetworkPolicy, ProcessPolicy, + SandboxPolicy, + }; + use std::path::PathBuf; + + /// A policy with one best-effort Landlock ruleset over `read_only`. + pub fn best_effort_policy(read_only: Vec) -> SandboxPolicy { + SandboxPolicy { + version: 1, + filesystem: FilesystemPolicy { + read_only, + read_write: Vec::new(), + include_workdir: false, + }, + network: NetworkPolicy::default(), + landlock: LandlockPolicy { + compatibility: LandlockCompatibility::BestEffort, + }, + process: ProcessPolicy::default(), + } + } + + /// Compile a filter that makes `landlock_restrict_self` fail with EPERM, + /// so `enforce` takes its degradation path on a Landlock-capable host. + pub fn build_restrict_self_blocking_filter() -> seccompiler::BpfProgram { + use std::collections::BTreeMap; + + let mut rules: BTreeMap> = BTreeMap::new(); + rules.entry(libc::SYS_landlock_restrict_self).or_default(); + let filter = seccompiler::SeccompFilter::new( + rules, + seccompiler::SeccompAction::Allow, + seccompiler::SeccompAction::Errno(libc::EPERM as u32), + std::env::consts::ARCH + .try_into() + .expect("supported architecture"), + ) + .expect("compile restrict_self-blocking filter"); + filter + .try_into() + .expect("build restrict_self-blocking BPF program") + } +} + +/// Emit the `landlock-enforce-failed` finding for one degraded best-effort +/// ruleset. +/// +/// Shared by the post-spawn drain reporter and the fresh-process +/// [`landlock::enforce_fresh`] path so the two transports cannot diverge. +/// Only call this where the tracing subscriber works — never between fork +/// and exec. `detail` is the failure rendering for the message: the drain +/// transport passes the errno-based cause rendering (the forked child cannot +/// format the landlock error, so only the errno crosses the report pipe), +/// while the fresh path passes the full error chain. The description keeps +/// the errno-based cause either way. +fn emit_landlock_enforce_failed(cause: landlock::DegradedCause, detail: &str) { + openshell_ocsf::ocsf_emit!( + openshell_ocsf::DetectionFindingBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(openshell_ocsf::ActivityId::Open) + .severity(openshell_ocsf::SeverityId::High) + .confidence(openshell_ocsf::ConfidenceId::High) + .is_alert(true) + .finding_info( + openshell_ocsf::FindingInfo::new( + "landlock-enforce-failed", + "Landlock restrict_self Failed", + ) + .with_desc(&format!( + "Ruleset was prepared but restrict_self() failed ({cause}). \ + Running WITHOUT filesystem restrictions. \ + Set landlock.compatibility to 'hard_requirement' to make this fatal." + )), + ) + .message(format!( + "Landlock restrict_self failed (best_effort): {detail}" + )) + .build() + ); +} + /// Probe Landlock availability and emit OCSF logs from the parent process. /// /// This must be called **before** `pre_exec` / `fork()` so that the OCSF events @@ -254,3 +358,186 @@ pub fn log_sandbox_readiness(policy: &SandboxPolicy, workdir: Option<&str>) { ); } } + +#[cfg(test)] +mod tests { + use super::landlock::{DegradedCause, LandlockAvailability}; + use super::test_support::{best_effort_policy, build_restrict_self_blocking_filter}; + use super::*; + use openshell_ocsf::test_support::OcsfCapture; + use openshell_ocsf::{OcsfEvent, SeverityId}; + + /// Check that one captured event is the `landlock-enforce-failed` finding + /// for the given cause rendered through the given detail, or describe the + /// mismatch. + fn check_landlock_enforce_failed_finding( + event: &OcsfEvent, + cause: DegradedCause, + detail: &str, + ) -> Result<(), String> { + let OcsfEvent::DetectionFinding(finding) = event else { + return Err(format!("expected a DetectionFinding, got {event:?}")); + }; + if finding.finding_info.uid != "landlock-enforce-failed" { + return Err(format!( + "unexpected finding uid: {}", + finding.finding_info.uid + )); + } + if finding.finding_info.title != "Landlock restrict_self Failed" { + return Err(format!( + "unexpected finding title: {}", + finding.finding_info.title + )); + } + if finding.base.severity != SeverityId::High { + return Err(format!("unexpected severity: {:?}", finding.base.severity)); + } + if finding.is_alert != Some(true) { + return Err(format!("finding is not an alert: {:?}", finding.is_alert)); + } + let expected_message = format!("Landlock restrict_self failed (best_effort): {detail}"); + if finding.base.message.as_deref() != Some(expected_message.as_str()) { + return Err(format!( + "unexpected message: {:?}, expected {expected_message:?}", + finding.base.message + )); + } + let Some(desc) = finding.finding_info.desc.as_deref() else { + return Err("finding carries no description".to_string()); + }; + if !desc.contains(&format!("restrict_self() failed ({cause})")) { + return Err(format!("description lost the degraded cause: {desc}")); + } + if !desc.contains("hard_requirement") { + return Err(format!("description lost the remediation hint: {desc}")); + } + Ok(()) + } + + /// The post-spawn drain must emit one `landlock-enforce-failed` finding + /// per degraded ruleset — not once per spawn — with the uid, title, High + /// severity, and errno-based message and description downstream OCSF + /// consumers rely on. + #[test] + #[allow(unsafe_code)] + fn report_drain_emits_one_finding_per_degraded_ruleset() { + let causes = [ + DegradedCause::Errno(libc::EPERM), + DegradedCause::NoErrno, + DegradedCause::Errno(libc::EACCES), + ]; + let capture = OcsfCapture::default(); + let _guard = capture.install(); + + let pipe = LandlockReportPipe::new().expect("create report pipe"); + let child_fd = pipe.child_fd(); + let mut drain = pipe.into_drain(); + let pid = unsafe { libc::fork() }; + assert!(pid >= 0, "fork failed"); + if pid == 0 { + for cause in causes { + child_fd.report_degraded(cause); + } + unsafe { libc::_exit(0) }; + } + let mut status: libc::c_int = 0; + unsafe { libc::waitpid(pid, &raw mut status, 0) }; + assert!( + libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, + "record-writing child failed" + ); + + assert_eq!( + drain.report_degradations(), + causes.to_vec(), + "drain must decode every record the child wrote" + ); + + let events = capture.events(); + assert_eq!( + events.len(), + causes.len(), + "one finding must be emitted per degraded ruleset, not per spawn: {events:?}" + ); + for (event, cause) in events.iter().zip(causes) { + // The drain transport reports the errno-based rendering. + check_landlock_enforce_failed_finding(event, cause, &cause.to_string()) + .unwrap_or_else(|error| panic!("drain emitted a wrong finding: {error}")); + } + } + + /// The fresh-process [`enforce`] path must report a degraded best-effort + /// ruleset through the same `landlock-enforce-failed` finding the drain + /// transport emits, so the two cannot diverge — and, unlike the drain, + /// with the full landlock error chain, because a fresh process can + /// format it. The probe installs an irreversible seccomp filter and + /// emits OCSF, so it runs in a fresh copy of this test binary + /// (env-marker re-exec) rather than a forked child of the multithreaded + /// test harness, where emission is forbidden. + #[test] + #[allow(unsafe_code)] + fn fresh_process_enforce_emits_the_detection_finding() { + const CHILD_MARKER: &str = "OPENSHELL_TEST_FRESH_ENFORCE_FINDING_CHILD"; + if !matches!( + landlock::probe_availability(), + LandlockAvailability::Available { abi } if abi >= 3 + ) { + eprintln!("skipping: Landlock unavailable or ABI < 3 on this host"); + return; + } + if std::env::var_os(CHILD_MARKER).is_some() { + let root = tempfile::tempdir().unwrap(); + let policy = best_effort_policy(vec![root.path().to_path_buf()]); + let prepared = + prepare(&policy, None).expect("prepare sandbox with one best-effort ruleset"); + assert_eq!(prepared.landlock.len(), 1, "expected exactly one ruleset"); + let filter = build_restrict_self_blocking_filter(); + + let capture = OcsfCapture::default(); + let _guard = capture.install(); + unsafe { + libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); + seccompiler::apply_filter(&filter).expect("apply blocking filter"); + } + enforce(prepared).expect("enforce must continue past a degraded ruleset"); + + let events = capture.events(); + assert_eq!( + events.len(), + 1, + "expected exactly one finding for the degraded ruleset, got {}", + events.len() + ); + // The fresh path reports the full error chain: the landlock + // crate's Display for the blocked restrict_self call, ending in + // the same strerror rendering std produces for EPERM. + let expected_detail = format!( + "failed to restrict the calling thread: {}", + std::io::Error::from_raw_os_error(libc::EPERM), + ); + check_landlock_enforce_failed_finding( + &events[0], + DegradedCause::Errno(libc::EPERM), + &expected_detail, + ) + .unwrap_or_else(|error| { + panic!("fresh-process enforce emitted a wrong finding: {error}") + }); + return; + } + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "sandbox::linux::tests::fresh_process_enforce_emits_the_detection_finding", + "--nocapture", + ]) + .env(CHILD_MARKER, "1") + .status() + .expect("run isolated fresh-process enforce emission test"); + assert!( + status.success(), + "isolated fresh-process enforce emission test failed" + ); + } +} From e2c7ebb4759c063509bbbfc34259a8155b16ae42 Mon Sep 17 00:00:00 2001 From: Emilien Macchi Date: Tue, 3 Nov 2026 00:57:11 -0500 Subject: [PATCH 3/4] docs(sandbox): correct pre_exec SAFETY comments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The SAFETY comments on the workload pre_exec hooks claimed that "all allocations and policy compilation happened before spawn" and that the process.rs hook only calls setpgid and setns — none of which matched the code, which compiled both seccomp filters and emitted OCSF from the forked child (and never called setns at all). Rewrite the three comments to describe what the hooks actually do now that the filters are prebuilt and best-effort Landlock failures cross to the parent as fixed-size pipe records: raw session/TTY syscalls and installation of parent-prebuilt sandbox state, with the success and degradation paths free of allocation, tracing, and OCSF emission. State the remaining caveat precisely — only a hard error return may allocate, like std's own pre_exec error reporting — instead of overclaiming. Closes #5180 Signed-off-by: Emilien Macchi --- crates/openshell-sandbox/src/process.rs | 10 ++++++++-- crates/openshell-sandbox/src/pty.rs | 18 ++++++++++++++---- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/crates/openshell-sandbox/src/process.rs b/crates/openshell-sandbox/src/process.rs index 0fe9dd6690..2135fb4a0b 100644 --- a/crates/openshell-sandbox/src/process.rs +++ b/crates/openshell-sandbox/src/process.rs @@ -632,8 +632,14 @@ impl ProcessHandle { // Set up process group for signal handling (non-interactive mode only). // In interactive mode, we inherit the parent's process group to maintain // proper terminal control for shells and interactive programs. - // SAFETY: pre_exec runs after fork but before exec in the child process. - // setpgid and setns are async-signal-safe and safe to call in this context. + // SAFETY: pre_exec runs after fork but before exec in the child of a + // multithreaded process. The hook uses raw session/process-group and + // TTY syscalls plus harden_child_process (rlimit/prctl), then installs + // only parent-prebuilt sandbox state; a best-effort Landlock failure + // crosses to the parent as one fixed-size pipe record. The success and + // degradation paths allocate nothing and emit no tracing or OCSF; only + // a hard error return may allocate, like std's own pre_exec error + // reporting. { // Rebind as mut so the FnMut closure can run the install, which // takes the prepared sandbox out of its Option. diff --git a/crates/openshell-sandbox/src/pty.rs b/crates/openshell-sandbox/src/pty.rs index 2187ebf96d..ef3a8837aa 100644 --- a/crates/openshell-sandbox/src/pty.rs +++ b/crates/openshell-sandbox/src/pty.rs @@ -64,8 +64,13 @@ pub fn install_pre_exec( ) -> anyhow::Result<()> { #[cfg(target_os = "linux")] let mut install = install; - // SAFETY: all allocations and policy compilation happened before spawn; - // the hook performs only the audited child transition. + // SAFETY: the hook runs after fork in the child of a multithreaded + // process. It uses raw session/TTY syscalls and installs only + // parent-prebuilt sandbox state (Landlock rulesets, seccomp filters); + // a best-effort Landlock failure crosses to the parent as one + // fixed-size pipe record. The success and degradation paths allocate + // nothing and emit no tracing or OCSF; only a hard error return may + // allocate, like std's own pre_exec error reporting. unsafe { command.pre_exec(move || { setsid().map_err(|error| std::io::Error::other(error.to_string()))?; @@ -93,8 +98,13 @@ pub fn install_pre_exec_no_pty( ) -> anyhow::Result<()> { #[cfg(target_os = "linux")] let mut install = install; - // SAFETY: all allocations and policy compilation happened before spawn; - // the hook performs only the audited child transition. + // SAFETY: the hook runs after fork in the child of a multithreaded + // process. It uses raw process-group syscalls and installs only + // parent-prebuilt sandbox state (Landlock rulesets, seccomp filters); + // a best-effort Landlock failure crosses to the parent as one + // fixed-size pipe record. The success and degradation paths allocate + // nothing and emit no tracing or OCSF; only a hard error return may + // allocate, like std's own pre_exec error reporting. unsafe { command.pre_exec(move || { if libc::setpgid(0, 0) != 0 { From 2f0e014cbd5a0303d4387c1db76e073304b450f3 Mon Sep 17 00:00:00 2001 From: Emilien Macchi Date: Tue, 1 Dec 2026 09:55:56 -0500 Subject: [PATCH 4/4] fix(sandbox): carry real errnos across the pre_exec error pipe The pre_exec hooks converted child-side failures with io::Error::other(err.to_string()), which allocates between fork and exec and collapses to std's EINVAL fallback: std reports a pre_exec error across its CLOEXEC pipe by raw errno only, so neither the formatted message nor the real errno ever reached the parent. The child-side failure path now returns errno-based io::Errors end to end. harden_child_process, PreparedSeccomp::install, landlock::enforce, enforce_capability_free, and ChildSandboxInstall::enforce return std::io::Result and map each failure to its innermost kernel errno, which the rustix, prctl, seccompiler, and landlock errors all carry. The pre_exec SAFETY comments now describe std's actual error transport instead of claiming it allocates. Part of #5180 Signed-off-by: Emilien Macchi --- crates/openshell-sandbox/src/process.rs | 25 +++++++------ crates/openshell-sandbox/src/pty.rs | 21 ++++++----- .../src/sandbox/linux/landlock.rs | 26 +++++++++++-- .../src/sandbox/linux/mod.rs | 19 +++++----- .../src/sandbox/linux/seccomp.rs | 37 ++++++++++++------- 5 files changed, 80 insertions(+), 48 deletions(-) diff --git a/crates/openshell-sandbox/src/process.rs b/crates/openshell-sandbox/src/process.rs index 2135fb4a0b..13f1dfa9d9 100644 --- a/crates/openshell-sandbox/src/process.rs +++ b/crates/openshell-sandbox/src/process.rs @@ -336,9 +336,12 @@ fn compose_canonical_process_environment( } #[cfg(unix)] -pub fn harden_child_process() -> Result<()> { +pub fn harden_child_process() -> std::io::Result<()> { use rustix::process::{Resource, Rlimit, setrlimit}; + // Called between fork and exec: errors must stay errno-based and + // allocation-free so std's pre_exec error pipe carries the real errno + // to the parent instead of the EINVAL fallback for non-os errors. setrlimit( Resource::Core, Rlimit { @@ -346,13 +349,12 @@ pub fn harden_child_process() -> Result<()> { maximum: Some(0), }, ) - .map_err(|e| miette::miette!("Failed to disable core dumps: {e}"))?; + .map_err(std::io::Error::from)?; #[cfg(target_os = "linux")] { use rustix::process::{DumpableBehavior, set_dumpable_behavior}; - set_dumpable_behavior(DumpableBehavior::NotDumpable) - .map_err(|e| miette::miette!("Failed to set PR_SET_DUMPABLE=0: {e}"))?; + set_dumpable_behavior(DumpableBehavior::NotDumpable).map_err(std::io::Error::from)?; } Ok(()) @@ -637,9 +639,10 @@ impl ProcessHandle { // TTY syscalls plus harden_child_process (rlimit/prctl), then installs // only parent-prebuilt sandbox state; a best-effort Landlock failure // crosses to the parent as one fixed-size pipe record. The success and - // degradation paths allocate nothing and emit no tracing or OCSF; only - // a hard error return may allocate, like std's own pre_exec error - // reporting. + // degradation paths allocate nothing and emit no tracing or OCSF; a + // hard error returns an errno-based io::Error, which std reports + // across the fork pipe without allocating (it forwards the raw errno + // and falls back to EINVAL for non-os errors). { // Rebind as mut so the FnMut closure can run the install, which // takes the prepared sandbox out of its Option. @@ -661,16 +664,14 @@ impl ProcessHandle { return Err(std::io::Error::last_os_error()); } - harden_child_process().map_err(|err| std::io::Error::other(err.to_string()))?; + harden_child_process()?; // Phase 2 (as unprivileged user): Enforce the prepared // Landlock ruleset via restrict_self() and install the // prebuilt seccomp filters. // restrict_self() does not require root. #[cfg(target_os = "linux")] - child_install - .enforce() - .map_err(|err| std::io::Error::other(err.to_string()))?; + child_install.enforce()?; Ok(()) }); @@ -803,7 +804,7 @@ impl ProcessHandle { return Err(std::io::Error::last_os_error()); } - harden_child_process().map_err(|err| std::io::Error::other(err.to_string()))?; + harden_child_process()?; sandbox::apply(&policy, workdir.as_deref()) .map_err(|err| std::io::Error::other(err.to_string()))?; diff --git a/crates/openshell-sandbox/src/pty.rs b/crates/openshell-sandbox/src/pty.rs index ef3a8837aa..1d62f0b245 100644 --- a/crates/openshell-sandbox/src/pty.rs +++ b/crates/openshell-sandbox/src/pty.rs @@ -69,11 +69,13 @@ pub fn install_pre_exec( // parent-prebuilt sandbox state (Landlock rulesets, seccomp filters); // a best-effort Landlock failure crosses to the parent as one // fixed-size pipe record. The success and degradation paths allocate - // nothing and emit no tracing or OCSF; only a hard error return may - // allocate, like std's own pre_exec error reporting. + // nothing and emit no tracing or OCSF; a hard error returns an + // errno-based io::Error, which std reports across the fork pipe + // without allocating (it forwards the raw errno and falls back to + // EINVAL for non-os errors). unsafe { command.pre_exec(move || { - setsid().map_err(|error| std::io::Error::other(error.to_string()))?; + setsid().map_err(std::io::Error::from)?; set_controlling_tty(slave_fd)?; enter_sandbox( &policy, @@ -103,8 +105,10 @@ pub fn install_pre_exec_no_pty( // parent-prebuilt sandbox state (Landlock rulesets, seccomp filters); // a best-effort Landlock failure crosses to the parent as one // fixed-size pipe record. The success and degradation paths allocate - // nothing and emit no tracing or OCSF; only a hard error return may - // allocate, like std's own pre_exec error reporting. + // nothing and emit no tracing or OCSF; a hard error returns an + // errno-based io::Error, which std reports across the fork pipe + // without allocating (it forwards the raw errno and falls back to + // EINVAL for non-os errors). unsafe { command.pre_exec(move || { if libc::setpgid(0, 0) != 0 { @@ -124,13 +128,10 @@ fn enter_sandbox( policy: &SandboxPolicy, #[cfg(target_os = "linux")] install: &mut crate::sandbox::linux::ChildSandboxInstall, ) -> std::io::Result<()> { - crate::process::harden_child_process() - .map_err(|error| std::io::Error::other(error.to_string()))?; + crate::process::harden_child_process()?; #[cfg(target_os = "linux")] - install - .enforce() - .map_err(|error| std::io::Error::other(error.to_string()))?; + install.enforce()?; #[cfg(not(target_os = "linux"))] crate::sandbox::apply(policy, None) diff --git a/crates/openshell-sandbox/src/sandbox/linux/landlock.rs b/crates/openshell-sandbox/src/sandbox/linux/landlock.rs index 198fe5d2ee..6d74a5da0b 100644 --- a/crates/openshell-sandbox/src/sandbox/linux/landlock.rs +++ b/crates/openshell-sandbox/src/sandbox/linux/landlock.rs @@ -461,17 +461,35 @@ impl std::fmt::Display for DegradedCause { /// it restricts the calling thread and its future children. /// /// Respects the same `best_effort` / `hard_requirement` compatibility as -/// [`prepare`]. A `hard_requirement` failure returns `Err` and may allocate -/// like any aborting error path. A `best_effort` failure returns +/// [`prepare`]. A `hard_requirement` failure returns an errno-based +/// `io::Error`: std reports a `pre_exec` error by raw errno across the +/// fork pipe (non-os errors surface as EINVAL), so the real errno reaches +/// the parent without allocating. A `best_effort` failure returns /// [`LandlockOutcome::Degraded`] built without formatting or logging: the /// spawn surfaces forward it to the parent through a /// [`LandlockReportPipe`]. Fresh-process callers that can format the error /// use [`enforce_fresh`] instead. -pub fn enforce(prepared: PreparedRuleset) -> Result { +pub fn enforce(prepared: PreparedRuleset) -> std::io::Result { match restrict_self_with_compatibility(prepared) { Ok(RestrictSelfOutcome::Enforced) => Ok(LandlockOutcome::Enforced), Ok(RestrictSelfOutcome::Degraded { cause, .. }) => Ok(LandlockOutcome::Degraded(cause)), - Err(error) => Err(error).into_diagnostic(), + Err(error) => Err(hard_requirement_error(&error)), + } +} + +/// Map a hard-requirement failure to the errno-based `io::Error` std's +/// pre-exec error pipe carries. +/// +/// std forwards a `pre_exec` error to the parent by raw errno only (non-os +/// errors surface as EINVAL), so extracting the innermost errno keeps the +/// real failure visible. Both `RestrictSelfError` variants wrap an +/// `io::Error` today; the no-errno fallback only guards future non-io +/// variants, whose rendering is lost to the pipe's errno-only transport +/// anyway. +fn hard_requirement_error(error: &RulesetError) -> std::io::Error { + match degraded_cause(error) { + DegradedCause::Errno(errno) => std::io::Error::from_raw_os_error(errno), + DegradedCause::NoErrno => std::io::Error::other(error.to_string()), } } diff --git a/crates/openshell-sandbox/src/sandbox/linux/mod.rs b/crates/openshell-sandbox/src/sandbox/linux/mod.rs index a7d98a1e7b..0a92996a31 100644 --- a/crates/openshell-sandbox/src/sandbox/linux/mod.rs +++ b/crates/openshell-sandbox/src/sandbox/linux/mod.rs @@ -6,7 +6,7 @@ mod landlock; mod seccomp; -use miette::Result; +use miette::{IntoDiagnostic, Result}; use openshell_core::policy::SandboxPolicy; use std::path::PathBuf; use std::sync::Once; @@ -85,7 +85,7 @@ pub fn enforce(prepared: PreparedSandbox) -> Result<()> { for ruleset in prepared.landlock { landlock::enforce_fresh(ruleset)?; } - prepared.seccomp.install()?; + prepared.seccomp.install().into_diagnostic()?; Ok(()) } @@ -99,21 +99,21 @@ pub fn enforce(prepared: PreparedSandbox) -> Result<()> { /// is written to the report pipe as one fixed-size, async-signal-safe record /// before the child self-protection filter is installed, so the `write(2)` /// cannot block on the seccomp broker and the parent reports the finding -/// after spawn. +/// after spawn. A hard failure returns an errno-based `io::Error`: std +/// reports a `pre_exec` error by raw errno across the fork pipe (non-os +/// errors surface as EINVAL), so the real errno reaches the parent. pub fn enforce_capability_free( prepared: PreparedSandbox, child_hardening: &mut crate::linux::child_seccomp::ChildHardeningProgram, report: LandlockReportFd, -) -> Result<()> { +) -> std::io::Result<()> { for ruleset in prepared.landlock { match landlock::enforce(ruleset)? { landlock::LandlockOutcome::Enforced => {} landlock::LandlockOutcome::Degraded(cause) => report.report_degraded(cause), } } - child_hardening - .install() - .map_err(|error| miette::miette!("install child self-protection filter: {error}"))?; + child_hardening.install()?; prepared.seccomp.install()?; Ok(()) } @@ -152,8 +152,9 @@ impl ChildSandboxInstall { /// /// A no-op when no sandbox was prepared, matching the previous optional /// plumbing: the child hardening program is only installed alongside a - /// prepared sandbox. - pub(crate) fn enforce(&mut self) -> Result<()> { + /// prepared sandbox. A hard failure returns an errno-based `io::Error` + /// for std's non-allocating pre-exec error pipe. + pub(crate) fn enforce(&mut self) -> std::io::Result<()> { let Some(prepared) = self.prepared.take() else { return Ok(()); }; diff --git a/crates/openshell-sandbox/src/sandbox/linux/seccomp.rs b/crates/openshell-sandbox/src/sandbox/linux/seccomp.rs index 0133628dac..bd1e408709 100644 --- a/crates/openshell-sandbox/src/sandbox/linux/seccomp.rs +++ b/crates/openshell-sandbox/src/sandbox/linux/seccomp.rs @@ -67,7 +67,7 @@ use libc::SYS_kexec_file_load; /// longer needs once bootstrap is complete. pub fn apply_supervisor_prelude() -> Result<()> { let filter = build_supervisor_prelude_filter()?; - set_no_new_privs()?; + set_no_new_privs().into_diagnostic()?; apply_filter_all_threads(&filter).into_diagnostic()?; Ok(()) } @@ -97,10 +97,11 @@ impl PreparedSeccomp { /// Install the prebuilt filters in the required order. /// /// This runs in the forked child before `exec` and must stay free of - /// allocation, tracing, and OCSF emission on the success path. Only the - /// hard-error return may allocate (std's `pre_exec` machinery allocates - /// on `Err` anyway). - pub fn install(&self) -> Result<()> { + /// allocation, tracing, and OCSF emission on the success path. A hard + /// failure returns an errno-based `io::Error`: std reports a `pre_exec` + /// error by raw errno across a CLOEXEC pipe (non-os errors surface as + /// EINVAL), so the real errno reaches the parent without allocating. + pub fn install(&self) -> std::io::Result<()> { set_no_new_privs()?; apply_runtime_filters(&self.main, &self.compatibility) } @@ -154,7 +155,7 @@ fn build_supervisor_prelude_rules() -> BTreeMap> { rules } -fn set_no_new_privs() -> Result<()> { +fn set_no_new_privs() -> std::io::Result<()> { // libc/syscall FFI requires unsafe #[allow(unsafe_code)] // SAFETY: prctl receives only scalar arguments; PR_SET_NO_NEW_PRIVS is @@ -162,10 +163,7 @@ fn set_no_new_privs() -> Result<()> { // irreversible. let rc = unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) }; if rc != 0 { - return Err(miette::miette!( - "Failed to set no_new_privs: {}", - std::io::Error::last_os_error() - )); + return Err(std::io::Error::last_os_error()); } Ok(()) @@ -213,12 +211,25 @@ fn build_compatibility_filter() -> Result { fn apply_runtime_filters( main_filter: seccompiler::BpfProgramRef<'_>, compatibility_filter: seccompiler::BpfProgramRef<'_>, -) -> Result<()> { - apply_filter(compatibility_filter).into_diagnostic()?; - apply_filter(main_filter).into_diagnostic()?; +) -> std::io::Result<()> { + apply_filter(compatibility_filter).map_err(seccomp_install_error)?; + apply_filter(main_filter).map_err(seccomp_install_error)?; Ok(()) } +/// Map a seccompiler failure to an errno-based `io::Error` for std's +/// pre-exec error pipe. +/// +/// The `Prctl` and `Seccomp` variants wrap the kernel's `io::Error`; the +/// remaining variants (empty filter, thread sync, backend) carry no errno, +/// and their rendering is lost to the pipe's errno-only transport anyway. +fn seccomp_install_error(error: seccompiler::Error) -> std::io::Error { + match error { + seccompiler::Error::Prctl(source) | seccompiler::Error::Seccomp(source) => source, + _ => std::io::Error::other(error.to_string()), + } +} + fn build_filter_rules(allow_inet: bool) -> Result>> { let mut rules: BTreeMap> = BTreeMap::new();