Linux Firewall and Router with NAT
This example is assuming that you are running a Debain or Ubuntu based system. RHEL or other distros should be somewhat similar. You are going to want to have the following before actually setting up a router:
- 2 NICs ( or more )
- Static IPs
In this example we are actually going to show you how you might setup a system with three NICs. This would allow routing two separate local/private networks out to the internet. If you only have one local/private network you could exclude one of these nics from the commands and config snippets.
- Practially eveything in this guide will need root access so we are going to assume that you are running as root during this setup.
- Swap any interface names for the names of the interfaces on your system.
Potentially useful commands:
ip link show
ip a
ip route
DNS and DHCP - We have two separate guides showing how to setup DNS and DHCP here:
Kernel Forwarding
Immediately enable forwarding in the kernel:
echo 1 > /proc/sys/net/ipv4/ip_forward
Configure the change persistently:
vi /etc/sysctl.confnet.ipv4.ip_forward = 1
Apply change:
sysctl -p
Verify:
sysctl net.ipv4.ip_forward
IPTables Forwarding
Forward traffic between two local interfaces and one WAN interface:
iptables -A FORWARD -i enp0s8 -o enp0s3 -j ACCEPT
iptables -A FORWARD -i enp0s9 -o enp0s3 -j ACCEPT
iptables -A FORWARD -i enp0s3 -o enp0s8 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i enp0s3 -o enp0s9 -m state --state RELATED,ESTABLISHED -j ACCEPT
IPTables Masquerading
iptables -t nat -A POSTROUTING -o enp0s3 -j MASQUERADE
Exposing Ports
You can expose specific ports. This will make them reachable from outside your local/privage network. Any connection from the outside to the routers public IP will be forwarded to the specified private IP on the internal network. Any associated traffic for that same connection will be forwarded back.
iptables -t nat -A PREROUTING -p tcp --dport 8001 -j DNAT --to-destination 192.168.1.200:8080
iptables -A FORWARD -p tcp -d 192.168.1.200 --dport 8080 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
Blocking Outgoing Ports
You might also decide to block outgoing connections on all ports by default. You could allow outgoing connections only for ports that you specifically list as OK (ex. web / DNS ).
Persistence - Save IPTables Rules
Install this tool and run it to save the changes that you have made to IPTables:
apt update -y
apt install iptables-persistent
iptables-save > /etc/iptables/rules.v4
Static IPs on Interfaces
You can also find our other guide here:
Note that /etc/network/interfaces is no longer used.
You can setup static interfaces like this:
vi /etc/netplan/00-installer-config.yamlnetwork: version: 2 renderer: networkd ethernets: enp0s3: dhcp4: no addresses: [192.168.100.101/24] gateway4: 192.168.100.1 nameservers: addresses: - 192.168.100.1 - 8.8.8.8 enp0s8: dhcp4: no addresses: [172.16.0.1/24] enp0s9: dhcp4: no addresses: [172.16.1.1/24]