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
- Connect to your server with SSH.
- Update the package list:
sudo apt-get update
- Install the module:
sudo apt-get install -y libapache2-mod-security2
This adds ModSecurity to Apache.
- Restart Apache:
sudo service apache2 restart
- 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.
- 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.
- Open it:
sudo nano /etc/modsecurity/modsecurity.conf
- Find the line
SecRuleEngine DetectionOnly. - Change it to
SecRuleEngine On. - Save with Ctrl+O, then Enter, then close with Ctrl+X.
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.
- Install the rule set:
sudo apt-get install -y modsecurity-crs
- Check the Apache module file lists the rules. Open:
sudo nano /etc/apache2/mods-enabled/security2.conf
- Make sure it includes the rules folder, for example
IncludeOptional /usr/share/modsecurity-crs/*.confand theactivated_rulesfiles. - Restart Apache again:
sudo service apache2 restart
Test it
- 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".
- 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 Onto block attacks. - Add the OWASP rules and test your site.