1use 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#[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
23const TIOCLINUX: u64 = 0x541C;
25
26const PR_SET_MM: u64 = 35;
28
29const 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
43pub 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
63pub 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 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
97pub 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
112fn 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
125pub fn nr_for_name(name: &str) -> Option<i64> {
140 let nr = match name {
141 "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 "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 "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 "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 "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" => 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 "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 "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 "getrandom" => libc::SYS_getrandom,
222 "prctl" => libc::SYS_prctl,
223 "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 "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 #[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
321pub 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 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 for nr in mandatory_deny_syscall_nrs()? {
349 rules.entry(nr).or_default();
350 }
351 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 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 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
409pub 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 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 let clone3 = build_clone3_enosys_filter()?;
446 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
465fn 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
494fn 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
526fn 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
538fn 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 let pid = unsafe { libc::syscall(libc::SYS_getpid) };
591 assert!(pid > 0);
592 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 assert_eq!(unsafe { libc::syscall(libc::SYS_getpid) }, pid);
607 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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}