Riadh Chelbi

DevOps Engineer

← All posts

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.

12 min read

eBPFLinuxSecurity

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.

Overview of the tool: exec.bpf.c is compiled by clang into exec.bpf.o, which bpf2go embeds into a Go binary, execwatch. execwatch loads the program into the kernel, where the verifier checks it, attaches it to the sched_process_exec tracepoint, and reads events from a ring buffer.exec.bpf.ckernel half, Cclangexec.bpf.obytecode + BTFbpf2goexecwatchGo, user halfkernelverifierphase 4tracepointphase 2ring bufferphase 5loadattachon execeventsyour terminal: PID · PPID · COMM, the moment a program starts
The whole tool on one page. Each box is one phase of this post.

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.

Top: ps reads /proc once a second; a process that lives 40 milliseconds between two reads is never seen. Bottom: an eBPF program on the exec tracepoint is called at the exact moment the process starts.polling /proc once a secondreadreadreadreadlives 40 msnever seenlistening on the exec tracepointtold at the exact moment
Polling only sees what is alive at the moment it looks. A tracepoint is told every time.

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.

A one-line script goes to bpftrace, which compiles it to eBPF and loads it; the kernel runs it on every exec, and printf lines come back to your terminal.one-line scriptbpftracecompiles to eBPFkernelruns it on every execprintf → one line per program started
bpftrace does all the phases of this post for you, in one command.
Terminal window
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.

Layers from user space down to the network driver, with the hooks at each: uprobes in user space, syscall tracepoints, the sched_process_exec tracepoint in the scheduler, LSM hooks at security checks, TC in the network stack and XDP in the driver. kprobes and fentry can attach to almost any kernel function.kerneluser-space programsuprobesystem callstracepoint sys_enter_*scheduler: process starttracepoint sched_process_execfiles and security checksLSM: file_open, bprm_check…network stackTCnetwork driverXDPkprobe / fentry: almost any kernel function, at any layer
Where each kind of hook sits. Our tool listens on the scheduler's exec tracepoint.
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:

Terminal window
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.

exec.bpf.c
#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:

  1. SEC("tp/sched/sched_process_exec") tells the loader which hook this function belongs to.
  2. When a program starts, the kernel calls handle_exec.
  3. It reserves room for one event in a ring buffer (more on that in phase 5).
  4. It fills in the process id, the parent’s id and the program name.
  5. It submits the event, and returns.
A program starts, the tracepoint fires and calls handle_exec, which reserves space in the ring buffer, fills in pid, ppid and comm, and submits the event.a program startstracepoint fireshandle_exec()1 reserve2 fill3 submitstruct eventpid4242ppid1337comm"curl"→ ring buffer
One program start, from the kernel's point of view.

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:

Terminal window
bpftool btf dump file /sys/kernel/btf/vmlinux format c > vmlinux.h

BPF_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.

exec.bpf.o remembers task_struct, real_parent, tgid by name. Loaded on kernel A, the loader finds real_parent at one offset; on kernel B, which has a new field earlier in the struct, at another. It reads each kernel's BTF and patches the offset at load time.exec.bpf.oremembers the field, not the offsetkernel Akernel Btask_structpidtgid…real_parent← patchedtask_structpidtgidnew_field…real_parent← patchedthe loader reads each kernel's BTF and fixes the offset at load time
CO-RE: the program remembers the field it wants; the loader finds it on each kernel.

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:

Terminal window
clang -O2 -g -target bpf -c exec.bpf.c -o exec.bpf.o

Phase 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 check

bpf_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.

Two versions of the program. With the null check, both paths after reserve are safe and the program loads. Without it, the null path writes through a null pointer and the verifier rejects the program.with the null checkreserve()oknullwrite e->pidreturn 0every path safe→ loadedwithout itreserve()oknullwrite e->pidwrite via nullone unsafe path→ rejected
The verifier follows both outcomes of reserve(). One unsafe path is enough to refuse the program.

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.

Programs running on CPUs 0 to 3 submit events into one ring buffer shared by all CPUs; execwatch reads them out in order. When the ring is full, reserve returns null and the event is skipped.CPU 0CPU 1CPU 2CPU 3ringexecwatchreads in orderone buffer shared by all CPUs, read in submit orderfull? reserve() returns null: the event is skipped, nothing breaks
One ring for all CPUs: events come out in the order they were submitted.

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.c

Running go generate produces execObjects, with one field per program (HandleExec) and per map (Events), and a loadExecObjects function. The rest is short:

main.go
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:

Terminal window
go generate && go build -o execwatch && sudo ./execwatch

Open 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.

execwatch in user space does three things: 1, load the program, where the verifier checks it; 2, attach it to the sched_process_exec tracepoint; 3, read events from the ring buffer.user spaceexecwatchkernelverifiertracepointsched_process_execring buffer1 load2 attach3 read
What execwatch does when it starts: load, attach, then read forever.

(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:

Terminal window
sudo bpftool prog list # our program, its id and attach type
sudo bpftool map list # our ring buffer
sudo bpftool prog dump xlated id 42 # the instructions the verifier accepted

Phase 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:

Left: every exec becomes an event, crosses into user space, and Go throws away 99 percent. Right: a uid check in the kernel creates only the events you want, and Go prints all of them.kerneluser spacefilter in Gofilter in the kernelevery exec → eventGo drops 99%uid check firstGo prints allevery event copied, then thrown awayonly the answer crosses
Same output, very different cost: drop events before they are created, not after they are shipped.
// 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 execObjects
if 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.

Three nodes, each with its own kernel and eBPF hooks, and an agent pod from a DaemonSet. The kernel knows processes and cgroups; the Kubernetes API adds pod, container and image. Every agent sends to one place where questions can be asked.node 1agentDaemonSet podkerneleBPF hooksnode 2agentDaemonSet podkerneleBPF hooksnode 3agentDaemonSet podkerneleBPF hooks+ pod, container, imagefrom the Kubernetes APIone place to askgraph, storage
On a cluster: one copy of the tool per node, Kubernetes identity added, and one place to ask questions.

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 bpftrace one-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.