Turning a PC into a gateway

During a project, I ended up needing to make a PC that was on 2 subnets into a gateway. This, of course, led to a lot of packet tracing and questions on how to set this up properly.

nw-diagram-lan-gw

As it can be seen in the diagram above, 10.0.0.5 is trying to access the Internet (Google) through the PC located on 10.0.0.1 and 192.168.0.100 . The PC is DHCP server also and it is the gateway for the 10.0.0.0/24 network. Its initial purpose was not to forward packages further to the 192.168.0.0/24 gateway, located at 192.168.0.1, but that has changed.

To do this, the following steps are to be followed:

  1. Enable forwarding
  2. Set up iptables rules
  3. Set up DNS

Enable forwarding

Can be done in one line by:

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

Normally, forwarding is now being handled. Packets from 10.0.0.5 destined for the Internet are getting forwarded to their destination, but responses are not making back to the source.

no-answer

This can be seen by having the client PC (10.0.0.5) pinging an external internet address (e.g. 8.8.8.8) by inspecting the packets on both interfaces from our soon-to-be gateway (10.0.0.1).

Set up iptables rules

Custom iptables rules are required to instruct the gateway to do simple NAT (network address translation) – basically what every home router does, forwarding packets from LAN clients to the Internet by using the routers external facing IP address. The rules are the following, where $LAN and $WAN are to be replaced with the interface facing the network in the variable (e,g, instead of LAN, we have eth0 and instead of $WAN we have eth1).

# Allow established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Masquerade.
iptables -t nat -A POSTROUTING -o $WAN -j MASQUERADE
# fowarding
iptables -A FORWARD -i $WAN -o $LAN -m state --state RELATED,ESTABLISHED -j ACCEPT
# Allow outgoing connections from the LAN side.
iptables -A FORWARD -i $LAN -o $WAN -j ACCEPT

Note that iptables rules are not preserved over reboots and must be added again after the machine has been rebooted.

Set up DNS

Traffic is now being routed but the new gateway does not resolves names and clients from 10.0.0.0/24 will not be able to use domain names. The simples way to make this work is by installing dnsmasq and leaving it to its default settings.

sudo apt-get install dnsmasq

sudo service dnsmasq start

Summing up

It can get annoying when troubleshooting such setup. Tcpdump and/or Wireshark can prove very useful in understanding how packets are being transmitted and received. I have gathered the iptables from above and the line that enables forwarding in a bash script, that should be run at startup so that the modifications are being redone after every reboot. The script can be found here , and make sure to modify the WAN and LAN variables according to your environment.

Print Friendly, PDF & Email