2012年10月30日 星期二

One to One NAT

最近在做1:1 NAT的東西.......趕快把這些日子的心得po上來

首先分兩種case來討論,single wan interface 與 multiple wan interface
如果是只有一個wan,那只要用L3 iptables就可以實現,如果是多wan
那就要在加上L2 ebtables  與 advanced route ,iproute2 (也就是要做策略性路由policy route)才行

假設你的wan = eth1, ip address=172.17.21.87
而你有一個external ip address=172.17.21.88
                  private ip address=192.168.1.100

你要讓100走88出去

1.single wan:
首先先做ip alias
ifconfig eth1:1 172.17.21.88 netmask 255.255.255.0 up

再來是加一條DNAT rule 讓外來封包的目的位址為88可以NAT到100
iptables -t nat -I PREROUTING -d 172.17.21.88 -i eth1 -j DNAT --to-destination 192.168.1.100

再來是加一條SNAT rule 讓內部封包的來源位址為100可以走專屬88出去
iptables -t nat -I POSTROUTING -s 192.168.1.100 -o eth1 -j SNAT --to-source 172.17.21.88

2.multiple wan:

如果是multiple wan,假設你有兩條好了
 wan 1 = eth1 , ip address = 163.18.81.87 (假設這一條是default,也就是說routing走這條)
                      搭配subnet = 192.168.1.0/24
wan 2 = eth2 , ip address = 172.17.21.87
                       搭配subnet = 192.168.2.0/24
假設你有一個external ip address=172.17.21.88 ,private ip address=192.168.1.100
要讓.1.100走21.88出去(理論上1.100是走default route就是81.87出去)

首先先在iproute2裡面的rt_tables寫入一個routing tables名稱,這裡叫做pr_ABC,並給一個index 201好了
echo 201 pr_ABC >> /var/iproute2/rt_tables

然後在ebtables 加一條 為.1.100 做一個mark
ebtables -t broute -I BROUTING 1  -p ipv4 --ip-src 192.168.1.101 -j mark --mark-or 0x40000000 --mark-target CONTINUE
然後在ip rule上加一條mark值為所要的時候,這裡是4,就look up所屬route table,這裡是pr_ABC

ip rule add fwmark 0x40000000/0x40000000  table pr_ABC

最後再把這個table要走的route加上去,這裡假設是gateway是172.17.21.1

ip route add default  via 172.17.21.1 dev eth2 table pr_ABC

然後再按single wan的步驟

ifconfig eth2:1 172.17.21.88 netmask 255.255.255.0 up
iptables -t nat -I PREROUTING -d 172.17.21.88 -i eth2 -j DNAT --to-destination 192.168.1.100
iptables -t nat -I POSTROUTING -s 192.168.1.100 -o eth2 -j SNAT --to-source 172.17.21.88

這樣應該就搞定了,這裡要提醒一下mark值要注意,不要衝到別人。

附記:
檢查ebtables command:
ebtables -t broute -L

檢查iptables command:
iptables -t nat -nvL

檢查ip rule command:
ip rule show

檢查default route command:
ip route show

沒有留言:

張貼留言