Setup secure Linux gateway using iptables

Nowadays, you might have a network of computers linked as an intranet and you want to let them read/reply e-mail. So you have to connect them to Internet by something. The key component is a router aka gateway. You might just buy an ADSL router  with RJ45 port. Anyway, in case of you have too many machines, ADSL router maybe unable to handle all requests successfully due to design limitation. For example, ZyXEL Prestige 650-R can only handle 1024 concurrent connections. If the router has 1024 concurrent connections, next connection will be dropped silently.

To prevent this problem, you have to filter out some machines or some services to access Internet through that router. Most router has built-in firewall and IP filtering capabilities. However, the built-in firewall may not serve complex rules. I like to use hardware router, but advanced features come with expensive price. If you have an unused machine or already setup a Linux server to run web server and/or mail server, you can setup it to be advanced Internet gateway easily. All you might have is just iptables. To setup a Linux gateway using iptables, follow below procedure.

  1. Add following line to /etc/sysctl.conf and run sysctl -p to activate setting
    net.ipv4.ip_forward = 1
  2. Edit /etc/sysconfig/iptables as follow
    *nat
    :PREROUTING ACCEPT [0:0]
    :POSTROUTING ACCEPT [0:0]
    :OUTPUT ACCEPT [0:0]
    -A POSTROUTING -o eth0 -j MASQUERADE
    COMMIT
    
    *filter
    :INPUT ACCEPT [0:0]
    :FORWARD ACCEPT [0:0]
    :OUTPUT ACCEPT [0:0]
    
    # add rules here
    
    -A INPUT -i lo -j ACCEPT
    -A INPUT -i eth0 -j ACCEPT
    COMMIT
  3. Restart iptables
    iptables -F
    iptables -X
    service iptables restart

That’s enough for just a plain gateway. Anyway, you might be interesting to disallow some machines to run some services, e.g., machine A to listen to streaming radio. You might add more rules as follows.

  1. Always allow DNS
    -A FORWARD -p udp --dport 53 -j ACCEPT
  2. Disallow streaming radio, e.g. Virgin Radio Thailand.
    -A FORWARD -p udp -m udp -s 192.168.0.0/24 -d 203.121.145.88/32 --dport 1755 -j DROP
  3. Disallow IRC
    -A FORWARD -p tcp -m tcp -s 192.168.0.0/24 --dport 6667 -j DROP
  4. Disallow some machines
    -A FORWARD -s 192.168.0.45/32 -j DROP

After changing iptables rules, you have to flush cache in iptables and then set all rules again as follows.

iptables -F
iptables -X
service iptables restart

Technorati Tags: , , , , , , , , , , ,

Post new comment