Black router with four colored Ethernet cables on a wooden table beside a sleeping cat
eBPF in OpenWRT
William  

eBPF on OpenWrt: Kernel Checks, XDP and TC

eBPF on OpenWrt is viable for targeted packet processing, especially early XDP or TC filtering, but it is not a turnkey replacement for netfilter, deep packet inspection, or serious DDoS protection. Start by checking the running kernel, driver, verifier, and toolchain. Then trace the attach and packet path before you deploy anything. A copied XDP example that loads on a server can fail on an embedded router for reasons the example never mentions.

Last updated: 2026-11-03

What eBPF on OpenWrt is good for

Use eBPF on OpenWrt when you need a small, fast decision close to the packet path. Good examples include:

  • Dropping packets from a blocklist.
  • Counting traffic by interface, address, protocol, or port.
  • Redirecting selected packets.
  • Applying simple rate limits.
  • Sending selected traffic to userspace through an AF_XDP socket.
  • Adding observability without changing the full firewall ruleset.

That is the useful part. A small eBPF program can inspect packet metadata and selected headers before the normal network stack does more work. An XDP program can return XDP_DROP for a packet it rejects or XDP_PASS for a packet that should continue through the stack.

The program still needs maps, counters, update logic, attachment code, and a recovery path. A return value alone is not a firewall policy. If you cannot tell which rule dropped a packet, you have built a black box with a fast failure mode.

OpenWrt makes this more difficult because router firmware has limited storage, limited memory, unusual network drivers, and frequent interface changes. A program that assumes fixed interface names or a permanent Ethernet device will eventually attach to the wrong place. Linux has many ways to punish assumptions. Network configuration is one of them.

I use netfilter and nftables for stateful policy, NAT, connection tracking, and rules that need context. I use eBPF when the decision is narrow enough to explain in one sentence. That split keeps the fast path small and leaves complicated policy where the kernel already has the machinery.

OpenWrt eBPF support starts with the kernel and toolchain

Check the running target before you write C. The package feed, SDK, and host compiler do not prove that the target kernel can load your program.

Start with the kernel version and configuration:

uname -a
zcat /proc/config.gz 2>/dev/null | grep -E 'CONFIG_(BPF|XDP|DEBUG_INFO_BTF)'

Some builds expose the configuration through /proc/config.gz. Others keep it in the build tree or omit it from the firmware. If the command produces nothing, that is missing evidence, not proof that support exists.

The Linux package supports eBPF through configuration options such as CONFIG_BPF, CONFIG_BPF_SYSCALL, and CONFIG_BPF_JIT. For XDP socket testing, CONFIG_XDP_SOCKETS=y matters. BTF support also matters for modern CO-RE programs and tools that need type information. The relevant OpenWrt settings include CONFIG_DEBUG_INFO_BTF=y, CONFIG_PACKAGE_bpftool-full, and CONFIG_BPF_TOOLCHAIN_BUILD_LLVM=y.

Check the tools on the actual router:

command -v bpftool
command -v clang
command -v llc
bpftool feature probe

bpftool feature probe reports what the running kernel exposes. Read the output instead of treating the command's existence as success. A router can contain bpftool while lacking a helper, map type, program type, or kernel feature your program needs.

The OpenWrt bpf-headers package exists because ordinary host headers are a poor fit for cross-compiling BPF code. It prepares a 5.10 kernel tree with a default MIPS configuration to generate suitable kernel headers. The architecture is forced to MIPS to avoid inline assembly problems across host toolchains and headers. It also supports both endian types.

That package does not turn an old target kernel into a new one. Headers help the compiler understand types. The running kernel still decides whether the program loads.

The compiler matters too. clang compiles eBPF source into BPF bytecode, while libbpf provides the loader and skeleton support used by many modern applications. On a small router, compiling on the target is often the wrong choice. Build on a workstation or OpenWrt build host, then copy the matching object and loader to the router.

If you are on Arch Linux, check the host compiler and target headers separately. The Arch host can produce an object that the OpenWrt kernel rejects. argp.h is another common host-build failure because it belongs to the GNU argument parsing interface and may not exist in a small target libc. Do not fix that by copying random headers into the firmware. Either build against the correct SDK or remove the dependency from the loader.

BCC is also a poor first choice on an embedded ARM router. It brings a large userspace and compiler dependency chain. For a small OpenWrt target, use a prebuilt BPF object with libbpf, or start with bpftool and a minimal loader. The LLVM documentation explains the compiler side; it does not guarantee that your target kernel accepts the result.

A project that requires Linux kernel 5.15 with BPF and BTF support on the target is not automatically portable to every OpenWrt image. The same project has only been tested on x86-64 or aarch64. Treat those requirements as a boundary. MIPS support may need different headers, different helper availability, and more careful handling of endianness.

XDP and TC provide different packet-processing trade-offs

XDP runs earlier than TC. That is its advantage and its limitation.

An XDP program receives a packet through the driver path before the kernel builds the normal socket buffer. It can pass, drop, transmit, abort, or redirect the packet. The program sees raw packet data and must prove every access is inside the packet.

TC uses the Linux traffic-control path. TC ingress runs after the packet has entered the network stack far enough to have a socket buffer. TC egress runs as the kernel sends a packet out. That placement gives TC more context and makes it useful for shaping, classification, and egress policy. It also means TC does not offer the same early-drop point as native XDP.

HookBest useMain cost
XDP ingressEarly drop, simple parsing, redirectLittle context, driver dependence
TC ingressIngress classification and policyPacket already has an sk_buff
TC egressOutbound filtering and shapingToo late for the cheapest ingress drops
UserspaceDeep parsing and flexible policyCopies, scheduling, memory, and failure handling

XDP has native, generic, and offloaded modes. Native mode runs through driver support. Generic mode runs later in the stack and keeps compatibility at the cost of much of XDP's speed advantage. Offload mode depends on hardware that can execute the program.

On upstream kernels, the mlx4, mlx5, and i40 drivers support XDP. That does not tell you what your OpenWrt router supports. Check the target driver:

ethtool -i eth0
ip -details link show dev eth0

Then inspect the attachment state. If you expected native XDP and the interface reports generic mode, stop benchmarking. You are measuring a different packet path.

I keep TC in the design when the rule needs metadata that XDP does not have or when the driver does not support native XDP. A slower hook that works and can be maintained beats a fast hook that only works on the lab interface.

Building an XDP firewall on OpenWrt

Start with a drop decision that is narrow enough to test. Do not begin with a full firewall, NAT, rate limiter, logging system, and configuration daemon in one program. That gives the verifier several problems to report and gives you no clean failure boundary.

A minimal XDP program usually does four things:

  1. Reads the packet and packet end pointers.
  2. Checks bounds before every header access.
  3. Looks up a rule or counter in a map.
  4. Returns a verdict.

The verdict is the important part. XDP_PASS sends the packet onward. XDP_DROP rejects it at the XDP hook. The program in the common XDP example returns XDP_PASS; changing that return to XDP_DROP changes the result from observation to rejection. Test that behavior with a rule that cannot lock you out.

The program needs a map for rules and a separate map for counters. Keep policy updates in userspace. The loader can replace an address, port, or protocol rule without recompiling the BPF object.

A safe deployment sequence looks like this:

bpftool prog show
bpftool map show
ip -details link show dev eth0
tcpdump -ni eth0

First confirm the interface. Then attach the program with the loader you built for the target. After attachment, generate one known packet and inspect the program and map counters. Do not trust a successful attach message by itself.

Use an out-of-band path before attaching to a router's management interface. A bad drop rule can remove the only route to the device. If the program fails to load, fall back to the normal netfilter path. If the service restarts, detach the old program before loading the new one. Stale attachments are a common reason a new source change appears to have no effect.

Your control plane also needs to handle:

  • Map creation and pinning.
  • Rule replacement.
  • Counter reads.
  • Program replacement.
  • Interface removal.
  • Service restart.
  • Failure during boot.
  • A safe default of XDP_PASS.

The fallback matters because OpenWrt interfaces are not static. WAN devices can be recreated after a link event, VLAN changes can produce a new interface path, and bridge membership can move the packet away from the device you chose during testing.

An XDP firewall only sees what arrives at its attachment point. It cannot inspect a packet that another path handles first. It also cannot perform full connection tracking by itself. For a deeper worked example, the guide on blocking IP addresses with eBPF covers the basic attach and blocklist pattern.

OpenWrt DDoS protection needs more than an eBPF hook

Wireless router beside a network switch filled with colorful Ethernet cables on a wooden desk

XDP can reduce local CPU work from simple floods. It cannot make an undersized internet connection receive less traffic.

A local XDP program can drop packets based on source addresses, destination ports, protocol fields, flags, or a small rate state. It can help with traffic that reaches the router and can be identified cheaply. It may also reduce the amount of work sent to conntrack.

That does not stop a volumetric attack upstream. The link remains full before the packet reaches your OpenWrt box. No local hook can recover bandwidth that the access provider has already consumed.

State exhaustion is a different problem. A flood of connection attempts can pressure conntrack, listen queues, memory, and CPU. Early filtering can help if the traffic has a reliable signature. However, rebuilding state tracking in eBPF is a poor substitute for the kernel's conntrack system. Tune conntrack and firewall policy when the attack requires connection state.

Application-layer attacks need application context. HTTP requests, TLS sessions, authentication attempts, and protocol abuse are not visible as complete transactions at XDP. Packet headers do not tell you what a user sent inside an encrypted stream.

For a small OpenWrt router, I use this order:

  1. Filter obvious unwanted traffic at XDP or TC.
  2. Keep nftables for stateful policy and NAT.
  3. Tune conntrack when state exhaustion is the problem.
  4. Move volumetric filtering upstream when the access link is the bottleneck.
  5. Use a dedicated firewall or userspace service when the rule needs full protocol context.

The XDP SYN flood guide is useful for the narrow packet-pattern case. It does not turn local filtering into upstream DDoS scrubbing.

OpenWrt deep packet inspection is usually the wrong eBPF job

XDP is good at reading a few bytes and making a fast decision. Deep packet inspection needs much more.

A real inspection system may need stream reassembly, fragmented packet handling, protocol parsing, encryption context, application state, and userspace reporting. XDP has none of that by default. It sees individual packets and gives you a small execution budget enforced by the verifier.

You can parse Ethernet, IP, TCP, UDP, and selected fields. You can identify a narrow signature when the bytes are present in the current packet. You cannot assume the application message is in one packet or that the bytes are visible at all.

TC gives you a little more context, but it does not solve stream reassembly. Userspace is the right place for inspection that needs protocol state. Keep the eBPF program as a filter or sampler that sends selected traffic to userspace.

The common mistake is calling any packet parser DPI. Parsing a destination port is metadata filtering. Searching a complete protocol stream is deep inspection. Those jobs have different memory, CPU, and failure requirements.

Endpoint-independent NAT with eBPF

Endpoint-independent NAT is possible in an eBPF-based design, but the word possible is doing a lot of work.

IPv4-to-IPv4 network address and port translation needs a bidirectional state table. The outbound flow maps an internal address and port to an external address and reserved port. The return path maps that external tuple back to the internal endpoint.

IPv6-to-IPv6 NAPT needs the same kind of state management, even though IPv6 normally avoids address translation. Full-cone TCP and UDP behavior also requires a policy decision about which outside endpoints may send traffic to the reserved external port. ICMP endpoint independence needs its own identifier and translation rules because ICMP does not use TCP or UDP ports.

That is already a conntrack problem. You need timeout handling, collision handling, checksum updates, fragment behavior, and safe state deletion. You also need to keep the eBPF maps and the normal OpenWrt firewall from disagreeing about the same flow.

I would not replace OpenWrt's established NAT path with an eBPF NAT implementation unless the project has a hard requirement that netfilter cannot satisfy. NAT is not a useful place to demonstrate that eBPF can do something. It is a useful place to discover that packet translation is a state machine.

An eBPF NAT design can make sense when you control the complete path, need a specific endpoint-independent behavior, and can test every protocol case. For ordinary OpenWrt routing, keep NAT in netfilter and use eBPF for early classification or measurement.

Port reservations and interface changes make NAT state difficult

Reserved external port ranges are not just a map lookup. The allocator must avoid collisions, preserve the mapping for the required lifetime, and release it when the flow expires or the interface disappears.

Interface changes make that harder. A WAN reconnect can change the external address. A VLAN reload can remove the device that carried the map's traffic. A route change can send return packets through a different interface. If the NAT state survives those changes, it may point at an address or route that no longer exists.

A reliable implementation needs explicit lifecycle handling:

  • Remove or invalidate state when the external interface goes down.
  • Rebuild external address and route information after reconfiguration.
  • Release reserved ports that no longer have a valid mapping.
  • Flush stale maps during service restart.
  • Reconcile hairpin routes and IP rules with the current interface state.
  • Confirm that return traffic reaches the same translation path.

Hairpinning adds another failure path. A client behind the router may connect to the router's external address and need the packet routed back inside. The NAT map can be correct while the route or IP rule sends the packet somewhere else.

OpenWrt's network service can reconfigure interfaces without restarting your custom eBPF daemon. Subscribe to the same lifecycle events or periodically reconcile state. A map is not a database with automatic knowledge of the network. It is memory that will happily retain a dead interface until you delete the entry.

What kmod-xdp-sockets-diag does and does not provide

kmod-xdp-sockets-diag provides kernel support for inspecting XDP socket information. It is a diagnostic package for AF_XDP-related state. Installing it does not enable XDP, attach an XDP program, or create an AF_XDP socket.

Check the running kernel before installing the package:

uname -r
opkg list-installed | grep -E 'xdp|bpf'
opkg update
opkg list | grep kmod-xdp-sockets-diag

The package must match the running OpenWrt kernel build. A package built for another kernel release will not fix a missing feature. If the package is unavailable for your target, build it with the same OpenWrt tree and configuration as the firmware.

AF_XDP also needs the kernel and interface support required by the socket mode you choose. Some paths use a copy between kernel and userspace. Others depend on zero-copy support that the driver may not provide. Do not treat an AF_XDP benchmark from a server as a router result. One Linux AF_XDP configuration has reported round-trip latency as low as 6.5 microseconds in the best case, including tracing overhead. That is a property of that configuration, not a promise for OpenWrt hardware.

Use bpftool, interface state, and packet captures to confirm the actual path. The package name is not evidence that the path is active.

Debugging failed OpenWrt eBPF deployments

Do not start by copying a forum command. Start with the failure emitted by the kernel and loader.

Run these checks in order:

  1. Confirm the target kernel and architecture.
uname -a
ubus call system board
  1. Check the available BPF features.
bpftool feature probe
bpftool prog show
bpftool map show
  1. Check the interface and driver.
ip -details link show dev eth0
ethtool -i eth0
  1. Read the kernel messages.
dmesg -T | tail -50
logread | tail -50
  1. Trace the loader if it exits without explaining itself.
strace -f -o /tmp/ebpf-loader.strace ./ebpf-loader
grep -E 'bpf|ENOENT|EINVAL|EPERM|EACCES' /tmp/ebpf-loader.strace

EINVAL often means the requested program, map, helper, or attach mode does not fit the running kernel. EPERM points toward privileges, locked-down settings, or missing capabilities. ENOENT usually means a path, pinned object, interface, or expected kernel file is absent. The exact error matters.

If the verifier rejects the program, keep the full verifier output. It reports the instruction and register state that failed its safety proof. Most failures come from missing bounds checks, unbounded loops, pointer arithmetic the verifier cannot prove safe, or helper arguments with the wrong type.

A typical packet parser must prove each header exists before reading it:

void *data = (void *)(long)ctx->data;
void *data_end = (void *)(long)ctx->data_end;

struct ethhdr *eth = data;
if ((void *)(eth + 1) > data_end)
 return XDP_PASS;

The verifier is not being difficult here. It is stopping the program from reading outside the packet. Fix the proof in the source. Do not weaken the check or paste a larger example until the error disappears.

Use bpftool map dump to inspect counters. Use tcpdump to verify that the traffic you think you generated actually arrived on the attached interface. Use journalctl on systems that run a systemd-based service; on OpenWrt, logread is usually the more useful service log.

For packet-level tracing, a controlled bpf_printk can help, but do not leave per-packet prints enabled on a busy router. Watch the trace output while reproducing one packet, then remove the print. Logging every packet is a denial-of-service tool aimed at your own CPU.

The evidence chain should be clear:

  • The interface exists.
  • The driver exposes the expected path.
  • The program is loaded.
  • The program is attached to that interface.
  • The map contains the expected rule.
  • The counter changes.
  • The packet capture matches the test.
  • The kernel log contains no attach or verifier failure.

If one link is missing, fix that layer. Do not change five things and call the result a test.

Choosing netfilter, TC, XDP, or userspace on OpenWrt

Use the hook that matches the decision you need:

RequirementUseWhy
Stateful firewall rulesnftables and netfilterConnection tracking and mature policy handling
NATnetfilterExisting translation and conntrack behavior
Early fixed-header dropsNative XDPThe earliest useful packet decision
Ingress classificationTC ingressMore packet context than XDP
Egress shapingTC egressThe packet is already on the outbound path
Deep inspectionUserspaceStream state and protocol parsing
Packet exportAF_XDP or a userspace capture pathFlexible processing outside the kernel
Portable router policynftablesBetter support across drivers and targets

Choose XDP when driver support is confirmed, the rule is cheap, and the cost of a false drop is understood. Choose TC when you need the socket buffer path or egress handling. Choose userspace when the program needs state that cannot fit safely in a packet hook.

Choose netfilter when the problem is ordinary firewalling. It already handles conntrack, NAT, interfaces, zones, and rule updates. Replacing that machinery with custom eBPF creates a maintenance project, not a performance improvement.

The OpenWrt eBPF toolchain guide is the right place to work through firmware and compiler configuration. For packet forwarding rather than filtering, the eBPF load balancer guide covers a different design with different trade-offs.

The practical rule is plain: use eBPF where the packet decision is small and early. Keep policy, state, and inspection in the subsystem built to carry them.

FAQ

Can OpenWrt run eBPF programs on ARM?

Yes, if the target kernel enables the required BPF features and the program uses helpers and map types that kernel supports. Build for the target architecture and test on the actual router. A host compiler can produce valid BPF bytecode while the target still rejects the program.

Does installing clang enable eBPF on OpenWrt?

No. clang compiles the program. The target kernel must support the BPF system call, the requested program type, the helpers, and any BTF or map features the loader uses. Check the target with bpftool feature probe.

Is BCC suitable for a small OpenWrt router?

Usually no. BCC is useful for tracing on larger Linux systems, but its userspace and compiler requirements are a poor fit for constrained firmware. Use libbpf, a small loader, or prebuilt objects when the router has limited storage and memory.

Can XDP replace an OpenWrt firewall?

No. XDP handles early packet decisions well, but it does not replace stateful filtering, NAT, conntrack, or deep inspection. Keep nftables for those jobs and use XDP only where its early position solves a measured problem.

Does kmod-xdp-sockets-diag turn on AF_XDP?

No. It provides diagnostic support for XDP socket state. You still need a compatible kernel, interface, driver, socket setup, and userspace program. Check every layer before assuming AF_XDP is active.

Related: XDP Offload: What Actually Runs on the NIC