1use std::ffi::CString;
5use std::io;
6use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
7
8use crate::policy::{FsIsolation, Policy};
9use crate::seccomp::bpf::{self, stmt, jump};
10use crate::sys::structs::{
11 AF_INET, AF_INET6, AF_NETLINK,
12 BPF_ABS, BPF_ALU, BPF_AND, BPF_JEQ, BPF_JSET, BPF_JMP, BPF_K, BPF_LD, BPF_RET, BPF_W,
13 CLONE_NS_FLAGS, DEFAULT_DENY_SYSCALLS, EPERM, NETLINK_SOCK_DIAG, SECCOMP_RET_ERRNO,
14 SOCK_DGRAM, SOCK_RAW, SOCK_TYPE_MASK, TIOCLINUX, TIOCSTI,
15 PR_SET_DUMPABLE, PR_SET_SECUREBITS, PR_SET_PTRACER,
16 OFFSET_ARGS0_LO, OFFSET_ARGS1_LO, OFFSET_ARGS2_LO, OFFSET_NR,
17 SockFilter,
18};
19
20pub struct PipePair {
26 pub notif_r: OwnedFd,
28 pub notif_w: OwnedFd,
30 pub ready_r: OwnedFd,
32 pub ready_w: OwnedFd,
34}
35
36impl PipePair {
37 pub fn new() -> io::Result<Self> {
39 let mut notif_fds = [0i32; 2];
40 let mut ready_fds = [0i32; 2];
41
42 let ret = unsafe { libc::pipe2(notif_fds.as_mut_ptr(), libc::O_CLOEXEC) };
44 if ret < 0 {
45 return Err(io::Error::last_os_error());
46 }
47
48 let ret = unsafe { libc::pipe2(ready_fds.as_mut_ptr(), libc::O_CLOEXEC) };
49 if ret < 0 {
50 unsafe {
52 libc::close(notif_fds[0]);
53 libc::close(notif_fds[1]);
54 }
55 return Err(io::Error::last_os_error());
56 }
57
58 Ok(PipePair {
60 notif_r: unsafe { OwnedFd::from_raw_fd(notif_fds[0]) },
61 notif_w: unsafe { OwnedFd::from_raw_fd(notif_fds[1]) },
62 ready_r: unsafe { OwnedFd::from_raw_fd(ready_fds[0]) },
63 ready_w: unsafe { OwnedFd::from_raw_fd(ready_fds[1]) },
64 })
65 }
66}
67
68pub(crate) fn write_u32_fd(fd: RawFd, val: u32) -> io::Result<()> {
74 let buf = val.to_le_bytes();
75 let mut written = 0usize;
76 while written < 4 {
77 let ret = unsafe {
78 libc::write(
79 fd,
80 buf[written..].as_ptr() as *const libc::c_void,
81 4 - written,
82 )
83 };
84 if ret < 0 {
85 return Err(io::Error::last_os_error());
86 }
87 written += ret as usize;
88 }
89 Ok(())
90}
91
92pub(crate) fn read_u32_fd(fd: RawFd) -> io::Result<u32> {
94 let mut buf = [0u8; 4];
95 let mut total = 0usize;
96 while total < 4 {
97 let ret = unsafe {
98 libc::read(
99 fd,
100 buf[total..].as_mut_ptr() as *mut libc::c_void,
101 4 - total,
102 )
103 };
104 if ret < 0 {
105 return Err(io::Error::last_os_error());
106 }
107 if ret == 0 {
108 return Err(io::Error::new(
109 io::ErrorKind::UnexpectedEof,
110 "pipe closed before 4 bytes read",
111 ));
112 }
113 total += ret as usize;
114 }
115 Ok(u32::from_le_bytes(buf))
116}
117
118pub fn syscall_name_to_nr(name: &str) -> Option<u32> {
127 let nr: i64 = match name {
128 "mount" => libc::SYS_mount,
129 "umount2" => libc::SYS_umount2,
130 "pivot_root" => libc::SYS_pivot_root,
131 "swapon" => libc::SYS_swapon,
132 "swapoff" => libc::SYS_swapoff,
133 "reboot" => libc::SYS_reboot,
134 "sethostname" => libc::SYS_sethostname,
135 "setdomainname" => libc::SYS_setdomainname,
136 "kexec_load" => libc::SYS_kexec_load,
137 "init_module" => libc::SYS_init_module,
138 "finit_module" => libc::SYS_finit_module,
139 "delete_module" => libc::SYS_delete_module,
140 "unshare" => libc::SYS_unshare,
141 "setns" => libc::SYS_setns,
142 "perf_event_open" => libc::SYS_perf_event_open,
143 "bpf" => libc::SYS_bpf,
144 "userfaultfd" => libc::SYS_userfaultfd,
145 "keyctl" => libc::SYS_keyctl,
146 "add_key" => libc::SYS_add_key,
147 "request_key" => libc::SYS_request_key,
148 "ptrace" => libc::SYS_ptrace,
149 "process_vm_readv" => libc::SYS_process_vm_readv,
150 "process_vm_writev" => libc::SYS_process_vm_writev,
151 "open_by_handle_at" => libc::SYS_open_by_handle_at,
152 "name_to_handle_at" => libc::SYS_name_to_handle_at,
153 "ioperm" => libc::SYS_ioperm,
154 "iopl" => libc::SYS_iopl,
155 "quotactl" => libc::SYS_quotactl,
156 "acct" => libc::SYS_acct,
157 "lookup_dcookie" => libc::SYS_lookup_dcookie,
158 "io_uring_setup" => libc::SYS_io_uring_setup,
160 "io_uring_enter" => libc::SYS_io_uring_enter,
161 "io_uring_register" => libc::SYS_io_uring_register,
162 "clone" => libc::SYS_clone,
164 "clone3" => libc::SYS_clone3,
165 "vfork" => libc::SYS_vfork,
166 "mmap" => libc::SYS_mmap,
167 "munmap" => libc::SYS_munmap,
168 "brk" => libc::SYS_brk,
169 "mremap" => libc::SYS_mremap,
170 "connect" => libc::SYS_connect,
171 "sendto" => libc::SYS_sendto,
172 "sendmsg" => libc::SYS_sendmsg,
173 "ioctl" => libc::SYS_ioctl,
174 "socket" => libc::SYS_socket,
175 "prctl" => libc::SYS_prctl,
176 "getrandom" => libc::SYS_getrandom,
177 "openat" => libc::SYS_openat,
178 "open" => libc::SYS_open,
179 "getdents64" => libc::SYS_getdents64,
180 "getdents" => libc::SYS_getdents,
181 "bind" => libc::SYS_bind,
182 "getsockname" => libc::SYS_getsockname,
183 "clock_gettime" => libc::SYS_clock_gettime,
184 "gettimeofday" => libc::SYS_gettimeofday,
185 "time" => libc::SYS_time,
186 "clock_nanosleep" => libc::SYS_clock_nanosleep,
187 "timerfd_settime" => libc::SYS_timerfd_settime,
188 "timer_settime" => libc::SYS_timer_settime,
189 "execve" => libc::SYS_execve,
190 "execveat" => libc::SYS_execveat,
191 "unlinkat" => libc::SYS_unlinkat,
193 "mkdirat" => libc::SYS_mkdirat,
194 "renameat2" => libc::SYS_renameat2,
195 "newfstatat" => libc::SYS_newfstatat,
196 "statx" => libc::SYS_statx,
197 "faccessat" => libc::SYS_faccessat,
198 "symlinkat" => libc::SYS_symlinkat,
199 "linkat" => libc::SYS_linkat,
200 "fchmodat" => libc::SYS_fchmodat,
201 "fchownat" => libc::SYS_fchownat,
202 "readlinkat" => libc::SYS_readlinkat,
203 "truncate" => libc::SYS_truncate,
204 "utimensat" => libc::SYS_utimensat,
205 "unlink" => libc::SYS_unlink,
206 "rmdir" => libc::SYS_rmdir,
207 "mkdir" => libc::SYS_mkdir,
208 "rename" => libc::SYS_rename,
209 "stat" => libc::SYS_stat,
210 "lstat" => libc::SYS_lstat,
211 "access" => libc::SYS_access,
212 "symlink" => libc::SYS_symlink,
213 "link" => libc::SYS_link,
214 "chmod" => libc::SYS_chmod,
215 "chown" => libc::SYS_chown,
216 "lchown" => libc::SYS_lchown,
217 "readlink" => libc::SYS_readlink,
218 "futimesat" => libc::SYS_futimesat,
219 "fork" => libc::SYS_fork,
220 _ => return None,
221 };
222 Some(nr as u32)
223}
224
225pub fn notif_syscalls(policy: &Policy) -> Vec<u32> {
231 let mut nrs = vec![
232 libc::SYS_clone as u32,
233 libc::SYS_clone3 as u32,
234 libc::SYS_vfork as u32,
235 ];
236
237 if policy.max_memory.is_some() {
238 nrs.push(libc::SYS_mmap as u32);
239 nrs.push(libc::SYS_munmap as u32);
240 nrs.push(libc::SYS_brk as u32);
241 nrs.push(libc::SYS_mremap as u32);
242 nrs.push(libc::SYS_shmget as u32);
243 }
244
245 if !policy.net_allow_hosts.is_empty() || policy.policy_fn.is_some() {
246 nrs.push(libc::SYS_connect as u32);
247 nrs.push(libc::SYS_sendto as u32);
248 nrs.push(libc::SYS_sendmsg as u32);
249 nrs.push(libc::SYS_bind as u32);
250 }
251
252 if policy.random_seed.is_some() {
253 nrs.push(libc::SYS_getrandom as u32);
254 nrs.push(libc::SYS_openat as u32);
256 }
257
258 if policy.time_start.is_some() {
259 nrs.extend_from_slice(&[
260 libc::SYS_clock_nanosleep as u32,
261 libc::SYS_timerfd_settime as u32,
262 libc::SYS_timer_settime as u32,
263 ]);
264 nrs.push(libc::SYS_openat as u32);
267 }
268
269 if policy.num_cpus.is_some() || policy.max_memory.is_some() || policy.isolate_pids || policy.port_remap {
271 nrs.push(libc::SYS_openat as u32);
272 }
273 if policy.num_cpus.is_some() {
275 nrs.push(libc::SYS_sched_getaffinity as u32);
276 }
277 if policy.isolate_pids || policy.deterministic_dirs {
278 nrs.extend_from_slice(&[
279 libc::SYS_getdents64 as u32,
280 libc::SYS_getdents as u32,
281 ]);
282 }
283 if policy.hostname.is_some() {
284 nrs.push(libc::SYS_uname as u32);
285 nrs.push(libc::SYS_openat as u32);
286 }
287
288 if policy.workdir.is_some() && policy.fs_isolation == FsIsolation::None {
290 nrs.extend_from_slice(&[
291 libc::SYS_openat as u32,
292 libc::SYS_unlinkat as u32,
293 libc::SYS_mkdirat as u32,
294 libc::SYS_renameat2 as u32,
295 libc::SYS_symlinkat as u32,
296 libc::SYS_linkat as u32,
297 libc::SYS_fchmodat as u32,
298 libc::SYS_fchownat as u32,
299 libc::SYS_truncate as u32,
300 libc::SYS_newfstatat as u32,
301 libc::SYS_statx as u32,
302 libc::SYS_faccessat as u32,
303 libc::SYS_readlinkat as u32,
304 libc::SYS_getdents64 as u32,
305 libc::SYS_getdents as u32,
306 ]);
307 }
308
309 if policy.chroot.is_some() {
311 nrs.extend_from_slice(&[
312 libc::SYS_openat as u32,
313 libc::SYS_open as u32, libc::SYS_execve as u32,
315 libc::SYS_execveat as u32,
316 libc::SYS_unlinkat as u32,
317 libc::SYS_mkdirat as u32,
318 libc::SYS_renameat2 as u32,
319 libc::SYS_symlinkat as u32,
320 libc::SYS_linkat as u32,
321 libc::SYS_fchmodat as u32,
322 libc::SYS_fchownat as u32,
323 libc::SYS_truncate as u32,
324 libc::SYS_newfstatat as u32,
325 libc::SYS_stat as u32, libc::SYS_lstat as u32, libc::SYS_statx as u32,
328 libc::SYS_faccessat as u32,
329 libc::SYS_access as u32, libc::SYS_readlinkat as u32,
331 libc::SYS_readlink as u32, libc::SYS_getdents64 as u32,
333 libc::SYS_getdents as u32,
334 libc::SYS_chdir as u32,
335 libc::SYS_getcwd as u32,
336 libc::SYS_statfs as u32,
337 libc::SYS_utimensat as u32,
338 libc::SYS_unlink as u32, libc::SYS_rmdir as u32, libc::SYS_mkdir as u32, libc::SYS_rename as u32, libc::SYS_symlink as u32, libc::SYS_link as u32, libc::SYS_chmod as u32, libc::SYS_chown as u32, libc::SYS_lchown as u32,
347 ]);
348 }
349
350 if policy.policy_fn.is_some() {
352 nrs.extend_from_slice(&[
353 libc::SYS_openat as u32,
354 libc::SYS_connect as u32,
355 libc::SYS_sendto as u32,
356 libc::SYS_bind as u32,
357 libc::SYS_execve as u32,
358 libc::SYS_execveat as u32,
359 ]);
360 }
361
362 if policy.port_remap {
364 nrs.extend_from_slice(&[
365 libc::SYS_bind as u32,
366 libc::SYS_getsockname as u32,
367 ]);
368 }
369
370 nrs.sort_unstable();
371 nrs.dedup();
372 nrs
373}
374
375pub fn deny_syscall_numbers(policy: &Policy) -> Vec<u32> {
380 if let Some(ref names) = policy.deny_syscalls {
381 names
382 .iter()
383 .filter_map(|n| syscall_name_to_nr(n))
384 .collect()
385 } else if policy.allow_syscalls.is_none() {
386 DEFAULT_DENY_SYSCALLS
387 .iter()
388 .filter_map(|n| syscall_name_to_nr(n))
389 .collect()
390 } else {
391 Vec::new()
393 }
394}
395
396pub fn arg_filters(policy: &Policy) -> Vec<SockFilter> {
406 let ret_errno = SECCOMP_RET_ERRNO | EPERM as u32;
407 let nr_clone = libc::SYS_clone as u32;
408 let nr_ioctl = libc::SYS_ioctl as u32;
409 let nr_prctl = libc::SYS_prctl as u32;
410 let nr_socket = libc::SYS_socket as u32;
411
412 let mut insns: Vec<SockFilter> = Vec::new();
413
414 insns.push(stmt(BPF_LD | BPF_W | BPF_ABS, OFFSET_NR));
422 insns.push(jump(BPF_JMP | BPF_JEQ | BPF_K, nr_clone, 0, 3));
423 insns.push(stmt(BPF_LD | BPF_W | BPF_ABS, OFFSET_ARGS0_LO));
424 insns.push(jump(BPF_JMP | BPF_JSET | BPF_K, CLONE_NS_FLAGS as u32, 0, 1));
425 insns.push(stmt(BPF_RET | BPF_K, ret_errno));
426
427 let dangerous_ioctls: &[u32] = &[TIOCSTI as u32, TIOCLINUX as u32];
430 let n_ioctls = dangerous_ioctls.len();
431 let skip_count = (1 + n_ioctls * 2) as u8;
432 insns.push(stmt(BPF_LD | BPF_W | BPF_ABS, OFFSET_NR));
433 insns.push(jump(BPF_JMP | BPF_JEQ | BPF_K, nr_ioctl, 0, skip_count));
434 insns.push(stmt(BPF_LD | BPF_W | BPF_ABS, OFFSET_ARGS1_LO));
435 for &cmd in dangerous_ioctls {
436 insns.push(jump(BPF_JMP | BPF_JEQ | BPF_K, cmd, 0, 1));
437 insns.push(stmt(BPF_RET | BPF_K, ret_errno));
438 }
439
440 let dangerous_prctl_ops: &[u32] = &[PR_SET_DUMPABLE, PR_SET_SECUREBITS, PR_SET_PTRACER];
443 let n_ops = dangerous_prctl_ops.len();
444 let skip_count = (1 + n_ops * 2) as u8;
445 insns.push(stmt(BPF_LD | BPF_W | BPF_ABS, OFFSET_NR));
446 insns.push(jump(BPF_JMP | BPF_JEQ | BPF_K, nr_prctl, 0, skip_count));
447 insns.push(stmt(BPF_LD | BPF_W | BPF_ABS, OFFSET_ARGS0_LO));
448 for &op in dangerous_prctl_ops {
449 insns.push(jump(BPF_JMP | BPF_JEQ | BPF_K, op, 0, 1));
450 insns.push(stmt(BPF_RET | BPF_K, ret_errno));
451 }
452
453 insns.push(stmt(BPF_LD | BPF_W | BPF_ABS, OFFSET_NR));
463 insns.push(jump(BPF_JMP | BPF_JEQ | BPF_K, nr_socket, 0, 5));
464 insns.push(stmt(BPF_LD | BPF_W | BPF_ABS, OFFSET_ARGS0_LO));
465 insns.push(jump(BPF_JMP | BPF_JEQ | BPF_K, AF_NETLINK, 0, 3));
466 insns.push(stmt(BPF_LD | BPF_W | BPF_ABS, OFFSET_ARGS2_LO));
467 insns.push(jump(BPF_JMP | BPF_JEQ | BPF_K, NETLINK_SOCK_DIAG, 0, 1));
468 insns.push(stmt(BPF_RET | BPF_K, ret_errno));
469
470 let mut blocked_types: Vec<u32> = Vec::new();
472 if policy.no_raw_sockets {
473 blocked_types.push(SOCK_RAW);
474 }
475 if policy.no_udp {
476 blocked_types.push(SOCK_DGRAM);
477 }
478
479 if !blocked_types.is_empty() {
480 let n = blocked_types.len();
481 let after_domain = 2 + n + 1;
483 let skip_all = (3 + after_domain) as u8;
485
486 insns.push(stmt(BPF_LD | BPF_W | BPF_ABS, OFFSET_NR));
487 insns.push(jump(BPF_JMP | BPF_JEQ | BPF_K, nr_socket, 0, skip_all));
488 insns.push(stmt(BPF_LD | BPF_W | BPF_ABS, OFFSET_ARGS0_LO));
490 insns.push(jump(BPF_JMP | BPF_JEQ | BPF_K, AF_INET, 1, 0));
492 insns.push(jump(BPF_JMP | BPF_JEQ | BPF_K, AF_INET6, 0, after_domain as u8));
494 insns.push(stmt(BPF_LD | BPF_W | BPF_ABS, OFFSET_ARGS1_LO));
496 insns.push(stmt(BPF_ALU | BPF_AND | BPF_K, SOCK_TYPE_MASK));
497 for (i, &sock_type) in blocked_types.iter().enumerate() {
499 let remaining = n - i - 1;
500 let jf: u8 = if remaining == 0 { 1 } else { 0 };
504 insns.push(jump(BPF_JMP | BPF_JEQ | BPF_K, sock_type, remaining as u8, jf));
505 }
506 insns.push(stmt(BPF_RET | BPF_K, ret_errno));
508 }
509
510 insns
511}
512
513fn close_fds_above(min_fd: RawFd, keep: &[RawFd]) {
519 let fds_to_close: Vec<RawFd> = {
523 let dir = match std::fs::read_dir("/proc/self/fd") {
524 Ok(d) => d,
525 Err(_) => return,
526 };
527 dir.flatten()
528 .filter_map(|entry| {
529 entry.file_name().into_string().ok()
530 .and_then(|name| name.parse::<RawFd>().ok())
531 })
532 .filter(|&fd| fd > min_fd && !keep.contains(&fd))
533 .collect()
534 };
535 for fd in fds_to_close {
537 unsafe { libc::close(fd) };
538 }
539}
540
541pub(crate) use crate::cow::ChildMountConfig;
547
548fn write_id_maps(real_uid: u32, real_gid: u32) {
552 let _ = std::fs::write("/proc/self/uid_map", format!("0 {} 1\n", real_uid));
553 let _ = std::fs::write("/proc/self/setgroups", "deny\n");
554 let _ = std::fs::write("/proc/self/gid_map", format!("0 {} 1\n", real_gid));
555}
556
557fn write_id_maps_overflow() {
560 let uid = unsafe { libc::getuid() };
561 let gid = unsafe { libc::getgid() };
562 write_id_maps(uid, gid);
563}
564
565pub(crate) fn confine_child(policy: &Policy, cmd: &[CString], pipes: &PipePair, cow_config: Option<&ChildMountConfig>, nested: bool) -> ! {
574 macro_rules! fail {
576 ($msg:expr) => {{
577 let err = std::io::Error::last_os_error();
578 let _ = write!(std::io::stderr(), "sandlock child: {}: {}\n", $msg, err);
579 unsafe { libc::_exit(127) };
580 }};
581 }
582
583 use std::io::Write;
584
585 if unsafe { libc::setpgid(0, 0) } != 0 {
587 fail!("setpgid");
588 }
589
590 if unsafe { libc::isatty(0) } == 1 {
595 unsafe {
596 libc::signal(libc::SIGTTOU, libc::SIG_IGN);
597 libc::tcsetpgrp(0, libc::getpgrp());
598 libc::signal(libc::SIGTTOU, libc::SIG_DFL);
599 }
600 }
601
602 if unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) } != 0 {
604 fail!("prctl(PR_SET_PDEATHSIG)");
605 }
606
607 if unsafe { libc::getppid() } == 1 {
609 fail!("parent died before confinement");
610 }
611
612 if policy.no_randomize_memory {
614 const ADDR_NO_RANDOMIZE: u64 = 0x0040000;
615 if unsafe { libc::personality(ADDR_NO_RANDOMIZE as libc::c_ulong) } == -1 {
616 fail!("personality(ADDR_NO_RANDOMIZE)");
617 }
618 }
619
620 if let Some(ref cores) = policy.cpu_cores {
622 if !cores.is_empty() {
623 let mut set = unsafe { std::mem::zeroed::<libc::cpu_set_t>() };
624 unsafe { libc::CPU_ZERO(&mut set) };
625 for &core in cores {
626 unsafe { libc::CPU_SET(core as usize, &mut set) };
627 }
628 if unsafe {
629 libc::sched_setaffinity(
630 0,
631 std::mem::size_of::<libc::cpu_set_t>(),
632 &set,
633 )
634 } != 0
635 {
636 fail!("sched_setaffinity");
637 }
638 }
639 }
640
641 if policy.no_huge_pages {
643 if unsafe { libc::prctl(libc::PR_SET_THP_DISABLE, 1, 0, 0, 0) } != 0 {
644 fail!("prctl(PR_SET_THP_DISABLE)");
645 }
646 }
647
648 let real_uid = unsafe { libc::getuid() };
650 let real_gid = unsafe { libc::getgid() };
651
652 if policy.privileged && cow_config.is_none() {
654 if unsafe { libc::unshare(libc::CLONE_NEWUSER) } != 0 {
655 fail!("unshare(CLONE_NEWUSER)");
656 }
657 write_id_maps(real_uid, real_gid);
658 }
659
660 if let Some(ref cow) = cow_config {
662 if unsafe { libc::unshare(libc::CLONE_NEWUSER | libc::CLONE_NEWNS) } != 0 {
664 fail!("unshare(CLONE_NEWUSER | CLONE_NEWNS)");
665 }
666
667 write_id_maps_overflow();
669
670 let lowerdir = cow.lowers.iter()
676 .map(|p| p.display().to_string())
677 .collect::<Vec<_>>()
678 .join(":");
679 let opts = format!(
680 "lowerdir={},upperdir={},workdir={}",
681 lowerdir,
682 cow.upper.display(),
683 cow.work.display(),
684 );
685
686 let mount_cstr = match CString::new(cow.mount_point.to_str().unwrap_or("")) {
687 Ok(c) => c,
688 Err(_) => fail!("invalid overlay mount point path"),
689 };
690 let overlay_cstr = CString::new("overlay").unwrap();
691 let opts_cstr = match CString::new(opts) {
692 Ok(c) => c,
693 Err(_) => fail!("invalid overlay opts"),
694 };
695
696 let ret = unsafe {
697 libc::mount(
698 overlay_cstr.as_ptr(),
699 mount_cstr.as_ptr(),
700 overlay_cstr.as_ptr(),
701 0,
702 opts_cstr.as_ptr() as *const libc::c_void,
703 )
704 };
705 if ret != 0 {
706 fail!("mount overlay");
707 }
708 }
709
710 let effective_cwd = if let Some(ref cwd) = policy.cwd {
713 if let Some(ref chroot_root) = policy.chroot {
714 Some(chroot_root.join(cwd.strip_prefix("/").unwrap_or(cwd)))
715 } else {
716 Some(cwd.clone())
717 }
718 } else if let Some(ref chroot_root) = policy.chroot {
719 Some(chroot_root.to_path_buf())
721 } else {
722 None
723 };
724
725 if let Some(ref cwd) = effective_cwd {
726 let c_path = match CString::new(cwd.as_os_str().as_encoded_bytes()) {
727 Ok(c) => c,
728 Err(_) => fail!("invalid cwd path"),
729 };
730 if unsafe { libc::chdir(c_path.as_ptr()) } != 0 {
731 fail!("chdir");
732 }
733 }
734
735 if unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) } != 0 {
737 fail!("prctl(PR_SET_NO_NEW_PRIVS)");
738 }
739
740 if let Err(e) = crate::landlock::confine(policy) {
742 fail!(format!("landlock: {}", e));
743 }
744
745 let deny = deny_syscall_numbers(policy);
747 let args = arg_filters(policy);
748 let mut keep_fd: i32 = -1;
749
750 if nested {
751 let filter = bpf::assemble_filter(&[], &deny, &args);
754 if let Err(e) = bpf::install_deny_filter(&filter) {
755 fail!(format!("seccomp deny filter: {}", e));
756 }
757 if let Err(e) = write_u32_fd(pipes.notif_w.as_raw_fd(), 0) {
759 fail!(format!("write nested signal: {}", e));
760 }
761 } else {
762 let notif = notif_syscalls(policy);
764 let filter = bpf::assemble_filter(¬if, &deny, &args);
765 let notif_fd = match bpf::install_filter(&filter) {
766 Ok(fd) => fd,
767 Err(e) => fail!(format!("seccomp install: {}", e)),
768 };
769 keep_fd = notif_fd.as_raw_fd();
770 if let Err(e) = write_u32_fd(pipes.notif_w.as_raw_fd(), keep_fd as u32) {
771 fail!(format!("write notif fd: {}", e));
772 }
773 std::mem::forget(notif_fd);
774 }
775
776 crate::sandbox::CONFINED.store(true, std::sync::atomic::Ordering::Relaxed);
778
779 match read_u32_fd(pipes.ready_r.as_raw_fd()) {
781 Ok(_) => {}
782 Err(e) => fail!(format!("read ready signal: {}", e)),
783 }
784
785 if policy.close_fds {
787 if keep_fd >= 0 {
788 close_fds_above(2, &[keep_fd]);
789 } else {
790 close_fds_above(2, &[]);
791 }
792 }
793
794 if policy.clean_env {
796 for (key, _) in std::env::vars_os() {
798 std::env::remove_var(&key);
799 }
800 }
801 for (key, value) in &policy.env {
802 std::env::set_var(key, value);
803 }
804
805 if let Some(ref devices) = policy.gpu_devices {
807 if !devices.is_empty() {
808 let vis = devices.iter().map(|d| d.to_string()).collect::<Vec<_>>().join(",");
809 std::env::set_var("CUDA_VISIBLE_DEVICES", &vis);
810 std::env::set_var("ROCR_VISIBLE_DEVICES", &vis);
811 }
812 }
814
815 debug_assert!(!cmd.is_empty(), "cmd must not be empty");
817 let argv_ptrs: Vec<*const libc::c_char> = cmd
818 .iter()
819 .map(|s| s.as_ptr())
820 .chain(std::iter::once(std::ptr::null()))
821 .collect();
822
823 if policy.chroot.is_some() {
824 let mut exec_path = vec![0u8; libc::PATH_MAX as usize];
830 let orig = cmd[0].as_bytes_with_nul();
831 exec_path[..orig.len()].copy_from_slice(orig);
832
833 unsafe {
834 libc::execvp(
835 exec_path.as_ptr() as *const libc::c_char,
836 argv_ptrs.as_ptr(),
837 )
838 };
839 } else {
840 unsafe { libc::execvp(argv_ptrs[0], argv_ptrs.as_ptr()) };
841 }
842
843 fail!(format!("execvp '{}'", cmd[0].to_string_lossy()));
845}
846
847#[cfg(test)]
852mod tests {
853 use super::*;
854
855 #[test]
856 fn test_pipe_pair_creation() {
857 let pipes = PipePair::new().expect("pipe creation failed");
858 assert!(pipes.notif_r.as_raw_fd() >= 0);
860 assert!(pipes.notif_w.as_raw_fd() >= 0);
861 assert!(pipes.ready_r.as_raw_fd() >= 0);
862 assert!(pipes.ready_w.as_raw_fd() >= 0);
863 let fds = [
865 pipes.notif_r.as_raw_fd(),
866 pipes.notif_w.as_raw_fd(),
867 pipes.ready_r.as_raw_fd(),
868 pipes.ready_w.as_raw_fd(),
869 ];
870 for i in 0..4 {
871 for j in (i + 1)..4 {
872 assert_ne!(fds[i], fds[j]);
873 }
874 }
875 }
876
877 #[test]
878 fn test_write_read_u32() {
879 let pipes = PipePair::new().expect("pipe creation failed");
880 let val = 42u32;
881 write_u32_fd(pipes.notif_w.as_raw_fd(), val).expect("write failed");
882 let got = read_u32_fd(pipes.notif_r.as_raw_fd()).expect("read failed");
883 assert_eq!(got, val);
884 }
885
886 #[test]
887 fn test_write_read_u32_large() {
888 let pipes = PipePair::new().expect("pipe creation failed");
889 let val = 0xDEAD_BEEFu32;
890 write_u32_fd(pipes.notif_w.as_raw_fd(), val).expect("write failed");
891 let got = read_u32_fd(pipes.notif_r.as_raw_fd()).expect("read failed");
892 assert_eq!(got, val);
893 }
894
895 #[test]
896 fn test_notif_syscalls_always_has_clone() {
897 let policy = Policy::builder().build().unwrap();
898 let nrs = notif_syscalls(&policy);
899 assert!(nrs.contains(&(libc::SYS_clone as u32)));
900 assert!(nrs.contains(&(libc::SYS_clone3 as u32)));
901 assert!(nrs.contains(&(libc::SYS_vfork as u32)));
902 }
903
904 #[test]
905 fn test_notif_syscalls_memory() {
906 let policy = Policy::builder()
907 .max_memory(crate::policy::ByteSize::mib(256))
908 .build()
909 .unwrap();
910 let nrs = notif_syscalls(&policy);
911 assert!(nrs.contains(&(libc::SYS_mmap as u32)));
912 assert!(nrs.contains(&(libc::SYS_munmap as u32)));
913 assert!(nrs.contains(&(libc::SYS_brk as u32)));
914 assert!(nrs.contains(&(libc::SYS_mremap as u32)));
915 assert!(nrs.contains(&(libc::SYS_shmget as u32)));
916 }
917
918 #[test]
919 fn test_notif_syscalls_net() {
920 let policy = Policy::builder()
921 .net_allow_host("example.com")
922 .build()
923 .unwrap();
924 let nrs = notif_syscalls(&policy);
925 assert!(nrs.contains(&(libc::SYS_connect as u32)));
926 assert!(nrs.contains(&(libc::SYS_sendto as u32)));
927 assert!(nrs.contains(&(libc::SYS_sendmsg as u32)));
928 }
929
930 #[test]
931 fn test_deny_syscall_numbers_default() {
932 let policy = Policy::builder().build().unwrap();
933 let nrs = deny_syscall_numbers(&policy);
934 assert!(nrs.contains(&(libc::SYS_mount as u32)));
936 assert!(nrs.contains(&(libc::SYS_ptrace as u32)));
937 assert!(nrs.contains(&(libc::SYS_bpf as u32)));
938 assert!(!nrs.is_empty());
940 }
941
942 #[test]
943 fn test_deny_syscall_numbers_custom() {
944 let policy = Policy::builder()
945 .deny_syscalls(vec!["mount".into(), "ptrace".into()])
946 .build()
947 .unwrap();
948 let nrs = deny_syscall_numbers(&policy);
949 assert_eq!(nrs.len(), 2);
950 assert!(nrs.contains(&(libc::SYS_mount as u32)));
951 assert!(nrs.contains(&(libc::SYS_ptrace as u32)));
952 }
953
954 #[test]
955 fn test_deny_syscall_numbers_empty_when_allow_set() {
956 let policy = Policy::builder()
957 .allow_syscalls(vec!["read".into(), "write".into()])
958 .build()
959 .unwrap();
960 let nrs = deny_syscall_numbers(&policy);
961 assert!(nrs.is_empty());
962 }
963
964 #[test]
965 fn test_arg_filters_has_clone_ioctl_prctl_socket() {
966 use crate::sys::structs::{
967 BPF_JEQ, BPF_JSET, BPF_JMP, BPF_K,
968 };
969 let policy = Policy::builder().build().unwrap();
970 let filters = arg_filters(&policy);
971 assert!(filters.iter().any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K)
973 && f.k == libc::SYS_clone as u32));
974 assert!(filters.iter().any(|f| f.code == (BPF_JMP | BPF_JSET | BPF_K)
976 && f.k == CLONE_NS_FLAGS as u32));
977 assert!(filters.iter().any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K)
979 && f.k == libc::SYS_ioctl as u32));
980 assert!(filters.iter().any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K)
982 && f.k == TIOCSTI as u32));
983 assert!(filters.iter().any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K)
984 && f.k == TIOCLINUX as u32));
985 assert!(filters.iter().any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K)
987 && f.k == libc::SYS_prctl as u32));
988 assert!(filters.iter().any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K)
990 && f.k == PR_SET_DUMPABLE));
991 assert!(filters.iter().any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K)
993 && f.k == AF_NETLINK));
994 assert!(filters.iter().any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K)
995 && f.k == NETLINK_SOCK_DIAG));
996 }
997
998 #[test]
999 fn test_arg_filters_raw_sockets() {
1000 use crate::sys::structs::{BPF_ALU, BPF_AND, BPF_JEQ, BPF_JMP, BPF_K};
1001 let policy = Policy::builder().no_raw_sockets(true).build().unwrap();
1002 let filters = arg_filters(&policy);
1003 assert!(filters.iter().any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K)
1005 && f.k == AF_INET));
1006 assert!(filters.iter().any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K)
1008 && f.k == AF_INET6));
1009 assert!(filters.iter().any(|f| f.code == (BPF_ALU | BPF_AND | BPF_K)
1011 && f.k == SOCK_TYPE_MASK));
1012 assert!(filters.iter().any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K)
1014 && f.k == SOCK_RAW));
1015 }
1016
1017 #[test]
1018 fn test_arg_filters_no_udp() {
1019 use crate::sys::structs::{BPF_JEQ, BPF_JMP, BPF_K};
1020 let policy = Policy::builder().no_udp(true).build().unwrap();
1021 let filters = arg_filters(&policy);
1022 assert!(filters.iter().any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K)
1024 && f.k == SOCK_DGRAM));
1025 }
1026
1027 #[test]
1028 fn test_syscall_name_to_nr_covers_defaults() {
1029 let mut skipped = 0;
1031 for name in DEFAULT_DENY_SYSCALLS {
1032 match syscall_name_to_nr(name) {
1033 Some(_) => {}
1034 None => {
1035 assert_eq!(*name, "nfsservctl", "unexpected unresolved syscall: {}", name);
1036 skipped += 1;
1037 }
1038 }
1039 }
1040 assert_eq!(skipped, 1); }
1042}