I like to keep my system clean and secured. Unfortunately, the GUI interface for iptables isn’t really matching my expectations. So I would like to create simple bash script which will execute iptables rules with every system boot-up.

By default it blocks all incoming AND outgoing traffic also, so be careful :-)
If you want to open another port – you just need to add it to the INPUT_OUTPUT list. Take a look at the source of the script:

#!/bin/bash

# Ports that are open for output and input
INPUT_OUTPUT=(
20:21      # FTP
22         # SSH
25         # SMTP
43         # WHOIS
80         # HTTP
8080       # HTTP ALTERNATIVE
110        # POP3
443        # HTTPS
465        # SMTP SSL
995        # POP3 SSL
#5222:5223 # XMMP/Jabber
8074       # GADU-GADU
26789      # SKYPE
1521       # OracleDB
3306       # MySQL
11371      # SKS Keyserver
8035       # .977 Smooth Jazz Shoutcast Radio
2628       # Dictionary
)

IN_OUT_COUNT=`echo ${INPUT_OUTPUT[@]:0}|tr -s ' ' '\n'|wc -l`

# Clear tables
iptables -F
iptables -X

# Set policy for all tables
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP

# Allow loopback traffic
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

# Allow traffic in LAN
iptables -A INPUT -i eth0 -m iprange --src-range 192.168.1.100-192.168.1.200 -j ACCEPT
iptables -A OUTPUT -o eth0 -m iprange --src-range 192.168.1.100-192.168.1.200 -j ACCEPT

for index in `seq 0 $[IN_OUT_COUNT-1]`
do
iptables -A OUTPUT -o eth0 -m state --state NEW,ESTABLISHED -p tcp --dport ${INPUT_OUTPUT[index]} -j ACCEPT
iptables -A INPUT -i eth0 -m state --state ESTABLISHED,RELATED -p tcp --sport ${INPUT_OUTPUT[index]} -j ACCEPT
done

#
# Additional rules
#

# PING
iptables -A INPUT -i eth0 -p icmp --icmp-type echo-reply -j ACCEPT
iptables -A OUTPUT -o eth0 -p icmp -m state --state NEW -j ACCEPT

# DNS
iptables -A INPUT -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT -p udp --sport 53
iptables -A OUTPUT -o eth0 -m state --state NEW,ESTABLISHED -j ACCEPT -p udp --dport 53

# INVALID STATE - put every rules that are added spontaniously after those lines
iptables -A INPUT -i eth0 -m state --state INVALID -j DROP
iptables -A OUTPUT -o eth0 -m state --state INVALID -j DROP

#
# Additional temporary rules
#

iptables -A INPUT -i eth0 -m state --state ESTABLISHED,RELATED -p tcp --sport 1024:65535 -s ??.??.??.?? -j ACCEPT    # Specified FTP
iptables -A OUTPUT -o eth0 -m state --state NEW,ESTABLISHED -p tcp --dport 1024:65535  -d ??.??.??.?? -j ACCEPT