2014年2月26日 星期三

Ubuntu Server 12.04 LTS 設定 iptables 實現 NAT Server


情境:實驗室的 AP 原本有一個實體 IP,由於想讓實驗室其他設備也可以有網路但是不要佔用實體 IP,所以想架一個 NAT Server

環境與 IP 配置:

NAT Server: Ubuntu 12.04.3 LTS (GNU/Linux 3.8.0-29-generic x86_64)
-eth0: 對外,有一實體 IP (140.xxx.xxx.xxx)
-eth1: 對內,有一虛擬 IP (10.0.10.1)
                  [不用 192.168.x.x 或 173.16.xxx.xxx 沒有特別原因]

AP: TP-LINK TL-WR940N
-WAN: 對外,連接至 NAT Server 10.0.10.2
-LAN: 對內,DHCP 派發至各設備 192.168.x.x


設定:

<NAT>

1. 設定 "/etc/network/interfaces":
# The primary network interface
#external interface
auto eth0
iface eth0 inet static
  address 140.xxx.xxx.xxx
netmask 255.255.255.0
network 140.xxx.254.0
broadcast 140.xxx.xxx.255
gateway 140.xxx.xxx.254
# dns-* options are implemented by the resolvconf package, if installed
dns-nameservers 140.xxx.1.110
dns-search nat

#internal interface
auto eth1
iface eth1 inet static
address 10.0.10.1
broadcast 10.0.10.255
netmask 255.255.255.0
network 10.0.10.0


2. 設定好網路,重新啟動網路:sudo /etc/init.d/networking restart

3. 假如沒有 iptables ,安裝方式: sudo apt-get install iptables

4. 清理 iptables:
iptables --flush
iptables --table nat --flush
iptables --delete
iptables --table nat --delete-chain

5. 設定 IP Forwarding and Masquerading
iptables --table nat --append POSTROUTING --out-interface eth0 -j MASQUERADE
iptables --append FORWARD --in-interface eth1 -j ACCEPT

6. 啟動 forwarding 服務
echo "1" > /proc/sys/net/ipv4/ip_forward

7. 因為每次重新開機,iptables 就會重置,所以要將 iptables 存起來
iptables-save

8. 為了要每次重新開機後能自動啟動 forwarding 服務
    所以要在 /etc/rc.local 或 /etc/rc.d/rc.local 寫入:
echo "1" > /proc/sys/net/ipv4/ip_forward

※ 步驟 3 ~ 4 需要 sudo 權限,可以 sudo bash 或寫成腳本後一次 sudo,就不用每次都多打 sudo

<AP>

#LAN
IP Address: 192.168.0.1
Subnet Mask: 255.255.255.0

#WAN
WAN Connectoin Type: Static IP
IP Address: 10.0.10.2
Subnet Mask: 255.255.255.0
Default Gateway: 10.0.10.1  (設為 NAT Server 的,才能夠讓 AP 將封包 router 到 NAT Server)
Primary DNS: 8.8.8.8 (有設定 DNS 才能解析域名)

這樣設定完後,不需重新啟動 AP 就可對外連線了!


進一步研究:Firewall 應該也是這樣架,原理應該差不多

參考資料:
1. NAT 原理 http://linux.vbird.org/linux_server/0250simple_firewall.php
2. NAT 設定 http://raypenglife.blogspot.tw/2006/03/linuxnat.html
3. Virtual IP Range
http://joechuang.wordpress.com/2008/10/27/%E4%BD%95%E8%AC%82%E5%AF%A6%E9%AB%94-ip-%E8%99%9B%E6%93%AC-ip/

沒有留言:

張貼留言