Since 1999

 

2 minutes estimated reading time.

ModSecurity and Fail2Ban as an Intrusion Prevention System

ModSecurity and fail2ban can be used as an open source intrusion prevention system.

The setup is pretty straight forward:

  1. Configure ModSecurity to detect some attacks against your system
  2. Configure fail2ban to read the ModSecurity audit log file

Configure ModSecurity

Install a commercial ruleset or open source ruleset, such as the OWASP ModSecurity Core Rule Set, for your ModSecurity web application firewall.

One of the neat tricks in the OWASP ruleset is that if your application raises an exception or certain content appears to leak out then it triggers a 403 Unauthorized HTTP response rather than returning the content to a potential attacker.

This error condition can be detected by fail2ban through the next configuration example.

Configure fail2ban

An example configuration for ModSecurity

Create /etc/fail2ban/filter.d/modsec.conf

This is the filter for the mod_security audit file.

  # Fail2Ban configuration file
  #
  # Author: Florian Roth

  [Definition]
  failregex = \[.*?\]\s[\w-]*\s<HOST>\s
  ignoreregex =

You can read more about this filter at HOWTO fail2ban with ModSecurity2.5 (fail2ban.org).

Edit the /etc/fail2ban/jail.conf

  #
  # HTTP servers
  #

  [modsec]
  enabled  = true
  filter   = modsec
  action   = iptables-multiport[name=ModSec, port="http,https"]
  sendmail-buffered[name=ModSec, lines=5, dest=hostmaster@rietta.com]
  logpath  = /var/log/apache2/modsec_audit.log
  bantime  = 172800
  maxretry = 3

  [apache]
  enabled  = true
  port     = http,https
  filter   = apache-auth
  logpath  = /var/log/apache*/*error.log
  maxretry = 6

Next steps

Now that you have a way to detect exceptions in your web application and to push rules to a firewall to block offending IP addresses for a period of time, you can design your web application to work in concert with the network level tools to respond to an attack against your app.

For example, if your application detects that a user is doing something unauthorized raise and exception and after the 3rd attempt that IP address will be blocked for 48 hours! Perhaps, you can craft a rule the detects the presence of honey tokens that triggers an immediately lockout and notifies your security response team of an active attack! In other words, booby trap your application!

Further reading