Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flush raw AF_PACKET socket to get correct filtered packets

sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &f, sizeof (f)) 

With this simple BPF/LPF attach code, when I try to receive packet on the socket, will get some wrong packets that doesn't match with the filter. Seems those packets got into the socket before I call setsockopt().

Seems like should first create the AF_PACKET SOCK_RAW socket, then attach the filter, then flush the socket to get rid of those wrong packets.

So the question is, how to flush those packet?

like image 919
Rider Avatar asked Oct 24 '20 19:10

Rider


People also ask

How do raw sockets work?

A raw socket is used to receive raw packets. This means packets received at the Ethernet layer will directly pass to the raw socket. Stating it precisely, a raw socket bypasses the normal TCP/IP processing and sends the packets to the specific user application (see Figure 1).

What is Af_packet?

The AF_PACKET socket in Linux allows an application to receive and send raw packets. This Linux-specific PMD binds to an AF_PACKET socket and allows a DPDK application to send and receive raw packets through the Kernel.

What is raw socket programming?

A raw socket is a type of socket that allows access to the underlying transport provider. This topic focuses only on raw sockets and the IPv4 and IPv6 protocols. This is because most other protocols with the exception of ATM do not support raw sockets.


1 Answers

The "bug" you're describing is real and I've seen it at multiple companies in my career. There is something like an "oral tradition" around this bug that is passed from one network engineer to another. Here are the common fixes:

  1. Just call recv on the socket until it is empty
  2. Double-filter by filtering packets in usermode as well as using the bpf
  3. Use the zero-bpf technique just like libpcap where you apply an empty bpf first, then empty the socket, and then apply the real bpf.

I've written about this problem extensively on my blog to try and codify the oral tradition around this bug into a concrete recommendation and best-practice.

like image 51
Natan Yellin Avatar answered Oct 13 '22 08:10

Natan Yellin