Who Is Allowed to Load a Program

Contents
On Linux 6.18, a light skeleton carrying a 375-byte signature loaded a 162-instruction loader program, and the kernel checked that signature against a keyring before its verifier had read a single instruction. Then I changed fifteen bytes of the program the loader carried: the kernel still accepted the signature, and the loader refused to load its cargo. I patched the loader to match, and the kernel refused the signature. Then, as root, I signed the same program with a key I had made a minute earlier, and the kernel accepted it without complaint.
That last result is what this post is about. For three and a half years this series has asked what a BPF program may do once it is loaded. This part asks the question that was underneath all along: who is allowed to load one, and how does the kernel know it is the program somebody meant?
This is Part 15 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 Ubuntu’s mainline build of Linux 6.18, released on 30 November, under an Ubuntu 24.04 userland, with libbpf and bpftool built from the 6.18 source tree, because no released version of either can sign yet. The output is pasted from those runs, and the note at the end says exactly where and how.
The question under every part
Every part of this series so far has been about what a BPF program may do. The verifier, which Part 4 spent a whole post being refused by, proves that a program terminates, stays inside its memory and calls only what its type allows. Maps, kfuncs, arenas and struct_ops widened what “allowed” means, each time with a new rule the verifier can check.
Underneath all of that sat a second question that the verifier cannot answer: who may hand the kernel a program in the first place, and how does the kernel know that the program it is holding is the one somebody meant to send? The verifier looks at the instructions. It has no idea who wrote them, who built them, whether the bytes changed on the way, or whether anyone with authority over the machine agreed that this program, as opposed to some other safe program, should run.
Part 1 met this question at its end, in a section called “Who is allowed to do this”, where an
ordinary user ran the counter and got EPERM. The answer then, on a stock Ubuntu 22.04, was
“root, more or less”. Three and a half years and twenty-one kernel releases later the answer has more parts,
and 6.18, the long-term kernel released two weeks ago, added the last one I had been waiting for:
the kernel can now check a signature on a BPF program. This part takes the answer apart in the
order the pieces arrived.
Who may load a program: eleven years of answers
Each card is one change to who may load, what may be checked at load time, or what can be proven about the program.
Linux 3.18 · Dec 2014
Only root, for everything
The first bpf() system call refuses every command, even reading a map, without CAP_SYS_ADMIN. The verifier exists, but nobody unprivileged ever reaches it.
Linux 4.4 · Jan 2016
Anyone, for socket filters
Unprivileged users may load socket filters, the one program type that only sees packets of a socket they already own. The verifier becomes the only line of defence for them, and the sysctl kernel.unprivileged_bpf_disabled (0 or 1) arrives with it.
Linux 4.15 · Jan 2018
Security modules get a say
LSM hooks on the bpf() command and on BPF maps and programs, so SELinux can label and mediate them. The same release adds CONFIG_BPF_JIT_ALWAYS_ON as a Spectre response.
Linux 5.7 · May 2020
BPF can be the security module
The BPF LSM: programs attached to LSM hooks that return an allow or deny decision, including on bpf() itself. Policy for BPF can now be written in BPF.
Linux 5.8 · Aug 2020
CAP_BPF and CAP_PERFMON
Loading BPF no longer needs all of CAP_SYS_ADMIN. CAP_BPF for BPF itself, plus CAP_PERFMON for tracing or CAP_NET_ADMIN for networking program types.
Linux 5.13 · Jun 2021
A switch for the default
CONFIG_BPF_UNPRIV_DEFAULT_OFF and sysctl value 2: unprivileged loading off at boot, re-enabled only by an administrator. Ubuntu turns it on with this kernel.
Linux 5.14 · Aug 2021
The loader program
BPF_PROG_TYPE_SYSCALL and the light skeleton: a BPF program that makes the bpf() calls libbpf would have made. Its cover letter calls it "a first step towards signed bpf programs".
Linux 5.16 · Jan 2022
Off by default, upstream
The Kconfig default flips, citing Spectre-type attacks: a default kernel boots with unprivileged_bpf_disabled = 2.
Linux 6.9 · May 2024
The BPF token
An administrator delegates chosen commands, map, program and attach types to a user namespace through a BPF filesystem mount. Capabilities are then checked in that namespace, and four new LSM hooks see each token.
Linux 6.15 · May 2025
Hooks learn who is calling
The BPF LSM hooks get a flag saying whether a bpf() command came from user space or from inside the kernel, such as from a loader program. Its stated purpose is program signing.
Linux 6.18 · Nov 2025
Signed programs
BPF_PROG_LOAD takes a PKCS#7 signature and a keyring. The kernel checks the loader's instructions against it; the loader checks the hash of everything else. Exclusive maps and map hashes come with it, and bpftool signs light skeletons.
Kernel versions are the first release containing each change's commit, checked against Linus Torvalds's tree. Not shown: RFC 9669 (October 2024), which standardised the instruction set and says nothing about who may load it.
The program
One program carries the whole post. It is Part 1’s counter, moved from the execve() tracepoint
to the raw tracepoint sched_process_exec, which fires after a successful exec, when the process
already carries the new program’s name. So where Part 1 counted thirteen calls from sh, this one
counts which programs started:
// execcount.bpf.c — count the programs started, by the name they start under
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
struct comm_key {
char comm[16];
};
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 1024);
__type(key, struct comm_key);
__type(value, __u64);
} counts SEC(".maps");
SEC("raw_tracepoint/sched_process_exec")
int count_exec(void *ctx)
{
struct comm_key key = {};
__u64 one = 1, *val;
bpf_get_current_comm(&key.comm, sizeof(key.comm));
val = bpf_map_lookup_elem(&counts, &key);
if (val)
__sync_fetch_and_add(val, 1);
else
bpf_map_update_elem(&counts, &key, &one, BPF_NOEXIST);
return 0;
}
char LICENSE[] SEC("license") = "GPL";
The user-space half is built three ways from one file. With no flags it includes a normal
skeleton, the one Part 1 used: libbpf opens the object, relocates it and loads it. With -DLIGHT
it includes a light skeleton, the kind
Part 6 built, where a small BPF program does the
loading. With -DSIGNED as well, it includes a light skeleton that bpftool has signed, and takes
the keyring to check the signature against as its second argument:
// execcount.c — load, attach, count for N seconds, print; built three ways
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <bpf/bpf.h>
#if defined(SIGNED)
#include "execcount.signed.lskel.h" /* loader program, signed by bpftool -S */
#define MAP_FD(s) ((s)->maps.counts.map_fd)
#elif defined(LIGHT)
#include "execcount.lskel.h" /* loader program, unsigned */
#define MAP_FD(s) ((s)->maps.counts.map_fd)
#else
#include <bpf/libbpf.h>
#include "execcount.skel.h" /* the object itself, relocated by libbpf */
#define MAP_FD(s) bpf_map__fd((s)->maps.counts)
#endif
int main(int argc, char **argv)
{
int seconds = argc > 1 ? atoi(argv[1]) : 5, err;
char key[16], next[16], *prev = NULL;
struct execcount *skel;
__u64 count;
skel = execcount__open();
if (!skel) {
fprintf(stderr, "open: %s\n", strerror(errno));
return 1;
}
#ifdef SIGNED
/* which keyring the kernel checks the signature against */
skel->keyring_id = argc > 2 ? strtol(argv[2], NULL, 0) : 0;
#endif
err = execcount__load(skel);
if (!err)
err = execcount__attach(skel);
if (err) {
fprintf(stderr, "load/attach: %d (%s)\n", err, strerror(-err));
execcount__destroy(skel);
return 1;
}
printf("counting exec() for %d s\n", seconds);
fflush(stdout);
sleep(seconds);
while (bpf_map_get_next_key(MAP_FD(skel), prev, next) == 0) {
bpf_map_lookup_elem(MAP_FD(skel), next, &count);
printf("%-16s %llu\n", next, (unsigned long long)count);
memcpy(key, next, sizeof(key));
prev = key;
}
execcount__destroy(skel);
return 0;
}
Root, then capabilities
For its first year, the answer to “who may load” was simple. The bpf() system call that 3.18
added in December 2014 began, before looking at which command it had been given, with
if (!capable(CAP_SYS_ADMIN)) return -EPERM;. Even reading a map needed root.
4.4, in January 2016, opened one door: unprivileged users could load socket filters, the program
type that only ever sees the packets of a socket its owner already holds, and could create the
maps those filters use. A sysctl, kernel.unprivileged_bpf_disabled, could shut the door again.
For six years that door was where the verifier was the only thing between an arbitrary user and
the kernel, and it is where the verifier’s bugs turned into privilege escalations. Spectre made it
worse in 2018: a bounds check the verifier insisted on is respected by the processor
architecturally and can be bypassed speculatively, so a proof about the program’s paths stopped
being a proof about what the CPU does. 5.13 gave the sysctl a value 2, “disabled, but an
administrator may turn it back on”, and a Kconfig option to boot that way; 5.16, in January
2022, made it the default upstream, citing exactly those attacks.
Meanwhile the privileged side was split up. Until 5.8, “privileged” meant CAP_SYS_ADMIN, the
capability that also mounts filesystems and does a hundred other things. 5.8 added CAP_BPF
for BPF itself and CAP_PERFMON for observing the system, and the rules became a matrix: a
program type that reads kernel memory needs CAP_BPF and CAP_PERFMON; one that touches the
network stack needs CAP_BPF and CAP_NET_ADMIN; socket filters and cgroup socket-buffer
programs need nothing at all when unprivileged BPF is enabled.
That matrix is easy to measure. This program tries to create a map and load a trivial two-instruction program of six types, and reports what the kernel said to each:
// tryload.c — which program types may this process load?
#define _GNU_SOURCE
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <bpf/bpf.h>
static const struct bpf_insn ret0[] = { /* r0 = 0; exit */
{ .code = BPF_ALU64 | BPF_MOV | BPF_K, .dst_reg = 0, .imm = 0 },
{ .code = BPF_JMP | BPF_EXIT },
};
static void try(const char *name, enum bpf_prog_type type,
enum bpf_attach_type attach)
{
LIBBPF_OPTS(bpf_prog_load_opts, o, .expected_attach_type = attach);
int fd = bpf_prog_load(type, NULL, "GPL", ret0, 2, &o);
printf(" %s=%s", name, fd >= 0 ? "ok" : strerrorname_np(errno));
if (fd >= 0)
close(fd);
}
int main(void)
{
int fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, 4, 8, 1, NULL);
printf("map=%s", fd >= 0 ? "ok" : strerrorname_np(errno));
try("socket_filter", BPF_PROG_TYPE_SOCKET_FILTER, 0);
try("cgroup_skb", BPF_PROG_TYPE_CGROUP_SKB, BPF_CGROUP_INET_INGRESS);
try("xdp", BPF_PROG_TYPE_XDP, BPF_XDP);
try("sched_cls", BPF_PROG_TYPE_SCHED_CLS, 0);
try("raw_tracepoint", BPF_PROG_TYPE_RAW_TRACEPOINT, 0);
try("kprobe", BPF_PROG_TYPE_KPROBE, 0);
printf("\n");
return 0;
}
The 6.18 build I am using has CONFIG_BPF_UNPRIV_DEFAULT_OFF=y, so it boots with the sysctl at 2.
I ran the program as uid 1000 under setpriv, which can hand a non-root process a chosen set of
capabilities through the ambient set, so they survive the exec. Each line below is one run of
setpriv --reuid=1000 --regid=1000 --clear-groups --inh-caps=-all,<set> --ambient-caps=-all,<set> ./tryload,
labelled with the set:
$ sysctl kernel.unprivileged_bpf_disabled
kernel.unprivileged_bpf_disabled = 2
none map=EPERM socket_filter=EPERM cgroup_skb=EPERM xdp=EPERM sched_cls=EPERM raw_tracepoint=EPERM kprobe=EPERM
+bpf map=ok socket_filter=ok cgroup_skb=ok xdp=EPERM sched_cls=EPERM raw_tracepoint=EPERM kprobe=EPERM
+bpf,+perfmon map=ok socket_filter=ok cgroup_skb=ok xdp=EPERM sched_cls=EPERM raw_tracepoint=ok kprobe=ok
+bpf,+net_admin map=ok socket_filter=ok cgroup_skb=ok xdp=ok sched_cls=ok raw_tracepoint=EPERM kprobe=EPERM
+sys_admin map=ok socket_filter=ok cgroup_skb=ok xdp=ok sched_cls=ok raw_tracepoint=ok kprobe=ok
$ sysctl -w kernel.unprivileged_bpf_disabled=0
kernel.unprivileged_bpf_disabled = 0
none map=ok socket_filter=ok cgroup_skb=ok xdp=EPERM sched_cls=EPERM raw_tracepoint=EPERM kprobe=EPERM
What uid 1000 may load, by capability
One map and six two-instruction programs, attempted with each set of capabilities on Linux 6.18.
Measured, not derived: every cell is what bpf() returned. Columns are grouped by the extra capability the kernel asks for: none beyond CAP_BPF, CAP_NET_ADMIN, CAP_PERFMON. CAP_SYS_ADMIN still implies all three. The sysctl only changes the row with no capabilities.
Read across the rows. With no capabilities and the sysctl at 2, nothing works, not even a map:
unprivileged_bpf_disabled blocks map creation too. With CAP_BPF alone, maps and the two
“harmless” types load, but XDP and traffic control need CAP_NET_ADMIN, and the tracing types
need CAP_PERFMON. CAP_SYS_ADMIN still implies everything, for compatibility. And with the
sysctl set back to 0 by root, uid 1000 with no capabilities at all can create maps and load socket
filters and cgroup socket-buffer programs again, which is the 2016 door, still there behind its
switch. (I ran every row again at 0; only the first changed. The figure has both.)
The capability split is what makes the counter deployable as something other than root. Give
the process CAP_BPF and CAP_PERFMON and nothing else, and uid 1000 can run it; give it
CAP_BPF alone, and the raw tracepoint is refused:
$ setpriv --reuid=1000 --regid=1000 --clear-groups --inh-caps=-all,+bpf,+perfmon --ambient-caps=-all,+bpf,+perfmon ./execcount 3
counting exec() for 3 s
ls 3
true 10
$ setpriv --reuid=1000 --regid=1000 --clear-groups --inh-caps=-all,+bpf --ambient-caps=-all,+bpf ./execcount 1
libbpf: prog 'count_exec': BPF program load failed: -EPERM
libbpf: prog 'count_exec': failed to load: -EPERM
libbpf: failed to load object 'execcount'
libbpf: failed to load BPF skeleton 'execcount': -EPERM
load/attach: -1 (Operation not permitted)
CAP_PERFMON is not a small grant. A process with it and CAP_BPF can load a program that reads
any kernel memory with bpf_probe_read_kernel, which is everything on the machine. The split made
the grant narrower than CAP_SYS_ADMIN; it did not make it safe to hand out.
Delegating a slice: the BPF token
Capabilities are checked in the initial user namespace. Root inside a container’s user namespace
is uid 1000, or 100000, outside it, and as far as bpf() is concerned it has nothing. That is
correct, and it is a problem for exactly the software that wants BPF most: a networking agent or
a tracer that runs in a container.
The BPF token, merged in 6.9 after an earlier version was pulled out of the 6.8 merge window,
is the answer, and
Part 13 used it to create maps
from a user namespace. It is a delegation, made by the host, through a filesystem. A BPF
filesystem instance can be created owned by a user namespace, and the host, with
CAP_SYS_ADMIN in the initial namespace, sets four mount options on it: delegate_cmds (which
bpf() commands), delegate_maps, delegate_progs and delegate_attachs (which map, program and
attach types). Inside the namespace, BPF_TOKEN_CREATE on that mount gives a token file
descriptor. Any command that carries the token is then checked against two things: the mount’s
lists, and the capabilities the caller has in the namespace that owns the token, where its root
has all of them. A container cannot widen its own delegation, because only the host can set the
options.
The kernel side of the check is a few lines in bpf_prog_load(), from the 6.18 source:
bpf_cap = bpf_token_capable(token, CAP_BPF);
...
if (sysctl_unprivileged_bpf_disabled && !bpf_cap)
goto put_token;
...
if (is_net_admin_prog_type(type) && !bpf_token_capable(token, CAP_NET_ADMIN))
goto put_token;
if (is_perfmon_prog_type(type) && !bpf_token_capable(token, CAP_PERFMON))
goto put_token;
bpf_token_capable() asks ns_capable() against the token’s namespace, and then an LSM hook,
security_bpf_token_capable, so a security module can veto what the token allows.
Setting one up needs two processes, because the namespace must create the filesystem and the host
must configure it. This one runs any command as uid 1000 in a fresh user and mount namespace, with
a BPF filesystem on /sys/fs/bpf that delegates what the first four arguments say:
// tokenrun.c — run a command as uid 1000 in a fresh user namespace whose
// /sys/fs/bpf is a BPF filesystem delegating what argv[1..4] list
// usage: tokenrun <cmds> <maps> <progs> <attachs> command [args...]
#define _GNU_SOURCE
#include <fcntl.h>
#include <sched.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <linux/mount.h>
static void sendfd(int sock, int fd) /* SCM_RIGHTS: hand over a descriptor */
{
char c = 0, buf[CMSG_SPACE(sizeof(int))] = {};
struct iovec io = { &c, 1 };
struct msghdr m = { .msg_iov = &io, .msg_iovlen = 1,
.msg_control = buf, .msg_controllen = sizeof(buf) };
struct cmsghdr *cm = CMSG_FIRSTHDR(&m);
cm->cmsg_level = SOL_SOCKET;
cm->cmsg_type = SCM_RIGHTS;
cm->cmsg_len = CMSG_LEN(sizeof(int));
memcpy(CMSG_DATA(cm), &fd, sizeof(int));
sendmsg(sock, &m, 0);
}
static int recvfd(int sock)
{
char c, buf[CMSG_SPACE(sizeof(int))];
struct iovec io = { &c, 1 };
struct msghdr m = { .msg_iov = &io, .msg_iovlen = 1,
.msg_control = buf, .msg_controllen = sizeof(buf) };
int fd = -1;
if (recvmsg(sock, &m, 0) == 1)
memcpy(&fd, CMSG_DATA(CMSG_FIRSTHDR(&m)), sizeof(int));
return fd;
}
static void put(const char *path, const char *s)
{
int fd = open(path, O_WRONLY);
if (fd < 0 || write(fd, s, strlen(s)) < 0)
perror(path);
close(fd);
}
static int child(int sock, char **cmd)
{
int fs, mnt;
if (setgid(1000) || setuid(1000)) /* no host privilege from here on */
return 1;
prctl(PR_SET_DUMPABLE, 1); /* so it may write its own uid_map */
if (unshare(CLONE_NEWUSER))
return perror("unshare user"), 1;
put("/proc/self/setgroups", "deny");
put("/proc/self/uid_map", "0 1000 1"); /* root in here is uid 1000 outside */
put("/proc/self/gid_map", "0 1000 1");
if (unshare(CLONE_NEWNS))
return perror("unshare mnt"), 1;
mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL);
fs = syscall(SYS_fsopen, "bpf", 0); /* a BPF FS owned by this namespace */
sendfd(sock, fs); /* the host sets the delegation */
mnt = recvfd(sock);
if (mnt < 0 || syscall(SYS_move_mount, mnt, "", AT_FDCWD, "/sys/fs/bpf",
MOVE_MOUNT_F_EMPTY_PATH))
return perror("mount"), 1;
execvp(cmd[0], cmd);
return perror(cmd[0]), 1;
}
int main(int argc, char **argv)
{
static const char *opt[] = { "delegate_cmds", "delegate_maps",
"delegate_progs", "delegate_attachs" };
int sv[2], fs, mnt, status, i;
pid_t pid;
if (argc < 6)
return fprintf(stderr, "usage: %s cmds maps progs attachs command...\n",
argv[0]), 2;
socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
pid = fork();
if (pid == 0)
return child(sv[1], argv + 5);
fs = recvfd(sv[0]); /* we are real root: configure it */
for (i = 0; i < 4; i++)
if (syscall(SYS_fsconfig, fs, FSCONFIG_SET_STRING, opt[i], argv[i + 1], 0))
perror(opt[i]);
syscall(SYS_fsconfig, fs, FSCONFIG_CMD_CREATE, NULL, NULL, 0);
mnt = syscall(SYS_fsmount, fs, 0, 0);
sendfd(sv[0], mnt);
waitpid(pid, &status, 0);
return WEXITSTATUS(status);
}
It runs the counter unchanged. libbpf, since 1.4, looks for a token-enabled BPF filesystem at
/sys/fs/bpf and, if it finds one, makes a token and passes it with every command. First a
delegation that covers the counter, its hash map and its raw tracepoint, while the host, outside
the namespace, runs /bin/true ten times and ls three times:
$ ./tokenrun map_create:prog_load:btf_load hash socket_filter:raw_tracepoint any sh -c 'id; bpftool token list; ./execcount 3'
uid=0(root) gid=0(root) groups=0(root)
token_info /sys/fs/bpf
allowed_cmds:
map_create prog_load btf_load
allowed_maps:
hash
allowed_progs:
socket_filter raw_tracepoint
allowed_attachs:
any
libbpf: Failed to bump RLIMIT_MEMLOCK (err = -EPERM), you might need to do it explicitly!
counting exec() for 3 s
true 10
ls 3
The process that printed that has no capabilities on the host. bpftool token list, which is new
in the 6.18 tree’s bpftool and in no release yet, shows what the mount delegates. The delegation
lists socket_filter although the counter has no socket filter, because the first thing libbpf
does with any object is load a two-instruction socket filter to see whether it can load anything
at all, Part 1’s probe; without socket_filter in the list, that probe fails and libbpf gives up
before it reaches the counter. The RLIMIT_MEMLOCK warning is libbpf’s too: a probe that doesn’t
use the token is refused, so libbpf falls back to raising a limit the namespace may not raise, and
carries on. And the counter counted the
host’s thirteen execs. That is not a leak in the token: a raw tracepoint on
sched_process_exec fires for every exec on the machine, in every namespace, because that is what
the hook is. Delegating a tracing program type delegates the view a tracing program has, which is
the whole kernel. The token makes it possible to give a container that view without giving it the
host’s root; whether to give it at all is a decision about trust that the kernel leaves to whoever
writes the mount options.
The same binary with a delegation that only covers socket filters:
$ ./tokenrun map_create:prog_load:btf_load hash socket_filter any ./execcount 1
libbpf: Failed to bump RLIMIT_MEMLOCK (err = -EPERM), you might need to do it explicitly!
libbpf: prog 'count_exec': BPF program load failed: -EPERM
libbpf: permission error while running as root; try raising 'ulimit -l'? current value: 8.0 MiB
libbpf: prog 'count_exec': failed to load: -EPERM
libbpf: failed to load object 'execcount'
libbpf: failed to load BPF skeleton 'execcount': -EPERM
load/attach: -1 (Operation not permitted)
Safe is not the same as approved
Everything so far decides who may call bpf(). None of it says anything about which program
they send. Once a process may load a raw tracepoint program, it may load any raw tracepoint
program the verifier accepts, and the verifier accepts a great deal. A program that copies the
arguments of every execve() on the machine into a ring buffer for a process to ship elsewhere
terminates, stays inside its memory and calls only allowed helpers. It is perfectly safe in the
verifier’s sense. Whether it is the program the machine’s owner intended to run is a different
question, and the kernel had, until this release, no way to ask it.
The usual answer for code entering a kernel is a signature. Kernel modules have been signed since
3.7; with CONFIG_MODULE_SIG_FORCE, an unsigned module does not load. IMA, the integrity
measurement architecture, can measure and appraise files as they are executed, mapped or read by
the kernel, including modules and firmware. Neither covers BPF. A BPF program never arrives as a
file: it arrives as an array of instructions in a bpf() system call, built in memory by whatever
loader the caller ran. IMA could check the loader binary on its way to exec, but the bytes the
loader then passes to the kernel are not a file anyone can measure.
What the kernel has had, since 4.15, is a place to make a decision. Security modules get hooks on
bpf(): one for every command (security_bpf), and hooks for maps and programs as they are
created, which SELinux uses to label them. 6.9 reshaped the program hook into
security_bpf_prog_load, which sees the program and the full union bpf_attr before the verifier
runs, and added hooks for tokens. And since 5.7 a security module can itself be written in BPF:
the BPF LSM attaches programs to LSM hooks and uses their return value as the decision. So BPF
can police BPF. What was missing was anything trustworthy for such a policy to decide on: the
hook could see the instructions, but not where they came from.
Why you can’t just sign the object file
The obvious design is to sign execcount.bpf.o at build time, and have the kernel check the
signature against the instructions it receives. It doesn’t work, because the instructions the
kernel receives are not the instructions in the object file. libbpf rewrites them on the way, and
the rewriting depends on the machine:
- Map references. The object says “the address of map
counts” as a relocation. libbpf creates the map, gets a file descriptor, and writes that number into the instruction (Part 1 watched it put descriptor 4 into instruction 10). The descriptor differs from run to run. - CO-RE. Part 6 showed libbpf rewriting the offset
of
task_struct.pidfrom 2384 to 2336 or 2496, depending on the kernel it found. A program that reads kernel structures is a different sequence of bytes on every kernel it runs on. - kfuncs and kernel symbols. Calls to kfuncs and references to kernel variables are resolved to BTF IDs of the running kernel.
- Feature fallbacks. libbpf probes the kernel and adjusts: it strips BTF the kernel doesn’t understand, rewrites some helper calls and global data accesses for older kernels.
So the thing that was signed is not the thing that is loaded. Signing the relocated instructions on the target machine would need the signing key on every target machine, which defeats the point. This is why BPF signing took years: Alexei Starovoitov’s light skeleton, which Part 6 took apart, was introduced in 5.14 in 2021 as “a first step towards signed bpf programs”, and the step after it arrived only now.
Sign the loader instead
The light skeleton moves the rewriting out of user space. bpftool runs libbpf at build time,
records every bpf() call libbpf would have made, and turns the recording into two things: a
small BPF program of type BPF_PROG_TYPE_SYSCALL, the loader, and a block of data holding the
real program’s instructions, its BTF and its maps’ descriptions. At run time the skeleton loads
the loader, runs it once with BPF_PROG_RUN, and the loader, inside the kernel, makes the
bpf() calls itself: it creates the maps, patches their descriptors into the real program, and
loads it, handing the CO-RE records to the kernel, which applies them against its own BTF (it can
since 5.17).
The loader is the same on every machine. It contains no descriptors and no offsets, because everything machine-specific happens when it runs. So the loader’s instructions can be signed at build time, and that is KP Singh’s design, merged for 6.18 after a summer of argument that I come back to below. Signing the loader is not enough on its own, because the loader takes its orders from the data block, which lives in a map that user space fills in. So the design has three parts:
- The signature covers the loader.
BPF_PROG_LOADhas three new attributes:signature,signature_sizeandkeyring_id. If a signature is present, the kernel checks it, a PKCS#7 signature over the loader’s instructions exactly as user space passed them, against the named keyring, before the verifier runs. A bad signature fails the load. - The loader checks the data. bpftool computes the SHA-256 of the data block at build time
and compiles it into the loader as constants. User space puts the block in a single-element
array map and freezes it, so user space can no longer write to it. Asking the kernel for the
map’s info with a hash buffer makes the kernel compute the SHA-256 of the frozen contents
itself, and keep it in the map. The loader’s first act, when it runs, is to compare the
kernel’s hash with its compiled-in one, eight bytes at a time; if they differ, it exits with
-EINVALbefore making a singlebpf()call. - Nothing else may touch the data. The map is created exclusive:
BPF_MAP_CREATEtakes a newexcl_prog_hash, the SHA-256 of the one program allowed to use the map, and the verifier refuses any other program that refers to it. Freezing stops user space writing to the block; exclusivity stops another BPF program doing it between the hash and the run.
The chain is: the key signs the loader; the loader carries the hash of the data; the kernel computes the hash of what is actually in the map; and the map can only be read by that loader. Here it is from build to load, with the unsigned path and the token path for comparison:
One program, seven stages, six ways to load it
Pick a kind of load, then step through what is checked between the source file and the attached program.
- libbpf, unsigned: capabilities checked, no signature, verified, attached.
- token: the same, with capabilities checked in the namespace that owns the token; it saw the host's execs.
- signed light skeleton: data in an exclusive frozen map, the kernel hashes it, the loader's 375-byte signature checked before the verifier, the loader compares hashes and loads the program.
- tampered data: signature valid, the loader refuses its data, -22.
- tampered, re-hashed: signature rejected, -129, before the verifier.
- signed with root's own key: valid against root's own keyring; only a policy that names the keyring refuses it.
Green passed, teal is a check of who is asking, copper refused or tampered with, grey not involved. Every outcome is from a run on Linux 6.18; the order of the checks is the order in bpf_prog_load().
Signing it
bpftool’s new -S option signs a light skeleton, with -k for the private key and -i for the
certificate. Here is the build, all of it; x509.genkey is the same recipe the kernel’s own build
uses to make its module-signing key, with a 2048-bit RSA key:
# build.sh — everything in this post; libbpf and bpftool are the 6.18 tree's, in /usr/local
set -e
bpftool btf dump file /sys/kernel/btf/vmlinux format c > vmlinux.h
BPF="clang -g -O2 -target bpf -D__TARGET_ARCH_x86 -I. -I/usr/local/include"
CC="cc -g -O2 -Wall -I. -I/usr/local/include"
LIBBPF="/usr/local/lib64/libbpf.a -lelf -lz"
$BPF -c execcount.bpf.c -o execcount.bpf.o
$BPF -c requiresig.bpf.c -o requiresig.bpf.o
bpftool gen skeleton execcount.bpf.o name execcount > execcount.skel.h
bpftool gen skeleton requiresig.bpf.o name requiresig > requiresig.skel.h
$CC execcount.c $LIBBPF -o execcount # full skeleton: libbpf loads it
$CC requiresig.c $LIBBPF -o requiresig
$CC tryload.c $LIBBPF -o tryload
$CC tokenrun.c -o tokenrun
# a signing key, made the way the kernel makes its module-signing key
cat > x509.genkey <<'EOF'
[ req ]
distinguished_name = dn
prompt = no
x509_extensions = exts
[ dn ]
CN = bpf program signing key
[ exts ]
basicConstraints=critical,CA:FALSE
keyUsage=digitalSignature
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid
EOF
openssl req -new -nodes -utf8 -sha256 -days 365 -batch -x509 -config x509.genkey \
-newkey rsa:2048 -keyout key.pem -outform DER -out cert.der 2>/dev/null
# the light skeleton, unsigned and signed
bpftool gen skeleton -L execcount.bpf.o name execcount > execcount.lskel.h
bpftool gen skeleton -L -S -k key.pem -i cert.der execcount.bpf.o name execcount \
> execcount.signed.lskel.h
$CC -DLIGHT execcount.c $LIBBPF -o execcount-light
$CC -DLIGHT -DSIGNED execcount.c $LIBBPF -o execcount-signed
# the timing harness, once per kind of skeleton
$CC loadbench.c $LIBBPF -o bench-full
$CC -DLIGHT loadbench.c $LIBBPF -o bench-light
$CC -DLIGHT -DSIGNED loadbench.c $LIBBPF -o bench-signed
The signed header is 2,708 bytes longer than the unsigned one (15,279 against 12,571). The extra
bytes are a 375-byte signature, a 32-byte excl_prog_hash (the SHA-256 of the loader), a
keyring_id field in the skeleton’s struct with the lines that pass it on, and, in the loader
itself, 28 more instructions: four comparisons of seven instructions each, one for each eight
bytes of the data block’s hash. The data block is 2,864 bytes in both; the loader is 162
instructions signed and 134 unsigned.
The keyring
The signature is checked against a keyring, and which keyring is the real trust decision.
keyring_id is either one of three system keyrings, selected by small numbers (0 for the keys
built into the kernel, 1 for the secondary trusted keyring, 2 for the platform keyring that holds
the firmware’s UEFI keys), or the serial number of an ordinary keyring a process can see. On this
machine the built-in keys are Canonical’s, compiled in from debian/canonical-certs.pem, and the
secondary keyring only accepts keys signed by a key already trusted, so I cannot put my key in
either. A keyring of my own I can make, and link into my session keyring. (A login shell gets a
session keyring from pam_keyinit; the bare shell in my test virtual machine had none, so I ran
everything in this section under keyctl session, which starts one.)
$ RING=$(keyctl newring bpf_signers @s); echo $RING
665131452
$ keyctl padd asymmetric signer $RING < cert.der
232058954
$ keyctl show @s
Keyring
413553218 --alswrv 0 0 keyring: p15
665131452 --alswrv 0 0 \_ keyring: bpf_signers
232058954 --als--v 0 0 \_ asymmetric: signer
$ openssl x509 -inform DER -in cert.der -noout -subject -ext keyUsage,basicConstraints
subject=CN = bpf program signing key
X509v3 Basic Constraints: critical
CA:FALSE
X509v3 Key Usage:
Digital Signature
Loading it
$ ./execcount-signed 3 $RING
counting exec() for 3 s
true 10
ls 3
$ bpftool prog show name count_exec # while it runs
60: raw_tracepoint name count_exec tag 4263538b7611fe49 gpl
[loaded_at line trimmed]
xlated 232B jited 143B memlock 4096B map_ids 17
btf_id 52
The signed counter loads and counts like the others, and once it is loaded nothing about it says
it was signed: bpftool prog show prints exactly what it would for an unsigned program, and no
__loader.prog is left behind. 6.18 checks a signature at load time and keeps no record that it
did. The interesting part is underneath, so here is the same load under strace, trimmed to the
arguments that matter as before:
$ strace -e trace=bpf ./execcount-signed 0 $RING
bpf(BPF_MAP_CREATE, {map_type=BPF_MAP_TYPE_ARRAY, key_size=4, value_size=2864, max_entries=1,
map_name="__loader.map", ..., map_extra=0, ...}, 92) = 3
bpf(BPF_MAP_UPDATE_ELEM, {map_fd=3, ..., flags=BPF_ANY}, 32) = 0
bpf(BPF_MAP_FREEZE, {map_fd=3}, 4) = 0
bpf(BPF_OBJ_GET_INFO_BY_FD, {info={bpf_fd=3, info_len=104, ...}}, 16) = 0
bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_SYSCALL, insn_cnt=162, license="Dual BSD/GPL",
prog_flags=BPF_F_SLEEPABLE, prog_name="__loader.prog", ..., fd_array=..., ...}, 168) = 4
bpf(BPF_PROG_TEST_RUN, {test={prog_fd=4, ..., ctx_size_in=44, ...}}, 80) = 0
bpf(BPF_RAW_TRACEPOINT_OPEN, {raw_tracepoint={name="sched_process_exec", prog_fd=7}}, 12) = 3
counting exec() for 0 s
bpf(BPF_MAP_GET_NEXT_KEY, {map_fd=6, key=NULL, ...}, 24) = -1 ENOENT (No such file or directory)
strace 6.8 is older than the new attributes and doesn’t print them, but it does notice them: the
... at the very end of the BPF_MAP_CREATE and BPF_PROG_LOAD lines is strace saying “there are
non-zero bytes after the fields I know”. For the unsigned light skeleton, those two lines end at
map_extra=0} and fd_array=...}, with no such tail, and its loader is 134 instructions. The tail
here is the exclusive hash in the first line, and the signature, its size and the keyring in the
second; 168 is the size of union bpf_attr up to keyring_id.
Read it as the three parts above, in order. BPF_MAP_CREATE makes the one-element array
__loader.map, 2,864 bytes, exclusive to the loader’s hash. BPF_MAP_UPDATE_ELEM writes
the data block; BPF_MAP_FREEZE seals it; BPF_OBJ_GET_INFO_BY_FD is the call that makes the
kernel hash it. Then BPF_PROG_LOAD of __loader.prog, type BPF_PROG_TYPE_SYSCALL, with the
signature and the keyring: the kernel checks the signature here, before the verifier, and the
verifier then checks that the loader’s hash matches the map’s excl_prog_hash. BPF_PROG_TEST_RUN
runs the loader once; everything the loader does from there, the hash comparison, creating the
real counts map, loading count_exec, happens inside that one call, as bpf() commands
issued from the kernel, which strace cannot see. The skeleton then attaches the program it gets
back, and closes the loader.
One mistake is worth seeing. If the program forgets to set keyring_id, it is 0, the kernel’s
built-in keys, and the load fails:
$ ./execcount-signed 1 0
load/attach: -126 (Required key not available)
$ ./execcount-signed 1 1
load/attach: -126 (Required key not available)
ENOKEY: the signature names its signer by the certificate’s key identifier, and no key with
that identifier is among Canonical’s built-in keys, or in the secondary keyring, 1, which the
second line tries. Nothing was loaded, and the verifier never saw an instruction: the signature is
checked first. The error is the honest one, which after Part 1’s RLIMIT_MEMLOCK hint is worth
saying.
What it costs
Signing adds work at load time: the freeze, the kernel hashing 2,864 bytes, the PKCS#7 check, and the loader’s comparison. To see how much, this harness loads the counter, without attaching it, a given number of times and prints the mean time per load:
// loadbench.c — time N loads of execcount (no attach), in microseconds each
#include <errno.h> /* skel_internal.h uses errno without including it */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#if defined(SIGNED)
#include "execcount.signed.lskel.h"
#elif defined(LIGHT)
#include "execcount.lskel.h"
#else
#include <bpf/libbpf.h>
#include "execcount.skel.h"
#endif
static double now_us(void)
{
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return t.tv_sec * 1e6 + t.tv_nsec / 1e3;
}
int main(int argc, char **argv)
{
int n = argc > 1 ? atoi(argv[1]) : 100, i;
double t0, sum = 0;
for (i = 0; i < n; i++) {
struct execcount *skel = execcount__open();
if (!skel)
return 1;
#ifdef SIGNED
skel->keyring_id = strtol(argv[2], NULL, 0);
#endif
t0 = now_us();
if (execcount__load(skel))
return fprintf(stderr, "load failed\n"), 1;
sum += now_us() - t0;
execcount__destroy(skel);
}
printf("%.1f\n", sum / n);
return 0;
}
I ran it in a boot of its own, under the test bed’s exclusive lock: eight rounds, each loading the ordinary skeleton, the unsigned light skeleton and the signed one 200 times apiece, one after the other:
$ for r in 1 2 3 4 5 6 7 8; do echo "$r $(./bench-full 200) $(./bench-light 200) $(./bench-signed 200 $RING)"; done
1 64.9 74.0 140.7
2 39.9 69.7 131.9
3 45.5 69.4 142.0
4 37.6 75.9 132.4
5 40.7 71.0 138.4
6 38.8 73.7 132.7
7 38.8 69.1 134.6
8 41.0 70.3 132.7
Microseconds per load. The signed light skeleton took between 132 and 142 µs, against 69 to 76 for the unsigned one: the two ranges are far apart, and the medians, 134 and 71, put the price of the signed path at about 63 µs per load. That buys the freeze, the kernel’s SHA-256 of 2,864 bytes, the check of an RSA-2048 PKCS#7 signature, and 28 more instructions to verify and run; I did not break it down further. The ordinary skeleton was the fastest of the three, at about 40 µs after its first round, because libbpf relocates in user space and, within one process, probes the kernel’s features only once, while every light-skeleton load creates, fills and runs a loader. For a program loaded once when a service starts, none of this matters; for a tool that loads hundreds of programs, 63 µs each is measurable and still small.
Breaking it on purpose
Part 1 broke the verifier’s rule on purpose to see what a refusal looks like. The signed load has
more than one rule, so there are more ways to break it. I took the role of an attacker who can
edit the signed binary, or its header before it is compiled, but does not have the private key.
tamper.py does the editing:
# tamper.py — edit a signed light skeleton the way an attacker would
# usage: tamper.py data|rehash <in.lskel.h> <out.lskel.h>
# data: change bytes in the loader's data blob (rename the program)
# rehash: the same, then patch the blob's SHA-256 inside the loader's code
import hashlib, re, sys
mode, src, dst = sys.argv[1:4]
text = open(src).read()
def blob(name): # the bytes of: static const char <name>[] = "\x..";
m = re.search(r'%s\[\] __attribute__\(\(__aligned__\(8\)\)\) = "\\\n(.*?)";' % name,
text, re.S)
raw = bytes(int(h[1:] or '0', 16) # bpftool writes \xNN, and \0 for zero
for h in re.findall(r'\\(x[0-9a-f]{2}|0)', m.group(1)))
return m, raw
def put(m, raw): # write bytes back in bpftool's format
global text
hexs = ''.join('\\x%02x' % b for b in raw)
body = '\\\n'.join(hexs[i:i + 80] for i in range(0, len(hexs), 80))
text = text[:m.start(1)] + body + text[m.end(1):]
m, data = blob('opts_data')
old_sha = hashlib.sha256(data).digest()
new = data.replace(b'count_exec', b'pwned_exec')
assert new != data
print('data blob: %d bytes, %d changed' % (len(data), sum(a != b for a, b in zip(data, new))))
put(m, new)
if mode == 'rehash':
new_sha = hashlib.sha256(new).digest()
m, insns = blob('opts_insn')
for i in range(4): # each 8-byte word sits in one ld_imm64: lo imm, 4 zero bytes, hi imm
lo, hi = old_sha[8 * i:8 * i + 4], old_sha[8 * i + 4:8 * i + 8]
pat = lo + b'\0\0\0\0' + hi
assert insns.count(pat) == 1
insns = insns.replace(pat, new_sha[8 * i:8 * i + 4] + b'\0\0\0\0' + new_sha[8 * i + 4:8 * i + 8])
print('loader: embedded SHA-256 %s... -> %s...' % (old_sha.hex()[:16], new_sha.hex()[:16]))
put(m, insns)
open(dst, 'w').write(text)
First, change the program and nothing else. The attacker renames count_exec inside the data
block, fifteen bytes in all, because the name appears there three times. The loader’s
instructions are untouched, so the signature is still valid:
$ python3 tamper.py data execcount.signed.lskel.h td/execcount.signed.lskel.h
data blob: 2864 bytes, 15 changed
$ ./td/execcount-signed 1 $RING
load/attach: -22 (Invalid argument)
$ strace -e trace=bpf ./td/execcount-signed 1 $RING
bpf(BPF_MAP_CREATE, {..., value_size=2864, max_entries=1, map_name="__loader.map", ...}, 92) = 3
bpf(BPF_MAP_UPDATE_ELEM, {map_fd=3, ..., flags=BPF_ANY}, 32) = 0
bpf(BPF_MAP_FREEZE, {map_fd=3}, 4) = 0
bpf(BPF_OBJ_GET_INFO_BY_FD, {info={bpf_fd=3, info_len=104, ...}}, 16) = 0
bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_SYSCALL, insn_cnt=162, ...,
prog_name="__loader.prog", ...}, 168) = 4
bpf(BPF_PROG_TEST_RUN, {test={prog_fd=4, ..., ctx_size_in=44, ...}}, 80) = 0
load/attach: -22 (Invalid argument)
The signature passed: BPF_PROG_LOAD returned descriptor 4, because the loader’s instructions
are exactly the ones I signed. The loader then ran, and BPF_PROG_TEST_RUN returned 0, because the
system call itself succeeded. The failure is the loader’s own return value, which the skeleton
reads back as “error returned by loader prog”: its first comparison found that the hash the kernel
had computed of the frozen map was not the one compiled into it, and it jumped to its clean-up code
without creating a map or loading a program. pwned_exec never existed.
Second, change the program and fix the hash. The attacker knows the loader compares a hash, so they compute the SHA-256 of their modified block and write it over the four constants in the loader:
$ python3 tamper.py rehash execcount.signed.lskel.h tr/execcount.signed.lskel.h
data blob: 2864 bytes, 15 changed
loader: embedded SHA-256 3270917a60bfdab2... -> 062d2130a02f26c0...
$ ./tr/execcount-signed 1 $RING
load/attach: -129 (Key was rejected by service)
$ strace -e trace=bpf ./tr/execcount-signed 1 $RING
...
bpf(BPF_OBJ_GET_INFO_BY_FD, {info={bpf_fd=3, info_len=104, ...}}, 16) = 0
bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_SYSCALL, insn_cnt=162, ...,
prog_name="__loader.prog", ...}, 168) = -1 EKEYREJECTED (Key was rejected by service)
Now the loader would have accepted the modified block, but the loader is no longer what was
signed, and the kernel says so before anything else happens: EKEYREJECTED from BPF_PROG_LOAD,
the verifier never called, nothing run. The two checks cover each other. Change the data and the
loader catches it; change the loader to stop it catching it, and the signature does.
Third, sign it yourself. The attacker cannot forge my signature, but they are root on the machine, so they can make a key of their own, sign the skeleton with it, and make a keyring to hold their certificate:
$ cd atk && openssl req ... -newkey rsa:2048 -keyout key.pem -outform DER -out cert.der
$ bpftool gen skeleton -L -S -k key.pem -i cert.der ../execcount.bpf.o name execcount > execcount.signed.lskel.h
$ cc ... -DLIGHT -DSIGNED execcount.c ... -o execcount-signed && cd ..
$ ./atk/execcount-signed 1 $RING
load/attach: -126 (Required key not available)
$ ARING=$(keyctl newring attacker @s); echo $ARING
59974337
$ keyctl padd asymmetric mine $ARING < atk/cert.der
924592027
$ ./atk/execcount-signed 3 $ARING
counting exec() for 3 s
true 10
ls 3
Against my keyring, the attacker’s signature names a signer that isn’t there: ENOKEY. Against
their own keyring, it is a perfectly valid signature, and the kernel loads the program and it
counts. The kernel did everything it promised. It checked that the loader was signed by a key in
the keyring the caller named, and it was.
That third result is the important one. A signature proves that someone holding a key in the named keyring signed the loader. It does not prove that the keyring is one you trust, and in 6.18 the kernel does not refuse unsigned programs either: signing is something a loader may do, and the unsigned light skeleton and the ordinary libbpf skeleton above loaded exactly as before. The kernel provides the check. Requiring it, and deciding which keyring counts, is policy, and policy is the job of a security module.
A policy that requires signatures
A BPF LSM program on security_bpf_prog_load sees the program, the union bpf_attr that came
with it, the token if there is one, and, since 6.15, a kernel flag that says whether the command
came from user space or from inside the kernel. A loader’s own bpf() calls arrive with the flag
set. That is enough for a small policy: a load from user space must carry a signature, the
signature must have been checked against one particular keyring, and loads issued by a loader in
the kernel are allowed, because the only loaders that can run are signed ones. It is the policy
the 6.18 design expects someone to write:
// requiresig.bpf.c — a BPF LSM policy: programs from user space must be signed
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#define EPERM 1
const volatile __s32 trusted_keyring; /* set by the loader before it loads us */
__u64 from_kernel, signed_ok, unsigned_denied, wrong_keyring_denied;
SEC("lsm/bpf_prog_load")
int BPF_PROG(require_signed, struct bpf_prog *prog, union bpf_attr *attr,
struct bpf_token *token, bool kernel, int ret)
{
if (ret) /* an earlier LSM already said no */
return ret;
if (kernel) { /* issued by a loader program, in the kernel */
__sync_fetch_and_add(&from_kernel, 1);
return 0;
}
if (!attr->signature) {
__sync_fetch_and_add(&unsigned_denied, 1);
return -EPERM;
}
if (attr->keyring_id != trusted_keyring) {
__sync_fetch_and_add(&wrong_keyring_denied, 1);
return -EPERM;
}
__sync_fetch_and_add(&signed_ok, 1); /* and the kernel checked it already */
return 0;
}
char LICENSE[] SEC("license") = "GPL";
The kernel has already verified the signature by the time this hook runs, and failed the load if
it was bad, so attr->signature being non-zero means “a valid signature, checked against
attr->keyring_id”. And a small loader that installs it for a while and reports what it decided:
// requiresig.c — install the policy for N seconds, then report what it decided
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <bpf/libbpf.h>
#include "requiresig.skel.h"
int main(int argc, char **argv)
{
struct requiresig *skel;
if (argc < 3)
return fprintf(stderr, "usage: %s keyring-id seconds\n", argv[0]), 2;
skel = requiresig__open();
if (!skel)
return 1;
skel->rodata->trusted_keyring = strtol(argv[1], NULL, 0);
if (requiresig__load(skel) || requiresig__attach(skel)) {
fprintf(stderr, "could not install the policy\n");
requiresig__destroy(skel);
return 1;
}
printf("policy on: user-space loads need a signature checked against keyring %d\n",
skel->rodata->trusted_keyring);
fflush(stdout);
sleep(atoi(argv[2]));
printf("policy off: %llu signed, %llu from the kernel, %llu unsigned denied,"
" %llu wrong keyring denied\n",
(unsigned long long)skel->bss->signed_ok,
(unsigned long long)skel->bss->from_kernel,
(unsigned long long)skel->bss->unsigned_denied,
(unsigned long long)skel->bss->wrong_keyring_denied);
requiresig__destroy(skel);
return 0;
}
The BPF LSM is compiled into Ubuntu’s mainline 6.18 build but not switched on: the default
CONFIG_LSM list is landlock,lockdown,yama,integrity,apparmor, and a BPF LSM program attaches
but is never called. So for this run I booted with bpf added to the list on the kernel command
line:
$ ./requiresig $RING 25 &
policy on: user-space loads need a signature checked against keyring 612285748
$ ./execcount 1
libbpf: Error in bpf_object__probe_loading(): -EPERM. Couldn't load trivial BPF program. Make sure your kernel supports BPF (CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is set to big enough value.
libbpf: failed to load BPF skeleton 'execcount': -EPERM
load/attach: -1 (Operation not permitted)
$ ./execcount-light 1
load/attach: -1 (Operation not permitted)
$ ./execcount-signed 1 $RING
counting exec() for 1 s
$ ./atk/execcount-signed 1 $ARING
load/attach: -1 (Operation not permitted)
$ ./td/execcount-signed 1 $RING
load/attach: -22 (Invalid argument)
$ ./tr/execcount-signed 1 $RING
load/attach: -129 (Key was rejected by service)
$ timeout 5 bpftrace -e 'tracepoint:syscalls:sys_enter_execve { @[comm] = count(); }'
Attaching 1 probe...
ERROR: Error loading program: tracepoint:syscalls:sys_enter_execve (try -v)
$ strace -e trace=bpf ./execcount 1 2>&1 | grep -E 'PROG_LOAD|BTF_LOAD|MAP_CREATE'
bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_SOCKET_FILTER, insn_cnt=2, ...}, 148) = -1 EPERM (Operation not permitted)
bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_SOCKET_FILTER, insn_cnt=2, ...}, 168) = -1 EPERM (Operation not permitted)
bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_TRACEPOINT, insn_cnt=2, ...}, 168) = -1 EPERM (Operation not permitted)
policy off: 2 signed, 1 from the kernel, 15 unsigned denied, 1 wrong keyring denied
(This was a second boot, so the keyrings have new serial numbers; they were set up as before.)
Everything unsigned was refused: the ordinary skeleton never got past libbpf’s probes, three
two-instruction programs it loads to learn what the kernel supports, and, as in Part 1, libbpf
blamed RLIMIT_MEMLOCK for the EPERM. The unsigned light skeleton’s loader was refused, and so
was bpftrace. The signed counter loaded. The attacker’s skeleton, validly signed against their own
keyring, was refused because of which keyring it named, which is the line in the policy that
matters most. The re-hashed one never reached the policy at all, because the kernel rejected its
signature first.
The counters at the end are the interesting part. Fifteen unsigned loads were refused, almost all
of them feature probes. One wrong keyring. One load came from inside the kernel: count_exec,
issued by the good loader. And two signed loads were allowed: the good one, and the one with the
tampered data block, whose loader then refused to load anything. The policy said yes to a load
that went on to fail. Hold on to that; it is the next section.
Hornet, and the argument about when
The design above was not the only one. On 21 March Blaise Boscaccy of Microsoft posted an RFC
for Hornet, a security module that verifies a PKCS#7 signature over a light skeleton’s loader
and its maps, and lets the real program through once the signed loader loads it from inside the
kernel. At LSFMM+BPF in April, LWN reported, the room was unconvinced: Starovoitov asked why it was
a new security module rather than part of an existing one, Daniel Borkmann asked whether the check
could be written as a BPF LSM, and Starovoitov added that “trying to prevent root from breaking
things is futile”. When the third version went out on 2 May, KP Singh replied with a Nacked-by
and the reason: “you cannot implement BPF program signing for BPF users without aligning with the
BPF maintainers and the community”. Singh posted his own series on 6 June, a loader-based design
and only that (“trusted loaders are an inevitability and a requirement for signing support”, as
LWN quoted him), and a second version on 21 July; it was applied in September and is what 6.18
shipped. The one piece of Boscaccy’s work that did land is the kernel flag the policy above
relies on, which went into 6.15 “to facilitate bpf program signing”.
The disagreement did not end there, and the tamper experiment shows exactly what it is about.
Look again at the first attack, the modified data block. The kernel verified the signature, then
called security_bpf_prog_load, and only after that did the loader run and find that the data
did not match. The policy’s counters recorded that order: two signed loads allowed, one of which
then failed inside the loader. A security module that keeps an audit trail, or that makes a
decision once and caches it, was told “signed” for a load that then failed.
After the merge, Boscaccy posted a follow-up, on top of Singh’s series, that would have moved the security-module hook to after the whole load, and checked the maps’ hash alongside the loader’s signature, so that a security module sees the result of every integrity check before it decides. LWN’s report of 27 October records Starovoitov declining it. His argument is that the kernel’s part ends once the loader is verified, as a self-extracting archive is trusted once its stub is, and that “both signed kernel modules and signed BPF programs need to have trusted build systems, or the signing is pointless”. Paul Moore, the LSM maintainer, wants verification complete before the hook runs, since otherwise the process can fail after the security module has recorded a success. James Bottomley adds that the comparison with modules fails because the module loader is part of the kernel, while a BPF loader program is generated by libbpf, which lives in the kernel’s source tree but is not the kernel. As of this week, 6.18 ships Singh’s design, Hornet is not in mainline, and the two sides agree on very little except the facts in the strace above.
My own reading, as someone who just ran it: both sides are describing the same chain correctly. The loader will refuse a block that doesn’t match, so nothing unverified ever runs, which is Starovoitov’s point. And the one hook a security module gets is placed before that refusal, so a policy can only reason about the loader, not about what the loader is about to load, which is Moore’s. The policy above works because it is written for that model: it trusts the loader completely, and makes its one decision about the signature and the keyring.
The kernel trusting BPF with more
The same year that made BPF checkable also gave it more to be trusted with, and the two trends are not unrelated: the more of the kernel’s own job a BPF program does, the more the question of who wrote it matters.
Resilient spinlocks (6.15). BPF programs could take a lock since 5.1, bpf_spin_lock, with the
verifier enforcing that a program holds at most one lock, never calls a helper while holding it,
and always releases it. Those restrictions are what kept a BPF program from deadlocking the
kernel, and they ruled out most interesting data structures. 6.15 added bpf_res_spin_lock,
built on a new resilient queued spinlock in the kernel: a lock that detects deadlocks (an
AA cycle on one CPU, ABBA across CPUs) and times out, returning an error instead of spinning
forever. A program may hold several, nest them, and must check the return value. The verifier no
longer has to prove the program can’t deadlock, because the lock itself won’t let it.
BPF qdisc (6.16). Since 5.6, struct_ops has let BPF implement a kernel interface, starting
with TCP congestion control, and
Part 14 ran a whole CPU
scheduler that way. 6.16 added Qdisc_ops: a queueing discipline, the packet scheduler behind
tc, written in BPF. The kernel’s own selftest, bpf_qdisc_fifo.c, is a FIFO in about a
hundred lines, keeping packets as kernel pointers in a BPF linked list. Built from the 6.18 tree,
registered with bpftool and put on the loopback interface:
$ bpftool struct_ops register bpf_qdisc_fifo.bpf.o
Registered Qdisc_ops fifo id 35
$ tc qdisc add dev lo root handle 1: bpf_fifo
$ ping -q -c 20 -i 0.01 127.0.0.1 | tail -2
20 packets transmitted, 20 received, 0% packet loss, time 209ms
rtt min/avg/max/mdev = 0.023/0.038/0.051/0.006 ms
$ tc -s qdisc show dev lo
qdisc bpf_fifo 1: root refcnt 2
Sent 3920 bytes 40 pkt (dropped 0, overlimits 0 requeues 0)
backlog 0b 0p requeues 0
$ tc qdisc del dev lo root
$ bpftool struct_ops unregister name fifo
Unregistered Qdisc_ops fifo id 35
Forty packets, the twenty echo requests and their twenty replies, each one handed to a BPF
function to enqueue and taken back from another to send, with the packet itself held in a BPF
list in between. tc from Ubuntu 24.04 knows nothing about bpf_fifo: it passes the name to the
kernel, and the kernel finds a queueing discipline of that name because bpftool registered one.
Nothing in this demonstration was signed. A qdisc sees every packet the interface sends.
And the rest of the year. 6.17 gave programs standard output and error streams, so a program
can report a fault in words rather than a counter; 6.18 added bpf_task_work, which lets a program
schedule work to run in the context of a task, and bpf_xdp_pull_data for XDP programs that need
more of a packet than the first buffer. Each is a little more of the kernel’s work handed to code
that arrives through bpf().
A standard for the instruction set
One thing was settled the year before, outside the kernel. In October 2024 the IETF published
RFC 9669, “BPF Instruction Set Architecture (ISA)”, a Proposed Standard edited by Dave Thaler,
from the BPF working group chartered in 2023. It standardises what
Part 2 decoded by
hand: the 64-bit instruction encoding, the 16-byte wide form that carries a 64-bit immediate, the
instruction classes, every ALU,
jump, load, store and atomic opcode, and register numbers 0 to 10. It sorts the instructions into
conformance groups (base32, which every implementation must support, then base64, atomic32,
atomic64, divmul32, divmul64, and packet, the legacy packet loads, now deprecated) and
creates IANA registries for both, so a new instruction is registered rather than merely merged.
What it leaves out is most of what this series has been about. Helper functions are “outside the
scope of this document”; maps are memory “defined in a separate document”; BTF is out of scope;
of the verifier it says only that one is expected to ensure programs terminate, and that “the
details are out of scope”. Even the calling convention, r1 to r5 for arguments and r0 for the
result, isn’t in the RFC: it lives in an informational ABI document in the Linux tree,
Documentation/bpf/standardization/abi.rst. So RFC 9669 makes a BPF program portable as a
sequence of instructions, which is why eBPF for Windows and the Linux kernel can be argued about
in the same terms, and says nothing about whether a given program should be allowed to run.
The working group’s charter lists more: cross-platform maps, helpers, program types, BTF, ELF conventions, verifier expectations. As of this week none of those has become a working-group draft. The one ELF document, an individual draft from 2023, has expired, and the group has not met since July 2024.
Windows: proving verification, not origin
Windows reached the signing question from the other end. As
Part 12 showed, eBPF for Windows on a machine with Memory
Integrity (HVCI) cannot JIT at all: the only path is native mode, where bpf2c runs the PREVAIL
verifier at build time and emits C that is compiled into a driver, and drivers must be signed. So
on a Memory Integrity machine a BPF program has always arrived as a signed binary, and the trust
question was the opposite of Linux’s: the signature was easy, but what did it prove?
v1.0.0-rc1, released on 23 October, answers that with Proof of Verification. The eBPF service
loads a native program only if its driver is signed with a Microsoft certificate carrying an
“eBPF verification” extended key usage. The signature then means something specific: this driver
came out of a build pipeline that ran the verifier on it. The service checks the file’s signature
with WinVerifyTrust, hashes it, and authorises that hash with the kernel, which checks it when
the driver registers with the eBPF runtime.
Put the two side by side and they sign different claims. Linux 6.18’s signature says whoever holds this key approved this loader, and checks verification, as always, at load time on the target. Windows’s says Microsoft’s pipeline verified this program, and does not verify on the target at all. Neither is in production use yet in the form shown here: on Linux nothing requires a signature unless a security module says so, and every eBPF for Windows release so far, rc2 of 24 November included, has shipped test-signed drivers, which load only with test signing switched on.
What’s around in December 2025
The kernel. 6.18, released on 30 November, is this year’s long-term kernel, with signed
programs, bpf_task_work, bpf_xdp_pull_data and arena faults reported to the new streams. The
6.19 merge window closed this morning with -rc1.
The tools. The signing support is in the 6.18 source tree’s copies of libbpf and bpftool, which call themselves libbpf 1.7 and bpftool 7.7.0, and in no release: the newest libbpf release is 1.6.2, from August, and the newest bpftool release is 7.6.0, from July. Anyone signing BPF programs this month is building the tools from the kernel tree, as I did.
Elsewhere. The IETF working group is quiet after RFC 9669; eBPF for Windows is at v1.0.0-rc2 (24 November), still test-signed; and the eBPF Foundation, now four years old, is still where the companies that build on BPF fund the work that no one of them owns.
What we covered
- The verifier proves a program is safe. Who may load one, and whether it is the program anyone meant, are separate questions with separate answers, and they arrived over eleven years.
- Who: root only in 3.18; unprivileged socket filters from 4.4;
CAP_BPF,CAP_PERFMONandCAP_NET_ADMINfrom 5.8; unprivileged loading off by default from 5.16. On 6.18, uid 1000 withCAP_BPFandCAP_PERFMONran the counter; with no capabilities it could not even create a map. - Delegation: a BPF token (6.9) lets the host hand a user namespace chosen commands and types through a BPF filesystem mount. An unmodified libbpf tool in a namespace counted the host’s thirteen execs: delegating a tracing type delegates a tracing program’s view.
- Approval: a BPF program arrives as bytes in a system call, not a file, and libbpf rewrites it per machine, so neither module signing nor IMA covers it, and signing the object file proves nothing about what is loaded.
- Signing (6.18): the signature covers the light skeleton’s loader, which is the same on every machine; the loader carries the SHA-256 of its data; the kernel hashes the frozen data map itself; and the map is exclusive to the loader. A modified data block got past the signature and was refused by the loader (-22); a modified loader was refused by the signature (-129); a key root made itself, in a keyring root made itself, passed.
- Policy: the kernel checks a signature if one is given and requires nothing. A BPF LSM policy
of thirty lines, on a kernel booted with
lsm=...,bpf, made signatures mandatory and pinned the keyring. The hook runs before the loader checks its data, which is the whole of the Hornet dispute. - The kernel trusts BPF with more: resilient spinlocks (6.15), qdiscs (6.16), streams (6.17), task work (6.18).
- RFC 9669 standardises the instruction set and nothing above it; eBPF for Windows signs a claim that verification happened, where Linux signs a claim of approval.
The next part goes back to Windows, to see where the port has got to.
A note on the evidence
What I ran, and where. Every listing in this post is pasted from a real run. The machine was a
KVM virtual machine with 4 virtual CPUs and 4 GiB of memory, running nested inside another virtual
machine, booting Ubuntu’s mainline build of Linux 6.18 (6.18.0-061800-generic, built on
30 November) on a minimal Ubuntu 24.04 userland from the release archive only: clang 18.1.3,
OpenSSL 3.0.13, keyutils 1.6.3, setpriv from util-linux 2.39.3, strace 6.8, iproute2 6.1.0 and
bpftrace 0.20.2. libbpf and bpftool were built from the linux-6.18 release tarball from
kernel.org (checked against its published SHA-256) and installed under /usr/local, together with
that tree’s copies of the UAPI headers bpf.h, bpf_common.h and btf.h, because 24.04’s headers
are 6.8’s and the light skeleton’s skel_internal.h needs the new attributes. Every C file, the
build script and tamper.py were extracted from this page and built and run as shown. There were
three boots of the same kernel: one as it comes, for everything up to the policy; one with bpf
added to lsm= on the command line, for the policy; and one for the timings, run under the test
bed’s exclusive lock, which keeps its other virtual machines off while it runs. All the signing commands ran inside a keyctl session, for
the reason given above. The kernel configuration I quote (CONFIG_BPF_UNPRIV_DEFAULT_OFF,
CONFIG_LSM, the trusted keys) is from the build’s own config-6.18.0-061800-generic.
What I trimmed. strace lines are cut to their meaningful arguments, marked ...; the exception
is the final ... inside the BPF_MAP_CREATE and BPF_PROG_LOAD attributes of the signed load,
which is strace’s own and is explained where it appears. Pointer values are cut. The loaded_at
line of bpftool prog show is cut, as marked, and trailing spaces in bpftool token list are
removed. In the attacker’s listing, the openssl, bpftool and cc commands ran in my script
without echoing, and are shown shortened. Keyring serial numbers are as printed; the policy ran in
a second boot, so its serials differ from the earlier ones. The timing figures are means of 200
loads per round, as printed.
What I cited rather than ran. The history: each kernel version in the timeline is the first
release whose tag contains the commit that introduced the change, checked against Linus Torvalds’s
tree, and the 3.18 behaviour is from that release’s kernel/bpf/syscall.c. The design of signed
programs is from the 6.18 source itself: bpf_prog_verify_signature() and bpf_prog_load() in
kernel/bpf/syscall.c, the exclusive-map check in the verifier, array_map_get_hash(), and the
loader code bpftool generates (gen_loader.c, skel_internal.h, sign.c). The Hornet story and
every quotation in it are from the patch threads on the kernel mailing list and from LWN’s reports
of 22 April, 12 August and 27 October. RFC 9669 is quoted from its text. Resilient spinlocks I
describe from their commits and did not run. Proof of Verification is from eBPF for Windows’s
v1.0.0-rc1 release notes and documentation; I did not run it, and none of this part ran on Windows.
What I’d still change. The keyring is the weak point of the demonstration, and deliberately
so: it is an ordinary keyring that root made and root can write to, which is exactly why the
attacker’s key worked. A real deployment would put its key where root cannot add one at run time,
in the secondary keyring vouched for by a built-in key, or in the platform keyring through the
firmware, and I could do neither on a kernel whose built-in keys are Canonical’s. The policy is a
sketch: it trusts every load issued from inside the kernel, which is right for the loader design
and wrong if anything else ever issues bpf() commands from the kernel, and it does nothing to
protect itself. The timings come from one virtual machine, nested, and
are means over 200 loads; the round-to-round spread, not the third digit, is the result.
Who Is Allowed to Load a Program