SSH Password Attacks - Block IP Script

Running SSH and some script kiddy or attacker is running a username/password dictionary against it?  This script might help:

#!/bin/sh
# ----------------------------------
# IPTABLES / SSHD ATTACK BLOCKING SCRIPT
#
# Author: Ron Brash
# March 1st, 2011
#
# Purpose:
# Add offending IP from failed SSH connections
# to the iptables (firewall) rules.
#
# ------------------------------------

## Explaination

# scan /var/log/secure for ssh attempts
# use iptables to block the bad guys

# Looking for attempts on existing and non-existing users.
# ie.//
# Mar  1 22:44:07 fizban sshd[28714]: Failed password for root from 192.168.174.1 port 55216 ssh2
# Mar  1 22:46:57 fizban sshd[31170]: Failed password for invalid user rockstar from 192.168.174.139 port 45841 ssh2

## Vars

# Set this variable for the number of failed attempts from an IP

USERVAR=2

## Business logic

tail -1000 /var/log/secure | awk -v USERVAR=$USERVAR '/sshd/ && /Failed password for/ { if (/invalid user/) try[$13]++; else try[$11]++; }
END { for (h in try) if (try[h] > USERVAR) print h; }' |
while read ip
do
        # Check if IP is already blocked...
        /sbin/iptables -L -n | grep -x $ip > /dev/null
        if [ $? -eq 0 ] ; then
                # echo "Already denied ip: [$ip]" ;
                true
        else
                # Add a little logging entry
                logger -p authpriv.notice "*** Blocked SSH attempt from: $ip"
                /sbin/iptables -I INPUT -s $ip -j DROP
        fi
done

Blog tags: 

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <python> <c>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.