How to Install Modsecurity 3 and OWASP CRS with Nginx on Fedora 39, 38 Linux

This guide aims to demonstrate how to install Modsecurity 3 and OWASP CRS with Nginx on Fedora Linux. Modsecurity 3, a powerful and adaptable web application firewall, is integral for enhancing the security of your web servers. Initially developed for Apache, Modsecurity has evolved, extending its robust security features to other platforms, including Nginx, a popular choice for its efficiency and scalability.

Integrating Modsecurity 3 with Nginx on Fedora Linux equips your server with a formidable shield against various web threats. The synergy between Modsecurity and the OWASP Core Rule Set (CRS) brings a comprehensive layer of protection essential for modern web applications. The CRS is a collection of security rules that actively identify and mitigate common web application vulnerabilities.

Key Features of this Setup:

  • Enhanced Security: Utilizes Modsecurity’s capabilities to safeguard against web threats.
  • Customizable Rules: The OWASP Core Rule Set provides a flexible framework for security configurations.
  • Performance Efficiency: Nginx’s renowned performance complements the security layer without compromising speed.
  • Broad Protection Spectrum: Guards against SQL injection, Cross-Site Scripting (XSS), and more.
  • Fedora Linux Integration: Leverages Fedora’s robust and secure environment for an optimal setup.

As we proceed, you will learn the precise steps to how to install Modsecurity 3 and OWASP CRS with Nginx on Fedora Linux, enhancing your web application’s security manifold. This guide ensures a straightforward installation experience tailored to newcomers and seasoned Linux users.

Table of Contents

Install Nginx or Nginx Mainline on Fedora Linux

Refresh Fedora Packages

To start, update your Fedora system’s packages. This step is crucial to ensure compatibility and prevent any installation issues:

sudo dnf upgrade --refresh

Install Nginx For Modsecurity 3

Now, install Nginx. Execute the following command in your terminal. If Nginx is already installed, you can skip this step and proceed to download the Nginx source:

Section the next section if you prefer using Nginx mainline over Nginx stable.

sudo dnf install nginx

Verify the Nginx installation by checking its version:

nginx -v

Optional: Install Nginx Mainline on Fedora for Modsecurity 3

Fedora’s default repositories include both stable and mainline versions of Nginx. To install the mainline version, which might offer newer features, follow these steps:

First, view the available Nginx modules:

dnf module list nginx
Listing Nginx Modules for Modsecurity 3 Installation on Fedora Linux
Available Nginx Modules for Mainline and Stable Versions

Remove Previous Nginx Installation (Situational)

If you prefer the Nginx mainline version, you must remove the standard version first. It’s essential to back up your configuration files, especially if you have custom settings:

sudo cp /etc/nginx/ /etc/nginx-backup/

After backing up, remove the existing Nginx installation:

sudo dnf autoremove nginx

Enable and Install Nginx Mainline

Enable the mainline module of Nginx:

sudo dnf module enable nginx:mainline -y

Now, install the Nginx mainline version:

sudo dnf install nginx -y

Confirm Nginx Mainline Installation

Check the installed Nginx version to confirm the mainline version is installed:

nginx -v

Enable Nginx Service on Fedora

To ensure Nginx starts automatically and is currently running, use:

sudo systemctl enable nginx --now

Example output indicating successful enablement:

Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service.

Check the status of the Nginx service:

systemctl status nginx
Successful Nginx Systemctl Status for Modsecurity 3 on Fedora Linux
Nginx Running Successfully with Systemctl on Fedora Linux

Test your Nginx web server by accessing http://<server-ip> or http://<domain-name> in your browser.

Fedora Nginx Test Page Display on Fedora Linux
Fedora Nginx Server Test Page Example

Configure Firewalld for Nginx

If this is a new Nginx installation, configure your firewall for web traffic:

Allow HTTP traffic:

sudo firewall-cmd --permanent --zone=public --add-service=http

Allow HTTPS traffic:

sudo firewall-cmd --permanent --zone=public --add-service=https

Reload the firewall to apply changes:

sudo firewall-cmd --reload

Download Nginx Source on Fedora Linux

Create and Configure Directories

To begin, establish a directory for storing the Nginx source code, which is necessary for compiling the ModSecurity dynamic module.

Create the directory with the following command:

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

Optional: If required, change the ownership of the directory for easier file management:

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

Download Source Archive

The next step involves downloading the Nginx source archive. Ensure that the version of the source archive matches the version of Nginx you plan to use. Whether you are working with the latest version or an older one is critical.

To download the source, use the wget command. Below is an example using the Nginx Mainline version from the Fedora repository. Replace {version} with your specific version number:

wget http://nginx.org/download/nginx-{version}.tar.gz

For instance (do not copy this directly; adjust according to your version):

wget https://nginx.org/download/nginx-1.23.2.tar.gz

After downloading, extract the archive:

tar -xvzf nginx-1.23.2.tar.gz

Verify Source Version

To confirm the successful download, list the files in the directory:

ls
LS Command Output Post-Extraction of Nginx Source on Fedora Linux
LS Command Showing Nginx Source Files on Fedora Linux

Finally, ensure the downloaded source package matches the Nginx version installed on your system. This verification is crucial to avoid any version mismatch issues.

Use the following command to check the installed Nginx version:

nginx -v

Install libmodsecurity3 for ModSecurity 3 on Fedora Linux

Clone ModSecurity Repository from GitHub

To start, you need to clone the ModSecurity repository from GitHub. This step is essential as it allows you to obtain the latest source code of libmodsecurity3, which is a critical component of web application firewall capabilities.

If you don’t have git installed on your Fedora system, install it first:

sudo dnf install git -y

This command installs git, a version control system that lets you manage and track changes in your source code.

After installing git, proceed to clone the repository:

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

This command clones the master branch of the libmodsecurity3 repository into a specified directory (/usr/local/src/ModSecurity/). The --depth 1 option ensures you only download the latest snapshot of the branch, saving time and bandwidth.

Navigate to the directory with:

cd /usr/local/src/ModSecurity/

Install libmodsecurity3 Dependencies

Before you can compile libmodsecurity3, you must install various dependencies. These dependencies are necessary to provide the libraries and tools required for the compilation process:

sudo dnf install gcc-c++ flex GeoIP-devel doxygen yajl-devel bison yajl curl-devel zlib-devel pcre-devel autoconf automake git curl make libxml2-devel pkgconfig libtool httpd-devel redhat-rpm-config wget openssl openssl-devel nano -y

Each package in this command plays a specific role. For instance, gcc-c++ is the GNU C++ compiler, while libxml2-devel and openssl-devel provide development files for XML and SSL support, respectively.

Next, initialize the Git submodules:

git submodule init
[joshua@fedora-linux ModSecurity]$ git submodule init
Submodule 'bindings/python' (https://github.com/SpiderLabs/ModSecurity-Python-bindings.git) registered for path 'bindings/python
Submodule 'others/libinjection' (https://github.com/libinjection/libinjection.git) registered for path 'others/libinjection'
Submodule 'test/test-cases/secrules-language-tests' (https://github.com/SpiderLabs/secrules-language-tests) registered for path 'test/test-cases/secrules-language-tests'

This command prepares the submodules, external dependencies, or libraries linked to this repository. The output will indicate the registration of these submodules.

git submodule update
[joshua@fedora-linux ModSecurity]$ git submodule update
Cloning into '/usr/local/src/ModSecurity/bindings/python'...
Cloning into '/usr/local/src/ModSecurity/others/libinjection'...
Cloning into '/usr/local/src/ModSecurity/test/test-cases/secrules-language-tests'...
Submodule path 'bindings/python': checked out 'bc625d5bb0bac6a64bcce8dc9902208612399348'
Submodule path 'others/libinjection': checked out 'bfba51f5af8f1f6cf5d6c4bf862f1e2474e018e3'
Submodule path 'test/test-cases/secrules-language-tests': checked out 'a3d4405e5a2c90488c387e589c5534974575e35b'

Updating submodules ensures you have the latest versions of these dependencies, which might include crucial updates or bug fixes.

Building the ModSecurity 3 Environment on Fedora

The next step is to build the ModSecurity environment. This process prepares the source code for compilation:

./build.sh

During this step, you may encounter a non-critical error message (fatal: No names found, cannot describe anything.). This error is related to Git descriptions and can be safely ignored.

Proceed to configure the build environment:

./configure

This script checks your system to ensure all necessary dependencies are present and configures the source code to compile correctly on your system.

The output displays the configuration summary, including mandatory and optional dependencies, informing you about the configured components.

ModSecurity -  for Linux
 
 Mandatory dependencies
   + libInjection                                  ....v3.9.2-46-gbfba51f
   + SecLang tests                                 ....a3d4405
 
 Optional dependencies
   + GeoIP/MaxMind                                 ....found 
      * (GeoIP) v1.6.12
         -lGeoIP , -I/usr/include/ 
   + LibCURL                                       ....found v7.85.0 
      -lcurl,  -DWITH_CURL_SSLVERSION_TLSv1_2 -DWITH_CURL
   + YAJL                                          ....found v2.1.0
      -lyajl , -DWITH_YAJL 
   + LMDB                                          ....not found
   + LibXML2                                       ....found v2.10.3
      -lxml2 , -I/usr/include/libxml2  -DWITH_LIBXML2
   + SSDEEP                                        ....not found
   + LUA                                           ....not found
   + PCRE2                                          ....not found
 
 Other Options
   + Test Utilities                                ....enabled
   + SecDebugLog                                   ....enabled
   + afl fuzzer                                    ....disabled
   + library examples                              ....enabled
   + Building parser                               ....disabled
   + Treating pm operations as critical section    ....disabled

Compiling the ModSecurity Source Code

Now, compile the libmodsecurity3 source code:

make

This command initiates the compilation process, translating the source code into executable binaries. It may take some time, depending on your system’s processing power.

For faster compilation on systems with multiple cores, use:

make -j 6

This command initiates the compilation process, translating the source code into executable binaries. It may take some time, depending on your system’s processing power.

For faster compilation on systems with multiple cores, use:

sudo make install

This command places the compiled binaries and other necessary files into the /usr/local/modsecurity/ directory. This directory will be referenced in future steps when integrating libmodsecurity3 with other software, such as Nginx.

Install ModSecurity-nginx Connector on Fedora Linux

Clone ModSecurity-nginx Repository from GitHub

To integrate ModSecurity with Nginx, the ModSecurity-Nginx connector is essential. This connector is the intermediary, facilitating communication between Nginx and ModSecurity (libmodsecurity3).

Begin by cloning the ModSecurity-nginx repository:

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

This command downloads the latest version of the ModSecurity-nginx connector to the specified directory, ensuring you have the most up-to-date version for your setup.

Compile ModSecurity-nginx Dynamic Module on Fedora

First, navigate to the Nginx source directory. Replace nginx-1.23.2 with your specific Nginx version:

cd /usr/local/src/nginx/nginx-1.23.2

Remember to replace nginx-1.23.2 with your actual version, the above is just an example command.

This step is crucial to ensure the connector is compatible with your Nginx installation.

Now, compile the ModSecurity-nginx Connector module. Use the --with-compat flag to ensure compatibility with your Nginx version:

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

This command configures the Nginx source to include the ModSecurity-nginx module as a dynamic module.

The output should look something like this, indicating a successful configuration:

Configuration summary
  + using system PCRE library
  + OpenSSL library is not used
  + using system zlib library

  nginx path prefix: "/usr/local/nginx"
  nginx binary file: "/usr/local/nginx/sbin/nginx"
  nginx modules path: "/usr/local/nginx/modules"
  nginx configuration prefix: "/usr/local/nginx/conf"
  nginx configuration file: "/usr/local/nginx/conf/nginx.conf"
  nginx pid file: "/usr/local/nginx/logs/nginx.pid"
  nginx error log file: "/usr/local/nginx/logs/error.log"
  nginx http access log file: "/usr/local/nginx/logs/access.log"
  nginx http client request body temporary files: "client_body_temp"
  nginx http proxy temporary files: "proxy_temp"
  nginx http fastcgi temporary files: "fastcgi_temp"
  nginx http uwsgi temporary files: "uwsgi_temp"
  nginx http scgi temporary files: "scgi_temp"

Make (Create) the Dynamic Modules

Now, compile the dynamic modules:

make modules

This command compiles the ModSecurity-nginx module, creating a .so file, which is a dynamic module that can be loaded into Nginx.

Copy the Compiled Modsecurity 3 Module to Nginx

Finally, copy the compiled module to the Nginx modules directory:

sudo cp objs/ngx_http_modsecurity_module.so /usr/share/nginx/modules/

This command moves the ngx_http_modsecurity_module.so file from the Nginx source directory to /usr/share/nginx/modules/, where Nginx can access and load it.

Configure ModSecurity-nginx Connector with Nginx on Fedora Linux

Enable ModSecurity in nginx.conf

After successfully compiling and locating the dynamic module, it’s time to configure Nginx to work with ModSecurity. Begin by editing the Nginx configuration file:

sudo nano /etc/nginx/nginx.conf

In the nginx.conf file, add the load_module directive at the top to load the ModSecurity module:

load_module /usr/share/nginx/modules/ngx_http_modsecurity_module.so;

This line directs Nginx to load the ModSecurity module from the specified path. If your module is in a different location, replace the path accordingly.

Next, enable ModSecurity within the http {} block by adding:

modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/modsec-config.conf;
Enabling Modsecurity 3 Module in Nginx Configuration on Fedora Linux
Modsecurity 3 Module Activation in Nginx Config File

These lines activate ModSecurity and specify the path to its configuration file. After making these changes, save (CTRL+O) and exit (CTRL+X) the editor.

Create and Configure Directory and Files for ModSecurity 3

Create a directory to house ModSecurity configuration files and rules:

sudo mkdir /etc/nginx/modsec/

Copy the default ModSecurity configuration file from the cloned Git directory to this new directory:

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

Open the modsecurity.conf file for editing:

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

By default, the ModSecurity rule engine is set to DetectionOnly, which monitors and logs potential threats without actively blocking them. This mode is helpful for testing and identifying false positives.

To activate ModSecurity’s blocking features, locate and change the SecRuleEngine directive:

SecRuleEngine DetectionOnly

Change it to:

SecRuleEngine On
Activating Modsecurity Detection in Nginx on Fedora Linux
Modsecurity Detection Mode Set to ‘On’ in Nginx

Now, you need to locate the following, which is located on line 224.

# Log everything we know about a transaction.
SecAuditLogParts ABIJDEFHZ

This isn’t correct and needs to be changed. Adjust the SecAuditLogParts directive to ensure comprehensive logging:

SecAuditLogParts ABCEFHJKZ

Save (CTRL+O) and exit (CTRL+X) the file after making these changes.

Create the modsec-config.conf file, where you’ll include the main configuration file and potentially other rule sets like OWASP CRS:

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

Inside this file, include the ModSecurity configuration:

include /etc/nginx/modsec/modsecurity.conf

Save and exit the editor.

Lastly, copy the unicode.mapping file, which is essential for correctly processing various character encodings:

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

Verify and Restart Nginx

Before proceeding, it’s crucial to check your Nginx configuration for any errors:

sudo nginx -t

A successful output will confirm the correct syntax and validity of your configuration:

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

Finally, apply the changes by restarting Nginx:

sudo systemctl restart nginx

Install OWASP CRS for ModSecurity 3 on Fedora Linux

Introduction to OWASP CRS

The Open Web Application Security Project (OWASP) Core Rule Set (CRS) is an essential set of rules for ModSecurity, a widely respected web application firewall. These rules are designed to identify and block common web application vulnerabilities and malicious activities. By installing OWASP CRS, you significantly enhance your web server’s defense against emerging online threats.

Downloading OWASP CRS

To ensure you have the latest protection, download the most recent version of OWASP CRS from the official GitHub page. For this guide, we’ll use version 3.3.5, the latest stable release at the time of writing.

Download the OWASP CRS 3.3.5 using wget:

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

The nightly build is available for users interested in the absolute latest features. However, be aware that this version can be less stable and may require frequent updates and troubleshooting:

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

Do not use the nightly in production environments, or if you are not prepared to deal with issues and monitoring and constant updates.

Extracting OWASP CRS

Once downloaded, extract the .tar.gz archive. This format is a compressed file, similar to .zip, but commonly used in Unix-like systems for better compression:

tar -xzvf v3.3.5.tar.gz -C /etc/nginx/modsec

This command decompresses and extracts the contents of the OWASP CRS archive directly into the /etc/nginx/modsec directory, which is the standard location for ModSecurity configurations.

Setting Up the OWASP CRS with Modsecurity 3

After extraction, a sample configuration file named crs-setup.conf.example is included in the package. This file needs to be renamed and used as the actual configuration file. It’s a good practice to keep the original as a backup:

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

Integrating OWASP CRS with ModSecurity

To activate the OWASP CRS rules, modify the ModSecurity configuration file. This step links ModSecurity with the newly installed OWASP rules:

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

In the modsec-config.conf file, add the following lines to include the OWASP CRS setup and rules:

include /etc/nginx/modsec/coreruleset-3.3.5/crs-setup.conf
include /etc/nginx/modsec/coreruleset-3.3.5/rules/*.conf
Integrating OWASP CRS with Modsecurity in Nginx on Fedora Linux
Adding OWASP CRS Settings to Modsecurity Configuration

After adding these lines, save and close the file.

Note the version numbers in this file. When you update, say to coreruleset 3.3.6 or higher, you need to update these lines to suite the Core Rule Set version.

Testing the Nginx Configuration

Before applying the changes to your live web server, it’s crucial to test the Nginx configuration for any syntax errors:

sudo nginx -t

A successful test result should look like this:

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

Restarting Nginx to Apply Changes

Finally, restart the Nginx service to implement the OWASP CRS rules:

sudo systemctl restart nginx

Understanding OWASP CRS with ModSecurity 3 on Fedora Linux

Introduction to OWASP CRS Configuration

The OWASP Core Rule Set (CRS) has various options to protect your server effectively right out of the box. These settings are optimized to safeguard your server while maintaining a seamless experience for legitimate visitors and SEO bots. To delve deeper into the myriad of configurations available, examining the configuration files directly is advisable, as they offer extensive and detailed options.

Accessing the CRS Configuration

Start by opening the CRS configuration file. The file path may differ based on the version you are using. Here, we are using version 3.3.5:

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

This file is the hub for modifying most of the OWASP CRS settings on your server.

Understanding OWASP CRS Scoring Modes

OWASP CRS operates in two primary modes:

  1. Anomaly Scoring Mode (Default):
    • This mode is the default in CRS3 and is recommended for its detailed logging and flexible blocking policies.
    • In this mode, each rule match increases an ‘anomaly score’.
    • After processing inbound and outbound rules, the anomaly score is evaluated, and if it exceeds a certain threshold, a disruptive action (like an error 403) is triggered.
  2. Self-Contained Mode:
    • This mode applies an action instantly when a rule is matched.
    • It was the default in CRS2 and can reduce resource usage.
    • However, it offers less flexibility and produces less informative logs, as only the first detected threat is logged.
    • The disruptive action specified (e.g., deny, drop) is executed on the first rule match, often stopping evaluation after the first match.

For most users, Anomaly Scoring Mode is the recommended choice due to its comprehensive approach to security.

Adjusting OWASP CRS Paranoia Levels

OWASP CRS offers four paranoia levels to control the strictness of rule checks and the resulting anomaly scores:

  1. Paranoia Level 1 (PL1):
    • The default and recommended level for most users.
    • PL1 activates most core rules, ideal for beginners or general security requirements.
    • Rarely causes false positives (FPs).
  2. Paranoia Level 2 (PL2):
    • Suitable for more experienced users who require additional coverage.
    • Activates extra rules for SQL and XSS injection protections.
    • PL2 may generate some FPs that need addressing.
  3. Paranoia Level 3 (PL3):
    • Targets experienced users with high-security needs.
    • Enables more rules and tightens limits on special characters.
    • Higher likelihood of encountering FPs.
  4. Paranoia Level 4 (PL4):
    • The most restrictive level is recommended only for highly experienced users.
    • Further restricts special characters.
    • Likely to produce a high number of FPs, suitable for very high-security environments.

Each rule logs its paranoia level to the audit log, allowing for easy assessment of how the chosen level influences the WAF behavior.

Testing OWASP CRS on Your Server

To verify the effectiveness of the OWASP CRS on your server, conduct a test with a simulated attack vector. Replace yourdomain.com with your actual domain:

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

A successful CRS configuration should return a 403 Forbidden error for this request. If the test fails, revisit the tutorial steps, especially ensuring that the SecRuleEngine is set to On instead of DetectionOnly.

Modsecurity 3 and OWASP CRS Blocking Access in Nginx on Fedora Linux
403 Forbidden Error Indicating Active Security Measures

Fix False Positives with ModSecurity 3 and OWASP CRS on Fedora Linux

Managing False Positives in ModSecurity and OWASP CRS

Dealing with false positives is an ongoing task when using ModSecurity and the OWASP Core Rule Set (CRS). While these tools provide robust protection, they require time and effort to fine-tune. A key strategy is to start with a lower paranoia level and gradually increase it over time. This approach helps avoid being overwhelmed by numerous false positives simultaneously.

Configuring Exclusions for Known Applications

ModSecurity allows for the whitelisting of common applications to reduce false positives. The configuration can be adjusted to include or exclude certain applications based on your specific needs.

Open the crs-setup.conf file for the latest OWASP CRS version:

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

In the configuration file, you will find sections to enable or disable exclusions for various applications. For instance, to enable exclusions for WordPress, phpBB, and phpMyAdmin and disable others, modify the configuration 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"

This setup activates exclusions for the specified applications, reducing false positives related to their normal behavior.

Setting Up Custom Exclusions

Custom exclusions are necessary for tailored ModSecurity behavior. Start by creating a backup of the sample exclusion rules file:

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

When creating custom exclusion rules, ensure that each rule has a unique ID (id:<rule number>) to avoid configuration errors.

For instance, to create rules that allow specific REQUEST_URI patterns, add rules like:

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 allow requests that begin with specified paths, bypassing other CRS checks for these URIs.

Whitelisting IP Addresses

Whitelisting specific IP addresses is another way to reduce false positives. This can be done by specifying individual IPs or ranges. For example:

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"

The @ipMatch directive allows for more extensive matching, including subnets. To deny access to certain IPs or subnets, change allow to deny in the rule.

With a deeper understanding of these configurations, you can create sophisticated blacklists and whitelists and integrate them with tools like Fail2Ban for enhanced security management.

Create ModSecurity 3 LogRotate File on Fedora Linux

Setting Up Log Rotation for ModSecurity

ModSecurity can generate extensive logs over time. A log rotation is crucial to manage this effectively on Fedora Linux, mainly since ModSecurity is compiled manually and not installed from an official repository. This process helps in maintaining log file size and ensures better manageability.

Creating a LogRotate Configuration File

Begin by creating a log rotation configuration file specifically for ModSecurity:

sudo nano /etc/logrotate.d/modsec

This command opens a new file named modsec in the /etc/logrotate.d directory, where you’ll define the log rotation rules for ModSecurity.

Configuring Log Rotation Settings

In the opened file, paste the following configuration:

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

This configuration sets up the log rotation for the ModSecurity audit log file located at /var/log/modsec_audit.log. Here’s a breakdown of what each directive accomplishes:

  • rotate 31: Retains the logs for 31 days. You can adjust this number to your preference, such as 7 for a week’s worth of logs.
  • daily: Specifies that the log rotation should occur daily.
  • missingok: Allows the rotation to proceed without error messages if the log file is missing.
  • compress: Compresses older versions of log files to save space.
  • delaycompress: Delays compression until the next log rotation cycle. This is useful for keeping the most recent uncompressed log file for immediate readability.
  • notifempty: Prevents rotation if the log file is empty, avoiding the creation of unnecessary empty rotated files.

Daily rotation is recommended for ModSecurity logs because of their potential size. Weekly rotations could result in unwieldy and large files that are difficult to review.

After adding these settings, save and exit the file. This configuration will ensure that your ModSecurity logs.

Important Note about Upgrading Nginx

Handling Nginx Upgrades with Compiled Dynamic Modules

When you’ve compiled a dynamic module for a specific Nginx version, it’s crucial to address upgrades appropriately. Any time a new version of Nginx is released, upgrading and recompiling the dynamic module is necessary to ensure compatibility.

Process for Upgrading Nginx with ModSecurity 3 on Fedora

The upgrading process becomes straightforward with experience. For most users, these steps can be completed quickly:

  1. Download the Latest Nginx Source: Begin by downloading the latest version of the Nginx source. This step is essential to obtain the most recent updates and features.
  2. Recompile the Dynamic Module: Once you have the new source, recompile the dynamic module. This recompilation is crucial because each Nginx version may have differences that impact the module’s functionality.
  3. Replace the Old Module: After recompiling, replace the old module with the newly compiled version. This ensures that the enhancements and fixes in the new Nginx version are effectively integrated into your server environment.
  4. Retain Your Configuration Files: A significant advantage of this process is that your existing configuration files remain unchanged. There’s no need to modify or adjust them during the upgrade process. The command to test if the new module is working correctly is:
nginx -t

Conclusion

This guide has equipped you with the know-how to install Nginx, download its source, compile ModSecurity, and integrate the OWASP Core Rule Set, key steps in fortifying your server’s security. Deploying ModSecurity is a significant step towards robust protection, but remember, it’s not just a set-it-and-forget-it solution. It demands patience, time, and continual learning to fine-tune its settings.

As you navigate its configurations, remember the importance of balancing security with accessibility. The goal is to shield your server from threats without inadvertently blocking legitimate SEO bots or, crucially, real visitors who could be potential customers. With these tips and your new setup, you’re well on your way to maintaining a secure and user-friendly server environment.

Leave a Comment


Your Mastodon Instance
Share to...