I'm looking for a way to examine the first packet only of a newly established TCP connection (the first packet with actual payload, that is). Is there a way to do this with iptables? Matching ESTABLISHED packets would match all packets of a connection after handshake, right?
Iptables – Capture first packet of established TCP connection with iptables
conntrackiptables
Related Topic
- Iptables – tcp flags in iptables: What’s the difference between RST SYN and RST and SYN RST ? When to use ALL
- Linux – Understanding connection tracking in iptables
- Linux – How to reset a tcp connection immediately on both ends on a certain condition using linux netfilter/iptables
- Iptables: match only the first packet of established TCP-connection
- iptables REDIRECT Works Only for First Packet: Solution
Best Answer
You can achieve your goal using (abusing)
iptables
, to be more specific:connbytes
match andNFQUEUE
target.connbytes
allows you to match the Nth packet in the connection andNFQUEUE
is a mechanism for passing packets matching an iptables rule to userspace program. Furthermore: you'll have to use some program which whill be receiving relevant packets from the kernel and processing them.iptables
I'm assuming here that you are interested in capturing the packets server-side (that can be changed if you are interested in client-side capturing). In that case we'll need to capture the 3-rd incoming packet for each connection (i.e. the first incoming packet after the three-way handshake) and put the packet in a netfilter queue (queue #1 in this case).
As soon as a packet matches this rule, it will be passed to the userspace program bound to the queue #1. The program can then examine the packet and afterwards decide to accept it or drop it.
The program
You will need a program which will receive the packets in userspace using the
libnetfilter_queue
library. Bindings for the library are available in different languages. The following is a sample program written in python:The program assumes that the queued packets will be IPv4 TCP packets and prints the source ip:port pair and the TCP payload of the packet.
Caveats
NFQUEUE
target: if the userspace program bound to the queue hangs, crashes or is slow to process packets, those will be dropped/stuck and the service bound to the specified port will become unreachable. You can pass the--queue-bypass
option to theNFQUEUE
target toACCEPT
the matched packets if no userspace program is bound to the specified queue: this should help with the problem of the program crashing but won't help with a hung or slow program.