Skip to main content

sandlock_core/
context.rs

1// Fork + confinement sequence: child-side Landlock + seccomp application
2// and parent-child pipe synchronization.
3
4use 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
20// ============================================================
21// Pipe pair for parent-child synchronization
22// ============================================================
23
24/// Pipes for parent-child communication after fork().
25pub struct PipePair {
26    /// Parent reads the notif fd number written by the child.
27    pub notif_r: OwnedFd,
28    /// Child writes the notif fd number to the parent.
29    pub notif_w: OwnedFd,
30    /// Child reads the "supervisor ready" signal from the parent.
31    pub ready_r: OwnedFd,
32    /// Parent writes the "supervisor ready" signal to the child.
33    pub ready_w: OwnedFd,
34}
35
36impl PipePair {
37    /// Create two pipe pairs using `pipe2(O_CLOEXEC)`.
38    pub fn new() -> io::Result<Self> {
39        let mut notif_fds = [0i32; 2];
40        let mut ready_fds = [0i32; 2];
41
42        // SAFETY: pipe2 with valid pointers and O_CLOEXEC
43        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            // Close the first pair on failure
51            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        // SAFETY: pipe2 returned valid fds
59        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
68// ============================================================
69// Pipe I/O helpers
70// ============================================================
71
72/// Write a `u32` as 4 little-endian bytes to a raw fd.
73pub(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
92/// Read a `u32` (4 little-endian bytes, blocking) from a raw fd.
93pub(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
118// ============================================================
119// Syscall name → number mapping
120// ============================================================
121
122/// Map a syscall name to its `libc::SYS_*` number.
123///
124/// Covers all names in `DEFAULT_DENY_SYSCALLS` plus extras needed for
125/// notif and arg-filter lists.
126pub 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        // nfsservctl was removed in Linux 3.1; no libc constant — skip
159        "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        // Additional syscalls for notif/arg filters
163        "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        // COW filesystem syscalls
192        "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
225// ============================================================
226// Policy → syscall lists
227// ============================================================
228
229/// Determine which syscalls need `SECCOMP_RET_USER_NOTIF`.
230pub 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        // Also intercept openat so the supervisor can re-patch vDSO after exec.
255        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        // Also intercept openat so the supervisor gets a notification after exec
265        // and can re-patch the vDSO (exec replaces vDSO with a fresh copy).
266        nrs.push(libc::SYS_openat as u32);
267    }
268
269    // /proc virtualization needs openat interception
270    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    // Virtualize sched_getaffinity so nproc/sysconf agree with /proc/cpuinfo
274    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    // COW filesystem interception (seccomp-based, unprivileged)
289    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    // Chroot path interception
310    if policy.chroot.is_some() {
311        nrs.extend_from_slice(&[
312            libc::SYS_openat as u32,
313            libc::SYS_open as u32,        // musl uses open(2) instead of openat
314            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,        // musl uses stat(2) instead of newfstatat
326            libc::SYS_lstat as u32,       // musl uses lstat(2) instead of newfstatat
327            libc::SYS_statx as u32,
328            libc::SYS_faccessat as u32,
329            libc::SYS_access as u32,      // musl uses access(2) instead of faccessat
330            libc::SYS_readlinkat as u32,
331            libc::SYS_readlink as u32,    // musl uses readlink(2) instead of readlinkat
332            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,      // musl uses unlink(2) instead of unlinkat
339            libc::SYS_rmdir as u32,       // musl uses rmdir(2) instead of unlinkat
340            libc::SYS_mkdir as u32,       // musl uses mkdir(2) instead of mkdirat
341            libc::SYS_rename as u32,      // musl uses rename(2) instead of renameat2
342            libc::SYS_symlink as u32,     // musl uses symlink(2) instead of symlinkat
343            libc::SYS_link as u32,        // musl uses link(2) instead of linkat
344            libc::SYS_chmod as u32,       // musl uses chmod(2) instead of fchmodat
345            libc::SYS_chown as u32,       // musl uses chown(2)/lchown(2) instead of fchownat
346            libc::SYS_lchown as u32,
347        ]);
348    }
349
350    // Dynamic policy callback — intercept key syscalls for event emission
351    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    // Port remapping
363    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
375/// Resolve `deny_syscalls` names to numbers.
376///
377/// If both `deny_syscalls` and `allow_syscalls` are `None`, returns the
378/// numbers for `DEFAULT_DENY_SYSCALLS`.
379pub 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        // allow_syscalls is set — no deny list
392        Vec::new()
393    }
394}
395
396/// Build argument-level seccomp filter instructions matching the Python
397/// `_build_arg_filters()` exactly.
398///
399/// Returns a `Vec<SockFilter>` containing self-contained BPF blocks for:
400///   - clone: block namespace creation flags
401///   - ioctl: block TIOCSTI, TIOCLINUX
402///   - prctl: block PR_SET_DUMPABLE, PR_SET_SECUREBITS, PR_SET_PTRACER
403///   - socket: block NETLINK_SOCK_DIAG (with AF_NETLINK domain check)
404///   - socket: block SOCK_RAW/SOCK_DGRAM on AF_INET/AF_INET6 (with type mask)
405pub 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    // --- clone: block namespace creation flags ---
415    // 5 instructions:
416    //   LD NR
417    //   JEQ clone → +0, skip 3
418    //   LD arg0
419    //   JSET NS_FLAGS → +0, skip 1
420    //   RET ERRNO
421    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    // --- ioctl: block dangerous commands (TIOCSTI, TIOCLINUX) ---
428    // Layout: LD NR, JEQ ioctl (skip 1 + N*2), LD arg1, [JEQ cmd, RET ERRNO] * N
429    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    // --- prctl: block dangerous options ---
441    // Layout: LD NR, JEQ prctl (skip 1 + N*2), LD arg0, [JEQ op, RET ERRNO] * N
442    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    // --- socket: block NETLINK_SOCK_DIAG (only on AF_NETLINK domain) ---
454    // 7 instructions:
455    //   LD NR
456    //   JEQ socket → +0, skip 5
457    //   LD arg0 (domain)
458    //   JEQ AF_NETLINK → +0, skip 3
459    //   LD arg2 (protocol)
460    //   JEQ NETLINK_SOCK_DIAG → +0, skip 1
461    //   RET ERRNO
462    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    // --- socket: block SOCK_RAW and/or SOCK_DGRAM on AF_INET/AF_INET6 ---
471    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        // Instructions after domain checks: 2 (load+AND) + N (JEQs) + 1 (RET)
482        let after_domain = 2 + n + 1;
483        // Total after NR check: 3 (load domain + 2 JEQs) + after_domain
484        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        // Load domain (arg0)
489        insns.push(stmt(BPF_LD | BPF_W | BPF_ABS, OFFSET_ARGS0_LO));
490        // AF_INET → skip to type check (jump over AF_INET6 check)
491        insns.push(jump(BPF_JMP | BPF_JEQ | BPF_K, AF_INET, 1, 0));
492        // AF_INET6 → type check; else skip everything remaining
493        insns.push(jump(BPF_JMP | BPF_JEQ | BPF_K, AF_INET6, 0, after_domain as u8));
494        // Load type (arg1) and mask off SOCK_NONBLOCK|SOCK_CLOEXEC
495        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        // Check each blocked type
498        for (i, &sock_type) in blocked_types.iter().enumerate() {
499            let remaining = n - i - 1;
500            // Match → jump to RET ERRNO (skip 'remaining' JEQs ahead)
501            // No match on last type → skip past RET ERRNO (jf=1)
502            // No match on non-last → check next type (jf=0)
503            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        // Deny return (reached by any matching JEQ)
507        insns.push(stmt(BPF_RET | BPF_K, ret_errno));
508    }
509
510    insns
511}
512
513// ============================================================
514// Close fds above threshold
515// ============================================================
516
517/// Close all file descriptors above `min_fd`, except those in `keep`.
518fn close_fds_above(min_fd: RawFd, keep: &[RawFd]) {
519    // Read /proc/self/fd to enumerate open fds.
520    // Collect all fd numbers first, then close them after dropping the directory
521    // iterator. This avoids closing the directory fd during iteration.
522    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    // The directory is now closed; safe to close the collected fds.
536    for fd in fds_to_close {
537        unsafe { libc::close(fd) };
538    }
539}
540
541// ============================================================
542// COW filesystem config passed from parent to child
543// ============================================================
544
545// Re-export ChildMountConfig so callers can use the old import path.
546pub(crate) use crate::cow::ChildMountConfig;
547
548/// Write uid/gid maps for an unprivileged user namespace.
549/// `real_uid`/`real_gid` must be captured *before* unshare(CLONE_NEWUSER),
550/// since getuid()/getgid() return the overflow id (65534) after unshare.
551fn 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
557/// Write uid/gid maps using the post-unshare overflow uid (65534).
558/// Used by the OverlayFS COW path which relies on this specific mapping.
559fn write_id_maps_overflow() {
560    let uid = unsafe { libc::getuid() };
561    let gid = unsafe { libc::getgid() };
562    write_id_maps(uid, gid);
563}
564
565// ============================================================
566// Child-side confinement (never returns)
567// ============================================================
568
569/// Apply irreversible confinement (Landlock + seccomp) then exec the command.
570///
571/// This function **never returns**: it calls `execvp` on success or
572/// `_exit(127)` on any error.
573pub(crate) fn confine_child(policy: &Policy, cmd: &[CString], pipes: &PipePair, cow_config: Option<&ChildMountConfig>, nested: bool) -> ! {
574    // Helper: abort child on error. Includes the OS error automatically.
575    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    // 1. New process group
586    if unsafe { libc::setpgid(0, 0) } != 0 {
587        fail!("setpgid");
588    }
589
590    // 1b. If stdin is a terminal, become the foreground process group
591    //     so interactive shells can read from the TTY.
592    //     Must ignore SIGTTOU first — a background pgrp calling tcsetpgrp
593    //     gets stopped by SIGTTOU otherwise.
594    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    // 2. Die if parent exits
603    if unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) } != 0 {
604        fail!("prctl(PR_SET_PDEATHSIG)");
605    }
606
607    // 3. Check parent didn't die between fork and prctl
608    if unsafe { libc::getppid() } == 1 {
609        fail!("parent died before confinement");
610    }
611
612    // 4. Optional: disable ASLR
613    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    // 4b. Optional: CPU core binding
621    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    // 5. Optional: disable THP
642    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    // Capture real uid/gid before any unshare (after unshare they become 65534)
649    let real_uid = unsafe { libc::getuid() };
650    let real_gid = unsafe { libc::getgid() };
651
652    // 5b. User namespace for privileged mode (fake root) or OverlayFS COW
653    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    // 5c. User + mount namespace for OverlayFS COW (includes CLONE_NEWUSER)
661    if let Some(ref cow) = cow_config {
662        // unshare user + mount namespaces (unprivileged)
663        if unsafe { libc::unshare(libc::CLONE_NEWUSER | libc::CLONE_NEWNS) } != 0 {
664            fail!("unshare(CLONE_NEWUSER | CLONE_NEWNS)");
665        }
666
667        // Write uid/gid maps using overflow uid (preserves existing COW behavior)
668        write_id_maps_overflow();
669
670        // Mount the overlay filesystem ON TOP of the workdir so the child
671        // sees the merged view at the original path.  The kernel resolves
672        // lowerdir before the covering mount takes effect, so using the
673        // same path as both lowerdir and mount-point is safe inside our
674        // private mount namespace.
675        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    // 6. Optional: change working directory
711    // cwd controls where the child starts; workdir is only for COW
712    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        // Default to chroot root
720        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    // 7. Set NO_NEW_PRIVS (required for both Landlock and seccomp without CAP_SYS_ADMIN)
736    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    // 8. Apply Landlock confinement (IRREVERSIBLE)
741    if let Err(e) = crate::landlock::confine(policy) {
742        fail!(format!("landlock: {}", e));
743    }
744
745    // 9. Assemble and install seccomp filter (IRREVERSIBLE)
746    let deny = deny_syscall_numbers(policy);
747    let args = arg_filters(policy);
748    let mut keep_fd: i32 = -1;
749
750    if nested {
751        // Nested sandbox: deny-only filter (no supervisor — parent handles it).
752        // BPF filters are ANDed by the kernel, so each level can only tighten.
753        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        // Signal nested mode to parent (fd=0 means no supervisor needed)
758        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        // First-level sandbox: notif + deny filter with NEW_LISTENER.
763        let notif = notif_syscalls(policy);
764        let filter = bpf::assemble_filter(&notif, &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    // Mark this process as confined for in-process nesting detection
777    crate::sandbox::CONFINED.store(true, std::sync::atomic::Ordering::Relaxed);
778
779    // 10. Wait for parent to signal ready
780    match read_u32_fd(pipes.ready_r.as_raw_fd()) {
781        Ok(_) => {}
782        Err(e) => fail!(format!("read ready signal: {}", e)),
783    }
784
785    // 12. Optional: close all fds above stderr
786    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    // 13. Apply environment
795    if policy.clean_env {
796        // Clear all env vars first
797        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    // 13b. GPU device visibility
806    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        // Empty list = all GPUs visible, don't set env vars
813    }
814
815    // 14. exec
816    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        // With chroot the seccomp handler rewrites the filename to a host path
825        // (or /proc/self/fd/N).  Pass a separate PATH_MAX buffer as the `file`
826        // argument so the rewrite does not corrupt argv[0] — which must stay as
827        // the original command name (e.g. busybox uses argv[0] for applet
828        // detection).  execvp still handles PATH lookup for bare command names.
829        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    // If we get here, exec failed
844    fail!(format!("execvp '{}'", cmd[0].to_string_lossy()));
845}
846
847// ============================================================
848// Tests
849// ============================================================
850
851#[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        // Verify fds are valid (non-negative)
859        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        // All four fds should be distinct
864        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        // Should contain mount, ptrace, etc.
935        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        // nfsservctl has no libc constant, so it is skipped
939        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        // Should contain JEQ for clone syscall nr
972        assert!(filters.iter().any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K)
973            && f.k == libc::SYS_clone as u32));
974        // Should contain JSET for CLONE_NS_FLAGS
975        assert!(filters.iter().any(|f| f.code == (BPF_JMP | BPF_JSET | BPF_K)
976            && f.k == CLONE_NS_FLAGS as u32));
977        // Should contain JEQ for ioctl syscall nr
978        assert!(filters.iter().any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K)
979            && f.k == libc::SYS_ioctl as u32));
980        // Should contain JEQ for TIOCSTI and TIOCLINUX
981        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        // Should contain JEQ for prctl syscall nr
986        assert!(filters.iter().any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K)
987            && f.k == libc::SYS_prctl as u32));
988        // Should contain JEQ for PR_SET_DUMPABLE
989        assert!(filters.iter().any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K)
990            && f.k == PR_SET_DUMPABLE));
991        // Should contain JEQ for socket + AF_NETLINK + NETLINK_SOCK_DIAG
992        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        // Should have AF_INET check
1004        assert!(filters.iter().any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K)
1005            && f.k == AF_INET));
1006        // Should have AF_INET6 check
1007        assert!(filters.iter().any(|f| f.code == (BPF_JMP | BPF_JEQ | BPF_K)
1008            && f.k == AF_INET6));
1009        // Should have ALU AND SOCK_TYPE_MASK
1010        assert!(filters.iter().any(|f| f.code == (BPF_ALU | BPF_AND | BPF_K)
1011            && f.k == SOCK_TYPE_MASK));
1012        // Should have JEQ SOCK_RAW
1013        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        // Should have JEQ SOCK_DGRAM
1023        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        // Every name in DEFAULT_DENY_SYSCALLS except nfsservctl should resolve
1030        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); // only nfsservctl
1041    }
1042}