CentOS 7 - Fail2Ban with Apache ModSecurity


One of the tools I am using to secure a server is Fail2ban. It was working well for SSH and I wanted to extend it to provide more protection for Apache.

I installed it and enabled it.

jail.d/apache-modsecurity.conf

[apache-modsecurity]
enabled = true
backend = auto
port = http,https
filter = apache-modsecurity
logpath = %(apache_error_log)s
bantime = 19200
maxretry = 2
findtime = 3600
ignoreip = 127.0.0.0/8 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16

filter.d/apache-modsecurity.conf 

# Fail2Ban apache-modsec filter
#

[INCLUDES]

# Read common prefixes. If any customizations available -- read them from
# apache-common.local
before = apache-common.conf

[Definition]
failregex = ^%(_apache_error_client)s(?: \[client [\d\.:]+\])? ModSecurity:\s+(?:\[(?:\w+ \"[^\"]*\"|[^\]]*\]\s*)*Access denied with code [45]\d\d (?:.*)$
ignoreregex =

# https://github.com/SpiderLabs/ModSecurity/wiki/ModSecurity-2-Data-Formats
# Author: Daniel Black
# Sergey G. Brester aka sebres (review, optimization)



Helpful commands

  • firewall-cmd --permanent --zone=public --add-service=http - allow HTTP through (add https as well)
  • fail2ban-client reload apache-modsecurity - reload the Apache ModSecurity configuration
  • fail2ban-client status apache-modsecurity - check the status of Apache ModSecurity configuration
  • fail2ban-client get apache-modsecurity failregex - get the regex which will cause fail2ban to ban entries (if maxretries)
  • fail2ban-regex /var/log/httpd/error_log '^\[\]\s\[(:?error|\S+:\S+)\]( \[pid \d+(:\S+ \d+)?\])? \[client (?:\[?(?:(?:::f{4,6}:)?(?P(?:\d{1,3}\.){3}\d{1,3})|(?P(?:[0-9a-fA-F]{1,4}::?|::){1,7}(?:[0-9a-fA-F]{1,4}|(?<=:):)))\]?|(?P[\w\-.^_]*\w))(:\d{1,5})?\](?: \[client [\d\.:]+\])? ModSecurity:\s+(?:\[(?:\w+ \"[^\"]*\"|[^\]]*)\]\s*)*Access denied with code [45]\d\d (?:.*)$' - check the regex
  • h-rules | grep http - list the current http (and https) - there's probably a better way to do this