Tuesday 1 June 2010

iptables in NAT (MASQUERADE, SNAT, DNAT)

Assumption in the case to config NAT
eth0 connection to external network
eth1 connection to internal network
Enable ip route
echo 1 > /proc/sys/net/ipv4/ip_forward

Set up IP FORWARDing and Masquerading
(this is the most simple method to config NAT for internal users)
[root@linux ~]#iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
[root@linux ~]#iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
[root@linux ~]#iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT

For this case using MASQUERADE, there is alternative
[root@linux ~]#iptables -t nat -A POSTROUTING -o ppp0 -j MASQUERADE
(suppose ppp0 is ready for external network)

More information (Just sample for your reference):
SNAT
Example: Internal users access external network with private IP
[root@linux ~]#iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to 202.175.12.34
(Map source addresses to 202.175.12.34)

[root@linux ~]#iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to 202.175.12.34-202.175.12.39
(Map source addresses to the range of 202.175.12.34~202.175.12.39)

DNAT
Example: External users access internal server
[root@linux ~]# iptables -t nat -A PREROUTING -i eth0 -j DNAT --to 192.168.1.10
[root@linux ~]# iptables -t nat -A PREROUTING -i eth0 -j DNAT --to 192.168.1.5-192.168.1.10
[root@linux ~]# iptables -t nat -A PREROUTING -p tcp -i eth0 --dport 80 -j DNAT --to 192.168.1.10:80
[root@linux ~]# iptables -t nat -A PREROUTING -p tcp -i eth0 --dport 80 -j DNAT --to 192.168.1.10:8080
[root@linux ~]# iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8080

No comments:

Post a Comment