Wednesday, September 17, 2008

Simple Linux IDS/IPS Shell Script

Click Here For Updated Version

So, I don't even know where to begin. I know there is great software out there like Snort but for whatever reason, I rolled my own IDS/IPS (specifically for SSH). Its quite simple as it just looks through the log file for failed attempts against the SSH server. To show how it works, I made a little video for you. :)


(oops, type-o in video. oh well)

First things first, run this command:
echo "IDSIPSDELIM-SSHD" >> /var/log/messages

Done? Good. Now here is the script:


idsips.sh.sshd


#! /bin/bash

# Using this for the first time???
# YOU WILL NEED TO DO THIS:
# echo "IDSIPSDELIM-SSHD" >> /var/log/messages
# Done? Good, now you can use this.

# Get old delimiter for where to look from
gto=`cat /var/log/messages | grep IDSIPSDELIM-SSHD | tail -n1`
# Apply new delimiter so we know where to look for again
echo "IDSIPSDELIM-SSHD-`date +%s`" >> /var/log/messages

gtf=`cat /var/log/messages | grep -A200000000 $gto | grep sshd | grep PAM | awk '{ print $NF }' | sort -u`

for s in `echo "$gtf"`
do
num=`echo "$gtf" | grep $s | wc -l`
if [ $num > 20 ]
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 `cat /etc/hosts.deny | grep AUTOBLOCK | cut -d"-" -f2`
do
gts=`expr $gtcd - $s`
if [ "$gts" -gt 360 ]
then
gto=`cat /etc/hosts.deny | grep -v $s`
echo "$gto" > /etc/hosts.deny
fi
done



Don't forget to setup the crontab for it:
*/5 * * * * /usr/local/bin/idsips.sh.sshd
(or wherever you put it)

No comments: