#!/bin/bash

# pick the last 10 mins of the owncloud.log (2000 lines should cover that) and count the auth failures 
# format logfile:
#   {"reqId":"O2znvT7UAsoLNo7X7O7W","level":2,"time":"2020-12-29T15:36:37+00:00","remoteAddr":"213.46.222.164","user":"--","app":"core","method":"POST","url":"\/cloud\/index.php\/login","message":"Login failed: 'Ignace. h' (Remote IP: '213.46.222.164')"}

ERRORFILE='/tmp/cloud_error.log'
rm -f ${ERRORFILE}
touch ${ERRORFILE}

NOW=$(date +"%s")
tail -2000 /var/www/owncloud/data/owncloud.log | grep 'Login failed' | while read -r LINE; do
    RDT=$( echo ${LINE} | awk -F'"' '{print $10}')
    D="${RDT:0:10}"
    D=$( echo ${D} | awk -F'-' '{print $2 "/" $3 "/" $1}')
    DT="${D} ${RDT:11:14}"
    DT=$(date --date="${DT}" +"%s")
    (( SECS = NOW - DT ))
    if [[ ${SECS} -lt 601 ]] ; then
        echo $LINE} >>${ERRORFILE}
	IP=$(echo ${LINE} | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b")
	addEvent.sh "BLOCK,${IP},3,5,Unauthorized authorization attempt in ownCloud"
    fi
done

cat ${ERRORFILE} | wc -l
