Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

How to Install and Set Up ModSecurity on Ubuntu 16.04

ModSecurity is a firewall for websites. This guide installs it with Apache on Ubuntu 16.04. It needs root access.

Web Hosting2 min read16 steps
Tip: Ubuntu 16.04 is old software. Newer versions work in a similar way, but package names and file paths may differ a little.

What is ModSecurity?

ModSecurity is a web application firewall (WAF). A firewall is a guard that checks traffic. This guard reads each web request and blocks the ones that look like attacks, such as attempts to steal data from your database. It works inside Apache, which is a popular web server program.

Install it

  1. Connect to your server with SSH.
  2. Update the package list:
sudo apt-get update
  1. Install the module:
sudo apt-get install -y libapache2-mod-security2

This adds ModSecurity to Apache.

  1. Restart Apache:
sudo service apache2 restart
  1. Check it is loaded:
apachectl -M | grep security

You should see security2_module in the list.

Turn on blocking

By default ModSecurity only watches and writes logs. You must tell it to block.

  1. Copy the sample settings file:
sudo mv /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf

This creates your real config file from the sample.

  1. Open it:
sudo nano /etc/modsecurity/modsecurity.conf
  1. Find the line SecRuleEngine DetectionOnly.
  2. Change it to SecRuleEngine On.
  3. Save with Ctrl+O, then Enter, then close with Ctrl+X.
Warning: With blocking on, real visitors can be blocked by mistake. Test your site after every change. You can go back to DetectionOnly any time.

Add the rules

Rules are the list of bad patterns to look for. The OWASP Core Rule Set is a popular free list.

  1. Install the rule set:
sudo apt-get install -y modsecurity-crs
  1. Check the Apache module file lists the rules. Open:
sudo nano /etc/apache2/mods-enabled/security2.conf
  1. Make sure it includes the rules folder, for example IncludeOptional /usr/share/modsecurity-crs/*.conf and the activated_rules files.
  2. Restart Apache again:
sudo service apache2 restart

Test it

  1. Visit this in your browser, using your own domain:
http://yourdomain.com/?test=<script>alert(1)</script>

This looks like a script attack. A working setup should answer with "403 Forbidden".

  1. Read the log to see what was blocked:
sudo tail -n 20 /var/log/apache2/modsec_audit.log

This shows the last 20 lines of the audit log.

Fix false alarms

Sometimes a normal action, like saving a blog post, is blocked. Find the rule number in the log. Then disable only that rule for that page. Ask for help if you are unsure: open a support ticket.

Quick recap

  • ModSecurity is a firewall for Apache.
  • Install libapache2-mod-security2.
  • Set SecRuleEngine On to block attacks.
  • Add the OWASP rules and test your site.