A simple script to block the IP's of brute-force password attacks

Scenerio

  • Sometimes servers must expose things like SSH to all originating IP’s.
  • An exposed server will usually be brute-force attacked by malicious people looking for a valid username from which they can launch a brute-force password attack against.
  • This is a simple script to scan the system’s login log (/var/log/secure) and add those attacking IP’s to the system iptables firewall.

BASH Script

#!/bin/bash
 
 for ATTACKER_IP in $(grep ": Failed password for invalid user" /var/log/secure |
  cut -d " " -f 13 | sort --unique)
 do
 
   FOUND=-iptables -nL INPUT | grep $ATTACKER_IP-
   if [ "x$FOUND" == "x" ]; then
     FOUND=": BLOCKING"
     iptables -A INPUT -s $ATTACKER_IP -j DROP
   else
     FOUND=" ... previously blocked"
   fi
   echo "  Brute-Force Attacker: [$ATTACKER_IP]     $FOUND"
 
 done

Example

./bruteforce.sh 
   Brute-Force Attacker: [187.4.198.10]     : BLOCKING
   Brute-Force Attacker: [193.2.147.240]     : BLOCKING
   Brute-Force Attacker: [193.239.173.88]     : BLOCKING
   Brute-Force Attacker: [218.78.209.253]     : BLOCKING
   Brute-Force Attacker: [24.214.31.146]     : BLOCKING
   Brute-Force Attacker: [60.32.151.202]     : BLOCKING
   Brute-Force Attacker: [62.90.166.130]     : BLOCKING
   Brute-Force Attacker: [64.68.190.99]     : BLOCKING
   Brute-Force Attacker: [66.83.119.2]     : BLOCKING
   Brute-Force Attacker: [71.2.19.50]     : BLOCKING
   Brute-Force Attacker: [84.38.74.226]     : BLOCKING
   Brute-Force Attacker: [92.241.190.96]     : BLOCKING
categories: linux | shell | security | bash |