我想使用虚拟接口测试 NAT 表。我有连接到互联网的 enp1s0 接口,并已将 NAT 表配置为 MASQUERADE 数据包,如下所示。
random@debian:~$ ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host noprefixroute
valid_lft forever preferred_lft forever
2: enp1s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
link/ether 52:54:00:4d:63:c0 brd ff:ff:ff:ff:ff:ff
inet 192.168.122.10/24 brd 192.168.122.255 scope global enp1s0
valid_lft forever preferred_lft forever
inet6 fe80::5054:ff:fe4d:63c0/64 scope link
valid_lft forever preferred_lft forever
3: dummy0: <BROADCAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN group default qlen 1000
link/ether 5e:81:f3:78:47:c0 brd ff:ff:ff:ff:ff:ff
inet 10.0.0.10/24 scope global dummy0
valid_lft forever preferred_lft forever
inet6 fe80::5c81:f3ff:fe78:47c0/64 scope link
valid_lft forever preferred_lft forever
random@debian:~$ ip route
default via 192.168.122.1 dev enp1s0 onlink
10.0.0.0/24 dev dummy0 proto kernel scope link src 10.0.0.10
192.168.122.0/24 dev enp1s0 proto kernel scope link src 192.168.122.10
random@debian:~$ sudo sysctl -w net.ipv4.ip_forward=1
net.ipv4.ip_forward = 1
random@debian:~$ lsmod | grep dummy
dummy 16384 0
random@debian:~$ ipt
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
random@debian:~$ sudo iptables -t nat -A POSTROUTING -j MASQUERADE -s 10.0.0.0/24 -o enp1s0
random@debian:~$ ipt -t nat
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
0 0 MASQUERADE all -- any enp1s0 10.0.0.0/24 anywhere
有了这些 ip 配置。使用 ping 进行测试
random@debian:~$ ping -I 10.0.0.10 8.8.8.8
PING 8.8.8.8 (8.8.8.8) from 10.0.0.10 : 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=114 time=28.3 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=114 time=30.9 ms
^C
--- 8.8.8.8 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1002ms
rtt min/avg/max/mdev = 28.302/29.583/30.865/1.281 ms
random@debian:~$ ping -I dummy0 8.8.8.8
PING 8.8.8.8 (8.8.8.8) from 10.0.0.10 dummy0: 56(84) bytes of data.
^C
--- 8.8.8.8 ping statistics ---
5 packets transmitted, 0 received, 100% packet loss, time 4095ms
通过虚拟接口发送数据包不起作用。可以使用 wireshark 观察到在虚拟接口 dummy0 中可以看到数据包,但数据包并未转发到 enp1s0。