Skip to content
systemcoding.dev
Security

Write a seccomp Filter With libseccomp

Build a default-deny seccomp allow-list in C with libseccomp, add an argument rule that limits write to one file descriptor, and inspect the generated BPF.

6 min read
Summarize in AI
Flat illustration of a shield with a lock, a key and a password field, with the Linux, C and Rust logos.

Writing a seccomp filter in raw BPF works, and the post on writing one by hand shows what the instructions mean. It is also the wrong tool for a real program. You have to track architecture numbers, compute jump offsets, and redo it when you add a call. libseccomp is the library that does that bookkeeping: you describe rules in C, and it emits the BPF for the target architecture. This post builds a default-deny allow-list with libseccomp 2.5.5, adds an argument rule, and shows how to dump what it generated. It assumes you have read seccomp-bpf explained and know the return actions. The API is documented in the seccomp_init(3), seccomp_rule_add(3) and seccomp_load(3) man pages of the project at github.com/seccomp/libseccomp.

The four calls you need

A libseccomp filter has a short life cycle.

  1. seccomp_init(default_action) returns a context whose default action applies to every call you do not mention.

  2. seccomp_rule_add(ctx, action, syscall, arg_count, ...) adds one rule, optionally with argument comparisons.

  3. seccomp_load(ctx) compiles the rules and installs the filter, after setting no_new_privs for you unless you turned that off.

  4. seccomp_release(ctx) frees the context.

All of them return 0 on success and a negative errno value on failure, except seccomp_init, which returns a context pointer or NULL. Always check the returns. A filter that failed to load while the program carries on is the worst kind of security bug, because everything seems fine.

System calls are named with the SCMP_SYS() macro, which resolves to the right number for the architecture the library was built for. SCMP_SYS(write) is better than __NR_write because it also handles the multi-architecture case through seccomp_arch_add().

A default-deny example

This program loads a filter, then shows that a call outside the list fails while a call on it works. It avoids stdio after the filter is loaded, because printf can call system calls you did not list (such as fstat or brk on first use), and a default-deny filter would then break the output in a confusing way.

jail.cc
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <seccomp.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

static void say(const char *s) {
    (void)!write(STDOUT_FILENO, s, strlen(s));
}

int main(void) {
    scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_ERRNO(EPERM));
    if (ctx == NULL) return 1;

    int rc = 0;
    rc |= seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(write), 0);
    rc |= seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(exit_group), 0);
    rc |= seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(exit), 0);
    if (rc != 0) {
        seccomp_release(ctx);
        return 1;
    }
    if (seccomp_load(ctx) < 0) {
        seccomp_release(ctx);
        return 1;
    }
    seccomp_release(ctx);

    say("filter loaded\n");

    int fd = open("/etc/hostname", O_RDONLY);
    if (fd < 0 && errno == EPERM) {
        say("open blocked: Operation not permitted\n");
    } else {
        say("open was not blocked\n");
    }
    return 0;
}

Build with cc -o jail jail.c -lseccomp. The output:

Text
filter loaded
open blocked: Operation not permitted

The program calls glibc's open, which on current glibc issues the openat system call. That call is not on the list, so the default action SCMP_ACT_ERRNO(EPERM) returns the error. Returning from main ends in exit_group, which is on the list, so the process exits cleanly. If you drop exit_group from the rules, the process cannot exit through the normal path and the default action returns an error to libc, which then tries other ways out. Test the exit path on purpose.

Choosing the default action matters. SCMP_ACT_ERRNO lets the program notice and recover. SCMP_ACT_KILL_PROCESS is stricter and is the right setting once the allow-list is stable, because a program that hits a forbidden call is in a state nobody planned for. During development, SCMP_ACT_LOG allows everything and records what a filter would block, which finds missing entries without breaking the program. Logging goes to the audit subsystem, so read it with ausearch -m SECCOMP or journalctl.

Limit arguments, not just calls

Rules can compare argument values. The macros SCMP_A0 to SCMP_A5 select the argument by position, and the comparison operators are SCMP_CMP_EQ, SCMP_CMP_NE, SCMP_CMP_LT, SCMP_CMP_LE, SCMP_CMP_GT, SCMP_CMP_GE and SCMP_CMP_MASKED_EQ. To allow write only on standard output and standard error, add two rules for the same call:

writefds.cc
rc |= seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(write), 1,
                       SCMP_A0(SCMP_CMP_EQ, STDOUT_FILENO));
rc |= seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(write), 1,
                       SCMP_A0(SCMP_CMP_EQ, STDERR_FILENO));

Multiple rules for one call are ORed; multiple comparisons inside a single rule are ANDed. After this, write(fd, ...) to a file you opened earlier is denied by the default action. That shrinks what a hijacked process can do with a descriptor it inherited.

Two limits are worth knowing. Comparisons see the raw register value, so a pointer argument is just a number, as the previous post explained. And the comparison is on a 64-bit value on 64-bit targets, so a 32-bit argument sign-extended into the register can produce surprising matches when you use SCMP_CMP_GT. Prefer SCMP_CMP_EQ and SCMP_CMP_MASKED_EQ for flag checks, as in allowing mmap only when PROT_EXEC is clear:

mmapnoexec.cc
rc |= seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(mmap), 1,
                       SCMP_A2(SCMP_CMP_MASKED_EQ, PROT_EXEC, 0));

SCMP_CMP_MASKED_EQ ANDs the argument with the mask first, so this matches when the protection argument has the PROT_EXEC bit clear. This is the pattern for flag-style arguments in general.

See what you built

Do not trust a filter you have not looked at. libseccomp can write the BPF it generated in two forms before you load it, through seccomp_export_pfc() for a human-readable pseudo filter code listing and seccomp_export_bpf() for the binary program, both taking a file descriptor:

exportpfc.cc
#include <seccomp.h>
#include <unistd.h>

void dump(scmp_filter_ctx ctx) {
    seccomp_export_pfc(ctx, STDERR_FILENO);
}

For a filter like the one above, the listing looks like this, with the comment markers the library prints at the start of its annotation lines left out here:

Text
pseudo filter code start
filter for arch x86_64 (3221225534)
if ($arch == 3221225534)
  filter for syscall "exit" (60) [priority: 65535]
  if ($syscall == 60)
    action ALLOW;
  filter for syscall "write" (1) [priority: 65535]
  if ($syscall == 1)
    action ALLOW;
  default action
  action ERRNO(1);
invalid architecture action
action KILL_PROCESS;

Check three things in a listing like this: the architecture matches where you will run, every call you meant to allow appears, and the invalid-architecture action is a kill. The value 3221225534 is AUDIT_ARCH_X86_64 (0xC000003E) in decimal.

Order of operations in a real program

Load the filter as late as you can, after the program has done the work that needs more privilege: opened its log file, bound its socket, read its configuration. Everything after the load is the sandboxed part. The most common mistake is loading early and then discovering that a library call you made later needs an unlisted system call. The record-then-allow workflow in the post on building an allow-list with strace finds those calls before a user does.

Third-party libraries make this harder than it looks. The allocator may call brk, mmap or madvise at any time; the dynamic loader calls openat when the first dlopen or lazy symbol resolution runs; getrandom appears the first time something seeds a hash table. Resolve lazy bindings before loading the filter by linking with -Wl,-z,now, and treat the allocator's calls as part of your allow-list.

Also inKernels
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.