Return XDP_PASS, XDP_DROP or XDP_TX from an XDP program
An XDP program ends with a verdict: XDP_PASS hands the frame to the stack, XDP_DROP discards it, XDP_TX bounces it out the same port. Linux 5.x, libbpf.
Every XDP program must return an action, and the number you return decides what the driver does with the frame. XDP_PASS sends it up the normal stack, XDP_DROP frees it at the earliest point, and XDP_TX transmits it back out of the interface it arrived on. XDP_ABORTED also drops, but it fires the xdp_exception tracepoint, which is what you want for bugs. XDP_REDIRECT is the fifth action, for other devices and sockets.
This example drops every IPv4 ICMP packet and passes the rest. It builds against libbpf 1.x headers on a Linux 5.15 kernel.
#include <linux/bpf.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/in.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>
SEC("xdp")
int drop_icmp(struct xdp_md *ctx)
{
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;
if (eth->h_proto != bpf_htons(ETH_P_IP))
return XDP_PASS;
struct iphdr *ip = (void *)(eth + 1);
if ((void *)(ip + 1) > data_end)
return XDP_PASS;
return ip->protocol == IPPROTO_ICMP ? XDP_DROP : XDP_PASS;
}
char LICENSE[] SEC("license") = "GPL";Returning XDP_DROP costs almost nothing, because no sk_buff has been allocated yet. That is the reason XDP firewalls are fast, and also the reason tcpdump on the host does not see what you drop: the packet never reaches the point where it would be captured. Use XDP_ABORTED during development, and swap to XDP_DROP once the program is correct.