Simple SSH bruteforce prevention using iptables


Since I like to learn more about scripting, I decided to write my own SSH bruteforce prevention script instead of installing a plug-and-play tool. You can run the script manually or have it run every hour or so using crontab.

As root, create a new directory for the script and files, name it for example bfCheck:

# mkdir bfCheck

In this folder, create a new file, name it for example bfCheck.sh:

# cd bfCheck
# touch bfCheck.sh

Open the file using nano and copy paste the following script:

# nano -w bfCheck.sh

#!/bin/sh
blockIPs=”$(cat /var/log/secure | grep “Failed password for” | grep -v “invalid” | awk {‘print $11’} | sort | uniq -c | awk -v limit=50 ‘$1 > limit{print $2}’)”
currentIPs=”$(/sbin/iptables-save)”

if [ -z “$blockIPs” ]
then
echo “No match found, skipping”
else

while read -r line; do
if grep -q $line <<<$currentIPs
then
echo “IP address already blocked, skipping. IP: $line”
else
/sbin/iptables -A INPUT -s $line -p tcp –dport 22 -j DROP
echo “Blocking IP address: $line”
echo `date +”%b %d %H:%M:%S”` Blocking $line >> /root/bfCheck/iptables.log
fi
done <<< “$blockIPs”

fi

Save and close (ctrl+x & y).

Change the file’s mode, give it +x:

# chmod +x bfCheck.sh

Run the script, you will it will start blocking IP addresses or it will show you that not match is found:

# ./bfCheck.sh

Please note the limit=50 at the very first line of the script just after #!/bin/sh. You can change it to your wishes, it means that it will only block the IP address if there was more than 50 tries to access your server with an invalid password.