BPF, raw access to network packets

A working example with the FreeBSD BPF kernel module

Mario Emmanuel
The Console
2 min readAug 30, 2022

--

Image from Unsplash by Lars Kienle

I recently attended a C/C++ MeetUp in Copenhagen where the organiser show some of the hooks that the Linux kernel allowed. The examples were around the OS network stack. I become interested in the topic so I decided to further investigate which were the options to do some tests using FreeBSD. While researching around the OS kernel network stack I found the Berkeley Packet Filter (BPF), which has been around since early 90s.

The Berkeley Packet Filter

The Berkeley Packet Filter is an interface to the kernel that enables direct access to network interfaces, so you can send and receive packets without any intermediate stack. It is an extremely useful option if you are interested in experimenting around networks. I discovered it through a Bastian Rieck post.

To use the BPF you need to first open a BPF pseudodevice (they are opened sequentially), associate it to a given network interface, activate its immediate mode, request a buffer length and receive the data. The following sample program illustrates a continuous read of all packets. It dumps every packet including its source address, destination address and EtherType (which refers to the payload type).

Testing

The BPF has to be executed as root. It can be seen how EtherTypes 0x0800 (IPv4) and 0x0806 (ARP) are clearly displayed. Notice how ARP requests are broadcasted while IPv4 communication happens between two hosts.

BPF inspecting source and destination MAC addresses and protocol

BPF enables to develop any custom network protocol that is intended to bypass the OS kernel easily, as it provides a direct interface to both send and receive Ethernet frames directly into our code.

Experimenting around protocols that does not use TCP or UDP (or even IP) is not a common need, but there might be applications where you might either want to alter on purpose certain packets or explore new specific protocols that run directly on top of a Ethernet network. BPF makes that experimentation easy and feasible.

--

--