Breaking

Wednesday, August 1, 2018

Prevent SSH Brute Force Attack by Automatically Blacklisted




Automated Solution for Centos/RHEL to Block Bad Actors
Here's a script for Centos to check ssh failed logins for both invalid user accounts and bad passwords for valid accounts. If the source IP has hit us more than 3 times and is not already on the deny list, it gets added to the deny list. I run this every 15 minutes from root's crontab. I've also disallowed root logins via ssh, so the combination keeps things fairly quiet.
     #/bin/bash
     # Save a copy of the existing hosts.deny file for safety
     cp /etc/hosts.deny /etc/hosts.deny.bak
     # Get a list of the offending IP addresses and process them
     for z in `grep "Invalid\|Failed" /var/log/secure | awk '{ print $NF }' | sort | uniq`
     do
     # Get the number of times this IP hit us
     hits=`grep "Invalid\|Failed" /var/log/secure* | grep $z | wc -l`
     # Check whether this IP is already blocked
     blocked=`grep $z /etc/hosts.deny | wc -l`
     # If they hit us more than 3 times and are not already on the deny list
     # add them to the deny list
     if [ $hits -gt 3 -a $blocked -eq 0 ]
     then
          echo "sshd : $z" >> /etc/hosts.deny
     fi
     done



Another Example: 

for z in `grep Invalid /var/log/auth.log | awk '{ print $NF }' | sort | uniq`
do
  count1=`grep $z /etc/hosts.deny | wc -l`
  count2=`grep Invalid /var/log/auth.log | grep $z | wc -l`
  if [ $count1 -eq 0 -a $count2 -gt 10 ] ; then
    current=`egrep "^ssh" /etc/hosts.deny | sed 's/sshd[ :,]*//'`
    sudo cp /etc/hosts.deny.bak /etc/hosts.deny
    sudo chmod 666 /etc/hosts.deny
    if [ $current ] ; then
      echo "sshd : $current , $z" >> /etc/hosts.deny
    else
      echo "sshd : $z" >> /etc/hosts.deny
    fi
    sudo chmod 644 /etc/hosts.deny
  fi
done




Post Credit: https://serverfault.com/questions/594746/how-to-stop-prevent-ssh-bruteforce 

No comments: