>samit_hota
Back to research
THREAT INTELLIGENCE

Building Custom eBPF Kernel Monitors for Fileless Linux Threats

Samit Hota·
#ebpf#linux#threat-detection#kernel

Most Linux security configurations treat auditd as an unassailable source of truth. That reliance is a tactical error. Userland logging infrastructure is trivially choked by event floods, routinely blinded when attackers unhook userland shims, and completely oblivious to stealth techniques like fileless payload execution via memfd_create. If your detection pipeline sits entirely above the kernel boundary, you are reading filtered telemetry curated by whatever executed on the host before your agent started watching.

To catch post-exploitation mechanics like process injection, credential scraping via memory access, and fileless execution, you need to monitor syscall invocation directly inside the kernel ring. Extended Berkeley Packet Filter (eBPF) lets us run safe, sandboxed bytecode at kernel tracepoints without writing unstable Kernel Modules (LKMs) or risking Kernel Panics.

In this tutorial, we will write a custom eBPF threat monitor from scratch using Python and the BPF Compiler Collection (BCC). By the end, you will have a running daemon capable of capturing sub-millisecond alerts on process memory tampering and fileless binary execution.

Setting Up the BCC Development Environment

We will use BCC because it abstracts the complex LLVM compilation chain while letting us embed C-based eBPF probes directly within Python control logic.

Run the following commands on a Debian/Ubuntu-based machine (kernel 5.4+ recommended) to install the necessary compiler toolchain, kernel headers, and BCC bindings:

sudo apt-get update
sudo apt-get install -y \
    bpfcc-tools \
    python3-bpfcc \
    linux-headers-$(uname -r) \
    build-essential \
    libbpf-dev

Verify your kernel supports BPF tracepoints by checking for the tracepoint filesystem:

ls /sys/kernel/debug/tracing/events/syscalls/sys_enter_ptrace

If that directory exists, your kernel exposes the tracepoints we need.

Identifying Key Syscalls for Threat Detection

Standard loggers focus heavily on process creation (execve). Modern attackers work around this by avoiding disk artifacts entirely or abusing debugging interfaces. We will focus our custom monitor on two high-fidelity attack vectors:

  1. ptrace (sys_enter_ptrace): Used by utilities like GDB, but also by attackers for process injection, shellcode insertion, and reading memory contents of sensitive processes (such as SSH daemons or keyrings).
  2. memfd_create (sys_enter_memfd_create): Allocates anonymous memory blocks that behave like regular file descriptors. Attackers write ELF binaries into this memory space and execute them via fexecve or /proc/self/fd/, bypassing disk-based file integrity monitoring (FIM) and AV scanners completely.

Writing the Kernel-Space eBPF Probe

Create a file named kernel_monitor.py. We will start by defining the C code that compiles into kernel eBPF bytecode. This code hooks directly into the kernel’s tracepoints and streams alert data back to userland via a perf ring buffer.

#!/usr/bin/env python3
from bcc import BPF
import ctypes as ct
import time
import json

# Define the C program running in kernel space
bpf_source = """
#include <uapi/linux/ptrace.h>
#include <linux/sched.h>

// Event structure pushed to userland
struct telemetry_event_t {
    u32 pid;
    u32 tgid;
    u32 uid;
    char comm[TASK_COMM_LEN];
    u32 event_type; // 1 = PTRACE, 2 = MEMFD
    u64 payload_val; // Stores ptrace request type or memfd flags
};

BPF_PERF_OUTPUT(events);

// Hook: ptrace execution (Process Injection / Scraping)
TRACEPOINT_PROBE(syscalls, sys_enter_ptrace) {
    struct telemetry_event_t event = {};
    
    u64 pid_tgid = bpf_get_current_pid_tgid();
    event.pid = pid_tgid;
    event.tgid = pid_tgid >> 32;
    event.uid = bpf_get_current_uid_gid();
    
    bpf_get_current_comm(&event.comm, sizeof(event.comm));
    
    event.event_type = 1;
    event.payload_val = args->request; // Capture PTRACE_ATTACH, PTRACE_POKETEXT, etc.

    events.perf_submit(args, &event, sizeof(event));
    return 0;
}

// Hook: memfd_create (Fileless Binary Allocation)
TRACEPOINT_PROBE(syscalls, sys_enter_memfd_create) {
    struct telemetry_event_t event = {};
    
    u64 pid_tgid = bpf_get_current_pid_tgid();
    event.pid = pid_tgid;
    event.tgid = pid_tgid >> 32;
    event.uid = bpf_get_current_uid_gid();
    
    bpf_get_current_comm(&event.comm, sizeof(event.comm));
    
    event.event_type = 2;
    event.payload_val = args->flags;

    events.perf_submit(args, &event, sizeof(event));
    return 0;
}
"""

Notice bpf_get_current_comm(). This pulls the process name directly from the process task structure inside kernel memory space, making it immune to basic process-renaming tricks attempted in userland.

Building the Userland Event Harvester

Now we append the Python consumer logic to kernel_monitor.py. This reads from the perf buffer, parses the struct fields sent by the eBPF probes, and prints structured JSON events.

# C-compatible struct for Python unpacking
class TelemetryEvent(ct.Structure):
    _fields_ = [
        ("pid", ct.c_uint32),
        ("tgid", ct.c_uint32),
        ("uid", ct.c_uint32),
        ("comm", ct.c_char * 16),
        ("event_type", ct.c_uint32),
        ("payload_val", ct.c_uint64),
    ]

PTRACE_REQUESTS = {
    0: "PTRACE_TRACEME",
    1: "PTRACE_PEEKTEXT",
    2: "PTRACE_PEEKDATA",
    4: "PTRACE_POKETEXT",
    5: "PTRACE_POKEDATA",
    16: "PTRACE_ATTACH",
    24: "PTRACE_SEIZE"
}

def print_event(cpu, data, size):
    event = ct.cast(data, ct.POINTER(TelemetryEvent)).contents
    
    event_type_str = "UNKNOWN"
    details = ""

    if event.event_type == 1:
        event_type_str = "PTRACE_SUSPECT"
        req_name = PTRACE_REQUESTS.get(event.payload_val, f"RAW_REQ_{event.payload_val}")
        details = f"Request: {req_name}"
    elif event.event_type == 2:
        event_type_str = "MEMFD_ANONYMOUS_EXEC"
        details = f"Flags: {hex(event.payload_val)}"

    log_entry = {
        "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "alert_type": event_type_str,
        "process_name": event.comm.decode('utf-8', 'replace'),
        "pid": event.pid,
        "uid": event.uid,
        "details": details
    }
    
    print(json.dumps(log_entry), flush=True)

def main():
    print("[*] Compiling eBPF probes and attaching to tracepoints...")
    b = BPF(text=bpf_source)
    
    # Open the ring buffer
    b["events"].open_perf_buffer(print_event)
    print("[*] Monitor live. Tracking kernel events (Ctrl+C to stop)...")

    while True:
        try:
            b.perf_buffer_poll()
        except KeyboardInterrupt:
            print("\n[*] Detaching probes and exiting.")
            exit(0)

if __name__ == "__main__":
    main()

Validating Detections Against Real Techniques

Make the script executable and launch it with root permissions (required to load eBPF bytecode into the kernel):

chmod +x kernel_monitor.py
sudo ./kernel_monitor.py

Leave that process running in terminal 1. Open a second terminal window to simulate real attacker behaviors.

Test 1: Simulating Memory Inspection / Injection (ptrace)

Run strace or gdb against any existing process, or target a system service:

# Attach strace to sleep (uses PTRACE_ATTACH under the hood)
sleep 100 &
strace -p $!

In terminal 1, your eBPF monitor immediately fires a context-rich JSON payload directly from the kernel event stream:

{
  "timestamp": "2026-03-30T14:22:01Z",
  "alert_type": "PTRACE_SUSPECT",
  "process_name": "strace",
  "pid": 14209,
  "uid": 1000,
  "details": "Request: PTRACE_ATTACH"
}

Test 2: Simulating Fileless Execution (memfd_create)

Test the memfd_create tracepoint using standard Python inside terminal 2 to allocate anonymous RAM execution space without creating a file on /tmp or /dev/shm:

python3 -c '
import ctypes, os
libc = ctypes.CDLL(None)
# Call memfd_create("stealth_module", 0) directly
fd = libc.memfd_create(b"stealth_module", 0)
print(f"Anonymous RAM File Descriptor created: {fd}")
'

Terminal 1 captures the creation instantly:

{
  "timestamp": "2026-03-30T14:24:18Z",
  "alert_type": "MEMFD_ANONYMOUS_EXEC",
  "process_name": "python3",
  "pid": 14352,
  "uid": 1000,
  "details": "Flags: 0x0"
}

Hardening the Monitor for Production

What we built here is a minimal operational prototype. Moving from a script to a production sensor requires three hardening steps:

  1. Move from BCC to CO-RE (Compile Once – Run Everywhere): BCC requires the full Clang/LLVM compiler and kernel headers installed on every production target. Production implementations should compile the C code using libbpf and BTF (BPF Type Format) into lightweight ELF binaries that run seamlessly across heterogeneous kernel versions without compiler dependencies.
  2. Filter Known-Good Binaries Kernel-Side: Avoid pushing noise (e.g., standard debuggers, valid container runtimes) to userland. Add filtering conditions directly inside the C code using eBPF maps to filter safe PIDs/UIDs before events enter the perf buffer.
  3. Monitor process_vm_writev: Ptrace is not the only vector for memory manipulation. Add tracepoint probes for sys_enter_process_vm_writev and sys_enter_process_vm_readv to catch stealth memory modification frameworks that avoid traditional debug attaches.

Want a second set of eyes on your security posture?

Let's talk about where your real exposure is.

Book an advisory call