Image

Knowledge base → Setting up NAT in Linux Debian (Internet on a local network)

[Virtual servers]
Date of publication: 11.03.2024

In order to use the server as a router, we will need to configure NAT. In this guide, the server has 2 physical ports:

  • enp3s0 - Internet (192.168.1.12)
  • enp1s0 - Local network (100.100.100.1)

1. enp1s0 configuration

more /etc/network/interfaces
auto enp1s0
     iface enp1s0 inet static
     address 100.100.100.1
     netmask 255.255.255.0

2. NAT setup

apt install iptables
modprobe iptable_nat
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -o enp3s0 -j MASQUERADE
iptables -A FORWARD -i enp1s0 -j ACCEPT

2.1 Configuring a local gateway as a DNS server

In our case, we use forwarding to DNS server 8.8.8.8

iptables -t nat -A PREROUTING -p tcp --dport 53 -j DNAT --to 8.8.8.8:53
iptables -t nat -A PREROUTING -p udp --dport 53 -j DNAT --to 8.8.8.8:53
iptables -t nat -A POSTROUTING -j MASQUERADE

2.2 Save module settings

nano /etc/modules
iptable_nat

2.3 Save traffic settings

nano /etc/sysctl.conf
net.ipv4.ip_forward=1

2.4 Save iptables settings

apt install iptables-persistent
iptables-save > /etc/iptables/rules.v4

3. Checking the work

Since we have the Internet on one port, and a local network on the second, all devices connected to the local network port should have access to the Internet. Sometimes it happens that the gateway itself is not configured as a DNS server and the correct check will be by ping the external IP address.

For example:

ping 8.8.8.8

Exchange of packets from 8.8.8.8 to 32 bytes of data:
Response from 8.8.8.8: number of bytes=32 time=23ms TTL=59
Response from 8.8.8.8: number of bytes=32 time=23ms TTL=59

Or

ping 1.1.1.1

Exchange of packets from 1.1.1.1 to 32 bytes of data:
Answer from 1.1.1.1: number of bytes=32 time=4ms TTL=57
Answer from 1.1.1.1: number of bytes=32 time=4ms TTL=57

As we can see, everything works correctly. Now our server acts as a router.





No Comments Yet