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. Add the following command to your /etc/sysconfig/iptables file in the POSTROUTING section of the NAT table. Be sure to use the Network IP address CIDR notation for your own network.

-A POSTROUTING -s 192.168.0.0/24 -j MASQUERADE

We also need to add a line to the FORWARD chain of the FILTER table. This assumes that the internal network interface, specified using the -i option, is enp2s0. You would of course use the NIC name appropriate for your host.

-A FORWARD -i enp2s0 -j ACCEPT

Save the revised file and activate the change using the following command.

cd /etc/sysconfig/ ; iptables-restore iptables

This line in the postrouting chain of the NAT table in IP Tables causes all packets from the 192.168.0.0 subnet to be masqueraded when they are passed to the external subnet.

You now have configured your Linux box as a router.





Leave a Reply