Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 8 additions & 18 deletions crates/sandlock-core/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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));
}
Expand All @@ -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) => {
Expand Down
16 changes: 10 additions & 6 deletions crates/sandlock-core/src/sandbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) },
Expand Down Expand Up @@ -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<u32> = 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
Expand Down Expand Up @@ -2699,8 +2706,6 @@ impl Sandbox {
let gather_keep_fds: Vec<i32> =
extra_fds_copy.iter().map(|&(target, _)| target).collect();

let extra_syscalls: Vec<u32> = 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) {
Expand All @@ -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,
});
}
Expand Down Expand Up @@ -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
Expand Down
67 changes: 30 additions & 37 deletions crates/sandlock-core/src/seccomp/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<i64> {
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.
Expand Down Expand Up @@ -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<i64> {
self.chains.keys().copied().find(|&nr| !filter.notifies(nr))
}

/// The handler chain for a notification, not yet started.
pub(crate) fn chain(
&self,
Expand Down Expand Up @@ -314,6 +306,7 @@ pub(crate) fn build_dispatch_table(
policy: &Arc<NotifPolicy>,
resource: &Arc<Mutex<ResourceState>>,
ctx: &Arc<SupervisorCtx>,
spec: &FilterSpec,
pending_handlers: Vec<(i64, std::sync::Arc<dyn Handler>)>,
) -> DispatchTable {
let mut table = DispatchTable::new();
Expand All @@ -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| {
Expand All @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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};
Expand Down
Loading
Loading