#!/bin/bash

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

#Copyright 2009, William Stearns, wstearns@pobox.com
#Released under the GPL.  This and other tools can be found at
#http://www.stearns.org/
#Modified by Sam Watkins, sam@ucm.dev

#Sole (optional) command line parameter is the file location of the
#drop list, such as:

cd /var/lib/
if [ "$1" = "-u" ]; then
	rm -f drop.lasso edrop.lasso
	wget -q http://www.spamhaus.org/drop/drop.lasso
	wget -q http://www.spamhaus.org/drop/edrop.lasso
fi
if [ "$1" = "-i" ]; then
	iptables -N spamhaus-drop-src
	iptables -N spamhaus-drop-dest
	iptables -A INPUT -j spamhaus-drop-src
	iptables -A FORWARD -j spamhaus-drop-dest
	iptables -A FORWARD -j spamhaus-drop-src
	iptables -A OUTPUT -j spamhaus-drop-dest
	exit
fi
if [ "$1" = "-r" ]; then
	iptables -D INPUT -j spamhaus-drop-src
	iptables -D FORWARD -j spamhaus-drop-dest
	iptables -D FORWARD -j spamhaus-drop-src
	iptables -D OUTPUT -j spamhaus-drop-dest
	iptables -F spamhaus-drop-src
	iptables -F spamhaus-drop-dest
	iptables -X spamhaus-drop-src
	iptables -X spamhaus-drop-dest
	exit
fi
# ./spamhaus-drop /var/lib/drop.lasso

#While the DROP file should be regularly updated, this should 
#probably be about once per day or less frequently; do _not_ 
#download DROP more than once an hour.

iptables -F spamhaus-drop-src
iptables -F spamhaus-drop-dest

(
echo *filter

for DropList in drop.lasso edrop.lasso; do

# if [ -n "$1" ]; then
# 	DropList="$1"
# else
# 	DropList="./drop.lasso"
# fi
if [ ! -e "$DropList" ]; then
	echo "Unable to find drop list file $DropList .  Perhaps do:" >&2
	echo "wget http://www.spamhaus.org/drop/drop.lasso -O $DropList"
	echo "exiting." >&2
	exit 1
fi

if [ ! -x /sbin/iptables ]; then
	echo "Missing iptables command line tool, exiting." >&2
	exit 1
fi

cat "$DropList" \
 | sed -e 's/;.*//' \
 | grep -v '^ *$' \
 | while read OneNetBlock ; do
	echo -A spamhaus-drop-src -s "$OneNetBlock" -j DROP
	echo -A spamhaus-drop-dest -d "$OneNetBlock" -j DROP
done

done
echo COMMIT
) | iptables-restore -n
