Richard Holloway Blog

Add the hostname to email subject in Fail2ban

Posted in April 2012 by under sysadmin

Fail2ban is really useful for blocking brute force attacks against you servers but when you have many servers, it would be useful to have the hostname in the subject line of the email you are sent when an IP address is blocked.

This is not something Fail2ban does but we can easily add it.

There are three steps:

1. Define a variable "host" in you jail.conf, assign the hostname to it and pass it to your action

Open up /etc/fail2ban/jail.conf and edit the action. In my case the action for dovecot-pop3imap is:

action   = iptables-multiport[name=dovecot-pop3imap, port="pop3,pop3s,imap,imaps",
               protocol=tcp]
           sendmail-whois[name=dovecot-pop3imap, dest=admin@mydomain.com,
               sender=fail2ban@server1.mydomain.com]
            

Now add the variable "host" so the action looks like:

action   = iptables-multiport[name=dovecot-pop3imap, port="pop3,pop3s,imap,imaps",
               protocol=tcp]
           sendmail-whois[name=dovecot-pop3imap, dest=admin@mydomain.com,
               sender=fail2ban@server1.mydomain.com, host=server1]
            

2. Use the value in your action.d script

You can see in my example that the action being called is sendmail-whois. So next open /etc/fail2ban/action.d/sendmail-whois.conf.

There are various sections here that send emails. They are "actionstart", "actionstop" and "actionban".

My actionstart for example looks like:

actionstart = printf %%b "Subject: [Fail2Ban] <name>: started on <host>
              From: Fail2Ban <<sender>>
              To: <dest>\n
              Hi,\n
              The jail <name> has been started successfully.\n
              Regards,\n
              Fail2Ban" | /usr/sbin/sendmail -f <sender> <dest>
            

Make similar amendments to the Subject of each section and save the file.

3. Restart fail2ban

For the changes to take effect, you need to restart fail2ban:

service fail2ban restart