iptables 用於透明 NAT

iptables 用於透明 NAT

我正在嘗試透過另一個 Xen VM 透明地路由流量,如下所示:

-------      192.168.250.4          192.168.250.3     ---------
| VM1 |   <-----------------bridged---------------->  | VM2   |  <-----> Internet
-------                                               | with  |
                                                      | squid |
                                                      | proxy |
                                                      ---------

不要問為什麼,只是用 iptables 來進行實驗。我能夠透過 VM2 的 Squid 代理程式(透明模式)成功路由 HTTP 流量

iptables -t nat -A PREROUTING -p tcp --dport 80 –s ! 192.168.250.3 -j REDIRECT --to-port 3128

但我怎麼能簡單地通過所有其他流量呢?已經嘗試過此配置,但在嘗試從 VM1 ( 192.168.250.4)存取網際網路時出現「連線被拒絕」錯誤:

vm2:~# iptables -t nat -L -n
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination
# route outgoing udp traffic
DNAT       udp  -- !192.168.250.3        0.0.0.0/0           udp dpt:!80 to:192.168.250.3
# route outgoing tcp traffic
DNAT       tcp  -- !192.168.250.3        0.0.0.0/0           tcp dpt:!80 to:192.168.250.3
# this is the working squid rule
REDIRECT   tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:80 redir ports 3128

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination
# route incoming traffic
SNAT       all  --  0.0.0.0/0            192.168.250.3       to:192.168.250.4 

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

這裡有什麼問題嗎?我已經閱讀了很多教程,但大多數都無法正常工作...(順便說一句:/proc/sys/net/ipv4/ip_forward是 1)

答案1

不要使用 REDIRECT,而是嘗試 DNAT 和 SNAT。嘗試這個:

iptables -t nat -I PREROUTING -d 192.168.250.3 -j DNAT --到目的地 192.168.250.4 iptables -t nat -I POSTROUTING -s 192.168.250.4 -t nat -I POSTROUTING -s 192.168.250.4 -t nat -I POSTROUTING -s 192.168.250.4 -j SNAT1到來源 19.

答案2

我終於找到正確的方法:

NAT 傳出連線(VM1 --> Internet/Intranet)與來源重寫 (SNAT) 搭配使用:

iptables -t nat -A POSTROUTING -s 192.168.250.4 -j SNAT --to-source 192.168.2.125

其中192.168.2.125VM2 目前的外部 IP(必須不是是內部位址)。由於在我的例子中該 IP 是由 DHCP 分配的,因此必須更改規則以在動態 IP 上執行 SNAT。這是透過 MASQUERADE 指令完成的:

iptables -t nat -A POSTROUTING -s 192.168.250.4 -j MASQUERADE

最終的 iptables 配置現在如下所示(其他表/鏈為空):

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination
MASQUERADE  all  --  192.168.250.4        0.0.0.0/0

相關內容