Tuesday 3 June 2014

Using fail2ban with dated log files

I recently set up a new web server and took advantage of apache's ability to log directly to date stamped log files. This means there is no need to restart apache each day or rotate the logs.

Unfortunately I could not find a way to get fail2ban to recognise the new log file names for example error_20140603.log rather than error.log Even when I managed to add and remove log files using fail2ban-client I found issues as sendmail-whois-lines still searched the original files rather than the latest.

My final solution was to simply write a script to start fail2ban when the server is booted which also runs each day at midnight and takes account of the dated log files.

One problem I faced is fail2ban won't start if it can't find the log file so you have to ensure it exists.

Below is the code which is called by /etc/rc.d/rc.local to ensure fail2ban is started when the server is booted and by cron at midnight.

# define variables
pidfile="/var/run/fail2ban/fail2ban.pid"
nlogfile="/var/log/apache2/error."
nlogfile+=`date +%Y.%m.%d`
nlogfile+=".log"
# check if fail2ban is running
dostart=1
if [ -f $pidfile ];
then
  pid=`cat $pidfile`
  if ps -p $pid > /dev/null
  then
    echo fail2ban is running
    dostart=0
  fi
fi
# create config file
cat < /etc/fail2ban/jail.local
[apache]
enabled  = true
filter   = apache
action   = iptables-multiport[name=APACHE, port="http,https"]
        sendmail-whois-lines[name=APACHE, dest=root, sender=fail2ban@mydomain.com, sendername="fail2ban", logpath=${nlogfile}]
logpath  = ${nlogfile}
maxretry = 0
bantime  = 86400
EOF
# ensure real log file is created
wget http://127.0.0.1/fail2ban.php

sleep 1
# reload/start as required
if [ $dostart == 1 ];
then
  fail2ban-client start
else
  fail2ban-client reload
fi


As you can hopefully see the code creates a new jail.local with the correct logfile name in it.

It also does a wget of a non existant file to cause an error to be logged by the web server. This ensures the dated log file is created by apache and has the correct permissions.

Just remember to ensure apache is started before fail2ban!