隧道环境下 Iptables 转发保留源IP
E.g.
主机A 公网IP:1.1.1.1
主机A Tunnel IP:192.168.233.1
主机B 公网IP:2.2.2.2
主机B Tunnel IP:192.168.233.2
A,B通过Wireguard进行连接,需要将 Server/Peer 端的AllowIPs均设置为0.0.0.0/0(默认情况下Wireguard会自动添加默认路由,需要在 [Interface] 下只能加 Table = off
目的:
使用主机A 转发端口给主机B,并且主机B能接收到源IP。
比如 3.3.3.3(客户机) => 1.1.1.1:8088 => 192.168.233.2:80 ,并且 192.168.233.2 能够看到客户机源IP(3.3.3.3)
主机A配置
1
2
3ip route add 192.168.233.2 dev wg0 # 添加Peer IP路由
iptables -t nat -A PREROUTING -p tcp --dport 8088 -j DNAT --to-destination 192.168.233.2:80
iptables -t nat -A PREROUTING -p udp --dport 8088 -j DNAT --to-destination 192.168.233.2:80注意不要添加 -A POSTROUTING -j MASQUERADE
主机B配置
1
2
3ip route add 192.168.233.1 dev wg0 # 添加Peer IP路由
ip ru add from 192.168.233.0/24 lookup 101
ip ro add default via 192.168.233.1 table 101
记得开启内核转发。
贴一个完整的配置文件,使用PostUp&PostDown自动添加/删除相应规则:
Peer端
1
2
3
4
5
6
7
8
9
10
11
12
13
14cat > /etc/wireguard/wg0.conf << EOF
[Interface]
Address = 192.168.233.2/32
PrivateKey = $wg_pri_key
Table = off
PostUp = ip route add 192.168.233.1 dev wg0; ip ru add from 192.168.233.0/24 lookup 101; ip ro add default via 192.168.233.1 table 101
PostDown = ip ru del from 192.168.233.0/24 lookup 101; ip ro del default via 192.168.233.1 table 101
[Peer]
PublicKey = $server_pub_key
AllowedIPs = 0.0.0.0/0
Endpoint = $server_ip:51820
PersistentKeepalive = 25
EOFServer端
1
2
3
4
5
6
7
8
9
10
11
12
13
14cat > /etc/wireguard/wg0.conf << EOF
[Interface]
Address = 192.168.233.1/32
PrivateKey = $wg_pri_key
ListenPort = 51820
Table = off
PostUp = ip route add 192.168.233.2 dev wg0; iptables -t nat -A PREROUTING -p tcp --dport 1000:50000 -j DNAT --to-destination 192.168.233.2:1000-50000; iptables -t nat -A PREROUTING -p udp --dport 1000:50000 -j DNAT --to-destination 192.168.233.2:1000-50000
PostDown = iptables -t nat -D PREROUTING -p tcp --dport 1000:50000 -j DNAT --to-destination 192.168.233.2:1000-50000; iptables -t nat -D PREROUTING -p udp --dport 1000:50000 -j DNAT --to-destination 192.168.233.2:1000-50000
[Peer]
PublicKey = $peer_pub_key
AllowedIPs = 0.0.0.0/0
EOF
隧道环境下 Iptables 转发保留源IP
http://example.com/2022/09/25/隧道环境下-Iptables-转发保留源IP/