linuxebpfbpfnetfilter

Attaching netfilter program with bpftool


I loaded a netfilter program successfully using

sudo bpftool prog load filter.bpf.o /sys/fs/bpf/filter

Now I want to attach the program to the kernel.

$ bpftool net help
Usage: bpftool net { show | list } [dev <devname>]
       bpftool net attach ATTACH_TYPE PROG dev <devname> [ overwrite ]
       bpftool net detach ATTACH_TYPE dev <devname>
       bpftool net help

       PROG := { id PROG_ID | pinned FILE | tag PROG_TAG | name PROG_NAME }
       ATTACH_TYPE := { xdp | xdpgeneric | xdpdrv | xdpoffload | tcx_ingress
                        | tcx_egress }
       OPTIONS := { {-j|--json} [{-p|--pretty}] | {-d|--debug} }

Note: Only xdp, tcx, tc, netkit, flow_dissector and netfilter attachments
      are currently supported.
      For progs attached to cgroups, use "bpftool cgroup"
      to dump program attachments. For program types
      sk_{filter,skb,msg,reuseport} and lwt/seg6, please
      consult iproute2.

bpftool claims netfilter attachments are supported, but they are not listed in ATTACH_TYPE options.

$ sudo bpftool net attach netfilter id 122 dev eth0
Error: invalid net attach/detach type: netfilter

How do you attach a netfilter program to an interface using bpftool?


Solution

  • bpftool claims netfilter attachments are supported, but they are not listed in ATTACH_TYPE options.

    I can't find that. The only mention I can find is the bpftool net { show | list } [ dev NAME ] command mentions it can show them.

    List bpf program attachments in the kernel networking subsystem.

    Currently, device driver xdp attachments, tcx, netkit and old-style tc classifier/action attachments, flow_dissector as well as netfilter attachments are implemented, i.e., for program types BPF_PROG_TYPE_XDP, BPF_PROG_TYPE_SCHED_CLS, BPF_PROG_TYPE_SCHED_ACT, BPF_PROG_TYPE_FLOW_DISSECTOR, BPF_PROG_TYPE_NETFILTER.

    But nothing about attaching.

    This is likely because netfilter programs need a few additional bits of information when attaching compared to most other program types. Specifically, when creating the link you should specify:

    It seems the bpftool maintainers did not want to extend the CLI to support all of this, at least not at the time of writing. You will have to use something like libbpf to attach your program.