Saturday, September 10, 2011

Swatch To Monitor Security Logs

Install the package with YUM = yum install swatch
 Then create a swatch configuration file called
/etc/swatchrc  containing the following:
 
vi  /etc/swatchrc
# Bad login attempts
watchfor   /Failed password for/
        exec "/usr/local/nix/scripts/bad_user $1 $2 $3 \
$4 $5 $6 $7 $8 $9 $10 $11 $12 $13 $14 $15" 
 
:wq!
Then create The Script with the following
 
vi /usr/local/nix/scripts/bad_user
 
#! /bin/bash
#
IP=`echo $* | sed 's/^.* from //' | awk '{print $1}' | sed 's/::ffff://'`
ATTEMPTS=`grep $IP /var/log/secure | grep "Failed password for"  | wc -l`

if [ $ATTEMPTS -gt 2 ]
then
 route add $IP lo
 MINUTES=`expr $ATTEMPTS - 2`
 echo "route del $IP lo 2> /dev/null" | at now +$MINUTES \
minutes 2>&1 > /tmp/.bad_user.$$
 (hostname ; echo $* ; echo "IP=$IP" ; echo "ATTEMPTS=$ATTEMPTS" ; 
  echo "Blocking for $MINUTES minutes" ; 
  cat /tmp/.bad_user.$$ ) | Mail -s "bad user" Admin
fi

rm -f /tmp/.bad_user.$$ 
:wq!
 
Then start the swatch 
swatch --config-file=/etc/swatchrc --tail-file=/var/log/secure  \
--awk-field-syntax --tail-args "-F" &