How willfindlay/bpfcontain-rs works
Project Type & Purpose
• BPFContain is a Linux container-security daemon written in Rust that leverages eBPF.
• It compiles and loads BPF programs into the kernel to enforce user-defined policies (YAML) on running processes/containers.
File Structure & Key Indicators
• src/cli.rs, src/main.rs, src/subcommands/... → CLI binary with subcommands (“daemon,” “run,” “confine”).
• src/bpf/*.c + src/bpf_program.rs + build.rs → BPF programs in C + Rust loader + build script generating vmlinux.h/BTF.
• src/policy → Policy language parser & rule engine.
• config/*.yml, examples/*.yml → Policy/configuration files.
• tests/…, examples/, scripts/ → CI, integration tests, example policies.
• DOCKER.md, Vagrantfile → Deployment/quick-start helpers.
Readme Insights
• Daemon runs in user–space to load/attach BPF to kernel.
• Policies in YAML drive enforcement logic.
• Dependencies: clang/LLVM (to compile BPF), bpftool (generate BTF), Rust toolchain.
Main Architectural Components
a. User-Space CLI & Daemon
– bpfcontain binary with three modes:
• daemon: boots up, loads/attaches BPF programs, monitors state
• run: spawn confined process under current policy
• confine: helper to enter existing namespace under policy
b. Configuration & Policy Engine
– Reads YAML policy (examples/*.yml) via src/config.rs + src/policy/*.rs
c. Build & BPF Loader
– build.rs invokes clang/LLVM to compile C programs (src/bpf/*.c) into .o
– Generates vmlinux.h/BTF for kernel types
– src/bpf_program.rs + src/bindings/*.rs wrap low-level BPF syscall APIs
d. Kernel-Space BPF Programs
– eBPF probes (tracepoints, LSM hooks) that enforce I/O, networking, file operations
– BPF maps hold per-process state, policy tables
e. Kernel Interaction
– Attaches BPF programs via BPF syscall to designated LSM hooks/tracepoints
– On enforcement triggers, BPF may kill or log events
f. Logging & Audit
– src/log.rs collects audit events via perf ring buffer or tracepoints
– Writes logs/metrics to syslog or files (config/logrotate)
Relationships & Data Flows
• User invokes “bpfcontain daemon start” → CLI parses args → policy loader reads YAML → BPF loader compiles & loads eBPF → attaches to kernel.
• Running processes generate syscalls/events → kernel invokes eBPF programs → enforcement decision (allow/deny) → event logged in BPF map or perf buffer → user-space daemon reads buffer → writes to log.
• “bpfcontain run <policy>” forks process under configured seccomp or namespace (via src/ns.rs), then the daemon’s BPF policies apply.
Architectural Patterns & Design Principles
• Layered design: CLI/Config → Policy Engine → BPF Loader → Kernel
• Separation of concerns:
• Policy parsing & validation (Rust)
• BPF program compilation/attachment (build.rs + Rust bindings)
• Enforcement logic in kernel (C)
• Logging/Auditing in user-space (Rust)
• Safe systems language (Rust) used for user-space control; C only in minimal in-kernel surface area.