Ubuntu: Debug iptables by inserting a log rule

Iptables is a powerful utility for controlling network traffic coming through your host.  But writing the rules that control the flow can be hard to troubleshoot when you have a complex network and multiple host interfaces.

Luckily, you have the ability to insert log rules wherever necessary to get visibility into the packets flowing through the rule chain.

For example, if you want to insert a rule at position #4 in the FORWARD chain that logs packets information:

sudo iptables -I FORWARD 4 -j LOG --log-prefix "RULE4:" --log-level 7

This will log packet information to “/var/log/kern.log”.  I’ve put a snippet of the log below and now armed with the IN/OUT interfaces, and SRC/DST locations, you can design your rules accordingly.

Jun 5 09:50:04 myhost kernel: [211988.093303] RULE4:IN=virbr226 OUT=virbr225 MAC=52:54:00:c0:a0:7e:52:54:00:93:04:1f:08:00 SRC=192.168.226.175 DST=192.168.225.176 LEN=84 TOS=0x00 PREC=0x00 TTL=63 ID=8597 PROTO=ICMP TYPE=0 CODE=0 ID=1975 SEQ=135

Multiple log rules can be added, and they can be added to any of the chains.  When you are ready to delete the log rule at position number 4 from the FORWARD chain, use this command:

# delete rule at position 4
sudo iptables -D FORWARD 4

# verify rule is gone
sudo iptables -L -v -n --line-number | grep FORWARD -A30

Log rule for NAT table

The same concept applies to rules in the nat table.  For example, to insert a rule at position #3 in the POSTROUTING chain of the nat table.

# insert rule at position 3
sudo iptables -t nat -I POSTROUTING 3 -j LOG --log-prefix "NAT3:" --log-level 7

# verify log rule was created
sudo iptables -t nat -L -n -v --line-number

# delete rule at position 3
sudo iptables -t nat -D POSTROUTING 3

 

REFERENCES

iptables man page

add log rule and change log location for Ubuntu

stackoverflow, iptables log rule

logging dropped packets

iptables rules and ssh example