Protecting Apache with fail2ban and mod_security

Tim Williams • March 26, 2017

Since I run a lot of custom servers I have found the open source tool fail2ban to be quite useful! Fail2ban is an open source log based IP bouncer. Essentially it reads specific logs that you configure and adds abusive requests to IPTables to be dropped. It should be available on most linux systems via whatever package manager you prefer.

Yum installation:

$ sudo yum install fail2ban

Here is my recommended settings for an Amazon Linux system. Open a text editor to /etc/fail2ban/jail.local

$ sudo nano /etc/fail2ban/jail.local

Add in these settings:

[apache]
enabled  = true
port     = http,https
filter   = apache-auth
logpath  = /var/log/httpd/error_log
maxretry = 3
findtime = 600
ignoreip = 192.168.1.227

[apache-noscript]
enabled  = true
port     = http,https
filter   = apache-noscript
logpath  = /var/log/httpd/error_log
maxretry = 3
findtime = 600
ignoreip = 9999.your.ip.9999

[apache-overflows]
enabled  = true
port     = http,https
filter   = apache-overflows
logpath  = /var/log/httpd/error_log
maxretry = 2
findtime = 600
ignoreip = 9999.your.ip.9999

[apache-badbots]
enabled  = true
port     = http,https
filter   = apache-badbots
logpath  = /var/log/httpd/error_log
maxretry = 2
findtime = 600
ignoreip = 9999.your.ip.9999

[php-url-fopen]

enabled = true
port    = http,https
filter  = php-url-fopen
logpath = /var/log/httpd/error_log
maxretry = 1

Close and save those settings then start the fail2ban process:

sudo service fail2ban start

Then check and make sure it is running:

$ sudo service fail2ban status
Fail2ban (pid 31182) is running...
Status
|- Number of jail:  6
`- Jail list:       php-url-fopen, apache-overflows, apache-noscript, ssh-iptables, apache-badbots, apache

If you’re running Apache 2.4, my development mentor (Michael) highly recommends also installing mod_security this will help guard agains some common SQL injection attacks.

sudo yum install mod_security_crs --skip-broken

If you’re using WordPress with modsec, you’ll need to use the wordpress filters: OWASP Wordpress