Fuzzing the EBPF Subsystem

Zac Ecob (Computer Science Student · UNSW)

BSides Canberra VII (2024) · Day 2 · Main Track

Overview

In his BSides Canberra talk, "Fuzzing the EBPF Subsystem," Zac Ecob, a final-year Computer Science student at UNSW, delved into the intricacies of fuzzing the Extended Berkeley Packet Filter (eBPF) subsystem within the Linux kernel. eBPF is a powerful in-kernel virtual machine that allows users to run custom programs at various hook points throughout the kernel, offering unprecedented flexibility for tasks like networking, tracing, and security monitoring. However, this power comes with a significant security challenge: ensuring that user-supplied eBPF programs cannot compromise the kernel.

Watch on YouTube

Visual summary for Fuzzing the EBPF Subsystem by Zac Ecob
Visual summary for Fuzzing the EBPF Subsystem by Zac Ecob

Key moments

  1. 1:00 What is eBPF? Kernel programs and security verifier.
  2. 5:05 Why eBPF is an interesting, under-researched fuzzing target.
  3. 11:55 Generating eBPF programs: from random bytes to valid instructions.
  4. 20:10 Tackling control flow: ensuring program reachability and termination.
  5. 32:00 Key fuzzer design lessons: automation and strong type systems.
  6. 42:40 Bug example: Verifier misestimates register values from signed casts.
  7. 46:40 Q&A: How the verifier handles infinite loops.
  8. 50:10 Q&A: Considering an intermediate language for easier eBPF modeling.

Fuzzing the EBPF Subsystem

Speakers: Zac Ecob, Computer Science Student, UNSW

Conference: BSides Canberra

YouTube: https://www.youtube.com/watch?v=bww1HkBiYpA

Overview

In his BSides Canberra talk, "Fuzzing the EBPF Subsystem," Zac Ecob, a final-year Computer Science student at UNSW, delved into the intricacies of fuzzing the Extended Berkeley Packet Filter (eBPF) subsystem within the Linux kernel. eBPF is a powerful in-kernel virtual machine that allows users to run custom programs at various hook points throughout the kernel, offering unprecedented flexibility for tasks like networking, tracing, and security monitoring. However, this power comes with a significant security challenge: ensuring that user-supplied eBPF programs cannot compromise the kernel.

The core security mechanism for eBPF is its verifier, a complex component responsible for statically analyzing eBPF programs before execution to guarantee their safety properties, such as memory access, termination, and initialized value usage. A bug in this verifier, allowing it to incorrectly approve an unsafe program, can lead directly to kernel code execution, a critical privilege escalation vulnerability. Ecob's talk focuses on the development of FEEP (Freaking Fabulous Extended Berkeley Packet Filter Fuzzer), a specialized fuzzer designed to automatically generate complex eBPF programs specifically crafted to uncover these elusive verifier logic bugs.

This research is particularly pertinent as eBPF's adoption continues to grow across various critical infrastructure components, from cloud environments to network devices. While eBPF programs ideally run in a sandboxed environment, a compromised verifier undermines this fundamental security model. Ecob's work highlights the ongoing need for rigorous security analysis of eBPF, demonstrating that even well-vetted kernel components can harbor subtle vulnerabilities detectable through targeted fuzzing approaches. His insights into building a fuzzer for such a complex target provide valuable lessons for security researchers and kernel developers alike.

Background

▶ Watch: What is eBPF? Kernel programs and security verifier. (1:00)

The eBPF subsystem is a revolutionary component of the Linux kernel, acting as a highly efficient and programmable virtual machine. Its primary purpose is to allow users to submit small, sandboxed programs that execute directly within the kernel context at predefined "hook points." Initially, its use cases were primarily networking-focused, such as filtering or rerouting packets. However, eBPF's capabilities have expanded dramatically, now encompassing a wide array of kernel operations, including file system events, system call tracing (via kprobes and uprobes), and performance monitoring.

eBPF presents itself as a modern alternative to traditional Linux kernel modules. While kernel modules offer immense power by being written in C and compiled directly into the kernel, they also inherit all the security pitfalls of C, including memory corruption vulnerabilities. Furthermore, loading kernel modules typically requires root privileges, making them unsuitable for less privileged users. eBPF, in contrast, aims to allow more flexible program submission, potentially even from unprivileged users, while maintaining kernel integrity. In practice, however, the security implications quickly led to restrictions; loading eBPF programs now generally requires specific capabilities like CAP_BPF, CAP_NET_ADMIN (for networking eBPF), or CAP_PERFMON (for performance monitoring). This means that eBPF vulnerabilities often manifest as privilege escalations from a lower-privileged, but still capable, user to full root access.

The linchpin of eBPF's security model is the eBPF verifier. This sophisticated static analysis engine scrutinizes every submitted eBPF program to ensure it adheres to a strict set of safety properties. The verifier asks crucial questions: Is the program memory-safe? Does it handle uninitialized values correctly? Will it always terminate? It operates with a conservative mindset, rejecting any program it cannot be 100% confident is safe. If the verifier makes an error – a "bug" in its logic – and incorrectly accepts an unsafe program, that program can then execute in the kernel with unintended, often malicious, consequences, leading to kernel code execution.

Zac Ecob specifically chose eBPF as a fuzzing target despite its current requirement for capabilities, which might make it less attractive for immediate financial gain compared to unprivileged vulnerabilities. His reasoning was multi-faceted. Firstly, the unique challenge of having a fuzzer generate programs from scratch, rather than simple data inputs, appealed to his "nerd self." Secondly, he observed that eBPF appeared to be under-researched in the fuzzing community. General-purpose kernel fuzzers like Syzkaller struggle with the intricate and complex type system required to describe valid eBPF programs, often falling short in generating effective test cases. Specialized eBPF fuzzers were either outdated (a decade-old framework from Google), found minimal bugs, or were only recently published academically. This relative lack of dedicated fuzzing effort suggested a fertile ground for discovering new vulnerabilities. Lastly, the nature of eBPF verifier bugs – logic flaws in program analysis – presented an intellectually stimulating challenge beyond typical memory corruption issues.

Key Findings

▶ Watch: Generating eBPF programs: from random bytes to valid instructions. (11:55)

The primary finding of Zac Ecob's research is the successful development and application of FEEP (Freaking Fabulous Extended Berkeley Packet Filter Fuzzer), a specialized fuzzer capable of generating semantically and syntactically valid eBPF programs to stress-test the kernel's eBPF verifier. Through FEEP, Zac identified a total of five distinct bugs within the eBPF subsystem. These included two issues related to type casting, two control flow issues (one leading to an infinite loop, another allowing an "escape"), and one bug concerning division instructions.

Out of these five bugs, Zac assessed that between two and four were potentially exploitable, depending on the level of optimism in crafting an exploit. He specifically detailed two of the most interesting bugs, one of which has already been patched in the Linux kernel:

  1. Signed 8-bit Casting Mishandling (Patched): This bug involved the verifier's value tracking mechanism, specifically when casting a u8 (unsigned 8-bit) value to an s8 (signed 8-bit) value. The verifier maintains estimations of register values, including minimum and maximum bounds. In this case, if an unknown u8 value X was cast to s8, the verifier incorrectly assumed its maximum possible value was 0x7F. However, a valid u8 could hold values up to 0xFF, meaning an s8 could also represent negative values like 0x80 through 0xFF. This misassumption about the maximum value allowed an attacker to craft out-of-bounds accesses. Zac noted that this bug was likely born from C duplication, where similar logic was copied across different functions (coerce_subreg_to_size_sX vs coerce_reg_to_size_sX), leading to an inconsistency where the ALU_MOV instruction path was buggy, but ALU64_MOV was not. This highlights a common source of bugs in large C codebases.
  1. Signed/Unsigned Casting for Register Value Tracking (Unpatched/Anonymized): The second bug discussed involved another subtle issue with signed and unsigned casting in register value tracking. While anonymized due to its unpatched status, Zac described it as a scenario where a s64 value was implicitly cast to a u32 before being assigned to a u64 variable. The problem arose because the implicit u32 cast would zero out the top 32 bits, and this zero-extension would then propagate to the u64. If the original s64 value had any bits set in its top 32 bits, this implicit casting would lead to a disparity, where the verifier's assumption about the u64 value would be incorrect. This bug, though "barely not exploitable" in Zac's initial attempts, still exhibited the critical trait of invalid assumptions on register values, which is key to crafting exploits. Zac found this particular bug fascinating as it wasn't immediately obvious, even in retrospect, highlighting the deep logical flaws FEEP was designed to uncover.

These findings underscore the effectiveness of specialized fuzzing in uncovering complex logic bugs in critical kernel components like the eBPF verifier, demonstrating that despite its robust design, subtle flaws can still exist due to the sheer complexity of its static analysis.

Technical Deep Dive

▶ Watch: Key fuzzer design lessons: automation and strong type systems. (32:00)

The core challenge in fuzzing the eBPF subsystem lies in generating valid, yet novel, eBPF programs that can trigger obscure logic paths in the verifier. Zac Ecob's fuzzer, FEEP, addresses this through a multi-layered approach to input generation, progressively ensuring syntactic, semantic, and control flow validity.

eBPF Program Structure and Instruction Format

An eBPF program is fundamentally an array of eBPF instructions. Each instruction is a fixed 8 bytes in length, forming a minimal RISC instruction set. This simplicity is intentional, designed to make the verifier's job easier by avoiding the complexities of variable-length or highly specialized instructions (e.g., vector operations). When a user submits an eBPF program via the bpf_call system call, it first passes through the verifier. If approved, it is then processed by either a JIT compiler or an emulator, depending on kernel configuration.

The 8-byte instruction format consists of several fields: an opcode, a destination register (dst_reg), a source register (src_reg), an offset, and an immediate value. The opcode field defines the instruction's operation, falling into eight main classes, broadly categorized into memory operations (loads/stores), ALU (arithmetic logic unit) operations, and control flow operations (branches/jumps).

Generating Syntactically Valid Instructions

FEEP's initial approach to input generation, akin to cat /dev/urandom, quickly revealed that random byte sequences rarely produced valid eBPF instructions. The verifier would reject these with "invalid opcodes" or other syntactic errors. This led to FEEP's first refinement: enforcing syntactic validity.

  1. Opcode Representation: The opcode field is an u8, but not all u8 values correspond to valid eBPF opcodes (e.g., 0xF2 is invalid). To address this, FEEP, written in Rust, models the opcode using an enum. Each variant of the enum corresponds to a valid eBPF instruction class (e.g., Loads, ALU, Jumps). By generating a random enum variant, FEEP ensures that every opcode produced is inherently valid, making it "impossible to construct invalid opcodes" at the type level.
  1. Instruction Source Mode: Many eBPF instructions operate in one of two modes: using a source register or an immediate field, but never both simultaneously. If an instruction is in immediate mode, the src_reg field must be r0 (the zero register); if in register mode, the immediate field must be zero. FEEP enforces these constraints, preventing common verifier complaints about malformed instructions.
  1. Other Invariants: Numerous other syntactic invariants exist, such as requiring aligned memory accesses for load/store operations, or restricting bit shift amounts to a maximum of 63 on a 64-bit system. FEEP handles these by either incorporating them into the type system where possible or by using "safe constructors" that perform checks and generate valid instructions. The overarching principle here is to use the type system to represent the grammar of the fuzzed input, reducing the need for dynamic checks and increasing fuzzer efficiency.

Generating Semantically Valid Programs (Types and Variable State)

Even with syntactically valid instructions, randomly generated programs often don't make semantic sense (e.g., multiplying a pointer, loading from a scalar). To overcome this, FEEP introduces a notion of types for registers within the eBPF program. The type system is simple, consisting primarily of three states:

  • Pointer: Associated with a specific pointer type (e.g., stack pointer, packet pointer).
  • Scalar: Represents an integer value, with an associated width.
  • Uninitialized: The register's value is unknown.

This type system closely mirrors the verifier's own internal type tracking. FEEP uses this to ensure:

  • Load and Store Operations: Only operate on pointer types as memory locations.
  • ALU Operations: Primarily operate on scalar types (e.g., no dividing a pointer), with exceptions for pointer arithmetic (adding/subtracting an offset to a pointer).
  • Uninitialized Values: Instructions generally avoid using uninitialized registers.

Crucially, FEEP maintains a variable state for all registers. When generating an instruction, FEEP queries this state to select appropriate registers based on type requirements (e.g., "give me an initialized register of any type" for a move instruction). After an instruction is generated, it mutates the variable state to reflect its effects. For example, a move reg instruction copies the type and value state from its source to its destination register, while a load instruction initializes its destination register based on what was loaded. This dynamic tracking allows FEEP to generate programs that are not only syntactically correct but also semantically coherent enough to pass initial verifier checks.

Battling Control Flow Analysis

The most complex aspect of program generation for eBPF is handling control flow. The verifier is extremely strict about program termination, reachability, and type consistency across jump targets.

  1. Instruction-Level Control Flow: Jumps use an offset field. FEEP must ensure jumps target valid instruction addresses within the program's bounds. Furthermore, jumps must be 8-byte aligned, as eBPF instructions are 8 bytes long (with one peculiar 16-byte exception that complicates matters).
  1. Program-Level Control Flow:
  • Termination: The program must always terminate. The eBPF verifier does not solve the halting problem; it's the submitter's responsibility to provide a program that can be proven to terminate.
  • Reachability: All instructions must be potentially reachable from the program's entry point. Dead code is flagged by the verifier, potentially because it could hide exploit payloads or indicate compiler issues.
  • Type Consistency: Jumps must not break assumptions about variable types. For example, if a block expects R1 to be a pointer, a preceding block cannot jump to it after having assigned a scalar value to R1.

To manage this, FEEP shifts its internal representation from a simple array of instructions to a graph of basic blocks.

  • A basic block is a sequence of instructions where only the last instruction can be a branch. This simplifies control flow analysis because if the first instruction of a block executes, all instructions within that block will execute sequentially.
  • Directed edges connect basic blocks, representing jump instructions. Conditional jumps introduce two edges: one for the true condition (jumping) and one for the false condition (continuing to the next block implicitly).

FEEP ensures two strong guarantees for its control flow graph:

  • Reachability from Origin: Every node (basic block) must be reachable from the program's starting node (instruction zero).
  • Reachability to Exit: Every node must be able to reach an exit node, ensuring termination.

FEEP iteratively adds nodes, ensuring connectivity. If, during generation, an "unconnected" basic block is identified, FEEP will force a jump to it, linearly connecting it to the current path and then to an exit.

  1. Block Prerequisites: To maintain type consistency across jumps, each basic block is assigned a "prerequisite variable state." This defines the expected types of registers at the block's entry point (e.g., "R8 must be a pointer, R2 must be initialized"). When FEEP decides where to jump, it only considers basic blocks whose prerequisites can be satisfied by the current variable state. The exit block, by definition, has no prerequisites, allowing any path to terminate.
  1. Infinite Loops (The Untackled Problem): Zac explicitly chose not to tackle the problem of generating non-terminating (infinite loop) programs. Precisely tracking register values to prove termination is incredibly complex, essentially requiring FEEP to reimplement a significant portion of the eBPF verifier's logic. This would introduce immense complexity, potential bugs in the fuzzer itself, and risk over-sanitizing inputs, potentially missing subtle bugs. The eBPF verifier already rejects programs it cannot confidently prove will terminate, so FEEP relies on the verifier to catch these.

Future Improvements

Zac outlined several areas for future improvement:

  • Explicitly pairing load and store operations: Currently, FEEP might store data that is never loaded, effectively creating no-op instructions.
  • Fuzzing eBPF helper functions: These are kernel functions callable from eBPF programs and represent another significant attack surface, but require a more advanced type system.
  • Detecting info leaks using eBPF maps: Registering maps and storing register values at program end, then disabling KASLR (Kernel Address Space Layout Randomization) to check if any scalar values are kernel pointers.

Demo / Proof of Concept

▶ Watch: Bug example: Verifier misestimates register values from signed casts. (42:40)

While the talk did not feature a live demo or a detailed proof-of-concept walkthrough, Zac Ecob explained how the identified vulnerabilities could be exploited. He emphasized that the "misassumptions about values" identified in the type casting bugs are precisely the kind of flaws an attacker seeks. By crafting an eBPF program that leverages the verifier's incorrect belief about a register's maximum or minimum value, an attacker can induce out-of-bounds memory accesses. These out-of-bounds accesses are the critical primitives needed to escalate privileges, potentially leading to arbitrary kernel memory read/write and ultimately kernel code execution. The "escape" control flow bug similarly implies a way to bypass intended execution boundaries. The absence of a live exploit demonstration is typical for security conference talks discussing newly discovered, unpatched (or recently patched) kernel vulnerabilities, where full exploit details are often withheld to allow time for widespread patching.

Defensive Implications

▶ Watch: Q&A: Considering an intermediate language for easier eBPF modeling. (50:10)

The work presented by Zac Ecob offers several critical defensive implications for both kernel developers and system administrators using eBPF.

For kernel developers, the findings underscore the importance of meticulous code review, especially in highly complex and security-critical components like the eBPF verifier. The bug stemming from C duplication highlights a recurring vulnerability pattern: when similar logic is copied and pasted, subtle inconsistencies can arise if one instance is updated or reasoned about differently than another. The strong recommendation is to leverage abstraction and generics where possible, forcing logic to be reasoned about at a higher level and reducing the chance of such copy-paste errors. Furthermore, the intricacies of type casting, particularly between signed and unsigned integers of varying widths, remain a fertile ground for bugs. Developers should pay extra attention to these conversions within the verifier's value tracking logic. Zac's work also implicitly advocates for continued investment in automated security testing, such as fuzzing, for eBPF, acknowledging that manual review alone is insufficient for such a complex attack surface.

For system administrators and users deploying or interacting with eBPF, the talk reinforces the understanding that eBPF, while powerful, is a potential privilege escalation vector.

  1. Restrict Capabilities: Never enable unprivileged eBPF (sysctl kernel.unprivileged_bpf_disabled=0) unless absolutely necessary and with a full understanding of the extreme risks involved. Instead, strictly adhere to the principle of least privilege, only granting specific eBPF-related capabilities (e.g., CAP_BPF, CAP_NET_ADMIN, CAP_PERFMON) to trusted applications or users that genuinely require them.
  2. Keep Kernels Updated: eBPF verifier bugs, once discovered, are critical. Promptly applying kernel security patches is paramount to mitigate known vulnerabilities.
  3. Understand Security Model: Maintain a clear understanding of how eBPF interacts with other security mechanisms like SELinux or AppArmor. While Zac admitted uncertainty about SELinux's current guarantees with eBPF, it's crucial to evaluate if these mechanisms provide effective additional layers of defense against potential eBPF exploits.
  4. Monitor eBPF Usage: Implement monitoring for unusual or unauthorized eBPF program loads or activity, which could indicate an attempted exploit or compromise.

In essence, while eBPF offers incredible functionality, its power necessitates an equally robust security posture, requiring vigilance from both those who develop and those who deploy kernel-level code.

Key Takeaways

  • eBPF Verifier Complexity is an Attack Surface: The eBPF verifier, while essential for security, is highly complex and thus prone to subtle logic bugs that can lead to kernel code execution.
  • Specialized Fuzzing is Critical: Generic kernel fuzzers like Syzkaller struggle with eBPF's unique program-based inputs and complex type system. Specialized fuzzers like FEEP are necessary to generate effective test cases.
  • Type Systems Enhance Fuzzing: Leveraging strong type systems (e.g., Rust enums for opcodes) allows fuzzers to statically enforce grammar rules, preventing the generation of syntactically invalid inputs and improving efficiency.
  • Semantic and Control Flow Validity are Key: Beyond syntax, fuzzers must reason about program semantics (register types, variable state) and control flow (basic blocks, reachability, termination) to generate programs complex enough to trigger deep verifier logic.
  • Differentiate Fuzzer from Target Failures: It's crucial for fuzzer development to clearly distinguish between crashes in the fuzzer's own environment (e.g., QEMU exiting due to init dying) and genuine bugs in the target kernel.
  • Don't Fear Target Modification: Modifying the fuzzed target (e.g., reducing the eBPF verifier's instruction limit from 1 million to 10,000) can significantly improve fuzzing speed and efficiency without compromising bug detection.
  • Beware C Duplication: Copy-pasting code in C, particularly for complex logic like value tracking or type casting, can lead to subtle inconsistencies and exploitable bugs if not meticulously maintained and reviewed.

About the Speaker(s)

Zac Ecob is a final-year Computer Science student at the University of New South Wales (UNSW), set to graduate soon. He is an active member of UNSW's cyber security society, SecSoc, and participates in Capture The Flag (CTF) competitions with the team Emu Exploit. Zac is a familiar face at Australian security conferences, where he is known for sharing his research and insights. This talk marks his return as a speaker to BSides Canberra, building on his previous contributions to the conference.

Reviews

  • Dr. Zero (Offensive Security Researcher) — MUST SEE ★★★★★

→ Top-rated talks at BSides Canberra VII (2024)

All talks from BSides Canberra VII (2024)