Making your Linux Box Into a Router



 

 


Three things are required to make a Linux box into a router. From a hardware standpoint you need two NICs. Each NIC must be connected to a different network segment. Then you need both masquerading (NAT) and forwarding enabled. All of the network configuration except installing the hardware for a second NIC can be accomplished without rebooting.

IP Forwarding

This turns on IP Forwarding so that packets can be forwarded from one NIC to another, or in level 3 parlance, from one network or subnet to another. Usually from an internal network to an external network such as the Internet.

You can turn on IP Forwarding immediately by changing the content of the ip_forward file in the /proc filesystem from 0 to 1 using the command:

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

To make sure that IP Forwarding is persistent after a reboot, change one line in /etc/sysctl.conf from 0 to 1. Change the line:

net.ipv4.ip_forward = 0

to

net.ipv4.ip_forward = 1

Masquerading

Masquerading modifies the packets coming from the internal network so that the return address is the same as the external NIC. IP Tables maintains an internal table with the ID of the packet transmitted out and the true source address of the packet. When the remote host, such as cnn.com, sends the response packet it has the destination address of the external NIC. IP Tables replaces that destination address with that of the true source of the original packet on the internal network and sends it on to that host.

Configure IPTables for masquerading with the following command:

iptables -t nat -A POSTROUTING -s 192.168.0.0/255.255.255.0 -j MASQUERADE

This command adds a line to the postrouting chain of the NAT table in IP Tables which causes all packets from the 192.168.0.0 class C subnet to be masqueraded when they are passed to the other, external subnet.

In Fedora or any other Red Hat based distribution be sure to also issue the following command which saves the change you just made.

service iptables save

For other distributions, use the appropriate command.

You now have configured your Linux box as a router.