Linux iptables NAT Step by Step Configuration With Diagram


IPTABLES NAT (Network Address Translator)
IP Forwarding : Also known as Internet routing. Send the data from one network(10.0.0.0 eth1) to another network(192.168.1.0 eth0).
In the Routing server.
eth0 -act as public network
eth1 -act as private network 

By Default Forward chain for Local Private network is disable. To enable in iptables.
# iptables -I FORWARD -s 10.0.1.0/24 -j ACCEPT
# iptables -I FORWARD -d 10.0.1.0/24 -j ACCEPT
It will reflect in iptables
target prot opt source destination
ACCEPT all -- anywhere 10.0.1.0/24
ACCEPT all -- 10.0.1.0/24 anywhere


In the above Diagram – Rectangular represent as a server.
Check List For configure Iptables routing 
1)Enable IP Forwarding in Local Network in iptables.
2)Enable IP Forwarding in systcl.conf
3)Add the iptables NAT MASQUERADE.
4)Client machine add the gateway and dns entry in /etc/resolve.conf

1.1) #iptables –t nat –I POSTROUTING –s 10.0.0.0/24 –o eth0 –j MASQUERADE
1.2 #iptables –t nat –I POSTROURTING –s 10.0.0.2 –J SNAT –to-source 192.168.1.240
NOTE: Difference between 1.1 & 1.2 is 
1.1)Source address become any one of the public ip.
1.2)Source address has been specified as 192.168.1.238

2.1)#iptables –t nat –I PREROUTING –p tcp –dport 80 –d 192.168.1.240 –j DNAT –to 10.0.0.2
2.2)#iptables –t nat –I PREROUTING –p tcp –dport 8080 –d 192.168.1.240 –j DNAT –to 10.0.0.2:80
2.1 & 2.2 is port forwarding.
2.3)#iptables –t nat –I PREROUTING –d 192.168.1.238 –j DNAT –to-destionation 10.0.0.2
2.3) what are the service request comes to the 192.168.1.238 it will automatically redirect to the 10.0.0.2.

From the Picture Point 2 & From the table 2.1,2.2 and 2.3.
when client hits 192.168.1.X IP it will redirect 10.0.0.0.
Simple Iptables Chain For Accept http(80) and drop ssh(22) ports.
Using netstat -tulpn command we can find out port number and their corresponding services.

Reference :
1. Step-By-Step Configuration of NAT with iptables
2. Linux NAT in Four Steps using iptables

How to Delete Iptables Chain.
#iptables -D INPUT 1
#iptables -D POSTROUTING 1
#iptables -D <CHAIN-POLICY> chain-number
#iptables -D <INPUT/OUTPUT/FORWARD/POSTROUTING/PREROUTING> chain-number

Related post