Dev.to Security 🔐 Cybersecurity 👁 0 📖 11 min read

Stop Blocking Syscalls One at a Time: Practical systemd SystemCallFilter on Linux

Stop Blocking Syscalls One at a Time: Practical systemd SystemCallFilter on Linux A common bit of unit hardening looks like this: [Service] SystemCallFilter=~mount The comment usually says "no mounting". But m

Stop Blocking Syscalls One at a Time: Practical systemd SystemCallFilter on Linux

A common bit of unit hardening looks like this:

[Service]
SystemCallFilter=~mount

The comment usually says "no mounting". But mount(2) is only one entry point. Since Linux 5.2 the kernel also has fsopen(), fsconfig(), fsmount(), move_mount(), and open_tree(). A process that can call those can still assemble and attach a filesystem without ever calling mount(). The deny-list is always a kernel release behind.

The kernel's own seccomp documentation makes the same point from the other direction: an allow-list is more robust, because new system calls are denied by default until you deliberately add them. systemd exposes that as a unit option. It also exposes enough sharp edges to make a service fail in ways that look nothing like a permission problem.

This post is about the sharp edges: what the kernel checks, what systemd adds on top, and a lab you can repeat on your own machine.

What the kernel actually filters

A seccomp filter is a classic BPF program that runs on every system call. It sees a fixed struct:

struct seccomp_data {
    int   nr;                    /* syscall number */
    __u32 arch;                  /* AUDIT_ARCH_* value */
    __u64 instruction_pointer;
    __u64 args[6];               /* raw register values */
};

That is the whole input. The filter returns an action, and the kernel applies the strictest action returned by any filter attached to the thread. Filters are per-thread, inherited across fork() and preserved across execve(). Once attached, a filter cannot be removed; you can only stack more filters on top, which can only make the policy stricter.

The available actions, in decreasing order of precedence, are listed by the kernel itself:

$ cat /proc/sys/kernel/seccomp/actions_avail
kill_process kill_thread trap errno user_notif trace log allow

The important ones for service hardening:

Action What happens
kill_process Whole thread group dies with SIGSYS (Linux 4.14+)
kill_thread Only the calling thread dies
errno Syscall is skipped; userspace gets the supplied errno
log Syscall runs and an audit record is emitted
allow Syscall runs

Two limitations matter more than the action table.

First, the filter cannot dereference pointers. The kernel documentation says it plainly: "BPF programs may not dereference pointers which constrains all filters to solely evaluating the system call arguments directly." You can deny openat(2) entirely. You cannot deny opening one path.

Second, the documentation is equally clear that this is not a sandbox: "System call filtering isn't a sandbox. It provides a clearly defined mechanism for minimizing the exposed kernel surface." Path policy, network policy, and information flow belong to LSMs, namespaces, and file permissions.

What systemd adds

The unit syntax is deceptively small:

[Service]
SystemCallFilter=@system-service
SystemCallErrorNumber=EPERM

The first line is an allow-list. Every syscall not in the set is denied. Prefix the list with ~ and it becomes a deny-list instead.

A few rules are easy to miss:

  • The first assignment decides the default action. If you start with an allow-list and later add a deny-list line, the later line removes entries from the allowed set. It does not switch the unit back to allow-by-default.
  • Some calls are implicitly allowed and do not need to be listed: execve, exit, exit_group, getrlimit, rt_sigreturn, sigreturn, and the time/sleep calls. Blocking execve would make service startup impossible, so systemd handles it.
  • The default denial is a kill, not an error. The process dies with SIGSYS. SystemCallErrorNumber= changes that to an errno such as EPERM. On deny-list entries you can also override per syscall: SystemCallFilter=~ptrace:ENOSYS.
  • Groups are version-dependent. @system-service is a moving set defined by the systemd build, and @known is frozen at build time. Inspect the real set with systemd-analyze syscall-filter @system-service, not with a blog post from three releases ago.
  • Alternative ABIs are a separate door. On x86-64, the x32 ABI shares AUDIT_ARCH_X86_64 and is distinguished only by __X32_SYSCALL_BIT in the syscall number. On mixed-ABI systems, add SystemCallArchitectures=native.

One behaviour is not obvious from the manual: systemd sets no_new_privs for you. On systemd 257, a unit with only SystemCallFilter= set reports NoNewPrivs: 1 in /proc/self/status; outside the unit it is 0. That is required by the kernel for unprivileged filter installation, and it has consequences for setuid helpers later.

A lab you can repeat

These results are from Debian 13, kernel 6.12.118+deb13-amd64, systemd 257.13-1~deb13u1. The probe calls ptrace(PTRACE_TRACEME), which an ordinary unprivileged process is allowed to do:

# /tmp/probe.py
import ctypes

libc = ctypes.CDLL("libc.so.6", use_errno=True)
print(libc.ptrace(0, 0, 0, 0), ctypes.get_errno())

Baseline, outside any filter:

$ python3 /tmp/probe.py
0 0

Under an allow-list with an errno action:

$ systemd-run --user --pipe --wait --quiet \
    -p SystemCallFilter=@system-service \
    -p SystemCallErrorNumber=EPERM \
    /usr/bin/python3 /tmp/probe.py
-1 1

1 is EPERM. The call was skipped and the process survived.

Remove SystemCallErrorNumber= and the same call kills the process:

$ systemd-run --user --pipe --wait --quiet \
    -p SystemCallFilter=@system-service \
    /bin/sh -c 'python3 /tmp/probe.py; echo rc=$?'
Bad system call
rc=159

159 is 128 + 31, which is SIGSYS. The journal records the same thing more precisely:

run-p5772-i6072.service: Main process exited, code=killed, status=31/SYS

A deny-list can choose a different errno per call:

$ systemd-run --user --pipe --wait --quiet \
    -p SystemCallFilter=~ptrace:ENOSYS \
    /usr/bin/python3 /tmp/probe.py
-1 38

38 is ENOSYS. And a later assignment edits the set rather than replacing it, so this succeeds again:

$ systemd-run --user --pipe --wait --quiet \
    -p SystemCallFilter=@system-service \
    -p SystemCallFilter=ptrace \
    -p SystemCallErrorNumber=EPERM \
    /usr/bin/python3 /tmp/probe.py
0 0

That last result is the mechanism, and also a warning: an accidentally appended group can widen the policy.

Five ways this goes wrong

1. The default action looks like a crash

A service that dies at startup with status=31/SYS does not look like a security policy. It looks like a segfault, a bad binary, or an OOM kill. During rollout, set SystemCallErrorNumber=EPERM so the application logs the failed operation. Keep it if the application handles errors gracefully; switch to the default kill only when you would rather lose the process than let it continue after a violation.

2. @system-service is a floor, not a ceiling

The name suggests a minimal set. It is a reasonable baseline, not least privilege. On this systemd build, resolving the nested groups gives 394 syscall names, including 32-bit and compat variants. It still allows setuid, keyctl, unshare, setns, process_vm_readv, and execve. It also includes @aio, and @aio contains io_uring_setup, io_uring_enter, and io_uring_register.

That last detail is measurable. With io_uring enabled on the host, the same program gets a file descriptor under the filter:

$ systemd-run --user --pipe --wait --quiet \
    -p SystemCallFilter=@system-service \
    -p SystemCallErrorNumber=EPERM \
    /usr/bin/python3 -c 'import ctypes; l=ctypes.CDLL("libc.so.6", use_errno=True); b=ctypes.create_string_buffer(256); print(l.syscall(425, 1, b), ctypes.get_errno())'
3 0

425 is io_uring_setup on x86-64. This is not a bug; it is what the group says. If your threat model assumes "no asynchronous file opens", an allow-list that includes @aio does not give you that.

The same gap appears with namespaces:

$ python3 -c 'import ctypes; l=ctypes.CDLL("libc.so.6", use_errno=True); print(l.unshare(0x10000000), ctypes.get_errno())'
0 0

$ systemd-run --user --pipe --wait --quiet \
    -p SystemCallFilter=@system-service \
    -p SystemCallErrorNumber=EPERM \
    /usr/bin/python3 -c 'import ctypes; l=ctypes.CDLL("libc.so.6", use_errno=True); print(l.unshare(0x10000000), ctypes.get_errno())'
0 0

$ systemd-run --user --pipe --wait --quiet \
    -p SystemCallFilter=@system-service \
    -p RestrictNamespaces=yes \
    -p SystemCallErrorNumber=EPERM \
    /usr/bin/python3 -c 'import ctypes; l=ctypes.CDLL("libc.so.6", use_errno=True); print(l.unshare(0x10000000), ctypes.get_errno())'
-1 1

unshare(CLONE_NEWUSER) is allowed by the syscall filter and denied by RestrictNamespaces=. Seccomp answers "may this process call unshare", not "may it create a user namespace". Stack the controls.

3. A too-narrow allow-list breaks the dynamic loader

The loader needs openat, mmap, and friends before your main() runs. A filter that only contains basic I/O produces a very confusing error:

$ systemd-run --user --pipe --wait --quiet \
    -p SystemCallFilter=@basic-io \
    -p SystemCallErrorNumber=EPERM \
    /bin/echo ok
/bin/echo: error while loading shared libraries: libc.so.6: cannot open shared object file: Operation not permitted

Exit status 127, no mention of seccomp. Static binaries and shell scripts have different startup needs, so test the actual payload, not a placeholder like /bin/true.

4. The other ABI is still open

On x86-64, a 32-bit process uses a different AUDIT_ARCH value, and the x32 ABI reuses the x86-64 value with __X32_SYSCALL_BIT set. A deny-list built from native syscall numbers can be bypassed by entering through another ABI. SystemCallArchitectures=native closes that door for a native service. It is a one-line addition and it costs nothing when the service is a normal 64-bit binary.

5. Filters never loosen, and no_new_privs is permanent

Filters stack. Adding a second filter cannot re-allow a call blocked by the first; the strictest result wins. systemd also sets no_new_privs, which means setuid binaries and file capabilities can no longer elevate inside the unit. A service that shells out to sudo, su, mount, or a setuid helper will break in a way that looks like an authentication bug.

Debugging changes too. Running strace inside the unit fails because the tracer itself cannot call ptrace(2) under a filter that excludes @debug. Trace from outside the unit, or reproduce with a relaxed filter in staging.

A unit that holds up

Here is a conservative starting point for a long-running network service. It assumes the binary is native, does not use io_uring, and does not need to create namespaces:

[Unit]
Description=Notes API
After=network-online.target
Wants=network-online.target

[Service]
Type=notify
ExecStart=/usr/local/bin/notes-api
User=notes
Group=notes
WorkingDirectory=/var/lib/notes
StateDirectory=notes
RuntimeDirectory=notes

# Syscall policy
SystemCallArchitectures=native
SystemCallFilter=@system-service
SystemCallFilter=~@mount @swap @reboot @clock @module
SystemCallErrorNumber=EPERM

# Adjacent controls seccomp cannot provide
NoNewPrivileges=yes
RestrictNamespaces=yes
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes

Why the second SystemCallFilter= line if @system-service already excludes those groups? Two reasons. It documents intent in the unit itself, and it keeps the denial in place if a future systemd version folds one of those groups into the baseline. Given the first-assignment rule, the deny-list subtracts from the allow-list, which is exactly what it looks like.

SystemCallErrorNumber=EPERM is a rollout decision, not a permanent law. It makes failures visible to the application. Once the service has run through its test suite and a production cycle without unexpected EPERM, you can remove the line and let violations kill the process.

Rollout without guessing

Test the real workload under the real filter before you write the unit:

$ systemd-run --user --pipe --wait \
    -p SystemCallFilter=@system-service \
    -p SystemCallArchitectures=native \
    -p SystemCallErrorNumber=EPERM \
    /usr/local/bin/notes-api --self-test

Then verify the unit and its exposure:

$ systemd-analyze verify /etc/systemd/system/notes-api.service
$ systemd-analyze security notes-api.service

The security output is blunt about missing filters. On this host, ssh.service shows lines like:

✗ SystemCallArchitectures=       Service may execute system calls with all ABIs   0.2
✗ SystemCallFilter=~@mount       Service does not filter system calls             0.2

Those are the two lines to make disappear. Also list the actual group contents on the machine that will run the service:

$ systemd-analyze syscall-filter @system-service

If a group is missing or has changed, you will see it there, not in a journal message six hours later.

Finally, watch for the two failure signatures:

$ journalctl -u notes-api -b | grep -E 'status=31/SYS|Operation not permitted'

A 31/SYS exit is a blocked syscall under the default action. An EPERM in the application log is a blocked syscall under SystemCallErrorNumber=. Both mean the same thing; only one gives you a stack trace.

If the process is not under systemd

Sometimes you cannot move a daemon into a unit. libseccomp gives you the same kernel feature with a small C API. The program below is a launcher: it installs a deny-list, then execvp()s the real binary. That detail matters, because a filter installed by a program that immediately exits protects nothing.

#include <errno.h>
#include <stddef.h>
#include <stdio.h>
#include <unistd.h>
#include <seccomp.h>

int main(int argc, char **argv)
{
    if (argc < 2) {
        fprintf(stderr, "usage: %s program [args...]\n", argv[0]);
        return 2;
    }

    scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_ALLOW);
    if (ctx == NULL) {
        fputs("seccomp_init failed\n", stderr);
        return 1;
    }

    const char *blocked[] = { "ptrace", "mount", "umount2", "bpf", "userfaultfd" };
    for (size_t i = 0; i < sizeof blocked / sizeof blocked[0]; i++) {
        int nr = seccomp_syscall_resolve_name(blocked[i]);
        int rc = seccomp_rule_add(ctx, SCMP_ACT_ERRNO(EPERM), nr, 0);
        if (rc < 0) {
            fprintf(stderr, "rule %s: %d\n", blocked[i], rc);
            seccomp_release(ctx);
            return 1;
        }
    }

    int rc = seccomp_load(ctx);
    seccomp_release(ctx);
    if (rc < 0) {
        fprintf(stderr, "seccomp_load: %d\n", rc);
        return 1;
    }

    execvp(argv[1], &argv[1]);
    perror("execvp");
    return 1;
}

Build and use it like this:

$ cc -O2 -o install-filter install-filter.c -lseccomp
$ ./install-filter /usr/local/bin/notes-api --port 8080

Packages are libseccomp-dev on Debian and libseccomp-devel on Fedora. seccomp_load() activates the filter; the rules do nothing until then, and the filter survives the execvp(). libseccomp sets no_new_privs by default via SCMP_FLTATR_CTL_NNP, so the same setuid caveat applies.

This example is a deny-list because it targets an existing binary whose full syscall set you have not inventoried. For a new service, the systemd allow-list is the better tool.

The short version

  • Prefer SystemCallFilter=@system-service over a growing deny-list.
  • Set SystemCallArchitectures=native.
  • Use SystemCallErrorNumber=EPERM while rolling out, then decide whether you want errors or kills.
  • Verify the group contents with systemd-analyze syscall-filter on the target host.
  • Remember what seccomp cannot see: paths, pointer contents, io_uring submission entries, and namespace semantics.

Seccomp reduces the kernel surface. It does not replace file permissions, LSMs, or namespaces, and it will not save a service that was going to break anyway. Used as one layer among several, it is one of the cheapest hardening wins in a unit file.

Sources

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.