Tuesday, July 06, 2004

linux :: nat, masquerading and port forwarding

NAT and port forwarding are all different terms but very related.

NAT is Network Address Translation. that allows me to connect to any external(public) ip directly. what happens is i first connect to my gateway, and it creates a connection to the public ip using some port. it now saves some mapping between the port used and my ip. the destination(public) ip sees the source ip of my gateway and replies back to it. The gateway sees that the reply is meant for me (using the port mapping) and forwards the packet to me.

In NAT MASQUERADE chain is required when you got a dynamic ip. **just a concept, don't understand the chain MASQUERADE

this concept is called ip masquerading. in linux i use iptables for this. i thought iptables is just a firewall to allow and deny packets in and out of your system. but its much more than it. almost complete routing powers.

how do we do it ??

first enable NAT. bole to bring you to the external net. bole to give you the feeling that you are no longer using a private ip, but a public ip.

$ iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to YOUR_GATEWAY_IP

so its simple. you can change the proxy ip of your connection. ie the ip where the requests seems to be coming from to the target public ip. but it has to be of your system.

someone tell me what does POSTROUTING/PREROUTING stands for ??

now the private ip must be allowed to send direct requests to public ips. that is done by using FORWARD chain. a simplest FORWARD rule is

$ iptables -t filters -A FORWARD -i eth0 -s ANY_PRIVATE_IP -j ACCEPT

this means that any request coming from ANY_PRIVATE_IP on eth0 is sent through eth1 (the other interface for web). NAT comes into picture during this FORWARDing.

Now comes a nice concept of port forwarding. "forwarding on a specific port"
that means whenever someone connects you on a specific port you can redirect the connection to some other machine on some other port.

$ iptables -t nat -A PREROUTING -i eth0 -p tcp -d 172.16.14.18 --dport 80 -j DNAT --to 192.168.36.200:80

** hope now i will be able to play age on empires on net with all this knowledge

NOTE : forwarding must be enabled in kernel
$ echo 1 > /proc/sys/net/ipv4/ip_forward

Assumptions :
eth0 is interface to private network
eth1 is interface to public network
no security concerns
some knowledge of iptables **if u dont have don't worry, my next post is about iptables :)

Refrences:
http://www.yolinux.com/TUTORIALS/LinuxTutorialIptablesNetworkGateway.html
http://www.aplawrence.com/Linux/iptables.html
http://www.linux.ie/articles/tutorials/firewall/
http://www.ibiblio.org/pub/Linux/docs/HOWTO/other-formats/html_single/Adv-Routing-HOWTO.html