Search This Blog

Saturday 3 July 2010

Linux iptables Basic Commands-Linux as a router






iptables is the inbuilt firewall in Linux kernel. It can be used for allowing and blocking the traffic passing trough the system.


Configuring iptables to work Linux as a router:

For Linux to work as a router, there should be two NICs normally.

Here we implement the router with below network settings with two NICs

eth1 -> 192.168.15.100, net mask =255.255.255.0, Gateway: 192.168.15.1 -> connected with modem and hence internet, No other system in my LAN des not have direct acces to this modem.

eth0 -> 192.168.1.1, netmask 255.255.255.0 connected with LAN, All system in the LAN has to communicate to internet trough this host.


For Linux to act as route, 2 settings must be done.

1. IP forwarding: This can be achieved temporary by setting the status to 1 as below.

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

For making it permanet and active on next reboot, we have to enable it by editing /etc/sysctl.conf and edit as below:
net.ipv4.ip_forward = 1
To enable this chage, run the command
sysctl -p /etc/sysctl

2. Adding iptables entry for packets routing:

Before you add any entry, make sure iptables service is running. 
[root@shimna /]# chkconfig --list|grep iptables
iptables        0:off   1:off   2:on    3:on    4:on    5:on    6:off
If its on yet on service level 2-5, make it on using below command.
[root@shimna /]# chkconfig iptables on

Make sure you don't have any unwanted iptables running currently

[root@shimna /]# iptables -nvL

If any unwanted iptables are running, flush all the rules using -F option and save the same.
[root@shimna /]# iptables -F
[root@shimna scripts]# service iptables save
iptables: Saving firewall rules to /etc/sysconfig/iptables:[  OK  ]
[root@shimna scripts]#

Now you can add the entry to route the packets:

[root@shimna scripts]# iptables -t nat -A POSTROUTING -o eth1 -s 192.168.1.0/24 -j MASQUERADE

The above setting can be verified by below command:

[root@shimna scripts]# iptables -nvL -t nat
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain POSTROUTING (policy ACCEPT 19 packets, 1554 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 MASQUERADE  all  --  *      eth1    192.168.1.0/24       0.0.0.0/0

Chain OUTPUT (policy ACCEPT 19 packets, 1554 bytes)
 pkts bytes target     prot opt in     out     source               destination


Now your Linux system is ready to act as a router. You can configure all other system the LAN gate way as the Linux host LAN IP.

No comments:

Post a Comment