Skip to content
systemcoding.dev
Networking

Attach eBPF to Traffic Control with tc and cls_bpf

Load an eBPF classifier with tc and cls_bpf on ingress or egress using a clsact qdisc, return TC_ACT verdicts, and see how tcx replaces it on Linux 6.6.

7 min read
Summarize in AI
Flat illustration of network packets crossing between two hosts, with the C, Linux and Rust logos.

XDP sees packets early but only on the way in, and it sees raw frames with no socket buffer metadata. When you need to act on egress traffic, or you need the parsed skb with its mark, its protocol and its checksum state, the hook to use is traffic control. Linux lets you attach an eBPF program there through the cls_bpf classifier, and since Linux 6.6 through a newer, cleaner attachment called tcx. This post uses Linux 6.12, iproute2 6.x and libbpf 1.5 to write a classifier that drops ICMP echo requests on ingress, attaches it with tc, inspects it and removes it, then shows the tcx equivalent. It assumes you know what a program and a map are; see the introduction to eBPF in this cluster if not.

Where the tc hook sits

The tc hook runs after the driver has built an sk_buff, so a program here gets a struct __sk_buff, a stable view of the skb with fields such as protocol, mark, len and data/data_end pointers. The program type is BPF_PROG_TYPE_SCHED_CLS, and in a C source file you place it in a section named tc (or classifier).

Traffic control exposes the hook through a special queueing discipline called clsact. Unlike a normal qdisc, clsact does not queue anything. It exists only to give you two attachment points per interface, ingress and egress, where classifiers can run without the shaping machinery. Ingress runs when a packet comes in, after XDP; egress runs just before the packet is handed to the device queue.

The tc-bpf(8) man page describes the program contract, and the kernel BPF documentation covers the program types and helpers.

The return values

A tc program returns a verdict from linux/pkt_cls.h. In direct-action mode, which is what you use, the verdict is the program's return value:

ReturnEffect
TC_ACT_OKLet the packet continue
TC_ACT_SHOTDrop it
TC_ACT_UNSPECBehave as if no classifier ran, try the next one
TC_ACT_REDIRECTUsed after bpf_redirect to send the packet elsewhere

Direct-action (da) is what lets one program both classify and decide. Without it, the program returns a class id and a separate tc action would be needed to do anything with it, which is the legacy model you should avoid.

An ICMP echo filter

icmp_drop.bpf.cc
#include <linux/bpf.h>
#include <linux/if_ether.h>
#include <linux/icmp.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/pkt_cls.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>

SEC("tc")
int tc_icmp_drop(struct __sk_buff *skb)
{
    void *data = (void *)(long)skb->data;
    void *data_end = (void *)(long)skb->data_end;

    struct ethhdr *eth = data;
    if ((void *)(eth + 1) > data_end)
        return TC_ACT_OK;
    if (eth->h_proto != bpf_htons(ETH_P_IP))
        return TC_ACT_OK;

    struct iphdr *ip = (void *)(eth + 1);
    if ((void *)(ip + 1) > data_end)
        return TC_ACT_OK;
    if (ip->protocol != IPPROTO_ICMP)
        return TC_ACT_OK;

    __u32 ip_len = ip->ihl * 4;
    if (ip_len < sizeof(*ip))
        return TC_ACT_OK;

    struct icmphdr *icmp = (void *)ip + ip_len;
    if ((void *)(icmp + 1) > data_end)
        return TC_ACT_OK;

    if (icmp->type == ICMP_ECHO)
        return TC_ACT_SHOT;

    return TC_ACT_OK;
}

char LICENSE[] SEC("license") = "GPL";

The parsing is the same bounds-checked chain as in the XDP examples, and the structure should look familiar. Two differences matter. First, the context is a __sk_buff and its data and data_end fields are 32-bit values cast to pointers, exactly as in XDP. Second, you could also have used bpf_skb_load_bytes to copy header bytes into the stack, which avoids direct packet access and is safer when the skb data is non-linear (for example with large receive offload or fragments in separate pages). Direct access reads only the linear part. For short headers at the front of a packet this is almost always sufficient, but code that must see deep into payloads should use the helper.

Compile it the usual way:

Shell
clang -O2 -g -target bpf -c icmp_drop.bpf.c -o icmp_drop.bpf.o

Attaching with tc

Create the clsact qdisc once per interface, then add the filter:

Shell
sudo tc qdisc add dev eth0 clsact
sudo tc filter add dev eth0 ingress bpf da obj icmp_drop.bpf.o sec tc

bpf selects the cls_bpf classifier, da enables direct action, obj names the object file and sec names the ELF section that holds the program. Use egress in place of ingress to filter outbound traffic with the same program.

List what is attached:

Shell
sudo tc filter show dev eth0 ingress
Text
filter protocol all pref 49152 bpf chain 0 
filter protocol all pref 49152 bpf chain 0 handle 0x1 icmp_drop.bpf.o:[tc] direct-action not_in_hw id 91 name tc_icmp_drop tag 3b1d27f09ac4e6d8 jited 

The second line is the active filter: the object and section, direct-action, the program id and name, and jited, which confirms it was compiled to native code. The id and tag differ per load. A ping to this host from another machine now gets no reply, while pings that originate here and their replies are unaffected, since replies are ICMP_ECHOREPLY, a different type.

Remove the filter and the qdisc:

Shell
sudo tc filter del dev eth0 ingress
sudo tc qdisc del dev eth0 clsact

Deleting the qdisc also removes every filter on it, so on an interface shared with other tools check for existing clsact filters before you do.

The tcx attachment on Linux 6.6 and later

The tc command approach has well-known drawbacks. Filters are tied to a priority and a handle, so two programs from different tools can clobber each other, the programs live in the qdisc rather than owning their lifetime, and removing the wrong filter is easy. Linux 6.6 added tcx, a dedicated, ordered attachment point for tc programs that uses BPF links. A link ties the attachment to the file descriptor of its creator, so when the process exits or closes the link, the program detaches automatically, unless you pin the link in the BPF filesystem.

With libbpf 1.3 or later you attach from C with bpf_program__attach_tcx:

attach_tcx.cc
#include <bpf/libbpf.h>
#include <net/if.h>
#include <stdio.h>

int main(void)
{
    struct bpf_object *obj = bpf_object__open_file("icmp_drop.bpf.o", NULL);
    if (!obj || bpf_object__load(obj))
        return 1;

    struct bpf_program *prog = bpf_object__find_program_by_name(obj, "tc_icmp_drop");
    LIBBPF_OPTS(bpf_tcx_opts, opts);
    struct bpf_link *link =
        bpf_program__attach_tcx(prog, if_nametoindex("eth0"), &opts);
    if (!link) {
        fprintf(stderr, "attach failed\n");
        return 1;
    }
    puts("attached; press Enter to detach");
    getchar();
    bpf_link__destroy(link);
    return 0;
}
Text
attached; press Enter to detach

Run as root, the filter is active until you press Enter, at which point the link is destroyed and the program detaches. Multiple tcx programs on the same hook run in a defined order, and options in bpf_tcx_opts let you place a program before or after another by id. Tools such as Cilium use this to avoid fighting over priorities.

Modifying packets in tc

Because the skb carries checksum state, tc programs are the safer place to rewrite fields. Changing a destination address in an IPv4 header invalidates the IP checksum and, for TCP and UDP, the transport checksum too. The helpers bpf_l3_csum_replace and bpf_l4_csum_replace update those checksums incrementally from the old and new values, and bpf_skb_store_bytes writes the new bytes. The order matters: fix the checksums using the old value before you store the new one, or in a single call that passes the correct flags, because after the store the old bytes are gone and cannot be fed to the checksum helper.

Any helper that changes packet data, including the store and the checksum helpers, invalidates the packet pointers you derived earlier from skb->data. The verifier enforces this: after such a call it forgets the verified ranges, and you must reload data and data_end from the context and check bounds again before further direct access. Forgetting this is the most common cause of a verifier failure in a tc program that edits packets.

Finally, remember that the program runs on a shared hook. Another tool, perhaps a container network plugin, may already have filters on the same interface. List the existing filters before you add yours, give the filter an explicit priority with prio, and prefer tcx links on Linux 6.6 and later so ordering is defined rather than accidental.

When to use tc instead of XDP

  • You need egress. XDP has no transmit-side hook; tc egress is the equivalent.

  • You need skb metadata such as the mark, ifindex, a socket cookie or the checksum state.

  • You want to modify packets with helpers like bpf_skb_store_bytes and bpf_l3_csum_replace, which fix checksums for you.

  • The driver has no native XDP support and generic mode's skb cost is already being paid.

If the decision needs only headers and the interface supports native XDP, XDP is cheaper because it avoids the skb. The two combine well: XDP for coarse early drops, tc for policy that needs the skb.

Share

Keep reading

Flat illustration of a microcontroller wired to an LED and a sensor, with the Bluetooth, Nordic Semiconductor and Arm logos.
Embedded

Create a Custom BLE GATT Service on nRF52

Define a custom 128-bit GATT service on nRF52 with Zephyr: characteristic properties, read and write callbacks, notifications through the CCC and MTU limits.

9 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.