tcpdump 和 iptables/netfilter 处理数据包的先后顺序

验证思路

  1. iptables的 PREROUTING 链做 dnat,若 tcpdump 捕获到 dnat 前的数据包,则进站的数据包先经过tcpdump,反之则进站数据包先经过 iptables
  2. iptables 的 POSTROUTING 链做 snat,若 tcpdump 捕获到 snat 后的数据包,则出站的数据包先经过 iptables,反之则出站数据包先经过 tcpdump
  3. 在 iptables 的 PREROUTING、FORWARD、POSTROUTING、分别记录日志,以追踪数据包的流向

操作

配置 PROROUTING
配置 iptables PREROUTING

添加 DNAT 记录
添加日志记录

配置 FORWARD
配置 FORWARD

添加日志记录

配置 POSTROUTING
配置 POSTROUTING

添加 SNAT 记录
添加日志记录

实验
从节点 10.4.71.126 ping 10.4.135.215

ping 10.4.135.215 -c 1

查看日志

journalctl -ex -f | grep debug_log

iptables 日志

数据包经过 PREROUTING

tcpdump 抓包

tcpdump -i ens192 src host 10.4.71.126 or dst host 10.4.71.124 -n

输出如下:
tcpdump 抓包

先抓到 10.4.71.126 -> 10.4.135.215 的 icmp request
再抓到 10.4.135.215 -> 10.4.71.124 的 icmp request

分析
数据流向

  1. 数据包进入系统协议栈后先被 tcpdump 捕获
  2. 数据包进入 iptables 处理流程
  3. PREROUTING 做 DNAT,将目的 IPv4 地址从 10.4.135.215 修改为 10.4.71.124
  4. 经过路由决策,该数据包不属于本机 (目的地址已被修改),数据包走 FORWARD 链
  5. 在经过路由决策,目的地址为 10.4.71.124 的数据包经由网卡 ens192 发往默认网关
  6. 数据包经过 POSTROUTING 链,做 SNAT,将源 IPv4 地址从10.4.71.126修改为10.4.135.215,到此iptables对数据包的处理已完成
  7. 出站数据包被tcpdump捕获

结论

  • 进站的数据包先经过 tcpdump,再经过iptables
  • 出站的数据包先经过iptables,再经过tcpdump

原理分析

事实上tcpdump在链路层就已经捕获数据包 (从 tcpdump man page 得知)
而iptables工作在协议栈的网络层,原理上tcpdump就比iptables更接近网卡设备
参考:
Iptables for Routing
···
You might wonder why iptables, a layer 3 (network layer) tool, could modify port information, which is on layer 4 (transport layer). In fact, although iptables mainly work on layer 3, it has been extended to work on layer 4 as well, so working with ports is also possible for iptables. In our case, the option -m tcp (m stands for “match” an extension) loads an extension called tcp to work on ports, and the --dport option is provided by this extension. Actually, the option -p tcp implicitly loads the tcp extension so -m tcp is redundant. Here is the documentation for all standard extensions on Ubuntu. Also note that DNAT rules must be configured on the PREROUTING or OUTPUT chain because it’s useless to modify the destination IP address after the routing decision has been made.
···

更多推荐