IP forwarding on Linux

Let’s assume your receiving packets from the LAN on device eth0 and want to send them over the WAN on device eth1. There are a few steps involved to doing this which are outlined below:

Enabling this feature

You can also see if it’s already turned on or off. A value of 1 indicates it is turned on and a value of 0 indicates it is turned off.

$ cat /proc/sys/net/ipv4/ip_forward
1

You can set this feature on or off with echo. Below we’re turning this feature on:

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

Setting up IP tables

Next we need to make sure we use IP masquerading for all packets going out of the WAN interface. This is because there is address translation needed between both devices. We also need to tell IP tables what device we should forward packets from, in this case eth0.

$ iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE
$ iptables -A FORWARD -i eth0 -j ACCEPT

That’s it. Now things should start to work.

Routing

One final point to mention is that the client that is behind all of this setup may need specific routing to tell it to send packets via your new forwarding Linux device.

If you had 2 of these (let’s say for a primary and secondary line both forwarding packets via their own separate WAN interfaces), you would need something like this:

$ ip route add 8.8.8.8 via 192.168.2.1 dev eth1
$ ip route add 8.8.4.4 via 192.168.12.1 dev eth2

You can find out how Linux will route traffic to the address you care about to ensure this worked:

$ ip route get 8.8.8.8
8.8.8.8 via 192.168.2.1 dev eth1  src 192.168.1.20 
    cache

What this does, is route packets for 8.8.8.8 to the first Linux device that’s forwarding packets which is connected to your eth1 (and has an IP address of 192.168.2.1) and the a similar set up for 8.8.4.4 via your second device connected to eth2.