technichristian.net

The best portal for technical, inspirational and Christian content

IPTables Firewall Script for a Linux Server

September 24, 2016 by Tagged with:    
Posted in: Linux

Share with:


My firewall script blocks traffic for both IPv4 and IPv6 protocols.

I open only port 80 for HTTP and port 22 for SSH.

Pings are allowed only from the HE.net IPv6 tunnel.

In addition, all IPs on the Spamhaus Drop List are blocked from accessing the server

In the following steps, run all commands as root or using sudo.

1. Get my firewall script.


#!/bin/sh
# description: Firewall

IPT=/sbin/iptables
IPT6=/sbin/ip6tables

case "$1" in
start)
# Flush all ipv4 chains
$IPT -F

#Script to add firewall rules to a linux system to completely block
#all traffic to and from networks in the spamhaus drop list.

rm /tmp/drop.lasso

echo "Setting up Drop Lists"
wget http://www.spamhaus.org/drop/drop.lasso -O /tmp/drop.lasso

cat /tmp/drop.lasso \
| sed -e 's/;.*//' \
| grep -v '^ *$' \
| while read IP ; do
echo "Adding $IP to DROPLIST"
$IPT -I INPUT -s "$IP" -j DROPLIST
$IPT -I OUTPUT -d "$IP" -j DROPLIST
$IPT -I FORWARD -s "$IP" -j DROPLIST
$IPT -I FORWARD -d "$IP" -j DROPLIST
done

$IPT -A DROPLIST -j DROP

$IPT -A INPUT -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT

# Accept HTTP server traffic

$IPT -A INPUT -i eth0 -p tcp --dport 80 -j ACCEPT

#Accept SSH traffic

$IPT -A INPUT -i eth0 -p tcp --dport 22 -j ACCEPT

# Accept PING only from HE.net tunnel

$IPT -A INPUT -i eth0 -p icmp --source 66.220.2.74 -j ACCEPT

# Flush all ipv6 chains

$IPT6 -F

$IPT6 -A INPUT -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT

#Accept HTTP traffic
$IPT6 -A INPUT -i eth0 -p tcp --dport 80 -j ACCEPT

# Accept SSH traffic
$IPT6 -A INPUT -i eth0 -p tcp --dport 22 -j ACCEPT

# Drop everything else on ipv4 and ipv6
$IPT -A INPUT -i eth0 -j DROP
$IPT6 -A INPUT -i eth0 -j DROP
exit 0
;;

stop)
$IPT -F
$IPT6 -F
exit 0
;;
*)
echo "Usage: /etc/init.d/firewall {start|stop}"
exit 1
;;
esac


2. Change the public network interface if required. My firewall is set to work with eth0 as the interface.

3. Save it as /etc/init.d/firewall

4. Make it executable:

chmod 700 /etc/init.d/firewall

5. Run it:

/etc/init.d/firewall start

6. Add it to the programs to start at boot.

On Debian, run:

update-rc.d firewall defaults

Adapt step 6 accordingly based on the distribution that you use.

The Spamhaus Drop List needs to be refreshed each day.

Run:

crontab -e

and add the firewall script as shown in the following example:

0 6 * * * /etc/init.d/firewall stop && sleep 5 && /etc/init.d/firewall start

In the example, the firewall is stopped and restarted with the new drop list at 6 AM each day.

Done.