Setting up Linux Box as a Router with NAT support
Setup on Router
First, the box should have two interfaces for simplicity (we can bind both IP address to one, yet I have not tried this)
In the example below, we will have two interface:
enp0s3 ad enp0s8, with enp0s3 as the interface towards internet, and enp0s8 towards intranet
Configure IP interfaces
Latest Ubuntu uses netplan. Configuration file is : /etc/netplan/*.yaml
network:
version: 2
renderer: NetworkManager
ethernets:
enp0s8:
dhcp4: no
addresses:
- 192.168.1.1/24
Then apply the setting
$ sudo netplan apply
Enable IP Forward
Enable IP forwarding in configuration file: /etc/sysctl.conf
net.ipv4.ip_forward=1
Configure IP tables
Configure IP tables to enable NAT
$ sudo iptables -F # flush the default tables
$ sudo iptables -t nat -F # flush the nat table
$ sudo iptables -P INPUT ACCEPT # default behavior. just in case
$ sudo iptables -P FORWARD ACCEPT # default behavior. just in case
$ sudo iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o enp0s3 -j MASQUERADE
$ sudo iptables -t nat -L # verify configuration
The last command is the actual command that enables nat.
IPTable Persistence
$ sudo apt install iptables-persistent
$ sudo service netfilter-persistent status # check the status of the service
Setup on Client
On the client side, the box has only one interface (enp0s3), which connects it to the intranet.
Configure IP interfaces
Configuration file: /etc/netplan/*.yaml
network:
version: 2
renderer: NetworkManager
ethernets:
enp0s3:
dhcp4: no
addresses:
- 192.168.1.100/24
gateway4: 192.168.1.1
nameservers:
addresses:
- <dns address assigned by your ISP>
- 8.8.8.8 # or well known dns servers. Please note # does not work in yaml
Verify your setup
To verify, just do the following on client:
$ ping www.bing.com
and ping response should be observed from server.