ModSecurity 2 is a core security component for Apache HTTP servers that works as a web application firewall (WAF), providing real-time monitoring and filtering via rules. ModSecurity protects from SQL injections, cross-site scripting (XSS), and other attacks when installed on a Debian 12 or 11 Linux server. With the Digitalwave ModSecurity Repository, the installation becomes easy and simple as we are using the latest stable version.
For increasing the security, OWASP Core Rule Set (CRS) comes with sets of predefined rules focusing on common vulnerabilities. If properly set up, a few quick manual configurations help administrators reinforce defenses. In this guide, we will be installing ModSecurity 2 on Debian and configuring it for protection using OWASP CRS, utilizing the Digitalwave repository.
Update Debian System Packages for ModSecurity 2 Installation
Start by ensuring your Debian system is updated. Keeping all packages current not only boosts performance but also minimizes security vulnerabilities. Use the following command:
sudo apt update && sudo apt upgrade
After updating, check if Apache is installed on your system. If it isn’t, install it with this command:
sudo apt install apache2
Import ModSecurity Module PPA
Setting up the Required Repository
The next step involves installing the ModSecurity Apache Module. The version available in Debian’s default repositories might be outdated, which could lead to errors. Instead, we’ll use a third-party repository maintained by Digitalwave, known for providing stable binaries of the latest ModSecurity Module for Apache.
Start by installing the necessary packages:
sudo apt install apt-transport-https lsb-release ca-certificates curl -y
Next, import the GPG key for the ModSecurity 2 Module PPA repository:
curl -fsSL https://modsecurity.digitalwave.hu/archive.key | sudo gpg --dearmor | sudo tee /usr/share/keyrings/digitalwave-modsecurity.gpg > /dev/null
Once the GPG key is in place, add the repository to your system:
echo "deb [signed-by=/usr/share/keyrings/digitalwave-modsecurity.gpg] http://modsecurity.digitalwave.hu/debian/ $(lsb_release -sc) main" | sudo tee -a /etc/apt/sources.list.d/digitalwave-modsecurity.list
echo "deb [signed-by=/usr/share/keyrings/digitalwave-modsecurity.gpg] http://modsecurity.digitalwave.hu/debian/ $(lsb_release -sc)-backports main" | sudo tee -a /etc/apt/sources.list.d/digitalwave-modsecurity.list
Prioritizing the New Apache Module PPA Repository
With the repository in place, it’s now necessary to adjust the APT policy to prioritize this repository for specific packages related to ModSecurity. The following command accomplishes this:
cat << EOF | sudo tee -a /etc/apt/preferences.d/99modsecurity
Package: *nginx*
Pin: origin modsecurity.digitalwave.hu
Pin-Priority: 900
Package: *libapache2-mod-security2*
Pin: origin modsecurity.digitalwave.hu
Pin-Priority: 900
Package: *modsecurity-crs*
Pin: origin modsecurity.digitalwave.hu
Pin-Priority: 900
Package: *libmodsecurity*
Pin: origin modsecurity.digitalwave.hu
Pin-Priority: 900
EOF
Next, run an APT update to reflect the newly imported source:
sudo apt update
Additionally, to confirm the preferences, you can confirm this policy change with the following:
sudo apt-cache policy libapache2-mod-security2 modsecurity-crs libmodsecurity3
Install ModSecurity 2 Module
Now that the repository is ready, proceed with the installation of the libapache2-mod-security2 module:
sudo apt install libapache2-mod-security2
After installation, the module must be enabled. Use the following command to achieve this:
sudo a2enmod security2
Restarting Apache Service
Lastly, we restart the Apache service to make sure all changes take effect and the newly added ModSecurity module is correctly integrated:
sudo nano /etc/apache2/mods-enabled/security2.conf
Enable ModSecurity 2 Module on Apache HTTP
Accessing the ModSecurity Configuration File
The configuration file for Apache ModSecurity can be found at /etc/apache2/mods-enabled/security2.conf. Access this file using the nano text editor (or your preferred text editor) with the following command:
sudo nano /etc/apache2/mods-enabled/security2.conf
Look for the line that reads:
IncludeOptional /etc/modsecurity/*.conf
Ensure this line is uncommented, as it includes other necessary configuration files from the /etc/modsecurity directory. It should be uncommented by default.
Modifying the ModSecurity 2 Configuration
We need to rename the modsecurity.conf-recommended configuration file to modsecurity.conf to make it active. This can be done with the following command:
sudo mv /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf
Now, let’s open this newly named configuration file:
sudo nano /etc/modsecurity/modsecurity.conf
The ModSecurity rule engine is set to DetectionOnly by default within this file. This means it will identify and log potentially malicious behavior without blocking it. To change this and enable ModSecurity’s blocking capabilities, locate the SecRuleEngine line (around line 7) and replace DetectionOnly with On.
From:
SecRuleEngine DetectionOnly
To:
SecRuleEngine On
Adjusting Log Settings for Apache
Further down the configuration file, you will find the SecAuditLogParts line (around line 224). The default setting for this line isn’t quite correct; it needs to be adjusted to log all transaction information accurately.
Change:
SecAuditLogParts ABDEFHIJZ
To:
SecAuditLogParts ABCEFHJKZ
With these modifications in place, save your changes and exit the editor.
Restarting Apache to Apply Changes
Our final step in this process is to restart the Apache service so that our changes to the ModSecurity configuration take effect. This is accomplished using the following command:
sudo systemctl restart apache2
Install OWASP Core Rule Set for ModSecurity2
ModSecurity alone does not safeguard your webserver. It requires a rule set to identify potential threats and block malicious activity. The OWASP (Open Web Application Security Project) Core Rule Set (CRS) is a highly regarded rule set used by various webservers and Web Application Firewalls (WAFs). Deploying this rule set furnishes your server with robust protection against a range of threats emerging on the internet.
Before we proceed, it is essential to verify that you have the latest version of OWASP CRS by visiting the OWASP Release tag page. This step ensures that you download and install the most up-to-date security measures for your server.
Creating the Parent Directory for OWASP CRS
First, let’s create the leading parent directory for OWASP using the mkdir command:
sudo mkdir /etc/apache2/modsec/
Download OWASP CRS Archive on Debian
Next, we’ll use the wget command to fetch the OWASP CRS 3.3.4 archive, which is the stable version at the time of writing. Remember that you should verify the version using the link mentioned earlier.
wget https://github.com/coreruleset/coreruleset/archive/refs/tags/v3.3.4.zip
The nightly build may offer more up-to-date security measures but could cause issues due to its development status. For new users, it is advisable to use the stable version to avoid potential complications.
Note: You should constantly check for updates; the stable rules do not change weekly but every quarter or unless an urgent update is required.
Extracting the Archive
With the archive downloaded, we can extract it into the directory we created earlier:
sudo tar xvf v3.3.4.tar.gz -C /etc/apache2/modsec
Remember to change the commands based on the OWASP CRS version you downloaded.
Configuring the Rule Set
The OWASP CRS has a sample configuration file you should rename while retaining the original as a backup. You can do this using the ‘cp command’:
sudo cp /etc/apache2/modsec/coreruleset-3.3.4/crs-setup.conf.example /etc/apache2/modsec/coreruleset-3.3.4/crs-setup.conf
Note: Remember to replace /coreruleset-3.3.4/ with the exact version of the OWASP CRS you chose.
Enabling the Rules
To activate the rules, open the /etc/apache2/mods-enabled/security2.conf file:
sudo apt install unzip -y
Then, insert the following two lines:
Include /etc/apache2/modsec/coreruleset-3.3.4/crs-setup.conf
Include /etc/apache2/modsec/coreruleset-3.3.4/rules/*.conf
Note: Again, ensure you replace /coreruleset-3.3.4/ with the exact version of OWASP CRS you’ve selected, as the coreruleset you will download will most likely be newer than the guide’s example.
Additionally, comment out or remove the following line:
IncludeOptional /usr/share/modsecurity-crs/*.load
Once done, save and exit the file:
Restarting Apache to Apply Changes
The last step is to restart your Apache service to ensure the changes take effect:
sudo systemctl restart apache2
Getting Started with OWASP Core Rule Set and ModSecurity 2
The OWASP Core Rule Set (CRS) is a comprehensive tool with numerous customizable options. Its default configuration provides immediate security enhancements for most servers without impacting genuine visitors or Search Engine Optimization (SEO) bots. We will discuss a few significant aspects of the CRS in this section, but exploring the configuration files for a complete understanding of all available options is always beneficial.
Adjusting the CRS Configuration
We initiate by opening the crs-setup.conf file where most of the CRS settings can be altered:
sudo nano /etc/apache2/modsec/coreruleset-3.3.4/crs-setup.conf
Understanding the CRS Scoring System
ModSecurity operates in two distinct modes:
- Anomaly Scoring Mode: Recommended for most users, this mode assigns an ‘anomaly score’ each time a rule matches. After processing both inbound and outbound rules, the anomaly score is checked, and a disruptive action is triggered if necessary. This action often takes the form of a 403 error. This mode provides accurate log information and offers greater flexibility in setting blocking policies.
- Self-Contained Mode: In this mode, an action is applied instantly whenever a rule is matched. While it can reduce resource usage, it offers less flexibility and yields less informative audit logs. The rule-matching process stops when the first rule is met and the specified action is executed.
Understanding Paranoia Levels
The OWASP CRS defines four paranoia levels:
- Paranoia Level 1: The default level is suitable for most users.
- Paranoia Level 2: For advanced users.
- Paranoia Level 3: For expert users.
- Paranoia Level 4: Only advisable under extraordinary circumstances.
Higher paranoia levels enable additional rules, increase security, and augment the likelihood of blocking legitimate traffic due to false positives. Choosing a paranoia level that aligns with your expertise and security needs is essential.
Testing OWASP CRS on Your Server
To ensure the OWASP CRS is operating correctly on your server, use your internet browser to access the following URL. Remember to replace “yourdomain.com” with your actual domain:
https://www.yourdomain.com/index.html?exec=/bin/bash
If you receive a 403 Forbidden error, OWASP CRS will function as expected. If not, there might be a misstep in the setup process that requires your attention; the most common issue can be forgetting to change DetectionOnly to On or something similar.
Address False Positives and Custom Exclusion Rules
Managing false positives with ModSecurity and the OWASP Core Rule Set (CRS) can be an ongoing task. However, the robust defense these systems offer against a wide range of threats makes this effort essential. To minimize false positives initially, it is advisable to set a low paranoia level.
By running the rule set at a lower paranoia level for several weeks or even months, you can reduce the likelihood of an overwhelming number of false positives. This approach gives you time to familiarize yourself with the alerts and the appropriate responses before gradually increasing the paranoia level for more stringent security.
Managing False Positives in Known Applications on Debian with OWASP, ModSecurity 2
ModSecurity includes the capability to whitelist certain actions that may unintentionally trigger false positives. For example:
#SecAction \
# "id:900130,\
# phase:1,\
# nolog,\
# pass,\
# t:none,\
# setvar:tx.crs_exclusions_cpanel=1,\
# setvar:tx.crs_exclusions_dokuwiki=1,\
# setvar:tx.crs_exclusions_drupal=1,\
# setvar:tx.crs_exclusions_nextcloud=1,\
# setvar:tx.crs_exclusions_phpbb=1,\
# setvar:tx.crs_exclusions_phpmyadmin=1,\
# setvar:tx.crs_exclusions_wordpress=1,\
# setvar:tx.crs_exclusions_xenforo=1"
To enact whitelisting for applications such as WordPress, phpBB, and phpMyAdmin, uncomment the respective lines and maintain the (1) value. To prevent the whitelisting of services not in use, adjust the value to (0).
The updated configuration could look as follows:
SecAction \
"id:900130,\
phase:1,\
nolog,\
pass,\
t:none,\
setvar:tx.crs_exclusions_phpbb=1,\
setvar:tx.crs_exclusions_phpmyadmin=1,\
setvar:tx.crs_exclusions_wordpress=1"
In this instance, extraneous options have been removed, leaving the correct syntax for the configurations you require.
Creating Rule Exclusions Before CRS Implementation
To create custom exclusions, begin by renaming the “REQUEST-900-EXCLUSION-RULES-BEFORE-CRS-SAMPLE.conf” file using the following command:
sudo cp /etc/apache2/modsec/coreruleset-3.3.4/rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf.example /etc/apache2/modsec/coreruleset-3.3.4/rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf
Remember, each exclusion rule must have a unique ‘idnumber’ to avoid errors during Apache2 service testing.
For example, some “REQUEST_URIs” may cause false positives. The following example illustrates two such cases involving Google PageSpeed beacon and the WPMU DEV plugin for WordPress:
SecRule REQUEST_URI "@beginsWith /wp-load.php?wpmudev" "id:1544,phase:1,log,allow,ctl:ruleEngine=off"
SecRule REQUEST_URI "@beginsWith /ngx_pagespeed_beacon" "id:1554,phase:1,log,allow,ctl:ruleEngine=off"
These rules automatically allow any URL beginning with the specified path.
You can also whitelist specific IP addresses:
SecRule REMOTE_ADDR "^195\.151\.128\.96" "id:1004,phase:1,nolog,allow,ctl:ruleEngine=off"
SecRule REMOTE_ADDR "@ipMatch 127.0.0.1/8, 195.151.0.0/24, 196.159.11.13" "phase:1,id:1313413,allow,ctl:ruleEngine=off"
In the first rule, a single IP address is whitelisted, while the second rule uses the ‘@ipMatch’ directive for broader subnet matching. To block a subnet or IP address, simply replace ‘allow’ with ‘deny’. This flexibility allows you to create detailed blacklists and whitelists, which can be integrated with Fail2Ban for an enhanced security strategy.
Disabling Specific Rules on Debian with OWASP, ModSecurity 2
Instead of whitelisting an entire path, another approach is to disable specific rules that cause persistent false positives. Although this method requires more testing, it offers long-term benefits.
For instance, if rules 941000 and 942999 in the “/admin/” area trigger false positives for your team, you can locate the rule ID in your ModSecurity logs and disable only those specific IDs using the “RemoveByID” command:
SecRule REQUEST_FILENAME "@beginsWith /admin" "id:1004,phase:1,pass,nolog,ctl:ruleRemoveById=941000-942999"
Monitoring Logs and Identifying Patterns
Continuous log monitoring is essential when handling false positives with Apache, ModSecurity, and OWASP. It helps identify patterns that trigger false positives, allowing you to create custom rules to address them.
For example, if specific rules consistently cause false positives, you can craft an exclusion rule to handle these specific instances. This tailored approach ensures more effective management of false positives.
By regularly reviewing your logs and adjusting your rules, you can maintain a more secure and efficient environment for your applications.
Log Rotation for ModSecurity 2
Due to the dynamic nature of web transactions, ModSecurity logs can grow quickly, making effective log management crucial. Log rotation is a useful tool for managing these logs, though it is not configured by default in ModSecurity. This section will guide you through setting up log rotation specifically for ModSecurity.
Creating a ModSecurity Rotation File
First, you need to create a dedicated file for ModSecurity log rotation. To do this, use the following command to create and open a new file named modsec:
sudo nano /etc/logrotate.d/modsec
Configuring the Rotation File
In the newly created ModSecurity (modsec) configuration file, add the following:
/var/log/modsec_audit.log
{
rotate 31
daily
missingok
compress
delaycompress
notifempty
}
This configuration retains logs for 31 days, but you can modify the number to fit your needs. For example, changing it to ‘rotate 7’ will keep a week’s worth of logs instead.
The ‘daily’ directive ensures logs are rotated every day, while ‘compress’ saves space by compressing old logs. The ‘delaycompress’ option delays compression until the second rotation cycle, and ‘missingok’ prevents errors if the log file is absent. Additionally, ‘notifempty’ ensures empty log files aren’t rotated.
Tip: Daily log rotation is advisable to avoid dealing with overly large log files, which can make analysis more time-consuming.
Conclusion
You’ve now installed ModSecurity 2 on your Debian 12 or 11 server using the Digitalwave repository and configured the OWASP Core Rule Set. With these tools in place, your server is equipped to block many common web application threats.
Remember to regularly update the CRS and monitor for any false positives or missed vulnerabilities. Consistent testing and adjustments are key to maintaining a robust security setup.
Not a bad article, everything is explained in detail, but some parts feel overly drawn out. I liked that it covers not only the installation of ModSecurity but also the setup of the OWASP Core Rule Set. This is useful for those just starting to explore web security. The section on paranoia levels and handling false positives stood out—it clearly highlights what to focus on to ensure stable system performance. One thing I wish it had is more practical examples for setting up exclusions for popular applications like WordPress or phpMyAdmin. Overall, it’s a solid resource, especially for beginners.
Thanks Alex, I could not cover too much more into OWASP core rule set as the needs a separate beginners guide and probably advanced guides, so many possibilities with the core rule set to customize, whitelist, create custom options and much more. The guide was just focused on installing it and doing a brief run through as you mentioned.
Appreciate the feedback.