I use tcpdump a lotĀ , we all doĀ , but if someone tells you to explain how it works what would you say?
Well we know that tcpdump applies a number of rules (if told) to filter traffic before the kernel(iptables or similar) drops itĀ , thatās why if you do something like
tcpdump -i any dst port 21
and you start some connections against port 21 you will see traffic even tho you might not have port 21 bound by any process (some ftp server or what not).
Well thatās a fair assumptionĀ , i want to divide this article in two/three partsĀ , the first part is about how tcpdump filters portsĀ , and shows you exactly what you want.
Letās say I want to see all the packets going to port 21 with the SYN flag lit up?
tcpdump -i any dst port 21 and tcp[13] == 2
You can go check the osi layer offsets and see why this makes senseĀ , but the question is how is this passed to the socket (potentially RAW) so it can filterĀ , also itās got to be something simple and fast so the overhead is not huge
Turns out that thereāss these bytecode language called bpf (http://www.tcpdump.org/papers/bpf-usenix93.pdf)Ā , that generates an expression that you can attach the socket using a setsockopt().
Look at this for exampleĀ , if you want to see the expression you can pass -d to tcpdump:
NeatĀ , and if you wanna how is this passed to the socket you could strace, for example:
The key is SO_ATTACH_FILTERĀ , which attaches that filter that was previously shown, plus some sizeofs etc.
Apparently thereās some iptables modules that let you attach complex bfp expressions in one single ruleĀ , meaning that your number of rules can go very deep and all in a single lineĀ , this will have tremendous impacts in the speed that rules are parsed (from an iptables perspective).
Letās leave it here for now as I need to go to workĀ , but i want to take a look to the iptables module and what happens after tcpdump accept() ās a packageĀ , how does it hand it over to the kernel or userland process etc.
Thanks!!!!