Thursday, November 03, 2011

Stop SSH attacks

If you run a server that has SSH accessible by the public, there are a few things you can do to secure it. Among them, I use a simple script that runs every hour (set up in cron). The script finds the attackers and blocks their IP using hosts.deny.

I don't remember if I created this script or copied it some somewhere. Either way, it's been modified for my purposes. To get this to work, you may have to create the /usr/local/sshd_block directory, and have sshd running under tcpwrapper. Name the script whatever you want, and set it to run as often as you would like in cron.
# Remove old file entries
cd /usr/local/sbin
rm block.txt
rm new_block.txt 
# Parse the messages file and extract the sshd lines
grep sshd /var/log/messages | grep Invalid >> block.txt
# Cut only the IP addresses out of that file, except for my network
rev block.txt | cut -d \  -f 1 | sort | uniq | rev | grep -v 10.0.0. >> new_block.txt 
# Add the references from new_block.txt to the ssh.blacklist
target=`cat new_block.txt`
for i in $target; do
        echo ALL:$i >> /etc/hosts.deny
# Remove duplicate entries from ssh.blacklist
cat /etc/hosts.deny | sort | uniq > /etc/
mv /etc/ /etc/hosts.deny
Obviously, change the 10.0.0. line to whatever your network is (ex. 192.168.0.). I've been running this script for a year or so, and my hosts.deny file now has over 700 lines in it.

No comments: