How to Block the SSH Brute force login attempts with bash scripts.
IPtables &
sendmail/postfix
*******************************
step 1: create a executable file
*******************************
ssh the sever using putty client
cd /usr/share
vi sshscan.sh
copy and paste the below script .
#!/bin/sh
# scan /var/log/secure for ssh attempts
# use iptables to block the bad guys
# Looking for attempts on existing and non-existing users. For example:
# Nov 2 22:44:07 pbxer sshd[28318]: Failed password for root from 74.143.42.70 port 52416 ssh2
# Nov 3 00:06:57 pbxer sshd[31767]: Failed password for invalid user mat3 from 192.203.145.200 port 35841 ssh2
tail -1000 /var/log/secure | awk '/sshd/ && /Failed password for/ { if (/invalid user/) try[$13]++; else try[$11]++; }
END { for (h in try) if (try[h] > 4) print h; }' |
while read ip
do
# note: check if IP is already blocked...
/sbin/iptables -L -n | grep $ip > /dev/null
if [ $? -eq 0 ] ; then
# echo "already denied ip: [$ip]" ;
true
else
echo "Subject: denying ip: $ip" | /usr/sbin/sendmail urmailid@gmail.com
logger -p authpriv.notice "*** Blocking SSH attempt from: $ip"
/sbin/iptables -I INPUT -s $ip -j DROP
fi
done
Save and exit from the file
chmod 755 /usr/share/sshscan.sh
*******************************
Step 2: Scheduling the script to run every minute
*******************************
Loign to the crontab edit page by running the below command
crontab -e
go to last line and copy and paste the below line
* * * * * /usr/share/sshscan.sh
note: for more details about cron check this LINK
we are done now.
the above script will every minute and check the var/log/secure file for the wrong password entry or wrong user or failed authentication and captures the ip , if the attack is more than 4 time, the particular ip will be blocked using iptables
IPTables command to check the blocked ip'
iptables -L -n