diff --git a/crates/sandlock-core/src/context.rs b/crates/sandlock-core/src/context.rs index 96d35a9f4..ddcbb99e1 100644 --- a/crates/sandlock-core/src/context.rs +++ b/crates/sandlock-core/src/context.rs @@ -6,7 +6,6 @@ use std::io; use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; use crate::child_env::ChildEnv; -use crate::features::SandboxFeatures; use crate::sandbox::Sandbox; use crate::seccomp::bpf; use crate::seccomp::filter::FilterSpec; @@ -214,13 +213,10 @@ pub(crate) struct ChildSpawnArgs<'a> { /// deny filter, parent reads `notif_fd_num = 0` and never starts a /// supervisor. Mirrors `Sandbox::no_supervisor`. pub no_supervisor: bool, - /// Derived before fork so the filter and the supervisor share one view. - pub features: SandboxFeatures, + /// Built before fork: the supervisor checks its handlers against the + /// same spec the child installs. + pub filter: &'a FilterSpec, pub keep_fds: &'a [RawFd], - /// Syscall numbers for which the parent registered user `Handler`s. - /// Merged into the child's BPF notif list so the kernel actually - /// raises USER_NOTIF for them. - pub extra_syscalls: &'a [u32], /// Make the child the terminal's foreground process group before exec. /// Only interactive (fully inherited) stdio wants this; a captured or /// piped run taking the foreground demotes the embedding process to a @@ -271,9 +267,8 @@ pub(crate) fn confine_child(args: ChildSpawnArgs<'_>) -> ! { env, pipes, no_supervisor, - features, + filter, keep_fds, - extra_syscalls, foreground, } = args; // Helper: abort child on error. Includes the OS error automatically. @@ -430,15 +425,15 @@ pub(crate) fn confine_child(args: ChildSpawnArgs<'_>) -> ! { // 9. Assemble and install seccomp filter (IRREVERSIBLE) let mut keep_fd: i32 = -1; + let filter = match filter.assemble() { + Ok(f) => f, + Err(e) => fail!(format!("seccomp assemble: {}", e)), + }; if no_supervisor { // No-supervisor mode: deny-only kernel filter, no NEW_LISTENER. // BPF filters are ANDed by the kernel, so an outer filter (from a // wrapping sandbox) keeps tightening this layer too. - let filter = match FilterSpec::no_supervisor(sandbox, &features).assemble() { - Ok(f) => f, - Err(e) => fail!(format!("seccomp assemble: {}", e)), - }; if let Err(e) = bpf::install_deny_filter(&filter) { fail!(format!("seccomp deny filter: {}", e)); } @@ -451,11 +446,6 @@ pub(crate) fn confine_child(args: ChildSpawnArgs<'_>) -> ! { } } else { // First-level sandbox: notif + deny filter with NEW_LISTENER. - let spec = FilterSpec::supervised(sandbox, &features, extra_syscalls); - let filter = match spec.assemble() { - Ok(f) => f, - Err(e) => fail!(format!("seccomp assemble: {}", e)), - }; let listener = match bpf::install_filter(&filter) { Ok(listener) => listener, Err(e) => { diff --git a/crates/sandlock-core/src/sandbox.rs b/crates/sandlock-core/src/sandbox.rs index d742be506..bf01729e2 100644 --- a/crates/sandlock-core/src/sandbox.rs +++ b/crates/sandlock-core/src/sandbox.rs @@ -13,6 +13,7 @@ pub use crate::grant::Grant; pub use crate::http::{http_acl_check, normalize_path, prefix_or_exact_match, HttpRule}; pub use crate::network::{IpCidr, NetAllow, NetDeny, NetRule, NetTarget, Protocol}; use crate::protection::{Protection, ProtectionPolicy, ProtectionState, ProtectionStatus}; +use crate::seccomp::filter::FilterSpec; mod builder; pub use builder::SandboxBuilder; @@ -2083,7 +2084,7 @@ impl Sandbox { let _ = crate::landlock_policy::confine(&sandbox_cfg); let features = crate::features::SandboxFeatures::from_sandbox(&sandbox_cfg, None, &[]); - let spec = crate::seccomp::filter::FilterSpec::deny_only(&sandbox_cfg, &features); + let spec = FilterSpec::deny_only(&sandbox_cfg, &features); let filter = match spec.assemble() { Ok(f) => f, Err(_) => unsafe { libc::_exit(1) }, @@ -2555,6 +2556,12 @@ impl Sandbox { Some(resolved_sandbox_name.as_str()), &handler_syscalls, ); + let filter = if no_supervisor { + FilterSpec::no_supervisor(self, &features) + } else { + let handler_nrs: Vec = handler_syscalls.iter().map(|&nr| nr as u32).collect(); + FilterSpec::supervised(self, &features, &handler_nrs) + }; // Per-stream stdio wiring. Each Piped stream gets a CLOEXEC pipe whose // parent-side end we keep: the caller writes the child's stdin and reads @@ -2699,8 +2706,6 @@ impl Sandbox { let gather_keep_fds: Vec = extra_fds_copy.iter().map(|&(target, _)| target).collect(); - let extra_syscalls: Vec = self.rt().handlers.iter().map(|h| h.0 as u32).collect(); - // In-process entrypoint (OCI PID-1) names the process from cmd[0]; // otherwise execve the command. let entry = match (self.in_child_main, self.rt().exec_fd) { @@ -2717,9 +2722,8 @@ impl Sandbox { env: &child_env, pipes: &pipes, no_supervisor, - features, + filter: &filter, keep_fds: &gather_keep_fds, - extra_syscalls: &extra_syscalls, foreground, }); } @@ -3000,7 +3004,7 @@ impl Sandbox { let control_ctx = Arc::clone(&ctx); self.rt_mut().notif_handle = Some(tokio::spawn(notif::supervisor( - notif_fd, ctx, handlers, startup_tx, + notif_fd, ctx, handlers, filter, startup_tx, ))); // Wait for the supervisor to register the notif fd with the IO // driver before we release the child to execve. Otherwise an diff --git a/crates/sandlock-core/src/seccomp/dispatch.rs b/crates/sandlock-core/src/seccomp/dispatch.rs index 4d644ba06..760e0186f 100644 --- a/crates/sandlock-core/src/seccomp/dispatch.rs +++ b/crates/sandlock-core/src/seccomp/dispatch.rs @@ -21,6 +21,7 @@ use std::os::unix::io::RawFd; use std::sync::Arc; use super::ctx::SupervisorCtx; +use super::filter::{self, open_family_syscalls, FilterSpec}; use super::notif::{NotifAction, NotifPolicy, OpenRequest}; use super::state::ResourceState; use super::syscall::SyscallError; @@ -167,21 +168,6 @@ pub enum HandlerError { /// /// The blocklist is whatever [`super::filter::blocklist`] /// resolves from Sandlock's default syscall blocklist plus policy extras. -/// -/// Every open-family syscall a path-keyed handler must intercept to be -/// leak-proof: `open` (legacy), `openat`, and `openat2`. A handler that -/// only registers `openat` is bypassed by any libc that picks one of -/// the others. The corresponding BPF notif list (in `seccomp::filter`) -/// must register the same set so the kernel actually produces a -/// notification — otherwise `RET_ALLOW` makes the handler unreachable. -fn open_family_syscalls() -> Vec { - let mut v = vec![libc::SYS_openat, arch::SYS_OPENAT2]; - if let Some(legacy_open) = arch::sys_open() { - v.push(legacy_open); - } - v -} - /// Takes only the syscall numbers because that's all it needs to check. /// Called from the `run_with_handlers` entry points before any /// handler is registered against the dispatch table. @@ -244,6 +230,12 @@ impl DispatchTable { .push(handler); } + /// A syscall with a handler the kernel never notifies: the filter allows + /// it, so the handler would silently never run. + pub(crate) fn unreachable_under(&self, filter: &FilterSpec) -> Option { + self.chains.keys().copied().find(|&nr| !filter.notifies(nr)) + } + /// The handler chain for a notification, not yet started. pub(crate) fn chain( &self, @@ -314,6 +306,7 @@ pub(crate) fn build_dispatch_table( policy: &Arc, resource: &Arc>, ctx: &Arc, + spec: &FilterSpec, pending_handlers: Vec<(i64, std::sync::Arc)>, ) -> DispatchTable { let mut table = DispatchTable::new(); @@ -338,14 +331,7 @@ pub(crate) fn build_dispatch_table( // Memory management (conditional on memory_limit) // ------------------------------------------------------------------ if policy.features.memory_limit { - for &nr in &[ - libc::SYS_mmap, - libc::SYS_munmap, - libc::SYS_brk, - libc::SYS_mremap, - libc::SYS_mprotect, - libc::SYS_shmget, - ] { + for nr in filter::memory_accounting_syscalls(&policy.features) { let policy_for_mem = Arc::clone(policy); let __sup = Arc::clone(ctx); table.register(nr, move |cx: &HandlerCtx| { @@ -360,7 +346,7 @@ pub(crate) fn build_dispatch_table( // its brk base; see handle_exec_memory_reset. Registered first for // these nrs (always Continue), so later chroot/COW exec handlers // still run. - for &nr in &[libc::SYS_execve, libc::SYS_execveat] { + for &nr in filter::EXEC_SYSCALLS { let __sup = Arc::clone(ctx); table.register(nr, move |cx: &HandlerCtx| { let notif = cx.notif; @@ -376,12 +362,7 @@ pub(crate) fn build_dispatch_table( // network_destination_policy, so it isn't listed. // ------------------------------------------------------------------ if policy.features.network_destination_policy || policy.supervises_named_unix() { - for &nr in &[ - libc::SYS_connect, - libc::SYS_sendto, - libc::SYS_sendmsg, - libc::SYS_sendmmsg, - ] { + for &nr in filter::DESTINATION_SYSCALLS { let __sup = Arc::clone(ctx); table.register(nr, move |cx: &HandlerCtx| { let notif = cx.notif; @@ -444,11 +425,7 @@ pub(crate) fn build_dispatch_table( // ------------------------------------------------------------------ if policy.features.time_start { let time_offset = policy.time_offset; - for &nr in &[ - libc::SYS_clock_nanosleep as i64, - libc::SYS_timerfd_settime as i64, - libc::SYS_timer_settime as i64, - ] { + for &nr in filter::TIMER_SYSCALLS { table.register(nr, move |cx: &HandlerCtx| { let notif = cx.notif; let notif_fd = cx.notif_fd; @@ -625,9 +602,9 @@ pub(crate) fn build_dispatch_table( } // ------------------------------------------------------------------ - // sysinfo virtualization (always on, like /proc/loadavg) + // sysinfo virtualization (on unless the policy denies sysinfo) // ------------------------------------------------------------------ - { + if spec.notifies(libc::SYS_sysinfo) { let policy = Arc::clone(policy); let resource = Arc::clone(resource); let sup = Arc::clone(ctx); @@ -1579,6 +1556,22 @@ mod handler_tests { // ---- Handler trait tests -------------------------------------- + #[test] + fn a_handler_on_an_unnotified_syscall_is_unreachable() { + let policy = crate::sandbox::Sandbox::builder().build().unwrap(); + let features = crate::features::SandboxFeatures::from_sandbox(&policy, None, &[]); + let mut table = DispatchTable::new(); + table.register(libc::SYS_getpid, |_cx: &HandlerCtx| async { + NotifAction::Continue + }); + + let unaware = FilterSpec::supervised(&policy, &features, &[]); + assert_eq!(table.unreachable_under(&unaware), Some(libc::SYS_getpid)); + + let aware = FilterSpec::supervised(&policy, &features, &[libc::SYS_getpid as u32]); + assert_eq!(table.unreachable_under(&aware), None); + } + #[tokio::test] async fn handler_via_blanket_impl_dispatches_closures() { use std::sync::atomic::{AtomicU64, Ordering}; diff --git a/crates/sandlock-core/src/seccomp/filter.rs b/crates/sandlock-core/src/seccomp/filter.rs index 203016514..475b866a6 100644 --- a/crates/sandlock-core/src/seccomp/filter.rs +++ b/crates/sandlock-core/src/seccomp/filter.rs @@ -67,6 +67,11 @@ impl FilterSpec { } } + /// Whether the kernel raises a notification for `nr` at all. + pub(crate) fn notifies(&self, nr: i64) -> bool { + self.notify.binary_search(&(nr as u32)).is_ok() + } + pub(crate) fn assemble(&self) -> std::io::Result> { bpf::assemble_filter(&self.notify, &self.deny, &self.arg_block) } @@ -121,41 +126,53 @@ const BASE_NOTIF_SYSCALLS: &[i64] = &[ libc::SYS_setpgid, ]; -const MEMORY_NOTIF_SYSCALLS: &[i64] = &[ - libc::SYS_mmap, - libc::SYS_munmap, - libc::SYS_brk, - libc::SYS_mremap, - // Only calls granting PROT_WRITE reach the supervisor; see arg_block. - libc::SYS_mprotect, - // exec destroys the address space and the kernel picks a fresh - // randomized brk base, so brk accounting must observe it to drop the - // old image's base; otherwise the new image's first brk is charged the - // ASLR distance between the two heaps. - libc::SYS_execve, - libc::SYS_execveat, -]; +// The lists below are iterated by `build_dispatch_table` as well, so a +// handler is registered for exactly the syscalls the filter notifies. + +pub(crate) fn memory_accounting_syscalls(features: &SandboxFeatures) -> Vec { + let mut v = vec![ + libc::SYS_mmap, + libc::SYS_munmap, + libc::SYS_brk, + libc::SYS_mremap, + // Only calls granting PROT_WRITE reach the supervisor; see arg_block. + libc::SYS_mprotect, + ]; + // Without "sysv_ipc" in extra_allow_syscalls shmget is on the + // blocklist, and notifying it would bypass that deny. + if features.sysv_ipc_allowed { + v.push(libc::SYS_shmget); + } + v +} -const NETWORK_POLICY_SYSCALLS: &[i64] = &[ +pub(crate) const EXEC_SYSCALLS: &[i64] = &[libc::SYS_execve, libc::SYS_execveat]; + +/// Syscalls that name a peer: `connect` for streams, the sends for datagrams. +pub(crate) const DESTINATION_SYSCALLS: &[i64] = &[ libc::SYS_connect, libc::SYS_sendto, libc::SYS_sendmsg, libc::SYS_sendmmsg, - libc::SYS_bind, ]; -// Also intercept openat so the supervisor can re-patch vDSO after exec. -const RANDOM_NOTIF_SYSCALLS: &[i64] = &[libc::SYS_getrandom, libc::SYS_openat]; - -// Also intercept openat so the supervisor gets a notification after exec -// and can re-patch the vDSO (exec replaces vDSO with a fresh copy). -const TIME_NOTIF_SYSCALLS: &[i64] = &[ +pub(crate) const TIMER_SYSCALLS: &[i64] = &[ libc::SYS_clock_nanosleep, libc::SYS_timerfd_settime, libc::SYS_timer_settime, - libc::SYS_openat, ]; +/// Every spelling of open a path-keyed handler must see: a libc that picks +/// one the handler does not cover reads the real file. +pub(crate) fn open_family_syscalls() -> Vec { + let mut v = vec![libc::SYS_openat, arch::SYS_OPENAT2]; + v.extend(arch::sys_open()); + v +} + +// Also intercept openat so the supervisor can re-patch vDSO after exec. +const RANDOM_NOTIF_SYSCALLS: &[i64] = &[libc::SYS_getrandom, libc::SYS_openat]; + // /proc virtualization + /etc/hosts virtualization (always on). // // `openat` carries the simple `(AT_FDCWD, "/proc/...")` and @@ -166,12 +183,9 @@ const TIME_NOTIF_SYSCALLS: &[i64] = &[ // a caller that picks `open` or `openat2` slips past virtualization // and reads the real on-disk file. fn procfs_hosts_notif_syscalls() -> Vec { - let mut v = vec![libc::SYS_openat, arch::SYS_OPENAT2, libc::SYS_getdents64]; - v.extend( - [arch::sys_open(), arch::sys_getdents()] - .into_iter() - .flatten(), - ); + let mut v = open_family_syscalls(); + v.push(libc::SYS_getdents64); + v.extend(arch::sys_getdents()); v.push(libc::SYS_lseek); v.extend(crate::procfs::net_dispatch::metadata_syscalls()); v @@ -409,8 +423,6 @@ const POLICY_NETWORK_EVENT_SYSCALLS: &[i64] = &[ libc::SYS_bind, ]; -const POLICY_EXEC_EVENT_SYSCALLS: &[i64] = &[libc::SYS_execve, libc::SYS_execveat]; - const PORT_REMAP_SYSCALLS: &[i64] = &[libc::SYS_bind, libc::SYS_getsockname]; /// Syscalls that need `SECCOMP_RET_USER_NOTIF`. @@ -423,30 +435,24 @@ fn notify_syscalls(features: &SandboxFeatures, deny: &[u32]) -> Vec { nrs.push_optional(arch::sys_fork()); if features.memory_limit { - nrs.extend(MEMORY_NOTIF_SYSCALLS); - // shmget is in notif only when SysV IPC is allowed. The BPF - // layout puts notif JEQs before deny JEQs, so a syscall on - // both lists would notify (RET_USER_NOTIF) and silently - // bypass the kernel-level deny. When extra_allow_syscalls does not contain "sysv_ipc", - // shmget belongs only on the blocklist. - if features.sysv_ipc_allowed { - nrs.push(libc::SYS_shmget); - } + nrs.extend(&memory_accounting_syscalls(features)); + // exec destroys the address space and the kernel picks a fresh + // randomized brk base, so brk accounting must observe it to drop the + // old image's base; otherwise the new image's first brk is charged the + // ASLR distance between the two heaps. + nrs.extend(EXEC_SYSCALLS); } if features.network_supervision { - nrs.extend(NETWORK_POLICY_SYSCALLS); + nrs.extend(DESTINATION_SYSCALLS); + nrs.push(libc::SYS_bind); } else if features.unix_fs_gate && (!features.landlock_unix_gate || features.chroot) { - // Named-unix gate: trap connect() (stream) and sendto()/sendmsg()/ - // sendmmsg() (datagram) so reaching a unix socket outside the fs-write - // grants is denied, even when no IP network rules are present. Landlock + // Named-unix gate: reaching a unix socket outside the fs-write + // grants is denied even when no IP network rules are present. Landlock // before ABI v9 cannot gate this, and under chroot no Landlock can, - // since the kernel would resolve the address on the host. Handlers bail cheaply on addr-less - // (connected) sends. - nrs.push(libc::SYS_connect); - nrs.push(libc::SYS_sendto); - nrs.push(libc::SYS_sendmsg); - nrs.push(libc::SYS_sendmmsg); + // since the kernel would resolve the address on the host. Handlers + // bail cheaply on addr-less (connected) sends. + nrs.extend(DESTINATION_SYSCALLS); } if features.random_seed { @@ -454,7 +460,10 @@ fn notify_syscalls(features: &SandboxFeatures, deny: &[u32]) -> Vec { } if features.time_start { - nrs.extend(TIME_NOTIF_SYSCALLS); + nrs.extend(TIMER_SYSCALLS); + // exec replaces the vDSO with a fresh copy; the open that follows + // is where the supervisor patches it again. + nrs.push(libc::SYS_openat); } nrs.extend(&procfs_hosts_notif_syscalls()); @@ -498,7 +507,7 @@ fn notify_syscalls(features: &SandboxFeatures, deny: &[u32]) -> Vec { nrs.extend(POLICY_NETWORK_EVENT_SYSCALLS); } if features.policy_events.contains(SyscallCategory::Exec) { - nrs.extend(POLICY_EXEC_EVENT_SYSCALLS); + nrs.extend(EXEC_SYSCALLS); } // Port remapping diff --git a/crates/sandlock-core/src/seccomp/notif.rs b/crates/sandlock-core/src/seccomp/notif.rs index 59d70cef9..31a7e56e8 100644 --- a/crates/sandlock-core/src/seccomp/notif.rs +++ b/crates/sandlock-core/src/seccomp/notif.rs @@ -3339,10 +3339,11 @@ async fn settle_parked( /// `pending_handlers` are user-supplied syscall handlers registered after all /// builtin handlers. For the default behaviour without any custom handlers /// pass an empty `Vec`. -pub async fn supervisor( +pub(crate) async fn supervisor( notif_fd: OwnedFd, ctx: Arc, pending_handlers: Vec<(i64, std::sync::Arc)>, + filter: super::filter::FilterSpec, startup: tokio::sync::oneshot::Sender>, ) { // Register the notif fd with the Tokio IO driver so we can wait for @@ -3367,8 +3368,16 @@ pub async fn supervisor( &ctx.policy, &ctx.resource, &ctx, + &filter, pending_handlers, )); + if let Some(nr) = dispatch_table.unreachable_under(&filter) { + let _ = startup.send(Err(io::Error::new( + io::ErrorKind::Other, + format!("syscall {nr} has a handler but the seccomp filter does not notify it"), + ))); + return; + } // Try to enable sync wakeup (Linux 6.7+, ignore error on older kernels). try_set_sync_wakeup(fd);