Jephe Wu - http://linuxtechres.blogspot.com
Objective: on a single NIC server, configure snat and dnat to totally change source ip and destination ip. When ssh-ing into ip 10.0.0.188 at port 222, 10.0.0.200->10.0.0.188:222 then it will NAT the traffic as 10.0.0.189->10.0.0.63:22
Environment: CentOS 5.4 server with single NIC, eth0: 10.0.0.184, eth0:0 10.0.0.188, eth0:1 10.0.0.189
Steps:
1. Enable IP forwarding - most important, otherwise everything will fail. Even on single NIC server, as long as you are using snat and dnat
ehco 1 > /proc/sys/net/ipv4/ip_forward
2. /etc/sysconfig/iptables
*nat
-A PREROUTING -s 10.0.0.0/24 -d 10.0.0.188 -p tcp -j DNAT --dport 222 --to-destination 10.0.0.63:22
-A POSTROUTING -s 10.0.0.0/24 -d 10.0.0.63 -p tcp --dport 22 -j SNAT --to-source 10.0.0.189
COMMIT
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:RH-Firewall-1-INPUT - [0:0]
-A INPUT -j RH-Firewall-1-INPUT
-A FORWARD -j RH-Firewall-1-INPUT
-A RH-Firewall-1-INPUT -i lo -j ACCEPT
-A RH-Firewall-1-INPUT -p icmp --icmp-type any -j ACCEPT
-A RH-Firewall-1-INPUT -p 50 -j ACCEPT
-A RH-Firewall-1-INPUT -p 51 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp --dport 5353 -d 224.0.0.251 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp -s 10.0.0.0/24 -d 10.0.0.63 --dport 22 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 443 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited
COMMIT
3. other usages for iptables NAT
If you are going to use tomcat to serve port 80, you can't do so without running tomcat as root, but you can use iptables to listen at port 80 while keeping tomcat to listen at unprivileged port 8080:
iptables -t nat -A PREROUTING -d 10.0.5.2 -p tcp -j DNAT --dport 80 --to-destination 10.0.5.2:8080
or
iptables -t nat -A PREROUTING -d 10.0.5.2 -p tcp --dport 80 -j REDIRECT --to-ports 8080
4. Notes:
a. only after prerouting , it will be tested by forwarding rules.
b. iptables package check sequence:
http://www.linuxhomenetworking.com/wiki/index.php/Quick_HOWTO_:_Ch14_:_Linux_Firewalls_Using_iptables