Using IP tables for NAT

2011-02-25

In my backup folder, I found, among a lot of random junk, a configuration for IPTables, which gives a Linux machine NAT functionality. I have previously used this setup when I used a Debian machine as a router. This requires a PC with two NICs and a distribution of Linux with IPTables installed. One NIC will be configured to connect to your ISP and the other will be configured to your internal network. One suggestion is that you configure a DHCP server on the internal network to easily connect more computers through a switch. IP-forwardning must be enabled for the machine to be able to forward your traffic. You can enable it through the following command in Debian:

echo 1 > /proc/sys/net/ipv4/ip_forward

However, this is a temporary solution that will disappear if the machine is rebooted, but how often do you really need to reboot a Debian machine? For a more permanent solution, you can in the file “/etc/sysctl.conf”, uncomment the parameter “net.ipv4.ip_forward=1”. Then the forwarding will always be activated at startup. Here’s the script that you need to to run, preferably at startup, to enable NAT:

#!/bin/bash
#Defining network cards
WAN=eth0
LAN=eth1

#Removing old rules.
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X

#Default rules.
iptables -P INPUT DROP
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT

#Convert internal addresses to one external.
iptables -t nat -A POSTROUTING -o $WAN -j MASQUERADE

#Accept return traffic that was initiated on the router.
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

#Accept traffic to the router from the internal network.
iptables -A INPUT -i $LAN -j ACCEPT