Using a Linux box as a router
The purpose was to have a Linux box act as a simple router.
Devices:
- Device1, configured with a 10.10.10.10 IP.
- Device2, which will be our router, configured with 2 interfaces: 10.10.10.1 and 192.168.1.245.
- Device3, which is my Internet-facing router, with an internal IP of 192.168.1.1
The router is going to be Device2, which is a Linux (Ubuntu Server 20.04) box, that has 2 interfaces, enp0s4 and enp0s5, each configured in a different network:
ifconfig | grep -A1 enp
enp0s4: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.1.245 netmask 255.255.255.0 broadcast 192.168.1.255
--
enp0s5: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 10.10.10.1 netmask 255.255.255.0 broadcast 10.10.10.255
Commands to run on Device2:
- Enable forwarding:
echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
sysctl --system
- Create iptables rules to forward/NAT the traffic from the 10.x network to the 192.x network:
iptables -t nat -A POSTROUTING -o enp0s4 -j MASQUERADE
iptables -A FORWARD -i enp0s5 -o enp0s4 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i enp0s5 -o enp0s4 -j ACCEPT
At a high level, these rules accept traffic from the enp0s5 interface, apply a NAT, then send the traffic out the enp0s4 interface.
Rules explained in more detail:
iptables -t nat -A POSTROUTING -o enp0s4 -j MASQUERADE
-t nat
Use this table (nat)-A POSTGROUTING
Append rule(s) to end of the selected chain, in this case the nat chain-o enp0s4
Egress interface, in this case enp0s4-j MASQUERADE
Jump to the target of the rule, if we match, in this case MASQUERADE
iptables -A FORWARD -i enp0s5 -o enp0s4 -m state --state RELATED,ESTABLISHED -j ACCEPT
-A FORWARD
Append rule(s) to end of the FORWARD chain-i enp0s5
Ingress interface is enp0s5-m state
Match to use an extension module that tests for a specific property (states that follow)--state RELATED,ESTABLISHED
Packets that are part of an already established connection-j ACCEPT
Jump to the target of the rule, if we match, in this case ACCEPT
iptables -A FORWARD -i enp0s5 -o enp0s4 -j ACCEPT
-A FORWARD
Append rule(s) to end of the FORWARD chain-i enp0s5
Ingress interface is enp0s5-o enp0s4
Egress interface is enp0s4-j ACCEPT
Jump to the target of the rule, if we match, in this case ACCEPT
To make the above rules permanent:
sudo /sbin/iptables-save > /etc/iptables/rules.v4
If we want to view connections after this is implemented, we need the conntrack
command to be installed:
sudo apt-get install -y conntrack
The NAT'd connection entry for a ping from our 10.10.10.10 box, to www.yahoo.com (74.6.231.20):
# conntrack -L -j
icmp 1 29 src=10.10.10.10 dst=74.6.231.20 type=8 code=0 id=26398 src=74.6.231.20 dst=192.168.1.245 type=0 code=0 id=26398 mark=0 use=1
Note: Must be root to use the conntrack
command.
References:
CenOS - IPTables https://wiki.centos.org/HowTos/Network/IPTables
Tecmint - Setup Linux as a router https://www.tecmint.com/setup-linux-as-router/