Skip to main content

eBPF Runtime Security for Container Escapes

eBPF LSM hooks, ring buffers, and Tetragon policies for catching container escapes at the syscall boundary, with namespace attribution the audit log misses.

KBY Technologies11 min read
eBPF Runtime Security for Container Escapes

Underlined words are defined in the KBY Lexicon. Tap or click one to see what it means.

Standard container isolation degrades the moment a workload requests elevated capabilities, mounts a hostPath volume, or triggers a kernel CVE. Seccomp profiles are static, AppArmor profiles are loaded ahead of time, and auditd operates on a slow, buffered pipeline that cannot correlate a syscall with the cgroup or mount namespace that issued it. By the time a ingests the audit log, the attacker has already pivoted from the container runtime into the host PID namespace. This is the exact gap that eBPF runtime security was built to close: kernel-level, in-line observability with low overhead and full namespace attribution, without recompiling the kernel or restarting the workload.

This article breaks down the architecture required to build a production-grade detection pipeline for container escapes using LSM ( Security Module) hooks, covering the verifier constraints, the userspace aggregation layer, and the failure modes that catch teams out when they move from a proof-of-concept to a fleet-wide rollout.

#The Problem: Static Policy vs Dynamic Kernel State

Container escape detection has traditionally relied on one of three mechanisms: seccomp-bpf syscall filtering, AppArmor/SELinux mandatory access control, or userspace audit correlation (auditd, Falco’s original kernel module). Each has a structural weakness:

  • Seccomp-bpf filters syscalls by number and argument pattern but has no concept of container identity, cgroup path, or mount namespace. It can block unshare() outright, but it cannot conditionally allow it based on runtime context.
  • AppArmor/SELinux profiles are compiled per-image and rarely updated post-deployment. A profile permissive enough to run a legacy application is permissive enough to permit privilege escalation via a writable /proc/sys mount.
  • auditd rules filter in the kernel only on coarse fields such as syscall, path and user, with no container context, so it generates high-cardinality log volume, forcing expensive userspace correlation and introducing detection latency measured in seconds, not microseconds.

None of these solve the core requirement: correlating a kernel-level security-relevant event (a namespace change, a capability escalation, a suspicious ptrace attach) with the exact container, pod, and process tree that generated it, in real time, at the point of execution rather than after the fact.

#Architectural Breakdown: LSM Hooks and the BPF Verifier

The architecture underpinning modern eBPF runtime security rests on the BPF_PROG_TYPE_LSM program type, introduced in Linux 5.7. Unlike kprobes, which attach opportunistically to arbitrary kernel functions and are subject to ABI drift across kernel versions, LSM hooks attach to stable, security-relevant chokepoints defined in security/security.c: bprm_check_security, task_kill, file_open, sb_mount, and capable among them.

eBPF runtime security

Every eBPF LSM program must pass the in-kernel verifier before load. The verifier performs static analysis to guarantee bounded loops, no unchecked pointer arithmetic, and no possibility of the program hanging or crashing the kernel. This is the trade-off that makes eBPF runtime security viable at scale: the kernel guarantees the safety of third-party code without a context switch to userspace on the hot path.

Data flows out of the kernel via a BPF ring buffer (BPF_MAP_TYPE_RINGBUF), which replaced the older perf buffer implementation to eliminate per-CPU memory waste and reduce event-copy overhead. The userspace agent (commonly built on libbpf and BPF CO-RE) polls this buffer, enriches each event with container metadata pulled from /proc/[pid]/cgroup and the cgroup ID cached in a BPF hash map, and forwards structured events to a detection engine.

#
Why eBPF Runtime Security Outperforms Kernel Modules

Legacy kernel-module-based detection (the original Falco driver, for instance) requires out-of-tree compilation against the exact running kernel headers, which is a maintenance burden across heterogeneous fleets. eBPF programs compiled with CO-RE relocations read kernel struct offsets from BTF (BPF Type Format) data at load time, which reduces the need for per-kernel builds on BTF-enabled kernels (those built with CONFIG_DEBUG_INFO_BTF). Programs still depend on the kernel features they use, so test them on each supported kernel. This portability is a primary reason eBPF runtime security has displaced kernel-module approaches in many production observability stacks such as Cilium Tetragon and Falco’s modern eBPF driver.

#Implementation Logic: From Hook to Alert

Building the detection pipeline follows a consistent sequence regardless of the specific tool used:

  • Step 1 — Hook selection: Attach to the LSM hook bprm_check_security for exec-time detection, sb_mount for host filesystem remounts, and ptrace_access_check for process-injection attempts. Denying an operation requires an LSM program (BPF_PROG_TYPE_LSM); kprobes on security_* functions only observe, unless the kernel is built with CONFIG_BPF_KPROBE_OVERRIDE, which from Linux 5.7 lets a kprobe override their return value.
  • Step 2 — Context capture: Inside the BPF program, read the task’s active PID namespace through task_struct->thread_pid to derive the PID namespace inode (nsproxy->pid_ns_for_children is the namespace its children will get, which differs after unshare(CLONE_NEWPID)), and bpf_get_current_cgroup_id() to bind the event to a specific container.
  • Step 3 — In-kernel filtering: Apply an allow-list lookup against a BPF hash map keyed by binary path hash, discarding benign events before they ever reach the ring buffer. This keeps event volume and CPU overhead down; measure the actual overhead on your own workloads.
  • Step 4 — Userspace correlation: The agent joins the cgroup ID against the container runtime’s metadata store (containerd’s CRI API or the Kubernetes API server) to resolve pod name, namespace, and image digest.
  • Step 5 — Policy evaluation: Events are matched against a declarative ruleset (a TracingPolicy or Falco rule) and either logged, alerted, or, where the program type supports it, used to call bpf_send_signal() against the offending process. Note that the signal is delivered asynchronously, so the operation may complete before the process is killed; to stop an operation before it completes, use an LSM return value.

#
Enforcing In-Kernel Kill Decisions

The most advanced deployments of eBPF runtime security do not stop at detection; they enforce a decision inside the LSM hook itself, returning a non-zero value (such as -EPERM) from the BPF program to deny the syscall before it completes. This closes the race-condition window that plagues userspace-only detection, where an attacker’s escape syscall has already succeeded by the time an alert reaches a human or an automated responder.

eBPF Runtime Security for Container Escapes architecture diagram 2

#Code and Configuration Examples

#
1. Minimal LSM Hook in C (libbpf CO-RE)

1SEC("lsm/bprm_check_security")
2int BPF_PROG(detect_exec, struct linux_binprm *bprm)
3{
4    u64 cgroup_id = bpf_get_current_cgroup_id();
5    const char *filename = BPF_CORE_READ(bprm, filename);
6
7    struct exec_event *e;
8    e = bpf_ringbuf_reserve(&events, sizeof(*e), 0);
9    if (!e)
10        return 0;
11
12    e->cgroup_id = cgroup_id;
13    e->pid = bpf_get_current_pid_tgid() >> 32;
14    bpf_probe_read_kernel_str(&e->filename, sizeof(e->filename), filename);
15
16    bpf_ringbuf_submit(e, 0);
17    // Detection-only: always allows the exec.
18    // To enforce, return -EPERM only under a specific condition, e.g.:
19    // if (is_denied(e)) return -EPERM;
20    return 0;
21}

#
2. Cilium Tetragon TracingPolicy for Mount Namespace Escapes

The following is an illustrative example for monitoring mounts, not a ready-to-deploy policy. Check the arguments of security_sb_mount for your kernel version and the Tetragon documentation before relying on the argument indexes and types below.

1apiVersion: cilium.io/v1alpha1
2kind: TracingPolicy
3metadata:
4  name: detect-host-mount-escape
5spec:
6  kprobes:
7  - call: security_sb_mount
8    syscall: false
9    args:
10    - index: 0
11      type: "string"
12    - index: 1
13      type: "path"
14    selectors:
15    - matchArgs:
16      - index: 1
17        operator: "Prefix"
18        values:
19        - "/host"
20        - "/proc/1/root"
21      matchActions:
22      - action: Post

Start with the Post action only, which reports matches without killing anything. Scope the policy with podSelector or namespace-scoped policies rather than applying it cluster-wide, and verify the hooked function’s argument types and indexes for your kernel before relying on it. Only after reviewing the events should you stage a move to Sigkill, starting with a small set of workloads. To roll back, delete the TracingPolicy (for example with kubectl delete tracingpolicy detect-host-mount-escape).

#
3. Verifying Load Success and Ring Buffer Health with bpftool

1$ bpftool prog show name detect_exec
242: lsm  name detect_exec  tag 3a9f2b7c1d0e4f58  gpl
3  loaded_at 2024-03-11T09:14:02+0000  uid 0
4  xlated 512B  jited 320B  memlock 4096B  map_ids 7,8
5
6$ bpftool map dump id 7 | head -n 5
7key: 00 00 00 00 00 00 00 00  value: 6f 6e 65 5f 62 69 6e...
8
9# Check program overhead (run_time_ns is cumulative runtime, not a drop counter)
10$ cat /proc/sys/kernel/bpf_stats_enabled
111
12$ bpftool prog show name detect_exec --json | jq '.run_time_ns'
131843221

#Failure Modes and Edge Cases

Deploying eBPF runtime security fleet-wide surfaces several failure classes that rarely appear in single-node testing:

  • Verifier rejection on kernel upgrade: A program that loads cleanly on 6.1 may be rejected on 5.10 due to differing complexity limits (the verifier’s instruction-count ceiling was raised progressively). Pin CO-RE builds to your minimum supported kernel and test against it explicitly in CI.
  • Ring buffer overflow under syscall storms: A fork-bomb or a legitimate CI runner generating thousands of exec events per second can exhaust the ring buffer faster than userspace can drain it, causing silent event loss. Size the single shared ring buffer (a power-of-two multiple of the page size, for example 8-64MB) based on the measured event rate. Count bpf_ringbuf_reserve() failures in the BPF program using a per-CPU array map that userspace reads, rather than relying on downstream alert gaps; use bpf_ringbuf_query() only to watch fill level.
  • TOCTOU races in file-based hooks: A hook on file_open that reads a file’s contents for signature matching after the open call completes can be beaten by a symlink swap between the check and the read. Prefer checks on stable kernel objects over re-reading paths in userspace, and validate any mitigation on your own kernels.
  • Stale cgroup metadata: The kernel gives each cgroup a 64-bit unique ID, but on clusters with high pod churn a userspace cache that misses a removal or a late container start may still attribute events to the wrong pod. Join on pod UID or container ID together with timestamps, and remove cache entries when a cgroup is removed, to avoid false attribution in forensic timelines.
  • Kernel lockdown mode conflicts: Kernel lockdown restricts BPF functionality: lockdown=integrity blocks helpers such as bpf_probe_write_user, and lockdown=confidentiality also blocks reading kernel memory (for example bpf_probe_read_kernel). Tracing programs that use these helpers may fail to load rather than degrade quietly. Check the lockdown mode on each node (/sys/kernel/security/lockdown) and confirm that programs load and behave as expected under it before rollout.

#Scaling and Security Trade-offs

Rolling eBPF runtime security across a multi-tenant fleet requires explicit trade-off decisions rather than default configuration. Teams building this into their broader architectural patterns for platform security should evaluate the following axes before committing to enforcement mode cluster-wide:

  • Detection-only vs enforcement: Detection-only deployments carry far lower risk of application disruption than enforcement mode, which risks blocking or killing legitimate processes on rule misconfiguration.
  • Per-core overhead: Pipelines with in-kernel filtering generally cost much less CPU than those that ship every syscall to userspace, but the actual overhead depends on event rate, hooks and workload. Measure it on your own workloads in a pilot before rollout.
  • Kernel version fragmentation: Fleets spanning kernel 4.x (pre-LSM-BPF) require a fallback to kprobe-based instrumentation, which lacks the ABI stability guarantees of the LSM hook API and increases maintenance surface.
  • Alert fidelity vs volume: Broad hook coverage (every capable() call, for example) generates high alert volume with a poor signal-to-noise ratio; narrowing to security-relevant capability checks (CAP_SYS_ADMIN, CAP_SYS_PTRACE) materially reduces false positives; check that the narrowed list still covers the escape techniques in your threat model.
  • Privileged agent exposure: The userspace agent itself needs at least CAP_BPF and CAP_PERFMON, and often more (many tools run fully privileged), making it a high-value target; it must be treated as part of the trusted computing base and isolated in its own restrictive seccomp profile, distinct from the workloads it monitors.

The architectural decision ultimately hinges on the organisation’s tolerance for enforcement-induced disruption against its exposure to kernel-level compromise. Reference the upstream Linux kernel BPF documentation when validating hook availability and verifier constraints against your specific kernel baseline before committing a policy to production enforcement.

Evidence trail

Sources and verification

Primary documentation and external technical references used in this article.

  1. 01libbpf and BPF CO-REebpf.io
  2. 02Linux kernel BPF documentationdocs.kernel.org

About this page

Credited to

Dates

Published

Last updated

Corrections

  • : Corrected during a review of published articles. Details
  • : Corrected during a review of published articles. Details
Reader Interaction

Comments

Add a thoughtful note on eBPF Runtime Security for Container Escapes. Comments are checked for spam and held for moderation before appearing.

Loading comments...

Discover more

Was this useful?

Reports go to the site owner and are used to correct pages. Corrections are listed at /corrections.

Engineering insights, direct to you.

Receive the latest Systems Engineering tutorials, production guides, Engineering Labs and operational best practices.