Skip to main content

sandbox/unix/
seccomp.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4use seccompiler::BpfProgram;
5use seccompiler::SeccompAction;
6use seccompiler::SeccompCmpArgLen;
7use seccompiler::SeccompCmpOp;
8use seccompiler::SeccompCondition;
9use seccompiler::SeccompFilter;
10use seccompiler::SeccompRule;
11use seccompiler::TargetArch;
12use std::collections::BTreeMap;
13use std::io;
14
15// ---- Local constants (not exposed by `libc`) ----
16
17/// AArch64 syscall number from Linux `asm-generic/unistd.h`, missing in musl bindings.
18#[cfg(all(target_arch = "aarch64", target_env = "musl"))]
19const SYS_KEXEC_FILE_LOAD: libc::c_long = 294;
20#[cfg(not(all(target_arch = "aarch64", target_env = "musl")))]
21const SYS_KEXEC_FILE_LOAD: libc::c_long = libc::SYS_kexec_file_load;
22
23/// `TIOCLINUX` ioctl request code. See `include/uapi/linux/tiocl.h`.
24const TIOCLINUX: u64 = 0x541C;
25
26/// `PR_SET_MM` prctl operation. See `include/uapi/linux/prctl.h`.
27const PR_SET_MM: u64 = 35;
28
29/// The individual `CLONE_NEW*` namespace-creation bits denied by the filter.
30/// The denylist filter can't express "any bit in a mask is
31/// set" with a single masked-equality condition, so it denies `clone` with one
32/// rule per bit (any match ⇒ deny). See [`clone_deny_rules`].
33const CLONE_NEW_BITS: [u64; 7] = [
34    libc::CLONE_NEWNS as u64,
35    libc::CLONE_NEWCGROUP as u64,
36    libc::CLONE_NEWUTS as u64,
37    libc::CLONE_NEWIPC as u64,
38    libc::CLONE_NEWUSER as u64,
39    libc::CLONE_NEWPID as u64,
40    libc::CLONE_NEWNET as u64,
41];
42
43/// Resolve the mandatory syscall policy into architecture-native numbers.
44///
45/// `clone3` is mandatory but deliberately omitted here because
46/// [`build_clone3_enosys_filter`] must return `ENOSYS` rather than the normal
47/// deny action so libc can fall back to the argument-filtered `clone`.
48pub fn mandatory_deny_syscall_nrs() -> io::Result<Vec<i64>> {
49    crate::platform_syscall_denylist()
50        .filter(|entry| entry.enforcement == crate::Enforcement::Mandatory)
51        .filter(|entry| entry.name != "clone3")
52        .map(|entry| {
53            nr_for_name(entry.name).ok_or_else(|| {
54                io::Error::other(format!(
55                    "mandatory syscall policy does not resolve on this architecture: {:?}",
56                    entry.name
57                ))
58            })
59        })
60        .collect()
61}
62
63/// Build the `clone3`-to-`ENOSYS` overlay filter.
64///
65/// `clone3` takes a pointer to `struct clone_args`, so its flags can't
66/// be inspected by seccomp at the argument level. Returning `ENOSYS`
67/// (rather than the default `EPERM`) lets glibc/musl's `pthread_create`
68/// treat `clone3` as unsupported and fall back to `clone`, which the
69/// main baseline filter requires `CLONE_THREAD` and rejects `CLONE_NEW*`
70/// bits. The `ENOSYS` fallback mirrors Docker's default profile.
71///
72/// The filter's `mismatch_action` is `Allow` so it doesn't affect any
73/// syscall other than `clone3`; the main baseline filter's decisions
74/// stand for everything else, and Linux seccomp uses the most
75/// restrictive action across all installed filters.
76pub fn build_clone3_enosys_filter() -> io::Result<BpfProgram> {
77    let arch = target_arch()?;
78
79    let mut rules: BTreeMap<i64, Vec<SeccompRule>> = BTreeMap::new();
80    // Match any invocation of clone3 — use MaskedEq(0) which reduces
81    // to `(arg0 & 0) == 0` and is therefore always true.
82    let always_match = SeccompRule::new(vec![
83        SeccompCondition::new(0, SeccompCmpArgLen::Qword, SeccompCmpOp::MaskedEq(0), 0)
84            .map_err(|e| io::Error::other(format!("seccomp condition: {e}")))?,
85    ])
86    .map_err(|e| io::Error::other(format!("seccomp rule: {e}")))?;
87    rules.insert(libc::SYS_clone3, vec![always_match]);
88
89    finalize_filter(
90        rules,
91        SeccompAction::Allow,
92        SeccompAction::Errno(libc::ENOSYS as u32),
93        arch,
94    )
95}
96
97/// Apply a pre-built BPF filter to all threads in the process using TSYNC.
98///
99/// Synchronization failures are errors; never fall back to thread-local
100/// enforcement.
101pub fn apply_filter_all_threads(bpf: &BpfProgram) -> io::Result<()> {
102    seccompiler::apply_filter_all_threads(bpf)
103        .map_err(|e| io::Error::other(format!("seccomp TSYNC apply failed: {e}")))
104}
105
106fn target_arch() -> io::Result<TargetArch> {
107    std::env::consts::ARCH
108        .try_into()
109        .map_err(|e| io::Error::other(format!("unsupported arch for seccomp: {e:?}")))
110}
111
112/// The minimal syscalls a process needs to unwind and exit. In the denylist
113/// model these are always allowed (they are never on the deny list); this set
114/// exists so [`apply_denylist`] can reject any attempt to *additionally* deny
115/// one of them, which would trap the worker with no way to exit.
116fn survival_syscall_nrs() -> [i64; 4] {
117    [
118        libc::SYS_exit,
119        libc::SYS_exit_group,
120        libc::SYS_rt_sigreturn,
121        libc::SYS_restart_syscall,
122    ]
123}
124
125/// Resolve a syscall *name* — as written in a profile's
126/// [`Syscalls::Deny`](crate::Syscalls::Deny) list — to its
127/// architecture-native syscall number.
128///
129/// Returns `None` for any name this crate does not recognize. Callers **must**
130/// treat an unknown name as a hard error rather than silently dropping it: a
131/// dropped deny entry makes the installed filter *less* restrictive than the
132/// author intended, silently leaving a syscall reachable.
133///
134/// The recognized set is intentionally limited to syscalls that exist on every
135/// Linux architecture this project targets, expressed in their modern spelling
136/// (`openat` not `open`, `ppoll` not `poll`, `dup3` not `dup2`, `newfstatat`
137/// not `stat`). Legacy aliases can be added behind an architecture `cfg` when a
138/// worker genuinely needs them.
139pub fn nr_for_name(name: &str) -> Option<i64> {
140    let nr = match name {
141        // Process lifecycle
142        "exit" => libc::SYS_exit,
143        "exit_group" => libc::SYS_exit_group,
144        "rt_sigreturn" => libc::SYS_rt_sigreturn,
145        "rt_sigaction" => libc::SYS_rt_sigaction,
146        "rt_sigprocmask" => libc::SYS_rt_sigprocmask,
147        "restart_syscall" => libc::SYS_restart_syscall,
148        "sigaltstack" => libc::SYS_sigaltstack,
149        "execve" => libc::SYS_execve,
150        "execveat" => libc::SYS_execveat,
151        "wait4" => libc::SYS_wait4,
152        "kill" => libc::SYS_kill,
153        "tkill" => libc::SYS_tkill,
154        "tgkill" => libc::SYS_tgkill,
155        // Memory management
156        "brk" => libc::SYS_brk,
157        "mmap" => libc::SYS_mmap,
158        "munmap" => libc::SYS_munmap,
159        "mprotect" => libc::SYS_mprotect,
160        "madvise" => libc::SYS_madvise,
161        "mremap" => libc::SYS_mremap,
162        // File I/O
163        "read" => libc::SYS_read,
164        "readv" => libc::SYS_readv,
165        "pread64" => libc::SYS_pread64,
166        "write" => libc::SYS_write,
167        "writev" => libc::SYS_writev,
168        "pwrite64" => libc::SYS_pwrite64,
169        "close" => libc::SYS_close,
170        "openat" => libc::SYS_openat,
171        "fstat" => libc::SYS_fstat,
172        "newfstatat" => libc::SYS_newfstatat,
173        "statx" => libc::SYS_statx,
174        "lseek" => libc::SYS_lseek,
175        "ioctl" => libc::SYS_ioctl,
176        "fcntl" => libc::SYS_fcntl,
177        "dup" => libc::SYS_dup,
178        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
179        "dup2" => libc::SYS_dup2,
180        "dup3" => libc::SYS_dup3,
181        "pipe2" => libc::SYS_pipe2,
182        "mkdirat" => libc::SYS_mkdirat,
183        "unlinkat" => libc::SYS_unlinkat,
184        "renameat2" => libc::SYS_renameat2,
185        // Event polling
186        "epoll_create1" => libc::SYS_epoll_create1,
187        "epoll_ctl" => libc::SYS_epoll_ctl,
188        "epoll_pwait" => libc::SYS_epoll_pwait,
189        "ppoll" => libc::SYS_ppoll,
190        "pselect6" => libc::SYS_pselect6,
191        // Directory / metadata
192        "getdents64" => libc::SYS_getdents64,
193        "getcwd" => libc::SYS_getcwd,
194        "readlinkat" => libc::SYS_readlinkat,
195        "faccessat" => libc::SYS_faccessat,
196        "faccessat2" => libc::SYS_faccessat2,
197        // Futex / threading
198        "futex" => libc::SYS_futex,
199        "set_robust_list" => libc::SYS_set_robust_list,
200        "get_robust_list" => libc::SYS_get_robust_list,
201        "clone" => libc::SYS_clone,
202        "sched_yield" => libc::SYS_sched_yield,
203        "sched_getaffinity" => libc::SYS_sched_getaffinity,
204        "set_tid_address" => libc::SYS_set_tid_address,
205        "rseq" => libc::SYS_rseq,
206        // Time
207        "clock_gettime" => libc::SYS_clock_gettime,
208        "clock_getres" => libc::SYS_clock_getres,
209        "clock_nanosleep" => libc::SYS_clock_nanosleep,
210        "nanosleep" => libc::SYS_nanosleep,
211        "gettimeofday" => libc::SYS_gettimeofday,
212        // Identity (read-only)
213        "getuid" => libc::SYS_getuid,
214        "geteuid" => libc::SYS_geteuid,
215        "getgid" => libc::SYS_getgid,
216        "getegid" => libc::SYS_getegid,
217        "getpid" => libc::SYS_getpid,
218        "gettid" => libc::SYS_gettid,
219        "getppid" => libc::SYS_getppid,
220        // Misc
221        "getrandom" => libc::SYS_getrandom,
222        "prctl" => libc::SYS_prctl,
223        // Network
224        "socket" => libc::SYS_socket,
225        "socketpair" => libc::SYS_socketpair,
226        "connect" => libc::SYS_connect,
227        "bind" => libc::SYS_bind,
228        "listen" => libc::SYS_listen,
229        "accept4" => libc::SYS_accept4,
230        "getsockname" => libc::SYS_getsockname,
231        "getpeername" => libc::SYS_getpeername,
232        "sendto" => libc::SYS_sendto,
233        "recvfrom" => libc::SYS_recvfrom,
234        "sendmsg" => libc::SYS_sendmsg,
235        "recvmsg" => libc::SYS_recvmsg,
236        "shutdown" => libc::SYS_shutdown,
237        "setsockopt" => libc::SYS_setsockopt,
238        "getsockopt" => libc::SYS_getsockopt,
239        // Configurable sandbox denylist
240        "acct" => libc::SYS_acct,
241        "add_key" => libc::SYS_add_key,
242        "adjtimex" => libc::SYS_adjtimex,
243        "bpf" => libc::SYS_bpf,
244        "capset" => libc::SYS_capset,
245        "chroot" => libc::SYS_chroot,
246        "clone3" => libc::SYS_clone3,
247        "clock_adjtime" => libc::SYS_clock_adjtime,
248        "clock_settime" => libc::SYS_clock_settime,
249        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
250        #[expect(deprecated, reason = "Recognize obsolete syscalls in deny policies.")]
251        "create_module" => libc::SYS_create_module,
252        "delete_module" => libc::SYS_delete_module,
253        "fanotify_init" => libc::SYS_fanotify_init,
254        "finit_module" => libc::SYS_finit_module,
255        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
256        "fork" => libc::SYS_fork,
257        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
258        "vfork" => libc::SYS_vfork,
259        "fsconfig" => libc::SYS_fsconfig,
260        "fsmount" => libc::SYS_fsmount,
261        "fsopen" => libc::SYS_fsopen,
262        "fspick" => libc::SYS_fspick,
263        "init_module" => libc::SYS_init_module,
264        "io_uring_enter" => libc::SYS_io_uring_enter,
265        "io_uring_register" => libc::SYS_io_uring_register,
266        "io_uring_setup" => libc::SYS_io_uring_setup,
267        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
268        "ioperm" => libc::SYS_ioperm,
269        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
270        "iopl" => libc::SYS_iopl,
271        "ioprio_set" => libc::SYS_ioprio_set,
272        "kcmp" => libc::SYS_kcmp,
273        "kexec_file_load" => SYS_KEXEC_FILE_LOAD,
274        "kexec_load" => libc::SYS_kexec_load,
275        "keyctl" => libc::SYS_keyctl,
276        "mbind" => libc::SYS_mbind,
277        "migrate_pages" => libc::SYS_migrate_pages,
278        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
279        "modify_ldt" => libc::SYS_modify_ldt,
280        "mount" => libc::SYS_mount,
281        "mount_setattr" => libc::SYS_mount_setattr,
282        "move_mount" => libc::SYS_move_mount,
283        "move_pages" => libc::SYS_move_pages,
284        "name_to_handle_at" => libc::SYS_name_to_handle_at,
285        "open_by_handle_at" => libc::SYS_open_by_handle_at,
286        "open_tree" => libc::SYS_open_tree,
287        "perf_event_open" => libc::SYS_perf_event_open,
288        "personality" => libc::SYS_personality,
289        "pidfd_getfd" => libc::SYS_pidfd_getfd,
290        "pivot_root" => libc::SYS_pivot_root,
291        "process_vm_readv" => libc::SYS_process_vm_readv,
292        "process_vm_writev" => libc::SYS_process_vm_writev,
293        "ptrace" => libc::SYS_ptrace,
294        "quotactl" => libc::SYS_quotactl,
295        "reboot" => libc::SYS_reboot,
296        "request_key" => libc::SYS_request_key,
297        "set_mempolicy" => libc::SYS_set_mempolicy,
298        "setdomainname" => libc::SYS_setdomainname,
299        "sethostname" => libc::SYS_sethostname,
300        "setns" => libc::SYS_setns,
301        "settimeofday" => libc::SYS_settimeofday,
302        "swapoff" => libc::SYS_swapoff,
303        "swapon" => libc::SYS_swapon,
304        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
305        "sysfs" => libc::SYS_sysfs,
306        "syslog" => libc::SYS_syslog,
307        "umount2" => libc::SYS_umount2,
308        "unshare" => libc::SYS_unshare,
309        "userfaultfd" => libc::SYS_userfaultfd,
310        "vhangup" => libc::SYS_vhangup,
311        "vmsplice" => libc::SYS_vmsplice,
312        "waitid" => libc::SYS_waitid,
313        // Architecture-specific: `arch_prctl` is x86-only.
314        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
315        "arch_prctl" => libc::SYS_arch_prctl,
316        _ => return None,
317    };
318    Some(nr)
319}
320
321/// Build a default-allow denylist filter that blocks the
322/// [mandatory-deny list](mandatory_deny_syscall_nrs) plus `extra_denied_nrs`
323/// with `deny_action`, and installs the argument-level guards on `ioctl`,
324/// `clone`, `prctl`, and `socket`.
325///
326/// On x86-64, only the native 64-bit syscall ABI is supported: seccompiler
327/// kills i386 calls, and x32 calls receive `deny_action`.
328///
329/// The filter's `mismatch_action` is `Allow`: any syscall not named here (and
330/// not caught by an argument-level guard) passes through. The complementary
331/// `clone3`-to-`ENOSYS` overlay is installed separately by [`apply_denylist`].
332pub fn build_denylist_filter(
333    extra_denied_nrs: &[i64],
334    deny_action: SeccompAction,
335) -> io::Result<BpfProgram> {
336    let arch = target_arch()?;
337    let mut rules: BTreeMap<i64, Vec<SeccompRule>> = BTreeMap::new();
338
339    // Argument-level guards first: block only the dangerous cases and leave the
340    // rest of each syscall allowed by the default `mismatch_action`.
341    rules.insert(libc::SYS_ioctl, ioctl_deny_rules()?);
342    rules.insert(libc::SYS_clone, clone_deny_rules()?);
343    rules.insert(libc::SYS_prctl, prctl_deny_rules()?);
344    rules.insert(libc::SYS_socket, socket_deny_rules()?);
345
346    // Blanket-deny the baseline set. It never overlaps the argument-guarded
347    // syscalls above, so `or_default` leaves their rules intact.
348    for nr in mandatory_deny_syscall_nrs()? {
349        rules.entry(nr).or_default();
350    }
351    // Profile-specified extras are unconditional denies. An extra that names an
352    // argument-guarded syscall (e.g. `socket`) overrides its guard with a full
353    // deny — stricter, which is exactly what an explicit request means.
354    for nr in extra_denied_nrs.iter().copied() {
355        rules.insert(nr, Vec::new());
356    }
357
358    let bpf = finalize_filter(rules, SeccompAction::Allow, deny_action.clone(), arch)?;
359    #[cfg(target_arch = "x86_64")]
360    let bpf = {
361        // x32 shares x86-64's audit architecture, but sets bit 30 in the
362        // syscall number. Other architectures must still reach seccompiler's
363        // architecture check, regardless of their syscall number.
364        const AUDIT_ARCH_X86_64: u32 = 62 | 0x8000_0000 | 0x4000_0000;
365        const X32_BIT: u32 = 0x4000_0000;
366        let prefix = [
367            seccompiler::sock_filter {
368                code: (libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as u16,
369                jt: 0,
370                jf: 0,
371                k: 4,
372            },
373            seccompiler::sock_filter {
374                code: (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16,
375                jt: 0,
376                jf: 3,
377                k: AUDIT_ARCH_X86_64,
378            },
379            seccompiler::sock_filter {
380                code: (libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as u16,
381                jt: 0,
382                jf: 0,
383                k: 0,
384            },
385            seccompiler::sock_filter {
386                code: (libc::BPF_JMP | libc::BPF_JSET | libc::BPF_K) as u16,
387                jt: 0,
388                jf: 1,
389                k: X32_BIT,
390            },
391            seccompiler::sock_filter {
392                code: (libc::BPF_RET | libc::BPF_K) as u16,
393                jt: 0,
394                jf: 0,
395                k: deny_action.into(),
396            },
397        ];
398        // Preserve seccompiler's length limit after adding the ABI check.
399        if bpf.len() + prefix.len() >= 4096 {
400            return Err(io::Error::other(
401                "seccomp BPF filter including x32 guard is too large",
402            ));
403        }
404        prefix.into_iter().chain(bpf).collect()
405    };
406    Ok(bpf)
407}
408
409/// Resolve `extra_deny_names` into syscall numbers, build the denylist filter
410/// (baseline + extras + argument-level guards), and apply it to all threads
411/// along with the `clone3`-to-`ENOSYS` overlay, using TSYNC for both filters.
412///
413/// Every name must resolve via [`nr_for_name`]; an unknown name is a hard
414/// error rather than a silent omission. A name on the
415/// [survival set](survival_syscall_nrs) is rejected, since blanket-denying a
416/// syscall the process needs to unwind and exit would trap it.
417///
418/// Because seccomp filters stack and the kernel takes the most restrictive
419/// verdict, this can be called both from `apply` (the profile's opt-in filter)
420/// and from `tighten` (an additional stacked filter that denies still more).
421pub fn apply_denylist(extra_deny_names: &[&str], deny_action: SeccompAction) -> io::Result<()> {
422    let survival = survival_syscall_nrs();
423    let mut extra = Vec::with_capacity(extra_deny_names.len());
424    for name in extra_deny_names {
425        // clone3 is always handled by the ENOSYS overlay below. Adding it to
426        // the normal filter would prevent libc's fallback to clone.
427        if *name == "clone3" {
428            continue;
429        }
430        let nr = nr_for_name(name).ok_or_else(|| {
431            io::Error::other(format!("unknown syscall name in denylist: {name:?}"))
432        })?;
433        if survival.contains(&nr) {
434            return Err(io::Error::other(format!(
435                "syscall {name:?} is required for a process to exit and cannot be denied"
436            )));
437        }
438        extra.push(nr);
439    }
440
441    let filter = build_denylist_filter(&extra, deny_action)?;
442    // Force clone3 to ENOSYS so the libc thread path falls back to the
443    // argument-filtered `clone`; clone3's flags live behind a pointer seccomp
444    // can't inspect.
445    let clone3 = build_clone3_enosys_filter()?;
446    // seccompiler sets no_new_privs via prctl for each installation, so install
447    // the main filter last in case the profile blanket-denies prctl.
448    apply_filter_all_threads(&clone3)?;
449    apply_filter_all_threads(&filter)
450}
451
452fn finalize_filter(
453    rules: BTreeMap<i64, Vec<SeccompRule>>,
454    mismatch_action: SeccompAction,
455    match_action: SeccompAction,
456    arch: TargetArch,
457) -> io::Result<BpfProgram> {
458    let filter = SeccompFilter::new(rules, mismatch_action, match_action, arch)
459        .map_err(|e| io::Error::other(format!("seccomp filter creation failed: {e}")))?;
460    filter
461        .try_into()
462        .map_err(|e| io::Error::other(format!("seccomp BPF compilation failed: {e}")))
463}
464
465// ---- Per-syscall argument rule builders ----
466
467/// `ioctl` — deny the `TIOCSTI` and `TIOCLINUX` request codes; every other
468/// request code falls through to the default allow.
469///
470/// Uses 32-bit (`Dword`) comparison so an attacker can't bypass by setting the
471/// upper 32 bits of arg1 (the kernel ignores them for ioctl request codes).
472/// The two codes are emitted as separate rules (rules are OR'd, so either one
473/// matching denies).
474fn ioctl_deny_rules() -> io::Result<Vec<SeccompRule>> {
475    Ok(vec![
476        SeccompRule::new(vec![
477            SeccompCondition::new(
478                1,
479                SeccompCmpArgLen::Dword,
480                SeccompCmpOp::Eq,
481                libc::TIOCSTI as _,
482            )
483            .map_err(|e| io::Error::other(format!("seccomp condition: {e}")))?,
484        ])
485        .map_err(|e| io::Error::other(format!("seccomp rule: {e}")))?,
486        SeccompRule::new(vec![
487            SeccompCondition::new(1, SeccompCmpArgLen::Dword, SeccompCmpOp::Eq, TIOCLINUX)
488                .map_err(|e| io::Error::other(format!("seccomp condition: {e}")))?,
489        ])
490        .map_err(|e| io::Error::other(format!("seccomp rule: {e}")))?,
491    ])
492}
493
494/// `clone` — require `CLONE_THREAD` and deny any `CLONE_NEW*` namespace bit
495/// in arg0. Sharing memory alone (`CLONE_VM`) does not make a child a thread.
496///
497/// seccomp can't express "any bit in a mask is set" in one condition, so this
498/// emits one rule per bit in [`CLONE_NEW_BITS`] (rules are OR'd, so any match
499/// denies), in addition to the missing-`CLONE_THREAD` rule.
500fn clone_deny_rules() -> io::Result<Vec<SeccompRule>> {
501    let mut rules = Vec::with_capacity(CLONE_NEW_BITS.len() + 1);
502    rules.push(
503        SeccompRule::new(vec![
504            SeccompCondition::new(
505                0,
506                SeccompCmpArgLen::Qword,
507                SeccompCmpOp::MaskedEq(libc::CLONE_THREAD as u64),
508                0,
509            )
510            .map_err(|e| io::Error::other(format!("seccomp condition: {e}")))?,
511        ])
512        .map_err(|e| io::Error::other(format!("seccomp rule: {e}")))?,
513    );
514    for bit in CLONE_NEW_BITS {
515        rules.push(
516            SeccompRule::new(vec![
517                SeccompCondition::new(0, SeccompCmpArgLen::Qword, SeccompCmpOp::MaskedEq(bit), bit)
518                    .map_err(|e| io::Error::other(format!("seccomp condition: {e}")))?,
519            ])
520            .map_err(|e| io::Error::other(format!("seccomp rule: {e}")))?,
521        );
522    }
523    Ok(rules)
524}
525
526/// `prctl` — deny the `PR_SET_MM` subcommand; every other subcommand falls
527/// through to the default allow.
528fn prctl_deny_rules() -> io::Result<Vec<SeccompRule>> {
529    Ok(vec![
530        SeccompRule::new(vec![
531            SeccompCondition::new(0, SeccompCmpArgLen::Dword, SeccompCmpOp::Eq, PR_SET_MM)
532                .map_err(|e| io::Error::other(format!("seccomp condition: {e}")))?,
533        ])
534        .map_err(|e| io::Error::other(format!("seccomp rule: {e}")))?,
535    ])
536}
537
538/// `socket` — deny the `AF_PACKET` address family; every other family falls
539/// through to the default allow. Stricter than Docker's default; motivated by
540/// CVE-2017-7308.
541fn socket_deny_rules() -> io::Result<Vec<SeccompRule>> {
542    Ok(vec![
543        SeccompRule::new(vec![
544            SeccompCondition::new(
545                0,
546                SeccompCmpArgLen::Dword,
547                SeccompCmpOp::Eq,
548                libc::AF_PACKET as u64,
549            )
550            .map_err(|e| io::Error::other(format!("seccomp condition: {e}")))?,
551        ])
552        .map_err(|e| io::Error::other(format!("seccomp rule: {e}")))?,
553    ])
554}
555
556#[cfg(test)]
557mod tests {
558    use super::*;
559    use test_with_tracing::test;
560
561    #[cfg(target_arch = "x86_64")]
562    #[test]
563    fn denylist_rejects_x32_syscalls() {
564        let output = std::process::Command::new(std::env::current_exe().unwrap())
565            .args([
566                "--exact",
567                "unix::seccomp::tests::helper_deny_x32",
568                "--ignored",
569                "--nocapture",
570                "--test-threads=1",
571            ])
572            .output()
573            .unwrap();
574        assert!(
575            output.status.success(),
576            "x32 denial helper failed ({}):\nstdout: {}\nstderr: {}",
577            output.status,
578            String::from_utf8_lossy(&output.stdout),
579            String::from_utf8_lossy(&output.stderr),
580        );
581    }
582
583    #[cfg(target_arch = "x86_64")]
584    #[test]
585    #[ignore]
586    fn helper_deny_x32() {
587        const X32_BIT: libc::c_long = 0x4000_0000;
588        let x32_getpid = X32_BIT | libc::SYS_getpid;
589        // SAFETY: getpid takes no arguments, including under the x32 ABI.
590        let pid = unsafe { libc::syscall(libc::SYS_getpid) };
591        assert!(pid > 0);
592        // Distinguish our filter from kernels without x32 support or outer
593        // filters returning ENOSYS/EPERM.
594        // SAFETY: As above.
595        let unfiltered = unsafe { libc::syscall(x32_getpid) };
596        if unfiltered == -1 {
597            assert_ne!(
598                io::Error::last_os_error().raw_os_error(),
599                Some(libc::EACCES)
600            );
601        }
602
603        apply_denylist(&[], SeccompAction::Errno(libc::EACCES as u32)).unwrap();
604
605        // SAFETY: These read-only queries take no arguments.
606        assert_eq!(unsafe { libc::syscall(libc::SYS_getpid) }, pid);
607        // SAFETY: As above.
608        assert_eq!(unsafe { libc::syscall(x32_getpid) }, -1);
609        assert_eq!(
610            io::Error::last_os_error().raw_os_error(),
611            Some(libc::EACCES)
612        );
613
614        // The main filter must reject x32 even for the clone3 overlay.
615        // SAFETY: Null arguments cannot create a child if either filter regresses.
616        let result =
617            unsafe { libc::syscall(X32_BIT | libc::SYS_clone3, std::ptr::null::<u8>(), 0usize) };
618        assert_eq!(result, -1);
619        assert_eq!(
620            io::Error::last_os_error().raw_os_error(),
621            Some(libc::EACCES)
622        );
623    }
624
625    #[cfg(target_arch = "x86_64")]
626    #[test]
627    fn denylist_kills_compat_abis() {
628        use std::os::unix::process::ExitStatusExt;
629
630        for abi in ["i386", "x32"] {
631            let output = std::process::Command::new(std::env::current_exe().unwrap())
632                .args([
633                    "--exact",
634                    "unix::seccomp::tests::helper_kill_compat_abi",
635                    "--ignored",
636                    "--nocapture",
637                    "--test-threads=1",
638                ])
639                .env("SANDBOX_TEST_ABI", abi)
640                .output()
641                .unwrap();
642            assert_eq!(
643                output.status.signal(),
644                Some(libc::SIGSYS),
645                "{abi} helper failed ({}):\nstdout: {}\nstderr: {}",
646                output.status,
647                String::from_utf8_lossy(&output.stdout),
648                String::from_utf8_lossy(&output.stderr),
649            );
650        }
651    }
652
653    #[cfg(target_arch = "x86_64")]
654    #[test]
655    #[ignore]
656    fn helper_kill_compat_abi() {
657        let abi = std::env::var("SANDBOX_TEST_ABI").unwrap();
658        apply_denylist(&[], SeccompAction::KillProcess).unwrap();
659        match abi.as_str() {
660            "i386" => {
661                // SAFETY: i386 getpid (20) takes no arguments. Conservatively
662                // clobber caller-saved registers if the syscall returns.
663                unsafe {
664                    std::arch::asm!(
665                        "int 0x80",
666                        in("eax") 20u32,
667                        clobber_abi("C"),
668                        options(nostack),
669                    );
670                }
671            }
672            "x32" => {
673                // SAFETY: x32 getpid takes no arguments.
674                unsafe { libc::syscall(0x4000_0000 | libc::SYS_getpid) };
675            }
676            _ => panic!("unknown test ABI: {abi}"),
677        }
678        panic!("{abi} syscall was not killed");
679    }
680
681    #[test]
682    fn worker_profiles_preserve_numa_binding_policy() {
683        let output = std::process::Command::new(std::env::current_exe().unwrap())
684            .args([
685                "--exact",
686                "unix::seccomp::tests::helper_worker_numa_binding",
687                "--ignored",
688                "--nocapture",
689                "--test-threads=1",
690            ])
691            .output()
692            .unwrap();
693        assert!(
694            output.status.success(),
695            "NUMA binding helper failed ({}):\nstdout: {}\nstderr: {}",
696            output.status,
697            String::from_utf8_lossy(&output.stdout),
698            String::from_utf8_lossy(&output.stderr),
699        );
700    }
701
702    #[test]
703    #[ignore]
704    fn helper_worker_numa_binding() {
705        let status = std::fs::read_to_string("/proc/self/status").unwrap();
706        let node: usize = status
707            .lines()
708            .find_map(|line| line.strip_prefix("Mems_allowed_list:"))
709            .unwrap_or("0")
710            .trim()
711            .split([',', '-'])
712            .next()
713            .unwrap()
714            .parse()
715            .unwrap();
716        let maxnode = node + 2;
717        let word_bits = libc::c_ulong::BITS as usize;
718        let mut nodemask = vec![0 as libc::c_ulong; maxnode.div_ceil(word_bits)];
719        nodemask[node / word_bits] = 1 << (node % word_bits);
720
721        const LEN: usize = 4096;
722        // SAFETY: An anonymous mapping with no requested address or backing fd.
723        let mapping = unsafe {
724            libc::mmap(
725                std::ptr::null_mut(),
726                LEN,
727                libc::PROT_READ | libc::PROT_WRITE,
728                libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
729                -1,
730                0,
731            )
732        };
733        assert_ne!(mapping, libc::MAP_FAILED);
734        let bind = || {
735            // SAFETY: The mapping and nodemask remain valid throughout the call.
736            let result = unsafe {
737                libc::syscall(
738                    libc::SYS_mbind,
739                    mapping,
740                    LEN,
741                    libc::MPOL_BIND,
742                    nodemask.as_ptr(),
743                    maxnode,
744                    0,
745                )
746            };
747            if result == 0 {
748                Ok(())
749            } else {
750                Err(io::Error::last_os_error().raw_os_error().unwrap())
751            }
752        };
753
754        caps::clear(None, caps::CapSet::Effective).unwrap();
755        caps::clear(None, caps::CapSet::Permitted).unwrap();
756        let unfiltered = bind();
757        // Use a distinct errno to distinguish our filter from host restrictions
758        // or kernels without NUMA support.
759        assert_ne!(unfiltered, Err(libc::EACCES));
760        crate::unix::hardening::set_no_new_privs().unwrap();
761        for (profile, expected) in [
762            (crate::profiles::vm_worker().build(), unfiltered),
763            (crate::profiles::tpm_worker().build(), Err(libc::EACCES)),
764        ] {
765            let crate::Syscalls::Deny(names) = &profile.inner.syscalls else {
766                panic!("worker must use syscall filtering");
767            };
768            let names = names.iter().map(String::as_str).collect::<Vec<_>>();
769            apply_denylist(&names, SeccompAction::Errno(libc::EACCES as u32)).unwrap();
770            assert_eq!(bind(), expected, "NUMA policy for {}", profile.name());
771        }
772        // SAFETY: Release the mapping obtained above; it is no longer used.
773        assert_eq!(unsafe { libc::munmap(mapping, LEN) }, 0);
774    }
775
776    #[test]
777    fn denylist_can_block_prctl_during_initial_installation() {
778        let output = std::process::Command::new(std::env::current_exe().unwrap())
779            .args([
780                "--exact",
781                "unix::seccomp::tests::helper_deny_prctl",
782                "--ignored",
783                "--nocapture",
784                "--test-threads=1",
785            ])
786            .output()
787            .unwrap();
788        assert!(
789            output.status.success(),
790            "prctl denial helper failed ({}):\nstdout: {}\nstderr: {}",
791            output.status,
792            String::from_utf8_lossy(&output.stdout),
793            String::from_utf8_lossy(&output.stderr),
794        );
795    }
796
797    #[test]
798    #[ignore]
799    fn helper_deny_prctl() {
800        apply_denylist(&["prctl"], SeccompAction::Errno(libc::EACCES as u32)).unwrap();
801
802        // SAFETY: This read-only query takes no pointer arguments.
803        let result = unsafe { libc::prctl(libc::PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0) };
804        assert_eq!(result, -1);
805        assert_eq!(
806            io::Error::last_os_error().raw_os_error(),
807            Some(libc::EACCES)
808        );
809
810        // SAFETY: Null arguments cannot create a child if the overlay regresses.
811        let result = unsafe { libc::syscall(libc::SYS_clone3, std::ptr::null::<u8>(), 0usize) };
812        assert_eq!(result, -1);
813        assert_eq!(
814            io::Error::last_os_error().raw_os_error(),
815            Some(libc::ENOSYS)
816        );
817    }
818
819    #[test]
820    fn mandatory_filter_denies_executable_replacement() {
821        let output = std::process::Command::new(std::env::current_exe().unwrap())
822            .args([
823                "--exact",
824                "unix::seccomp::tests::helper_deny_executable_replacement",
825                "--ignored",
826                "--nocapture",
827                "--test-threads=1",
828            ])
829            .output()
830            .unwrap();
831        assert!(
832            output.status.success(),
833            "execution denial helper failed ({}):\nstdout: {}\nstderr: {}",
834            output.status,
835            String::from_utf8_lossy(&output.stdout),
836            String::from_utf8_lossy(&output.stderr),
837        );
838    }
839
840    #[test]
841    #[ignore]
842    fn helper_deny_executable_replacement() {
843        crate::unix::hardening::set_no_new_privs().unwrap();
844        apply_denylist(&[], SeccompAction::Errno(libc::EPERM as u32)).unwrap();
845
846        // Empty paths cannot execute anything even if the filter regresses.
847        // SAFETY: The path is NUL-terminated; null argument arrays are accepted
848        // by Linux.
849        let result = unsafe { libc::execve(c"".as_ptr(), std::ptr::null(), std::ptr::null()) };
850        assert_eq!(result, -1);
851        assert_eq!(io::Error::last_os_error().raw_os_error(), Some(libc::EPERM));
852
853        // SAFETY: As above. AT_EMPTY_PATH exercises execution via a file
854        // descriptor; -1 ensures no executable is available without the filter.
855        let result = unsafe {
856            libc::syscall(
857                libc::SYS_execveat,
858                -1,
859                c"".as_ptr(),
860                std::ptr::null::<*const libc::c_char>(),
861                std::ptr::null::<*const libc::c_char>(),
862                libc::AT_EMPTY_PATH,
863            )
864        };
865        assert_eq!(result, -1);
866        assert_eq!(io::Error::last_os_error().raw_os_error(), Some(libc::EPERM));
867    }
868
869    #[test]
870    fn mandatory_filter_denies_process_creation_but_allows_threads() {
871        let output = std::process::Command::new(std::env::current_exe().unwrap())
872            .args([
873                "--exact",
874                "unix::seccomp::tests::helper_deny_process_creation",
875                "--ignored",
876                "--nocapture",
877                "--test-threads=1",
878            ])
879            .output()
880            .unwrap();
881        assert!(
882            output.status.success(),
883            "process creation helper failed ({}):\nstdout: {}\nstderr: {}",
884            output.status,
885            String::from_utf8_lossy(&output.stdout),
886            String::from_utf8_lossy(&output.stderr),
887        );
888    }
889
890    #[test]
891    #[ignore]
892    fn helper_deny_process_creation() {
893        crate::unix::hardening::set_no_new_privs().unwrap();
894
895        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
896        {
897            // Keep raw fork/vfork probes safe even if the policy regresses.
898            // The newer policy's EACCES must override this older ENOSYS.
899            let guard = finalize_filter(
900                BTreeMap::from([(libc::SYS_fork, Vec::new()), (libc::SYS_vfork, Vec::new())]),
901                SeccompAction::Allow,
902                SeccompAction::Errno(libc::ENOSYS as u32),
903                target_arch().unwrap(),
904            )
905            .unwrap();
906            apply_filter_all_threads(&guard).unwrap();
907        }
908
909        apply_denylist(&[], SeccompAction::Errno(libc::EACCES as u32)).unwrap();
910        assert_eq!(std::thread::spawn(|| 42).join().unwrap(), 42);
911
912        // SAFETY: Null arguments cannot create a child if the overlay regresses.
913        let result = unsafe { libc::syscall(libc::SYS_clone3, std::ptr::null::<u8>(), 0usize) };
914        assert_eq!(result, -1);
915        assert_eq!(
916            io::Error::last_os_error().raw_os_error(),
917            Some(libc::ENOSYS)
918        );
919
920        extern "C" fn child(_: *mut libc::c_void) -> libc::c_int {
921            0
922        }
923
924        let mut stack = vec![0u128; 4096];
925        // SAFETY: The aligned buffer stays alive until each child is reaped.
926        // clone's stack grows down from the end of the allocation.
927        let stack_top = unsafe { stack.as_mut_ptr().add(stack.len()).cast() };
928        for flags in [
929            libc::SIGCHLD,
930            libc::CLONE_VM | libc::SIGCHLD,
931            libc::CLONE_VM | libc::CLONE_SIGHAND | libc::SIGCHLD,
932            libc::CLONE_VM | libc::CLONE_VFORK | libc::SIGCHLD,
933        ] {
934            // SAFETY: The callback needs no Rust runtime or TLS and returns
935            // directly to libc's child exit path, using its own valid stack.
936            let result = unsafe { libc::clone(child, stack_top, flags, std::ptr::null_mut()) };
937            let error = io::Error::last_os_error().raw_os_error();
938            if result > 0 {
939                assert_eq!(
940                    // SAFETY: Reap only the child just created by this helper.
941                    unsafe { libc::waitpid(result, std::ptr::null_mut(), 0) },
942                    result
943                );
944            }
945            assert_eq!(result, -1, "process-forming clone allowed: {flags:#x}");
946            assert_eq!(error, Some(libc::EACCES), "clone flags: {flags:#x}");
947        }
948
949        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
950        for nr in [libc::SYS_fork, libc::SYS_vfork] {
951            // SAFETY: The guard above prevents child creation even if the
952            // main policy omits this syscall.
953            assert_eq!(unsafe { libc::syscall(nr) }, -1);
954            assert_eq!(
955                io::Error::last_os_error().raw_os_error(),
956                Some(libc::EACCES)
957            );
958        }
959    }
960
961    #[test]
962    fn mandatory_deny_disjoint_from_survival() {
963        // The baseline denylist must be non-empty and must never contain a
964        // survival syscall — `apply_denylist` relies on that invariant so a
965        // profile can't blanket-deny a syscall the worker needs to exit.
966        let denied = mandatory_deny_syscall_nrs().expect("mandatory policy must resolve");
967        assert!(!denied.is_empty());
968        for nr in survival_syscall_nrs() {
969            assert!(
970                !denied.contains(&nr),
971                "survival syscall {nr} must not be on the mandatory-deny list",
972            );
973        }
974    }
975
976    #[test]
977    fn clone3_enosys_filter_builds() {
978        let bpf = build_clone3_enosys_filter().expect("should build clone3 ENOSYS filter");
979        assert!(!bpf.is_empty());
980    }
981
982    #[test]
983    fn configured_syscall_policy_is_unique_and_resolvable() {
984        let mut names = std::collections::BTreeSet::new();
985        for entry in crate::platform_syscall_denylist() {
986            assert!(
987                names.insert(entry.name),
988                "duplicate policy for {}",
989                entry.name
990            );
991            assert!(
992                nr_for_name(entry.name).is_some(),
993                "policy syscall does not resolve: {}",
994                entry.name
995            );
996        }
997    }
998
999    #[test]
1000    fn optional_syscalls_are_not_in_mandatory_baseline() {
1001        let mandatory = mandatory_deny_syscall_nrs().expect("mandatory policy must resolve");
1002        for entry in crate::platform_syscall_denylist()
1003            .filter(|entry| entry.enforcement == crate::Enforcement::Optional)
1004        {
1005            let nr = nr_for_name(entry.name).expect("optional policy must resolve");
1006            assert!(
1007                !mandatory.contains(&nr),
1008                "optional syscall is mandatory: {}",
1009                entry.name
1010            );
1011        }
1012    }
1013
1014    #[test]
1015    fn argument_filter_rules_build() {
1016        // Confirms all per-syscall arg-filter helpers produce valid
1017        // conditions. Runtime enforcement is exercised by higher-level
1018        // sandbox integration tests in a subprocess.
1019        ioctl_deny_rules().expect("ioctl rules");
1020        clone_deny_rules().expect("clone rules");
1021        prctl_deny_rules().expect("prctl rules");
1022        socket_deny_rules().expect("socket rules");
1023    }
1024
1025    #[test]
1026    fn nr_for_name_resolves_known_and_rejects_unknown() {
1027        assert_eq!(nr_for_name("read"), Some(libc::SYS_read));
1028        assert_eq!(nr_for_name("openat"), Some(libc::SYS_openat));
1029        assert_eq!(nr_for_name("kill"), Some(libc::SYS_kill));
1030        assert_eq!(nr_for_name("tkill"), Some(libc::SYS_tkill));
1031        assert_eq!(nr_for_name("tgkill"), Some(libc::SYS_tgkill));
1032        assert_eq!(nr_for_name("exit_group"), Some(libc::SYS_exit_group));
1033        assert_eq!(nr_for_name("definitely_not_a_syscall"), None);
1034        // Legacy spellings are intentionally not recognized.
1035        assert_eq!(nr_for_name("open"), None);
1036        assert_eq!(nr_for_name("poll"), None);
1037    }
1038
1039    #[test]
1040    fn denylist_filter_builds_with_extras() {
1041        let nrs = &[libc::SYS_execve, libc::SYS_connect];
1042        let bpf = build_denylist_filter(nrs, SeccompAction::Errno(libc::EPERM as u32))
1043            .expect("should build denylist filter");
1044        assert!(!bpf.is_empty());
1045    }
1046}