#!/bin/bash

IPSFILE="/tmp/lastIPs.txt"

if [[ $1 == 'count' ]] ; then
    # pick the last 10 mins of the auth.log (2000 lines should cover that) and count the auth failures for ssh
    rm -f ${IPSFILE}
    NOW=$(date +"%s")
    tail -2000 /var/log/auth.log | grep sshd | grep -e "failure" -e "invalid" | ./last10mins | while read LINE; do
        # send the ip-address to a temp file
        echo "$LINE" | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b" >>${IPSFILE}
    done
    # count the number of lines found
    cat ${IPSFILE} | wc -l
fi

if [[ $1 == 'block' ]] ; then
    cat ${IPSFILE} | sort -u | while read LINE; do
        IP=$(echo ${LINE} | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b")
        addEvent.sh "BLOCK,${IP},0,0,Unauthorized authorization attempt in SSH"
	# ufw deny from $LINE
    done
    cat ${IPSFILE} | sort -u | wc -l
fi
