Linux as a router

Posted on Aug 1, 2024

Overview

TODO: add the discription

Types of NAT

  • SNAT (Static NAT)
  • DNAT (Dinamic NAT)
  • PAT (Port Address Translation)

Network Interfaces Configuration

Router

  • enp0s3: 192.168.1.XX (Bridge)
  • enp0s8: 192.168.56.10 (Host-only Adapter)

Client

  • enp0s3: 192.168.56.120 (Host-only Adapter)

Configuring timezone

sudo timedatectl set-timezone Europe/Madrid
date

IP Forwarding

/etc/sysctl.conf

net.ipv4.ip_forward=1

Apply the changes and check.

sudo sysctl -p /etc/sysctl.conf
cat /proc/sys/net/ipv4/ip_forward

Configuring default iptables rules

Disable the UFW.

sudo systemctl stop ufw
sudo systemctl disable ufw
sudo systemctl status ufw

Install iptables-persistent which is a boot-time loader for netfilter.

sudo apt update  
sudo apt install -y iptables-persistent
sudo systemctl enable iptables
sudo systemctl start iptables
sudo systemctl status iptables

Implement the default iptables rules.

TODO: add your default iptables configuration here

Just because the router runs SSH, DNS, DHCP and NTP servers, need to allow access for 22/tcp, 53/udp, 67/udp and 123/udp ports respectively.

# SSH
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT

# DNS
-A INPUT -p udp -m udp --dport 53 -j ACCEPT

# DHCP
-A INPUT -p udp -m udp --dport 67 -j ACCEPT

# NTP
-A INPUT -p udp -m udp --dport 123 -j ACCEPT

Display the rules.

sudo iptables -nvL

Configuring NAT

sudo iptables -t nat -A POSTROUTING -o enp0s3 -j MASQUERADE

sudo iptables -A FORWARD -i enp0s3 -o enp0s8 -m state --state RELATED,ESTABLISHED -j ACCEPT

sudo iptables -A FORWARD -i enp0s8 -o enp0s3 -j ACCEPT
sudo sh -c 'iptables-save > /etc/iptables/rules.v4'

Display the rules.

sudo iptables -nvL

Configuring NTP, DHCP and DNS

dnsmasq runs as DHCP and DNS servers.

NTP Server

TODO: add a link to NTP article.

DHCP

dhcp-range=192.168.56.50.192.168.56.99,255.255.255.0
dhcp-option=option:router,192.168.56.10
dhcp-option=option:dns-server,192.168.56.10 # 8.8.8.8,8.8.4.4
dhcp-option=option:ntp-server,192.168.56.10

Check configuration syntax.

sudo dnsmasq --test
sudo systemctl restart dnsmasq

DNS

interface=enp0s8
listen-address=127.0.0.1,192.168.56.10

server=8.8.8.8
server=8.8.4.4

Check configuration syntax.

sudo dnsmasq --test
sudo systemctl restart dnsmasq

Configuring a client

The client resides within the private network (192.168.56.0/24). It has only one interface (Host-only Adapter, vboxnet0) and has a static 192.168.56.120 IP address.

/etc/netplan/50-cloud-init.yaml

network:
  ethernets:
    enp0s3:
      dhcp4: true
#    enp0s8:
#      addresses:
#      - 192.168.56.120/24
#      routes:
#      - to: default
#        via: 192.168.56.10
sudo netplan apply

Test.

ping 8.8.8.8
ping google.com

Note: make sure you have a line nameserver 8.8.8.8 in /etc/resolv.conf file.