Sample Linux Firewall Script

This is a sample, work in progress firewall script which allows incoming MySQL, WWW and SSH traffic, as well as ICMP Pings.

#!/bin/sh
# My system IP/set ip address of server
SERVER_IP="192.168.0.1"

# Flushing all rules
iptables -F
iptables -X
iptables -F -t nat

# Setting default filter policy
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP

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

#Allow stated, related traffic back in
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

# Allow incoming ssh from ANYWHERE
iptables -A INPUT -p tcp -s 0/0 -d $SERVER_IP --sport 513:65535 --dport 22 -m state --state NEW -j ACCEPT
iptables -A OUTPUT -p tcp -s $SERVER_IP -d 0/0 --sport 22 --dport 513:65535 -m state --state ESTABLISHED -j ACCEPT

#Allow incoming web on port 80 only from ANYWHERE
iptables -A INPUT -p tcp -s 0/0 -d $SERVER_IP --sport 513:65535 --dport 80 -m state --state NEW -j ACCEPT
iptables -A OUTPUT -p tcp -s $SERVER_IP -d 0/0 --sport 80 --dport 513:65535 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT

#Allow incoming mysql on port 3306 FROM ANYWHERE
iptables -A INPUT -p tcp -s 0/0 -d $SERVER_IP --sport 513:65535 --dport 3306 -m state --state NEW -j ACCEPT
iptables -A OUTPUT -p tcp -s $SERVER_IP -d 0/0 --sport 3306 --dport 513:65535 -m state --state ESTABLISHED -j ACCEPT

#Allow incoming ICMP traffic from ANYWHERE
iptables -A INPUT -p icmp -m state --state NEW -j ACCEPT
iptables -A OUTPUT -p icmp -m state --state ESTABLISHED -j ACCEPT

# Allow outgoing DNS requests. Few things will work without this.
iptables -A OUTPUT -m state --state NEW -p udp --dport 53 -j ACCEPT
iptables -A OUTPUT -m state --state NEW,RELATED,ESTABLISHED -p tcp --dport 53 -j ACCEPT

# Allow outgoing HTTP requests. Unencrypted, use with care. (related,established rules required)
iptables -A OUTPUT -m state --state NEW,RELATED,ESTABLISHED -p tcp --dport 80 -j ACCEPT

# Allow outgoing HTTPS requests.
iptables -A OUTPUT -m state --state NEW,RELATED,ESTABLISHED -p tcp --dport 443 -j ACCEPT

# Allow outgoing pings (echo request, fragmentation needed, time exceeded).
iptables -A OUTPUT -m state --state NEW -p icmp --icmp-type 8 -j ACCEPT
iptables -A OUTPUT -m state --state NEW -p icmp --icmp-type 11 -j ACCEPT

Leave a Reply