Skip to content

Instantly share code, notes, and snippets.

@emctoo
Last active April 11, 2022 08:22
Show Gist options
  • Save emctoo/ff988860b4c6e78d11b64756db91258c to your computer and use it in GitHub Desktop.
Save emctoo/ff988860b4c6e78d11b64756db91258c to your computer and use it in GitHub Desktop.
nat.md

ip forward

sudo modprobe ip_tables
sudo modprobe ip_conntrack
sudo modprobe iptables_nat

sysctl -w net.ipv4.ip_forward = 1

# or
echo "net.ipv4.ip_forward = 1" | sudo tee /etc/sysctl.conf

iptables 基本操作

# list rules with index
iptables -t nat -nvL --line-number

# delete rule by index
iptables -t nat -D PREROUTING 1

SNAT

基本的拓扑如下


               |                                            |
192.168.9.2 -> | eth3 (192.168.9.1) -> eth2 (192.168.8.185) | -> internet
               |                                            |

所有的配置都在中间的机器上

iptables -t nat -F
iptables -t nat -A POSTROUTING -s 192.168.9.0/24 -o eth2 -j SNAT --to-source 192.168.8.185

DNAT

               |                                            |
192.168.9.2 <- | eth3 (192.168.9.1) <- eth2 (192.168.8.185) | <- 192.168.8.45
               |                                            |
iptables -t nat -A PREROUTING -i eth2 -d 192.168.8.185 -p tcp --dport 8000 -j DNAT --to-destination 192.168.9.2:8000

# 另外需要一条SNAT, 否则 eth3 上 ip_forward 转发之后的 pkt 的源地址是 192.168.8.0/24 子网的,网卡会丢掉
# 如果 eth2 上是一个公网地址就不需要
iptables -t nat -A POSTROUTING -o eth3 -s 192.168.8.0/24 -p tcp -J SNAT --to-source 192.168.9.1

notes

  • DNAT 的实现基于 connect tracking。在有了 SNAT rule 之后,并不需要手动添加与之对应的 DNAT rule。
# Example at https://git.busybox.net/busybox/tree/examples/udhcp/udhcpd.conf
start 192.168.9.10
end 192.168.9.50
interface eth3
remaining yes
option dns 192.168.8.145 119.29.29.29
option domain myctl.space
option subnet 255.255.255.0
option router 192.168.8.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment