Blacklisting hosts that try to break into my host

I have been noticing lately that a lot of poeple are trying to attack my host by logging in over ssh.  With the help of a friend I was able to concoct a script which takes those nasty IPs out of /var/log/auth.log and then banishes these IPs by using route and the reject option:

#!/bin/bash

echo -e “\n[`date`] – Scanning for new bad hosts to blacklist…”
tail -2000 /var/log/auth.log | grep ‘invalid user’ | awk ‘{print $13}’ | uniq > /tmp/badhosts.txt
route | egrep -v ‘Kernel|Destination|default’ | awk ‘{print $1}’ > /tmp/routes.txt

for i in `cat /tmp/badhosts.txt`; do
if [ -z `grep $i /tmp/routes.txt` ]; then
echo -e “\n Adding $i to blacklist” ;
route add -host $i reject ;
else echo “$i is in routing table”;
fi;
done
echo -e “Now printing routing table, make sure nothing in here looks wrong”
route
echo -e “\n”
exit 0

I have put the script in a cronjob so that it runs every fifteen minutes:

0,15,30,45 * * * * /usr/local/bin/blacklist.sh >> /tmp/blacklist.log

This all gets dumped to a log at /tmp/blacklist.log, which I then have emailed to myself each day at 8:00 AM by a cronjob:

0 8 * * * mail -s “Blacklist.log for `date +%b” “%d” “%Y`” XXXX@gmail.com < /tmp/blacklist.log

In this way, I effectively block anyone who ends up in /var/log/auth.log as an invalid user from bombarding my ssh daemon with nasty brute force attacks to get into my server.

Linux is so awesome.

Advertisements

Author: jayholler

A technology lover living in California with my wife and two children.

1 thought on “Blacklisting hosts that try to break into my host”

  1. Great post! Make sure you blog is being submitted to Google. I bet a lot of people would find this useful.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s