To set up a Linux system as a router, you need to perform two key tasks: enable IP forwarding and configure iptables rules correctly. Below, I will walk you through the process step by step.
Step 1: Enabling IP Forwarding
-
Permanently Enable IP Forwarding To allow the Linux system to forward packets, you must first enable IP forwarding. This can be achieved by modifying the system configuration file. Edit the
/etc/sysctl.conffile and add the following lines:bashnet.ipv4.ip_forward = 1Save and close the file. This setting persists across reboots.
-
Temporarily Enable IP Forwarding If you wish to enable IP forwarding immediately without rebooting the system, use the following command:
bashsudo sysctl -w net.ipv4.ip_forward=1This is a temporary change and will be lost after a reboot.
Step 2: Configuring iptables Rules
After setting up IP forwarding, you need to configure the firewall to permit packet forwarding. This is done by establishing iptables rules.
-
Set NAT Forwarding Rules Assume your Linux system has two network interfaces: eth0 connected to the internet and eth1 connected to the internal network. Configure NAT (Network Address Translation) to allow the internal network to access the internet. Use the following iptables command:
bashsudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADEThis command masquerades the source IP address of all packets originating from eth1 and destined for the internet via eth0 to the IP address of eth0.
-
Allow Forwarded Packets to Pass Through Ensure that forwarding requests from the internal network to the external network are permitted. Set rules for the FORWARD chain:
bashsudo iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT sudo iptables -A FORWARD -i eth0 -o eth1 -m state --state ESTABLISHED,RELATED -j ACCEPTThe first command allows all packets from eth1 to eth0 to pass through. The second command permits response packets for established and related connections to flow back from eth0 to eth1.
-
Save iptables Rules After configuration, ensure the rules persist across reboots. You can use
iptables-saveandiptables-restorecommands or persistence tools likenetfilter-persistent.bashsudo apt-get install iptables-persistentAfter installation, save the rules with:
bashsudo netfilter-persistent save
Summary
After completing these steps, your Linux system should function as a router, forwarding traffic from the internal network to the internet. With this configuration, devices on the internal network can access the internet through the Linux router while maintaining network security.