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.

In this guide
Table of Contents
Table of contents
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 policies are compiled at build 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 SIEMThe KBY LexiconSIEMSIEM (Security Information and Event Management) centralises log and event data and applies correlation logic to support security detection, investigation and response. 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 eBPFThe KBY LexiconeBPF (Extended Berkeley Packet Filter)eBPF is a Linux kernel virtual machine that runs sandboxed, verified programs at kernel hook points for near-native-speed observability, networking, and security enforcement without kernel modules. LSM (LinuxThe KBY LexiconLinuxLinux is the open-source kernel underlying most server, container and cloud infrastructure; distinct from the distributions built around it. 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/sysmount. - auditd generates high-cardinality log volume with no in-kernel filtering, 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.

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_securityfor exec-time detection,sb_mountfor host filesystem remounts, andptrace_access_checkfor process-injection attempts. Denying an operation requires an LSM program (BPF_PROG_TYPE_LSM); kprobes onsecurity_*functions can observe but cannot deny a syscall. - Step 2 — Context capture: Inside the BPF program, read
task_struct->nsproxy->pid_ns_for_childrento derive the PID namespace inode, andbpf_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.

#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: PostStart 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 3a9f2b7c1d0e 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; usebpf_ringbuf_query()only to watch fill level. - TOCTOU races in file-based hooks: A hook on
file_openthat 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. - Cgroup ID reuse: A cgroup ID can be reused after the cgroup is removed, so on clusters with high pod churn a stale cache entry may 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=integrityblocks helpers such asbpf_probe_write_user, andlockdown=confidentialityalso blocks reading kernel memory (for examplebpf_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 without losing coverage of known escape techniques. - Privileged agent exposure: The userspace agent itself typically runs with
CAP_BPFandCAP_PERFMON, 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.
#Related reading
Evidence trail
Sources and verification
Primary documentation and external technical references used in this article.
About this page
Credited to
Dates
Published
Last updated
Corrections
- : Corrected during a review of published articles. Details
Read-only scripts
- Windows devices with no BitLocker recovery key in Entra IDMicrosoft Entra ID, Windows
- Intune devices that haven't synced in N daysMicrosoft Intune
- Mailboxes forwarding to external addressesExchange Online
- BitLocker status of every volume on this PCWindows
Upcoming deadlines
- Intune moves to macOS 15 and laterQ4 2026
- SAP SuccessFactors provisioning: move from basic auth to workload identityNovember 2026
- Intune November release: JIT registration reminder at APNs renewal and automatic JIT for eligible tenantsNovember 2026
Explore KBY
The KBY Brief
A short email about twice a week with new runbooks, configuration traps and fixes from KBY Technologies.
SubscribeRelated Engineering Labs
Calculator
Resource Profiler
Generate conservative Node.js, Go, or Java runtime starting policies for a supplied Kubernetes CPU and memory limit, with explicit caveats.
Simulator
CA What-If
Model a set of Conditional Access policies against one sign-in and see which policies apply, why the others don't, and whether access is blocked, granted, or granted after MFA.
Calculator
CIDR Planner
Normalize IPv4/IPv6 networks, calculate exact ranges and audit batch allocations for containment, overlap, alignment and unused capacity.
Related articles
Security & Operations
eBPF Intrusion Detection for K8s Lateral Movement
A staff engineer's guide to building eBPF intrusion detection pipelines that catch lateral movement and syscall anomalies inside Kubernetes clusters.
Security & Operations
Detecting DNS Tunnelling via Resolver Entropy
How Shannon entropy scoring, dnstap capture, and PowerDNS Lua hooks catch DNS tunnelling exfiltration that firewall egress rules miss entirely.
Security & Operations
Sudoers NOPASSWD: The Silent Path to Root
Wildcard NOPASSWD entries in sudoers quietly open root shells; here's how the escalation chain forms, how to audit it fleet-wide, and how to fix it.
Security & Operations
Microsoft Defender for Endpoint Device Stuck Onboarding or Inactive
A layered method for diagnosing Windows devices that show Inactive or never appear in Microsoft Defender for Endpoint.
Discover more
Learn More About KBY
About KBY
Learn about our mission, how our content is produced, and how we handle corrections.
Why Trust KBY
How KBY content is produced, what is checked automatically, and how errors are corrected.
The KBY Brief
A short email about twice a week with new runbooks, configuration traps and fixes from KBY Technologies.
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.
Comments
Add a thoughtful note on eBPF Runtime Security for Container Escapes. Comments are checked for spam and held for moderation before appearing.