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:

  1. #!/bin/sh
  2. # ----------------------------------
  3. # IPTABLES / SSHD ATTACK BLOCKING SCRIPT
  4. #
  5. # Author: Ron Brash
  6. # March 1st, 2011
  7. #
  8. # Purpose:
  9. # Add offending IP from failed SSH connections
  10. # to the iptables (firewall) rules.
  11. #
  12. # ------------------------------------
  13.  
  14. ## Explaination
  15.  
  16. # scan /var/log/secure for ssh attempts
  17. # use iptables to block the bad guys
  18.  
  19. # Looking for attempts on existing and non-existing users.
  20. # ie.//
  21. # Mar 1 22:44:07 fizban sshd[28714]: Failed password for root from 192.168.174.1 port 55216 ssh2
  22. # Mar 1 22:46:57 fizban sshd[31170]: Failed password for invalid user rockstar from 192.168.174.139 port 45841 ssh2
  23.  
  24. ## Vars
  25.  
  26. # Set this variable for the number of failed attempts from an IP
  27.  
  28. USERVAR=2
  29.  
  30. ## Business logic
  31.  
  32. tail -1000 /var/log/secure | awk -v USERVAR=$USERVAR '/sshd/ && /Failed password for/ { if (/invalid user/) try[$13]++; else try[$11]++; }
  33. END { for (h in try) if (try[h] > USERVAR) print h; }' |
  34. while read ip
  35. do
  36. # Check if IP is already blocked...
  37. /sbin/iptables -L -n | grep -x $ip > /dev/null
  38. if [ $? -eq 0 ] ; then
  39. # echo "Already denied ip: [$ip]" ;
  40. true
  41. else
  42. # Add a little logging entry
  43. logger -p authpriv.notice "*** Blocked SSH attempt from: $ip"
  44. /sbin/iptables -I INPUT -s $ip -j DROP
  45. fi
  46. 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>
  • 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.