How to Setup NAT

From ITCwiki

Introduction

Network Address Translation (NAT) configuration with iptables firewall on Linux operating system. This system can act as gateway and provide Internet access to multiple hosts in Local Area Network (LAN) using a single public IP address.


Requirement

  • Two Network interface cards (NICs)
  • Iptables
  • Linux operating system


Network Configuration

Edit configuration file /etc/network/interfaces using text editor like nano and add eth0 and eth1 configuration.

  • WAN interface (eth0 - connection to ISP)

This is IP address, subnet mask, default gateway, and network address from your Internet Service Provider (ISP). If you get static IP address from your ISP follow step 1 and replace this addresses with your addresses otherwise go to step 2.

  • Step 1
   auto eth0
   iface eth0 inet static
   address 172.16.1.2
   netmask 255.255.255.0
   network 172.16.1.0 
   gateway 172.16.1.1
  • Step 2
  auto eth0
  iface eth0 inet dhcp 
  • LAN interface (eth1 - LAN connection and default gateway for local hosts)
   auto eth1
   iface eth1 inet static
   address 192.168.1.1
   netmask 255.255.255.0
   network 192.168.1.0	
  • DNS setup

Set up Domain Name System servers IP addresses by editing /etc/resolv.conf

nameserver 172.16.2.254 (replace this with your Domain Name System servers IP addresses)


NAT configuration with iptables

To delete existing rules from every iptables table, execute the following commands:

iptables -F
iptables -t nat -F
iptables -t mangle -F
  • Enable NAT:
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables -A FORWARD -i eth1 -j ACCEPT


Enable IP Forwarding

echo 1 > /proc/sys/net/ipv4/ip_forward


Local host configuration

Configure LAN hosts to access Internet through the gateway.

address 192.168.1.254
netmask: 255.255.255.0
dns  172.16.2.254
network 192.168.1.0 
gateway: 192.168.1.1