Using Linux BPF Filter in DHCP Client
During DHCP discovery process, the DHCP network flow is based on UDP when lower IP stack is not ready yet. The user space DHCP client program will need ethernet RAW socket(AF_PACKET, SOCK_RAW) to receive UDP package otherwise kernel will drop the UDP package as IP mismatch.
Hooking on Ethernet RAW socket requires DHCP client filter out non-DHCP network package in user space which could result a large CPU overhead. The Linux kernel is providing BPF (Berkeley Packet Filter) facility for filtering packages in kernel space before sending to user space.
Let’s go through the workflow via an example:
|
|
The kernel allows us to use setsockopt()
via SO_ATTACH_FILTER
to apply
an BPF filter on a socket. The filter is in special format allowing kernel
to do sanity check.
As user space developer, you don’t need to understand every bites of it, using
the output of tcpdump -dd <filter>
is sufficient.
In this case, we are using output of tcpdump -dd 'ip and udp dst port 68'
,
it means only UDP package with 68 as destination port will be sent to
this socket for userspace processing. You may refer to man page
pcap-filter(7)
for filter syntax.