Wednesday, December 31, 2008

Defending SSH Brute Force Attacks

I noticed allot of invalid user trying to login to my ssh box on the internet rather then changing my port or doing something else I opted to create an ssh script that denies all traffic coming from an IP who is trying to login with an invalid user. There are a couple requirements for the script. The primary IP needs to be on Eth0 interface and iptables has to be enabled on the box.

Here is the basic script that searches /var/log/messages for bad ssh attempts and adds a new iptables drop rule for each ip.

chmod 700
########## /root/Badssh.sh ############
!/bin/bash
#Badssh Audit Version 1.0
#Info-struct security system Inc.
#Authored Ryan Fawcett Gryanfawcett @ gmail dot com
TEMP=`grep sshd /var/log/messages | grep "Invalid user" | awk {'print $10'} | sort -u`;
echo "######Badssh.sh rules#########" >>/etc/rc.d/badssh-ips.sh;
for ip in $TEMP
do
echo "\$IPTABLES -A INPUT -i \$EXT_INT -s" $ip"/32 -j DROP" >>/etc/rc.d/badssh-ips.ssh;
done
sleep 2
/etc/rc.d/badssh-ips.ssh;

Here is the script that searches the logs and then appends the bad ips to the iptables rule set. You will need to clean up the script once in a while and I suggest setting up ssh keys to avoid locking yourself out by fat fingering your login.

chmod 700
####### /etc/rc.d/badssh-ips.sh #########
#!/bin/sh
# Ryan fawcett gryanfawcett at Gmail dot com 2001
# this script clears existing firewall rules and sets new rules
export EXT_IP="`/sbin/ifconfig eth0 | grep 'inet addr' | awk '{print $2}' | sed
-e 's/.*://'`"


###### Roots Crontab ########
0,15,30,45 * * * * /root/badssh.sh