Help, SSH /ipfw block script

Hello,

This is an SSH Block hammer script using ipfw, that I have modified for my own use. It is for a freenas 7.2 box which is FreeBSD based.

The script works, but if there is more then one hammer attack per day, my issue is the script reads the first five instances of refused or invalid users lines from the logs, not the most recent which is what I'd like it to do. Can some one better at scripting help me. The script is split into two searchs because of the need to parse the parentheses from the refused connections awk output.
TIA

DP

Script follows:

#!/bin/sh
#begin routine for refused connections
#del existing block rule
if ipfw show | awk '{print $1}' | grep -q 350 ; then
        ipfw delete 350
fi
#5 or more refused connections
awk '/refused/  {try[$(NF)]++}
END {for (h in try) if (try[h] > 5) print h}' /var/log/sshd.log |sed 's/[()]//g'|
while read ip
do
echo 'adding' $ip        
ipfw -q add 350 deny tcp from $ip to any in
done
#
#begin routine for invalid users
if ipfw show | awk '{print $1}' | grep -q 360 ; then
        ipfw delete 360
fi
awk '/Invalid user/ {try[$(NF)]++}
END {for (h in try) if (try[h] > 5) print h}' /var/log/sshd.log |
while read ip
do
echo 'adding' $ip        
ipfw -q add 360 deny tcp from $ip to any in
done

This will pickup only the first IP appears more than 5 times as refused (or Invalid user) and block:

#!/bin/sh
#begin routine for refused connections
#del existing block rule
if ipfw show | awk '{print $1}' | grep -q 350 ; then
        ipfw delete 350
fi
#First with 5 or more refused/Invalid user connections
awk '/refused/&&++try[$NF]>5{gsub(/[)(]/,"",$NF); print $NF; exit}' /var/log/sshd.log |
while read ip
do
    echo 'adding' $ip        
    ipfw -q add 350 deny tcp from $ip to any in
done
#
#begin routine for invalid users
if ipfw show | awk '{print $1}' | grep -q 360 ; then
        ipfw delete 360
fi
awk '/Invalid user/&&++try[$NF]>5{gsub(/[)(]/,"",$NF); print $NF; exit}' /var/log/sshd.log |
while read ip
do
    echo 'adding' $ip        
    ipfw -q add 360 deny tcp from $ip to any in
done

Is this what you wanted or did you want first IP that appears more the 5 times as EITHER Reject or Invalid?

1 Like

I'm an idiot. Needs over 5 duh..

Thanks