What is ModSecurity?
ModSecurity is an open-source Web Application Firewall (WAF) that acts as a robust line of defense for web servers. By inspecting incoming HTTP traffic against a set of predefined rules, ModSecurity can intercept and block common exploits such as SQL injection, Cross-Site Scripting (XSS), and local file inclusions before they ever reach your application logic.
Step 1: Install ModSecurity
Before proceeding, ensure your Apache web server is installed and running on Ubuntu. To install the ModSecurity module for Apache, open your terminal and execute the following command:
sudo apt-get install libapache2-mod-security2 -y
Step 2: Enable the ModSecurity Module
Once the package is installed, enable the module in Apache and restart the service to apply the changes:
sudo a2enmod security2sudo systemctl restart apache2
Step 3: Configure ModSecurity
By default, ModSecurity is installed in “DetectionOnly” mode, meaning it will log malicious activity but won’t actively block it. To enable blocking, you need to rename the recommended configuration file and edit it:
sudo mv /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf
Open the file in a text editor:
sudo nano /etc/modsecurity/modsecurity.conf
Locate the line that says SecRuleEngine DetectionOnly and change it to:
SecRuleEngine On
Save and close the file.
Step 4: Install the OWASP Core Rule Set (CRS)
ModSecurity relies on rules to know what to block. The OWASP Core Rule Set is a widely trusted collection of rules. Delete the default rules and download the latest CRS from GitHub:
sudo rm -rf /usr/share/modsecurity-crsgit clone https://github.com/coreruleset/coreruleset /usr/share/modsecurity-crs
Rename the CRS setup file:
sudo mv /usr/share/modsecurity-crs/crs-setup.conf.example /usr/share/modsecurity-crs/crs-setup.conf
Step 5: Apply the Rules to Apache
Now, you must tell Apache to load the OWASP rules. Edit the ModSecurity Apache configuration file:
sudo nano /etc/apache2/mods-enabled/security2.conf
Inside the <IfModule security2_module> block, ensure the following lines are present to include the setup file and the rules:
IncludeOptional /usr/share/modsecurity-crs/crs-setup.conf
IncludeOptional /usr/share/modsecurity-crs/rules/*.conf
Restart Apache one final time to enforce the new firewall rules:
sudo systemctl restart apache2
Your Apache web server is now actively protected against the most common web vulnerabilities.