Friday, April 6, 2012

Another blog post on HOWTO PORT FORWARD with IPTABLES #in #sysadmin


My application (puppetmaster) is behind a firewall and there is no direct access from the internet to the server.  So, it was necessary to configure a host on the DMZ to act as a proxy.  This was accomplished using IPTABLES to do a forward and reverse NAT. Iptables version: v1.3.5.


This first step is very important.  Without doing this, you will scratch your head wondering why your perfectly formed IPTABLES rules don't get the job done.  


Step 1: enable ip forwarding on the system (if it hasn't already been done):
echo 1 > /proc/sys/net/ipv4/ip_forward
 Step 2: configure IPTABLES (on CentOS, add these lines to your /etc/sysconfig/iptables file and restart iptables):
iptables -A PREROUTING -p tcp -s *route_only_for_this_ip* -d *router_ip* --dport *router_port* -j DNAT --to *destination_ip*:*destination_port*
iptables -A POSTROUTING -o eth0 -d *destination_ip* -j SNAT --to-source *router_ip*
A few definitions for the above:


--dport 8140 -- the default puppetmaster listening port
*route_only_for_this_ip* -- if you want to limit incoming IPs to a single known IP (not required)
*router_port* -- which port incoming requests are accepted on.  This does not have to be the same as the destination_port.  No one should rely on security through obscurity, but using it is a best practice.
*router_ip* -- the host doing the routing (the one running these rules!)
*destination_ip* -- the server that will actually be servicing the request
*destination_port* -- the port on the above server that will accept requests


Now here's an important note.  If you input those rules and run a simple:
iptables -L
Chain INPUT (policy ACCEPT)target     prot opt source               destination         
Chain FORWARD (policy ACCEPT)target     prot opt source               destination         
Chain OUTPUT (policy ACCEPT)target     prot opt source               destination      


What?  Your rules are NOT in your ouptut!  To see them, you need to specify the nat table, like this: 
iptables -L -t nat
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination      
DNAT       tcp  --  anywhere             router_ip                tcp dpt:router_port to:destination_ip:destination_port
Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination      
SNAT       all  --  anywhere             destination_ip      to:router_ip
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         









Resources:


http://www.linuxquestions.org/questions/linux-networking-3/iptables-port-forwarding-599401/
http://www.whatismyip.com -- love this tool.  From a command line using wget or curl goto: http://automation.whatismyip.com/n09230945.asp
http://www.linuxquestions.org/questions/linux-software-2/iptables-list-does-not-show-pre-or-postrouting-rules-785184/