Skip to content
blah-blah-cellPublic

About

Rust and eBPF (XDP/TC) flow-monitoring and quarantine firewall prototype

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

9 Commits

Folders and files

Repository files navigation

Protector (zqfw)

Protector is a Rust and eBPF (XDP/TC) flow-monitoring and quarantine firewall prototype.

Overview

zqfw pairs an eBPF data plane (XDP ingress and TC ingress/egress) with a Rust userspace daemon. Kernel probes track per-flow counters on the packet path and push new-flow events over a ring buffer. On each reap interval, the daemon merges kernel flow counters, scores active sessions against nine weighted heuristic signals, and writes TTL-bounded entries into the kernel blocklist or blocklist_ip maps when a session crosses the risk threshold. Quarantines expire once the TTL passes and evidence clears.

Live verification on Linux 6.19 in a self-owned lab VM is logged in RESULTS.md: a port scan was detected and quarantined within one reap interval with 0.9-21 us map-write enforcement latency, and kernel drop counters matched block_hits 1:1.

Table of contents

Capabilities

  • Kernel data plane (XDP + TC): tracks per-flow counters, runs basic L7 header classification, and enforces blocklists without a userspace round-trip per packet.
  • Heuristic flow triage: scores sessions with nine weighted signals (port_scan, syn_flood, dns_tunnel, data_exfil, lateral_movement, unidirectional_udp, rst_flood, slow_drip, first_contact) and records each signal's contribution in the audit log.
  • TTL-bounded quarantine: expires blocks after --quarantine elapses and deduplicates repeated IP quarantines per window.
  • Monitor-first workflow: start with --monitor, inspect the JSONL audit log, and toggle enforcement live via SIGUSR1 without reloading BPF programs.
  • Rootless mock mode: --mock runs the supervisor and triage pipeline against synthetic traffic with no sudo or kernel BPF access.
  • Operations and integrations: exposes Prometheus metrics, writes JSONL audit logs, supports an optional OpenAI-compatible HTTP LLM second-opinion hook (--features llm), includes a hardened systemd unit, and supports CIDR allowlisting and BPF map pinning.

How it works

                        userspace                          kernel
┌───────────────────────────────────────────┐  ┌───────────────────────┐
│  zqfw (Rust daemon)                       │  │  firewall.bpf.c       │
│                                           │  │                       │
│  supervisor -- every --reap-interval -----┼->│  XDP (ingress)        │
│    · merge flow metrics from flows map    │  │  TC (in/egress)       │
│    · rebuild triage context (5m window)   │  │   · parse L2-L4       │
│    · score sessions: risk = Σ(w·c) / Σ(w) │  │   · L7 classification │
│    · write blocklist / blocklist_ip       │<-┼-- blocklist lookups   │
│    · expire quarantines back to allow     │  │   · drop / pass       │
│                                           │  │   · ring-buffer event │
│  audit: JSONL, rationale + latency        │  │                       │
│  metrics: Prometheus on --metrics-addr    │  │  maps: flows,         │
│  optional LLM review (--features llm)     │  │  blocklist,           │
└───────────────────────────────────────────┘  │  blocklist_ip, ctl,   │
                                               │  counters, allowlist  │
                                               └───────────────────────┘

Signals and weights (defined in src/triage/signals.rs):

signal weight fires on
port_scan 0.90 >=10 distinct dst ports to one dst, or >=20 distinct dst IPs from one src
syn_flood 0.95 >=8 SYNs with no ACK seen, or >40 SYNs/sec
dns_tunnel 0.85 DNS flows with long query names (>40 bytes and >50 packets, or >30 bytes and >10 pps)
data_exfil 0.90 >250 KB/s over TLS or to a non-ephemeral port >=1000 (excluding 443)
lateral_movement 0.85 internal-to-internal TCP flow to a sensitive service port with >5 SYNs and no ACK
unidirectional_udp 0.60 UDP flow >200 pps and >100 KB
rst_flood 0.60 TCP flow with >35% RST ratio and >10 RSTs
slow_drip 0.40 UDP flow with >500 packets lasting >5 s
first_contact 0.30 public source IP seen for the first time in the window

Risk is computed as Σ(contribution · weight) / Σ(weight of fired signals). Triage returns Allow (sessions at or above 0.7 * threshold are marked Suspicious), Quarantine (5-tuple block), or QuarantineIp (blocks the whole source IP when --block-ip is set and a systemic signal fires across at least 3 flows from that source).

Requirements

  • Linux 5.8+ (BTF recommended) with a NIC supporting XDP.
  • Root (or CAP_BPF + CAP_NET_ADMIN) to load BPF programs in real mode. Mock mode needs neither.
  • clang/LLVM to compile the C probes, a Rust toolchain, libelf, and optionally linux-headers-$(uname -r).
  • For BPF map pinning: bpftool and a mounted BPF filesystem (mount -t bpf bpf /sys/fs/bpf).

Install

Install script (Debian/Ubuntu, Fedora/RHEL, Arch, Alpine)

git clone https://github.com/blah-blah-cell/protector.git
cd protector
./scripts/install.sh            # installs deps, builds, installs to /usr/local/bin
zqfw --version                  # verify

The script invokes sudo for package installation and copying the binary to /usr/local/bin.

Manual build

# 1. Toolchain
rustup 2>/dev/null || curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
sudo apt install -y clang llvm libelf-dev linux-tools-common   # Debian/Ubuntu
sudo dnf install -y clang llvm elfutils-libelf-devel            # Fedora
sudo pacman -Sy --noconfirm base-devel clang llvm elfutils      # Arch

# 2. Build
cargo build --release                       # default: heuristic triage
cargo build --release --features llm        # + optional HTTP LLM review backend

# 3. Install
sudo install -m 0755 target/release/zqfw /usr/local/bin/zqfw

Run as a service (systemd)

sudo install -m 0644 packaging/zqfw.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now zqfw    # attaches to the default-route NIC, monitor-first
sudo journalctl -fu zqfw

Usage

Rootless demo (no BPF, no root)

zqfw --mock --block-ip --audit audit.jsonl

This replays five synthetic attack scenarios (port scan, SYN flood, DNS tunneling, data exfiltration, lateral movement) alongside benign traffic and logs each quarantine decision with its signals, risk score, and latency.

Real mode (attach to live traffic)

sudo zqfw --iface eth0 --block-ip --monitor --reap-interval 2s --quarantine 30s
  • --iface defaults to auto, which resolves the IPv4 default-route interface from /proc/net/route. Override it with --iface ens33 or ZQFW_IFACE=ens33.
  • --monitor logs decisions without dropping traffic. Toggle enforcement or dump sessions at runtime:
    sudo kill -USR1 "$(pgrep zqfw)"   # toggle monitor <-> enforce
    sudo kill -USR2 "$(pgrep zqfw)"   # dump the live session table

Advanced features

Allowlist trusted sources

Exempt trusted CIDRs (management subnets, DNS servers, etc.) in the kernel allowlist map before enforcement runs:

sudo zqfw --iface auto --block-ip --allowlist 10.0.0.0/8,192.168.1.0/24

Accepts CIDR notation and single-host prefixes (/32, /128). Prefixes larger than 65,536 addresses are skipped with a warning (note that the kernel allowlist hash map currently holds up to 4,096 individual host entries).

BPF map pinning

Pin BPF maps under a bpffs directory:

sudo mount -t bpf bpf /sys/fs/bpf   # once at boot
sudo zqfw --pin-dir /sys/fs/bpf/zqfw ...

This pins flows, blocklist, blocklist_ip, allowlist, ctl, and counters under the given directory.

Shutdown behavior

On SIGTERM, the supervisor stops its event loop without explicitly clearing active quarantine map entries.

Systemd hardening

packaging/zqfw.service configures:

  • Type=notify with WatchdogSec=30 (WATCHDOG=1 heartbeat over NOTIFY_SOCKET).
  • Restart=always with StartLimitBurst=3.
  • Scoped capabilities (CAP_BPF, CAP_SYS_ADMIN, CAP_NET_ADMIN, CAP_NET_RAW, CAP_DAC_OVERRIDE).
  • Filesystem isolation (ProtectSystem=strict, ProtectHome=true, PrivateTmp=true) and syscall filtering (@system-service @clock @network @bpf @resources @file-system).
  • Resource limits (LimitNOFILE=65536, LimitMEMLOCK=infinity, MemoryMax=512M).
  • Optional environment file at /etc/default/zqfw (see packaging/zqfw.env for supported variables such as ZQFW_IFACE, RUST_LOG, and ZQFW_LLM_*).

Tuning reference

flag default meaning
--threshold 0.8 risk score needed to quarantine (0-1)
--quarantine 5m how long a blocked IP/flow stays blocked (e.g. 30s, 5m)
--reap-interval 5s supervisor re-evaluation period
--flow-ttl 60s idle flow expiry
--monitor off observe and audit only; never drop
--block-ip off whole-IP quarantine on systemic behavior (e.g. port scan)
--allowlist none comma-separated CIDRs exempt from quarantine
--pin-dir none directory for pinned BPF maps
--metrics-addr 127.0.0.1:9790 Prometheus text endpoint
--audit - JSONL audit path (- for stdout)
--hit-events off emit block-hit events into the ring buffer
--xdp-mode default default | skb | driver

Metrics and observability

  • Audit log (--audit audit.jsonl): writes one JSON object per event with risk score, fired signals, weights, enforcement latency, and target kernel map.
  • Prometheus endpoint (curl localhost:9790/metrics): exposes zqfw_packets_passed_total, zqfw_packets_dropped_total, zqfw_block_hits_total, zqfw_new_flows_total, zqfw_malformed_total, zqfw_events_lost_total, zqfw_sessions, zqfw_quarantined_flows, zqfw_quarantined_ips, zqfw_decisions_total, and zqfw_enforce.
  • Signals: SIGUSR1 toggles monitor/enforce; SIGUSR2 dumps the live session table.

Testing

cargo test          # unit + regression tests: byte-order, triage, BPF object parse, mock e2e

Live lab verification and the seven bugs found and fixed during real-mode testing are logged in RESULTS.md.

FAQ

Does it drop packets in the kernel? Yes. When enforce mode is active, the XDP and TC probes drop packets matching blocklist or blocklist_ip and increment the in-kernel drop and block_hits counters.

Will it block my own traffic? On a live host, any unseen public source IP (such as reply traffic from a remote endpoint) fires first_contact with a contribution of 0.8. When no other signal fires, the normalized risk is 0.8, which meets the default threshold. Start with --monitor, review the audit log, and add trusted CIDRs via --allowlist before enabling enforcement.

Why does real mode need root? Loading eBPF programs requires CAP_BPF, CAP_SYS_ADMIN, and CAP_NET_ADMIN. --mock runs unprivileged.

Disclaimer

This prototype drops real network traffic when enforce mode is enabled and can break host connectivity if misconfigured. Run in --monitor mode first and test only on hosts and networks you own.

License

MIT

About

Rust and eBPF (XDP/TC) flow-monitoring and quarantine firewall prototype

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages