Creating 1:1 NAT using iptables

Its a POC where I needed a 1:1 NAT using  Linux iptables. I used 2 Debian 11 OS for this and here’s the machine IP plans-

  • VM-1: IPTables/NAT Router- 123.45.67.5/24, 123.45.67.6/24 and 192.168.10.5/24
  • VM-2: Backend Server- 192.168.10.6/24 (this VM’s gateway will be 192.168.10.5

On VM-1

Uninstall nftables and its Dependencies

IPtables is being replaced by nftables starting with Debian 10 Buster. Debian 11 comes with nftables framework. To install iptables first we need uninstall nftables and its dependencies. SSH into your server and run the next commands:

# apt-get remove --auto-remove nftables
# apt-get purge nftables

Install IPtables in Debian 11

# apt-get update
# apt-get install iptables

Now we can check the iptables status and list rules. For list all the rules we will use option -L.

Run command:

# iptables -L -v

You will see the output:

As you see on the screenshot just installed iptables firewall and it works. But all chains (INPUT, FORWARD, OUTPUT) are set to ACCEPT, and we have no security rules configured.

Clear Iptables Rules: То clear iptables rules (open all ports) use the following command sequence:

# iptables -P INPUT ACCEPT
# iptables -F
# iptables -X

Once iptables is installed, we configure it as NAT gateway by allow ip_forward_v4 and route all traffic using iptables firewall rule. This is something, which I’m not going to cover.

Now, we’ll apply iptables one-to-one NAT rules-

iptables -t nat -A POSTROUTING -s 192.168.10.6 -o eth0 -j SNAT --to-source 123.45.67.6
iptables -t nat -A PREROUTING -d 123.45.67.6 -i eth0 -j DNAT --to-destination 192.168.10.6

Now save iptables rule permanently-

sudo sh -c '/sbin/iptables-save > /etc/iptables.up.rules'

On VM-2: Install an NGINX server

We’ll install an nginx server to test the status of the 1:1 Nat policy. Once installation is done, we’ll hit-

http://123.45.67.6

and nginx page will appear. it means, the backend server with the private ip 192.168.10.6 is 1:1 mapped with its public ip 123.45.67.6

Share

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.