As Linux systems become popular, it may be used as gateway in small networks.
This is the case when iptables – standard Linux firewall will come in handy.
You can easily set up simple NAT-ed network with few simple command lines.
Basic syntax: iptables -t *table* *command*
Parameters:
-L – list rules
-F – flush all rules
-A – add rule
ex: iptables -t *table* -A *chain* *rule*
-D – delete rule
For example: iptables -t *table* -D *chain* *rule number*
To make current ruleset persistent, run:
[code]
/etc/init.d/iptables save
[/code]
So let’s imagine we have a simple netork (at home), with a Linux host, Internet gateway (cable modem or similar) and a PC host (running Windows for example).
Before setting up iptables, we need to allow Linux kernel to forward packets (Turned Off by default):
[code]
echo 1 > /proc/sys/net/ipv4/ip_forward
[/code]
For setting this automatically each boot, we need to uncomment 1 line in /etc/sysctl.conf :
net.ipv4.ip_forward=1
Assuming eth0 is connected to the ISP with IP-address 199.199.199.2. With default gateway 199.199.199.1 (ISP modem or similar).
eth1 is connected to PC workstation, which needs to access Internet via Linux host.
eth1 has IP-address 10.10.10.1.
PC workstation has one interface, with IP – 10.10.10.2
Setting up Internet access from 10.10.10.2:
[code]
iptables -t nat -A POSTROUTING -s 10.10.10.2 -o eth1 -j MASQUERADE
[/code]
Or, if you have multiple PC-s, use a subnet mask and allow access for the whole network:
[code]
iptables -t nat -A POSTROUTING -s 10.10.10.0/24 -o eth1 -j MASQUERADE
[/code]
Imagine Workstation PC has ftp server running on 10.10.10.2, port 21, and we need to allow it to be accessible from the Internet.
External address is – 199.199.199.2, ftp server IP – 10.10.10.2, TCP port – 21.
[code]
iptables -t nat -A PREROUTING –dst 199.199.199.2 -p tcp –dport 21 -j DNAT –to-destination 10.10.10.2
iptables -I FORWARD -i eth0 -o eth1 -d 10.10.10.2 -p tcp -m tcp –dport 21 -j ACCEPT
[/code]
First rule adds a network translation entry to NAT table(-t nat), it diverts packets, sent to port 21, from IP 199.199.199.2 to 10.10.10.2.
Second rule is a firewall access rule, that allows packets to pass.
To forward multiple ports at once, use colon – :
[code]
iptables -t nat -A PREROUTING –dst 199.199.199.2 -p tcp –dport 1024:65535 -j DNAT –to-destination 10.10.10.2
iptables -I FORWARD -i eth0 -o eth1 -d 10.10.10.2 -p tcp -m tcp –dport 1024:65535 -j ACCEPT
[/code]
This will forward all high ports from 199.199.199.2 to 10.10.10.2.
Sometimes you don’t want to expose port 21 to outer network, you can change the external port to any other port, for example – 4321, so accessing 199.199.199.2:4321 will be translated to 192.168.0.2:21.
To achieve this enter following commands:
[code]
iptables -t nat -A PREROUTING –dst 199.199.199.2 -p tcp -m tcp –dport 4321 -j DNAT –to-destination 10.10.10.2:21
iptables -I FORWARD -i eth0 -o eth1 -d 10.10.10.2 -p tcp -m tcp –dport 21 -j ACCEPT
[/code]
strong