iptable的策略中,有一个用来记录日志用的'-j LOG',可以在匹配的数据包经过此策略时记一条日志,可以帮我们弄清数据包在netfilter链表中的处理过程,定位出问题的位置。
其支持的参数有:
--log-level level
Level of logging (numeric or see syslog.conf(5)).
--log-prefix prefix
Prefix log messages with the specified prefix; up to 29 letters long, and useful for distinguishing messages in the logs.
--log-tcp-sequence
Log TCP sequence numbers. This is a security risk if the log is readable by users.
--log-tcp-options
Log options from the TCP packet header.
--log-ip-options
Log options from the IP packet header.
--log-uid
Log the userid of the process which generated the packet.
为了方便,我写了个脚本,在各表的默认链的开始结尾处各添加一个日志记录点:
#! /bin/bash
# netfilter_debug.sh
ACTION=$1
FILTER=$2
if [ "$#" -ne 2 -a "$1" != "I" -a "$1" != "D" ];then
echo "USAGE: $0 <ACTION> <FILTER>"
echo "EG: $0 I '-s 1.1.1.1'"
exit 1
fi
LOG_LEVEL=7
OPTIONS="--log-level $LOG_LEVEL -m comment --comment debuglog --log-ip-options"
## tables and chains
TABLES="raw mangle nat filter"
raw_chains="PREROUTING OUTPUT"
mangle_chains="PREROUTING INPUT FORWARD OUTPUT POSTROUTING"
nat_chains="PREROUTING INPUT OUTPUT POSTROUTING"
filter_chains="INPUT FORWARD OUTPUT"
for table in $TABLES; do
table_chains="${table}_chains"
eval "chains=\$$table_chains"
for chain in $chains; do
echo "$chain" "$table"
if [ "$ACTION" = "I" ]; then
iptables -t $table -I $chain $FILTER -j LOG --log-prefix "$chain $table:I " $OPTIONS
iptables -t $table -A $chain $FILTER -j LOG --log-prefix "$chain $table:O " $OPTIONS
elif [ "$ACTION" = "D" ]; then
iptables -t $table -D $chain $FILTER -j LOG --log-prefix "$chain $table:I " $OPTIONS
iptables -t $table -D $chain $FILTER -j LOG --log-prefix "$chain $table:O " $OPTIONS
fi
done
done
echo "Run:tail -f /var/log/messages or dmesg -w"
用起来也很简单:
netfilter_debug.sh I/D '-d 1.1.1.1'
添加就用I (insert),删除就用D (delete),后边用单引号包起来的是匹配策略。
可以用iptables-save查看添加进去的策略:
此时ping一下目标IP:ping 1.1.1.1 -c 1
用 tail -f /var/log/messages 或 dmesg -w 看下日志结果:
很清晰的就看到此数据包从OUTPUT处理过程中穿过了各个表,又在POSTROUTING过程中穿过两个表。
如果你有自定义或感兴趣的链,可以加入到各表的列表中。
补充下处理过程、链 和 表的概念关系:
1. 链是属于某个表的,各个表中的链相互独立,比如mangle表和filter表都有OUTPUT链,他们是相互独立的。
2. 数据经过5个处理过程时,会依次穿过特定的表,默认查找其中链名和当前处理过程名相同的链进行处理。
我之前就是把处理过程当成链(因为他们名字相同),以为是链穿过表了,有和我一样的小伙伴吗😀