Hi everyone,
This is the first entry of my blog on iptables. I will try to keep my writings around iptables however I have more to share other than iptables. Let’s start with a simple iptables example.
Network Topology
Assume that your office network has a linux router (e.g Linux Router1) and you have 2 PCs. You need to share network connection in Linux with those 2 PCs. Our sample network has several things to mention before going further. As you can also see from the topology we have the following networks:
Internal network: 192.168.200.0/24
Internal network Gateway: 192.168.200.1
This means you can have IP addresses in the range 192.168.200.1-192.168.200.254 in your internal network and all the clients are set to use 192.168.200.1 as default gateway. Now we will directly jump to the configuration of our Linux router1 .
Configuration of Linux router 1:
1) Enable IP forwarding
By default, your Linux distribution shouldn’t be allowing IP forwarding. First enable ip forwarding in order not to beat the air for hours.
#sysctl net.ipv4.ip_forward=1
2) Add iptables rules
There are two ways to enable NAT (Network Address Translation) which will allow our internal clients to appear as if their source address is 172.16.1.2 which is the external IP address of our Linux router.
a) Static maping:
#iptables -t nat -A POSTROUTING -s 192.168.200.0/24 -o eth1 -j SNAT –to 172.16.1.2
b) Masquerading:
#iptables -t nat -A POSTROUTING -s 192.168.200.0/24 -o eth1 -j MASQUERADE
Once you run any of these commands, you should be able to ping external sites from your internal PCs but why we have two different ways to do the same thing. As you can see command in method B doesn’t contain any IP of our external interface by which you can also use this method for interfaces which receive their IPs via DHCP protocol.
3) Make the changes persistent
- Open the file /etc/sysctl.conf and toggle the attribute “net.ipv4.ip_forward” into 1
- Either add one of the command in step 2 into /etc/rc.local to have it run at every reboot which is the dirty way or if you use a redhat flavoured distribution, use the following commands:
#chkconfig iptables on
#service iptables save
After these configurations, any client in your internal network should be able to reach external networks.
For the time being, it is all about this simple example. I will add more complex scenarios later on.
