#!/bin/bash

MAX_MB_DAY=25 # max. daily traffic per ip
DB=system-log # sql-database
WHITELIST="78.46.84.243 78.46.84.244 176.9.89.165 176.9.33.188" # never block whitelisted IP
HTACCESS=/srv/www/clamav.net/httpdocs/.htaccess # add "Deny from" from .htaccess direct to the firewall
XT_RECENT=/proc/net/xt_recent/DenyAccessClamAV

# binaries
IPTABLESBIN=/usr/local/sbin/iptables
SQLBIN=`which mysql`

# for statistics send to syslog like 
# mx03.schaal-24..de traffic-clamav: added 2 ip to /proc/net/xt_recent/DenyAccessClamAV (old: 159; new: 161)
#define and uncomment:
#SYSLOG_TAG=traffic-clamav
#LOGGER=`which logger`

# calculate allowed traffic
DOM=`date +%e|cut -d" " -f2`
let MAX_TRAFFIC=$DOM*$MAX_MB_DAY # set allowed_traffic to day of month * MAX_MB_DAY

# uncomment for statistics:
#OLD=`cat $XT_RECENT|wc -l`

# get ip from database with traffic >= MAX_TRAFFIC
$SQLBIN $DB -e "select INET_NTOA(source) as source from clamavtraffic where bytes >= $MAX_TRAFFIC*1048576 order by bytes;"|grep -v source|while read ip; do
  # add ip to xt_recent
  echo +$ip > $XT_RECENT
done

# block clients from .htaccess
grep "Deny from" $HTACCESS | grep -v "env="| cut -d" " -f3|while read ip; do
  echo +$ip > $XT_RECENT
done

# remove whitelisted ip from firewall (checking during ban will increase the runtime, so just remove them)
for ip in $(echo $WHITELIST); do
  echo -$ip > $XT_RECENT
done

# uncomment for statistics:
#NEW=`cat $XT_RECENT|wc -l`
#if (( $NEW > $OLD )); then
#  let diff=$NEW-$OLD
#  logger -d -t $SYSLOG_TAG "added $diff ip to $XT_RECENT (old: $OLD; new: $NEW)"
#fi
