Thursday, 10 June 2010

Sysadmin IPTables

Sysadmin IPTables

IPTables is installed by default in Ubuntu. The default setup allows all traffic. It just remains to specify restrictions as required. For our servers, firewall rules (if required) will be kept in /etc/scripts/firewall_rules.sh.

Reference: https://help.ubuntu.com/community/IptablesHowTo

When managing many servers, here's a quick iptables firewall template. You just need to define the Ports you want to block and the exception IPs you want to allow - in 3 easy steps.

Step 1: Copy the template script below and modify the arrays IPS and PORTS with your data:

#!/bin/bash 
#   /etc/scripts/firewall_rules.sh 

#   IP Table Firewall Rules

#   array of allowed ips (or ranges) - modify the IPs to suit your needs
IPS=( 192.168.100.0/24 100.101.102.103 )

#   array of ports to block (from all IPs except he ones above)
PORTS=( 80 443 ftp ssh )

#   note: bash scripting requires a function to be defined before it is called

function iptables_tcp_block() {

    #   block port access except from specified IPs

    #   get count of elements in array
    count2=$((${#IPS[@]} - 1))

    #   walk thru array
    for index2 in $(seq 0 $count2)
    do
        #   allow from specified locations for this port
        iptables -A INPUT -s ${IPS[$index2]} -p tcp --dport $1 -j ACCEPT
    done

    #   disable from everywhere else for this port
    iptables -A INPUT -p tcp --dport $1 -j DROP
}
 
#   flush all existing iptables rules
iptables --flush
 
#   execute new blocking rules
 
#   get count of elements in array
count=$((${#PORTS[@]} - 1))

#   walk thru array
for index in $(seq 0 $count)
do
    #   allow from specified locations for this
    iptables_tcp_block ${PORTS[$index]}
done

#   save rules (no real need for this as we're generating rules from scratch anyway - but I like backups)
iptables-save > /etc/scripts/firewall_rules.iptables


Step 2: Run the script and check to activate the firewall rules:

You can check the rules with the following command:
iptables --list


Step 3: Make the script auto-run on reboot:

Here is an example of network setting in Ubuntu where you can force the script to run before the network is started.

# primary network interface
auto eth0
iface eth0 inet static
  # run iptables firewall rules
  pre-up /etc/scripts/firewall_rules.sh
  address 192.168.100.15
  netmask 255.255.255.0
  network 192.168.100.0
  broadcast 192.168.100.255
  gateway 192.168.100.1
  # dns-* options are implemented by the resolvconf package, if installed
  dns-nameservers 8.8.8.8 8.8.4.4
  dns-search mydomain.com