原標題:實戰經驗:Linux Source NAT在Ping場景下的應用
有時候,有這樣的一種需求:
需要修改IP數據包中的源地址,比如,從某一個主機發送Ping包到另一個主機,需要修改源地址為另一個源(通常,發出Ping請求的主機有多個網卡地址)。
為了解決這一需求,Linux下的netfilter組件中有個Source NAT的功能,可以修改IP數據包中的源地址。
此功能實際上是通過iptables在POSTROUTING鏈中添加一條規則,此規則在數據包被最終發送出去之前被應用。下面是一個實例:
主機A網絡配置:
eth0: 192.168.10.10
eth1: 172.18.10.10
主機B:
eth0: 192.168.10.1
1) 第一張場景
從A發送Ping請求到B:
# ping 192.168.10.1
通過WireShark抓包可以知道,Ping包中的源地址為192.168.10.10(默認Ping請求從eth0出來),目的地址是192.168.10.1。
2) 第二種場景
從A發送Ping請求到B,并使用-I選項:
# ping 192.168.10.1 -I 172.18.10.10
在此場景下,這里指定了-I選項,表明指定源地址為172.18.10.10。
所以,Ping請求包中的源地址變為172.18.10.10,目的地址不變,依然為192.168.10.1。
問題來了:怎樣在第二種場景中(在指定-I選項的情況下)將源地址修改為192.168.10.10?
解決方法:添加Source NAT規則。具體步驟如下:
添加規則:
# iptables -t nat -A POSTROUTING -o eth0 -j SNAT –to 192.168.10.10
添加完上述規則后,再次執行ping 192.168.10.1 -I 172.18.10.10,可以通過抓包發現Ping請求中的源地址已經由172.18.10.10修改為192.168.10.10。
備注:
如果想刪除上面添加的Source NAT規則,可以執行如下指令刪除:
刪除規則:
# iptables -t nat -A POSTROUTING -o eth0 -j SNAT –to 192.168.10.10
查看規則:
# iptables -nvL -t nat
參考資料:
以下內容來自netfilter官網幫助文檔,也記錄在這里留作參考:
1) Source NAT
You want to do Source NAT; change the source address of connections to something different. This is done in the POSTROUTING chain, just before it is finally sent out; this is an important detail, since it means that anything else on the Linux box itself (routing, packet filtering) will see the packet unchanged. It also means that the `-o’ (outgoing interface) option can be used.
Source NAT is specified using `-j SNAT’, and the `–to-source’ option specifies an IP address, a range of IP addresses, and an optional port or range of ports (for UDP and TCP protocols only).
Masquerading
There is a specialized case of Source NAT called masquerading: it should only be used for dynamically-assigned IP addresses, such as standard dialups (for static IP addresses, use SNAT above).
You don’t need to put in the source address explicitly with masquerading: it will use the source address of the interface the packet is going out from. But more importantly, if the link goes down, the connections (which are now lost anyway) are forgotten, meaning fewer glitches when connection comes back up with a new IP address.
2) Destination NAT
This is done in the PREROUTING chain, just as the packet comes in; this means that anything else on the Linux box itself (routing, packet filtering) will see the packet going to its `real’ destination. It also means that the `-i’ (incoming interface) option can be used.
Destination NAT is specified using `-j DNAT’, and the `–to-destination’ option specifies an IP address, a range of IP addresses, and an optional port or range of ports (for UDP and TCP protocols only).
Redirection
There is a specialized case of Destination NAT called redirection: it is a simple convenience which is exactly equivalent to doing DNAT to the address of the incoming interface.
Note that squid needs to be configured to know it’s a transparent proxy!返回搜狐,查看更多
責任編輯: