RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
Build the PDF sandbox's seccomp filter in Zig and drop libseccomp
oxydizer59b19cbce7d5
diff --git a/README.md b/README.mdindex 5d72ca9..1a27e21 100644--- a/README.md+++ b/README.md@@ -53,7 +53,7 @@ nix build github:oxydizer/rediwmRequirements: Zig 0.17, wlroots 0.20, and the development files for Wayland,wayland-protocols, xkbcommon, pixman, FreeType, HarfBuzz, Fontconfig,librsvg/GdkPixbuf, PangoCairo, libinput, PAM, libpulse, libpipewire-0.3, Poppler GLib,-libseccomp, libarchive, libjpeg, libpng, libwebp and GNU Readline.+libarchive, libjpeg, libpng, libwebp and GNU Readline.```shzig build run -- foot # nested in your current Wayland sessiondiff --git a/build/apps.zig b/build/apps.zigindex 00ff115..ee32570 100644--- a/build/apps.zig+++ b/build/apps.zig@@ -197,7 +197,6 @@ pub fn add(ctx: Context) Apps {pdf.root_module.addImport("wayland", wayland);pdf.root_module.addCSourceFile(.{ .file = b.path("src/pdf/sandbox.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });pdf.root_module.addCSourceFile(.{ .file = b.path("src/pdf/print.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });- pdf.root_module.linkSystemLibrary("seccomp", .{});inline for (.{ "wayland-client", "wayland-cursor", "poppler-glib", "cairo", "gio-2.0", "gobject-2.0", "glib-2.0", "xkbcommon" }) |lib| pdf.root_module.linkSystemLibrary(lib, .{});const install_pdf = b.addInstallArtifact(pdf, .{});const pdf_entry = b.addInstallFileWithDir(localizedData(b, i18n_tool, ctx.layout.prefix, "data/rediwm-pdf.desktop"), .prefix, "share/applications/rediwm-pdf.desktop");diff --git a/docs/agent-notes/map.md b/docs/agent-notes/map.mdindex 85b216c..1a94bc3 100644--- a/docs/agent-notes/map.md+++ b/docs/agent-notes/map.md@@ -44,7 +44,8 @@ widgets, layout, text, theme, animation), `config` (`src/config/`: parsing andsaving `config.toml`), `dbus`, `i18n`, `memory` and `protocol`(`src/ipc/protocol.zig`, the IPC wire format shared with `rediwm-msg`). Also`platform` (`src/platform/`, std only): child-process handles, directory-watching and the program's own path, the seam for other operating systems.+watching, the program's own path and syscall filters (`seccomp.zig`), the+seam for other operating systems.## Compositordiff --git a/docs/plans/freebsd.md b/docs/plans/freebsd.mdindex 467bfb8..dffdb8a 100644--- a/docs/plans/freebsd.md+++ b/docs/plans/freebsd.md@@ -47,7 +47,8 @@ translate. About 47 Zig files call `std.os.linux.*` directly.### 2. Sandboxes-The PDF sandbox (`pdf/sandbox.c`: libseccomp + Landlock) and the theme helper+The PDF sandbox (`pdf/sandbox.c` + `pdf/syscall_policy.zig`: raw BPF through+`platform/seccomp.zig`, + Landlock) and the theme helper(`theme_helper/native.c`: raw BPF + Landlock) have no FreeBSD counterpartshort of a rewrite on **Capsicum** (`cap_enter`, `cap_rights_limit` onpre-opened directory fds). The design fits, since both already preload before@@ -118,10 +119,12 @@ ReleaseSafe, `zig build test` and affected integration suites.`/proc/self/exe` readers.4. **Raw syscalls to libc** where libc has the call (fork, execve, wait4,close, read, getuid, …), keeping `std.os.linux` for what has no libc form.-5. **One sandbox interface:** move the PDF sandbox from libseccomp to the raw- BPF the theme helper already uses and give both one "restrict to these- directories" entry point. Drops a dependency; Capsicum later implements the- same entry point.+5. **One sandbox interface:** (half done) the PDF sandbox no longer uses+ libseccomp: `platform/seccomp.zig` builds and loads the filter and+ `pdf/syscall_policy.zig` holds its allow-list, checked verdict for verdict+ against the libseccomp program it replaced. Left: move the theme helper's+ C filter onto the same builder and give both one "restrict to these+ directories" entry point, which Capsicum later implements.6. **Process listing:** keep `/proc` parsing behind the system monitor'scollector interface (shared with `ipc/processes.zig`).7. **Paths:** replace fixed `/usr/bin/…` tool paths with `PATH` lookup.@@ -141,8 +144,9 @@ headless + GLES2 path works there.Split `src/platform/` into Linux and FreeBSD parts (`exe.path` can use`std.process.executablePath`, which already reads `kern.proc.pathname`);-split the translate roots; build conditions for `seccomp`,-`util`, `pam`. Hide NM, BlueZ, PPD, UDisks, app scopes; PDF and theme helper+split the translate roots; build conditions for `util`, `pam`, and for+`platform/seccomp.zig`, which is Linux-only code now that nothing links+libseccomp. Hide NM, BlueZ, PPD, UDisks, app scopes; PDF and theme helperrefuse. Goal: `rediwm` and the apps start in a seatd session and the headlessintegration suites run.diff --git a/docs/wiki/Getting-Started.md b/docs/wiki/Getting-Started.mdindex 6659c0c..078faff 100644--- a/docs/wiki/Getting-Started.md+++ b/docs/wiki/Getting-Started.md@@ -29,7 +29,7 @@ Building needs Zig 0.16 and wlroots 0.20 (`scripts/install.sh --build` builds itinto a private prefix on Debian/Ubuntu; `REDIWM_PRIVATE_WLROOTS=1` does the sameon Arch and Fedora), plus dev files for Wayland, wayland-protocols, xkbcommon,pixman, FreeType, HarfBuzz, Fontconfig, librsvg/GdkPixbuf, PangoCairo, libinput,-PAM, libpulse, libpipewire-0.3, Poppler GLib, libseccomp, libjpeg and libpng.+PAM, libpulse, libpipewire-0.3, Poppler GLib, libjpeg and libpng.```shzig build run -- foot # nested in your current Wayland sessiondiff --git a/nix/package.nix b/nix/package.nixindex 7cf57dd..1d7e4bc 100644--- a/nix/package.nix+++ b/nix/package.nix@@ -25,7 +25,6 @@pulseaudio,pipewire,poppler,- libseccomp,libarchive,libjpeg,libpng,@@ -115,7 +114,6 @@ stdenv.mkDerivation {libpulseaudiopipewirepoppler- libseccomplibarchivelibjpeglibpngdiff --git a/packaging/arch/PKGBUILD b/packaging/arch/PKGBUILDindex 680cd7f..d7df1a3 100644--- a/packaging/arch/PKGBUILD+++ b/packaging/arch/PKGBUILD@@ -22,7 +22,6 @@ depends=('libpulse''pipewire''poppler-glib'- 'libseccomp''libarchive''libjpeg-turbo''libpng'diff --git a/scripts/install.sh b/scripts/install.shindex d369def..45df74d 100755--- a/scripts/install.sh+++ b/scripts/install.sh@@ -235,7 +235,7 @@ log "Installing dependencies (needs sudo)..."case "$FAMILY" inarch)deps="wayland wayland-protocols pixman libxkbcommon \- freetype2 harfbuzz fontconfig librsvg cairo pango libinput poppler-glib libseccomp \+ freetype2 harfbuzz fontconfig librsvg cairo pango libinput poppler-glib \libarchive libwebp libpng libjpeg-turbo libpulse pipewire pam libcups mesa pkgconf git readline gcc boost libtorrent-rasterbar json-glib \xorg-xwayland xdg-desktop-portal xdg-desktop-portal-wlr xdg-desktop-portal-gtk"if [ "$PRIVATE_WLROOTS" = no ]; then@@ -259,13 +259,13 @@ case "$FAMILY" inlibxcb-res0-dev libxcb-xfixes0-dev libxcb-dri3-dev libxcb-present-dev \libxcb-render-util0-dev libxcb-shm0-dev libxcb-xinput-dev xwayland \libfreetype-dev libharfbuzz-dev libfontconfig-dev librsvg2-dev libcairo2-dev libpango1.0-dev libgdk-pixbuf-2.0-dev \- libglib2.0-dev libarchive-dev libwebp-dev libpng-dev libjpeg-dev libpulse-dev libpipewire-0.3-dev libpam0g-dev libaudit-dev libcups2-dev libgnutls28-dev libavahi-client-dev libpoppler-glib-dev libseccomp-dev libreadline-dev libtorrent-rasterbar-dev libjson-glib-dev \+ libglib2.0-dev libarchive-dev libwebp-dev libpng-dev libjpeg-dev libpulse-dev libpipewire-0.3-dev libpam0g-dev libaudit-dev libcups2-dev libgnutls28-dev libavahi-client-dev libpoppler-glib-dev libreadline-dev libtorrent-rasterbar-dev libjson-glib-dev \xdg-desktop-portal xdg-desktop-portal-wlr xdg-desktop-portal-gtk";;fedora)deps="wayland-devel wayland-protocols-devel pixman-devel libxkbcommon-devel \freetype-devel harfbuzz-devel fontconfig-devel librsvg2-devel cairo-devel pango-devel libinput-devel \- libarchive-devel libwebp-devel libpng-devel libjpeg-turbo-devel pulseaudio-libs-devel pipewire-devel pam-devel cups-devel poppler-glib-devel libseccomp-devel \+ libarchive-devel libwebp-devel libpng-devel libjpeg-turbo-devel pulseaudio-libs-devel pipewire-devel pam-devel cups-devel poppler-glib-devel \mesa-libEGL-devel mesa-libGLES-devel glibc-devel readline-devel gcc-c++ json-glib-devel \pkgconf-pkg-config git rb_libtorrent-devel \xorg-x11-server-Xwayland \@@ -282,7 +282,7 @@ case "$FAMILY" inopensuse)deps="wlroots-devel wayland-devel wayland-protocols-devel libpixman-1-0-devel libxkbcommon-devel \freetype2-devel harfbuzz-devel fontconfig-devel librsvg-devel cairo-devel pango-devel libinput-devel \- libarchive-devel libwebp-devel libpng16-devel libjpeg8-devel libpulse-devel pipewire-devel pam-devel cups-devel libpoppler-glib-devel libseccomp-devel \+ libarchive-devel libwebp-devel libpng16-devel libjpeg8-devel libpulse-devel pipewire-devel pam-devel cups-devel libpoppler-glib-devel \Mesa-libEGL-devel Mesa-libGLESv2-devel glibc-devel readline-devel gcc-c++ json-glib-devel \pkg-config git libtorrent-rasterbar-devel \xwayland \diff --git a/src/pdf/main.zig b/src/pdf/main.zigindex 6002814..3ac6074 100644--- a/src/pdf/main.zig+++ b/src/pdf/main.zig@@ -15,6 +15,11 @@ const client_input = @import("client_input.zig");const client_render = @import("client_render.zig");const client_print = @import("client_print.zig");+// `sandbox.c` calls the exported syscall policy.+comptime {+ _ = @import("syscall_policy.zig");+}+const a = std.heap.c_allocator;pub const CSD_TITLEBAR_H: i32 = 32;diff --git a/src/pdf/sandbox.c b/src/pdf/sandbox.cindex 0fe3e8b..7c6533d 100644--- a/src/pdf/sandbox.c+++ b/src/pdf/sandbox.c@@ -6,8 +6,6 @@#include <fcntl.h>#include <iconv.h>#include <linux/landlock.h>-#include <sched.h>-#include <seccomp.h>#include <stdint.h>#include <stdlib.h>#include <string.h>@@ -119,72 +117,8 @@ static int filesystem_policy(void) {return rc;}-static int syscall_policy(int display) {- scmp_filter_ctx filter = seccomp_init(SCMP_ACT_ERRNO(EPERM));- if (!filter) return -1;- int rc = seccomp_attr_set(filter, SCMP_FLTATR_CTL_TSYNC, 1);- if (rc < 0) goto done;- // File opens are checked by Landlock. No exec, fork, socket/connect,- // ptrace, process_vm_*, pidfd, io_uring, BPF, keyring, mount or general- // ioctl/prctl is allowed. Unsupported/new syscalls are denied as well.- const int allowed[] = {- SCMP_SYS(read), SCMP_SYS(write), SCMP_SYS(readv), SCMP_SYS(writev),- SCMP_SYS(pread64), SCMP_SYS(lseek), SCMP_SYS(close), SCMP_SYS(dup),- SCMP_SYS(dup2), SCMP_SYS(dup3), SCMP_SYS(open), SCMP_SYS(openat),- SCMP_SYS(fstat), SCMP_SYS(fstatfs), SCMP_SYS(newfstatat), SCMP_SYS(stat), SCMP_SYS(lstat),- SCMP_SYS(statx), SCMP_SYS(access), SCMP_SYS(faccessat), SCMP_SYS(faccessat2),- SCMP_SYS(readlink), SCMP_SYS(readlinkat), SCMP_SYS(getdents64),- SCMP_SYS(mmap), SCMP_SYS(mprotect), SCMP_SYS(munmap), SCMP_SYS(mremap),- SCMP_SYS(madvise), SCMP_SYS(brk), SCMP_SYS(mlock), SCMP_SYS(munlock),- SCMP_SYS(futex), SCMP_SYS(futex_waitv), SCMP_SYS(set_robust_list), SCMP_SYS(rseq),- SCMP_SYS(sched_yield), SCMP_SYS(sched_getaffinity),- SCMP_SYS(rt_sigaction), SCMP_SYS(rt_sigprocmask), SCMP_SYS(rt_sigreturn),- SCMP_SYS(sigaltstack), SCMP_SYS(getpid), SCMP_SYS(gettid),- SCMP_SYS(getuid), SCMP_SYS(geteuid), SCMP_SYS(getgid), SCMP_SYS(getegid),- SCMP_SYS(clock_gettime), SCMP_SYS(gettimeofday), SCMP_SYS(clock_nanosleep),- SCMP_SYS(nanosleep), SCMP_SYS(time), SCMP_SYS(uname), SCMP_SYS(getrandom),- SCMP_SYS(poll), SCMP_SYS(ppoll), SCMP_SYS(select), SCMP_SYS(pselect6),- SCMP_SYS(eventfd2), SCMP_SYS(pipe2), SCMP_SYS(ftruncate),- SCMP_SYS(exit), SCMP_SYS(exit_group), SCMP_SYS(restart_syscall),- };- for (unsigned i = 0; i < sizeof(allowed) / sizeof(allowed[0]); i++) {- // Some legacy syscalls are absent on other native architectures.- // Skipping their pseudo-numbers leaves the default denial intact.- if (allowed[i] < 0) continue;- rc = seccomp_rule_add(filter, SCMP_ACT_ALLOW, allowed[i], 0);- if (rc < 0) goto done;- }- const int commands[] = { F_GETFD, F_SETFD, F_GETFL, F_SETFL, F_DUPFD_CLOEXEC, F_GET_SEALS, F_ADD_SEALS };- for (unsigned i = 0; i < sizeof(commands) / sizeof(commands[0]); i++) {- rc = seccomp_rule_add(filter, SCMP_ACT_ALLOW, SCMP_SYS(fcntl), 1, SCMP_A1(SCMP_CMP_EQ, commands[i], 0));- if (rc < 0) goto done;- }- rc = seccomp_rule_add(filter, SCMP_ACT_ALLOW, SCMP_SYS(memfd_create), 1,- SCMP_A1(SCMP_CMP_MASKED_EQ, ~3ULL, 0));- if (rc < 0) goto done;- // glibc retries pthread_create with clone when clone3 returns ENOSYS.- rc = seccomp_rule_add(filter, SCMP_ACT_ERRNO(ENOSYS), SCMP_SYS(clone3), 0);- if (rc < 0) goto done;- const unsigned thread_flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |- CLONE_THREAD | CLONE_SYSVSEM | CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID;- rc = seccomp_rule_add(filter, SCMP_ACT_ALLOW, SCMP_SYS(clone), 1,- SCMP_A0(SCMP_CMP_EQ, thread_flags, 0));- if (rc < 0) goto done;- rc = seccomp_rule_add(filter, SCMP_ACT_ALLOW, SCMP_SYS(tgkill), 1,- SCMP_A0(SCMP_CMP_EQ, getpid(), 0));- if (rc < 0) goto done;- rc = seccomp_rule_add(filter, SCMP_ACT_ALLOW, SCMP_SYS(sendmsg), 1,- SCMP_A0(SCMP_CMP_EQ, display, 0));- if (rc < 0) goto done;- rc = seccomp_rule_add(filter, SCMP_ACT_ALLOW, SCMP_SYS(recvmsg), 1,- SCMP_A0(SCMP_CMP_EQ, display, 0));- if (rc < 0) goto done;- rc = seccomp_load(filter);-done:- seccomp_release(filter);- if (rc < 0) { errno = -rc; return -1; }- return 0;-}+// The syscall allow-list is built and loaded in syscall_policy.zig.+extern int rediwm_pdf_syscall_policy(int display);// `print` is the print helper's socket (see print.c), or -1. The viewer// may only read and write bytes on it: sendmsg is limited to `display`, so@@ -225,5 +159,5 @@ int rediwm_pdf_sandbox_enter(int document, int display, int print) {setrlimit(RLIMIT_NOFILE, &files) < 0 || prctl(PR_SET_DUMPABLE, 0) < 0 ||prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) return -1;if (filesystem_policy() < 0) return -1;- return syscall_policy(display);+ return rediwm_pdf_syscall_policy(display);}diff --git a/src/pdf/syscall_policy.zig b/src/pdf/syscall_policy.zignew file mode 100644index 0000000..48e42df--- /dev/null+++ b/src/pdf/syscall_policy.zig@@ -0,0 +1,132 @@+//! The PDF parser's syscall policy, loaded by `sandbox.c` after the filesystem+//! policy. File opens are checked by Landlock. No exec, fork, socket/connect,+//! ptrace, process_vm_*, pidfd, io_uring, BPF, keyring, mount or general+//! ioctl/prctl is allowed. Unsupported and new syscalls are denied as well.+const std = @import("std");+const linux = std.os.linux;+const seccomp = @import("platform").seccomp;++const allowed = [_][]const u8{+ "read", "write", "readv", "writev",+ "pread64", "lseek", "close", "dup",+ "dup3", "openat", "fstat", "fstatfs",+ "newfstatat", "statx", "faccessat", "faccessat2",+ "readlinkat", "getdents64", "mmap", "mprotect",+ "munmap", "mremap", "madvise", "brk",+ "mlock", "munlock", "futex", "futex_waitv",+ "set_robust_list", "rseq", "sched_yield", "sched_getaffinity",+ "rt_sigaction", "rt_sigprocmask", "rt_sigreturn", "sigaltstack",+ "getpid", "gettid", "getuid", "geteuid",+ "getgid", "getegid", "clock_gettime", "gettimeofday",+ "clock_nanosleep", "nanosleep", "uname", "getrandom",+ "ppoll", "pselect6", "eventfd2", "pipe2",+ "ftruncate", "exit", "exit_group", "restart_syscall",+};++/// Calls newer architectures dropped; absent there, the default denial stands.+const legacy = [_][]const u8{+ "dup2", "open", "stat", "lstat", "access", "readlink", "poll", "select", "time",+};++const fcntl_commands = [_]u32{+ linux.F.GETFD, linux.F.SETFD, linux.F.GETFL, linux.F.SETFL,+ linux.F.DUPFD_CLOEXEC, linux.F.GET_SEALS, linux.F.ADD_SEALS,+};++/// What a `pthread_create` passes to clone.+const thread_flags: u64 = linux.CLONE.VM | linux.CLONE.FS | linux.CLONE.FILES | linux.CLONE.SIGHAND |+ linux.CLONE.THREAD | linux.CLONE.SYSVSEM | linux.CLONE.SETTLS | linux.CLONE.PARENT_SETTID |+ linux.CLONE.CHILD_CLEARTID;++/// The program for a process `pid` whose only socket is `display`.+pub fn program(buf: []seccomp.Insn, display: u64, pid: u64) seccomp.Builder.Error![]const seccomp.Insn {+ var b = try seccomp.Builder.init(buf);+ inline for (allowed) |name| {+ const nr = comptime seccomp.number(name) orelse @compileError("no syscall " ++ name);+ try b.rule(nr, seccomp.allow);+ }+ inline for (legacy) |name| {+ if (comptime seccomp.number(name)) |nr| try b.rule(nr, seccomp.allow);+ }+ for (fcntl_commands) |command| {+ try b.ruleArg(seccomp.number("fcntl").?, seccomp.allow, .{ .index = 1, .value = command });+ }+ // MFD_CLOEXEC and MFD_ALLOW_SEALING only.+ try b.ruleArg(seccomp.number("memfd_create").?, seccomp.allow, .{ .index = 1, .value = 0, .mask = ~@as(u64, 3) });+ // glibc retries pthread_create with clone when clone3 returns ENOSYS.+ try b.rule(seccomp.number("clone3").?, seccomp.errno(.NOSYS));+ try b.ruleArg(seccomp.number("clone").?, seccomp.allow, .{ .index = 0, .value = thread_flags });+ try b.ruleArg(seccomp.number("tgkill").?, seccomp.allow, .{ .index = 0, .value = pid });+ try b.ruleArg(seccomp.number("sendmsg").?, seccomp.allow, .{ .index = 0, .value = display });+ try b.ruleArg(seccomp.number("recvmsg").?, seccomp.allow, .{ .index = 0, .value = display });+ return b.finish(seccomp.errno(.PERM));+}++fn install(display: c_int) !void {+ var buf: [512]seccomp.Insn = undefined;+ const fd = std.math.cast(u64, display) orelse return error.BadDescriptor;+ const pid = std.math.cast(u64, linux.getpid()) orelse return error.BadDescriptor;+ try seccomp.install(try program(&buf, fd, pid));+}++/// Called by `sandbox.c` once the filesystem policy is in place: 0 or -1.+export fn rediwm_pdf_syscall_policy(display: c_int) c_int {+ install(display) catch return -1;+ return 0;+}++const Call = linux.SECCOMP.data;++fn call(nr: u32, args: [6]u64) Call {+ return .{+ .nr = @bitCast(nr),+ .arch = seccomp.audit_arch,+ .instruction_pointer = 0,+ .arg0 = args[0],+ .arg1 = args[1],+ .arg2 = args[2],+ .arg3 = args[3],+ .arg4 = args[4],+ .arg5 = args[5],+ };+}++test "policy allows the parser's calls and its two descriptors, nothing else" {+ var buf: [512]seccomp.Insn = undefined;+ const display: u64 = 7;+ const pid: u64 = 4242;+ const p = try program(&buf, display, pid);+ const none: [6]u64 = @splat(0);+ const deny = seccomp.errno(.PERM);++ try std.testing.expectEqual(seccomp.allow, seccomp.evaluate(p, call(seccomp.number("read").?, none)));+ try std.testing.expectEqual(seccomp.allow, seccomp.evaluate(p, call(seccomp.number("futex").?, none)));+ inline for ([_][]const u8{ "socket", "connect", "execve", "ptrace", "io_uring_setup", "pidfd_open", "process_vm_readv", "kill", "ioctl", "prctl" }) |name| {+ try std.testing.expectEqual(deny, seccomp.evaluate(p, call(seccomp.number(name).?, none)));+ }++ const fcntl = seccomp.number("fcntl").?;+ try std.testing.expectEqual(seccomp.allow, seccomp.evaluate(p, call(fcntl, .{ 3, linux.F.ADD_SEALS, 0, 0, 0, 0 })));+ try std.testing.expectEqual(deny, seccomp.evaluate(p, call(fcntl, .{ 3, linux.F.SETOWN, 0, 0, 0, 0 })));++ const memfd = seccomp.number("memfd_create").?;+ try std.testing.expectEqual(seccomp.allow, seccomp.evaluate(p, call(memfd, .{ 0, 3, 0, 0, 0, 0 })));+ try std.testing.expectEqual(deny, seccomp.evaluate(p, call(memfd, .{ 0, 4, 0, 0, 0, 0 })));++ const clone = seccomp.number("clone").?;+ try std.testing.expectEqual(seccomp.allow, seccomp.evaluate(p, call(clone, .{ thread_flags, 0, 0, 0, 0, 0 })));+ try std.testing.expectEqual(deny, seccomp.evaluate(p, call(clone, .{ thread_flags & ~@as(u64, linux.CLONE.VM), 0, 0, 0, 0, 0 })));+ try std.testing.expectEqual(seccomp.errno(.NOSYS), seccomp.evaluate(p, call(seccomp.number("clone3").?, none)));++ const tgkill = seccomp.number("tgkill").?;+ try std.testing.expectEqual(seccomp.allow, seccomp.evaluate(p, call(tgkill, .{ pid, 0, 0, 0, 0, 0 })));+ try std.testing.expectEqual(deny, seccomp.evaluate(p, call(tgkill, .{ pid + 1, 0, 0, 0, 0, 0 })));++ // Only the compositor's socket may carry bytes, and only it.+ inline for ([_][]const u8{ "sendmsg", "recvmsg" }) |name| {+ const nr = seccomp.number(name).?;+ try std.testing.expectEqual(seccomp.allow, seccomp.evaluate(p, call(nr, .{ display, 0, 0, 0, 0, 0 })));+ try std.testing.expectEqual(deny, seccomp.evaluate(p, call(nr, .{ display + 1, 0, 0, 0, 0, 0 })));+ try std.testing.expectEqual(deny, seccomp.evaluate(p, call(nr, .{ display | (1 << 32), 0, 0, 0, 0, 0 })));+ }+}diff --git a/src/pdf_tests.zig b/src/pdf_tests.zigindex 1d8faa0..da726e8 100644--- a/src/pdf_tests.zig+++ b/src/pdf_tests.zig@@ -6,6 +6,10 @@ const selection = @import("pdf/selection.zig");const cache = @import("pdf/cache.zig");const worker = @import("pdf/worker.zig");+test {+ _ = @import("pdf/syscall_policy.zig");+}+const testing = std.testing;const a = testing.allocator;diff --git a/src/platform/AGENTS.md b/src/platform/AGENTS.mdindex 1bcbae3..e02f68d 100644--- a/src/platform/AGENTS.md+++ b/src/platform/AGENTS.md@@ -1,8 +1,8 @@# Platform moduleThe one place the OS shows: child handles (`child.zig`), directory watching-(`watch.zig`), the program's own path (`exe.zig`), and `child.h`/`self_exe.h`-for C and C++. Std only, no compositor imports. Linux today; the FreeBSD port+(`watch.zig`), the program's own path (`exe.zig`), seccomp-BPF filters+(`seccomp.zig`), and `child.h`/`self_exe.h` for C and C++. Std only, no compositor imports. Linux today; the FreeBSD port(`docs/plans/freebsd.md`) adds `freebsd_*.zig` parts without changing callers.* **A `Handle` is not a pid.** Hold it for as long as you may signal; a bare@@ -17,6 +17,19 @@ for C and C++. Std only, no compositor imports. Linux today; the FreeBSD port`moved_to` over `modified` (often half-written).* `drain` returning `error.Broken` means stop using the watcher. Callbacks mayadd watches, not call `drain`. Event names are valid only in the callback.+* **Seccomp filters are built, not linked** (no libseccomp): `Builder` takes a+ caller-owned buffer, so a program can be built after the filesystem is closed+ and nothing allocates. Rules match in order; `ruleArg` compares all 64 bits+ and falls through on a mismatch. The header kills a foreign arch and an x32+ number, but not -1 (a tracer's skip number: it gets the default action, as+ libseccomp did). Use `seccomp.number("name")` (null where an architecture+ dropped the call) and keep optional legacy names in a separate list from+ required ones, so a typo is a compile error and not a silent hole. Load with+ `install` only after `PR_SET_NO_NEW_PRIVS`, single-threaded; it goes through+ libc `syscall()` so `tests/pdf_sandbox_hook.c` can fail it. `linux.AUDIT.ARCH`+ does not compile in Zig 0.17: use `seccomp.audit_arch`. A policy change is+ checked by evaluating both programs over all numbers and argument samples+ (`seccomp.evaluate`), not by trusting a read.* Nothing here arms a timer or starts a thread; a caller retrying a failed`add` owns that clock.diff --git a/src/platform/mod.zig b/src/platform/mod.zigindex 615972b..2c51865 100644--- a/src/platform/mod.zig+++ b/src/platform/mod.zig@@ -1,5 +1,6 @@//! Everything that differs between operating systems, behind one interface:-//! child processes, file-change notification and the program's own path.+//! child processes, file-change notification, the program's own path and+//! syscall filters.//! Callers never test the OS; `std.os.linux` is used only in here (see//! `AGENTS.md` beside this file). No compositor imports.pub const child = @import("child.zig");@@ -7,9 +8,11 @@ pub const exe = @import("exe.zig");pub const power_supply = @import("power_supply.zig");pub const charge_limit = @import("charge_limit.zig");pub const watch = @import("watch.zig");+pub const seccomp = @import("seccomp.zig");test {_ = child;_ = exe;_ = watch;+ _ = @import("seccomp_tests.zig");}diff --git a/src/platform/seccomp.zig b/src/platform/seccomp.zignew file mode 100644index 0000000..3a6fc7d--- /dev/null+++ b/src/platform/seccomp.zig@@ -0,0 +1,192 @@+//! Seccomp-BPF filters without libseccomp: a builder for the small linear+//! programs the sandboxes need, a reference evaluator for tests, and the call+//! that loads one. Linux only; the FreeBSD port restricts with Capsicum+//! behind the same kind of entry point (`docs/plans/freebsd.md`).+//!+//! A program is the header, then one block per rule in the order they were+//! added (the first match wins), then the default action. The header kills+//! the process for a foreign architecture and, on x86-64, for an x32 number+//! (it shares the audit arch; its numbers carry bit 30; -1 is exempt, see+//! `Builder.init`). No allocation: the+//! caller owns the instruction buffer, so a program can be built after the+//! filesystem has been closed.+const std = @import("std");+const builtin = @import("builtin");+const linux = std.os.linux;+const SECCOMP = linux.SECCOMP;++/// One classic-BPF instruction (`struct sock_filter`).+pub const Insn = extern struct { code: u16, jt: u8, jf: u8, k: u32 };++const SockFprog = extern struct { len: u16, filter: [*]const Insn };++comptime {+ std.debug.assert(@sizeOf(Insn) == 8);+}++// BPF_LD|BPF_W|BPF_ABS, BPF_ALU|BPF_AND|BPF_K, BPF_JMP|BPF_JEQ|BPF_K,+// BPF_JMP|BPF_JGE|BPF_K, BPF_RET|BPF_K.+const ld_abs: u16 = 0x20;+const and_k: u16 = 0x54;+const jeq_k: u16 = 0x15;+const jge_k: u16 = 0x35;+const ret_k: u16 = 0x06;++/// The kernel refuses longer programs.+pub const max_insns = 4096;++const x32_bit: u32 = 0x40000000;+const x32_abi = switch (builtin.abi) {+ .gnux32, .muslx32 => true,+ else => false,+};++/// The kernel's `AUDIT_ARCH_*` for this build: the machine, plus the 64-bit+/// and little-endian flags. (`linux.AUDIT.ARCH` does not compile in Zig 0.17.)+pub const audit_arch: u32 = blk: {+ const em = std.elf.EM;+ const bits64: u32 = 0x80000000;+ const le: u32 = 0x40000000;+ break :blk switch (builtin.cpu.arch) {+ .x86_64 => @as(u32, @backingInt(em.X86_64)) | bits64 | le,+ .aarch64 => @as(u32, @backingInt(em.AARCH64)) | bits64 | le,+ .riscv64 => @as(u32, @backingInt(em.RISCV)) | bits64 | le,+ .loongarch64 => @as(u32, @backingInt(em.LOONGARCH)) | bits64 | le,+ .powerpc64le => @as(u32, @backingInt(em.PPC64)) | bits64 | le,+ .s390x => @as(u32, @backingInt(em.S390)) | bits64,+ else => @compileError("no seccomp audit arch for this target"),+ };+};++const little = builtin.cpu.arch.endian() == .little;+const nr_offset: u32 = @offsetOf(SECCOMP.data, "nr");+const arch_offset: u32 = @offsetOf(SECCOMP.data, "arch");++fn argOffset(index: u3, high: bool) u32 {+ const base: u32 = @offsetOf(SECCOMP.data, "arg0") + 8 * @as(u32, index);+ return base + if (high == little) @as(u32, 4) else 0;+}++/// What a call gets: the filter's verdicts.+pub const allow: u32 = SECCOMP.RET.ALLOW;+pub const kill_process: u32 = SECCOMP.RET.KILL_PROCESS;++pub fn errno(code: linux.E) u32 {+ return SECCOMP.RET.ERRNO | @as(u32, @backingInt(code));+}++/// The number of syscall `name` on this architecture, or null where it does+/// not exist (the legacy calls newer architectures dropped).+pub fn number(comptime name: []const u8) ?u32 {+ if (!@hasField(linux.SYS, name)) return null;+ return @intCast(@backingInt(@field(linux.SYS, name)));+}++/// A condition on one argument: `(argument & mask) == value`, over all 64 bits.+pub const Arg = struct {+ index: u3,+ value: u64,+ mask: u64 = std.math.maxInt(u64),+};++pub const Builder = struct {+ buf: []Insn,+ len: usize = 0,++ pub const Error = error{ProgramTooLarge};++ pub fn init(buf: []Insn) Error!Builder {+ var self = Builder{ .buf = buf };+ try self.push(.{ .code = ld_abs, .jt = 0, .jf = 0, .k = arch_offset });+ try self.push(.{ .code = jeq_k, .jt = 1, .jf = 0, .k = audit_arch });+ try self.push(.{ .code = ret_k, .jt = 0, .jf = 0, .k = kill_process });+ try self.push(.{ .code = ld_abs, .jt = 0, .jf = 0, .k = nr_offset });+ if (builtin.cpu.arch == .x86_64 and !x32_abi) {+ // -1 is no x32 call but what a tracer writes to skip one: it is+ // just an unknown number here and gets the default action.+ try self.push(.{ .code = jge_k, .jt = 0, .jf = 2, .k = x32_bit });+ try self.push(.{ .code = jeq_k, .jt = 1, .jf = 0, .k = std.math.maxInt(u32) });+ try self.push(.{ .code = ret_k, .jt = 0, .jf = 0, .k = kill_process });+ }+ return self;+ }++ /// Calls to syscall `nr` get `action`.+ pub fn rule(self: *Builder, nr: u32, action: u32) Error!void {+ try self.push(.{ .code = jeq_k, .jt = 0, .jf = 1, .k = nr });+ try self.push(.{ .code = ret_k, .jt = 0, .jf = 0, .k = action });+ }++ /// Calls to syscall `nr` whose argument matches `arg` get `action`; any+ /// other call to it falls through to the next rule, so several of these+ /// for one syscall are alternatives.+ pub fn ruleArg(self: *Builder, nr: u32, action: u32, arg: Arg) Error!void {+ std.debug.assert(arg.index < 6);+ const skip = self.len;+ try self.push(.{ .code = jeq_k, .jt = 0, .jf = 0, .k = nr });+ var mismatch: [2]usize = undefined;+ const offsets = [2]u32{ argOffset(arg.index, false), argOffset(arg.index, true) };+ const values = [2]u64{ arg.value, arg.value >> 32 };+ const masks = [2]u64{ arg.mask, arg.mask >> 32 };+ for (&mismatch, offsets, values, masks) |*at, offset, value, mask| {+ try self.push(.{ .code = ld_abs, .jt = 0, .jf = 0, .k = offset });+ const word: u32 = @truncate(mask);+ if (word != std.math.maxInt(u32)) try self.push(.{ .code = and_k, .jt = 0, .jf = 0, .k = word });+ at.* = self.len;+ try self.push(.{ .code = jeq_k, .jt = 0, .jf = 0, .k = @truncate(value) });+ }+ try self.push(.{ .code = ret_k, .jt = 0, .jf = 0, .k = action });+ // The accumulator held the number; later rules compare it again.+ const restore = self.len;+ try self.push(.{ .code = ld_abs, .jt = 0, .jf = 0, .k = nr_offset });+ for (mismatch) |at| try self.jumpTo(at, restore);+ try self.jumpTo(skip, self.len);+ }++ /// The finished program: every call no rule matched gets `default`.+ pub fn finish(self: *Builder, default: u32) Error![]const Insn {+ try self.push(.{ .code = ret_k, .jt = 0, .jf = 0, .k = default });+ return self.buf[0..self.len];+ }++ fn push(self: *Builder, insn: Insn) Error!void {+ if (self.len == self.buf.len or self.len == max_insns) return error.ProgramTooLarge;+ self.buf[self.len] = insn;+ self.len += 1;+ }++ /// Makes the jump at `at` go to `target` when its comparison fails.+ fn jumpTo(self: *Builder, at: usize, target: usize) Error!void {+ self.buf[at].jf = std.math.cast(u8, target - (at + 1)) orelse return error.ProgramTooLarge;+ }+};++/// What `program` returns for a call, as the kernel would run it. For tests.+pub fn evaluate(program: []const Insn, call: SECCOMP.data) u32 {+ const bytes = std.mem.asBytes(&call);+ var acc: u32 = 0;+ var pc: usize = 0;+ while (true) : (pc += 1) {+ const insn = program[pc];+ switch (insn.code) {+ ld_abs => acc = std.mem.readInt(u32, bytes[insn.k..][0..4], builtin.cpu.arch.endian()),+ and_k => acc &= insn.k,+ jeq_k => pc += if (acc == insn.k) insn.jt else insn.jf,+ jge_k => pc += if (acc >= insn.k) insn.jt else insn.jf,+ ret_k => return insn.k,+ else => unreachable,+ }+ }+}++// Through libc rather than `linux.seccomp` so a test can interpose the call.+extern "c" fn syscall(number: c_long, ...) c_long;++/// Loads `program` on every thread of the process. The caller has set+/// `PR_SET_NO_NEW_PRIVS`, and the process is single-threaded, so nothing+/// escapes the filter by already running elsewhere.+pub fn install(program: []const Insn) error{InstallFailed}!void {+ const prog = SockFprog{ .len = @intCast(program.len), .filter = program.ptr };+ const rc = syscall(@backingInt(linux.SYS.seccomp), @as(c_long, SECCOMP.SET_MODE_FILTER), @as(c_long, SECCOMP.FILTER_FLAG.TSYNC), @intFromPtr(&prog));+ if (rc != 0) return error.InstallFailed;+}diff --git a/src/platform/seccomp_tests.zig b/src/platform/seccomp_tests.zignew file mode 100644index 0000000..cb9e5c1--- /dev/null+++ b/src/platform/seccomp_tests.zig@@ -0,0 +1,81 @@+const std = @import("std");+const builtin = @import("builtin");+const linux = std.os.linux;+const seccomp = @import("seccomp.zig");++const testing = std.testing;+const Call = linux.SECCOMP.data;++fn call(nr: u32, arg0: u64, arg1: u64) Call {+ return .{+ .nr = @bitCast(nr),+ .arch = seccomp.audit_arch,+ .instruction_pointer = 0,+ .arg0 = arg0,+ .arg1 = arg1,+ .arg2 = 0,+ .arg3 = 0,+ .arg4 = 0,+ .arg5 = 0,+ };+}++const deny = seccomp.errno(.PERM);++test "listed calls get their action and everything else the default" {+ var buf: [32]seccomp.Insn = undefined;+ var b = try seccomp.Builder.init(&buf);+ try b.rule(10, seccomp.allow);+ try b.rule(11, seccomp.errno(.NOSYS));+ const p = try b.finish(deny);+ try testing.expectEqual(seccomp.allow, seccomp.evaluate(p, call(10, 0, 0)));+ try testing.expectEqual(seccomp.errno(.NOSYS), seccomp.evaluate(p, call(11, 0, 0)));+ try testing.expectEqual(deny, seccomp.evaluate(p, call(12, 0, 0)));+}++test "a foreign architecture or an x32 number kills the process" {+ var buf: [32]seccomp.Insn = undefined;+ var b = try seccomp.Builder.init(&buf);+ try b.rule(10, seccomp.allow);+ const p = try b.finish(deny);+ var foreign = call(10, 0, 0);+ foreign.arch = foreign.arch ^ 1;+ try testing.expectEqual(seccomp.kill_process, seccomp.evaluate(p, foreign));+ if (builtin.cpu.arch == .x86_64) {+ try testing.expectEqual(seccomp.kill_process, seccomp.evaluate(p, call(10 | 0x40000000, 0, 0)));+ // A tracer's "skip this call" number is only an unknown call.+ try testing.expectEqual(deny, seccomp.evaluate(p, call(0xffffffff, 0, 0)));+ }+}++test "argument rules compare all 64 bits and fall through to the next rule" {+ var buf: [64]seccomp.Insn = undefined;+ var b = try seccomp.Builder.init(&buf);+ // Alternatives for one syscall, then a plain rule after them: the+ // accumulator must hold the number again after a failed comparison.+ try b.ruleArg(20, seccomp.allow, .{ .index = 1, .value = 5 });+ try b.ruleArg(20, seccomp.allow, .{ .index = 1, .value = 0x1_0000_0006 });+ try b.ruleArg(21, seccomp.allow, .{ .index = 0, .value = 0, .mask = ~@as(u64, 3) });+ try b.rule(22, seccomp.allow);+ const p = try b.finish(deny);+ try testing.expectEqual(seccomp.allow, seccomp.evaluate(p, call(20, 9, 5)));+ try testing.expectEqual(seccomp.allow, seccomp.evaluate(p, call(20, 9, 0x1_0000_0006)));+ try testing.expectEqual(deny, seccomp.evaluate(p, call(20, 5, 6)));+ // The high word differs from either alternative.+ try testing.expectEqual(deny, seccomp.evaluate(p, call(20, 9, 0x2_0000_0005)));+ try testing.expectEqual(seccomp.allow, seccomp.evaluate(p, call(21, 3, 0)));+ try testing.expectEqual(deny, seccomp.evaluate(p, call(21, 4, 0)));+ try testing.expectEqual(deny, seccomp.evaluate(p, call(21, 1 << 40, 0)));+ try testing.expectEqual(seccomp.allow, seccomp.evaluate(p, call(22, 99, 99)));+}++test "a program that does not fit is an error, not a truncation" {+ var small: [8]seccomp.Insn = undefined;+ var b = try seccomp.Builder.init(&small);+ var failed = false;+ for (0..8) |n| b.rule(@intCast(n), seccomp.allow) catch {+ failed = true;+ };+ try testing.expect(failed);+ try testing.expectError(error.ProgramTooLarge, b.finish(deny));+}diff --git a/tests/pdf_sandbox_hook.c b/tests/pdf_sandbox_hook.cindex 2cf2ea9..55c39f7 100644--- a/tests/pdf_sandbox_hook.c+++ b/tests/pdf_sandbox_hook.c@@ -5,8 +5,8 @@#include <errno.h>#include <fcntl.h>#include <limits.h>-#include <seccomp.h>#include <signal.h>+#include <stdarg.h>#include <stdbool.h>#include <stdio.h>#include <stdlib.h>@@ -52,11 +52,18 @@ struct wl_display *wl_display_connect_to_fd(int fd) {return filtered_display;}-int seccomp_load(scmp_filter_ctx context) {- if (fail_policy) return -EPERM;- int (*real)(scmp_filter_ctx) = dlsym(RTLD_NEXT, "seccomp_load");+// The sandbox loads its filter through libc's syscall(). Fail that one call+// when the test asks for a failed policy; forward every other.+long syscall(long number, ...) {+ long args[6];+ va_list ap;+ va_start(ap, number);+ for (int i = 0; i < 6; i++) args[i] = va_arg(ap, long);+ va_end(ap);+ if (fail_policy && number == SYS_seccomp) { errno = EPERM; return -1; }+ long (*real)(long, ...) = (long (*)(long, ...))dlsym(RTLD_NEXT, "syscall");CHECK(real);- return real(context);+ return real(number, args[0], args[1], args[2], args[3], args[4], args[5]);}static bool denied(int rc) {