Skip to content

Instantly share code, notes, and snippets.

@gerard-kanters
Last active November 11, 2020 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerard-kanters/7fed50003f8f3cbdf743568b50da3006 to your computer and use it in GitHub Desktop.
Save gerard-kanters/7fed50003f8f3cbdf743568b50da3006 to your computer and use it in GitHub Desktop.
Stop spam with firewalld and ipset. Ipset is very fast and can have hundres of thousands of rules without delaying your site.
#!/bin/bash
# Script downloads monthly spammers and adds them via ipset to firewalld. Add this script in /etc/cron.daily and make it executable (chmod +x /etc/cron.daily/stopforumspam.sh)
#Inital command to create ipset, run once
#ipset create dailyspam hash:ip maxelem 16777216
#Add set to firewalld
#firewall-cmd --permanent --new-ipset=dailyspam --type=hash:ip --option=maxelem=16777216
#firewall-cmd --permanent --add-rich-rule='rule source ipset=dailyspam log prefix="spam" level="debug" limit value="1/h" drop'
#Choose the number of days your would like to download, choices are 1,30,90,180,365
DAYS="30"
# list of known spammers
URL="www.stopforumspam.com/downloads/listed_ip_${DAYS}.zip";
# save local copy here
FILE="/tmp/listed_ip_${DAYS}.zip";
FILE_UNZIPPED="/tmp/listed_ip_${DAYS}.txt";
# Firewalld list name
SET="dailyspam";
/usr/sbin/ipset flush $SET
wget -qc $URL -O $FILE
if [ $? -eq 1 ]; then
echo "The source file $FILE could not be downloaded, it might have been downloaded to many times per day"
exit 1
fi
# get a copy of the spam list
unzip $FILE -d /tmp/ > /dev/null 2>&1 #No output required, messes up cron mail
#Optionally add a list of individual IP address to a spam list, in this example they are put in /spam/list
cat /spam/list >> $FILE_UNZIPPED > /dev/null 2>&1
firewall-cmd --permanent --ipset=$SET --add-entries-from-file=$FILE_UNZIPPED
#make new list active in memory
firewall-cmd --reload
# remove the spam list
unlink $FILE
unlink $FILE_UNZIPPED
@gerard-kanters
Copy link
Author

gerard-kanters commented Nov 11, 2018

This script can be used in daily cron /etc/cron.daily or using crontab -e. It will download a list of known spammers and will put this in the firewall. It uses ipset sinces this is much faster than individual rules in firewalld. The list is actively maintained. Using the combination of ipset and firewalld makes it run wirespeed, since ipset adds the rules to the kernel.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment