Intercept Ethernet packets before they reach kernel

Issue

I’d like to receive raw Ethernet packets for two different scenarios:

  1. Receive a copy so it still reaches the Kernel
  2. Intercept the packets so the Kernel never sees them and I implement the logic.

From Googling I found this:

sock_raw = socket(AF_PACKET , SOCK_RAW , htons(ETH_P_ALL));

I think this makes the Kernel send a copy, i.e. scenario #1?

Q: How would I implement the second scenario, to intercept the packet and deprive the Kernel?

My goal is to intercept packets from the network card driver and process them through my own Ethernet, IP and TCP stack.

I’m aware this isn’t trivial. I’m fine reading RFC specifications and writing code, my weak area is understanding how the Linux Kernel works (although if I’m bypassing it, that might be less of a problem?).

Any advice/tips/links are most-welcome.

Solution

your Kernel is in charge of your network card. It literally is the only thing in your system that knows how to get packets (frames) from the card!

My goal is to intercept packets from the network card driver

The network card driver is the kernel.

 

You hence cannot intercept a packet before it reaches the kernel, unless you completely remove the network card from the control of the kernel. (that exists, e.g., in the shape of DPDK, but I’m very sure you’re not interested in writing a userland driver for your card) And then you’d still be stuck with the problem of getting the packet into the kernel afterwards.

So, what you want makes no sense.

What you probably instead want to do is write a filter that runs within the kernel space. eBPF makes that possible. But it’s in the kernel.


I think this makes the Kernel send a copy, i.e. scenario #1?

No, that means your program is now listening on the raw ethernet device for frames, which you get, after they’ve gone through the kernel. But they will not be copied to the IP stack.

Answered By – Marcus Müller

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published