Tuesday, January 6, 2009

Simple Linux SSH IDS/IPS Script - Ver. 2

EDIT: Go figure that I re-invented the wheel. :)
I will leave this here for reference. Go ahead and check out: DenyHosts. The biggest thing about it that I am promoting it for is that you can potentially block zombie computers before they reach your network. It blocks based off attacks against your system and also pulls from a database of attacks other networks have seen (or not if you tell it not to). Enjoy!




I realized that the original SSH IDS/IPS I wrote was a little flawed... It was finding and logging items that weren't actual hosts. BUT, it was doing its job on blocking those "non-hosts". ha I think i've got it to a good point now. So far it has only been tested on openSUSE 10.3 (script should apply to entire line of openSUSE distros). I think it is generic enough to apply to most other *nix based OS's but you will want to check for location mis-matches just in case.

Also, there is no pre-setup. Just run the script and it will let you know if you have never ran the script before or if logrotate was doing its job. :)



idsips.ssh.sh


#! /bin/bash

# Version 2

# Get old delimiter for where to look from
gto=`grep IDSIPSDELIM-SSHD /var/log/messages | tail -n1`
if [ `echo "$gto" | grep SSH | wc -l` -lt 1 ]
then
echo "Looks like the log file is missing the delimiter. If this is the first time running this script, please run it again. If it has been running ok then it probably means logrotate is doing its job. Exiting..."
echo "IDSIPSDELIM-SSHD-`date +%s`" >> /var/log/messages
exit
fi

# Apply new delimiter so we know where to look for again
echo "IDSIPSDELIM-SSHD-`date +%s`" >> /var/log/messages

#gtf=`grep -A200000000 $gto /var/log/messages | grep sshd | grep -i fail | awk '{ print $NF }' | grep [0-9] | sort -u`
gtf=`grep -A200000000 $gto /var/log/messages | grep sshd | grep -i fail | awk -F"from" '{ print $2 }' | awk '{ print $1 }' | grep [0-9a-zA-Z]"\."[0-9a-zA-Z] | sort -u`

for s in `echo "$gtf"`
do
num=`echo "$gtf" | grep $s | wc -l`
if [ $num > 10 ]
then
blkd="`date +%s`"
echo "ALL : $s # AUTOBLOCK-$blkd" >> /etc/hosts.deny
echo "`date` - AUTOBLOCK - $s - $blkd" >> /var/log/idsips.sh.log
sleep 1
fi
done

gtcd=`date +%s`
for s in `grep AUTOBLOCK /etc/hosts.deny | cut -d"-" -f2`
do
gts=`expr $gtcd - $s`
if [ "$gts" -gt 360 ]
then
gto=`grep -v $s /etc/hosts.deny`
echo "$gto" > /etc/hosts.deny
fi
done