From c46a60c3914ee486aeafd2b90881b2c5a98701d7 Mon Sep 17 00:00:00 2001 From: Cong Wang Date: Sat, 28 Nov 2026 11:44:54 -0800 Subject: [PATCH 1/2] seccomp: share one SandboxFeatures between the filter and the supervisor The feature gates lived in three places: SandboxFeatures behind a one-field ResolvedSandbox wrapper, and a renamed copy of each flag on NotifPolicy. The child derived its own copy after fork to build the BPF filter while the parent derived another for the supervisor, so nothing tied the trapped syscalls to the handlers gated on the same facts. Derive SandboxFeatures once before fork, hand it to the child, and embed it in NotifPolicy in place of the copied flags. Signed-off-by: Cong Wang --- crates/sandlock-core/src/context.rs | 15 ++--- .../src/{resolved.rs => features.rs} | 46 ++++++---------- crates/sandlock-core/src/lib.rs | 2 +- crates/sandlock-core/src/network/connect.rs | 4 +- crates/sandlock-core/src/network/send.rs | 6 +- crates/sandlock-core/src/policy_fn.rs | 2 +- crates/sandlock-core/src/procfs.rs | 4 +- crates/sandlock-core/src/procfs/net.rs | 4 +- crates/sandlock-core/src/resource.rs | 26 ++++----- crates/sandlock-core/src/sandbox.rs | 18 ++---- crates/sandlock-core/src/seccomp/dispatch.rs | 41 ++++++-------- crates/sandlock-core/src/seccomp/notif.rs | 55 ++++--------------- crates/sandlock-core/src/seccomp_plan.rs | 14 ++--- 13 files changed, 82 insertions(+), 155 deletions(-) rename crates/sandlock-core/src/{resolved.rs => features.rs} (78%) diff --git a/crates/sandlock-core/src/context.rs b/crates/sandlock-core/src/context.rs index 61ed8161e..c1b7d6ff6 100644 --- a/crates/sandlock-core/src/context.rs +++ b/crates/sandlock-core/src/context.rs @@ -6,7 +6,7 @@ use std::io; use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; use crate::child_env::ChildEnv; -use crate::resolved::ResolvedSandbox; +use crate::features::SandboxFeatures; use crate::sandbox::Sandbox; use crate::seccomp::bpf; @@ -246,10 +246,9 @@ 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, pub keep_fds: &'a [RawFd], - /// Sandbox instance name. When set, it is also exposed as the - /// sandbox's virtual hostname. - pub sandbox_name: Option<&'a str>, /// 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. @@ -304,8 +303,8 @@ pub(crate) fn confine_child(args: ChildSpawnArgs<'_>) -> ! { env, pipes, no_supervisor, + features, keep_fds, - sandbox_name, extra_syscalls, foreground, } = args; @@ -462,9 +461,7 @@ pub(crate) fn confine_child(args: ChildSpawnArgs<'_>) -> ! { } // 9. Assemble and install seccomp filter (IRREVERSIBLE) - let handler_syscalls: Vec = extra_syscalls.iter().map(|&nr| nr as i64).collect(); - let resolved = ResolvedSandbox::from_sandbox(sandbox, sandbox_name, &handler_syscalls); - let args = arg_filters_resolved(&resolved); + let args = arg_filters_resolved(&features); let mut keep_fd: i32 = -1; if no_supervisor { @@ -500,7 +497,7 @@ pub(crate) fn confine_child(args: ChildSpawnArgs<'_>) -> ! { // them and the handler silently never fires. We merge `extra_syscalls` // into the notif list and dedup so each syscall produces exactly one // JEQ in the assembled program. - let mut notif = notif_syscalls_resolved(&resolved); + let mut notif = notif_syscalls_resolved(&features); if !extra_syscalls.is_empty() { notif.extend_from_slice(extra_syscalls); } diff --git a/crates/sandlock-core/src/resolved.rs b/crates/sandlock-core/src/features.rs similarity index 78% rename from crates/sandlock-core/src/resolved.rs rename to crates/sandlock-core/src/features.rs index ffce817ab..c2b0112d4 100644 --- a/crates/sandlock-core/src/resolved.rs +++ b/crates/sandlock-core/src/features.rs @@ -1,40 +1,26 @@ use crate::policy_fn::{CategorySet, SyscallCategory}; use crate::sandbox::Sandbox; -/// Internal normalized view of a sandbox configuration. -/// -/// `Sandbox` is the public configuration surface. `ResolvedSandbox` is the -/// private shape used by runtime setup after defaults and feature activation -/// have been reduced to named facts. -#[derive(Debug, Clone)] -pub(crate) struct ResolvedSandbox { - pub(crate) features: SandboxFeatures, -} - -impl ResolvedSandbox { - pub(crate) fn from_sandbox( - sandbox: &Sandbox, - sandbox_name: Option<&str>, - handler_syscalls: &[i64], - ) -> Self { - Self { - features: SandboxFeatures::from_sandbox(sandbox, sandbox_name, handler_syscalls), - } - } -} - -/// Boolean feature gates derived from a sandbox configuration. -/// -/// These are deliberately named around runtime behavior instead of raw option -/// names. That keeps syscall planning and supervisor setup from re-encoding -/// the same `Option`/empty-list checks in several places. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +/// Feature gates derived once from a sandbox configuration and shared by the +/// seccomp filter and the supervisor, so the two cannot disagree on what is +/// active. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub(crate) struct SandboxFeatures { pub(crate) memory_limit: bool, pub(crate) network_supervision: bool, + /// A destination policy is active: a `net_allow` allowlist, a `net_deny` + /// denylist, an HTTP ACL, or a live `policy_fn`. The on-behalf path is + /// then the IP-level enforcer for connect/sendto/sendmsg and must never + /// `Continue`; otherwise those syscalls are trapped only to gate named + /// `AF_UNIX` sockets and IP destinations go back to the kernel. pub(crate) network_destination_policy: bool, + /// `--net-deny-bind` is active, independent of the connect side. pub(crate) bind_denylist: bool, + /// `connect()` to a named unix socket outside the fs-write grants is + /// denied. Abstract sockets are scoped by Landlock instead. pub(crate) unix_fs_gate: bool, + /// The host's Landlock enforces [`Self::unix_fs_gate`] itself, so the + /// caller can connect in its own name. pub(crate) landlock_unix_gate: bool, pub(crate) random_seed: bool, pub(crate) time_start: bool, @@ -48,6 +34,8 @@ pub(crate) struct SandboxFeatures { pub(crate) policy_events: CategorySet, pub(crate) port_remap: bool, pub(crate) http_acl: bool, + /// Every task that could mutate argv must be frozen before a consumer + /// reads it, and fork events are traced so the freeze sees every task. pub(crate) argv_safety_required: bool, pub(crate) sysv_ipc_allowed: bool, /// Whether an outbound allow layer is active. Derived from the separated @@ -58,7 +46,7 @@ pub(crate) struct SandboxFeatures { } impl SandboxFeatures { - fn from_sandbox( + pub(crate) fn from_sandbox( sandbox: &Sandbox, sandbox_name: Option<&str>, handler_syscalls: &[i64], diff --git a/crates/sandlock-core/src/lib.rs b/crates/sandlock-core/src/lib.rs index 1418a68b6..1b26f6a41 100644 --- a/crates/sandlock-core/src/lib.rs +++ b/crates/sandlock-core/src/lib.rs @@ -17,6 +17,7 @@ pub(crate) mod credential; pub(crate) mod credential; pub mod error; pub mod expand; +pub(crate) mod features; pub mod fork; pub(crate) mod freeze; pub mod grant; @@ -38,7 +39,6 @@ pub(crate) mod random; pub(crate) mod reaper; #[cfg(feature = "cow")] pub mod recovery; -pub(crate) mod resolved; pub(crate) mod resource; pub mod result; pub mod sandbox; // formerly `policy`; contains Sandbox + SandboxBuilder + Confinement diff --git a/crates/sandlock-core/src/network/connect.rs b/crates/sandlock-core/src/network/connect.rs index 0e675258e..c9fcea725 100644 --- a/crates/sandlock-core/src/network/connect.rs +++ b/crates/sandlock-core/src/network/connect.rs @@ -87,7 +87,7 @@ pub(super) async fn connect_on_behalf( let proxy = ns .http_acl_addr .filter(|_| dest_port.map_or(false, |p| ns.http_acl_ports.contains(&p))); - let remap_port = if ctx.policy.port_remap && ip.is_loopback() { + let remap_port = if ctx.policy.features.port_remap && ip.is_loopback() { dest_port.and_then(|p| ns.port_map.get_real(p)) } else { None @@ -140,7 +140,7 @@ pub(super) async fn connect_on_behalf( DestShape::UnixNamed(path) if ctx.policy.supervises_named_unix() => { connect_named_unix_on_behalf(notif, ctx, sockfd, &path) } - _ if !ctx.policy.has_net_destination_policy => NotifAction::Continue, + _ if !ctx.policy.features.network_destination_policy => NotifAction::Continue, // From here a Continue is a way around the destination policy: the // kernel looks the fd and the address up again, and a sibling // thread can have put an IP socket and a forbidden IP there. diff --git a/crates/sandlock-core/src/network/send.rs b/crates/sandlock-core/src/network/send.rs index 9d7fe5c0e..8584d37bf 100644 --- a/crates/sandlock-core/src/network/send.rs +++ b/crates/sandlock-core/src/network/send.rs @@ -125,7 +125,7 @@ pub(super) async fn sendto_on_behalf( // non-unix sockets and for AF_UNIX destinations we cannot pin in // the child's context (abstract / empty `sun_path`) // under a destination policy — see the PR description. - if !ctx.policy.has_net_destination_policy { + if !ctx.policy.features.network_destination_policy { return NotifAction::Continue; } let dup_fd = match crate::seccomp::notif::dup_fd_from_pid(notif.pid, sockfd) { @@ -233,7 +233,7 @@ pub(super) async fn sendmsg_on_behalf( // connected (NULL) name for a denied address. Send on-behalf (including // connected sends) so the verdict is made on the immune copy. Without a // policy there is nothing to bypass, so the Continue fast path below stands. - let dest_policy = ctx.policy.has_net_destination_policy; + let dest_policy = ctx.policy.features.network_destination_policy; if !dest_policy { // Pre-scan for Continue cases (connected socket / non-IP family). // EFAULT on unreadable msghdr (vs. Continue, which would let the kernel @@ -468,7 +468,7 @@ pub(super) async fn sendmmsg_on_behalf( // entry for a denied address after our prescan, bypassing the allowlist on // an unconnected datagram socket. On-behalf sends use the immune copy and // validate every IP destination, so the verdict is TOCTOU-free. - if ctx.policy.has_net_destination_policy { + if ctx.policy.features.network_destination_policy { let dup_fd = match crate::seccomp::notif::dup_fd_from_pid(notif.pid, sockfd) { Ok(fd) => fd, Err(e) => return NotifAction::Errno(e.raw_os_error().unwrap_or(libc::EBADF)), diff --git a/crates/sandlock-core/src/policy_fn.rs b/crates/sandlock-core/src/policy_fn.rs index 6e7826667..ed9fb9109 100644 --- a/crates/sandlock-core/src/policy_fn.rs +++ b/crates/sandlock-core/src/policy_fn.rs @@ -55,7 +55,7 @@ pub enum SyscallCategory { } /// The event categories a policy callback subscribes to. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub(crate) struct CategorySet(u8); impl CategorySet { diff --git a/crates/sandlock-core/src/procfs.rs b/crates/sandlock-core/src/procfs.rs index 7b053a73b..f597d6a59 100644 --- a/crates/sandlock-core/src/procfs.rs +++ b/crates/sandlock-core/src/procfs.rs @@ -162,7 +162,9 @@ pub(crate) fn virtual_file(path: &str, policy: &NotifPolicy) -> Option VirtualFile::CpuInfo, - "/proc/stat" if policy.num_cpus.is_some() || policy.has_time_start => VirtualFile::Stat, + "/proc/stat" if policy.num_cpus.is_some() || policy.features.time_start => { + VirtualFile::Stat + } // glibc's sysconf(_SC_NPROCESSORS_ONLN/CONF) counts these, not the // affinity mask, so `make -j$(getconf _NPROCESSORS_ONLN)` sees them. "/sys/devices/system/cpu/online" diff --git a/crates/sandlock-core/src/procfs/net.rs b/crates/sandlock-core/src/procfs/net.rs index 8966ccde6..85b4c6c34 100644 --- a/crates/sandlock-core/src/procfs/net.rs +++ b/crates/sandlock-core/src/procfs/net.rs @@ -346,13 +346,13 @@ pub(crate) fn render( libc::IPPROTO_UDP }; let records = sock_diag::dump(family, protocol, &cookies)?; - render_inet(&records, port_map, policy.port_remap, protocol) + render_inet(&records, port_map, policy.features.port_remap, protocol) } NetFile::Unix => { let records = sock_diag::dump(libc::AF_UNIX, 0, &cookies)?; render_unix(&records, |path| { if path.starts_with('@') { return Some(path.into()); } - if policy.cow_enabled || !path.starts_with('/') { return None; } + if policy.features.cow || !path.starts_with('/') { return None; } visible_unix_path(path, policy.chroot_root.as_deref(), &policy.chroot_mounts) }) } diff --git a/crates/sandlock-core/src/resource.rs b/crates/sandlock-core/src/resource.rs index 6891f164f..0f6a4ab35 100644 --- a/crates/sandlock-core/src/resource.rs +++ b/crates/sandlock-core/src/resource.rs @@ -239,7 +239,7 @@ pub(crate) fn requires_process_creation_tracking( notif: &SeccompNotif, policy: &NotifPolicy, ) -> bool { - policy.argv_safety_required && fork_counted_on_continue(notif) + policy.features.argv_safety_required && fork_counted_on_continue(notif) } /// Arm ptrace fork-event tracking on the syscall's calling task. @@ -956,6 +956,7 @@ mod memory_range_tests { #[cfg(test)] mod tests { use super::*; + use crate::features::SandboxFeatures; use crate::netlink::NetlinkState; use crate::seccomp::state::{ ChrootState, CowState, NetworkState, PolicyFnState, ProcessIndex, ProcfsState, @@ -990,19 +991,13 @@ mod tests { NotifPolicy { max_memory_bytes: 0, max_processes: 0, - has_memory_limit: false, - has_net_destination_policy: false, - has_bind_denylist: false, - has_unix_fs_gate: false, - landlock_unix_gate: false, - has_random_seed: false, - has_time_start: false, - argv_safety_required, + features: SandboxFeatures { + argv_safety_required, + ..Default::default() + }, notif_wait_killable: true, time_offset: 0, num_cpus: None, - port_remap: false, - cow_enabled: false, chroot_root: None, chroot_readable: Vec::new(), chroot_writable: Vec::new(), @@ -1012,7 +1007,6 @@ mod tests { deterministic_dirs: false, virtual_hostname: None, uname: Default::default(), - has_http_acl: false, virtual_etc_hosts: String::new(), ca_inject_paths: Vec::new(), ca_inject_pem: None, @@ -1058,7 +1052,7 @@ mod tests { let ctx = fake_supervisor_ctx(false); let mut policy = fake_policy(false); policy.max_memory_bytes = 1 << 20; - policy.has_memory_limit = true; + policy.features.memory_limit = true; let rw = (libc::PROT_READ | libc::PROT_WRITE) as u64; let shared = file_mmap_notif(1 << 30, rw, libc::MAP_SHARED as u64); @@ -1095,7 +1089,7 @@ mod tests { let ctx = fake_supervisor_ctx(false); let mut policy = fake_policy(false); policy.max_memory_bytes = 1 << 20; - policy.has_memory_limit = true; + policy.features.memory_limit = true; let reserve = mmap_notif(1 << 30, libc::PROT_NONE as u64); let action = handle_memory(&reserve, &ctx, &policy).await; @@ -1150,7 +1144,7 @@ mod tests { let ctx = fake_supervisor_ctx(false); let mut policy = fake_policy(false); policy.max_memory_bytes = 1 << 20; - policy.has_memory_limit = true; + policy.features.memory_limit = true; let reserved = map_anon(1 << 30, libc::PROT_NONE); let over = handle_memory(&mprotect_notif(reserved, 1 << 30), &ctx, &policy).await; @@ -1180,7 +1174,7 @@ mod tests { let ctx = fake_supervisor_ctx(false); let mut policy = fake_policy(false); policy.max_memory_bytes = 64 << 20; - policy.has_memory_limit = true; + policy.features.memory_limit = true; ctx.resource.lock().await.mem_used = 60 << 20; let writable = map_anon(16 << 20, libc::PROT_READ | libc::PROT_WRITE); diff --git a/crates/sandlock-core/src/sandbox.rs b/crates/sandlock-core/src/sandbox.rs index db278e577..81632e3b8 100644 --- a/crates/sandlock-core/src/sandbox.rs +++ b/crates/sandlock-core/src/sandbox.rs @@ -2244,7 +2244,7 @@ impl Sandbox { /// Whether named (pathname) `AF_UNIX` connects should be gated by the /// fs-write grants (`has_unix_fs_gate`). Active whenever the sandbox /// confines the filesystem. Single source of truth for both the - /// `NotifPolicy` flag and the `notif_syscalls` BPF set. + /// `SandboxFeatures` flag and the BPF notif set. pub(crate) fn has_unix_fs_gate(&self) -> bool { !self.fs_readable.is_empty() || !self.fs_writable.is_empty() } @@ -2550,7 +2550,7 @@ impl Sandbox { let handler_syscalls: Vec = self.rt().handlers.iter().map(|(nr, _)| *nr).collect(); let resolved_sandbox_name = self.rt().name.clone(); - let resolved = crate::resolved::ResolvedSandbox::from_sandbox( + let features = crate::features::SandboxFeatures::from_sandbox( self, Some(resolved_sandbox_name.as_str()), &handler_syscalls, @@ -2717,8 +2717,8 @@ impl Sandbox { env: &child_env, pipes: &pipes, no_supervisor, + features, keep_fds: &gather_keep_fds, - sandbox_name: Some(sandbox_name.as_str()), extra_syscalls: &extra_syscalls, foreground, }); @@ -2799,19 +2799,10 @@ impl Sandbox { let notif_policy = NotifPolicy { max_memory_bytes: self.max_memory.map(|m| m.0).unwrap_or(0), max_processes: self.max_processes.unwrap_or(u32::MAX), - has_memory_limit: resolved.features.memory_limit, - has_net_destination_policy: resolved.features.network_destination_policy, - has_bind_denylist: resolved.features.bind_denylist, - has_unix_fs_gate: resolved.features.unix_fs_gate, - landlock_unix_gate: resolved.features.landlock_unix_gate, - has_random_seed: resolved.features.random_seed, - has_time_start: resolved.features.time_start, - argv_safety_required: resolved.features.argv_safety_required, + features, notif_wait_killable, time_offset: time_offset.unwrap_or(0), num_cpus: self.num_cpus, - port_remap: resolved.features.port_remap, - cow_enabled: resolved.features.cow, chroot_root: chroot_root.clone(), chroot_readable: self.fs_readable.clone(), chroot_writable: self.fs_writable.clone(), @@ -2821,7 +2812,6 @@ impl Sandbox { deterministic_dirs: self.deterministic_dirs, virtual_hostname: Some(rt_name), uname: self.uname.clone(), - has_http_acl: resolved.features.http_acl, virtual_etc_hosts, ca_inject_paths: self.http_inject_ca.clone(), ca_inject_pem: ca_inject_pem.clone(), diff --git a/crates/sandlock-core/src/seccomp/dispatch.rs b/crates/sandlock-core/src/seccomp/dispatch.rs index 39905e46f..1d026dd05 100644 --- a/crates/sandlock-core/src/seccomp/dispatch.rs +++ b/crates/sandlock-core/src/seccomp/dispatch.rs @@ -337,9 +337,9 @@ pub(crate) fn build_dispatch_table( } // ------------------------------------------------------------------ - // Memory management (conditional on has_memory_limit) + // Memory management (conditional on memory_limit) // ------------------------------------------------------------------ - if policy.has_memory_limit { + if policy.features.memory_limit { for &nr in &[ libc::SYS_mmap, libc::SYS_munmap, @@ -373,11 +373,11 @@ pub(crate) fn build_dispatch_table( } // ------------------------------------------------------------------ - // Network (conditional on has_net_destination_policy or the supervisor - // gating named unix sockets). has_http_acl is already subsumed by - // has_net_destination_policy, so it isn't listed. + // Network (conditional on network_destination_policy or the supervisor + // gating named unix sockets). http_acl is already subsumed by + // network_destination_policy, so it isn't listed. // ------------------------------------------------------------------ - if policy.has_net_destination_policy || policy.supervises_named_unix() { + if policy.features.network_destination_policy || policy.supervises_named_unix() { for &nr in &[ libc::SYS_connect, libc::SYS_sendto, @@ -397,7 +397,7 @@ pub(crate) fn build_dispatch_table( // ------------------------------------------------------------------ // Deterministic random — getrandom() // ------------------------------------------------------------------ - if policy.has_random_seed { + if policy.features.random_seed { let __sup = Arc::clone(ctx); table.register(libc::SYS_getrandom, move |cx: &HandlerCtx| { let notif = cx.notif; @@ -420,7 +420,7 @@ pub(crate) fn build_dispatch_table( // legacy `open` spellings can't slip past the seed and read the // kernel's real entropy. // ------------------------------------------------------------------ - if policy.has_random_seed { + if policy.features.random_seed { for nr in open_family_syscalls() { let __sup = Arc::clone(ctx); table.register(nr, move |cx: &HandlerCtx| { @@ -442,9 +442,9 @@ pub(crate) fn build_dispatch_table( } // ------------------------------------------------------------------ - // Timer adjustment (conditional on has_time_start) + // Timer adjustment (conditional on time_start) // ------------------------------------------------------------------ - if policy.has_time_start { + if policy.features.time_start { let time_offset = policy.time_offset; for &nr in &[ libc::SYS_clock_nanosleep as i64, @@ -591,7 +591,7 @@ pub(crate) fn build_dispatch_table( // COW filesystem interception // ------------------------------------------------------------------ #[cfg(feature = "cow")] - if policy.cow_enabled { + if policy.features.cow { register_cow_handlers(&mut table, ctx); } @@ -760,7 +760,10 @@ pub(crate) fn build_dispatch_table( // ------------------------------------------------------------------ // Bind — on-behalf // ------------------------------------------------------------------ - if policy.port_remap || policy.has_net_destination_policy || policy.has_bind_denylist { + if policy.features.port_remap + || policy.features.network_destination_policy + || policy.features.bind_denylist + { let __sup = Arc::clone(ctx); table.register(libc::SYS_bind, move |cx: &HandlerCtx| { let notif = cx.notif; @@ -773,7 +776,7 @@ pub(crate) fn build_dispatch_table( // ------------------------------------------------------------------ // getsockname — port remap // ------------------------------------------------------------------ - if policy.port_remap { + if policy.features.port_remap { let __sup = Arc::clone(ctx); table.register(libc::SYS_getsockname, move |cx: &HandlerCtx| { let notif = cx.notif; @@ -1301,19 +1304,10 @@ mod handler_tests { policy: Arc::new(NotifPolicy { max_memory_bytes: 0, max_processes: 0, - has_memory_limit: false, - has_net_destination_policy: false, - has_bind_denylist: false, - has_unix_fs_gate: false, - landlock_unix_gate: false, - has_random_seed: false, - has_time_start: false, + features: Default::default(), time_offset: 0, num_cpus: None, - argv_safety_required: false, notif_wait_killable: true, - port_remap: false, - cow_enabled: false, chroot_root: None, chroot_readable: Vec::new(), chroot_writable: Vec::new(), @@ -1323,7 +1317,6 @@ mod handler_tests { deterministic_dirs: false, virtual_hostname: None, uname: Default::default(), - has_http_acl: false, virtual_etc_hosts: String::new(), ca_inject_paths: Vec::new(), ca_inject_pem: None, diff --git a/crates/sandlock-core/src/seccomp/notif.rs b/crates/sandlock-core/src/seccomp/notif.rs index fafd511d9..ddb9a759e 100644 --- a/crates/sandlock-core/src/seccomp/notif.rs +++ b/crates/sandlock-core/src/seccomp/notif.rs @@ -1354,45 +1354,12 @@ pub(crate) fn dup_fd_from_pid(pid: u32, target_fd: i32) -> io::Result { pub struct NotifPolicy { pub max_memory_bytes: u64, pub max_processes: u32, - pub has_memory_limit: bool, - /// A **network destination policy** is active: a `net_allow` allowlist, a - /// `net_deny` denylist, an HTTP ACL, or a live `policy_fn` (i.e. - /// `network_destination_policy`). Despite the historical singular framing - /// this is *not* only an allowlist. When set, the on-behalf path is the - /// IP-level enforcer for connect/sendto/sendmsg and those handlers must - /// never `Continue`; when clear, the syscalls are trapped only to gate - /// named `AF_UNIX` sockets and IP destinations are returned to the kernel - /// so Landlock/BPF govern them. - pub has_net_destination_policy: bool, - /// `--net-deny-bind` is active: trap `bind()` and register the on-behalf - /// handler so denied TCP ports can be refused (independent of the - /// connect-side `has_net_destination_policy`). - pub has_bind_denylist: bool, - /// Named (pathname) `AF_UNIX` connect gate. When true, `connect()` to a - /// named unix socket whose path is not covered by an fs-write grant is - /// denied with EACCES. Abstract sockets are handled by - /// `LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET` instead. - pub has_unix_fs_gate: bool, - /// The host's Landlock enforces [`Self::has_unix_fs_gate`] itself - /// (`LANDLOCK_ACCESS_FS_RESOLVE_UNIX`), so the caller can connect in its - /// own name. - pub landlock_unix_gate: bool, - pub has_random_seed: bool, - pub has_time_start: bool, - /// Argv-safety gate: the supervisor must freeze every task that - /// could mutate argv before any consumer reads it. True when - /// `policy_fn` is active or when a handler is bound to - /// execve/execveat (such handlers can call `read_child_mem`). - /// Also gates ptrace fork-event tracking so `ProcessIndex` is - /// complete when the freeze enumerates it. - pub argv_safety_required: bool, + pub(crate) features: crate::features::SandboxFeatures, /// The child's listener holds a received notification's caller until it /// is answered (`WAIT_KILLABLE_RECV`); the exec freeze relies on that. pub notif_wait_killable: bool, pub time_offset: i64, pub num_cpus: Option, - pub port_remap: bool, - pub cow_enabled: bool, pub chroot_root: Option, /// Virtual paths allowed for reading under chroot (original user-specified paths). pub chroot_readable: Vec, @@ -1410,7 +1377,6 @@ pub struct NotifPolicy { pub deterministic_dirs: bool, pub virtual_hostname: Option, pub uname: crate::sandbox::Uname, - pub has_http_acl: bool, /// Synthetic `/etc/hosts` served to the sandbox. Always populated: /// `openat("/etc/hosts")` returns a memfd with this content so the /// host's on-disk `/etc/hosts` never leaks in. The content is the @@ -1428,10 +1394,11 @@ impl NotifPolicy { /// wherever Landlock cannot gate it, or a `Continue` could be raced past a /// destination policy. The peer's `SO_PEERCRED` then names the supervisor. pub(crate) fn supervises_named_unix(&self) -> bool { - self.has_unix_fs_gate - && (!self.landlock_unix_gate + let features = &self.features; + features.unix_fs_gate + && (!features.landlock_unix_gate || self.chroot_root.is_some() - || self.has_net_destination_policy) + || features.network_destination_policy) } /// Whether an open may land on something the supervisor answers for @@ -1459,7 +1426,7 @@ impl NotifPolicy { /// supervisor, given the destination's loopback-ness. /// /// This is the connect-side form of the invariant the `sendto`/`sendmsg` - /// handlers already follow: with [`Self::has_net_destination_policy`] the + /// handlers already follow: with a destination policy the /// on-behalf path is the IP-level enforcer and must never `Continue`; /// without it there is nothing to enforce and the syscall is returned to /// the kernel. `connect()` adds one wrinkle over datagram sends — @@ -1471,7 +1438,7 @@ impl NotifPolicy { /// empty `net_allow`); handling it on-behalf would run it in the /// unconfined supervisor and bypass that decision. pub(crate) fn ip_connect_supervised(&self, dest_is_loopback: bool) -> bool { - self.has_net_destination_policy || (self.port_remap && dest_is_loopback) + self.features.network_destination_policy || (self.features.port_remap && dest_is_loopback) } } @@ -2204,12 +2171,12 @@ fn maybe_patch_vdso(pid: i32, procfs: &mut super::state::ProcfsState, policy: &N if base == procfs.vdso_patched_addr { return; // already patched this vDSO } - let time_offset = if policy.has_time_start { + let time_offset = if policy.features.time_start { Some(policy.time_offset) } else { None }; - if crate::vdso::patch(pid, time_offset, policy.has_random_seed).is_ok() { + if crate::vdso::patch(pid, time_offset, policy.features.random_seed).is_ok() { procfs.vdso_patched_addr = base; } } @@ -3022,7 +2989,7 @@ async fn handle_notification( crate::resource::register_child_if_new(ctx, notif.pid as i32).await; // Re-patch vDSO if needed (exec replaces it with a fresh copy). - if policy.has_time_start || policy.has_random_seed { + if policy.features.time_start || policy.features.random_seed { let mut pfs = ctx.procfs.lock().await; maybe_patch_vdso(notif.pid as i32, &mut pfs, policy); } @@ -3129,7 +3096,7 @@ async fn decide( // Read without freezing so the sandbox keeps running while policy_fn // decides; `freeze_exec` re-reads it under the freeze before Continue. let exec_image = (matches!(action, NotifAction::Continue) - && policy.argv_safety_required + && policy.features.argv_safety_required && crate::freeze::requires_freeze_on_continue(nr)) .then(|| read_exec_image(¬if, fd)); diff --git a/crates/sandlock-core/src/seccomp_plan.rs b/crates/sandlock-core/src/seccomp_plan.rs index 9de4a584f..d94c24299 100644 --- a/crates/sandlock-core/src/seccomp_plan.rs +++ b/crates/sandlock-core/src/seccomp_plan.rs @@ -7,8 +7,8 @@ use syscalls::{Sysno, SysnoSet}; use crate::arch; +use crate::features::SandboxFeatures; use crate::policy_fn::SyscallCategory; -use crate::resolved::ResolvedSandbox; use crate::sandbox::Sandbox; use crate::seccomp::bpf::{jump, stmt}; use crate::sys::structs::{ @@ -364,14 +364,12 @@ const PORT_REMAP_SYSCALLS: &[i64] = &[libc::SYS_bind, libc::SYS_getsockname]; /// Determine which syscalls need `SECCOMP_RET_USER_NOTIF`. pub(crate) fn notif_syscalls(policy: &Sandbox, sandbox_name: Option<&str>) -> Vec { - let resolved = ResolvedSandbox::from_sandbox(policy, sandbox_name, &[]); - notif_syscalls_resolved(&resolved) + notif_syscalls_resolved(&SandboxFeatures::from_sandbox(policy, sandbox_name, &[])) } /// Determine which syscalls need `SECCOMP_RET_USER_NOTIF` from the resolved /// internal feature view. -pub(crate) fn notif_syscalls_resolved(resolved: &ResolvedSandbox) -> Vec { - let features = &resolved.features; +pub(crate) fn notif_syscalls_resolved(features: &SandboxFeatures) -> Vec { let mut nrs = SyscallList::with(BASE_NOTIF_SYSCALLS); nrs.push_optional(arch::sys_vfork()); @@ -523,12 +521,10 @@ pub(crate) fn blocklist_syscall_numbers(policy: &Sandbox) -> Vec { /// - prctl: block PR_SET_DUMPABLE, PR_SET_SECUREBITS, PR_SET_PTRACER /// - socket: block SOCK_RAW/SOCK_DGRAM on AF_INET/AF_INET6 (with type mask) pub(crate) fn arg_filters(policy: &Sandbox) -> Vec { - let resolved = ResolvedSandbox::from_sandbox(policy, None, &[]); - arg_filters_resolved(&resolved) + arg_filters_resolved(&SandboxFeatures::from_sandbox(policy, None, &[])) } -pub(crate) fn arg_filters_resolved(resolved: &ResolvedSandbox) -> Vec { - let features = &resolved.features; +pub(crate) fn arg_filters_resolved(features: &SandboxFeatures) -> Vec { let ret_errno = SECCOMP_RET_ERRNO | EPERM as u32; let nr_clone = libc::SYS_clone as u32; let nr_ioctl = libc::SYS_ioctl as u32; From 3f6f308e1794d6c0fc44f7af9e78e35078feab8e Mon Sep 17 00:00:00 2001 From: Cong Wang Date: Sat, 28 Nov 2026 11:46:35 -0800 Subject: [PATCH 2/2] seccomp: replace seccomp_plan with a FilterSpec type seccomp_plan was a bag of free functions returning a notif list, a blocklist and an argument block, which every caller stitched together by hand, and context.rs re-exported them as public wrappers. The feature view also called back into it to learn whether sysinfo was denied. FilterSpec in seccomp/filter.rs owns the three parts and is the only way to assemble them. Its constructors name the three filters sandlock installs: supervised, deny_only and no_supervisor. The sysinfo check moves next to the deny list it depends on, so SandboxFeatures no longer needs the blocklist. Signed-off-by: Cong Wang --- crates/sandlock-core/src/context.rs | 59 +-- crates/sandlock-core/src/context/tests.rs | 400 ---------------- crates/sandlock-core/src/features.rs | 4 - crates/sandlock-core/src/lib.rs | 1 - crates/sandlock-core/src/sandbox.rs | 6 +- crates/sandlock-core/src/seccomp/bpf.rs | 2 +- crates/sandlock-core/src/seccomp/dispatch.rs | 10 +- .../{seccomp_plan.rs => seccomp/filter.rs} | 102 ++-- .../sandlock-core/src/seccomp/filter/tests.rs | 453 ++++++++++++++++++ crates/sandlock-core/src/seccomp/mod.rs | 1 + crates/sandlock-core/src/seccomp/notif.rs | 2 +- .../tests/integration/test_handlers.rs | 4 +- .../tests/integration/test_netlink_virt.rs | 9 - .../tests/integration/test_policy_fn.rs | 14 - 14 files changed, 538 insertions(+), 529 deletions(-) rename crates/sandlock-core/src/{seccomp_plan.rs => seccomp/filter.rs} (90%) create mode 100644 crates/sandlock-core/src/seccomp/filter/tests.rs diff --git a/crates/sandlock-core/src/context.rs b/crates/sandlock-core/src/context.rs index c1b7d6ff6..96d35a9f4 100644 --- a/crates/sandlock-core/src/context.rs +++ b/crates/sandlock-core/src/context.rs @@ -9,14 +9,7 @@ use crate::child_env::ChildEnv; use crate::features::SandboxFeatures; use crate::sandbox::Sandbox; use crate::seccomp::bpf; - -#[cfg(test)] -use crate::arch; -#[cfg(test)] -use crate::sys::structs::{ - AF_INET, AF_INET6, CLONE_NS_FLAGS, DEFAULT_BLOCKLIST_SYSCALLS, PR_SET_DUMPABLE, SIOCETHTOOL, - SIOCGIFCONF, SOCK_RAW, SOCK_TYPE_MASK, TIOCLINUX, TIOCSTI, -}; +use crate::seccomp::filter::FilterSpec; // ============================================================ // Pipe pair for parent-child synchronization @@ -125,31 +118,6 @@ pub(crate) fn read_u32_fd(fd: RawFd) -> io::Result { Ok(u32::from_le_bytes(buf)) } -#[cfg(test)] -use crate::seccomp::syscall::syscall_name_to_nr; - -// ============================================================ -// Sandbox -> seccomp plan -// ============================================================ - -pub(crate) use crate::seccomp_plan::{arg_filters_resolved, notif_syscalls_resolved}; - -pub fn notif_syscalls(policy: &Sandbox, sandbox_name: Option<&str>) -> Vec { - crate::seccomp_plan::notif_syscalls(policy, sandbox_name) -} - -pub fn no_supervisor_blocklist_syscall_numbers(policy: &Sandbox) -> Vec { - crate::seccomp_plan::no_supervisor_blocklist_syscall_numbers(policy) -} - -pub fn blocklist_syscall_numbers(policy: &Sandbox) -> Vec { - crate::seccomp_plan::blocklist_syscall_numbers(policy) -} - -pub fn arg_filters(policy: &Sandbox) -> Vec { - crate::seccomp_plan::arg_filters(policy) -} - // ============================================================ // Close fds above threshold // ============================================================ @@ -461,20 +429,13 @@ pub(crate) fn confine_child(args: ChildSpawnArgs<'_>) -> ! { } // 9. Assemble and install seccomp filter (IRREVERSIBLE) - let args = arg_filters_resolved(&features); let mut keep_fd: i32 = -1; 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. - // - // Uses the relaxed `no_supervisor_blocklist_syscall_numbers` deny - // list (which leaves `ptrace`, `process_vm_*`, etc. alone) so an - // inner full-supervisor sandlock nested under this one still has - // the syscalls its supervisor needs. - let deny = no_supervisor_blocklist_syscall_numbers(sandbox); - let filter = match bpf::assemble_filter(&[], &deny, &args) { + let filter = match FilterSpec::no_supervisor(sandbox, &features).assemble() { Ok(f) => f, Err(e) => fail!(format!("seccomp assemble: {}", e)), }; @@ -489,21 +450,9 @@ pub(crate) fn confine_child(args: ChildSpawnArgs<'_>) -> ! { fail!(format!("write notif wait: {}", e)); } } else { - let deny = blocklist_syscall_numbers(sandbox); // First-level sandbox: notif + deny filter with NEW_LISTENER. - // - // Caller-supplied handlers must have their syscalls registered in - // the BPF filter, otherwise the kernel never raises a notification for - // them and the handler silently never fires. We merge `extra_syscalls` - // into the notif list and dedup so each syscall produces exactly one - // JEQ in the assembled program. - let mut notif = notif_syscalls_resolved(&features); - if !extra_syscalls.is_empty() { - notif.extend_from_slice(extra_syscalls); - } - notif.sort_unstable(); - notif.dedup(); - let filter = match bpf::assemble_filter(¬if, &deny, &args) { + let spec = FilterSpec::supervised(sandbox, &features, extra_syscalls); + let filter = match spec.assemble() { Ok(f) => f, Err(e) => fail!(format!("seccomp assemble: {}", e)), }; diff --git a/crates/sandlock-core/src/context/tests.rs b/crates/sandlock-core/src/context/tests.rs index a92c14743..1f9d46db9 100644 --- a/crates/sandlock-core/src/context/tests.rs +++ b/crates/sandlock-core/src/context/tests.rs @@ -40,406 +40,6 @@ fn test_write_read_u32_large() { assert_eq!(got, val); } -#[test] -fn test_notif_syscalls_always_has_clone() { - let policy = Sandbox::builder().build().unwrap(); - let nrs = notif_syscalls(&policy, None); - assert!(nrs.contains(&(libc::SYS_clone as u32))); - if let Some(vfork) = arch::sys_vfork() { - assert!(nrs.contains(&(vfork as u32))); - } - if let Some(fork) = arch::sys_fork() { - assert!(nrs.contains(&(fork as u32))); - } -} - -#[test] -fn test_notif_syscalls_memory() { - // shmget only appears in notif when SysV IPC is allowed: - // otherwise it is on the kernel blocklist and notifying would - // bypass the deny (notif JEQs precede deny JEQs in the BPF - // layout). - let policy = Sandbox::builder() - .max_memory(crate::sandbox::ByteSize::mib(256)) - .extra_allow_syscalls(vec!["sysv_ipc".into()]) - .build() - .unwrap(); - let nrs = notif_syscalls(&policy, None); - assert!(nrs.contains(&(libc::SYS_mmap as u32))); - assert!(nrs.contains(&(libc::SYS_munmap as u32))); - assert!(nrs.contains(&(libc::SYS_brk as u32))); - assert!(nrs.contains(&(libc::SYS_mremap as u32))); - assert!(nrs.contains(&(libc::SYS_shmget as u32))); -} - -#[test] -fn test_notif_syscalls_memory_excludes_shmget_when_sysv_ipc_denied() { - // With max_memory but allows_sysv_ipc()=false (the default), - // shmget must NOT be in notif: if it were, the BPF filter - // would route it to RET_USER_NOTIF before reaching the deny - // JEQ, silently bypassing the kernel-level deny. - let policy = Sandbox::builder() - .max_memory(crate::sandbox::ByteSize::mib(256)) - .build() - .unwrap(); - let nrs = notif_syscalls(&policy, None); - assert!(!nrs.contains(&(libc::SYS_shmget as u32))); - // Other memory syscalls remain notified; they are not denied. - assert!(nrs.contains(&(libc::SYS_mmap as u32))); - assert!(nrs.contains(&(libc::SYS_brk as u32))); -} - -#[test] -fn test_notif_syscalls_net() { - let policy = Sandbox::builder() - .net_allow("example.com:443") - .build() - .unwrap(); - let nrs = notif_syscalls(&policy, None); - assert!(nrs.contains(&(libc::SYS_connect as u32))); - assert!(nrs.contains(&(libc::SYS_sendto as u32))); - assert!(nrs.contains(&(libc::SYS_sendmsg as u32))); - assert!(nrs.contains(&(libc::SYS_sendmmsg as u32))); -} - -#[test] -fn test_notif_syscalls_net_deny() { - // --net-deny is default-allow but still needs every connect/sendto - // routed to the on-behalf path so the DenyList can refuse matches. - let policy = Sandbox::builder().net_deny("10.0.0.0/8").build().unwrap(); - let nrs = notif_syscalls(&policy, None); - assert!(nrs.contains(&(libc::SYS_connect as u32))); - assert!(nrs.contains(&(libc::SYS_sendto as u32))); -} - -#[test] -fn test_notif_syscalls_sandbox_name_enables_hostname_virtualization() { - let policy = Sandbox::builder().build().unwrap(); - let nrs = notif_syscalls(&policy, Some("api.local")); - assert!(nrs.contains(&(libc::SYS_uname as u32))); - assert!(nrs.contains(&(libc::SYS_openat as u32))); -} - -#[test] -fn test_notif_syscalls_virtualize_sysinfo() { - let policy = Sandbox::builder().build().unwrap(); - assert!(notif_syscalls(&policy, None).contains(&(libc::SYS_sysinfo as u32))); -} - -#[test] -fn test_notif_syscalls_skip_denied_sysinfo() { - let policy = Sandbox::builder() - .extra_deny_syscalls(vec!["sysinfo".into()]) - .build() - .unwrap(); - assert!(!notif_syscalls(&policy, None).contains(&(libc::SYS_sysinfo as u32))); -} - -/// SYS_faccessat2 (439) must be in the notification filter for both -/// chroot and COW modes; glibc 2.33+ uses it instead of faccessat. -#[test] -fn test_notif_syscalls_faccessat2() { - // Chroot mode - let policy = Sandbox::builder().chroot("/tmp").build().unwrap(); - let nrs = notif_syscalls(&policy, None); - assert!(nrs.contains(&(libc::SYS_faccessat as u32))); - assert!( - nrs.contains(&(arch::SYS_FACCESSAT2 as u32)), - "chroot notif filter must include SYS_faccessat2 (439)" - ); -} - -#[cfg(feature = "cow")] -#[test] -fn test_notif_syscalls_faccessat2_cow() { - let policy = Sandbox::builder().workdir("/tmp").build().unwrap(); - let nrs = notif_syscalls(&policy, None); - assert!(nrs.contains(&(libc::SYS_faccessat as u32))); - assert!( - nrs.contains(&(arch::SYS_FACCESSAT2 as u32)), - "COW notif filter must include SYS_faccessat2 (439)" - ); -} - -#[test] -fn test_blocklist_syscall_numbers_default() { - let policy = Sandbox::builder().build().unwrap(); - let nrs = blocklist_syscall_numbers(&policy); - // Should contain mount, ptrace, etc. - assert!(nrs.contains(&(libc::SYS_mount as u32))); - assert!(nrs.contains(&(libc::SYS_ptrace as u32))); - assert!(nrs.contains(&(libc::SYS_bpf as u32))); - // SysV IPC denied by default (no IPC namespace in sandlock) - assert!(nrs.contains(&(libc::SYS_shmget as u32))); - assert!(nrs.contains(&(libc::SYS_shmat as u32))); - assert!(nrs.contains(&(libc::SYS_msgget as u32))); - assert!(nrs.contains(&(libc::SYS_semget as u32))); - // nfsservctl has no libc constant, so it is skipped - assert!(!nrs.is_empty()); -} - -#[test] -fn test_blocklist_syscall_numbers_custom() { - let policy = Sandbox::builder() - .extra_deny_syscalls(vec!["mount".into(), "ptrace".into()]) - .build() - .unwrap(); - let nrs = blocklist_syscall_numbers(&policy); - // User-supplied blocklist still gets SysV IPC appended - // (allows_sysv_ipc() defaults to false). - assert!(nrs.contains(&(libc::SYS_mount as u32))); - assert!(nrs.contains(&(libc::SYS_ptrace as u32))); - assert!(nrs.contains(&(libc::SYS_shmget as u32))); -} - -#[test] -fn test_blocklist_syscall_numbers_custom_with_sysv_ipc_allowed() { - let policy = Sandbox::builder() - .extra_deny_syscalls(vec!["mount".into(), "ptrace".into()]) - .extra_allow_syscalls(vec!["sysv_ipc".into()]) - .build() - .unwrap(); - let nrs = blocklist_syscall_numbers(&policy); - // Default blocklist plus user extras: no SysV IPC append. - assert!(nrs.contains(&(libc::SYS_mount as u32))); - assert!(nrs.contains(&(libc::SYS_ptrace as u32))); - assert!(nrs.contains(&(libc::SYS_bpf as u32))); - assert!(!nrs.contains(&(libc::SYS_shmget as u32))); -} - -#[test] -fn test_blocklist_syscall_numbers_default_with_sysv_ipc_allowed() { - let policy = Sandbox::builder() - .extra_allow_syscalls(vec!["sysv_ipc".into()]) - .build() - .unwrap(); - let nrs = blocklist_syscall_numbers(&policy); - // Default blocklist still present, but SysV IPC is permitted. - assert!(nrs.contains(&(libc::SYS_mount as u32))); - assert!(!nrs.contains(&(libc::SYS_shmget as u32))); - assert!(!nrs.contains(&(libc::SYS_msgget as u32))); - assert!(!nrs.contains(&(libc::SYS_semget as u32))); -} - -// The expansion tests below inject the group deny after build(): with -// allow "sysv_ipc" set, the !allows_sysv_ipc() fallback in -// resolve_blocklist is skipped, so the members can appear only through -// group expansion of the deny entry. Going through build() instead -// would either trip the allow/deny conflict check or (deny-only) let -// the fallback add the members and mask a broken expansion. -#[test] -fn test_blocklist_syscall_numbers_expands_deny_group() { - let mut policy = Sandbox::builder() - .extra_allow_syscalls(vec!["sysv_ipc".into()]) - .build() - .unwrap(); - policy.extra_deny_syscalls = vec!["sysv_ipc".into()]; - let nrs = blocklist_syscall_numbers(&policy); - assert!(nrs.contains(&(libc::SYS_shmget as u32))); - assert!(nrs.contains(&(libc::SYS_msgget as u32))); - assert!(nrs.contains(&(libc::SYS_semget as u32))); - assert!(nrs.contains(&(libc::SYS_semtimedop as u32))); -} - -#[test] -fn test_no_supervisor_blocklist_expands_deny_group() { - let mut policy = Sandbox::builder() - .extra_allow_syscalls(vec!["sysv_ipc".into()]) - .build() - .unwrap(); - policy.extra_deny_syscalls = vec!["sysv_ipc".into()]; - let nrs = no_supervisor_blocklist_syscall_numbers(&policy); - assert!(nrs.contains(&(libc::SYS_shmget as u32))); - assert!(nrs.contains(&(libc::SYS_msgctl as u32))); -} - -#[test] -fn test_no_supervisor_blocklist_includes_sysv_ipc_by_default() { - let policy = Sandbox::builder().build().unwrap(); - let nrs = no_supervisor_blocklist_syscall_numbers(&policy); - assert!(nrs.contains(&(libc::SYS_shmget as u32))); - assert!(nrs.contains(&(libc::SYS_msgget as u32))); - assert!(nrs.contains(&(libc::SYS_semget as u32))); -} - -#[test] -fn test_no_supervisor_blocklist_excludes_sysv_ipc_when_allowed() { - let policy = Sandbox::builder() - .extra_allow_syscalls(vec!["sysv_ipc".into()]) - .build() - .unwrap(); - let nrs = no_supervisor_blocklist_syscall_numbers(&policy); - assert!(!nrs.contains(&(libc::SYS_shmget as u32))); - assert!(!nrs.contains(&(libc::SYS_msgget as u32))); - assert!(!nrs.contains(&(libc::SYS_semget as u32))); -} - -#[test] -fn test_no_supervisor_blocklist_denies_namespaces() { - let policy = Sandbox::builder().build().unwrap(); - let nrs = no_supervisor_blocklist_syscall_numbers(&policy); - assert!(nrs.contains(&(libc::SYS_unshare as u32))); - assert!(nrs.contains(&(libc::SYS_setns as u32))); -} - -#[test] -fn test_arg_filters_has_clone_ioctl_prctl_socket() { - use crate::sys::structs::{BPF_JEQ, BPF_JMP, BPF_JSET, BPF_K}; - let policy = Sandbox::builder().build().unwrap(); - let filters = arg_filters(&policy); - // Should contain JEQ for clone syscall nr - assert!(filters - .iter() - .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == libc::SYS_clone as u32)); - // Should contain JSET for CLONE_NS_FLAGS - assert!(filters - .iter() - .any(|f| f.code == (BPF_JMP | BPF_JSET | BPF_K) && f.k == CLONE_NS_FLAGS as u32)); - // Should contain JEQ for ioctl syscall nr - assert!(filters - .iter() - .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == libc::SYS_ioctl as u32)); - // Should contain JEQ for TIOCSTI, TIOCLINUX, and SIOCGIF*/SIOCETHTOOL - assert!(filters - .iter() - .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == TIOCSTI as u32)); - assert!(filters - .iter() - .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == TIOCLINUX as u32)); - assert!(filters - .iter() - .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == SIOCGIFCONF as u32)); - assert!(filters - .iter() - .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == SIOCETHTOOL as u32)); - // Should contain JEQ for prctl syscall nr - assert!(filters - .iter() - .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == libc::SYS_prctl as u32)); - // Should contain JEQ for PR_SET_DUMPABLE - assert!(filters - .iter() - .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == PR_SET_DUMPABLE)); -} - -#[test] -fn test_arg_filters_mprotect_traps_only_with_memory_limit() { - use crate::sys::structs::{ - BPF_ABS, BPF_JEQ, BPF_JMP, BPF_JSET, BPF_K, BPF_LD, BPF_W, OFFSET_ARGS2_LO, - }; - // SYS_mprotect collides with AF_INET6 on x86_64, so the test looks for - // the nr check followed by the prot load rather than the bare constant. - let has_mprotect = |filters: &[crate::sys::structs::SockFilter]| { - filters.windows(2).any(|w| { - w[0].code == (BPF_JMP | BPF_JEQ | BPF_K) - && w[0].k == libc::SYS_mprotect as u32 - && w[1].code == (BPF_LD | BPF_W | BPF_ABS) - && w[1].k == OFFSET_ARGS2_LO - }) - }; - let unlimited = Sandbox::builder().build().unwrap(); - assert!(!has_mprotect(&arg_filters(&unlimited))); - - let limited = Sandbox::builder() - .max_memory(crate::sandbox::ByteSize::mib(256)) - .build() - .unwrap(); - let filters = arg_filters(&limited); - assert!(has_mprotect(&filters)); - assert!(filters - .iter() - .any(|f| f.code == (BPF_JMP | BPF_JSET | BPF_K) && f.k == libc::PROT_WRITE as u32)); -} - -#[test] -fn test_arg_filters_raw_sockets() { - use crate::sys::structs::{BPF_ALU, BPF_AND, BPF_JEQ, BPF_JMP, BPF_K}; - // Raw sockets are blocked by default: no `icmp-raw://*` rule. - let policy = Sandbox::builder().build().unwrap(); - let filters = arg_filters(&policy); - // Should have AF_INET check - assert!(filters - .iter() - .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == AF_INET)); - // Should have AF_INET6 check - assert!(filters - .iter() - .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == AF_INET6)); - // Should have ALU AND SOCK_TYPE_MASK - assert!(filters - .iter() - .any(|f| f.code == (BPF_ALU | BPF_AND | BPF_K) && f.k == SOCK_TYPE_MASK)); - // Should have JEQ SOCK_RAW - assert!(filters - .iter() - .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == SOCK_RAW)); -} - -#[test] -fn test_arg_filters_udp_denied_by_default() { - // SOCK_DGRAM creation is denied when no net rule exists: nothing traps - // sends, so socket() is the only enforcement point. - let policy = Sandbox::builder().build().unwrap(); - assert_eq!(count_jeq_2(&arg_filters(&policy)), 2); -} - -/// AF_INET and SOCK_DGRAM share the constant 2, so presence of the -/// SOCK_DGRAM JEQ is observed as the JEQ-with-k==2 count: the AF_INET -/// domain check contributes one in every socket filter, the type check -/// contributes the second only when SOCK_DGRAM is in the blocked set. -fn count_jeq_2(filters: &[crate::sys::structs::SockFilter]) -> usize { - use crate::sys::structs::{BPF_JEQ, BPF_JMP, BPF_K}; - filters - .iter() - .filter(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == 2) - .count() -} - -#[test] -fn test_arg_filters_udp_creatable_with_tcp_only_rules() { - // Any net rule moves UDP enforcement to send time: the on-behalf - // handlers deny destinations for rule-less protocols, so socket() - // must succeed (glibc getaddrinfo probes create UDP sockets). - let policy = Sandbox::builder().net_allow("1.1.1.1:443").build().unwrap(); - assert_eq!(count_jeq_2(&arg_filters(&policy)), 1); -} - -#[test] -fn test_arg_filters_udp_creatable_with_net_deny() { - let policy = Sandbox::builder().net_deny("10.0.0.0/8").build().unwrap(); - assert_eq!(count_jeq_2(&arg_filters(&policy)), 1); -} - -#[test] -fn test_syscall_name_to_nr_covers_defaults() { - // Every name in DEFAULT_BLOCKLIST_SYSCALLS should resolve unless the - // running architecture does not expose that syscall. - // `nfsservctl` now resolves: the syscalls crate carries it (kernel - // returns ENOSYS, but the ABI number exists), so it is enforced in the - // blocklist rather than silently dropped. `ioperm`/`iopl` are x86-only. - let expected_unresolved: &[&str] = &[ - #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))] - "ioperm", - #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))] - "iopl", - ]; - let mut skipped = 0; - for name in DEFAULT_BLOCKLIST_SYSCALLS { - match syscall_name_to_nr(name) { - Some(_) => {} - None => { - assert!( - expected_unresolved.contains(name), - "unexpected unresolved syscall: {}", - name - ); - skipped += 1; - } - } - } - assert_eq!(skipped, expected_unresolved.len()); -} - #[test] fn test_effective_nofile_clamps_to_both_inherited_bounds() { // A request below both bounds is applied verbatim, the ordinary case. diff --git a/crates/sandlock-core/src/features.rs b/crates/sandlock-core/src/features.rs index c2b0112d4..a251f671d 100644 --- a/crates/sandlock-core/src/features.rs +++ b/crates/sandlock-core/src/features.rs @@ -26,8 +26,6 @@ pub(crate) struct SandboxFeatures { pub(crate) time_start: bool, pub(crate) virtual_cpu_count: bool, pub(crate) virtual_hostname: bool, - /// Off when the policy denies sysinfo: a notified syscall would bypass the deny. - pub(crate) virtual_sysinfo: bool, pub(crate) cow: bool, pub(crate) chroot: bool, pub(crate) fs_denies: bool, @@ -73,8 +71,6 @@ impl SandboxFeatures { time_start: sandbox.time_start.is_some(), virtual_cpu_count: sandbox.num_cpus.is_some(), virtual_hostname: sandbox_name.is_some(), - virtual_sysinfo: !crate::seccomp_plan::blocklist_syscall_numbers(sandbox) - .contains(&(libc::SYS_sysinfo as u32)), cow: sandbox.workdir.is_some(), chroot: sandbox.chroot.is_some(), fs_denies: !sandbox.fs_denied.is_empty(), diff --git a/crates/sandlock-core/src/lib.rs b/crates/sandlock-core/src/lib.rs index 1b26f6a41..b0be45fdb 100644 --- a/crates/sandlock-core/src/lib.rs +++ b/crates/sandlock-core/src/lib.rs @@ -43,7 +43,6 @@ pub(crate) mod resource; pub mod result; pub mod sandbox; // formerly `policy`; contains Sandbox + SandboxBuilder + Confinement pub mod seccomp; -pub(crate) mod seccomp_plan; pub(crate) mod sys; pub(crate) mod time; #[cfg(feature = "cow")] diff --git a/crates/sandlock-core/src/sandbox.rs b/crates/sandlock-core/src/sandbox.rs index 81632e3b8..d742be506 100644 --- a/crates/sandlock-core/src/sandbox.rs +++ b/crates/sandlock-core/src/sandbox.rs @@ -2082,9 +2082,9 @@ impl Sandbox { let _ = crate::landlock_policy::confine(&sandbox_cfg); - let deny = crate::context::blocklist_syscall_numbers(&sandbox_cfg); - let args = crate::context::arg_filters(&sandbox_cfg); - let filter = match crate::seccomp::bpf::assemble_filter(&[], &deny, &args) { + let features = crate::features::SandboxFeatures::from_sandbox(&sandbox_cfg, None, &[]); + let spec = crate::seccomp::filter::FilterSpec::deny_only(&sandbox_cfg, &features); + let filter = match spec.assemble() { Ok(f) => f, Err(_) => unsafe { libc::_exit(1) }, }; diff --git a/crates/sandlock-core/src/seccomp/bpf.rs b/crates/sandlock-core/src/seccomp/bpf.rs index 67ac2272e..0a8eb53ef 100644 --- a/crates/sandlock-core/src/seccomp/bpf.rs +++ b/crates/sandlock-core/src/seccomp/bpf.rs @@ -47,7 +47,7 @@ pub(crate) fn jump(code: u16, k: u32, jt: u8, jf: u8) -> SockFilter { /// /// * `notif_syscalls` — syscalls that generate SECCOMP_RET_USER_NOTIF /// * `block_syscalls` — syscalls that return ERRNO(EPERM) -/// * `arg_block` — pre-built arg filter instructions (from `context::arg_filters`) +/// * `arg_block` — pre-built arg filter instructions (from `filter::FilterSpec`) /// /// Returns an error if a syscall appears in both notification and deny lists, /// or if the resulting program would exceed the kernel's `BPF_MAXINSNS` diff --git a/crates/sandlock-core/src/seccomp/dispatch.rs b/crates/sandlock-core/src/seccomp/dispatch.rs index 1d026dd05..4d644ba06 100644 --- a/crates/sandlock-core/src/seccomp/dispatch.rs +++ b/crates/sandlock-core/src/seccomp/dispatch.rs @@ -165,13 +165,13 @@ pub enum HandlerError { /// `NotifAction::Continue` becomes `SECCOMP_USER_NOTIF_FLAG_CONTINUE` and /// the kernel actually runs the syscall — silently bypassing deny. /// -/// The blocklist is whatever [`crate::context::blocklist_syscall_numbers`] +/// 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 `context::notif_syscalls`) +/// 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 { @@ -193,9 +193,7 @@ pub(crate) fn validate_handler_syscalls_against_policy( policy: &crate::sandbox::Sandbox, ) -> Result<(), i64> { let blocklist: std::collections::HashSet = - crate::context::blocklist_syscall_numbers(policy) - .into_iter() - .collect(); + super::filter::blocklist(policy).into_iter().collect(); for &nr in syscall_nrs { if blocklist.contains(&(nr as u32)) { return Err(nr); @@ -1558,7 +1556,7 @@ mod handler_tests { /// Uses `mremap` because it is in `syscall_name_to_nr` but not in /// `DEFAULT_BLOCKLIST_SYSCALLS` — putting it into `extra_deny_syscalls` is the only /// way it ends up on the extra blocklist, so the test isolates the user-supplied - /// path of `blocklist_syscall_numbers` from the default branch covered by + /// path of `blocklist` from the default branch covered by /// `handler_on_default_blocklist_syscall_is_rejected`. /// /// Pure-logic counterpart to the integration test of the same name — diff --git a/crates/sandlock-core/src/seccomp_plan.rs b/crates/sandlock-core/src/seccomp/filter.rs similarity index 90% rename from crates/sandlock-core/src/seccomp_plan.rs rename to crates/sandlock-core/src/seccomp/filter.rs index d94c24299..203016514 100644 --- a/crates/sandlock-core/src/seccomp_plan.rs +++ b/crates/sandlock-core/src/seccomp/filter.rs @@ -1,8 +1,6 @@ -//! Seccomp syscall and argument-filter planning. -//! -//! This module turns the normalized sandbox feature view into the concrete -//! syscall notification lists, blocklists, and BPF argument filters installed -//! by the child-side confinement path. +//! What the kernel filter does for one sandbox: which syscalls reach the +//! supervisor, which are refused outright, and which are decided on their +//! arguments. use syscalls::{Sysno, SysnoSet}; @@ -10,7 +8,7 @@ use crate::arch; use crate::features::SandboxFeatures; use crate::policy_fn::SyscallCategory; use crate::sandbox::Sandbox; -use crate::seccomp::bpf::{jump, stmt}; +use crate::seccomp::bpf::{self, jump, stmt}; use crate::sys::structs::{ SockFilter, AF_INET, AF_INET6, BPF_ABS, BPF_ALU, BPF_AND, BPF_JEQ, BPF_JMP, BPF_JSET, BPF_K, BPF_LD, BPF_RET, BPF_W, CLONE_NS_FLAGS, DEFAULT_BLOCKLIST_SYSCALLS, EPERM, OFFSET_ARGS0_LO, @@ -21,6 +19,59 @@ use crate::sys::structs::{ TIOCLINUX, TIOCSTI, }; +/// The seccomp filter of one sandbox, before it is encoded as cBPF. +pub(crate) struct FilterSpec { + notify: Vec, + deny: Vec, + arg_block: Vec, +} + +impl FilterSpec { + /// `handler_syscalls` are notified as well: the kernel raises nothing + /// for a syscall the filter allows, so its handler would never fire. + pub(crate) fn supervised( + sandbox: &Sandbox, + features: &SandboxFeatures, + handler_syscalls: &[u32], + ) -> Self { + let deny = blocklist(sandbox); + let mut notify = notify_syscalls(features, &deny); + notify.extend_from_slice(handler_syscalls); + notify.sort_unstable(); + notify.dedup(); + Self { + notify, + deny, + arg_block: arg_block(features), + } + } + + /// Nothing is notified: for a process that has no supervisor of its own. + pub(crate) fn deny_only(sandbox: &Sandbox, features: &SandboxFeatures) -> Self { + Self { + notify: Vec::new(), + deny: blocklist(sandbox), + arg_block: arg_block(features), + } + } + + /// Like [`Self::deny_only`], but leaves `ptrace`, `process_vm_*` and the + /// like alone so a supervised sandbox nested inside still has the + /// syscalls its supervisor needs. + pub(crate) fn no_supervisor(sandbox: &Sandbox, features: &SandboxFeatures) -> Self { + use crate::sys::structs::NO_SUPERVISOR_BLOCKLIST_SYSCALLS; + Self { + notify: Vec::new(), + deny: resolve_blocklist(NO_SUPERVISOR_BLOCKLIST_SYSCALLS, sandbox), + arg_block: arg_block(features), + } + } + + pub(crate) fn assemble(&self) -> std::io::Result> { + bpf::assemble_filter(&self.notify, &self.deny, &self.arg_block) + } +} + // ============================================================ // Sandbox -> syscall lists // ============================================================ @@ -75,7 +126,7 @@ const MEMORY_NOTIF_SYSCALLS: &[i64] = &[ libc::SYS_munmap, libc::SYS_brk, libc::SYS_mremap, - // Only calls granting PROT_WRITE reach the supervisor; see arg_filters. + // 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 @@ -362,14 +413,8 @@ const POLICY_EXEC_EVENT_SYSCALLS: &[i64] = &[libc::SYS_execve, libc::SYS_execvea const PORT_REMAP_SYSCALLS: &[i64] = &[libc::SYS_bind, libc::SYS_getsockname]; -/// Determine which syscalls need `SECCOMP_RET_USER_NOTIF`. -pub(crate) fn notif_syscalls(policy: &Sandbox, sandbox_name: Option<&str>) -> Vec { - notif_syscalls_resolved(&SandboxFeatures::from_sandbox(policy, sandbox_name, &[])) -} - -/// Determine which syscalls need `SECCOMP_RET_USER_NOTIF` from the resolved -/// internal feature view. -pub(crate) fn notif_syscalls_resolved(features: &SandboxFeatures) -> Vec { +/// Syscalls that need `SECCOMP_RET_USER_NOTIF`. +fn notify_syscalls(features: &SandboxFeatures, deny: &[u32]) -> Vec { let mut nrs = SyscallList::with(BASE_NOTIF_SYSCALLS); nrs.push_optional(arch::sys_vfork()); @@ -414,7 +459,8 @@ pub(crate) fn notif_syscalls_resolved(features: &SandboxFeatures) -> Vec { nrs.extend(&procfs_hosts_notif_syscalls()); nrs.extend(NETLINK_NOTIF_SYSCALLS); - if features.virtual_sysinfo { + // A notified syscall would bypass the deny. + if !deny.contains(&(libc::SYS_sysinfo as u32)) { nrs.push(libc::SYS_sysinfo); } @@ -496,35 +542,22 @@ fn resolve_blocklist(base: &[&str], policy: &Sandbox) -> Vec { set.iter().map(|s| s.id() as u32).collect() } -/// Resolve `NO_SUPERVISOR_BLOCKLIST_SYSCALLS` names to numbers, plus -/// SysV IPC syscalls when `policy.allows_sysv_ipc()` is false. -pub(crate) fn no_supervisor_blocklist_syscall_numbers(policy: &Sandbox) -> Vec { - use crate::sys::structs::NO_SUPERVISOR_BLOCKLIST_SYSCALLS; - resolve_blocklist(NO_SUPERVISOR_BLOCKLIST_SYSCALLS, policy) -} - /// Resolve the default syscall blocklist plus policy extras to numbers. /// /// SysV IPC syscalls are appended to the resolved blocklist when /// `policy.allows_sysv_ipc()` is false. -pub(crate) fn blocklist_syscall_numbers(policy: &Sandbox) -> Vec { +pub(crate) fn blocklist(policy: &Sandbox) -> Vec { resolve_blocklist(DEFAULT_BLOCKLIST_SYSCALLS, policy) } -/// Build argument-level seccomp filter instructions matching the Python -/// `_build_arg_filters()` exactly. -/// -/// Returns a `Vec` containing self-contained BPF blocks for: +/// Self-contained BPF blocks that decide a syscall on its arguments: /// - clone: block namespace creation flags /// - clone3: refuse with ENOSYS so callers fall back to clone /// - ioctl: block TIOCSTI, TIOCLINUX, SIOCGIF*, SIOCETHTOOL /// - prctl: block PR_SET_DUMPABLE, PR_SET_SECUREBITS, PR_SET_PTRACER /// - socket: block SOCK_RAW/SOCK_DGRAM on AF_INET/AF_INET6 (with type mask) -pub(crate) fn arg_filters(policy: &Sandbox) -> Vec { - arg_filters_resolved(&SandboxFeatures::from_sandbox(policy, None, &[])) -} - -pub(crate) fn arg_filters_resolved(features: &SandboxFeatures) -> Vec { +/// - mprotect: allow without notifying unless PROT_WRITE is granted +fn arg_block(features: &SandboxFeatures) -> Vec { let ret_errno = SECCOMP_RET_ERRNO | EPERM as u32; let nr_clone = libc::SYS_clone as u32; let nr_ioctl = libc::SYS_ioctl as u32; @@ -704,3 +737,6 @@ pub(crate) fn arg_filters_resolved(features: &SandboxFeatures) -> Vec) -> SandboxFeatures { + SandboxFeatures::from_sandbox(policy, sandbox_name, &[]) +} + +fn notified(policy: &Sandbox, sandbox_name: Option<&str>) -> Vec { + FilterSpec::supervised(policy, &features(policy, sandbox_name), &[]).notify +} + +#[test] +fn handler_syscalls_are_notified_once() { + let policy = Sandbox::builder().build().unwrap(); + let extra = [libc::SYS_getpid as u32, libc::SYS_clone as u32]; + let spec = FilterSpec::supervised(&policy, &features(&policy, None), &extra); + for nr in extra { + assert_eq!(spec.notify.iter().filter(|&&n| n == nr).count(), 1); + } +} + +#[test] +fn deny_only_filters_notify_nothing() { + let policy = Sandbox::builder().build().unwrap(); + let features = features(&policy, None); + assert!(FilterSpec::deny_only(&policy, &features).notify.is_empty()); + assert!(FilterSpec::no_supervisor(&policy, &features) + .notify + .is_empty()); +} + +/// The netlink cookie is recognised by identity, so close() need not be +/// trapped for it; close is one of the hottest syscalls a program makes. +#[test] +fn close_is_not_a_notified_syscall() { + let policy = Sandbox::builder().build().unwrap(); + assert!(!notified(&policy, None).contains(&(libc::SYS_close as u32))); +} + +#[test] +fn test_policy_fn_network_events_skip_file_and_exec_traps() { + let policy = Sandbox::builder() + .policy_fn(PolicyFn::new(|_event, _ctx| Verdict::Allow).events(&[SyscallCategory::Network])) + .build() + .unwrap(); + let notified = notified(&policy, None); + assert!(notified.contains(&(libc::SYS_connect as u32))); + assert!(notified.contains(&(libc::SYS_sendmmsg as u32))); + assert!(!notified.contains(&(libc::SYS_mkdirat as u32))); + assert!(!notified.contains(&(libc::SYS_unlinkat as u32))); + assert!(!notified.contains(&(libc::SYS_execve as u32))); +} + +#[test] +fn test_notif_syscalls_always_has_clone() { + let policy = Sandbox::builder().build().unwrap(); + let nrs = notified(&policy, None); + assert!(nrs.contains(&(libc::SYS_clone as u32))); + if let Some(vfork) = arch::sys_vfork() { + assert!(nrs.contains(&(vfork as u32))); + } + if let Some(fork) = arch::sys_fork() { + assert!(nrs.contains(&(fork as u32))); + } +} + +#[test] +fn test_notif_syscalls_memory() { + // shmget only appears in notif when SysV IPC is allowed: + // otherwise it is on the kernel blocklist and notifying would + // bypass the deny (notif JEQs precede deny JEQs in the BPF + // layout). + let policy = Sandbox::builder() + .max_memory(crate::sandbox::ByteSize::mib(256)) + .extra_allow_syscalls(vec!["sysv_ipc".into()]) + .build() + .unwrap(); + let nrs = notified(&policy, None); + assert!(nrs.contains(&(libc::SYS_mmap as u32))); + assert!(nrs.contains(&(libc::SYS_munmap as u32))); + assert!(nrs.contains(&(libc::SYS_brk as u32))); + assert!(nrs.contains(&(libc::SYS_mremap as u32))); + assert!(nrs.contains(&(libc::SYS_shmget as u32))); +} + +#[test] +fn test_notif_syscalls_memory_excludes_shmget_when_sysv_ipc_denied() { + // With max_memory but allows_sysv_ipc()=false (the default), + // shmget must NOT be in notif: if it were, the BPF filter + // would route it to RET_USER_NOTIF before reaching the deny + // JEQ, silently bypassing the kernel-level deny. + let policy = Sandbox::builder() + .max_memory(crate::sandbox::ByteSize::mib(256)) + .build() + .unwrap(); + let nrs = notified(&policy, None); + assert!(!nrs.contains(&(libc::SYS_shmget as u32))); + // Other memory syscalls remain notified; they are not denied. + assert!(nrs.contains(&(libc::SYS_mmap as u32))); + assert!(nrs.contains(&(libc::SYS_brk as u32))); +} + +#[test] +fn test_notif_syscalls_net() { + let policy = Sandbox::builder() + .net_allow("example.com:443") + .build() + .unwrap(); + let nrs = notified(&policy, None); + assert!(nrs.contains(&(libc::SYS_connect as u32))); + assert!(nrs.contains(&(libc::SYS_sendto as u32))); + assert!(nrs.contains(&(libc::SYS_sendmsg as u32))); + assert!(nrs.contains(&(libc::SYS_sendmmsg as u32))); +} + +#[test] +fn test_notif_syscalls_net_deny() { + // --net-deny is default-allow but still needs every connect/sendto + // routed to the on-behalf path so the DenyList can refuse matches. + let policy = Sandbox::builder().net_deny("10.0.0.0/8").build().unwrap(); + let nrs = notified(&policy, None); + assert!(nrs.contains(&(libc::SYS_connect as u32))); + assert!(nrs.contains(&(libc::SYS_sendto as u32))); +} + +#[test] +fn test_notif_syscalls_sandbox_name_enables_hostname_virtualization() { + let policy = Sandbox::builder().build().unwrap(); + let nrs = notified(&policy, Some("api.local")); + assert!(nrs.contains(&(libc::SYS_uname as u32))); + assert!(nrs.contains(&(libc::SYS_openat as u32))); +} + +#[test] +fn test_notif_syscalls_virtualize_sysinfo() { + let policy = Sandbox::builder().build().unwrap(); + assert!(notified(&policy, None).contains(&(libc::SYS_sysinfo as u32))); +} + +#[test] +fn test_notif_syscalls_skip_denied_sysinfo() { + let policy = Sandbox::builder() + .extra_deny_syscalls(vec!["sysinfo".into()]) + .build() + .unwrap(); + assert!(!notified(&policy, None).contains(&(libc::SYS_sysinfo as u32))); +} + +/// SYS_faccessat2 (439) must be in the notification filter for both +/// chroot and COW modes; glibc 2.33+ uses it instead of faccessat. +#[test] +fn test_notif_syscalls_faccessat2() { + // Chroot mode + let policy = Sandbox::builder().chroot("/tmp").build().unwrap(); + let nrs = notified(&policy, None); + assert!(nrs.contains(&(libc::SYS_faccessat as u32))); + assert!( + nrs.contains(&(arch::SYS_FACCESSAT2 as u32)), + "chroot notif filter must include SYS_faccessat2 (439)" + ); +} + +#[cfg(feature = "cow")] +#[test] +fn test_notif_syscalls_faccessat2_cow() { + let policy = Sandbox::builder().workdir("/tmp").build().unwrap(); + let nrs = notified(&policy, None); + assert!(nrs.contains(&(libc::SYS_faccessat as u32))); + assert!( + nrs.contains(&(arch::SYS_FACCESSAT2 as u32)), + "COW notif filter must include SYS_faccessat2 (439)" + ); +} + +#[test] +fn test_blocklist_syscall_numbers_default() { + let policy = Sandbox::builder().build().unwrap(); + let nrs = blocklist(&policy); + // Should contain mount, ptrace, etc. + assert!(nrs.contains(&(libc::SYS_mount as u32))); + assert!(nrs.contains(&(libc::SYS_ptrace as u32))); + assert!(nrs.contains(&(libc::SYS_bpf as u32))); + // SysV IPC denied by default (no IPC namespace in sandlock) + assert!(nrs.contains(&(libc::SYS_shmget as u32))); + assert!(nrs.contains(&(libc::SYS_shmat as u32))); + assert!(nrs.contains(&(libc::SYS_msgget as u32))); + assert!(nrs.contains(&(libc::SYS_semget as u32))); + // nfsservctl has no libc constant, so it is skipped + assert!(!nrs.is_empty()); +} + +#[test] +fn test_blocklist_syscall_numbers_custom() { + let policy = Sandbox::builder() + .extra_deny_syscalls(vec!["mount".into(), "ptrace".into()]) + .build() + .unwrap(); + let nrs = blocklist(&policy); + // User-supplied blocklist still gets SysV IPC appended + // (allows_sysv_ipc() defaults to false). + assert!(nrs.contains(&(libc::SYS_mount as u32))); + assert!(nrs.contains(&(libc::SYS_ptrace as u32))); + assert!(nrs.contains(&(libc::SYS_shmget as u32))); +} + +#[test] +fn test_blocklist_syscall_numbers_custom_with_sysv_ipc_allowed() { + let policy = Sandbox::builder() + .extra_deny_syscalls(vec!["mount".into(), "ptrace".into()]) + .extra_allow_syscalls(vec!["sysv_ipc".into()]) + .build() + .unwrap(); + let nrs = blocklist(&policy); + // Default blocklist plus user extras: no SysV IPC append. + assert!(nrs.contains(&(libc::SYS_mount as u32))); + assert!(nrs.contains(&(libc::SYS_ptrace as u32))); + assert!(nrs.contains(&(libc::SYS_bpf as u32))); + assert!(!nrs.contains(&(libc::SYS_shmget as u32))); +} + +#[test] +fn test_blocklist_syscall_numbers_default_with_sysv_ipc_allowed() { + let policy = Sandbox::builder() + .extra_allow_syscalls(vec!["sysv_ipc".into()]) + .build() + .unwrap(); + let nrs = blocklist(&policy); + // Default blocklist still present, but SysV IPC is permitted. + assert!(nrs.contains(&(libc::SYS_mount as u32))); + assert!(!nrs.contains(&(libc::SYS_shmget as u32))); + assert!(!nrs.contains(&(libc::SYS_msgget as u32))); + assert!(!nrs.contains(&(libc::SYS_semget as u32))); +} + +// The expansion tests below inject the group deny after build(): with +// allow "sysv_ipc" set, the !allows_sysv_ipc() fallback in +// resolve_blocklist is skipped, so the members can appear only through +// group expansion of the deny entry. Going through build() instead +// would either trip the allow/deny conflict check or (deny-only) let +// the fallback add the members and mask a broken expansion. +#[test] +fn test_blocklist_syscall_numbers_expands_deny_group() { + let mut policy = Sandbox::builder() + .extra_allow_syscalls(vec!["sysv_ipc".into()]) + .build() + .unwrap(); + policy.extra_deny_syscalls = vec!["sysv_ipc".into()]; + let nrs = blocklist(&policy); + assert!(nrs.contains(&(libc::SYS_shmget as u32))); + assert!(nrs.contains(&(libc::SYS_msgget as u32))); + assert!(nrs.contains(&(libc::SYS_semget as u32))); + assert!(nrs.contains(&(libc::SYS_semtimedop as u32))); +} + +#[test] +fn test_no_supervisor_blocklist_expands_deny_group() { + let mut policy = Sandbox::builder() + .extra_allow_syscalls(vec!["sysv_ipc".into()]) + .build() + .unwrap(); + policy.extra_deny_syscalls = vec!["sysv_ipc".into()]; + let nrs = FilterSpec::no_supervisor(&policy, &features(&policy, None)).deny; + assert!(nrs.contains(&(libc::SYS_shmget as u32))); + assert!(nrs.contains(&(libc::SYS_msgctl as u32))); +} + +#[test] +fn test_no_supervisor_blocklist_includes_sysv_ipc_by_default() { + let policy = Sandbox::builder().build().unwrap(); + let nrs = FilterSpec::no_supervisor(&policy, &features(&policy, None)).deny; + assert!(nrs.contains(&(libc::SYS_shmget as u32))); + assert!(nrs.contains(&(libc::SYS_msgget as u32))); + assert!(nrs.contains(&(libc::SYS_semget as u32))); +} + +#[test] +fn test_no_supervisor_blocklist_excludes_sysv_ipc_when_allowed() { + let policy = Sandbox::builder() + .extra_allow_syscalls(vec!["sysv_ipc".into()]) + .build() + .unwrap(); + let nrs = FilterSpec::no_supervisor(&policy, &features(&policy, None)).deny; + assert!(!nrs.contains(&(libc::SYS_shmget as u32))); + assert!(!nrs.contains(&(libc::SYS_msgget as u32))); + assert!(!nrs.contains(&(libc::SYS_semget as u32))); +} + +#[test] +fn test_no_supervisor_blocklist_denies_namespaces() { + let policy = Sandbox::builder().build().unwrap(); + let nrs = FilterSpec::no_supervisor(&policy, &features(&policy, None)).deny; + assert!(nrs.contains(&(libc::SYS_unshare as u32))); + assert!(nrs.contains(&(libc::SYS_setns as u32))); +} + +#[test] +fn test_arg_filters_has_clone_ioctl_prctl_socket() { + use crate::sys::structs::{BPF_JEQ, BPF_JMP, BPF_JSET, BPF_K}; + let policy = Sandbox::builder().build().unwrap(); + let filters = arg_block(&features(&policy, None)); + // Should contain JEQ for clone syscall nr + assert!(filters + .iter() + .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == libc::SYS_clone as u32)); + // Should contain JSET for CLONE_NS_FLAGS + assert!(filters + .iter() + .any(|f| f.code == (BPF_JMP | BPF_JSET | BPF_K) && f.k == CLONE_NS_FLAGS as u32)); + // Should contain JEQ for ioctl syscall nr + assert!(filters + .iter() + .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == libc::SYS_ioctl as u32)); + // Should contain JEQ for TIOCSTI, TIOCLINUX, and SIOCGIF*/SIOCETHTOOL + assert!(filters + .iter() + .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == TIOCSTI as u32)); + assert!(filters + .iter() + .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == TIOCLINUX as u32)); + assert!(filters + .iter() + .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == SIOCGIFCONF as u32)); + assert!(filters + .iter() + .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == SIOCETHTOOL as u32)); + // Should contain JEQ for prctl syscall nr + assert!(filters + .iter() + .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == libc::SYS_prctl as u32)); + // Should contain JEQ for PR_SET_DUMPABLE + assert!(filters + .iter() + .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == PR_SET_DUMPABLE)); +} + +#[test] +fn test_arg_filters_mprotect_traps_only_with_memory_limit() { + use crate::sys::structs::{ + BPF_ABS, BPF_JEQ, BPF_JMP, BPF_JSET, BPF_K, BPF_LD, BPF_W, OFFSET_ARGS2_LO, + }; + // SYS_mprotect collides with AF_INET6 on x86_64, so the test looks for + // the nr check followed by the prot load rather than the bare constant. + let has_mprotect = |filters: &[crate::sys::structs::SockFilter]| { + filters.windows(2).any(|w| { + w[0].code == (BPF_JMP | BPF_JEQ | BPF_K) + && w[0].k == libc::SYS_mprotect as u32 + && w[1].code == (BPF_LD | BPF_W | BPF_ABS) + && w[1].k == OFFSET_ARGS2_LO + }) + }; + let unlimited = Sandbox::builder().build().unwrap(); + assert!(!has_mprotect(&arg_block(&features(&unlimited, None)))); + + let limited = Sandbox::builder() + .max_memory(crate::sandbox::ByteSize::mib(256)) + .build() + .unwrap(); + let filters = arg_block(&features(&limited, None)); + assert!(has_mprotect(&filters)); + assert!(filters + .iter() + .any(|f| f.code == (BPF_JMP | BPF_JSET | BPF_K) && f.k == libc::PROT_WRITE as u32)); +} + +#[test] +fn test_arg_filters_raw_sockets() { + use crate::sys::structs::{BPF_ALU, BPF_AND, BPF_JEQ, BPF_JMP, BPF_K}; + // Raw sockets are blocked by default: no `icmp-raw://*` rule. + let policy = Sandbox::builder().build().unwrap(); + let filters = arg_block(&features(&policy, None)); + // Should have AF_INET check + assert!(filters + .iter() + .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == AF_INET)); + // Should have AF_INET6 check + assert!(filters + .iter() + .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == AF_INET6)); + // Should have ALU AND SOCK_TYPE_MASK + assert!(filters + .iter() + .any(|f| f.code == (BPF_ALU | BPF_AND | BPF_K) && f.k == SOCK_TYPE_MASK)); + // Should have JEQ SOCK_RAW + assert!(filters + .iter() + .any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == SOCK_RAW)); +} + +#[test] +fn test_arg_filters_udp_denied_by_default() { + // SOCK_DGRAM creation is denied when no net rule exists: nothing traps + // sends, so socket() is the only enforcement point. + let policy = Sandbox::builder().build().unwrap(); + assert_eq!(count_jeq_2(&arg_block(&features(&policy, None))), 2); +} + +/// AF_INET and SOCK_DGRAM share the constant 2, so presence of the +/// SOCK_DGRAM JEQ is observed as the JEQ-with-k==2 count: the AF_INET +/// domain check contributes one in every socket filter, the type check +/// contributes the second only when SOCK_DGRAM is in the blocked set. +fn count_jeq_2(filters: &[crate::sys::structs::SockFilter]) -> usize { + use crate::sys::structs::{BPF_JEQ, BPF_JMP, BPF_K}; + filters + .iter() + .filter(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K) && f.k == 2) + .count() +} + +#[test] +fn test_arg_filters_udp_creatable_with_tcp_only_rules() { + // Any net rule moves UDP enforcement to send time: the on-behalf + // handlers deny destinations for rule-less protocols, so socket() + // must succeed (glibc getaddrinfo probes create UDP sockets). + let policy = Sandbox::builder().net_allow("1.1.1.1:443").build().unwrap(); + assert_eq!(count_jeq_2(&arg_block(&features(&policy, None))), 1); +} + +#[test] +fn test_arg_filters_udp_creatable_with_net_deny() { + let policy = Sandbox::builder().net_deny("10.0.0.0/8").build().unwrap(); + assert_eq!(count_jeq_2(&arg_block(&features(&policy, None))), 1); +} + +#[test] +fn test_syscall_name_to_nr_covers_defaults() { + // Every name in DEFAULT_BLOCKLIST_SYSCALLS should resolve unless the + // running architecture does not expose that syscall. + // `nfsservctl` now resolves: the syscalls crate carries it (kernel + // returns ENOSYS, but the ABI number exists), so it is enforced in the + // blocklist rather than silently dropped. `ioperm`/`iopl` are x86-only. + let expected_unresolved: &[&str] = &[ + #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))] + "ioperm", + #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))] + "iopl", + ]; + let mut skipped = 0; + for name in DEFAULT_BLOCKLIST_SYSCALLS { + match syscall_name_to_nr(name) { + Some(_) => {} + None => { + assert!( + expected_unresolved.contains(name), + "unexpected unresolved syscall: {}", + name + ); + skipped += 1; + } + } + } + assert_eq!(skipped, expected_unresolved.len()); +} diff --git a/crates/sandlock-core/src/seccomp/mod.rs b/crates/sandlock-core/src/seccomp/mod.rs index b7b59e1b9..9bbca2882 100644 --- a/crates/sandlock-core/src/seccomp/mod.rs +++ b/crates/sandlock-core/src/seccomp/mod.rs @@ -1,6 +1,7 @@ pub mod bpf; pub(crate) mod ctx; pub mod dispatch; +pub(crate) mod filter; pub(crate) mod gate; pub(crate) mod native; pub mod notif; diff --git a/crates/sandlock-core/src/seccomp/notif.rs b/crates/sandlock-core/src/seccomp/notif.rs index ddb9a759e..59d70cef9 100644 --- a/crates/sandlock-core/src/seccomp/notif.rs +++ b/crates/sandlock-core/src/seccomp/notif.rs @@ -3007,7 +3007,7 @@ async fn handle_notification( .flatten() .map(Arc::new); let denied = has_denied - && crate::seccomp_plan::fs_denied_path_syscalls().contains(&nr) + && super::filter::fs_denied_path_syscalls().contains(&nr) && is_path_denied_for_notif(&*ctx.policy_fn.lock().await, ¬if, fd); // Dispatch runs first so /proc virtualization and the other handlers // still win for their paths. diff --git a/crates/sandlock-core/tests/integration/test_handlers.rs b/crates/sandlock-core/tests/integration/test_handlers.rs index 64bb5abc9..7308cfe9d 100644 --- a/crates/sandlock-core/tests/integration/test_handlers.rs +++ b/crates/sandlock-core/tests/integration/test_handlers.rs @@ -412,8 +412,8 @@ async fn handler_on_default_blocklist_syscall_is_rejected() { /// rejection at user-space discretion. /// /// Counterpart to `handler_on_default_blocklist_syscall_is_rejected`, -/// driving the user-list branch of `blocklist_syscall_numbers` (see -/// `crates/sandlock-core/src/context.rs`). Uses `SYS_mremap` because it is +/// driving the user-list branch of `blocklist` (see +/// `crates/sandlock-core/src/seccomp/filter.rs`). Uses `SYS_mremap` because it is /// in `syscall_name_to_nr` but **not** in DEFAULT_BLOCKLIST — putting it into /// `extra_deny_syscalls` is the only way it lands on the blocklist, isolating the /// user-supplied branch under test from the default-blocklist branch. diff --git a/crates/sandlock-core/tests/integration/test_netlink_virt.rs b/crates/sandlock-core/tests/integration/test_netlink_virt.rs index 3ea4dd3e7..4c8f39b23 100644 --- a/crates/sandlock-core/tests/integration/test_netlink_virt.rs +++ b/crates/sandlock-core/tests/integration/test_netlink_virt.rs @@ -657,15 +657,6 @@ async fn dup2_over_the_cookie_fd_ends_the_netlink_fixups() { ); } -/// The netlink cookie is recognised by identity, so close() need not be -/// trapped for it; close is one of the hottest syscalls a program makes. -#[tokio::test] -async fn close_is_not_a_notified_syscall() { - let policy = base_policy().build().unwrap(); - let notified = sandlock_core::context::notif_syscalls(&policy, None); - assert!(!notified.contains(&(libc::SYS_close as u32))); -} - async fn check_socket_alias(setup: &str) { let script = format!( r#" diff --git a/crates/sandlock-core/tests/integration/test_policy_fn.rs b/crates/sandlock-core/tests/integration/test_policy_fn.rs index d4a80683a..1f8bbfba3 100644 --- a/crates/sandlock-core/tests/integration/test_policy_fn.rs +++ b/crates/sandlock-core/tests/integration/test_policy_fn.rs @@ -556,20 +556,6 @@ async fn test_policy_fn_network_events_only() { ); } -#[test] -fn test_policy_fn_network_events_skip_file_and_exec_traps() { - let policy = base_policy() - .policy_fn(PolicyFn::new(|_event, _ctx| Verdict::Allow).events(&[SyscallCategory::Network])) - .build() - .unwrap(); - let notified = sandlock_core::context::notif_syscalls(&policy, None); - assert!(notified.contains(&(libc::SYS_connect as u32))); - assert!(notified.contains(&(libc::SYS_sendmmsg as u32))); - assert!(!notified.contains(&(libc::SYS_mkdirat as u32))); - assert!(!notified.contains(&(libc::SYS_unlinkat as u32))); - assert!(!notified.contains(&(libc::SYS_execve as u32))); -} - // ============================================================ // Parent PID tests // ============================================================