🌍 Networking

eBPF

extended Berkeley Packet Filter

A programmable sandbox inside the kernel. Networking, security.

📖 Detailed Explanation

eBPF (extended Berkeley Packet Filter) is an innovative technology that allows safely sandboxed programs to run inside the Linux kernel. Because it can extend the kernel's behavior without modifying the kernel source code or loading modules, it is regarded as a game changer in the fields of system observability, networking, and security.

Originally, BPF (Berkeley Packet Filter) was designed in 1992 for network packet filtering. In 2014, in Linux 3.18, it was substantially extended into "extended" BPF, making it capable of going beyond packet filtering to system-wide tracing, performance profiling, and enforcing security policies. Because an eBPF program runs only after passing the kernel's Verifier, there is no risk of a system crash.

eBPF's core strength is that it combines kernel-level performance with user-space flexibility. Traditionally, system performance monitoring or network filtering required developing kernel modules, but with eBPF, you can compile a program written in Python or C and load it dynamically into the kernel. Large companies such as Netflix, Meta, and Google actively use it in production.

Representative eBPF-based tools include Cilium for networking, bpftrace and Pixie for observability, and Falco and Tetragon for security. In Kubernetes environments, Cilium replaces kube-proxy and implements even service mesh functionality with eBPF alone, and it provides up to 10 times faster processing performance compared to the existing iptables.

💻 Code Example

# bpftrace - 고수준 eBPF 트레이싱 도구

# 시스템 콜 추적 - 어떤 프로세스가 어떤 syscall을 호출하는지
sudo bpftrace -e 'tracepoint:syscalls:sys_enter_* { @[comm, probe] = count(); }'

# 파일 열기 추적 - 어떤 파일이 열리는지 실시간 모니터링
sudo bpftrace -e 'tracepoint:syscalls:sys_enter_openat {
    printf("%s opened %s\n", comm, str(args->filename));
}'

# 함수 실행 시간 측정 - TCP 연결 지연 분석
sudo bpftrace -e '
kprobe:tcp_v4_connect { @start[tid] = nsecs; }
kretprobe:tcp_v4_connect /@start[tid]/ {
    @latency = hist((nsecs - @start[tid]) / 1000);
    delete(@start[tid]);
}'

# 프로세스 생성 추적 - 보안 모니터링
sudo bpftrace -e 'tracepoint:sched:sched_process_exec {
    printf("%s (pid=%d) executed by %s\n",
        str(args->filename), args->pid, comm);
}'

# CPU 사용량 높은 스택 프로파일링
sudo bpftrace -e 'profile:hz:99 { @[kstack] = count(); }'

# 디스크 I/O 지연 히스토그램
sudo bpftrace -e 'tracepoint:block:block_rq_complete {
    @bytes = hist(args->nr_sector * 512);
}'
#!/usr/bin/python3
# BCC (BPF Compiler Collection) - Python으로 eBPF 프로그래밍
# pip install bcc

from bcc import BPF
from time import sleep

# 1. TCP 연결 추적 프로그램
program = """
#include 
#include 

BPF_HASH(connections, u32, u64);

int trace_connect(struct pt_regs *ctx, struct sock *sk) {
    u32 pid = bpf_get_current_pid_tgid() >> 32;
    u64 ts = bpf_ktime_get_ns();
    connections.update(&pid, &ts);
    return 0;
}

int trace_connect_return(struct pt_regs *ctx) {
    u32 pid = bpf_get_current_pid_tgid() >> 32;
    u64 *start_ts = connections.lookup(&pid);
    if (start_ts) {
        u64 latency = bpf_ktime_get_ns() - *start_ts;
        bpf_trace_printk("PID %d: connect latency %d us\\n",
                         pid, latency / 1000);
        connections.delete(&pid);
    }
    return 0;
}
"""

b = BPF(text=program)
b.attach_kprobe(event="tcp_v4_connect", fn_name="trace_connect")
b.attach_kretprobe(event="tcp_v4_connect", fn_name="trace_connect_return")

print("Tracing TCP connects... Ctrl+C to exit")
b.trace_print()


# 2. 간단한 시스템콜 카운터
from bcc import BPF
from collections import Counter
import time

bpf_text = """
BPF_HASH(syscall_count, u64, u64);

TRACEPOINT_PROBE(raw_syscalls, sys_enter) {
    u64 key = args->id;
    u64 *val = syscall_count.lookup(&key);
    if (val) {
        (*val)++;
    } else {
        u64 one = 1;
        syscall_count.update(&key, &one);
    }
    return 0;
}
"""

b = BPF(text=bpf_text)
print("Counting syscalls for 10 seconds...")
time.sleep(10)

for k, v in b["syscall_count"].items():
    print(f"Syscall #{k.value}: {v.value} calls")
# eBPF 환경 확인 및 도구 사용법

# 커널 eBPF 지원 확인
cat /boot/config-$(uname -r) | grep BPF
# CONFIG_BPF=y, CONFIG_BPF_SYSCALL=y 확인

# bpftrace 설치 (Ubuntu/Debian)
sudo apt-get install bpftrace

# BCC 도구 모음 설치
sudo apt-get install bpfcc-tools linux-headers-$(uname -r)

# Cilium CLI 설치 (Kubernetes eBPF 네트워킹)
curl -L --remote-name-all https://github.com/cilium/cilium-cli/releases/latest/download/cilium-linux-amd64.tar.gz
sudo tar xzvfC cilium-linux-amd64.tar.gz /usr/local/bin

# 유용한 BCC 도구들
sudo /usr/share/bcc/tools/execsnoop      # 프로세스 실행 추적
sudo /usr/share/bcc/tools/opensnoop      # 파일 열기 추적
sudo /usr/share/bcc/tools/biolatency     # 디스크 I/O 지연
sudo /usr/share/bcc/tools/tcpconnect     # TCP 연결 추적
sudo /usr/share/bcc/tools/tcplife        # TCP 세션 수명
sudo /usr/share/bcc/tools/profile        # CPU 프로파일링
sudo /usr/share/bcc/tools/funclatency    # 함수 실행 시간

# bpftool - eBPF 프로그램 관리
sudo bpftool prog list          # 로드된 eBPF 프로그램 목록
sudo bpftool map list           # eBPF 맵 목록
sudo bpftool prog dump xlated id 123  # 프로그램 바이트코드 확인

# Cilium 상태 확인 (Kubernetes)
cilium status
cilium hubble observe --follow   # 네트워크 플로우 실시간 관찰

🗣️ Say It Like This in Practice

💬 In a Performance Analysis Meeting
"It's hard to find the cause of latency spikes in production, so how about trying kernel-level tracing with bpftrace? Without modifying application code, we can analyze TCP connection delays, system call bottlenecks, and disk I/O patterns in real time. I hear Netflix solved a problem this way too."
💬 In a Kubernetes Networking Discussion
"The iptables mode of kube-proxy is becoming a bottleneck as the number of services grows. If we switch to Cilium, it is eBPF-based, so it maintains O(1) performance regardless of the number of rules, and we can also gain visibility into service-to-service traffic with Hubble. There is a case where Pod-to-Pod communication latency improved by 40% after the switch."
💬 In a Security Team Meeting
"Let's consider adopting Falco or Tetragon to strengthen runtime security. Because they are eBPF-based, they can monitor all container behavior in real time at the system call level. They can detect and block file access, network connections, and privilege escalation attempts directly in the kernel, so the overhead is much lower than with existing agent-based approaches."

⚠️ Common Mistakes & Cautions

❌
Ignoring Kernel Version Compatibility

eBPF features vary greatly depending on the kernel version. Linux 4.x supports only basic features, and newer features such as BTF (BPF Type Format) and CO-RE (Compile Once Run Everywhere) require 5.x or later. Be sure to check the kernel version before applying it in production.

❌
Neglecting Verifier Errors

If an eBPF program fails verification, cryptic errors such as "invalid access to map value" occur. You need to understand the verifier's rules, such as loop count limits, stack size limits, and memory access range validation.

❌
Excessive Tracing in Production

If you use bpftrace or BCC tools indiscriminately on high-traffic production servers, CPU overhead occurs. Trace only the events that are truly necessary, and reduce the amount of data by applying filter conditions.

✅
The Right Way to Adopt eBPF

Write kernel-version-independent programs using libbpf and CO-RE. Test thoroughly in a development environment before applying to production. Start with proven tools such as Cilium and Falco, and gradually expand to developing custom programs.

🔗 Related Terms

📚 Learn More