Add Me!Close Menu Navigation

My technical corner about Linux, Perl, programming, computer networks and network security

Add Me!Open Categories Menu

Basics of writing bash scripts, autoblocking ssh break in attempts

This script is a typical problem of the reinvention wheel, because there are many programs, which may prevent from robots which are try to guess the passwords in the ssh service. If you don’t trust your security skills, you should use them or read this text.

I will try to write a script, which prevents from many guessing the password based on the ssh service logs.

These information are saved when someone enters an invalid password over the ssh service:

Failed password for mateusz from 10.0.0.1 port 56344 ssh2

 

I tried login with a bad password at the mateusz account. Most of automated programs generate this information (at the /var/log/auth.log location). So the script is simple, additionaly I improved it by a whitelist of trusted hosts (the hosts which won’t be blocked anyway).

 

for i in `grep "Failed password for" /var/log/auth.log | pcregrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'`; 
do 
 ### List of trusted hosts
 TRUSTED=( 127.0.0.1 192.168.1.1 172.16.0.1 )
 IS_TRUSTED=0
 for j in ${TRUSTED[@]};
 then
  if [ "$j" == "$i" ]; 
  then
   IS_TRUSTED=1
  fi
 fi

 ### Simple check if the host isn't trusted
 if [ "$IS_TRUSTED" != "1" ];
 then
  CHECK=`grep $i /tmp/failed-ssh`
  if [ -z "$CHECK" ];
  then
   ### It's first time - only write this
   echo $i >> /tmp/failed-ssh
  else
   ### It's another time - block it
   ### I use iptables, but you can use /etc/hosts.deny also
   iptables -A INPUT -s $i -j DROP
  fi
 fi
done

It’s obvious that the regular expression [0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3} isn’t a good choice for checking of validity an IP address, but is completely enough for my script.

Leave a Reply

You must be logged in to post a comment.