Firewall functions: IPTABLES
NETWORK ADDRESS TRANSLATION WITH NAT TABLE
The NAT table (-t NAT) is used to modify packets addresses, source ports and destination. It has 3
default chains:
Is used to modify received packets through a network interface. It is used to
apply Destination NAT. The target is –j DNAT.
Is used to modify outgoing packets, i.e. those generated locally. Is used to
apply Source NAT. The target is –j SNAT.
This chain modifies packets before they are routed through a network
interface. It is used for Source NAT. The target is –j SNAT or –j
MASQUERADE for interfaces with dynamic IP.
For example:
Packets coming from sub-network 10.10.0.0/16 and addressed to sub-network 192.168.1.0/24
are transmitted with source IP 172.16.1.1:
iptables –t nat –A POSTROUTING –s 10.10.0.0/16 –d 192.168.1.0/24 –j SNAT --to-source 172.16.1.1
The parameter --to-source can be expressed only as --to
Outgoing packets on the ppp0 interface are transmitted with the IP associated with that interface:
iptables -t nat –A POSTROUTING –o ppp0 -j MASQUERADE
Packets addressed to the sub-network 192.168.1.0/24 have IP 172.16.1.1, while packets
addressed to sub-network 192.168.2.0/24 have IP 172.16.2.2:
iptables –t nat –A POSTROUTING –d 192.168.1.0/24 –j SNAT --to 172.16.1.1
iptables –t nat –A POSTROUTING –d 192.168.2.0/24 –j SNAT --to 172.16.2.2
Received packets and addressed to public address 85.34.166.21 are redirected to the private
address 10.10.1.195:
iptables –t nat –A PREROUTING –d 85.34.166.21 –j DNAT --to-destination 10.10.1.195
The parameter --to-destination can be expressed only as –to.
PORT FORWARDING
The target –j DNAT in the NAT table is often used to execute Port Forwarding and Load Balancing
functions, for example, TCP packets addressed to port 80 of the public address 85.34.166.21 are
redirected to port 8080 of the private address 10.10.1.195:
iptables –t nat –A PREROUTING –p tcp –d 85.34.166.21 --dport 80 –j DNAT --to 10.10.1.195:8080
In order to distribute http connections towards a group of internal servers:
iptables –t nat –A PREROUTING –p tcp –d 85.34.166.21 --dport 80 –j DNAT --to 10.10.1.195-10.10.1.198
With this command connections are re-addressed in round robin way towards servers 10.10.1.195,
10.10.1.196, 10.10.1.197 and 10.10.1.198. Notice that the connection fails when one of the
servers is not available.