Skip to main content

kizz_trace_linux/
filter.rs

1// Copyright (c) 2026 Sakura Industries LLC.
2//
3// SPDX-License-Identifier: AGPL-3.0-only
4
5//! The seccomp-bpf filter in front of `ptrace`.
6//!
7//! The filter decides, inside the kernel and before each system call runs, whether
8//! the tracer needs to see it:
9//!
10//! * a system call through a non-native interface, the 32-bit `int 0x80` interface or
11//!   x32, stops for the tracer, which marks the run as incompletely traced;
12//! * `io_uring_setup` fails with `ENOSYS`, so programs fall back to ordinary system
13//!   calls, because `io_uring` operations would bypass the filter;
14//! * a native system call outside [`KNOWN_SYSTEM_CALLS`] stops for the tracer, which
15//!   reports its number as one that it does not know and lets it run;
16//! * each system call in [`UNTRACEABLE_SYSTEM_CALLS`] stops for the tracer, which marks
17//!   the run as incompletely traced, with the checks of its arguments that the filter can
18//!   make itself: `clone` and `unshare` only with `CLONE_NEWNS` in their flags, and
19//!   `setns` only when its namespace type is 0 or includes `CLONE_NEWNS`; `clone3` always
20//!   stops, and the tracer reads the flags in its `struct clone_args`;
21//! * each system call in [`TRACKED_SYSTEM_CALLS`] stops for the tracer, `sendto` only
22//!   with a destination address: a null address names none, so the call, which a
23//!   connected socket makes for every `send`, runs at full speed;
24//! * every other system call runs at full speed.
25
26use std::{num::TryFromIntError, ops::RangeInclusive};
27
28use libc::{c_long, sock_filter};
29
30/// A system call that the filter stops for, with its `x86_64` name and number.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub struct TrackedSystemCall {
33    /// The system call's `x86_64` name.
34    pub name: &'static str,
35    /// The system call's `x86_64` number.
36    pub number: c_long,
37}
38
39impl TrackedSystemCall {
40    /// A tracked system call with its `x86_64` name and number.
41    const fn new(
42        name: &'static str,
43        number: c_long,
44    ) -> Self {
45        Self { name, number }
46    }
47}
48
49/// The `x86_64` numbers of the system calls that the filter stops for and that the
50/// `libc` crate does not define, from the kernel's `x86_64` table,
51/// `arch/x86/entry/syscalls/syscall_64.tbl`.
52pub(crate) mod numbers {
53    use libc::c_long;
54
55    /// `fchmodat2`, number 452 in the kernel's `x86_64` table.
56    pub(crate) const SYS_FCHMODAT2: c_long = 452;
57    /// `setxattrat`, number 463 in the kernel's `x86_64` table.
58    pub(crate) const SYS_SETXATTRAT: c_long = 463;
59    /// `getxattrat`, number 464 in the kernel's `x86_64` table.
60    pub(crate) const SYS_GETXATTRAT: c_long = 464;
61    /// `listxattrat`, number 465 in the kernel's `x86_64` table.
62    pub(crate) const SYS_LISTXATTRAT: c_long = 465;
63    /// `removexattrat`, number 466 in the kernel's `x86_64` table.
64    pub(crate) const SYS_REMOVEXATTRAT: c_long = 466;
65    /// `file_getattr`, number 468 in the kernel's `x86_64` table.
66    pub(crate) const SYS_FILE_GETATTR: c_long = 468;
67    /// `file_setattr`, number 469 in the kernel's `x86_64` table.
68    pub(crate) const SYS_FILE_SETATTR: c_long = 469;
69    /// `open_tree_attr`, number 467 in the kernel's `x86_64` table.
70    pub(crate) const SYS_OPEN_TREE_ATTR: c_long = 467;
71    /// `fchroot`, number 472 in the kernel's `x86_64` table.
72    pub(crate) const SYS_FCHROOT: c_long = 472;
73}
74
75/// Every system call the filter stops for, in the order of the spec's list:
76/// opening files, metadata and existence, file systems, watches, extended
77/// attributes, links, directory listings, programs, the working directory, changes,
78/// changes through a descriptor, and sockets.
79pub const TRACKED_SYSTEM_CALLS: &[TrackedSystemCall] = &[
80    // Opening files.
81    TrackedSystemCall::new("open", libc::SYS_open),
82    TrackedSystemCall::new("openat", libc::SYS_openat),
83    TrackedSystemCall::new("openat2", libc::SYS_openat2),
84    TrackedSystemCall::new("creat", libc::SYS_creat),
85    // Metadata and existence.
86    TrackedSystemCall::new("stat", libc::SYS_stat),
87    TrackedSystemCall::new("lstat", libc::SYS_lstat),
88    TrackedSystemCall::new("newfstatat", libc::SYS_newfstatat),
89    TrackedSystemCall::new("statx", libc::SYS_statx),
90    TrackedSystemCall::new("access", libc::SYS_access),
91    TrackedSystemCall::new("faccessat", libc::SYS_faccessat),
92    TrackedSystemCall::new("faccessat2", libc::SYS_faccessat2),
93    TrackedSystemCall::new("file_getattr", numbers::SYS_FILE_GETATTR),
94    TrackedSystemCall::new("name_to_handle_at", libc::SYS_name_to_handle_at),
95    // File systems.
96    TrackedSystemCall::new("statfs", libc::SYS_statfs),
97    TrackedSystemCall::new("fstatfs", libc::SYS_fstatfs),
98    // Watches.
99    TrackedSystemCall::new("inotify_add_watch", libc::SYS_inotify_add_watch),
100    TrackedSystemCall::new("fanotify_mark", libc::SYS_fanotify_mark),
101    // Extended attributes.
102    TrackedSystemCall::new("getxattr", libc::SYS_getxattr),
103    TrackedSystemCall::new("lgetxattr", libc::SYS_lgetxattr),
104    TrackedSystemCall::new("fgetxattr", libc::SYS_fgetxattr),
105    TrackedSystemCall::new("getxattrat", numbers::SYS_GETXATTRAT),
106    TrackedSystemCall::new("listxattr", libc::SYS_listxattr),
107    TrackedSystemCall::new("llistxattr", libc::SYS_llistxattr),
108    TrackedSystemCall::new("flistxattr", libc::SYS_flistxattr),
109    TrackedSystemCall::new("listxattrat", numbers::SYS_LISTXATTRAT),
110    TrackedSystemCall::new("setxattr", libc::SYS_setxattr),
111    TrackedSystemCall::new("lsetxattr", libc::SYS_lsetxattr),
112    TrackedSystemCall::new("fsetxattr", libc::SYS_fsetxattr),
113    TrackedSystemCall::new("setxattrat", numbers::SYS_SETXATTRAT),
114    TrackedSystemCall::new("removexattr", libc::SYS_removexattr),
115    TrackedSystemCall::new("lremovexattr", libc::SYS_lremovexattr),
116    TrackedSystemCall::new("fremovexattr", libc::SYS_fremovexattr),
117    TrackedSystemCall::new("removexattrat", numbers::SYS_REMOVEXATTRAT),
118    // Links.
119    TrackedSystemCall::new("readlink", libc::SYS_readlink),
120    TrackedSystemCall::new("readlinkat", libc::SYS_readlinkat),
121    TrackedSystemCall::new("link", libc::SYS_link),
122    TrackedSystemCall::new("linkat", libc::SYS_linkat),
123    TrackedSystemCall::new("symlink", libc::SYS_symlink),
124    TrackedSystemCall::new("symlinkat", libc::SYS_symlinkat),
125    // Directory listings.
126    TrackedSystemCall::new("getdents", libc::SYS_getdents),
127    TrackedSystemCall::new("getdents64", libc::SYS_getdents64),
128    // Programs.
129    TrackedSystemCall::new("execve", libc::SYS_execve),
130    TrackedSystemCall::new("execveat", libc::SYS_execveat),
131    // The working directory.
132    TrackedSystemCall::new("chdir", libc::SYS_chdir),
133    TrackedSystemCall::new("fchdir", libc::SYS_fchdir),
134    // Changes.
135    TrackedSystemCall::new("rename", libc::SYS_rename),
136    TrackedSystemCall::new("renameat", libc::SYS_renameat),
137    TrackedSystemCall::new("renameat2", libc::SYS_renameat2),
138    TrackedSystemCall::new("unlink", libc::SYS_unlink),
139    TrackedSystemCall::new("unlinkat", libc::SYS_unlinkat),
140    TrackedSystemCall::new("rmdir", libc::SYS_rmdir),
141    TrackedSystemCall::new("mkdir", libc::SYS_mkdir),
142    TrackedSystemCall::new("mkdirat", libc::SYS_mkdirat),
143    TrackedSystemCall::new("mknod", libc::SYS_mknod),
144    TrackedSystemCall::new("mknodat", libc::SYS_mknodat),
145    TrackedSystemCall::new("truncate", libc::SYS_truncate),
146    TrackedSystemCall::new("chmod", libc::SYS_chmod),
147    TrackedSystemCall::new("fchmodat", libc::SYS_fchmodat),
148    TrackedSystemCall::new("fchmodat2", numbers::SYS_FCHMODAT2),
149    TrackedSystemCall::new("chown", libc::SYS_chown),
150    TrackedSystemCall::new("lchown", libc::SYS_lchown),
151    TrackedSystemCall::new("fchownat", libc::SYS_fchownat),
152    TrackedSystemCall::new("utime", libc::SYS_utime),
153    TrackedSystemCall::new("utimes", libc::SYS_utimes),
154    TrackedSystemCall::new("utimensat", libc::SYS_utimensat),
155    TrackedSystemCall::new("futimesat", libc::SYS_futimesat),
156    TrackedSystemCall::new("file_setattr", numbers::SYS_FILE_SETATTR),
157    // Changes through a descriptor, resolved to the path behind it.
158    TrackedSystemCall::new("ftruncate", libc::SYS_ftruncate),
159    TrackedSystemCall::new("fchmod", libc::SYS_fchmod),
160    TrackedSystemCall::new("fchown", libc::SYS_fchown),
161    TrackedSystemCall::new("fallocate", libc::SYS_fallocate),
162    // Sockets.
163    TrackedSystemCall::new("bind", libc::SYS_bind),
164    TrackedSystemCall::new("connect", libc::SYS_connect),
165    TrackedSystemCall::new("sendto", libc::SYS_sendto),
166    TrackedSystemCall::new("sendmsg", libc::SYS_sendmsg),
167    TrackedSystemCall::new("sendmmsg", libc::SYS_sendmmsg),
168];
169
170/// Every system call that marks a run as incompletely traced, in the order of the
171/// spec's list: opening by handle, changing the root, mounting, mount namespaces,
172/// and the other uses of a path. The first four groups can change what a path
173/// means; the last uses a path in ways that the tracer does not record. `unshare`,
174/// `clone` and `clone3` mark the run only with `CLONE_NEWNS`, and `setns` only when
175/// it can enter a mount namespace.
176pub const UNTRACEABLE_SYSTEM_CALLS: &[TrackedSystemCall] = &[
177    // Opening by handle.
178    TrackedSystemCall::new("open_by_handle_at", libc::SYS_open_by_handle_at),
179    // Changing the root.
180    TrackedSystemCall::new("chroot", libc::SYS_chroot),
181    TrackedSystemCall::new("fchroot", numbers::SYS_FCHROOT),
182    TrackedSystemCall::new("pivot_root", libc::SYS_pivot_root),
183    // Mounting.
184    TrackedSystemCall::new("mount", libc::SYS_mount),
185    TrackedSystemCall::new("umount2", libc::SYS_umount2),
186    TrackedSystemCall::new("fsopen", libc::SYS_fsopen),
187    TrackedSystemCall::new("fsconfig", libc::SYS_fsconfig),
188    TrackedSystemCall::new("fsmount", libc::SYS_fsmount),
189    TrackedSystemCall::new("fspick", libc::SYS_fspick),
190    TrackedSystemCall::new("move_mount", libc::SYS_move_mount),
191    TrackedSystemCall::new("open_tree", libc::SYS_open_tree),
192    TrackedSystemCall::new("open_tree_attr", numbers::SYS_OPEN_TREE_ATTR),
193    TrackedSystemCall::new("mount_setattr", libc::SYS_mount_setattr),
194    // Mount namespaces.
195    TrackedSystemCall::new("unshare", libc::SYS_unshare),
196    TrackedSystemCall::new("setns", libc::SYS_setns),
197    TrackedSystemCall::new("clone", libc::SYS_clone),
198    TrackedSystemCall::new("clone3", libc::SYS_clone3),
199    // Other uses of a path.
200    TrackedSystemCall::new("uselib", libc::SYS_uselib),
201    TrackedSystemCall::new("acct", libc::SYS_acct),
202    TrackedSystemCall::new("quotactl", libc::SYS_quotactl),
203    TrackedSystemCall::new("quotactl_fd", libc::SYS_quotactl_fd),
204    TrackedSystemCall::new("swapon", libc::SYS_swapon),
205    TrackedSystemCall::new("swapoff", libc::SYS_swapoff),
206];
207
208/// The native system calls that the tracer knows, as ranges of numbers: those of
209/// the `x86_64` table of Linux 7.3, `arch/x86/entry/syscalls/syscall_64.tbl`, which
210/// uses 0 through 336 and 424 through 472 for native calls. Any other native
211/// number is a system call that the tracer does not know: 337 through 423, which
212/// the table leaves unused, and every number above 472.
213pub const KNOWN_SYSTEM_CALLS: [RangeInclusive<u32>; 2] = [0..=336, 424..=472];
214
215/// The filter's return data for a tracked system call.
216pub(crate) const DATA_TRACKED: u16 = 0;
217/// The filter's return data for a system call through a foreign architecture's
218/// interface, which on `x86_64` is the 32-bit `int 0x80` interface.
219pub(crate) const DATA_FOREIGN_ARCH: u16 = 1;
220/// The filter's return data for a system call through the x32 interface.
221pub(crate) const DATA_X32: u16 = 2;
222/// The filter's return data for a system call of [`UNTRACEABLE_SYSTEM_CALLS`] that
223/// marks the run, or that the tracer checks itself.
224pub(crate) const DATA_UNTRACEABLE: u16 = 3;
225/// The filter's return data for a native system call outside
226/// [`KNOWN_SYSTEM_CALLS`].
227pub(crate) const DATA_UNKNOWN: u16 = 4;
228
229/// The bit that marks an x32 system call number.
230pub(crate) const X32_SYSCALL_BIT: u32 = 0x4000_0000;
231
232/// The audit architecture of native `x86_64` system calls, `AUDIT_ARCH_X86_64`:
233/// `EM_X86_64` (62) with the 64-bit and little-endian flags.
234const AUDIT_ARCH_X86_64: u32 = 0xC000_003E;
235
236/// The offset of the system call number, `nr`, in `struct seccomp_data`.
237const NR_OFFSET: u32 = 0;
238/// The offset of the audit architecture, `arch`, in `struct seccomp_data`.
239const ARCH_OFFSET: u32 = 4;
240/// The offset of the low 32 bits of the first argument, `args[0]`, in
241/// `struct seccomp_data` on a little-endian machine.
242const FIRST_ARGUMENT_OFFSET: u32 = 16;
243/// The offset of the low 32 bits of the second argument, `args[1]`, in
244/// `struct seccomp_data` on a little-endian machine.
245const SECOND_ARGUMENT_OFFSET: u32 = 24;
246/// The offset of the low 32 bits of the fifth argument, `args[4]`, in
247/// `struct seccomp_data` on a little-endian machine: the destination address of
248/// `sendto`.
249const FIFTH_ARGUMENT_OFFSET: u32 = 48;
250/// The offset of the high 32 bits of the fifth argument, `args[4]`, in
251/// `struct seccomp_data` on a little-endian machine.
252const FIFTH_ARGUMENT_HIGH_OFFSET: u32 = 52;
253
254/// The `CLONE_NEWNS` flag, which asks for a new mount namespace, as the filter
255/// compares it with the low 32 bits of an argument.
256const NEW_MOUNT_NAMESPACE: u32 = libc::CLONE_NEWNS.cast_unsigned();
257
258/// `BPF_LD | BPF_W | BPF_ABS`: load a 32-bit word of `struct seccomp_data`.
259const LOAD_WORD: u16 = 0x20;
260/// `BPF_JMP | BPF_JEQ | BPF_K`: jump on equality with a constant.
261const JUMP_IF_EQUAL: u16 = 0x15;
262/// `BPF_JMP | BPF_JSET | BPF_K`: jump when any bit of a constant is set.
263const JUMP_IF_SET: u16 = 0x45;
264/// `BPF_JMP | BPF_JGT | BPF_K`: jump when the loaded word is greater than a
265/// constant.
266const JUMP_IF_GREATER: u16 = 0x25;
267/// `BPF_JMP | BPF_JGE | BPF_K`: jump when the loaded word is at least a constant.
268const JUMP_IF_AT_LEAST: u16 = 0x35;
269/// `BPF_RET | BPF_K`: return a constant action.
270const RETURN: u16 = 0x06;
271
272/// Load the word at `offset` of `struct seccomp_data`.
273const fn load(offset: u32) -> sock_filter {
274    sock_filter {
275        code: LOAD_WORD,
276        jt: 0,
277        jf: 0,
278        k: offset,
279    }
280}
281
282/// Compare the loaded word with `value` by `code`, and skip `taken` instructions
283/// when the comparison holds, or `not_taken` when it does not.
284const fn jump(
285    code: u16,
286    value: u32,
287    taken: u8,
288    not_taken: u8,
289) -> sock_filter {
290    sock_filter {
291        code,
292        jt: taken,
293        jf: not_taken,
294        k: value,
295    }
296}
297
298/// Skip the next instruction unless the loaded word equals `value`.
299const fn unless_equal_skip(value: u32) -> sock_filter {
300    sock_filter {
301        code: JUMP_IF_EQUAL,
302        jt: 0,
303        jf: 1,
304        k: value,
305    }
306}
307
308/// Skip the next instruction if the loaded word equals `value`.
309const fn if_equal_skip(value: u32) -> sock_filter {
310    sock_filter {
311        code: JUMP_IF_EQUAL,
312        jt: 1,
313        jf: 0,
314        k: value,
315    }
316}
317
318/// Skip the next instruction unless the loaded word has a bit of `bits` set.
319const fn unless_set_skip(bits: u32) -> sock_filter {
320    sock_filter {
321        code: JUMP_IF_SET,
322        jt: 0,
323        jf: 1,
324        k: bits,
325    }
326}
327
328/// Return `action` from the filter.
329const fn action(action: u32) -> sock_filter {
330    sock_filter {
331        code: RETURN,
332        jt: 0,
333        jf: 0,
334        k: action,
335    }
336}
337
338/// Stop for the tracer, which reads `data` with `PTRACE_GETEVENTMSG`.
339fn trace(data: u16) -> sock_filter {
340    action(libc::SECCOMP_RET_TRACE | u32::from(data))
341}
342
343/// Allow the system call.
344const fn allow() -> sock_filter {
345    action(libc::SECCOMP_RET_ALLOW)
346}
347
348/// The instructions for `call`, one of [`UNTRACEABLE_SYSTEM_CALLS`]: stop for the
349/// tracer when the call can mark the run, and otherwise allow it. `clone` and
350/// `unshare` stop only with `CLONE_NEWNS` in their first argument, and `setns` only
351/// when its second argument, the namespace type, is 0 or includes `CLONE_NEWNS`;
352/// every other call, `clone3` included, always stops. The instructions that load an
353/// argument end in an action on every path, so the number that the instructions
354/// after them compare stays loaded.
355///
356/// # Errors
357///
358/// Returns an error only if the call's number does not fit the filter's 32-bit
359/// comparison.
360fn untraceable(call: &TrackedSystemCall) -> Result<Vec<sock_filter>, TryFromIntError> {
361    let number = u32::try_from(call.number)?;
362    Ok(match call.number {
363        libc::SYS_clone | libc::SYS_unshare => {
364            vec![
365                jump(JUMP_IF_EQUAL, number, 0, 4),
366                load(FIRST_ARGUMENT_OFFSET),
367                jump(JUMP_IF_SET, NEW_MOUNT_NAMESPACE, 0, 1),
368                trace(DATA_UNTRACEABLE),
369                allow(),
370            ]
371        },
372        libc::SYS_setns => {
373            vec![
374                jump(JUMP_IF_EQUAL, number, 0, 5),
375                load(SECOND_ARGUMENT_OFFSET),
376                jump(JUMP_IF_EQUAL, 0, 1, 0),
377                jump(JUMP_IF_SET, NEW_MOUNT_NAMESPACE, 0, 1),
378                trace(DATA_UNTRACEABLE),
379                allow(),
380            ]
381        },
382        _ => vec![unless_equal_skip(number), trace(DATA_UNTRACEABLE)],
383    })
384}
385
386/// The instructions for `call`, one of [`TRACKED_SYSTEM_CALLS`]: stop for the
387/// tracer. `sendto` stops only with a destination address, a fifth argument that
388/// is not null, which the filter compares in its two 32-bit halves; with a null
389/// one, it runs. The instructions that load an argument end in an action on every
390/// path, so the number that the instructions after them compare stays loaded.
391///
392/// # Errors
393///
394/// Returns an error only if the call's number does not fit the filter's 32-bit
395/// comparison.
396fn tracked(call: &TrackedSystemCall) -> Result<Vec<sock_filter>, TryFromIntError> {
397    let number = u32::try_from(call.number)?;
398    Ok(if call.number == libc::SYS_sendto {
399        vec![
400            jump(JUMP_IF_EQUAL, number, 0, 7),
401            load(FIFTH_ARGUMENT_OFFSET),
402            jump(JUMP_IF_EQUAL, 0, 1, 0),
403            trace(DATA_TRACKED),
404            load(FIFTH_ARGUMENT_HIGH_OFFSET),
405            jump(JUMP_IF_EQUAL, 0, 1, 0),
406            trace(DATA_TRACKED),
407            allow(),
408        ]
409    } else {
410        vec![unless_equal_skip(number), trace(DATA_TRACKED)]
411    })
412}
413
414/// Build the filter program.
415///
416/// # Errors
417///
418/// Returns an error only if a system call number does not fit the filter's 32-bit
419/// comparison, which no `x86_64` number does.
420pub(crate) fn program() -> Result<Vec<sock_filter>, TryFromIntError> {
421    let io_uring_setup = u32::try_from(libc::SYS_io_uring_setup)?;
422    let mut program = vec![
423        load(ARCH_OFFSET),
424        if_equal_skip(AUDIT_ARCH_X86_64),
425        trace(DATA_FOREIGN_ARCH),
426        load(NR_OFFSET),
427        unless_set_skip(X32_SYSCALL_BIT),
428        trace(DATA_X32),
429        unless_equal_skip(io_uring_setup),
430        action(libc::SECCOMP_RET_ERRNO | libc::ENOSYS.unsigned_abs()),
431    ];
432    // Every native number outside the known table, which starts at 0: above its
433    // last number, and in the gap between its two ranges.
434    let [low, high] = KNOWN_SYSTEM_CALLS;
435    program.extend([
436        jump(JUMP_IF_GREATER, *high.end(), 0, 1),
437        trace(DATA_UNKNOWN),
438        jump(JUMP_IF_GREATER, *low.end(), 0, 2),
439        jump(JUMP_IF_AT_LEAST, *high.start(), 1, 0),
440        trace(DATA_UNKNOWN),
441    ]);
442    for call in UNTRACEABLE_SYSTEM_CALLS {
443        program.extend(untraceable(call)?);
444    }
445    for call in TRACKED_SYSTEM_CALLS {
446        program.extend(tracked(call)?);
447    }
448    program.push(allow());
449    Ok(program)
450}
451
452/// Unit tests that pin the filter's system-call set and run its program.
453#[cfg(test)]
454#[allow(
455    clippy::disallowed_macros,
456    clippy::disallowed_methods,
457    reason = "test code: the tests assert and lock"
458)]
459mod tests {
460    use std::{collections::BTreeSet, mem};
461
462    use super::*;
463
464    /// The 32-bit audit architecture, `AUDIT_ARCH_I386`.
465    const AUDIT_ARCH_I386: u32 = 0x4000_0003;
466
467    /// The kernel's limit on the length of a filter program, `BPF_MAXINSNS`.
468    const MAX_INSTRUCTIONS: usize = 4096;
469
470    /// Run the filter program on one system call without arguments, as the kernel
471    /// does, and return the action it chooses.
472    fn evaluate(
473        program: &[sock_filter],
474        arch: u32,
475        nr: u32,
476    ) -> u32 {
477        evaluate_with(program, arch, nr, [0; 2])
478    }
479
480    /// Run the filter program on one system call whose first two arguments have
481    /// the low 32 bits `arguments`, and whose other arguments are 0, as the kernel
482    /// does, and return the action it chooses.
483    fn evaluate_with(
484        program: &[sock_filter],
485        arch: u32,
486        nr: u32,
487        arguments: [u32; 2],
488    ) -> u32 {
489        let [first, second] = arguments;
490        evaluate_all(program, arch, nr, [
491            u64::from(first),
492            u64::from(second),
493            0,
494            0,
495            0,
496            0,
497        ])
498    }
499
500    /// Run the filter program on one system call with the six arguments
501    /// `arguments`, as the kernel does, and return the action it chooses.
502    fn evaluate_all(
503        program: &[sock_filter],
504        arch: u32,
505        nr: u32,
506        arguments: [u64; 6],
507    ) -> u32 {
508        let low = |argument: u64| u32::try_from(argument & u64::from(u32::MAX)).unwrap();
509        let high = |argument: u64| u32::try_from(argument >> 32).unwrap();
510        let mut pc = 0_usize;
511        let mut accumulator = 0_u32;
512        loop {
513            let instruction = program[pc];
514            let next = pc.checked_add(1).unwrap();
515            pc = match instruction.code {
516                LOAD_WORD => {
517                    accumulator = match instruction.k {
518                        NR_OFFSET => nr,
519                        ARCH_OFFSET => arch,
520                        FIRST_ARGUMENT_OFFSET => low(arguments[0]),
521                        SECOND_ARGUMENT_OFFSET => low(arguments[1]),
522                        FIFTH_ARGUMENT_OFFSET => low(arguments[4]),
523                        FIFTH_ARGUMENT_HIGH_OFFSET => high(arguments[4]),
524                        offset => panic!("unexpected load offset {offset}"),
525                    };
526                    next
527                },
528                JUMP_IF_EQUAL | JUMP_IF_SET | JUMP_IF_GREATER | JUMP_IF_AT_LEAST => {
529                    let taken = match instruction.code {
530                        JUMP_IF_EQUAL => accumulator == instruction.k,
531                        JUMP_IF_SET => accumulator & instruction.k != 0,
532                        JUMP_IF_GREATER => accumulator > instruction.k,
533                        _ => accumulator >= instruction.k,
534                    };
535                    let skip = if taken {
536                        instruction.jt
537                    } else {
538                        instruction.jf
539                    };
540                    next.checked_add(usize::from(skip)).unwrap()
541                },
542                RETURN => return instruction.k,
543                code => panic!("unexpected instruction {code:#x}"),
544            };
545        }
546    }
547
548    /// The `x86_64` number of a system call, as the filter compares it.
549    fn number(nr: c_long) -> u32 {
550        u32::try_from(nr).unwrap()
551    }
552
553    /// The tracked calls are the spec's 76, in the order of its list.
554    #[test]
555    fn tracked_set_is_the_spec_list() {
556        let names: Vec<&str> = TRACKED_SYSTEM_CALLS.iter().map(|call| call.name).collect();
557        assert_eq!(names, vec![
558            "open",
559            "openat",
560            "openat2",
561            "creat",
562            "stat",
563            "lstat",
564            "newfstatat",
565            "statx",
566            "access",
567            "faccessat",
568            "faccessat2",
569            "file_getattr",
570            "name_to_handle_at",
571            "statfs",
572            "fstatfs",
573            "inotify_add_watch",
574            "fanotify_mark",
575            "getxattr",
576            "lgetxattr",
577            "fgetxattr",
578            "getxattrat",
579            "listxattr",
580            "llistxattr",
581            "flistxattr",
582            "listxattrat",
583            "setxattr",
584            "lsetxattr",
585            "fsetxattr",
586            "setxattrat",
587            "removexattr",
588            "lremovexattr",
589            "fremovexattr",
590            "removexattrat",
591            "readlink",
592            "readlinkat",
593            "link",
594            "linkat",
595            "symlink",
596            "symlinkat",
597            "getdents",
598            "getdents64",
599            "execve",
600            "execveat",
601            "chdir",
602            "fchdir",
603            "rename",
604            "renameat",
605            "renameat2",
606            "unlink",
607            "unlinkat",
608            "rmdir",
609            "mkdir",
610            "mkdirat",
611            "mknod",
612            "mknodat",
613            "truncate",
614            "chmod",
615            "fchmodat",
616            "fchmodat2",
617            "chown",
618            "lchown",
619            "fchownat",
620            "utime",
621            "utimes",
622            "utimensat",
623            "futimesat",
624            "file_setattr",
625            "ftruncate",
626            "fchmod",
627            "fchown",
628            "fallocate",
629            "bind",
630            "connect",
631            "sendto",
632            "sendmsg",
633            "sendmmsg",
634        ]);
635        assert_eq!(names.len(), 76);
636    }
637
638    #[test]
639    fn tracked_numbers_are_distinct_x86_64_numbers() {
640        let numbers: BTreeSet<c_long> = TRACKED_SYSTEM_CALLS
641            .iter()
642            .map(|call| call.number)
643            .collect();
644        assert_eq!(numbers.len(), TRACKED_SYSTEM_CALLS.len());
645        let known = [
646            ("open", 2),
647            ("stat", 4),
648            ("access", 21),
649            ("execve", 59),
650            ("chdir", 80),
651            ("getdents64", 217),
652            ("openat", 257),
653            ("execveat", 322),
654            ("statx", 332),
655            ("openat2", 437),
656            ("faccessat2", 439),
657            ("statfs", 137),
658            ("fstatfs", 138),
659            ("getxattr", 191),
660            ("removexattr", 197),
661            ("fremovexattr", 199),
662            ("inotify_add_watch", 254),
663            ("fallocate", 285),
664            ("fanotify_mark", 301),
665            ("name_to_handle_at", 303),
666            ("fchmodat2", 452),
667            ("setxattrat", 463),
668            ("getxattrat", 464),
669            ("listxattrat", 465),
670            ("removexattrat", 466),
671            ("file_getattr", 468),
672            ("file_setattr", 469),
673            ("connect", 42),
674            ("sendto", 44),
675            ("sendmsg", 46),
676            ("bind", 49),
677            ("sendmmsg", 307),
678        ];
679        for (name, nr) in known {
680            let call = TRACKED_SYSTEM_CALLS
681                .iter()
682                .find(|call| call.name == name)
683                .unwrap();
684            assert_eq!(call.number, nr, "{name}");
685        }
686        assert_eq!(libc::SYS_io_uring_setup, 425);
687    }
688
689    #[test]
690    fn instruction_codes_and_offsets_match_the_kernel() {
691        assert_eq!(
692            u32::from(LOAD_WORD),
693            libc::BPF_LD | libc::BPF_W | libc::BPF_ABS
694        );
695        assert_eq!(
696            u32::from(JUMP_IF_EQUAL),
697            libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K
698        );
699        assert_eq!(
700            u32::from(JUMP_IF_SET),
701            libc::BPF_JMP | libc::BPF_JSET | libc::BPF_K
702        );
703        assert_eq!(
704            u32::from(JUMP_IF_GREATER),
705            libc::BPF_JMP | libc::BPF_JGT | libc::BPF_K
706        );
707        assert_eq!(
708            u32::from(JUMP_IF_AT_LEAST),
709            libc::BPF_JMP | libc::BPF_JGE | libc::BPF_K
710        );
711        assert_eq!(u32::from(RETURN), libc::BPF_RET | libc::BPF_K);
712        assert_eq!(
713            usize::try_from(NR_OFFSET).unwrap(),
714            mem::offset_of!(libc::seccomp_data, nr)
715        );
716        assert_eq!(
717            usize::try_from(ARCH_OFFSET).unwrap(),
718            mem::offset_of!(libc::seccomp_data, arch)
719        );
720        // The low 32 bits of each argument, on a little-endian machine.
721        let arguments = mem::offset_of!(libc::seccomp_data, args);
722        assert_eq!(usize::try_from(FIRST_ARGUMENT_OFFSET).unwrap(), arguments);
723        assert_eq!(
724            usize::try_from(SECOND_ARGUMENT_OFFSET).unwrap(),
725            arguments.checked_add(mem::size_of::<u64>()).unwrap()
726        );
727        // The fifth argument, `args[4]`, in its low and high halves.
728        let fifth = arguments
729            .checked_add(mem::size_of::<u64>().checked_mul(4).unwrap())
730            .unwrap();
731        assert_eq!(usize::try_from(FIFTH_ARGUMENT_OFFSET).unwrap(), fifth);
732        assert_eq!(
733            usize::try_from(FIFTH_ARGUMENT_HIGH_OFFSET).unwrap(),
734            fifth.checked_add(mem::size_of::<u32>()).unwrap()
735        );
736        assert_eq!(NEW_MOUNT_NAMESPACE, 0x0002_0000);
737    }
738
739    #[test]
740    fn program_fits_the_kernel_limits() {
741        let program = program().unwrap();
742        assert!(program.len() <= MAX_INSTRUCTIONS);
743        assert!(u16::try_from(program.len()).is_ok());
744    }
745
746    /// Every tracked call stops for the tracer, `sendto` with a destination address
747    /// in its fifth argument.
748    #[test]
749    fn tracked_calls_stop_for_the_tracer() {
750        let program = program().unwrap();
751        let stop = libc::SECCOMP_RET_TRACE | u32::from(DATA_TRACKED);
752        let destination = [0, 0, 0, 0, 0x7FFF_0000_1000, 16];
753        for call in TRACKED_SYSTEM_CALLS {
754            assert_eq!(
755                evaluate_all(
756                    &program,
757                    AUDIT_ARCH_X86_64,
758                    number(call.number),
759                    destination
760                ),
761                stop,
762                "{}",
763                call.name
764            );
765        }
766    }
767
768    /// `sendto` stops for the tracer when its destination address is not null, in
769    /// either half of the register, and runs at full speed with a null one, as a
770    /// `send` on a connected socket makes it; the calls after it in the program are
771    /// still compared.
772    #[test]
773    fn sendto_stops_only_with_a_destination() {
774        let program = program().unwrap();
775        let stop = libc::SECCOMP_RET_TRACE | u32::from(DATA_TRACKED);
776        let sendto = number(libc::SYS_sendto);
777        for address in [
778            1,
779            0x1000,
780            0xFFFF_FFFF,
781            0x1_0000_0000,
782            0x7FFF_0000_1000,
783            u64::MAX,
784        ] {
785            assert_eq!(
786                evaluate_all(&program, AUDIT_ARCH_X86_64, sendto, [
787                    3, 0, 5, 0, address, 16
788                ]),
789                stop,
790                "{address:#x}"
791            );
792        }
793        for length in [0, 16] {
794            assert_eq!(
795                evaluate_all(&program, AUDIT_ARCH_X86_64, sendto, [3, 0, 5, 0, 0, length]),
796                libc::SECCOMP_RET_ALLOW,
797                "{length}"
798            );
799        }
800        for call in ["sendmsg", "sendmmsg"] {
801            let nr = TRACKED_SYSTEM_CALLS
802                .iter()
803                .find(|tracked| tracked.name == call)
804                .map(|tracked| number(tracked.number))
805                .unwrap();
806            assert_eq!(evaluate(&program, AUDIT_ARCH_X86_64, nr), stop, "{call}");
807        }
808    }
809
810    #[test]
811    fn other_calls_run_at_full_speed() {
812        let program = program().unwrap();
813        let untracked = [
814            libc::SYS_read,
815            libc::SYS_write,
816            libc::SYS_close,
817            libc::SYS_fstat,
818            libc::SYS_mmap,
819            libc::SYS_brk,
820            libc::SYS_getpid,
821            libc::SYS_clone,
822            libc::SYS_wait4,
823            libc::SYS_exit_group,
824            libc::SYS_io_uring_enter,
825            libc::SYS_io_uring_register,
826        ];
827        for nr in untracked {
828            assert_eq!(
829                evaluate(&program, AUDIT_ARCH_X86_64, number(nr)),
830                libc::SECCOMP_RET_ALLOW,
831                "system call {nr}"
832            );
833        }
834    }
835
836    #[test]
837    fn io_uring_setup_fails_with_enosys() {
838        let program = program().unwrap();
839        let action = evaluate(
840            &program,
841            AUDIT_ARCH_X86_64,
842            number(libc::SYS_io_uring_setup),
843        );
844        assert_eq!(
845            action & libc::SECCOMP_RET_ACTION_FULL,
846            libc::SECCOMP_RET_ERRNO
847        );
848        assert_eq!(action & libc::SECCOMP_RET_DATA, libc::ENOSYS.unsigned_abs());
849    }
850
851    #[test]
852    fn non_native_calls_stop_with_their_interface() {
853        let program = program().unwrap();
854        let foreign = libc::SECCOMP_RET_TRACE | u32::from(DATA_FOREIGN_ARCH);
855        let x32 = libc::SECCOMP_RET_TRACE | u32::from(DATA_X32);
856        for nr in [
857            number(libc::SYS_getpid),
858            number(libc::SYS_open),
859            number(libc::SYS_io_uring_setup),
860        ] {
861            assert_eq!(evaluate(&program, AUDIT_ARCH_I386, nr), foreign);
862            assert_eq!(
863                evaluate(&program, AUDIT_ARCH_X86_64, nr | X32_SYSCALL_BIT),
864                x32
865            );
866        }
867    }
868
869    /// The calls that mark a run are the spec's 24, in the order of its list, with
870    /// their numbers in the kernel's `x86_64` table.
871    #[test]
872    fn untraceable_set_is_the_spec_list() {
873        let calls: Vec<(&str, c_long)> = UNTRACEABLE_SYSTEM_CALLS
874            .iter()
875            .map(|call| (call.name, call.number))
876            .collect();
877        assert_eq!(calls, vec![
878            ("open_by_handle_at", 304),
879            ("chroot", 161),
880            ("fchroot", 472),
881            ("pivot_root", 155),
882            ("mount", 165),
883            ("umount2", 166),
884            ("fsopen", 430),
885            ("fsconfig", 431),
886            ("fsmount", 432),
887            ("fspick", 433),
888            ("move_mount", 429),
889            ("open_tree", 428),
890            ("open_tree_attr", 467),
891            ("mount_setattr", 442),
892            ("unshare", 272),
893            ("setns", 308),
894            ("clone", 56),
895            ("clone3", 435),
896            ("uselib", 134),
897            ("acct", 163),
898            ("quotactl", 179),
899            ("quotactl_fd", 443),
900            ("swapon", 167),
901            ("swapoff", 168),
902        ]);
903        let tracked: BTreeSet<c_long> = TRACKED_SYSTEM_CALLS
904            .iter()
905            .map(|call| call.number)
906            .collect();
907        let untraceable: BTreeSet<c_long> = UNTRACEABLE_SYSTEM_CALLS
908            .iter()
909            .map(|call| call.number)
910            .collect();
911        assert_eq!(untraceable.len(), 24);
912        assert!(tracked.is_disjoint(&untraceable));
913    }
914
915    /// The known calls are those of the `x86_64` table of Linux 7.3,
916    /// `arch/x86/entry/syscalls/syscall_64.tbl`: 0 through 336, from `read` to
917    /// `uprobe`, and 424 through 472, from `pidfd_send_signal` to `fchroot`; every
918    /// tracked call and every call that marks a run is among them.
919    #[test]
920    fn known_system_calls_are_the_linux_7_3_table() {
921        assert_eq!(KNOWN_SYSTEM_CALLS, [0..=336, 424..=472]);
922        assert_eq!(libc::SYS_read, 0);
923        assert_eq!(libc::SYS_rseq, 334);
924        assert_eq!(libc::SYS_pidfd_send_signal, 424);
925        let known = |nr: c_long| {
926            KNOWN_SYSTEM_CALLS
927                .iter()
928                .any(|range| range.contains(&number(nr)))
929        };
930        for call in TRACKED_SYSTEM_CALLS.iter().chain(UNTRACEABLE_SYSTEM_CALLS) {
931            assert!(known(call.number), "{}", call.name);
932        }
933    }
934
935    /// Each call that marks a run stops for the tracer with the arguments that let
936    /// it change what a path means; `clone` and `unshare` without `CLONE_NEWNS`, and
937    /// `setns` with another namespace type, run at full speed, while `clone3` always
938    /// stops, because the filter cannot read its flags.
939    #[test]
940    fn untraceable_calls_stop_for_the_tracer() {
941        let program = program().unwrap();
942        let stop = libc::SECCOMP_RET_TRACE | u32::from(DATA_UNTRACEABLE);
943        let allow = libc::SECCOMP_RET_ALLOW;
944        let new_namespace = NEW_MOUNT_NAMESPACE;
945        let other_namespace = libc::CLONE_NEWUTS.cast_unsigned();
946        let child_signal = libc::SIGCHLD.cast_unsigned();
947        for call in UNTRACEABLE_SYSTEM_CALLS {
948            let nr = number(call.number);
949            let (marking, running): (Vec<[u32; 2]>, Vec<[u32; 2]>) = match call.name {
950                "clone" => {
951                    (
952                        vec![[new_namespace | child_signal, 0], [new_namespace, 0]],
953                        vec![[child_signal, 0], [libc::CLONE_FILES.cast_unsigned(), 0], [
954                            0,
955                            new_namespace,
956                        ]],
957                    )
958                },
959                "unshare" => {
960                    (
961                        vec![[new_namespace, 0], [new_namespace | other_namespace, 0]],
962                        vec![[0, 0], [libc::CLONE_FILES.cast_unsigned(), 0], [
963                            other_namespace,
964                            new_namespace,
965                        ]],
966                    )
967                },
968                "setns" => {
969                    (vec![[3, 0], [3, new_namespace], [u32::MAX, 0]], vec![
970                        [3, other_namespace],
971                        [new_namespace, libc::CLONE_NEWNET.cast_unsigned()],
972                    ])
973                },
974                _ => {
975                    (
976                        vec![[0, 0], [u32::MAX, u32::MAX], [new_namespace, 0]],
977                        Vec::new(),
978                    )
979                },
980            };
981            for arguments in marking {
982                assert_eq!(
983                    evaluate_with(&program, AUDIT_ARCH_X86_64, nr, arguments),
984                    stop,
985                    "{} {arguments:?}",
986                    call.name
987                );
988            }
989            for arguments in running {
990                assert_eq!(
991                    evaluate_with(&program, AUDIT_ARCH_X86_64, nr, arguments),
992                    allow,
993                    "{} {arguments:?}",
994                    call.name
995                );
996            }
997        }
998    }
999
1000    /// The numbers around the bounds of the known table: 336 runs; 337, 400 and 423
1001    /// stop as unknown; 424, 470 and 471 run; 472, `fchroot`, stops as a call that
1002    /// marks the run; 473 and 1,000,000 stop as unknown; an x32 number and a 32-bit
1003    /// call keep their own stops.
1004    #[test]
1005    fn numbers_outside_the_known_table_stop_as_unknown() {
1006        let program = program().unwrap();
1007        let unknown = libc::SECCOMP_RET_TRACE | u32::from(DATA_UNKNOWN);
1008        let untraceable = libc::SECCOMP_RET_TRACE | u32::from(DATA_UNTRACEABLE);
1009        let allow = libc::SECCOMP_RET_ALLOW;
1010        for (nr, expected) in [
1011            (336, allow),
1012            (337, unknown),
1013            (400, unknown),
1014            (423, unknown),
1015            (424, allow),
1016            (470, allow),
1017            (471, allow),
1018            (472, untraceable),
1019            (473, unknown),
1020            (1_000_000, unknown),
1021        ] {
1022            assert_eq!(
1023                evaluate(&program, AUDIT_ARCH_X86_64, nr),
1024                expected,
1025                "system call {nr}"
1026            );
1027        }
1028        let foreign = libc::SECCOMP_RET_TRACE | u32::from(DATA_FOREIGN_ARCH);
1029        let x32 = libc::SECCOMP_RET_TRACE | u32::from(DATA_X32);
1030        for nr in [400, 1_000_000] {
1031            assert_eq!(evaluate(&program, AUDIT_ARCH_I386, nr), foreign);
1032            assert_eq!(
1033                evaluate(&program, AUDIT_ARCH_X86_64, nr | X32_SYSCALL_BIT),
1034                x32
1035            );
1036        }
1037    }
1038
1039    /// Every native number up to 1,000 gets exactly its stop: `io_uring_setup`
1040    /// fails, a tracked call and a call that marks the run stop for the tracer
1041    /// (`sendto` without a destination, and `clone` and `unshare` without
1042    /// arguments, run, and `setns` with type 0 stops), every other known number
1043    /// runs, and every number outside the table stops as unknown.
1044    #[test]
1045    fn every_native_number_gets_its_stop() {
1046        let program = program().unwrap();
1047        let stop = |data: u16| libc::SECCOMP_RET_TRACE | u32::from(data);
1048        let failure = libc::SECCOMP_RET_ERRNO | libc::ENOSYS.unsigned_abs();
1049        for nr in 0..=1_000_u32 {
1050            let number = c_long::from(nr);
1051            let expected = if number == libc::SYS_io_uring_setup {
1052                failure
1053            } else if number == libc::SYS_sendto {
1054                libc::SECCOMP_RET_ALLOW
1055            } else if TRACKED_SYSTEM_CALLS
1056                .iter()
1057                .any(|call| call.number == number)
1058            {
1059                stop(DATA_TRACKED)
1060            } else if [libc::SYS_clone, libc::SYS_unshare].contains(&number) {
1061                libc::SECCOMP_RET_ALLOW
1062            } else if UNTRACEABLE_SYSTEM_CALLS
1063                .iter()
1064                .any(|call| call.number == number)
1065            {
1066                stop(DATA_UNTRACEABLE)
1067            } else if KNOWN_SYSTEM_CALLS.iter().any(|range| range.contains(&nr)) {
1068                libc::SECCOMP_RET_ALLOW
1069            } else {
1070                stop(DATA_UNKNOWN)
1071            };
1072            assert_eq!(
1073                evaluate(&program, AUDIT_ARCH_X86_64, nr),
1074                expected,
1075                "system call {nr}"
1076            );
1077        }
1078    }
1079}