How to Install ModSecurity 3, OWASP CRS with Nginx on Debian 12

Introduction

Before we begin talking about how to install ModSecurity 3, OWASP CRS with Nginx on Debian 12, let's briefly understand – What is ModSecurity 3?

ModSecurity 3 is a powerful open-source web application firewall (WAF) designed to enhance security and protect websites from various cyber threats. It provides proactive defense mechanisms by analyzing HTTP traffic and blocking malicious activities, such as SQL injections and cross-site scripting (XSS) attacks.

OWASP, which stands for Open Web Application Security Project, is a globally recognized nonprofit organization that focuses on improving the security of web applications. The mission of OWASP is to make web applications more secure by providing tools, documentation, and resources to developers, administrators, and organizations.

In this tutorial, you will install ModSecurity 3, OWASP CRS with Nginx on Debian 12. We will also address a few FAQs on how to install ModSecurity 3, OWASP CRS with Nginx on Debian 12.

Advantages of ModSecurity 3

  1. Enhanced Website Security: ModSecurity 3 provides robust protection against web application attacks, safeguarding websites from potential threats like SQL injections and cross-site scripting (XSS).
  2. Customizable Rules: With a flexible rule-based engine, ModSecurity 3 allows customization to fit specific security needs, enabling tailored defenses.
  3. Open-Source and Free: ModSecurity 3 is an open-source solution, making it accessible and cost-effective for organizations seeking web application protection.
  4. Seamless Integration: ModSecurity 3 is compatible with popular web servers like Apache and Nginx, ensuring easy integration into existing infrastructures.
  5. Proactive Defense Mechanisms: By analyzing and monitoring HTTP traffic, ModSecurity 3 blocks potential threats before they compromise the security of web applications, providing proactive defense.

Pre-Installation Steps with ModSecurity 3 with Nginx on Debian 12

It is crucial that we sufficiently prepare our server before beginning the ModSecurity installation. This entails maintaining the most recent version of NGINX, a high-performance web server and reverse proxy server, and updating our system. These preparatory steps eliminate potential incompatibilities and plug security holes, thereby fostering an installation process that is smooth and error-free.

Step 1: Update Debian System Packages Before ModSecurity 3 with Nginx Installation

Maintaining it on a regular basis is the route to a secure and effective server. All software packages are guaranteed to have the most recent security patches and performance enhancements through regular updates. Run the following command to maintain the most recent version of your system:

sudo apt update && sudo apt upgrade

To make sure your system is up to date with all available updates, run sudo apt update first. This updates the package list for upgrades.

Step 2: Remove Existing NGINX Installation (Situational)

💡
In case you have already installed Nginx, you can skip this step. In the event that you choose to delete it and your setup is complicated, be sure to backup your configuration files.

We advise you to remove any current NGINX installation in order to make room for the newest version, which is available from a special PPA that is kept up to date by Ondřej Surý. With the addition of new dynamic modules like the Brotli module, this version promises better compression.

In order to do this, first stop the running instance of NGINX by doing the following:

sudo systemctl stop nginx

Next, make sure the current NGINX installation is gone using:

sudo apt purge nginx
sudo apt autoremove nginx

The purge option in this command completely removes the NGINX package and all of its configuration files. Any packages that were installed automatically to meet NGINX dependencies but are no longer needed are removed using the autoremove command.

Step 3: Import NGINX PPA for ModSecurity 3 and Debian for Latest Version (Optional)

💡
Although optional, taking this step is strongly advised. Please make sure that you download the corresponding source files if you decide not to use this method and instead run Nginx using the standard Debian version. Later on in the guide, this ought to be simple to figure out.

Once the old NGINX service has been removed, add a fresh, current NGINX Personal Package Archive (PPA). Select between the mainline and stable versions. The mainline version, which comes with the newest features and enhancements, is generally advised.

Run the following command to add the new PPA:

curl -sSL https://packages.sury.org/nginx-mainline/README.txt | sudo bash -x

Step 4: Refresh APT Cache after Nginx PPA Import on Debian

It becomes necessary to update your APT sources list after the desired repository is added. Making sure the system detects the new packages in the added repository is the goal of this step. Add the following to your list of references:

sudo apt update

After applying the updates, carry out the following steps to install NGINX:

sudo apt install nginx-core nginx-common nginx

You might get a prompt during the installation asking if you want to replace or keep your current /etc/nginx/nginx.conf configuration file. It is generally advisable to save your current configuration file by pressing n in order to prevent any unplanned disruptions.

Step 5: Import NGINX Source Code PPA Configuration File on Debian

The NGINX source code is not by default bundled with the PPA installation. But before you can manually download the NGINX source code and compile ModSecurity in the later steps of this guide, you must enable this feature.

Open the configuration file in /etc/apt/sources.list.d to begin this process.

sudo nano /etc/apt/sources.list.d/nginx-mainline.list

If you installed Nginx or got it from another third-party source, this filename will be different.

Now, right beneath the original source line, add the following:

deb-src [signed-by=/usr/share/keyrings/deb.sury.org-nginx-mainline.gpg] https://packages.sury.org/nginx-mainline/ bookworm main
Adding deb-src repositories for Debian 12 in preparation for Modsecurity 3 installation

After finishing, hit CTRL+O to save your changes, and CTRL+X to close the editor.
Refresh the repository list with the following to wrap up this step:

sudo apt update

By running this command, you can be sure that your system will acknowledge that the NGINX source code is now part of the repository and be available for use in other commands.

Download Nginx Source For ModSecurity 3 on Debian 12

For ModSecurity and Nginx to seamlessly integrate, we need to compile the ModSecurity dynamic module using the Nginx source code. This means that we have to retrieve and save the Nginx source code in a particular directory, which we will call /usr/local/src/nginx.

This section will walk you through the process of making the necessary directories, setting up the dependencies, obtaining the source code, and confirming that the source version that you retrieved matches the version of Nginx that is installed on your system.

Step 1: Create Directory Structure for Nginx Source on Debian

Create the directory where the Nginx source code will be fetched and stored first. The command to create and access the directory is as follows:

sudo mkdir /usr/local/src/nginx && cd /usr/local/src/nginx

Step 2: Install Initial Packages and Fetch the Nginx Source Code

Make sure the dpkg-dev package is installed before downloading the source code. Several development tools for building, uploading, and unpacking Debian source packages are included in this package. Use the following command to install it:

sudo apt install dpkg-dev -y

Now that the necessary tools have been installed, we can retrieve the Nginx source code by using:

sudo apt source nginx

Don't worry if you get an error message when using this command; you can safely ignore it.

Error message that can be ignored when downloading Nginx source for Modsecurity 3 installation on Debian 12

Step 3: Verifying the Source Version on Debian

💡
This is an important section. If you use a different version of the Nginx source than the one that is currently installed on your Debian system, compilation will fail and errors will occur. Here is where you need to pay great attention.

Make sure the source code you download matches the Nginx version that is installed on your computer. This verification step is vital because any version disparity can lead to compatibility problems.

Use the following command to first list the files in the current directory and verify that the source code download was successful:

ls

The output should include a number of Nginx-related files and directories.

Nginx source files before proceeding with Modsecurity 3 installation on Debian 12

Make sure the version of the source package corresponds to the Nginx version that is set up on your Debian system. To see which version of Nginx is installed, run the following command:

nginx -v

The output will show the version of Nginx that you have installed. Making sure that this version matches the source version you downloaded is essential. You'll need to retrieve the correct Nginx source code version if they don't line up.

Install libmodsecurity3 on Debian 12

libmodsecurity3 serves as the foundation for ModSecurity's powerful web application firewall, which makes HTTP filtering easier. This section will assist you in obtaining and installing this essential software.

Step 1: Fetch ModSecurity 3 Repository on Debian

Using Git, a popular distributed version control system, download the source code for libmodsecurity3 from its GitHub repository first. Use this command to install Git if it's not already installed on your system:

sudo apt install git -y

Change the directory ownership before cloning the repository to prevent most commands from requiring root privileges (sudo):

sudo chown -R $USER:$USER /usr/local/src/

The ownership of the /usr/local/src/ directory is changed recursively to the current user by this command.

Cloning the libmodsecurity3 repository is the next step. To save storage space and bandwidth, we'll perform a shallow clone --depth 1, which means we'll only retrieve the most recent version of the v3/master branch:

git clone --depth 1 -b v3/master --single-branch https://github.com/SpiderLabs/ModSecurity /usr/local/src/ModSecurity/

After cloning the repository, move your current working directory to the newly created copy:

cd /usr/local/src/ModSecurity/

Step 2: Install libmodsecurity3 Initial Packages on Debian

libmodsecurity3 requires a number of dependencies to compile. Use the following to install them:

sudo apt install gcc make build-essential autoconf automake libtool libcurl4-openssl-dev liblua5.3-dev libfuzzy-dev ssdeep gettext pkg-config libpcre3 libpcre3-dev libxml2 libxml2-dev libcurl4 libgeoip-dev libyajl-dev doxygen libpcre2-16-0 libpcre2-dev libpcre2-posix3 -y

As of version 1.21.4, indispensible dependencies are required for the successful compilation of Nginx with ModSecurity. In most cases, installing the correct dependencies will fix the issues that some users report during this step.

Next, use the following commands to initialize and update the Git submodules:

git submodule init
git submodule update

Step 3: Build the ModSecurity 3 Environment on Debian

Now that our workspace is ready, we can build the ModSecurity environment. Start by running the build script:

./build.sh
Setting up the build environment for Modsecurity 3 and Nginx on Debian 12

Configure the environment after that:

./configure

You may receive an error message saying fatal: No names found, cannot describe anything during this process. You can ignore this error message without risk.

Configuring the necessary environment for Modsecurity 3 and Nginx connector on Debian 12

Step 4: Compile the ModSecurity 3 Source Code on Debian

We are prepared to compile libmodsecurity3 now that the environment has been built and set up. For this purpose, the following command is useful:

make

On high-performance servers, run make with the -j option and then the number of CPU cores your server has to speed up the compilation process. Use the following command, for instance, if your server has six CPU cores:

make -j 6
Showing the output of the ‘make’ command during the build process for Modsecurity and Nginx connector on Debian 12

Step 5: Install the Compiled Code of ModSecurity 3 on Debian

Now that the source code has been compiled, we can install the compiled code as the last step:

sudo make install

This command installs libmodsecurity3 in the directory /usr/local/modsecurity/, which will be used as a reference by later sections of this guide.

Using the ‘make install’ command to build the Nginx connector for Modsecurity 3 on Debian 12

Install ModSecurity-nginx Connector on Debian 12

Your web applications' security can be greatly increased by installing ModSecurity-nginx, the essential mediator between ModSecurity and the widely-used Nginx web server. We'll carefully walk you through the process of configuring this connector on your Debian server in this section.

Step 1: Fetch ModSecurity-nginx Connector Source on Debian

Getting the source code for the ModSecurity-nginx connector is the first step in our journey. This source code is available from the GitHub repository. If this sounds familiar, it is because the procedure is the same as the previous one used to obtain the source code for libmodsecurity3. To clone the ModSecurity-nginx repository, use this command:

git clone --depth 1 https://github.com/SpiderLabs/ModSecurity-nginx.git /usr/local/src/ModSecurity-nginx/

By importing only the most recent revision, this command performs a shallow repository clone. This effective cloning reduces the amount of bandwidth and storage needed.

Step 2: Install ModSecurity-nginx Connector Initial Packages

The next step is to navigate to the Nginx source directory after the source code has been successfully fetched. To accomplish this, run the cd command as follows:

cd /usr/local/src/nginx/nginx-1.*.*

The next step is to install the dependencies needed for the ModSecurity-nginx connector once we are inside the Nginx source directory. Not only can the following command install the required dependencies, it will also fetch them:

sudo apt build-dep nginx && sudo apt install uuid-dev

Step 3: Build ModSecurity-nginx Connector Environment on Debian

It is now possible to compile the ModSecurity-nginx connector since all dependencies have been installed. This entails executing the configure command with the options --add-dynamic-module and --with-compat:

./configure --with-compat --add-dynamic-module=/usr/local/src/ModSecurity-nginx

The ModSecurity-nginx connector's location is specified by the --add-dynamic-module option, whereas the --with-compat flag ensures compatibility with various systems.

Nginx dynamic module output when using Modsecurity 3 on Debian 12

We can now generate the dynamic modules after setting up the environment. The make command is used in this manner to accomplish this:

make modules
The ‘make modules’ output during the build process for Modsecurity 3 and Nginx on Debian 12

Step 4: Install ModSecurity 3 Dynamic Module on Debian

Moving the dynamic module to a suitable directory is the final step in this setup process. A dynamic module is created at the objs/ngx_http_modsecurity_module.so location by the make modules command. This module needs to be moved to the /etc/nginx/modules/ directory. To do this, run the following command:

sudo cp objs/ngx_http_modsecurity_module.so /etc/nginx/modules/

Recall that, as long as you provide the complete path when the loading process is executed, you can store the dynamic module anywhere.

If you are unable to move the folder, create it right away as it might not exist depending on where your Nginx installation came from:

sudo mkdir /etc/nginx/modules/

Enable ModSecurity-nginx Connector with Nginx on Debian 12

After you've successfully configured the ModSecurity-nginx connector, the next step is to load it into Nginx and modify the configuration to suit your needs. The main step in this process will be modifying the /etc/nginx/nginx.conf Nginx configuration file, which will finally make ModSecurity fully functional with your Nginx web server.

Step 1: Activating ModSecurity within nginx.conf on Debian

Our first task is to specify where in the nginx.conf file the ModSecurity module is located. Using a text editor, edit the nginx.conf file to complete this step. Here, we'll make use of nano:

sudo nano /etc/nginx/nginx.conf

Add the following line at the beginning of the file:

load_module modules/ngx_http_modsecurity_module.so;

Nginx is instructed to load the ModSecurity module by this directive.

💡
If you have the module somewhere else, don't forget to include the full path in this directive.

Then, add the subsequent directives to the http {} block:

modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/modsec-config.conf;

The above directives specify where the ModSecurity rules file is located and activate ModSecurity. Press Ctrl+O to save the changes, and Ctrl+X to exit the file.

Step 2: Create ModSecurity 3 Directories and Files on Debian

It is required to create a dedicated directory in order to hold configuration files and additional rules. To create the /etc/nginx/modsec directory, run the following command:

sudo mkdir /etc/nginx/modsec/

Next, copy the example ModSecurity configuration file into the newly created directory from the cloned Git directory:

sudo cp /usr/local/src/ModSecurity/modsecurity.conf-recommended /etc/nginx/modsec/modsecurity.conf

Let's now modify the modsecurity.conf file. The ModSecurity rule engine runs in DetectionOnly mode by default, which detects malicious activity but does not block it. Open the modsecurity.conf file to change this behavior:

sudo nano /etc/nginx/modsec/modsecurity.conf

Find and change the line SecRuleEngine DetectionOnly to:

SecRuleEngine On

Then, find the SecAuditLogParts line:

# Log everything we know about a transaction.
SecAuditLogParts ABIJDEFHZ

It is not accurate as it is now configured. The line should be adjusted as follows:

SecAuditLogParts ABCEFHJKZ

Now, save Ctrl+Oand close Ctrl+X the file.

Step 3: Create modsec-config.conf on Debian

The next step is to make a modsec-config.conf file. Later on, this file will contain the modsecurity.conf file along with additional rule sets like the OWASP CRS. Use the following command to create and open the file:

sudo nano /etc/nginx/modsec/modsec-config.conf

After entering the file, add the next line:

Include /etc/nginx/modsec/modsecurity.conf

Use Ctrl+O to save the file and Ctrl+X to close it.

Finally, replicate the ModSecurity’s unicode.mapping file using the cp command:

sudo cp /usr/local/src/ModSecurity/unicode.mapping /etc/nginx/modsec/

Step 4: Test ModSecurity 3 Configuration on Debian

It is imperative that we confirm your configuration before continuing. To run the Nginx service in a dry run, type the following command:

sudo nginx -t

After you've correctly configured every setting, the following message ought to show up:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

The output shows that the configuration test was successfully completed and that your Nginx configuration file has the proper syntax. If mistakes arise, go back and check the earlier procedures to make sure all commands were entered accurately and all file paths were specified precisely.

Step 5: Restart Nginx to Enable ModSecurity 3 New Configuration on Debian

Restarting the Nginx service will enable the changes you've made to take effect after you've checked your configuration and made sure there are no syntax errors. Completing this step is essential to making ModSecurity function.

To restart the Nginx service, use the following systemctl command:

sudo systemctl restart nginx

With this command, your system will stop the Nginx service and then restart it right away. As a result, your Nginx service ought to have a ModSecurity WAF that is active and functioning.

Install OWASP Core Rule Set within ModSecurity 3 on Debian 12

This section walks you through applying the OWASP Core Rule Set (CRS) for ModSecurity to strengthen the security of your web server. ModSecurity is a powerful tool, but protection isn't provided by it alone. It needs a set of regulations in order to operate properly.

One well-known and reliable web application firewall (WAF) rule is the OWASP CRS. These regulations are adept at spotting possible attacks and averting them, serving as a strong defense against the majority of modern online threats. By embracing this essential resource, you're already taking the first steps toward securing your server. It serves as the foundation for numerous systems that are similar to it.

Step 1: Returning to the ModSecurity Directory on Debian

We'll start by going over the ModSecurity directory that was made in the earlier steps. Execute the following command:

cd /etc/nginx/modsec

You can use this command to change the ownership of this directory to your current user in order to avoid using the sudo command for the following steps:

sudo chown -R $USER:$USER /etc/nginx/modsec/

Step 2: Retrieving the OWASP CRS Archive

Next, retrieve the OWASP CRS archive using the wget command. As of this writing, the most recent stable release is 3.3.4. To verify the most recent version, though, visit the OWASP Release tag page.

wget https://github.com/coreruleset/coreruleset/archive/refs/tags/v3.3.4.tar.gz

Do not forget to check for the most recent stable versions by visiting the OWASP CRS release page. The aforementioned command is just one example. Don't just copy it without thinking; it might be an old version.

To remain up to date with the most recent advancements, download the nightly build version. Though it might be less stable and need frequent updates, this version includes the most recent enhancements and changes. Ideally, this version is meant for experienced users.

wget https://github.com/coreruleset/coreruleset/archive/refs/tags/nightly.tar.gz

Downloading the Nightly version is only recommended for highly experienced users with extra time on their hands. These will need to be downloaded nearly every day!

Step 3: Extract OWASP CRS Archive on Debian

Once the download is finished, decompress the archive using the tar command:

tar -xvf v3.3.4.tar.gz

If you are using a different version, make sure to replace v3.3.4.tar.gz with the name of the file you downloaded.

Step 4: Configure the CRS on Debian and ModSecurity 3

Like the ModSecurity configuration we've already worked with, the OWASP CRS comes with an example configuration file. This file needs to be renamed. We'll copy this file and keep the original as a backup by using the cp command to do so:

sudo cp /etc/nginx/modsec/coreruleset-3.3.4/crs-setup.conf.example /etc/nginx/modsec/coreruleset-3.3.4/crs-setup.conf

Step 5: Enable the OWASP CRS Rules on Debian and ModSecurity 3

We must make changes to the modsec-config.conf file in order to activate the OWASP CRS rules:

sudo nano /etc/nginx/modsec/modsec-config.conf

Add the next two lines to this file in order to include the CRS configuration and rules:

Include /etc/nginx/modsec/coreruleset-3.3.4/crs-setup.conf
Include /etc/nginx/modsec/coreruleset-3.3.4/rules/*.conf

After that, press CTRL+O to save the file and CTRL+X to exit.

Adding CRS rules into the modsec configuration file when setting up Nginx with Modsecurity 3 and OWASP CRS on Debian 12
💡
Don't forget to substitute "coreruleset-3.3.4" with the downloaded version. Every three to six months, a new stable release usually makes an appearance, so be sure to check the current release page often.

Press Ctrl+O to save the changes, and Ctrl+X to close the text editor.

Step 6: Verify the Configuration and Rebooting Nginx on Debian and ModSecurity 3

After making these significant adjustments to our Nginx configuration, it is critical to confirm that everything is accurate and free of typos or misconfigurations. This validation process is a trial run for when the updated service is actually launched.

This "dry run" can be started by entering the following command:

sudo nginx -t

You get to see the following message if the configuration file syntax is accurate:

Output

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

This attests to the accuracy of our configuration and the non-disruptive nature of our modifications. However, if you see error messages, carefully read them to look for clues about possible problems. Usually quite descriptive, the error messages can point you in the direction of the problematic section of your configuration files.

We are prepared to execute these changes live after the dry run went well. Restarting the Nginx service will enable the updated configuration:

sudo systemctl restart nginx

Getting Started with OWASP Core Rule Set on Debian 12 with ModSecurity 3

Explore the inner workings and subtleties of the OWASP Core Rule Set (CRS) and ModSecurity after they have been successfully installed and configured on your Debian web server. Recognize its wide range of adjustable settings to further customize the security of your server beyond the general protection provided by the default configurations.

Exploring the Core Rule Set Configuration on Debian and ModSecurity 3

To start your exploration, open the CRS configuration file. This file contains a number of settings that you can adjust to meet the unique requirements of your server. Use this command to access this file:

sudo nano /etc/nginx/modsec/coreruleset-3.3.4/crs-setup.conf

This configuration file has a number of settings, all of which have thorough explanations included in the comments. This file really is a knowledge gold mine. It is essential to take the time to comprehend these choices in order to acquire knowledge about CRS functions and customize them to your needs.

Understanding Scoring Modes in the CRS on Debian and ModSecurity 3

The CRS operates using a scoring system that consists of two main modes:

Anomaly Scoring Mode

# -- [[ Anomaly Scoring Mode (default) ]] --

"Anomaly score" is the default mode that is advised. This score is increased by each rule that matches a request or response. Following the evaluation of all incoming and outgoing rules, the system compares the total anomaly score to a predetermined threshold. The system initiates a disruptive action—typically an HTTP 403 error—if the score surpasses the threshold. This mode generates comprehensive audit logs and permits flexible blocking policy settings.

Self-Contained Mode

# -- [[ Self-Contained Mode ]] --

When a rule match occurs in this mode, it immediately takes action and ends further analysis. Similar to many Intrusion Detection Systems (IDS), this technique saves resources but limits flexibility in blocking policies and produces audit logs that are less informative because it only logs the first threat that is detected. Because of its adaptability and informativeness, the Anomaly Scoring Mode is typically preferred by users.

Leveraging Paranoia Levels: Striking a Balance Between Security and Usability

The idea of paranoia levels is one of the CRS's distinctive features. By adjusting the CRS's sensitivity, you can manage how many rule checks go toward your anomaly scores.

The four paranoia levels are:

  • Paranoia Level 1: For most users, the default level is ideal. It reduces the possibility of false positives, or legitimate requests that are mistakenly interpreted as malicious, and it permits the majority of core rules.
  • Paranoia Level 2: This level, intended for experienced users, activates additional rules, like XSS injection prevention and regex-based SQL. There could be some false positives at this level.
  • Paranoia Level 3: Designed with experienced users in mind, this level sets additional restrictions and limitations on the use of special characters. At this point, be ready to deal with more false positives.
  • Paranoia Level 4: It is only advised to use this level in extreme situations. Special characters are further restricted, and a lot of false positives are probably going to occur.

It's critical to strike a balance between usability and security. Although higher levels of paranoia can lead to false alarms and block legitimate traffic, they can also provide better security. To reduce false positives, add exclusion rules for particular requests and applications if you become overly paranoid.

Customize OWASP CRS Rules to Your Needs on Debian and ModSecurity 3

Because the OWASP CRS is customizable, you can create and modify rules to suit your specific needs, which contributes to its versatility. Let's examine how this customization is accomplished.

Access OWASP CRS Rule Configuration File on Debian

The coreruleset-3.3.4 directory's rules directory is home to the CRS rules. The rules used by the CRS to examine incoming and outgoing HTTP traffic are stored in these files. Use the following command to view these files and add your own custom rules:

sudo nano /etc/nginx/modsec/coreruleset-3.3.4/rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf

The file containing the exclusion rules that were processed prior to the CRS rules is opened by this command.

Deciphering OWASP CRS Rule Structure on Debian

Every rule in ModSecurity follows a specific format. Here's an example of what a normal rule might resemble:

SecRule ARGS "@rx attack" "id:1234,phase:2,t:none,log,deny,msg:'Attempted attack'"

Let’s break down the components of this rule:

  • SecRule: This directive initiates the rule.
  • ARGS: The variable under inspection. ARGS represents all arguments, including GET, POST, and cookies.
  • "@rx attack": This is the operator and its argument. @rx is a regular expression match, and attack is the pattern to match.
  • "id:1234,phase:2,t:none,log,deny,msg:'Attempted attack'": This is the rule's action list. In addition to the rule's unique ID, it contains information about the rule's operation phase, transformations to apply (t:none denotes no transformations), what to do if the rule matches, such as logging the event and rejecting the request, and a message to log in the event that it does.

Create Custom Rules with OWASP CRS with ModSecurity 3 and Debian

Considering the variable to check, the pattern to find, and what to do when a match is found are all important when creating a custom rule. For example, to block requests containing a particular suspicious user-agent string, create a rule. When the suspicious string is found in the USER_AGENT variable, this rule should examine it closely and reject the request.

SecRule REQUEST_HEADERS:User-Agent "@rx suspicious-user-agent" "id:1235,phase:1,t:none,log,deny,msg:'Suspicious User-Agent Detected'"

Any request that contains the string "suspicious-user-agent" in its user-agent header is blocked by this rule.

💡
Please keep in mind that creating custom rules requires a thorough knowledge of HTTP, the OWASP CRS, and the behavior of your application. To prevent interfering with lawful traffic, be ready to thoroughly test and modify your rules.

Test OWASP Core Rule Set with ModSecurity 3 and Debian

Ensuring the correct implementation and functionality of OWASP CRS (Core Rule Set) on your Debian server is a crucial step that follows its successful configuration. We can verify that our system is adequately protected by the security rules we've implemented thanks to this process. It is an essential validation procedure that enables us to address any mistakes or problems that may have occurred during setup.

Step 1: Conducting a Test Request

In order to verify the efficacy of our newly deployed OWASP CRS, we will employ a specifically created URL that is meant to raise an alert in the event that a rule is broken. This URL includes a query string that attempts to run a particular command, which is against our security policies.

Depending on how your server is configured, here is an example of such a URL or IP address:

https://www.yourdomain.com/index.html?exec=/bin/bash

or

http://your-ip-address

In this URL, replace yourdomain.com with the name of your real domain. Try using the exec parameter in the query string to pass the `/bin/bash command. Your security measures ought to detect and prevent this activity if they are functioning properly.

Understanding the Server’s Response with ModSecurity 3 and Debian

The OWASP CRS should be able to successfully intercept this malicious request and return a 403 Forbidden error if it is properly configured and running on your server. The 403 Forbidden error indicates that although the server understood the request, it purposefully declined to grant access. In this case, breaking the ModSecurity rule is the reason for the rejection.

This is an example of what a 403 Forbidden response ought to look like:

Modsecurity 3 correctly blocks requests when used with Nginx and the OWASP Core Rule Set on Debian 12

An example of what to expect when you encounter a 403 Forbidden error page can be seen in the image above. This error indicates that ModSecurity and OWASP CRS are correctly configured, preventing malicious requests from accessing your server. You should see it during testing.

Troubleshooting with ModSecurity 3 and Debian

You have an issue if, after submitting a test request, you don't get a 403 Forbidden error. Users often overlook setting ModSecurity's DetectionOnly mode to On. ModSecurity logs threats in DetectionOnly mode but does not block them, giving the impression that the rule set is non-functional.

Turn ModSecurity on by following the tutorial's previous instructions. This modification enables OWASP CRS and ModSecurity to actively intercept and block any request that deviates from predetermined guidelines, thereby enabling them to provide full protection. Pay close attention to these steps to guarantee that your server is adequately safeguarded against a variety of web-based attacks.

Understand False OWASP CRS Positivies Custom Rule Exemptions with ModSecurity 3 and Debian 12

When using OWASP CRS and ModSecurity as cybersecurity measures in a Debian environment, one may occasionally run into false positives. It might take a lot of your time to handle these false positives. It may seem difficult, but the time invested is frequently justified by the protection it offers.

Fix False Positives with ModSecurity 3 and Debian

It's difficult to strike a balance between security and usability. An excessively paranoid setting for the ModSecurity rules may result in a spike in false positives. Reduce your level of paranoia at first. You should probably see few false positives if you leave this setting on for a few weeks or months. It's critical to comprehend the system's behavior and alerts during this stage. Consider progressively raising your level of paranoia after you are comfortable with the system's output in order to avoid becoming overtaken by false positives.

Precluding Common False Positives with ModSecurity 3 and Debian

A feature in ModSecurity allows you to make an exclusion list of routine actions that often result in false positives. This feature is especially useful for applications that communicate with your server on a regular basis. An illustration of a standard rule that creates these exceptions is as follows:

#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"

You can leave the (1) value in place and uncomment the relevant lines to exempt certain applications from the rule. Change the (1) to (0) for any programs or services that you do not use, such as Xenforo. This update makes sure you don't omit any rules that aren't necessary.

Simplifying the Syntax with ModSecurity 3 and Debian

You can update the command to only include the apps you want to be exempt from the rule for a cleaner syntax. For example, the command would look like this if WordPress, phpBB, and phpMyAdmin are installed on your server:

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"

A syntax this simplified makes maintenance and comprehension easier to handle.

Managing Custom Exclusions with ModSecurity 3 and Debian

In order to support personalized exclusions, turn on a particular file. Use the cp command to rename the REQUEST-900-EXCLUSION-RULES-BEFORE-CRS-SAMPLE.conf file:

sudo cp /etc/nginx/modsec/coreruleset-3.3.4/rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf.example /etc/nginx/modsec/coreruleset-3.3.4/rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf

It's crucial to remember that every exclusion rule needs to have a distinct id. During the Nginx service testing phase, duplicate rule id will result in an error that could potentially disrupt your workflow.

Whitelist Specific Paths and IP Addresses with ModSecurity 3 and Debian

In some cases, certain paths connected to particular applications might reliably result in false positives. You can whitelist these paths in such circumstances to stop pointless alerts. Here's how to make this happen:

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"

The above example minimizes false positives by automatically allowing any URL that begins with the specified path.

In other situations, you might want to add particular IP addresses that are thought to be secure to your whitelist. ModSecurity offers alternatives in this regard:

SecRule REMOTE_ADDR "^195\.151\.128\.96" "id:1004,phase:1,nolog,allow,ctl:ruleEngine=off"

## or ###

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"

These examples demonstrate how to whitelist entire subnets using the @ipMatch directive, which gives your whitelisting strategy more flexibility. Replace allow with deny if you need to add a specific IP address or subnet to your blacklist.

Perfecting Rule Exclusions

Whitelisting IP addresses or whole paths can help lower false positives, but doing so may unintentionally allow requests that could be harmful. Disabling particular rules that cause false positives instead of whitelisting entire paths would be a more nuanced approach. This method is frequently more accurate even though it requires more time and testing.

For example, if the rules with IDs 941000 and 942999 are consistently generating false alerts for your /admin/ area, you can use the ruleRemoveById directive in the following way to disable those particular rules:

SecRule REQUEST_FILENAME "@beginsWith /admin" "id:1004,phase:1,pass,nolog,ctl:ruleRemoveById=941000-942999"

With this setup, the /admin/ path will only have the defined rules disabled, keeping the remainder of your application highly protected..

Setup Log Rotation for ModSecurity 3 and Debian 12

Maintaining an appropriate web application firewall, such as ModSecurity, requires ongoing attention to the logs. These logs have the potential to grow over time, consuming important server storage space and making it more difficult to identify particular entries for security analysis or troubleshooting. We will set up a log rotation mechanism to address this challenge.

Step 1: Create ModSecurity Log Rotation File with ModSecurity 3 and Debian

The creation of a configuration file is the initial stage in the log rotation setup. The parameters for the log rotation will be set by this file. The logrotate utility looks for its configuration files in the /etc/logrotate.d/ directory, so this is where it should be located.

To create and modify a new file with the name modsec, use the following command:

sudo nano /etc/logrotate.d/modsec

You can create and modify the file immediately by using the nano command, which opens a terminal text editor.

Step 2: Laying Out the Log Rotation Parameters

We're going to establish the guidelines for the ModSecurity log rotation in this file. Put the following code block into the file:

/var/log/modsec_audit.log
{
        rotate 31
        daily
        missingok
        compress
        delaycompress
        notifempty
}

Here’s a clear breakdown of each line in the code:

  • /var/log/modsec_audit.log: Identifies the file we aim to rotate, the ModSecurity audit log.
  • rotate 31: Tells logrotate to retain 31 rotated log files before letting go of the oldest.
  • daily: Instructs logrotate to rotate the log file on a daily basis.
  • missingok: If the log file can’t be found, logrotate won’t produce an error message.
  • compress: Directs logrotate to compress the rotated log files, hence saving space.
  • delaycompress: Defers the compression of the previous log file until the next rotation cycle. Useful for when some programs are still writing to the file.
  • notifempty: If the log file is empty, logrotate will avoid rotating it.

The configuration makes sure that your ModSecurity logs rotate every day and have a log backlog of one month. Feel free to adjust these settings, though, to meet your needs. To keep only a week's worth of logs, for example, switch rotation 31 to rotation 7. Remember that daily ModSecurity rotation is advised due to the massive potential size of the logs. Weekly log files could get difficult to handle and evaluate.

Safeguarding Nginx from Updates with APT-HOLD with ModSecurity 3 and Debian 12

Don't freak out if you upgrade Nginx after failing to use APT-HOLD, breaking your webserver because of ModSecurity 3. To fix the problem, take these actions:

  1. Re-download the latest Nginx source.
  2. Re-compile the dynamic module using the upgraded version of Nginx.
  3. Move the newly built dynamic module to the same directory as before.
  4. Reboot your Nginx server.

You can get back online in a matter of minutes if you follow the first few instructions in this guide.

In the complex world of web server management, we understand that while automatic system updates are usually beneficial, they can sometimes mess with our carefully calibrated configurations. This is especially true when we use custom or extremely specialized configurations, such as when we use ModSecurity in conjunction with Nginx. Automated updates for Nginx could replace our settings or cause issues with compatibility with the current configuration. Because of this, it might be beneficial to disable Nginx's automatic updates. We can do this by utilizing the "APT-HOLD" feature of the APT package management system.

Grasping the Concept of APT-HOLD

One useful tool that allows us to control the package status in the APT package management system is the apt-mark command. The "hold" option is one of its features. A package marked with "hold" indicates that it is being held back and will not be updated.

Applying APT-HOLD to Nginx

The apt-mark command can be used to put Nginx on hold and prevent it from updating automatically, as shown below:

sudo apt-mark hold nginx

Once this command is run, the system will not allow any updates for the Nginx package until you change this configuration. This ensures that your configuration is not impacted or disturbed by automatic system updates.

Reversing APT-HOLD

You may eventually need to update Nginx in order to take advantage of new features or apply security updates. You can use the unhold option to lift the hold and allow updates to Nginx once more:

sudo apt-mark unhold nginx

When you are ready to handle any potential issues that may arise between Nginx and ModSecurity, like recompiling, you can take this action to return the package to its normal state. It will then be updated during the next system package update.

FAQs to Install ModSecurity 3, OWASP CRS with Nginx on Debian 12

What is ModSecurity 3 and how does it enhance website security?

ModSecurity 3 is a web application firewall that helps protect websites from cyber threats. It analyzes HTTP traffic, detects and blocks attacks such as SQL injections and cross-site scripting (XSS), thereby enhancing overall website security.

What is the role of OWASP CRS in ModSecurity 3?

OWASP CRS, or Core Rule Set, provides a collection of rules that can be applied to ModSecurity 3. These rules define security policies, helping to detect and prevent various web application attacks.

What are the benefits of using ModSecurity 3 with OWASP CRS?

By using ModSecurity 3 with OWASP CRS, you can add a layer of protection to your web application, blocking potential attacks like SQL injections and cross-site scripting (XSS).

Can I customize the rules in OWASP CRS?

Yes, OWASP CRS allows customization of rules to fit your specific security needs. You can modify the rules or create new ones according to the requirements of your web application.

Are there any performance implications when using ModSecurity 3 with OWASP CRS?

While there may be a slight performance impact when using ModSecurity 3 with OWASP CRS, the added security benefits outweigh the minimal overhead. Proper tuning and optimization can minimize any negative effects.

Can I use ModSecurity 3 and OWASP CRS with other web servers besides Nginx?

Yes, ModSecurity 3 and OWASP CRS are compatible with various web servers, including Apache. You can follow similar installation and configuration steps on different web server platforms.

Is ModSecurity 3 and OWASP CRS suitable for small websites?

Yes, ModSecurity 3 and OWASP CRS can benefit websites of all sizes. Implementing these security measures helps protect against common web application attacks, regardless of the website's scale.

Conclusion

We hope this tutorial helped you understand how to install ModSecurity 3, OWASP CRS with Nginx on Debian 12.

If you have any queries, please leave a comment below, and we’ll be happy to respond to them for sure.