eBPF from the ground up: building a tool that watches the kernel
A hands-on tutorial. We build a small tool that reports every program started on a Linux machine, one step at a time, and run into the verifier, maps, ring buffers and CO-RE along the way.
A disk on a server keeps filling up. Something starts a short-lived process every so often that writes a file and exits. You run ps and top and see nothing, because by the time you look, the process is already gone.
We’re going to build a tool that would catch it. It starts as a one-line experiment and ends as a small C and Go program that reports every program started on the machine, along with its parent, as it happens. Each phase adds one eBPF idea, with a drawing for each.
You need a Linux machine with a kernel from the last few years (5.8 or newer for everything here), root access, clang, bpftool, bpftrace and Go.
Phase 0: why the usual tools miss it
The usual tools work by asking the kernel. ps and top read /proc, which is a snapshot of the processes alive at the moment you read it. Read it every second and you get one snapshot per second.
A process that starts and exits between two snapshots never existed, as far as those tools know.
The fix is to stop asking and get the kernel to tell us every time a process starts. That’s what eBPF is for. We hand the kernel a small program and say “run this every time a process starts”, so there’s no polling and nothing slips through between reads.
Phase 1: ask the question in one line
Before writing real code, it’s worth checking that the kernel can answer the question at all. bpftrace is the fastest way: it takes a small script, turns it into an eBPF program, loads it, and prints what comes back.
sudo bpftrace -e 'tracepoint:sched:sched_process_exec { printf("%-7d %-7d %s\n", pid, curtask->real_parent->tgid, comm);}'Leave it running, and in another terminal run ls, curl, anything. Each one prints a line as soon as it starts, even processes that only live for a millisecond. Our disk-filling process would have shown up here.
So that one line already does everything our tool will do. The rest of the post builds the same thing by hand, so that each piece makes sense and we can extend it later: filter it, send the events somewhere, run it on every node of a cluster.
Phase 2: choose where to listen
An eBPF program does not run on its own. It is attached to a hook: a point in the kernel where something happens. The hook you pick decides what you can see.
| Hook | Fires when | Typical use |
|---|---|---|
| Tracepoint | A stable, named kernel event fires (sched_process_exec, sys_enter_openat) |
Tracing with an interface that does not change between kernel versions |
| kprobe / kretprobe | Any kernel function is entered or returns | Deep tracing where no tracepoint exists, at the cost of stability |
| fentry / fexit | Same as kprobes, through BPF trampolines | Lower overhead, typed arguments via BTF (5.5+) |
| LSM | A security check runs (file_open, bprm_check_security) |
Allowing or denying operations, not only observing them |
| XDP | A packet arrives at the network driver | Filtering and load balancing at line rate |
| TC | A packet passes traffic control, in or out | Container networking, policy enforcement |
| uprobe | A function in a user-space program is called | Tracing TLS libraries, language runtimes |
Our question is “which program just started?”, and the kernel has a tracepoint for exactly that: sched:sched_process_exec, fired after a successful execve, when the new program has replaced the old one. Tracepoints are a stable interface, so the tool keeps working across kernel upgrades. Easy choice.
To see what else you could listen to:
sudo bpftrace -l 'tracepoint:sched:*'Phase 3: write the kernel half
Our tool has two halves. The kernel half is a small C program that runs inside the kernel every time the hook fires. The user-space half loads it and prints what it reports. We start with the kernel half.
#include "vmlinux.h"#include <bpf/bpf_helpers.h>#include <bpf/bpf_core_read.h>
struct event { u32 pid; u32 ppid; char comm[16];};
struct { __uint(type, BPF_MAP_TYPE_RINGBUF); __uint(max_entries, 256 * 1024);} events SEC(".maps");
SEC("tp/sched/sched_process_exec")int handle_exec(struct trace_event_raw_sched_process_exec *ctx){ struct task_struct *task = (struct task_struct *)bpf_get_current_task(); struct event *e;
e = bpf_ringbuf_reserve(&events, sizeof(*e), 0); if (!e) return 0;
e->pid = bpf_get_current_pid_tgid() >> 32; e->ppid = BPF_CORE_READ(task, real_parent, tgid); bpf_get_current_comm(&e->comm, sizeof(e->comm));
bpf_ringbuf_submit(e, 0); return 0;}
char LICENSE[] SEC("license") = "GPL";Here’s what happens for one event, top to bottom:
SEC("tp/sched/sched_process_exec")tells the loader which hook this function belongs to.- When a program starts, the kernel calls
handle_exec. - It reserves room for one
eventin a ring buffer (more on that in phase 5). - It fills in the process id, the parent’s id and the program name.
- It submits the event, and returns.
Two lines need more explanation, because most of what makes eBPF portable is in them.
vmlinux.h is every type of your running kernel, dumped into one header. You do not install kernel headers; you ask the kernel to describe itself:
bpftool btf dump file /sys/kernel/btf/vmlinux format c > vmlinux.hBPF_CORE_READ(task, real_parent, tgid) reads task->real_parent->tgid. But the layout of task_struct changes between kernel versions: the field real_parent is not at the same offset on every machine. If the offset were baked into the program when you compiled it, the program would read garbage on another kernel.
CO-RE (Compile Once, Run Everywhere) fixes that. The compiler records which field you meant, not just where it was on your machine. When the program is loaded, the loader reads the running kernel’s type information (BTF) and patches the offset to the right value for that kernel. One compiled file works across kernels.
The GPL license line at the end matters too. Many kernel helpers are only available to GPL-compatible programs, and the kernel checks.
Compile it:
clang -O2 -g -target bpf -c exec.bpf.c -o exec.bpf.oPhase 4: meet the verifier
The kernel checks our program before running a single instruction of it. That check is what makes eBPF safe. While it runs, the program is part of the kernel, so there’s no process to kill if it misbehaves, and a bug in it can’t be allowed to crash the machine.
The verifier walks every possible path through the program, instruction by instruction, tracking what every register could hold: a number, a pointer into the stack, a pointer into a map, a pointer that might be null. It rejects the program if, on any path:
- memory is read or written out of bounds;
- a pointer that could be null is used before it is checked;
- the program might not finish (loops need a bound the verifier can see);
- the paths are too many to explore (the limit is one million instructions for privileged programs).
Almost everyone hits this one on their first day. Remove the null check:
e = bpf_ringbuf_reserve(&events, sizeof(*e), 0);e->pid = bpf_get_current_pid_tgid() >> 32; // no null checkbpf_ringbuf_reserve returns null when the buffer is full. On that path, the next line writes through a null pointer. The verifier finds that path and refuses to load the program, with a message along the lines of invalid mem access 'ringbuf_mem_or_null'. Put the if (!e) return 0; back and it loads.
After a few rounds with the verifier you start writing differently: you know the type of every pointer, you bound every length, and you handle every failure path before it asks. Think of it as a code reviewer you can’t merge around.
Phase 5: get the data out
The program runs in the kernel. It cannot print to your terminal or write to a file. Data leaves through maps: data structures that live in the kernel and can be read and written by both the eBPF program and user space.
There are many kinds:
- hash and array maps keep state between events: counters per process, a list of things to watch, a setting chosen from user space;
- per-CPU variants give each CPU its own copy, so busy programs never wait on a lock;
- LRU hash maps forget their oldest entries, for keys that never stop growing, like network connections;
- ring buffers (
BPF_MAP_TYPE_RINGBUF, kernel 5.8+) stream events to user space, in order, in one buffer shared by all CPUs.
For “tell me every time something happens”, the ring buffer is what you want. Our program reserves space, fills it, submits it; user space reads the events in the order they were submitted. If user space falls behind and the buffer fills up, bpf_ringbuf_reserve returns null, our program skips that event, and nothing crashes. That’s the same path the verifier made us handle in phase 4.
Phase 6: write the user-space half
The kernel half is compiled. Now we need a program that loads it into the kernel, attaches it to the hook, and reads the ring buffer. I will use Go and the cilium/ebpf library, which has no C dependencies.
bpf2go compiles the C file and generates Go code that embeds the compiled program and gives you typed handles to it:
//go:generate go run github.com/cilium/ebpf/cmd/bpf2go exec exec.bpf.cRunning go generate produces execObjects, with one field per program (HandleExec) and per map (Events), and a loadExecObjects function. The rest is short:
package main
import ( "bytes" "encoding/binary" "fmt" "log"
"github.com/cilium/ebpf/link" "github.com/cilium/ebpf/ringbuf" "github.com/cilium/ebpf/rlimit")
// Must match struct event in exec.bpf.c, field for field.type event struct { Pid uint32 Ppid uint32 Comm [16]byte}
func main() { // Kernels before 5.11 count eBPF memory against the memlock limit. if err := rlimit.RemoveMemlock(); err != nil { log.Fatal(err) }
// Load the program and the map into the kernel. The verifier runs here. var objs execObjects if err := loadExecObjects(&objs, nil); err != nil { log.Fatalf("loading: %v", err) } defer objs.Close()
// Attach the program to the hook. From now on, it runs on every exec. tp, err := link.Tracepoint("sched", "sched_process_exec", objs.HandleExec, nil) if err != nil { log.Fatalf("attaching: %v", err) } defer tp.Close()
rd, err := ringbuf.NewReader(objs.Events) if err != nil { log.Fatalf("ring buffer: %v", err) } defer rd.Close()
fmt.Printf("%-7s %-7s %s\n", "PID", "PPID", "COMM") for { rec, err := rd.Read() if err != nil { log.Fatalf("reading: %v", err) } var e event if err := binary.Read(bytes.NewReader(rec.RawSample), binary.LittleEndian, &e); err != nil { continue } fmt.Printf("%-7d %-7d %s\n", e.Pid, e.Ppid, bytes.TrimRight(e.Comm[:], "\x00")) }}Build and run it:
go generate && go build -o execwatch && sudo ./execwatchOpen another terminal and start anything. Every program shows up with its parent as soon as it starts. That’s the tool we needed for the full disk.
(binary.LittleEndian is right for x86-64 and arm64, which is almost every machine you will run this on.)
While it runs, bpftool shows you what is actually loaded in the kernel:
sudo bpftool prog list # our program, its id and attach typesudo bpftool map list # our ring buffersudo bpftool prog dump xlated id 42 # the instructions the verifier acceptedPhase 7: filter in the kernel, not after
On a busy machine the tool prints a lot. The obvious fix is to filter in Go: read every event and drop the ones we don’t care about. That works, but every dropped event was still copied out of the kernel and woke up the reader, which costs CPU on both sides.
It’s cheaper to filter in the kernel, before the event is even created. Say we only care about programs started by one user. Add a setting to the kernel half:
// Set from user space before the program is loaded. (u32)-1 means "everyone".const volatile u32 target_uid = (u32)-1;and check it before reserving anything:
u32 uid = (u32)bpf_get_current_uid_gid();if (target_uid != (u32)-1 && uid != target_uid) return 0;const volatile makes this a read-only global that user space can set before loading. The verifier then knows its value, and can even remove the dead branch entirely. In Go, load the spec, set the value, then load the objects:
spec, err := loadExec()if err != nil { log.Fatal(err)}if err := spec.Variables["target_uid"].Set(uint32(1000)); err != nil { log.Fatal(err)}var objs execObjectsif err := spec.LoadAndAssign(&objs, nil); err != nil { log.Fatal(err)}(Older versions of cilium/ebpf used spec.RewriteConstants for the same thing.)
This is the habit I’d pass on first: make the decision in the kernel, and only send out the result. If every event goes to user space to be filtered there, you’ve brought back the overhead eBPF was supposed to save you.
Phase 8: from one machine to a cluster
Our tool watches one machine. On Kubernetes, the interesting question is the same, “what just ran?”, but for every node and with more context: which pod, which container, which image.
That changes the problem in two ways. First, every node runs its own kernel, so the tool has to run on every node: in Kubernetes terms, a DaemonSet. Second, a container is not something the kernel knows by name. It sees processes, namespaces and cgroups; mapping them back to pods means asking the Kubernetes API, and that’s a whole design problem of its own.
That is what Tetragon does: eBPF programs on kprobes, tracepoints and LSM hooks, Kubernetes-aware filtering inside the kernel, and the option to enforce, killing a process at the moment it breaks a policy instead of raising an alert afterwards.
It’s also where my own work picks up. Gait takes that stream of kernel events from every node and turns it into a graph, so you can ask questions about relationships over time: has this pod ever talked to that service, which process tree led to this file being opened. The Building Gait series starts about where this post ends.
What we built, and where to go next
We started with a process too fast for ps and ended with a tool that sees every exec, as long as the ring buffer keeps up:
- a tracepoint, so the kernel tells us instead of us asking;
- a kernel half that passed the verifier, and uses CO-RE to run on other kernels;
- a ring buffer to get events out;
- a user-space half in Go that loads, attaches and reads;
- a filter in the kernel, so we only pay for what we keep.
To go further:
- libbpf-bootstrap: minimal, working templates in C and Rust.
- cilium/ebpf examples: one small program per hook type, in Go.
- The kernel’s BPF documentation: the reference for helpers, map types and the verifier.
- Your own machine. Pick something you have always wondered about (what opens files at boot, which process makes that DNS query) and answer it with a
bpftraceone-liner first.
The tool is small, but it changed how I look at the kernel. Instead of reading status out of /proc after the fact, you can put your question right where the thing happens.