Security and Technology Ramblings…

Here’s a great way to automate the process of blacklisting specific countries within the Shorewall firewall system.

Source data is pulled via the website IPDeny.


#!/bin/bash
HOME=/etc/shorewall/country
DATA=/etc/shorewall/country/data
LOG=/var/log/messages
WGET=/usr/bin/wget
MAIL=/usr/bin/mail
SHOREWALL="/sbin/shorewall"
SNAGROOT="http://www.ipdeny.com/ipblocks/data/countries"
COUNTRY="cn af kr"
#LOCALBLACK is an array to add IP addresses you want to manually blacklist.
LOCALBLACK="1.1.1.1 2.2.2.2"
NOW=$(date +"%c")
SUBJECT="Shorewall Country Refresh Status"
EMAIL="your@email.com"
touch $LOG
cat /etc/shorewall/country/blacklist > /etc/shorewall/blacklist
for k  in $COUNTRY
do
  tDB=$DATA/$k.zone
  echo "$NOW: Fetching $k.zone now."
  echo "$NOW: [SHOREWALL BLACKLIST REFRESH] Fetching $k.zone now." >> $LOG
  $WGET -O $tDB $SNAGROOT/$k.zone > /dev/null 2>&1
  echo "$NOW: Dumping $k.zone to shorewall blacklist file."
  echo "$NOW: [SHOREWALL BLACKLIST REFRESH] Dumping $k.zone to shorewall blacklist file." >> $LOG
  echo "#ZONE START FOR $k.zone" >> /etc/shorewall/blacklist
  cat $DATA/$k.zone >> /etc/shorewall/blacklist
  echo "#ZONE STOP FOR $k.zone" >> /etc/shorewall/blacklist
 done
echo "#LocalBlack Start" >> /etc/shorewall/blacklist
for k in $LOCALBLACK
do
echo "$NOW: Dumping local blacklist array to shorewall blacklist file."
echo "$NOW: [SHOREWALL BLACKLIST REFRESH] Dumping local blacklist array to shorewall blacklist file." >> $LOG
echo $k >> /etc/shorewall/blacklist
done
echo "#LocalBlack Stop" >> /etc/shorewall/blacklist
OUTPUT=$($SHOREWALL check |grep -i verified )
if [ "$OUTPUT" = "Shorewall configuration verified" ] ; then
  echo "$NOW: Shorewall config looks good!"
  echo "$NOW: [SHOREWALL BLACKLIST REFRESH] Shorewall config looks good!" >> $LOG
  echo "$NOW: [SHOREWALL BLACKLIST REFRESH] Restarting shorewall now." >> $LOG
  /etc/init.d/shorewall restart
  SUBJECT="Sucess: Shorewall Country Refresh Status"
  echo "$NOW:  Shorewall Country Refresh Status Sucessful!" >/tmp/emailoutput
  $MAIL -s "$SUBJECT" "$EMAIL" < /tmp/emailoutput
else
  echo "$NOW: Shorewall config is bad!" 
  echo "$NOW: [SHOREWALL BLACKLIST REFRESH] Shorewall config is bad!" >> $LOG
        SUBJECT="Failed: Shorewall Country Refresh Status"
        echo "$NOW:  Shorewall Country Refresh Status Failed!" >/tmp/emailoutput
        $MAIL -s "$SUBJECT" "$EMAIL" < /tmp/emailoutput
fi

Disclaimer: This bash script is just something I threw together. Do not blame me if it destroys your system, causes cancer or punches one of your small pets.

Leave a Reply