Search code examples
iptablespcaptcpdump

How to record the packets after iptables?


I want to record the packets (using tcpdump) after iptables, but it seems that tcpdump will record all the packets. I don't want the packet dropped by iptables.

Is there any way to

  • record the packets after iptables? or
  • output the packets (processing by iptables) into pcap/log file?

Thanks.


Solution

  • Tcpdump acts before iptables for inbound traffic, but you can use iptables "NFLOG" extension to reach your goal: http://ipset.netfilter.org/iptables-extensions.man.html#lbDI

    Using "NFLOG" destination you can log desired packets to userspace application, and that's where tcpdump belongs (you can also assign traffic to a specific group and then tell tcpdump to listen from it).

    Webserver (very basic) example, let's pretend you are accepting http/https traffic and dropping ssh:

    #BASIC RULES
    iptables -A INPUT -p tcp --dport 80 -j ACCEPT
    iptables -A INPUT -p tcp --dport 443 -j ACCEPT
    iptables -A INPUT -p tcp --dport 22 -j DROP
    
    #NFLOG REDIRECT ONLY HTTP TRAFFIC
    iptables -A INPUT -p tcp --dport 80 -j NFLOG
    
    #TCPDUMP ONLY ON MATCHED TRAFFIC (=HTTP)
    tcpdump -i nflog