Skip to content

Instantly share code, notes, and snippets.

@Aikhjarto
Last active April 8, 2021 15:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save Aikhjarto/68ce0a59e6138609dab8 to your computer and use it in GitHub Desktop.
Save Aikhjarto/68ce0a59e6138609dab8 to your computer and use it in GitHub Desktop.
Fetch a list of known brute force attackers from badips.com and apply/update iptables DROP rules
#!/bin/bash
# This script downloads a list of IPs known for brute force attacking within the last two weeks.
# The fetched IPs get blocked with iptables with the special comment "BADIP". This script only
# modifies iptables rules with that comment. This measure makes it well compatible with other firewall
# scripts like the SUSEFirewall.
# The iptables rules are updated every time this script is executed. Additionally this script is
# quiet on stdout, which makes it well suited for being executed as a cronjob.
#
# Please also use fail2ban with the badips modification and help to maintain the list of attackers.
# See also: fail2ban and http:///www.badips.com
IPTABLES_BIN=/usr/sbin/iptables
IPTABLES_SAVE_BIN=/usr/sbin/iptables-save
LOGGER_OPTS="-t add_badips"
# fetch IP list from badips.com
URL="http://www.badips.com/get/list/ssh/2?age=2w"
### download
logger $LOGGER_OPTS "fetching list of bad IPs from $URL"
FILE=`mktemp`
# curl or wget can be used to download. Uncomment line which one should be used
curl -s $URL > $FILE
#wget -q -O $FILE $URL
if [ $? -ne 0 ]; then
logger $LOGGER_OPTS -s "ERROR: download of $URL failed"
exit 1
else
logger $LOGGER_OPTS "got "`wc -l $FILE | awk '{ print $1 }'` " IPs"
fi
### remove old blocked entries
FILE2=`mktemp`
# export all rules with comment "BADIP"
$IPTABLES_SAVE_BIN | grep -e "--comment BADIP" | sed 's/-A/-D/' > $FILE2
logger $LOGGER_OPTS "removing "`wc -l $FILE2 | awk '{ print $1 }'` " old entries"
# remove all IPs previously known as bad
# HINT: use a while loop here since a for loop would require changing the IFS due to spaces in $FILE2
while read RULE; do
$IPTABLES_BIN $RULE
done < $FILE2
rm $FILE2
### add new IPs
for IP in $(cat $FILE); do
$IPTABLES_BIN -I INPUT $RULE -s $IP -j DROP -m comment --comment "BADIP"
done
rm $FILE
logger $LOGGER_OPTS "done applying IPs"
@slrslr
Copy link

slrslr commented Mar 30, 2017

Is this approach safe because of high number of IPs in iptables?

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