Watching Every Exec, and Saying No

Contents
A tracepoint program that read the file name of every open() at the moment the system call began
was wrong 836 times in 100,000 on Linux 6.4, because a second thread kept rewriting
the name after the program had read it. A second BPF program, on a hook a few microseconds further
into the same system call, the kernel’s own security check, saw the file the kernel had actually
resolved. Told to refuse, it turned away all 96,943 attempts to open the forbidden file and
was never fooled once. Watching happens where the process can still change the answer; deciding
has to happen where it cannot.
This post is about that difference. It starts from the hooks Linux has had for two decades for
security modules, shows how a BPF program becomes one of them and says no with -EPERM, and builds a
small exec and connect policy that refuses binaries from /tmp, binaries with a known hash and
connections to the cloud metadata address, logging every decision. Then it measures what that
costs, and is frank about what it cannot stop.
This is Part 10 of a series on eBPF, written for C programmers who know what a process, a system
call and a socket are, and nothing about kernel internals. Everything here ran on Linux 6.4, released
on 25 June, under the userland of Ubuntu 23.04 as it shipped in April: clang 15, libbpf 1.1,
bpftrace 0.17 and the bpftool from linux-tools-6.2.0-20-generic. The output is pasted from those
runs, not reconstructed. The note at the end says exactly where and how.
Watching is not deciding
Nearly every program so far in this series has been a witness. The execve() counter of
Part 1 saw every process start and changed nothing about
any of them. A tracepoint program’s return value is ignored, and so is a kprobe’s: the program runs,
writes to a map, and the kernel carries on exactly as it would have without it. That is what makes
tracing safe to leave running on a production machine, and it is also why tracing, on its own, is
not security.
Security tools want two different things from the kernel, and it helps to keep them apart.
Observing means: tell me that /tmp/x was executed, by whom, with which arguments, so that a
person or a rule engine can react. The reaction comes afterwards, in user space, and by then the
event has happened.
Enforcing means: do not let /tmp/x be executed. The decision has to be taken inside the kernel,
before the operation takes effect, at a point where the kernel will act on the answer and where it
has already settled what the operation is about.
The second needs a hook whose return value the kernel obeys. Linux has had a whole family of such hooks since the 2.6 kernels. They belong to the Linux Security Module framework, and since 5.7 a BPF program can be one of them.
The Linux Security Module framework
SELinux, AppArmor, Smack, TOMOYO, Landlock and Yama are all Linux Security Modules, and none of
them is a module in the loadable sense: each is compiled into the kernel and plugs into the same set
of hooks. A hook is a call the kernel makes at a point where it is about to do something that a
security policy might want to forbid, with the objects involved as arguments. The kernel 6.4 sources
define 247 of them, one line each, in include/linux/lsm_hook_defs.h. Four matter for this post:
LSM_HOOK(int, 0, bprm_check_security, struct linux_binprm *bprm)
LSM_HOOK(int, 0, mmap_file, struct file *file, unsigned long reqprot,
unsigned long prot, unsigned long flags)
LSM_HOOK(int, 0, file_open, struct file *file)
LSM_HOOK(int, 0, socket_connect, struct socket *sock, struct sockaddr *address,
int addrlen)
Each line gives the return type, the default value and the arguments. bprm_check_security runs
during execve(), once the kernel has opened the file to be executed and read its first bytes, and
its argument is the linux_binprm that describes the new program, including the open struct file.
file_open runs when a file has been looked up and is about to be handed out as a descriptor.
socket_connect runs at the start of connect(), with the address already copied into the kernel.
mmap_file runs whenever a file is about to be mapped into memory, with the protection asked for.
The return value is the point. Here is how the kernel calls a hook, from security/security.c:
#define call_int_hook(FUNC, IRC, ...) ({ \
int RC = IRC; \
do { \
struct security_hook_list *P; \
\
hlist_for_each_entry(P, &security_hook_heads.FUNC, list) { \
RC = P->hook.FUNC(__VA_ARGS__); \
if (RC != 0) \
break; \
} \
} while (0); \
RC; \
})
int security_bprm_check(struct linux_binprm *bprm)
{
int ret;
ret = call_int_hook(bprm_check_security, 0, bprm);
if (ret)
return ret;
return ima_bprm_check(bprm);
}
Every module that registered for bprm_check_security is called in turn, and the first one to
return anything other than zero stops the walk, and its value becomes the result of
security_bprm_check(). execve() sees a non-zero value, abandons the exec and returns it to the
caller as the error. A module says no by returning a negative errno, almost always -EACCES or
-EPERM, and the program that asked sees Permission denied or Operation not permitted.
Stacking. Several modules can be active at once; the order they are called in is set at boot.
The kernel’s default list is the CONFIG_LSM string it was built with, and the lsm= boot
parameter, added in 5.1, overrides it. capability, the module that implements ordinary Linux
capabilities, is always enabled and runs ahead of the listed ones; only lockdown, which this
kernel is built to start early, comes before it. Modules that keep a label on every object, SELinux and AppArmor
among them, are marked exclusive in 6.4, so only one of them can be active; Landlock, Yama, the
lockdown module and BPF are not, and stack with whichever it is. Ubuntu builds its kernels with
AppArmor:
$ cat /sys/kernel/security/lsm
lockdown,capability,landlock,yama,apparmor
That is the list from a stock boot of the 6.4 kernel used here, whose CONFIG_LSM names landlock,
lockdown, yama, integrity and apparmor, in that order. (integrity, the base for IMA, registers no hooks of its own
and so is never listed.) Ubuntu 23.04’s own 6.2 kernel and Ubuntu 22.04’s 5.15 have exactly the same
CONFIG_LSM. All three are built with CONFIG_BPF_LSM=y, and in none of them is bpf in the
list. That detail decides whether anything in the rest of this post works, and we will come back to
it.
A BPF program as a security module
The BPF LSM arrived in Linux 5.7, in May 2020, from KP Singh at Google; its patch series was first
called KRSI, Kernel Runtime Security Instrumentation. It adds a program type, BPF_PROG_TYPE_LSM,
and a module called bpf whose job is to give those programs somewhere to run. The mechanism is
neat. For every hook in lsm_hook_defs.h, the kernel defines an empty function:
/* For every LSM hook that allows attachment of BPF programs, declare a nop
* function where a BPF program can be attached.
*/
#define LSM_HOOK(RET, DEFAULT, NAME, ...) \
noinline RET bpf_lsm_##NAME(__VA_ARGS__) \
{ \
return DEFAULT; \
}
and the bpf module registers all 247 of them as its hooks. With bpf in the boot list, every
security check in the kernel calls, among the others, a function like bpf_lsm_file_open() that
returns 0 and does nothing else. Attaching an LSM program puts a BPF trampoline on that function,
the same machinery Part 9 used for
fentry and fexit, but in the mode that lets a program replace the function’s return value. The
program receives the hook’s arguments, typed by BTF, and whatever it returns becomes the bpf
module’s answer.
That makes three ways to put a BPF program at the start of a kernel function, and they differ in what the kernel does with the result:
- fentry/fexit (5.5) observe: they see the arguments, and with fexit the return value, and cannot change either.
- fmod_ret (5.7) can replace the return value of a function, but only of a function marked as safe for error injection, essentially system calls and a short list of others.
- LSM programs (5.7) can replace the return value of the
bpf_lsm_*functions, and the LSM framework then acts on that value as it would on SELinux’s.
The verifier treats the arguments as trusted pointers, so the program can read bprm->file
directly instead of going through bpf_probe_read_kernel. It does not check what the program
returns. The 6.4 verifier’s comment says so plainly: “Regular BPF_PROG_TYPE_LSM programs can return
any value.” Return 0 to allow, a negative errno to refuse; returning anything else is a bug the
kernel will not catch for you.
Turning it on takes the boot parameter. Here is the same kernel booted with bpf added to the
end of the list:
$ grep -o "lsm=[^ ]*" /proc/cmdline
lsm=landlock,lockdown,yama,integrity,apparmor,bpf
$ cat /sys/kernel/security/lsm
lockdown,capability,landlock,yama,apparmor,bpf
Everything that follows ran on that boot unless I say otherwise.
Which hooks fire
Before writing a policy it is worth seeing how many hooks a single operation passes through.
With bpf in the list, every hook invocation is a call to one of the bpf_lsm_* functions, so a
kprobe on all of them, filtered to the system calls of one process, lists every security check an
operation makes, in order. This program does one open(), one connect() to a listening socket on
the loopback interface, and one execve():
// hookmap.c — one open(), one connect() and one execve(), nothing else
#include <arpa/inet.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
int main(void)
{
struct sockaddr_in a = { .sin_family = AF_INET,
.sin_addr.s_addr = htonl(INADDR_LOOPBACK) };
socklen_t len = sizeof(a);
int l = socket(AF_INET, SOCK_STREAM, 0), s, fd;
bind(l, (struct sockaddr *)&a, sizeof(a)); /* port 0: any free port */
listen(l, 1);
getsockname(l, (struct sockaddr *)&a, &len);
s = socket(AF_INET, SOCK_STREAM, 0);
fd = open("/etc/hostname", O_RDONLY); /* 1 */
connect(s, (struct sockaddr *)&a, sizeof(a)); /* 2 */
execl("/bin/true", "true", (char *)NULL); /* 3 */
return fd < 0;
}
and this bpftrace script prints every hook that runs inside those three system calls:
// hooks.bt — every BPF LSM hook that runs inside hookmap's three system calls
tracepoint:syscalls:sys_enter_openat,
tracepoint:syscalls:sys_enter_connect,
tracepoint:syscalls:sys_enter_execve
/comm == "hookmap"/
{
@inside[tid] = 1;
printf("-- %s\n", probe);
}
kprobe:bpf_lsm_* /@inside[tid]/ { printf("%s\n", func); }
tracepoint:syscalls:sys_exit_openat,
tracepoint:syscalls:sys_exit_connect,
tracepoint:syscalls:sys_exit_execve
/@inside[tid]/
{
delete(@inside[tid]);
printf("-- returned %d\n", args->ret);
}
The figure has the result. The open() of /etc/hostname passed eight hooks. The connect()
passed thirteen, and only the first, socket_connect, is about the connecting side: on the
loopback interface the whole TCP handshake runs inside the connect() call, so the listening
socket’s checks, socket_sock_rcv_skb, inet_conn_request and the hooks for the new socket it
accepts, run in the connecting process’s context. The execve() of /bin/true passed 86,
through 19 different hooks.
One system call, many security checks
Every BPF LSM hook that ran, in order, inside each of three system calls. Linux 6.4, measured with bpftrace.
hooks this post's programs attach to: file_open, bprm_check_security, mmap_file, socket_connect
Every hook and how often it ran
| hook | open() | connect() | execve() |
|---|---|---|---|
| file_alloc_security | 1 | · | 2 |
| inode_permission | 3 | · | 17 |
| inode_alloc_security | 1 | · | 6 |
| d_instantiate | 1 | · | 6 |
| file_open | 1 | · | 2 |
| current_getsecid_subj | 1 | · | 11 |
| socket_connect | · | 1 | · |
| sk_getsecid | · | 2 | · |
| socket_sock_rcv_skb | · | 3 | · |
| inet_conn_request | · | 1 | · |
| req_classify_flow | · | 2 | · |
| inet_conn_established | · | 1 | · |
| sk_alloc_security | · | 1 | · |
| sk_clone_security | · | 1 | · |
| inet_csk_clone | · | 1 | · |
| vm_enough_memory | · | · | 4 |
| cred_prepare | · | · | 1 |
| inode_follow_link | · | · | 4 |
| inode_free_security | · | · | 5 |
| bprm_creds_for_exec | · | · | 1 |
| file_permission | · | · | 5 |
| bprm_check_security | · | · | 1 |
| cred_getsecid | · | · | 1 |
| bprm_creds_from_file | · | · | 1 |
| bprm_committing_creds | · | · | 1 |
| bprm_committed_creds | · | · | 1 |
| mmap_file | · | · | 8 |
| mmap_addr | · | · | 9 |
Three things in the exec list are worth noticing. The binary is opened like any other file, so
file_open fires for it, and again for the dynamic loader /lib64/ld-linux-x86-64.so.2, which the
kernel opens itself because the binary names it as its interpreter. bprm_check_security, the hook
this post’s policy uses, fires once, after the kernel has read the file’s first bytes and before
it commits to replacing the process. And eight mmap_file calls map the binary’s and the loader’s
segments; those are the kernel’s own mappings, made during the exec, and every library the loader
maps afterwards passes through the same hook from user space. (The inode_alloc_security and
d_instantiate lines on almost every path lookup are an artefact of this test machine, whose root
file system is shared from the host over 9p without caching: every lookup builds a fresh inode. On
a disk file system they appear only the first time a file is looked up.)
The race an observer loses
Here is the problem with deciding at the wrong place. The obvious way to watch file opens is the
sys_enter_openat tracepoint, which fires as the system call begins and gets its arguments. One of
them is the file name, but not the name itself: a pointer to it, in the calling process’s memory.
The program has to copy the string out with bpf_probe_read_user_str, and so does the kernel, a
moment later, when openat() gets round to it with getname(). Between the two copies the memory
belongs to the process, and a process has more than one thread.
That is a time-of-check to time-of-use race, and it is the classic weakness of security tools that
hook system calls at entry. The tool checks one string; the kernel uses another. An LSM hook does
not have the problem, because by the time file_open runs the kernel has copied the name, walked
the path, followed any symbolic links and found the file. What the hook is handed is a struct file, the kernel’s own object, and nothing the process does to its memory can change which file
that is.
To see it happen, this program watches the same open() from both places. The tracepoint copies the
name and stores it under the thread’s ID. The LSM program, when the open reaches file_open, asks
for the opened file’s path with bpf_d_path and compares the two:
// race.bpf.c — what a tracepoint reads at syscall entry, against what the kernel opened
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#define EPERM 1
#define NAME_LEN 32
const volatile __u32 target_tgid;
const volatile bool enforce;
__u64 agreed, fooled, false_alarm, refused;
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 64);
__type(key, __u32); /* thread id */
__type(value, char[NAME_LEN]); /* the name the tracepoint read */
} seen SEC(".maps");
/* "/tmp/race/secret" and its NUL, compared as two 8-byte words and a byte */
static __always_inline bool is_secret(const char *s)
{
return *(const __u64 *)s == *(const __u64 *)"/tmp/rac" &&
*(const __u64 *)(s + 8) == *(const __u64 *)"e/secret" &&
s[16] == 0;
}
/* The observer: read the file name from the caller's memory at syscall entry. */
SEC("tracepoint/syscalls/sys_enter_openat")
int observe(struct trace_event_raw_sys_enter *ctx)
{
__u64 id = bpf_get_current_pid_tgid();
__u32 tid = (__u32)id;
char name[NAME_LEN] = {};
if (id >> 32 != target_tgid)
return 0;
bpf_probe_read_user_str(name, sizeof(name), (const char *)ctx->args[1]);
bpf_map_update_elem(&seen, &tid, name, BPF_ANY);
return 0;
}
/* The LSM hook: the file the kernel actually resolved and is about to open. */
SEC("lsm/file_open")
int BPF_PROG(check_open, struct file *file)
{
__u64 id = bpf_get_current_pid_tgid();
__u32 tid = (__u32)id;
char path[NAME_LEN] __attribute__((aligned(8))) = {};
bool saw, opened;
char *name;
if (id >> 32 != target_tgid)
return 0;
name = bpf_map_lookup_elem(&seen, &tid);
if (!name)
return 0;
bpf_d_path(&file->f_path, path, sizeof(path));
saw = is_secret(name);
opened = is_secret(path);
if (opened && !saw)
__sync_fetch_and_add(&fooled, 1);
else if (saw && !opened)
__sync_fetch_and_add(&false_alarm, 1);
else
__sync_fetch_and_add(&agreed, 1);
if (enforce && opened) {
__sync_fetch_and_add(&refused, 1);
return -EPERM;
}
return 0;
}
char LICENSE[] SEC("license") = "GPL";
The user-space half loads it, starts a second thread that flips the path between
/tmp/race/public and /tmp/race/secret as fast as it can, and opens the path 100,000 times:
// race.c — open one path while a second thread keeps rewriting it
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <bpf/libbpf.h>
#include "race.skel.h"
static char path[24] __attribute__((aligned(8))) = "/tmp/race/public";
static volatile int stop;
/* Bytes 8..15 of the path are "e/public" or "e/secret": one aligned 8-byte
* store swaps them, so a reader never sees half of each. */
static void *flipper(void *arg)
{
uint64_t pub, sec;
memcpy(&pub, "e/public", 8);
memcpy(&sec, "e/secret", 8);
while (!stop) {
__atomic_store_n((uint64_t *)(path + 8), sec, __ATOMIC_RELAXED);
__atomic_store_n((uint64_t *)(path + 8), pub, __ATOMIC_RELAXED);
}
return NULL;
}
int main(int argc, char **argv)
{
long n = 100000, secret = 0, eperm = 0, other = 0;
struct race_bpf *skel;
pthread_t t;
skel = race_bpf__open();
if (!skel)
return 1;
skel->rodata->target_tgid = getpid();
skel->rodata->enforce = argc > 1 && strcmp(argv[1], "enforce") == 0;
if (race_bpf__load(skel) || race_bpf__attach(skel))
return 1;
pthread_create(&t, NULL, flipper, NULL);
for (long i = 0; i < n; i++) {
char c = 0;
int fd = open(path, O_RDONLY);
if (fd < 0) {
if (errno == EPERM)
eperm++;
else
other++;
continue;
}
if (read(fd, &c, 1) == 1 && c == 'S') /* the secret file says "SECRET" */
secret++;
close(fd);
}
stop = 1;
pthread_join(t, NULL);
printf("%ld opens: %ld read the secret, %ld refused, %ld other errors\n",
n, secret, eperm, other);
printf(" tracepoint and LSM hook agreed: %6llu\n", skel->bss->agreed);
printf(" tracepoint saw public, opened secret: %6llu\n", skel->bss->fooled);
printf(" tracepoint saw secret, opened public: %6llu\n", skel->bss->false_alarm);
printf(" refused by the LSM hook: %6llu\n", skel->bss->refused);
race_bpf__destroy(skel);
return 0;
}
The flipping thread changes the eight bytes e/public to e/secret and back with single aligned
8-byte stores, so a reader can see either name but never half of each. The secret file contains
SECRET, so the main loop can tell from the first byte which file it really got. Run without
enforcement, then with it:
$ ./race
100000 opens: 89615 read the secret, 0 refused, 0 other errors
tracepoint and LSM hook agreed: 99164
tracepoint saw public, opened secret: 214
tracepoint saw secret, opened public: 622
refused by the LSM hook: 0
$ ./race enforce
100000 opens: 0 read the secret, 96943 refused, 0 other errors
tracepoint and LSM hook agreed: 99419
tracepoint saw public, opened secret: 185
tracepoint saw secret, opened public: 396
refused by the LSM hook: 96943
Without enforcement, the main thread got the secret file 89,615 times in
100,000. That lopsided split is a quirk of two CPUs passing one cache line back and forth,
not anything the kernel does; what matters is the next three lines. In 99,164 opens the
tracepoint and the LSM hook agreed on the name. In 214 the tracepoint recorded
/tmp/race/public while the kernel opened /tmp/race/secret: the log says the process read the
harmless file at the very moment it read the secret one. In 622 it was the other
way round, which for a tool that acted on what it saw would have meant punishing an innocent open.
A third run gave 339 and 732. A fraction of a percent sounds small,
but an attacker does not need a rate. It needs one win, and it can try as often as it likes.
With enforcement, the LSM hook refused all 96,943 opens that resolved to the secret file, and the main thread never read it. The tracepoint was still wrong 581 times in that run, and it no longer mattered, because the decision was taken on the kernel’s copy.
Checked at one moment, used at another
One openat() of a path that a second thread keeps rewriting, step by step.
the path in thread A's memory
what the tracepoint copied
the kernel's copy (getname)
the file the hook was handed
1. Thread A calls openat(path)
The argument is a pointer into thread A's memory, where the path currently reads /tmp/race/public.
2. The sys_enter_openat tracepoint runs
The BPF program copies the string out with bpf_probe_read_user_str and records public. An observer that decides here has decided.
3. Thread B rewrites the path
One 8-byte store turns e/public into e/secret. The memory is the process's own; nothing stops it.
4. openat() copies the name with getname()
From here the kernel works only on its own copy, which says secret. The process can change its memory again; it no longer matters.
5. The path walk finds the file; file_open runs
The LSM hook gets the struct file the kernel resolved. bpf_d_path on it says /tmp/race/secret: a fact, not a claim.
6. The result
Tracepoint only: thread A gets a descriptor for the secret file, and the log says it opened public. Measured: in 100,000 opens the tracepoint recorded public while the kernel opened secret 214 times, and the reverse 622 times.
With the LSM hook: it returns -EPERM and openat() fails, whatever the tracepoint saw. Measured: of 100,000 opens, 96,943 were refused and 0 read the secret; the tracepoint was wrong 581 times and it made no difference.
Steps 1–5 show one losing round in order; most rounds the two copies agree. Counts: the post's race, 100,000 opens per run, Linux 6.4 in a 4-vCPU VM.
This is why a security tool that starts from system call tracing has to take its decisions deeper.
It can still be told at syscall entry that an open() is coming, and it can still log there, but
anything it records from user memory at that point is a claim made by the process, not a fact about
what the kernel did. The places where the kernel has made up its mind are the LSM hooks, the
security_* functions that call them, and functions like fd_install, which installs an opened
file in the descriptor table; two of the projects later in this post attach kprobes to exactly
those for exactly this reason.
The worked example: an exec and connect policy
guard enforces three rules and logs every decision to a ring buffer:
- no program may be executed from a directory given on the command line,
/tmp/here; - no file whose SHA-1 is on a deny list may be executed, wherever it lives and whatever it is called;
- no process may
connect()to one IPv4 address, here169.254.169.254, the address at which cloud providers serve each virtual machine’s credentials and metadata, and a favourite first request of anyone who gets code running on one.
The header is shared between the two halves:
// guard.h — shared by guard.bpf.c and guard.c
#define PATH_LEN 256
#define DIGEST_LEN 20 /* SHA-1: IMA's default hash on this kernel */
enum kind { EV_EXEC = 1, EV_MMAP, EV_CONNECT };
enum why { ALLOWED = 0, BY_PATH, BY_HASH, BY_ADDR };
struct event {
__u32 kind, why;
__s32 verdict; /* 0, or -EPERM */
__u32 pid, uid;
__u32 daddr; /* connect: IPv4 address, network order */
__u16 dport; /* connect: port, host order */
char comm[16];
char path[PATH_LEN]; /* exec, mmap: the file */
};
struct digest {
__u8 b[DIGEST_LEN];
};
and this is the kernel half, the whole of it:
// guard.bpf.c — an exec and connect policy, enforced at LSM hooks
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_endian.h>
#include "guard.h"
#define EPERM 1
#define AF_INET 2
#define PROT_EXEC 4
const volatile char deny_dir[32] = "/tmp/"; /* set by guard.c before load */
const volatile __u32 deny_dir_len = 5;
const volatile __u32 deny_ip; /* network order; 0 = none */
const volatile __u32 guard_tgid;
const volatile bool protect;
__u64 lost;
struct {
__uint(type, BPF_MAP_TYPE_RINGBUF);
__uint(max_entries, 256 * 1024);
} events SEC(".maps");
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 64);
__type(key, struct digest);
__type(value, __u8);
} bad_hashes SEC(".maps");
static __always_inline bool in_deny_dir(const char *path)
{
for (int i = 0; i < sizeof(deny_dir); i++) {
if (i == deny_dir_len)
return true;
if (path[i] != deny_dir[i])
return false;
}
return false;
}
/* Fill in who asked, log the decision, and return it to the LSM framework. */
static __always_inline int decide(struct event *e)
{
e->pid = bpf_get_current_pid_tgid() >> 32;
e->uid = (__u32)bpf_get_current_uid_gid();
bpf_get_current_comm(e->comm, sizeof(e->comm));
e->verdict = e->why == ALLOWED ? 0 : -EPERM;
if (bpf_ringbuf_output(&events, e, sizeof(*e), 0))
__sync_fetch_and_add(&lost, 1);
return e->verdict;
}
SEC("lsm.s/bprm_check_security")
int BPF_PROG(check_exec, struct linux_binprm *bprm)
{
struct event e = {};
struct digest d = {};
e.kind = EV_EXEC;
bpf_d_path(&bprm->file->f_path, e.path, sizeof(e.path));
if (in_deny_dir(e.path))
e.why = BY_PATH;
else if (bpf_ima_file_hash(bprm->file, d.b, sizeof(d.b)) >= 0 &&
bpf_map_lookup_elem(&bad_hashes, &d))
e.why = BY_HASH;
return decide(&e);
}
SEC("lsm.s/mmap_file")
int BPF_PROG(check_mmap, struct file *file, unsigned long reqprot,
unsigned long prot, unsigned long flags)
{
struct event e = {};
if (!file || !(prot & PROT_EXEC))
return 0;
bpf_d_path(&file->f_path, e.path, sizeof(e.path));
if (!in_deny_dir(e.path))
return 0; /* log only refusals: every library is mapped */
e.kind = EV_MMAP;
e.why = BY_PATH;
return decide(&e);
}
SEC("lsm/socket_connect")
int BPF_PROG(check_connect, struct socket *sock, struct sockaddr *address,
int addrlen)
{
struct sockaddr_in sin = {};
struct event e = {};
if (address->sa_family != AF_INET || addrlen < sizeof(sin))
return 0;
bpf_probe_read_kernel(&sin, sizeof(sin), address);
e.kind = EV_CONNECT;
e.daddr = sin.sin_addr.s_addr;
e.dport = bpf_ntohs(sin.sin_port);
if (deny_ip && e.daddr == deny_ip)
e.why = BY_ADDR;
return decide(&e);
}
SEC("lsm/task_kill")
int BPF_PROG(protect_guard, struct task_struct *p, struct kernel_siginfo *info,
int sig, const struct cred *cred)
{
if (!protect || p->tgid != guard_tgid || sig == 0)
return 0;
if (bpf_get_current_pid_tgid() >> 32 == guard_tgid)
return 0;
return -EPERM;
}
char LICENSE[] SEC("license") = "GPL";
Taking it apart in order:
Configuration lives in .rodata. deny_dir, deny_ip, guard_tgid and protect are const volatile globals. User space writes them through the skeleton after opening the object and before
loading it; at load time libbpf freezes the map that holds them, and from then on the verifier
treats their values as constants. The loop in in_deny_dir compares at most 32 bytes and stops at
deny_dir_len, which the verifier knows is 5, so it walks only the paths that can happen.
Two maps. events is a 256 KiB ring buffer, the shared, ordered one
Part 5 measured, and it
carries a struct event for every decision. bad_hashes is a hash map keyed by a 20-byte digest;
user space fills it.
decide() is the only place a verdict is made. It fills in who asked, sets the verdict from
why, copies the event into the ring buffer with bpf_ringbuf_output, and returns the verdict,
which the program returns to the LSM framework. If the ring buffer is full, the copy fails, a
counter goes up, and the verdict stands: the policy fails closed for enforcement and open only for
logging. The order matters. An earlier draft reserved the ring buffer record first and returned 0 if
the reservation failed, which would have let a process that filled the buffer run anything it
liked.
The event is built on the stack, about 300 of the 512 bytes. A per-CPU array would be the
usual scratch space for something that size, and here it would be a bug: check_exec is
sleepable, and while it sleeps another exec on the same CPU can run the same program and overwrite
the same per-CPU slot.
check_exec is attached to bprm_check_security. The section name lsm.s/ instead of lsm/
makes it sleepable, which the next section explains. bpf_d_path turns the file the kernel is
about to execute into a path, resolved: if the user ran a symbolic link, this is where the link
points. If the path is under the deny directory, the answer is no. If not, bpf_ima_file_hash asks
the Integrity Measurement Architecture for the file’s hash, and the program looks it up in
bad_hashes. Note that the comm recorded here is the caller’s: at this hook the process has not
yet become the new program, so the event for /tmp/evil run from bash says comm=bash.
check_mmap closes a hole the exec check leaves open, which we will see in the session. It
refuses any executable mapping of a file under the deny directory, and logs only refusals, since
every shared library every process loads passes through this hook.
check_connect reads the destination from the sockaddr the kernel has already copied in.
Only IPv4 is checked, which a real policy would have to fix, since ::ffff:169.254.169.254 reaches
the same address over an IPv6 socket.
protect_guard, on task_kill, refuses signals sent to the guard process by anyone else, when
-p asks for it. It belongs to the section on limits.
The user-space half sets the configuration, loads, fills the hash map, attaches, and prints events until it is told to stop:
// guard.c — load the policy, then print every decision it makes
#include <arpa/inet.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <linux/types.h>
#include <bpf/libbpf.h>
#include <bpf/bpf.h>
#include "guard.h"
#include "guard.skel.h"
static volatile sig_atomic_t done;
static void on_signal(int sig) { done = 1; }
static const char *kinds[] = { "", "exec", "mmap", "connect" };
static const char *whys[] = { "", "path", "hash", "address" };
static int on_event(void *ctx, void *data, size_t len)
{
const struct event *e = data;
char ip[INET_ADDRSTRLEN];
printf("%-5s %-7s pid=%-4u uid=%-4u comm=%-8s ", e->verdict ? "DENY" : "allow",
kinds[e->kind], e->pid, e->uid, e->comm);
if (e->kind == EV_CONNECT)
printf("%s:%u", inet_ntop(AF_INET, &e->daddr, ip, sizeof(ip)), e->dport);
else
printf("%s", e->path);
if (e->verdict)
printf(" [%s]", whys[e->why]);
printf("\n");
fflush(stdout);
return 0;
}
static int parse_digest(const char *hex, struct digest *d)
{
if (strlen(hex) < 2 * DIGEST_LEN)
return -1;
for (int i = 0; i < DIGEST_LEN; i++)
if (sscanf(hex + 2 * i, "%2hhx", &d->b[i]) != 1)
return -1;
return 0;
}
int main(int argc, char **argv)
{
struct digest bad[8];
int nbad = 0, seconds = 0, opt; /* 0: until SIGINT or SIGTERM */
struct guard_bpf *skel;
struct ring_buffer *rb;
__u8 one = 1;
time_t end;
skel = guard_bpf__open();
if (!skel)
return 1;
skel->rodata->guard_tgid = getpid();
while ((opt = getopt(argc, argv, "d:c:h:t:p")) != -1) {
switch (opt) {
case 'd': /* deny exec from under this directory */
snprintf((char *)skel->rodata->deny_dir, sizeof(skel->rodata->deny_dir), "%s", optarg);
skel->rodata->deny_dir_len = strlen((char *)skel->rodata->deny_dir);
break;
case 'c': /* deny connect() to this IPv4 address */
inet_pton(AF_INET, optarg, (void *)&skel->rodata->deny_ip);
break;
case 'h': /* deny exec of a file with this SHA-1 */
if (nbad < 8 && parse_digest(optarg, &bad[nbad]) == 0)
nbad++;
break;
case 't':
seconds = atoi(optarg);
break;
case 'p': /* refuse signals from other processes */
skel->rodata->protect = true;
break;
}
}
if (guard_bpf__load(skel))
goto out;
for (int i = 0; i < nbad; i++)
bpf_map__update_elem(skel->maps.bad_hashes, &bad[i], sizeof(bad[i]),
&one, sizeof(one), BPF_ANY);
if (guard_bpf__attach(skel))
goto out;
rb = ring_buffer__new(bpf_map__fd(skel->maps.events), on_event, NULL, NULL);
if (!rb)
goto out;
signal(SIGINT, on_signal);
signal(SIGTERM, on_signal);
printf("guard %d: enforcing\n", getpid());
fflush(stdout);
end = time(NULL) + seconds;
while (!done && (!seconds || time(NULL) < end))
ring_buffer__poll(rb, 100);
ring_buffer__free(rb);
printf("guard %d: done, %llu events lost\n", getpid(), (unsigned long long)skel->bss->lost);
out:
guard_bpf__destroy(skel);
return 0;
}
And a stand-in for a program nobody should run:
// evil.c — a stand-in for a binary nobody should run
#include <stdio.h>
int main(void) { puts("evil ran"); return 0; }
Building everything in this post takes the same four kinds of command as Part 1. On Ubuntu 23.04,
clang 15, libbpf-dev 1.1 and bpftool (from linux-tools-generic) are packages:
bpftool btf dump file /sys/kernel/btf/vmlinux format c > vmlinux.h
for p in guard race; do
clang -g -O2 -target bpf -D__TARGET_ARCH_x86 -c $p.bpf.c -o $p.bpf.o
bpftool gen skeleton $p.bpf.o > $p.skel.h
done
for p in kf fmodret; do
clang -g -O2 -target bpf -D__TARGET_ARCH_x86 -c $p.bpf.c -o $p.bpf.o
done
cc -g -O2 -Wall guard.c -lbpf -lelf -lz -o guard
cc -g -O2 -Wall race.c -lbpf -lelf -lz -lpthread -o race
cc -O2 -Wall hookmap.c -o hookmap
cc -O2 -Wall evil.c -o evil
The session
/tmp/evil and /root/evil-copy are both copies of evil. I took the copy’s SHA-1, started
guard in the background with /tmp/ as the deny directory, that hash on the deny list and the
metadata address blocked, and ran these commands, each in a fresh bash -c from a script, which is
why bash’s complaints begin line 1:
$ sha1sum /root/evil-copy
3b3a8955b46ce4b8e3528f88e8345cb05ce2b395 /root/evil-copy
$ ./guard -d /tmp/ -c 169.254.169.254 -h 3b3a8955b46ce4b8e3528f88e8345cb05ce2b395 > guard.log &
$ /tmp/evil
bash: line 1: /tmp/evil: Operation not permitted
$ /root/evil-copy
bash: line 1: /root/evil-copy: Operation not permitted
$ cp /root/evil-copy /usr/local/bin/renamed && /usr/local/bin/renamed
bash: line 1: /usr/local/bin/renamed: Operation not permitted
$ ln -s /tmp/evil /root/link && /root/link
bash: line 1: /root/link: Operation not permitted
$ cp /root/evil-copy /root/evil2 && printf x >> /root/evil2 && /root/evil2
evil ran
$ /lib64/ld-linux-x86-64.so.2 /tmp/evil
/tmp/evil: error while loading shared libraries: /tmp/evil: failed to map segment from shared object
$ printf "echo script ran\n" > /tmp/s.sh && chmod +x /tmp/s.sh
$ /tmp/s.sh
bash: line 1: /tmp/s.sh: Operation not permitted
$ sh /tmp/s.sh
script ran
$ python3 -c 'import socket; socket.create_connection(("169.254.169.254", 80))'
[traceback trimmed]
PermissionError: [Errno 1] Operation not permitted
$ python3 -c 'import socket; socket.create_connection(("127.0.0.1", 9))'
[traceback trimmed]
ConnectionRefusedError: [Errno 111] Connection refused
Line by line:
/tmp/evilwas refused by path, and/root/evil-copyby hash. The same file in two places, and each rule caught one.- Copying the file to a new name in a new directory did not help: the hash is of the contents.
- A symbolic link from
/root/linkto/tmp/evildid not help either.bpf_d_pathreports the path of the file being executed, and that is/tmp/evil. - Appending one byte gave a new hash, and the copy ran. A deny list of hashes stops known files, not their trivially modified siblings. Allow lists, “only these hashes may run”, don’t have that weakness, and are what serious exec policies use.
/lib64/ld-linux-x86-64.so.2 /tmp/evilis the classic way round an exec policy: the program executed is the dynamic loader, which is allowed, and the loader then maps/tmp/evilinto memory itself and jumps to it. No exec of/tmp/evilever happens.check_mmapis there for this: the loader’s executable mapping of a file under/tmp/is refused, and the loader reportsfailed to map segment from shared object.- A script in
/tmprun directly was refused, because the kernel executes the script file and only then switches to its interpreter.sh /tmp/s.shran, because there the executed program is/bin/sh, and the script is just a file it reads. An exec policy cannot see interpreted code; policing what interpreters read is a different problem. - The connection to
169.254.169.254failed withEPERMbefore any packet was sent, while the one to127.0.0.1:9, a port with nothing listening, got as far as being refused by the other end.
And here is what guard printed meanwhile, every decision, in order:
guard 252: enforcing
allow exec pid=254 uid=0 comm=sh /usr/bin/bash
allow exec pid=256 uid=0 comm=bash /usr/bin/grep
allow exec pid=255 uid=0 comm=bash /usr/lib/linux-tools-6.2.0-20/bpftool
allow exec pid=257 uid=0 comm=sh /usr/bin/bash
allow exec pid=259 uid=0 comm=bash /usr/bin/grep
allow exec pid=258 uid=0 comm=bash /usr/lib/linux-tools-6.2.0-20/bpftool
allow exec pid=260 uid=0 comm=sh /usr/bin/bash
DENY exec pid=260 uid=0 comm=bash /tmp/evil [path]
allow exec pid=261 uid=0 comm=sh /usr/bin/bash
DENY exec pid=261 uid=0 comm=bash /root/evil-copy [hash]
allow exec pid=262 uid=0 comm=sh /usr/bin/bash
allow exec pid=263 uid=0 comm=bash /usr/bin/cp
DENY exec pid=262 uid=0 comm=bash /usr/local/bin/renamed [hash]
allow exec pid=264 uid=0 comm=sh /usr/bin/bash
allow exec pid=265 uid=0 comm=bash /usr/bin/ln
DENY exec pid=264 uid=0 comm=bash /tmp/evil [path]
allow exec pid=266 uid=0 comm=sh /usr/bin/bash
allow exec pid=267 uid=0 comm=bash /usr/bin/cp
allow exec pid=266 uid=0 comm=bash /root/evil2
allow exec pid=268 uid=0 comm=sh /usr/bin/bash
allow exec pid=268 uid=0 comm=bash /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
DENY mmap pid=268 uid=0 comm=ld-linux-x86-64 /tmp/evil [path]
allow exec pid=269 uid=0 comm=sh /usr/bin/bash
allow exec pid=269 uid=0 comm=bash /usr/bin/chmod
allow exec pid=270 uid=0 comm=sh /usr/bin/bash
DENY exec pid=270 uid=0 comm=bash /tmp/s.sh [path]
allow exec pid=271 uid=0 comm=sh /usr/bin/bash
allow exec pid=271 uid=0 comm=bash /usr/bin/dash
allow exec pid=272 uid=0 comm=sh /usr/bin/bash
allow exec pid=272 uid=0 comm=bash /usr/bin/python3.11
DENY connect pid=272 uid=0 comm=python3 169.254.169.254:80 [address]
allow exec pid=273 uid=0 comm=sh /usr/bin/bash
allow exec pid=273 uid=0 comm=bash /usr/bin/python3.11
allow connect pid=273 uid=0 comm=python3 127.0.0.1:9
allow exec pid=274 uid=0 comm=sh /usr/bin/sleep
guard 252: done, 0 events lost
The pid and comm are the caller’s: pid 260 is the bash that tried to run /tmp/evil. The
allowed /usr/bin/bash lines are my test harness starting a shell for each command, and the log
also caught bpftool and grep running for the listing below. While it ran, bpftool showed the four programs, each lsm, each attached through a
tracing link with attach type lsm_mac:
$ bpftool prog show | grep -A3 " lsm "
35: lsm name check_exec tag 9f4f16a22bb15ffe gpl
[loaded_at line trimmed]
xlated 1200B jited 826B memlock 4096B map_ids 25,23,22,26
btf_id 44
--
37: lsm name check_mmap tag 47a86df849e80239 gpl
[loaded_at line trimmed]
xlated 816B jited 542B memlock 4096B map_ids 25,22,26
btf_id 44
--
38: lsm name check_connect tag 87208ef83eb509d1 gpl
[loaded_at line trimmed]
xlated 1088B jited 682B memlock 4096B map_ids 25,22,26
btf_id 44
--
39: lsm name protect_guard tag e5bb5267b65d0aaa gpl
[loaded_at line trimmed]
xlated 56B jited 39B memlock 4096B map_ids 25
btf_id 44
$ bpftool link show | grep -B1 -A1 tracing
[link 1, the kernel's own hid_tail_call program, trimmed]
8: tracing prog 35
prog_type lsm attach_type lsm_mac
pids guard(252)
9: tracing prog 37
prog_type lsm attach_type lsm_mac
pids guard(252)
10: tracing prog 38
prog_type lsm attach_type lsm_mac
pids guard(252)
11: tracing prog 39
prog_type lsm attach_type lsm_mac
Sleepable programs and the helpers that need them
Most BPF programs run with preemption or migration disabled, inside an RCU read-side critical
section, and must not sleep. That rules out anything that might wait: reading user memory that is
paged out, taking a mutex, reading a file. Linux 5.10 added sleepable programs, loaded with the
BPF_F_SLEEPABLE flag, which libbpf sets for any section name ending in .s. They run under a
different flavour of RCU, rcu_read_lock_trace(), that tolerates sleeping, and in exchange they
are restricted: at first only fentry, fexit, fmod_ret and LSM programs could be sleepable, and only
on hooks that are themselves called where sleeping is allowed. On 6.4, 72 of the 247 LSM hooks are
on that list, bprm_check_security, file_open, mmap_file and socket_connect among them.
Some helpers exist only for sleepable programs:
bpf_copy_from_user(5.10) reads user memory and, unlikebpf_probe_read_user, can wait for a page to be faulted in.bpf_ima_inode_hash(5.11) andbpf_ima_file_hash(5.18) return a file’s hash as IMA computes it.guarduses the second.
bpf_d_path (5.10) is a slightly different case. It may be called from an LSM program on any hook
in the sleepable list, whether or not the program itself is sleepable, and from other tracing programs, fentry, fexit and fmod_ret, only on a short allow list of functions such as security_file_open and vfs_truncate, where
the kernel knows the struct path is safe to walk. That is why race.bpf.c’s non-sleepable
lsm/file_open program could call it.
The verifier enforces all of this at load time. Change check_exec’s section from
lsm.s/bprm_check_security to lsm/bprm_check_security and the load fails at the IMA call:
; else if (bpf_ima_file_hash(bprm->file, d.b, sizeof(d.b)) >= 0 &&
108: (b7) r3 = 20 ; R3_w=20
109: (85) call bpf_ima_file_hash#193
helper call might sleep in a non-sleepable prog
processed 204 insns (limit 1000000) max_states_per_insn 1 total_states 8 peak_states 8 mark_read 6
-- END PROG LOAD LOG --
Killing instead of refusing: bpf_send_signal
Before LSM programs, and on kernels where bpf is not in the boot list, the other way for a BPF
program to stop something is to kill whoever is doing it. bpf_send_signal (5.3) sends a signal to
the current process from inside any tracing program, and bpftrace exposes it as signal(), behind
its --unsafe flag. Here is a one-line policy that kills anyone who tries to delete
/tmp/precious:
bpftrace --unsafe -e 'tracepoint:syscalls:sys_enter_unlinkat /str(args->pathname) == "/tmp/precious"/ { signal("SIGKILL"); }'
With it running:
$ rm /tmp/precious; echo "exit status $?"
bash: line 1: 300 Killed rm /tmp/precious
exit status 137
$ ls /tmp/precious
ls: cannot access '/tmp/precious': No such file or directory
rm was killed, and the file was deleted anyway. The signal is sent at syscall entry, but a
signal is acted on only when the process next returns to user space, which is after
unlinkat() has done its work. The kill is real; it is just too late for the operation it was
meant to stop. For a program that reads a secret and sends it over the network in two system calls,
killing it at the first one is in time. For a single system call that does damage on its own, it is
not. An LSM program on path_unlink or inode_unlink would have refused the unlink itself.
The other tool of that era is bpf_override_return (4.16), which lets a kprobe program make a
function return an error without running it, but only for functions on the kernel’s error injection
list, chiefly the system call entry points, and only in kernels built with
CONFIG_BPF_KPROBE_OVERRIDE, which Ubuntu’s are. Overriding a system call at entry brings back the
first problem: the arguments it has to decide on are still in user memory.
kfuncs: the kernel’s functions, called directly
Every helper used so far is part of a fixed, numbered list, the one Part 1 counted 175 of on 5.15: each has a number in the UAPI header, a prototype the verifier knows, and the promise of a stable ABI that comes with being in the UAPI. That list has stopped growing. Counting the 6.1, 6.2 and 6.4 sources, there are 209 helpers in 6.1 and 211 in 6.2, the last two being the cgroup storage helpers, and still 211 in 6.4. The 6.4 documentation says why, in its BPF design Q&A: “New BPF functionality is generally added through the use of kfuncs instead of new helpers.”
A kfunc is an ordinary kernel function that has been registered as callable from BPF programs of particular types. The mechanism arrived in 5.13, where the only kfuncs were a handful of TCP congestion-control functions; by 6.4 there are 134 registered names in the source tree, of which 28 exist only for the kernel’s own tests, against 67 and 24 in 6.1. They differ from helpers in three ways that matter:
- They have no number. A program declares a kfunc as an
externwith__ksym, and libbpf resolves the name to its BTF ID in the running kernel at load time. The verifier checks the call against the function’s BTF prototype. - They carry flags the verifier enforces.
KF_ACQUIREsays the function returns a reference the program must release;KF_RELEASEsays it consumes one;KF_RET_NULLsays the result may be NULL. The verifier tracks every acquired reference through every path and refuses a program that could leak one. - They are not stable. The design Q&A gives kfuncs “their own lifecycle expectations”: a kfunc can change or go away between releases like any other kernel function, and a program that uses one is tied to the kernels that have it.
Here is a small one. bpf_task_from_pid (6.2) looks up a task by PID and returns it with a
reference held; bpf_task_release gives the reference back:
// kf.bpf.c — calling a kfunc: look a task up by PID, read it, give it back
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
extern struct task_struct *bpf_task_from_pid(s32 pid) __ksym;
extern void bpf_task_release(struct task_struct *p) __ksym;
const volatile __s32 watched_pid = 1;
char watched_comm[16];
SEC("lsm/task_kill")
int BPF_PROG(who_is_it, struct task_struct *p, struct kernel_siginfo *info,
int sig, const struct cred *cred)
{
struct task_struct *t;
t = bpf_task_from_pid(watched_pid); /* takes a reference, or returns NULL */
if (!t)
return 0;
bpf_probe_read_kernel_str(watched_comm, sizeof(watched_comm), t->comm);
bpf_task_release(t); /* drop it: the verifier insists */
return 0;
}
char LICENSE[] SEC("license") = "GPL";
It loads, and the translated program shows the two kfuncs called by address like any helper:
$ bpftool prog load kf.bpf.o /sys/fs/bpf/kf autoattach
$ bpftool prog show name who_is_it
103: lsm name who_is_it tag ed984e6bd4bbd32a gpl
[loaded_at line trimmed]
xlated 136B jited 83B memlock 4096B map_ids 56,57
btf_id 98
$ bpftool prog dump xlated name who_is_it | grep call
3: (85) call bpf_task_from_pid#236352
12: (85) call bpf_probe_read_kernel_str#-103344
14: (85) call bpf_task_release#235808
Delete the bpf_task_release call and the verifier refuses the program, pointing at the
instruction that took the reference:
; int BPF_PROG(who_is_it, struct task_struct *p, struct kernel_siginfo *info,
12: (b7) r0 = 0 ; R0_w=0 refs=2
13: (95) exit
Unreleased reference id=2 alloc_insn=3
processed 12 insns (limit 1000000) max_states_per_insn 0 total_states 1 peak_states 1 mark_read 0
-- END PROG LOAD LOG --
Delete the NULL check instead and the refusal comes earlier, at the first use of the pointer:
5: (b7) r1 = 2960 ; R1_w=2960 refs=2
6: (bf) r3 = r6 ; R3_w=ptr_or_null_task_struct(id=2,ref_obj_id=2,off=0,imm=0) R6_w=ptr_or_null_task_struct(id=2,ref_obj_id=2,off=0,imm=0) refs=2
7: (0f) r3 += r1
R3 pointer arithmetic on ptr_or_null_ prohibited, null-check it first
processed 7 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0
-- END PROG LOAD LOG --
Helpers that hand out references, bpf_sk_lookup_tcp and bpf_sk_release for instance, get the
same checks, but the 6.4 verifier’s is_acquire_function lists the helpers that take a reference
one by one. With kfuncs the rules are flags
on the function, and the verifier applies them to any kfunc that carries them. The kfuncs most relevant to security tools in 6.4 are of this kind: task and
cgroup references, bpf_rcu_read_lock, and, since 6.1, bpf_lookup_user_key and
bpf_verify_pkcs7_signature, which let a sleepable program check a signature against a kernel
keyring.
What it costs
A policy that runs on every open() and every execve() on a machine had better be cheap. I timed
both with nothing attached, with programs attached that return 0 and do nothing else, and with the
policies of this post, in one run with no other test virtual machine running, conditions
interleaved and their order rotated, over 9 rounds in each of two sittings. Each round spawned and waited for
2,000 processes of a statically linked program that returns at once, and opened and closed a file
200,000 times, both on a tmpfs so that the 9p root stayed out of it. The conditions:
- nothing attached;
- lsm, empty: LSM programs on
file_openandbprm_check_securitythat return 0; - fentry, empty: fentry programs on
security_file_openandsecurity_bprm_check, also empty; - path check: an LSM program on
file_openthat resolves the path withbpf_d_pathand compares a prefix, and the same onbprm_check_security, sleepable, with no logging; - guard: the same
file_openprogram, andguard’s owncheck_exec: path, IMA hash, hash lookup and a ring buffer event, with a thread draining the buffer.
What a policy costs
Median (dot) and range (bar) over 18 rounds. Linux 6.4, 4 vCPUs.
The numbers as tables
| attached | µs per exec | range | ns per open() | range |
|---|---|---|---|---|
| nothing | 390.4 | 380–426.7 | 644.6 | 609.5–706.5 |
| lsm, empty | 395 | 377.7–420.6 | 722.5 | 685.5–778.8 |
| fentry, empty | 390.9 | 374.2–415.8 | 654 | 599.3–706.5 |
| path check | 393.8 | 379.9–464.5 | 737 | 701.9–996.6 |
| guard (hash + log) | 1365.2 | 1357–1409 | 749.2 | 697–803.3 |
| program (bpf_stats) | runs | ns per run |
|---|---|---|
| lsm on file_open, empty | 404000 | 17.3 |
| fentry on security_file_open, empty | 404000 | 16 |
| lsm on file_open, path check | 808000 | 65 |
| lsm on bprm_check_security, empty | 4000 | 47.4 |
| fentry on security_bprm_check, empty | 4000 | 19.8 |
| lsm.s on bprm_check_security, path check | 4000 | 131.4 |
| guard's check_exec (path, hash, log) | 4000 | 927206.9 |
Exec: posix_spawn and waitpid of a statically linked program that returns at once, wall time per process. open(): open and close of a tmpfs file. "path" resolves the path with bpf_d_path and compares a prefix; "guard" adds the IMA hash of the whole 756 KiB binary and a ring buffer event on every exec. Absolute times are a VM's; compare the rows.
The medians over both sittings’ 18 rounds together, with the full range; the two sittings were separate boots, whose baselines differed, so the differences quoted below are taken within each sitting:
| attached | µs per exec | ns per open() |
|---|---|---|
| nothing | 390.4 (380.0–426.7) | 644.6 (609.5–706.5) |
| lsm, empty | 395.0 (377.7–420.6) | 722.5 (685.5–778.8) |
| fentry, empty | 390.9 (374.2–415.8) | 654.0 (599.3–706.5) |
| path check | 393.8 (379.9–464.5) | 737.0 (701.9–996.6) |
| guard (hash + log) | 1365.2 (1357.0–1409.0) | 749.2 (697.0–803.3) |
An empty LSM program is not free, and costs more than an empty fentry program. On open(), the
empty LSM program moved the median by +84 to +88 ns in the two sittings, and the empty
fentry program by +1 to +3 ns,
although the kernel’s own accounting put both programs at about the same time inside the program
itself, 17.3 and 16.0 ns per run. The difference
is the trampoline. An fentry program only watches, so its trampoline runs the program and lets the
function carry on; an LSM program may replace the return value, so in 6.4 its trampoline is built
with BPF_TRAMP_F_CALL_ORIG: it calls the original bpf_lsm_file_open itself, keeps its return
value, and takes and drops a per-CPU reference on the trampoline image around the call. That is a
few dozen instructions more on every open, and in this nested virtual machine it showed as
84 to 88 ns.
Resolving a path is the next cheapest thing. The path check, bpf_d_path plus a prefix
compare, ran in 65.0 ns per call by bpf_stats and added 105 ns to an
open() that cost 622 to 664 ns with nothing attached. On exec, where a process costs
about 390 µs to create and reap, the empty programs and the path check
(131.4 ns per call) are lost in the variation between rounds: +4.6 and
+3.4 µs on the pooled medians, inside ranges tens of microseconds wide.
Hashing every exec is not cheap at all. guard added 979 to 985 µs to every exec, more than
tripling its cost, and bpf_stats put check_exec at 927 µs
per run. Almost all of that is SHA-1 over the whole 756 KiB static binary, recomputed on every exec
because no IMA policy is there to cache it; the ring buffer event and the map lookup are lost in it.
The lesson is not that BPF security is slow, but that a sleepable program can do slow things, and
that what a hook does matters far more than the hook.
One thing the interleaving cannot measure is what having bpf in the boot list costs with no
program attached, because that needs a different boot. One further sitting on a
stock boot, run the same way with only “nothing” and “fentry, empty”, gave a median open() of
591.8 ns (577.3–597.2) with nothing attached, against
644.6 ns on the boots with bpf listed. If that 53 ns is real, it is the
price of the 8 extra indirect calls an open() makes into bpf_lsm_* functions that do nothing,
a few nanoseconds each. But it is a difference between boots of a virtual machine, and the two boots
with bpf listed differed from each other by 42 ns on the same measurement, so I
would want many more boots before quoting it as a cost.
The projects, as of July 2023
Several open-source projects are built on all this, and they sit at different points on the line between observing and enforcing.
Tetragon, which Isovalent open-sourced in May 2022 (0.9 is the current release, from April),
attaches kprobes and tracepoints chosen by a policy file and filters events in the kernel, so that
only matching events reach user space. It can also act: its tracing policies have a Sigkill
action, which uses bpf_send_signal, and an Override action, which uses bpf_override_return on
functions that allow it. Its documentation’s own example of Override intercepts the
symlinkat system call when its first argument, a string read from user memory at entry, is
/etc/passwd. In the 0.9 sources there are no LSM programs; its enforcement is kprobe-based.
Falco detects rather than enforces: rules over a stream of system call events. Its new modern probe, built with CO-RE and the ring buffer and needing no kernel-specific build, was experimental in 0.34 in February and became an official driver in 0.35, on 7 June.
KubeArmor enforces through whichever LSM the node has: AppArmor, SELinux or the BPF LSM. Its
BPF-LSM enforcer, in its tree since v0.5 last July, attaches LSM programs to
bprm_check_security, file_open, socket_connect and the path_* hooks, among others; v0.10.2 is
from 27 June.
Tracee, from Aqua Security, is a detection tool; its 0.16 release on 2 July attaches 26 kprobes
to security_* functions, the callers of the LSM hooks, where, as the race section showed, the
arguments are the kernel’s objects rather than the caller’s memory.
All four need root, or the capabilities that amount to it, to load their programs.
The limits
It does nothing unless bpf is in the boot list. This is the trap. On a kernel booted without
it, the BPF LSM is compiled in but not registered, the bpf_lsm_* functions are never called, and
attaching programs to them still succeeds. Here is guard on a stock boot of the same kernel:
$ ./guard -d /tmp/ &
$ cat /sys/kernel/security/lsm
lockdown,capability,landlock,yama,apparmor
$ grep -o "lsm=[^ ]*" /proc/cmdline
(nothing: the kernel's built-in list)
$ bpftool prog show | grep " lsm " | cut -c1-40
8: lsm name check_exec tag 9f4f16a22bb
10: lsm name check_mmap tag 47a86df849
11: lsm name check_connect tag 87208ef
12: lsm name protect_guard tag e5bb526
$ /tmp/evil
evil ran
Loaded, attached, listed by bpftool, and enforcing nothing, with no error anywhere. A tool that
relies on the BPF LSM has to check /sys/kernel/security/lsm itself and refuse to start, or fall
back to something else, as KubeArmor does. And getting bpf into the list means changing the kernel
command line and rebooting, on every machine; neither Ubuntu 23.04 nor 22.04 has it there by
default.
There is a way round the boot list, and it shows how thin the line between these program types is.
fmod_ret programs, the ones that may replace a function’s return value, are allowed on the error
injection list and also, the 6.4 verifier’s check_attach_modify_return says, on any function whose
name begins with security_. So a program on security_file_open itself can refuse an open on a
kernel that has trampolines and BTF, whether or not bpf is in the list:
// fmodret.bpf.c — refusing an open without the BPF LSM: fmod_ret on security_file_open
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#define EPERM 1
SEC("fmod_ret/security_file_open")
int BPF_PROG(no_secret, struct file *file, int ret)
{
char path[32] __attribute__((aligned(8))) = {};
if (ret) /* another fmod_ret program has already answered */
return ret;
bpf_d_path(&file->f_path, path, sizeof(path));
if (*(__u64 *)path == *(__u64 *)"/tmp/rac" &&
*(__u64 *)(path + 8) == *(__u64 *)"e/secret" && path[16] == 0)
return -EPERM; /* security_file_open() itself never runs */
return 0; /* run security_file_open(), every LSM included */
}
char LICENSE[] SEC("license") = "GPL";
On the same stock boot:
$ cat /sys/kernel/security/lsm
lockdown,capability,landlock,yama,apparmor
$ bpftool prog load fmodret.bpf.o /sys/fs/bpf/fmodret autoattach
$ cat /tmp/race/public
public
$ cat /tmp/race/secret
cat: /tmp/race/secret: Operation not permitted
$ bpftool prog show name no_secret | head -1
7: tracing name no_secret tag 9dc00d5ab4e9fe94 gpl
$ rm /sys/fs/bpf/fmodret
$ cat /tmp/race/secret
SECRET
It is a blunter instrument than an LSM program. When it returns non-zero, security_file_open() is
skipped entirely, so AppArmor, Landlock and the rest are not asked about that open at all; when it
returns 0 they run as usual. And the security_* functions, unlike the hooks, are internal kernel
functions that nobody has promised to keep.
Only root can load it. Loading an LSM program needs CAP_BPF and CAP_PERFMON, the
program must carry a GPL-compatible licence, and unprivileged BPF has been off by default since
5.16. That is as it should be, but it means the policy is only as trustworthy as root.
An attacker with root wins. guard -p refuses signals from other processes, including root’s:
$ ./guard -p -t 6 &
$ kill -TERM 276
bash: line 1: kill: (276) - Operation not permitted
$ kill -KILL 276
bash: line 1: kill: (276) - Operation not permitted
$ bpftool link show | grep -A1 tracing
[link 1, the kernel's own hid_tail_call program, trimmed]
14: tracing prog 61
prog_type lsm attach_type lsm_mac
--
15: tracing prog 63
prog_type lsm attach_type lsm_mac
--
16: tracing prog 64
prog_type lsm attach_type lsm_mac
--
17: tracing prog 65
prog_type lsm attach_type lsm_mac
$ bpftool link detach id 14
Error: failed link detach: Operation not supported
The kill fails, and links of this kind cannot be detached from outside; the programs stay attached
until the process holding the links exits, or the six seconds I gave it run out. Nor can another
program of root’s overrule a refusal: the hooks stop at the first non-zero answer, so a second BPF
program that returns 0 changes nothing. But this is a lock on a door in a house whose owner has
every key. Root can load a kernel module, unless lockdown forbids it; overwrite the policy’s binary
or its configuration on disk; edit the boot command line and reboot without bpf; or simply stop
whatever starts the policy at boot. guard would need LSM programs on the bpf hook, on module
loading, on its own files and on the boot loader to begin to close those doors, and the last one
it cannot reach at all. The BPF LSM, like every LSM, is a way for root to restrict everyone else,
including root’s own processes once they are compromised. It is not a way to restrict an
administrator who is the attacker.
Policies have edges. The session showed three: interpreters run scripts the exec hook never
sees, a hash deny list misses a modified copy, and IPv4-only address checks miss IPv6. Each is
fixable, and each is the kind of thing that separates a demonstration like guard from the
projects above.
What we covered
- Tracing programs observe; their return values are ignored. Enforcement needs a hook whose answer the kernel obeys, at a point where the kernel has settled what the operation is.
- The LSM framework provides 247 such hooks in 6.4. The modules in the boot list are called in turn, and the first non-zero return refuses the operation.
- The BPF LSM (5.7) registers a no-op function for every hook and lets BPF programs attach to it
through a trampoline; a program returns 0 or
-EPERM. The verifier does not check the value. - A tracepoint at syscall entry reads the caller’s memory, and a second thread can change it before the kernel copies it: over 100,000 opens the tracepoint was wrong 836 times, while the LSM hook, deciding on the file the kernel resolved, refused all 96,943 opens of the forbidden file.
guardrefused execs by path (with symbolic links resolved) and by IMA hash, refused the dynamic loader’s mapping of a forbidden file, and refusedconnect()to the metadata address, logging every decision through a ring buffer. A modified copy andsh scriptgot through.- Sleepable programs (5.10) may wait;
bpf_ima_file_hash(5.18) andbpf_copy_from_userneed them, and the verifier refuses the call from a non-sleepable program. bpf_send_signal(5.3) kills at syscall entry, but the system call completes first:rmdied and the file was gone.- kfuncs (5.13) are kernel functions registered for BPF, typed by BTF, with ownership rules the verifier enforces and no ABI promise. New functionality arrives as kfuncs; the helper count has been 211 since 6.2.
- An empty LSM program added 84 to 88 ns to an
open(), an empty fentry program 1 to 3 ns, and a path check 105 ns; per exec onlyguard’s hashing showed, at 979 to 985 µs, because without an IMA policy the whole binary is hashed every time. - None of it works unless
bpfis in the boot list, and attaching without it fails silently.
A later part goes back to the network, and to the hooks where packets, rather than processes, are allowed or refused.
A note on the evidence
What I ran, and where. Every listing in this post is pasted from a real run, and the C files,
the header, the bpftrace script and the build commands were extracted from this page and built as
shown. The machine was a KVM virtual machine with 4 virtual CPUs and 4 GiB of memory, itself
running nested inside another virtual machine, booting the Ubuntu mainline build of Linux 6.4
(6.4.0-060400-generic #202306271339, built from the v6.4 tag two days after its release) with
bpf added to the end of the lsm= list on the kernel command line, as shown earlier, on a minimal Ubuntu
23.04 userland built from the release archive only: clang 15.0.7, libbpf 1.1.0, bpftrace 0.17.0,
Python 3.11. bpftool v7.1.0 comes from linux-tools-6.2.0-20-generic, which I installed into that
userland from the 23.04 archive; Ubuntu’s bpftool wrapper refuses to run on a kernel it has no
tools package for, so the bpftool in the build commands is that binary, put first on the PATH.
libbpf 1.2 had been out since May, but nothing here needs it, so I used the 1.1 that Ubuntu 23.04
ships. The root file system was shared from the host over 9p, and /tmp was a tmpfs. Every command
ran as root, from scripts. The two contrast runs, guard doing nothing and the fmod_ret program,
booted the same kernel without the lsm= parameter.
What I trimmed. The loaded_at lines of bpftool prog show, which carry the time of the run,
are cut and marked. bpftool link show also listed one link that is not ours, a modify_return program
called hid_tail_call that the kernel’s HID-BPF support loads by itself at boot, which I cut and
marked. Python’s
tracebacks are cut to their last line, and the two python3 -c commands are shown with single
quotes where the script escaped double quotes. The verifier logs are their last lines. bpftrace 0.17
printed a warning, Addrspace mismatch, about comparing a user-space string in the rm one-liner,
which I left out; the probe worked as shown. The hook map’s output had two more openat calls, made
by the dynamic loader while hookmap started; the figure uses the third, the one in hookmap.c.
The race. race ran three times in one boot, 100,000 opens each, on 4 virtual CPUs: without
enforcement, with it, and without it again. The post shows the first two; the third gave
91,236 reads of the secret, 339 and 732 disagreements.
The proportions depend on the scheduler and the machine and will differ elsewhere; that there are
any disagreements is the point.
The timings. Every timing came from vrun-alone sittings, with no other test virtual machine
running: two sittings on boots with bpf in the LSM list, each of 9
rounds with the five conditions interleaved and their order rotated, and one on a stock boot with
only “nothing” and “fentry, empty”. A round spawned the static program 2,000 times and opened a
tmpfs file 200,000 times. The medians and ranges are over all 18 rounds of the
first kind. The harness that attached and detached the programs, bench.c with its
bench.bpf.c, is not printed; it links guard’s own skeleton for the last condition, and its
path programs are guard’s path check without the logging. Per-program times are the kernel’s
bpf_stats, from a separate pass with statistics enabled after each sitting, and include the
statistics’ own clock reads. Absolute numbers from a nested virtual machine do not transfer to
hardware; the differences between conditions are what I rely on. One earlier stock-boot sitting
was discarded unused, because other virtual machines may have been running on the host during it.
What I cited rather than ran. The kernel version each feature arrived in, checked by asking which
release tag first contains it: bpf_override_return 4.16, the lsm= parameter 5.1,
bpf_send_signal 5.3, fentry and fexit 5.5, LSM programs and fmod_ret 5.7, sleepable programs,
bpf_d_path and bpf_copy_from_user 5.10, bpf_ima_inode_hash 5.11, kfuncs 5.13,
bpf_ima_file_hash 5.18, bpf_lookup_user_key and bpf_verify_pkcs7_signature 6.1,
bpf_task_from_pid 6.2. The hook definitions, call_int_hook, the bpf_lsm_* functions, the
sleepable list, the bpf_d_path rules, the verifier’s comment on return values, the trampoline
flags and IMA’s fallback hashing are read from the 6.4 sources; the helper and kfunc counts are
counted in the 6.1, 6.2 and 6.4 sources, and the quotations come from 6.4’s
Documentation/bpf/bpf_design_QA.rst. Ubuntu’s CONFIG_LSM is from the .config in
linux-headers-6.2.0-20-generic and from 22.04’s config-5.15.0-25-generic. The projects are
described from their release pages and from their source trees at the release current on this
date: Tetragon v0.9.0, Falco’s 0.34 and 0.35 announcements, KubeArmor v0.5 and v0.10.2, Tracee
v0.16.0.
What I’d still change. The timings come from one nested virtual machine, and the exec numbers
are dominated by process creation, which hides anything under a few microseconds; a bare-metal run
with a tighter exec benchmark would show the empty programs’ cost on exec too. guard with an IMA
policy that measures executables, so that hashes are cached, is the version worth timing next. And
guard itself would need IPv6, an allow list instead of a deny list, and a check on the bpf hook
before I would let it near a real machine.
Watching Every Exec, and Saying No