User-space logging tools like auditd and process-listing polling scripts are fundamentally inadequate for detecting modern Linux post-exploitation. By the time a user-space daemon polls /proc to check for suspicious child processes, an attacker’s short-lived subshell or memory-injected payload has already executed, exfiltrated credentials, and cleaned up its trace.
eBPF (Extended Berkeley Packet Filter) solves this problem by allowing us to execute sandboxed programs directly inside the Linux kernel at safety-checked tracepoints. When an adversary achieves remote code execution (RCE) on a web application, they almost always violate process behavioral norms in two distinct ways: spawning an unexpected binary (execve) or initiating an egress socket connection (connect).
In this tutorial, we will construct an eBPF-based detection pipeline using bpftrace to intercept these exact syscalls, isolate anomalous behavior originating from web processes, and emit actionable alerts.
Prerequisites and Setup
To run eBPF programs, your Linux kernel must be compiled with CONFIG_BPF=y and CONFIG_BPF_SYSCALL=y (standard on Ubuntu 20.04+, Debian 11+, and RHEL 8+). You will also need root privileges to load eBPF programs into the kernel.
Install bpftrace and kernel headers on Debian/Ubuntu systems:
sudo apt-get update
sudo apt-get install -y bpftrace linux-headers-$(uname -r)
Verify that tracepoints for execution and network sockets are available on your system:
sudo bpftrace -l 'tracepoint:sys_enter_execve'
sudo bpftrace -l 'tracepoint:sys_enter_connect'
If both tracepoints return in your terminal, your kernel is ready.
Tracing Process Executions with bpftrace
When a web server like Nginx, Node.js, Python (gunicorn), or Apache is compromised, it typically transitions from handling HTTP traffic to executing system shells (such as /bin/sh or /bin/bash).
We start by attaching an eBPF program to the sys_enter_execve kernel tracepoint. This tracepoint fires every time a process calls the execve system call to execute a new program.
Create a file named detect_exec.bt:
#!/usr/bin/env bpftrace
tracepoint:sys_enter_execve
/comm == "nginx" || comm == "node" || comm == "python3" || comm == "gunicorn"/
{
$filename = str(args->filename);
$parent_pid = curtask->real_parent->pid;
$parent_comm = curtask->real_parent->comm;
printf("[ALERT - EXEC] Web Server Process '%s' (PID %d, Parent %s [%d]) executed: %s\n",
comm, pid, $parent_comm, $parent_pid, $filename);
}
How this detection logic works:
tracepoint:sys_enter_execve: Attaches the probe to the entry of theexecvesystem call./comm == .../: Filters events at the kernel level. Only calls made by processes namednginx,node,python3, orgunicornwill trigger the execution block. Unrelated system events are discarded immediately inside the kernel, keeping CPU overhead near zero.args->filename: Reads the path of the binary being executed directly from the tracepoint argument structure.curtask->real_parent: Navigates the kernel’stask_structto extract the parent process identifier and name for contextual attribution.
Run the program:
sudo bpftrace detect_exec.bt
If a Python web application triggers os.system('/bin/bash'), bpftrace captures the event instantly before the shell even renders a prompt:
[ALERT - EXEC] Web Server Process 'python3' (PID 41205, Parent systemd [1]) executed: /bin/bash
Catching Unintended Outbound Connections
A web server rarely needs to initiate outbound TCP connections to arbitrary external IP addresses. When attackers establish reverse shells or fetch secondary payloads, they trigger the connect syscall.
To monitor outbound network traffic, we attach to sys_enter_connect. Because raw kernel memory represents IP addresses and port structures as binary sockaddrs, we must parse and cast the memory buffer to extract IPv4 targets.
Create a file named detect_connect.bt:
#!/usr/bin/env bpftrace
#include <linux/in.h>
tracepoint:sys_enter_connect
/comm == "nginx" || comm == "node" || comm == "python3" || comm == "gunicorn"/
{
$sa = (struct sockaddr_in *)args->uservaddr;
// Only inspect IPv4 connections (AF_INET = 2)
if ($sa->sin_family == AF_INET) {
$raw_port = $sa->sin_port;
// Convert port from network byte order (big-endian) to host byte order
$port = ($raw_port >> 8) | (($raw_port & 0xff) << 8);
$ip = ntop(AF_INET, &$sa->sin_addr.s_addr);
// Filter out loopback traffic (127.0.0.1)
if ($ip != "127.0.0.1") {
printf("[ALERT - CONNECT] Web Server '%s' (PID %d) initiating egress connection to %s:%d\n",
comm, pid, $ip, $port);
}
}
}
Key Technical Considerations:
- Byte Ordering: Network protocols use big-endian ordering, while standard x86_64 architecture uses little-endian. We perform bit-shifting (
($raw_port >> 8) | ...) to parse the actual destination port correctly. - Kernel Helpers: The
ntophelper formats the raw 32-bit integer IP representation into a human-readable dotted-decimal string right inside kernel space. - Noise Reduction: Excluding
127.0.0.1prevents alert fatigue caused by application servers querying local databases or sidecar proxies (like Redis or PostgreSQL running on localhost).
Assembling a Production-Ready Threat Detector
We can combine both execution tracing and egress socket monitoring into a single unified script. We will add timestamping and standard JSON output formatting so events can be routed directly into a SIEM or log forwarder like Fluentbit or Vector.
Save the following complete detector script as web_runtime_monitor.bt:
#!/usr/bin/env bpftrace
#include <linux/in.h>
BEGIN
{
printf("{\"status\": \"eBPF monitor initialized\", \"target_processes\": [\"nginx\", \"node\", \"python3\"]}\n");
}
tracepoint:sys_enter_execve
/comm == "nginx" || comm == "node" || comm == "python3"/
{
$filename = str(args->filename);
printf("{\"timestamp\": \"%s\", \"event\": \"EXEC\", \"process\": \"%s\", \"pid\": %d, \"ppid\": %d, \"target\": \"%s\"}\n",
strftime("%Y-%m-%dT%H:%M:%SZ", nsecs),
comm,
pid,
curtask->real_parent->pid,
$filename);
}
tracepoint:sys_enter_connect
/comm == "nginx" || comm == "node" || comm == "python3"/
{
$sa = (struct sockaddr_in *)args->uservaddr;
if ($sa->sin_family == AF_INET) {
$port = (($sa->sin_port >> 8) | (($sa->sin_port & 0xff) << 8));
$ip = ntop(AF_INET, &$sa->sin_addr.s_addr);
if ($ip != "127.0.0.1") {
printf("{\"timestamp\": \"%s\", \"event\": \"CONNECT\", \"process\": \"%s\", \"pid\": %d, \"dst_ip\": \"%s\", \"dst_port\": %d}\n",
strftime("%Y-%m-%dT%H:%M:%SZ", nsecs),
comm,
pid,
$ip,
$port);
}
}
}
Make the script executable and launch it:
chmod +x web_runtime_monitor.bt
sudo ./web_runtime_monitor.bt
Testing the Logic Against a Simulated RCE
To validate the detection logic, simulate an exploitation scenario in a separate terminal window.
- Start a mock Python web application:
python3 -m http.server 8080
- Open another terminal and simulate an RCE payload executing a command and fetching a remote resource via
python3:
# Simulate a shell payload execution
python3 -c "import os; os.system('id')"
# Simulate an outbound reverse shell attempt or payload retrieval
python3 -c "import socket; s = socket.socket(); s.connect(('93.184.216.34', 80))"
- Observe the output generated by
web_runtime_monitor.bt:
{"status": "eBPF monitor initialized", "target_processes": ["nginx", "node", "python3"]}
{"timestamp": "2024-03-30T14:22:01Z", "event": "EXEC", "process": "python3", "pid": 48912, "ppid": 48800, "target": "/usr/bin/id"}
{"timestamp": "2024-03-30T14:22:15Z", "event": "CONNECT", "process": "python3", "pid": 48950, "dst_ip": "93.184.216.34", "dst_port": 80}
The detector captures the underlying execve call (/usr/bin/id) and the egress TCP handshake (93.184.216.34:80) immediately as they occur at the kernel layer, providing high-fidelity telemetry that cannot be blinded by standard user-space evasion tricks.
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