Pages

NAT & IP forwarding on Linux gateway

Suppose we have only one publicly routable IP address assigned by our ISP and we want to be able to connect from the computers located in our internal LAN to the internet. Using private IP addresses is a common way to access the internet and internal shared resources
For the ease of explanation/understanding we’ll add some details in our scenario.

eth0 – the network interface card (NIC) connected to the ISP net
eth1 – the NIC connected to the internal LAN

As for the gateway there are some basic requirements:
- we’ll need at least 2 network interface cards (one/more connected to the internal LAN switch/hub, one/more connected to your ISP provider net) supported by your kernel
- support for networking, iptables and NAT in the kernel (for default 2.6/ 2.4 kernels on major Linux distributions this is enabled by default)
- enable IP forwarding (disabled by default on modern Linux distribution). To enable IP forwarding there are several ways to accomplish this. The common accepted method is through sysctl

Run the following command as root:
sysctl -w net.ipv4.ip_forward = 1
To make the change permanent we can add the following line in /etc/sysctl.conf
net.ipv4.ip_forward = 1
To enable the change made to the /etc/sysctl.conf file run
sysctl -p /etc/sysctl.conf
Finally, to allow hosts connected in the internal LAN to access internet resources configure the Linux gateway as:
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
or (if the IP address assigned by the ISP is xxx.xxx.xxx.xxx):
iptables -t nat -A POSTROUTING -o eth0 -j SNAT –-to-source xxx.xxx.xxx.xxx
I will focus future posts on other benefits of using iptables like allowing access from the internet to services located on hosts with private IP addresses located behind the Linux gateway and building stateful firewalls.

No comments: