How to Install ModSecurity in Nginx on Ubuntu 18.04 20.4 22.04 & Debian

Posted on

How to Install ModSecurity in Nginx on Ubuntu 18.04 20.4 22.04 & Debian

How to Install ModSecurity in Nginx on Ubuntu 18.04 20.4 22.04 & Debian

ModSecurity is a powerful, open-source web application firewall (WAF) designed to shield web applications from a myriad of malicious attacks. It operates at layer 7 (the application layer) of the OSI model, specifically targeting threats like SQL injection, cross-site scripting (XSS), and other sophisticated application-level exploits. This tutorial provides a comprehensive guide on how to install and configure ModSecurity in conjunction with Nginx on Ubuntu and Debian systems, fortifying your web server against potential vulnerabilities. This article focuses on How to Install ModSecurity in Nginx.

Prerequisites

Before embarking on the installation process, ensure that you have the following prerequisites in place:

  • A server running Ubuntu 18.04, 20.04, 22.04, or Debian.
  • Root or sudo privileges on the server.
  • A working installation of Nginx web server.
  • Basic familiarity with Linux command-line operations.

Step 1: Install Nginx

If Nginx is not already installed on your server, execute the following command to install it. If you already have Nginx installed, you can safely skip this step.

$ sudo apt install nginx

Step 2: Download and Compile ModSecurity

First, install the necessary build dependencies. These tools are essential for compiling ModSecurity from source.

$ apt-get install libtool autoconf build-essential libpcre3-dev zlib1g-dev libssl-dev libxml2-dev libgeoip-dev liblmdb-dev libyajl-dev libcurl4-openssl-dev libpcre++-dev pkgconf libxslt1-dev libgd-dev automake

Next, download the ModSecurity source code from the official GitHub repository.

$ cd /usr/local/src
$ git clone --depth 100 -b v3/master --single-branch https://github.com/SpiderLabs/ModSecurity
$ cd ModSecurity
$ git submodule init
$ git submodule update

Now, compile ModSecurity and install it on your server. This process involves generating a configuration file, performing dependency checks, compiling the source code, and installing the ModSecurity library.

# Generate configure file
$ sh build.sh
# Pre compilation step. Checks for dependencies
./configure
# Compiles the source code
$ make
# Installs the Libmodsecurity to **/usr/local/modsecurity/lib/libmodsecurity.so**
$ make install

Step 3: Download and Compile ModSecurity v3 Nginx Connector Source Code

Determine your Nginx server version by running the command nginx -V. This version number is crucial for downloading the correct Nginx source code and the Nginx Connector Source Code. The source code is then used to generate a Libmodsecurity module specifically tailored for your Nginx server.

$ mkdir /usr/local/src/cpg
$ cd /usr/local/src/cpg

Replace 1.21.4 with your actual Nginx version number.

$ wget http://nginx.org/download/nginx-1.21.4.tar.gz
$ tar -xvzf nginx-1.21.4.tar.gz
# Download the source code for ModSecurity-nginx connector
$ git clone https://github.com/SpiderLabs/ModSecurity-nginx
Compile Nginx

Compile Nginx with the ModSecurity module. It’s crucial that your Nginx package is compiled with the --with-compat flag. This flag ensures that the module is binary-compatible with your existing Nginx binary.

$ cd nginx-1.21.4
$ ./configure --with-compat --with-openssl=/usr/include/openssl/ --add-dynamic-module=/usr/local/src/cpg/ModSecurity-nginx

Build the modules and copy the resulting module to the Nginx module directory.

$ make modules
$ cp objs/ngx_http_modsecurity_module.so /usr/share/nginx/modules/

Step 4: Load ModSecurity Module into Nginx

Open the file /etc/nginx/modules-enabled/50-mod-http-modsecurity.conf and add the following line to load the ModSecurity module.

load_module modules/ngx_http_modsecurity_module.so;

Step 5: Install Nginx Configuration

  1. Open /etc/nginx/nginx.conf and add the following line after including /etc/nginx/sites-enabled/*.conf.
include /etc/nginx/cpguard_waf_load.conf;
  1. Add the following contents to /etc/nginx/cpguard_waf_load.conf.
modsecurity on;
modsecurity_rules_file /etc/nginx/nginx-modsecurity.conf;
  1. Add the following contents to /etc/nginx/nginx-modsecurity.conf.
SecRuleEngine On
SecRequestBodyAccess On
SecDefaultAction "phase:2,deny,log,status:406"
SecRequestBodyLimitAction ProcessPartial
SecResponseBodyLimitAction ProcessPartial
SecRequestBodyLimit 13107200
SecRequestBodyNoFilesLimit 131072
SecPcreMatchLimit 250000
SecPcreMatchLimitRecursion 250000
SecCollectionTimeout 600
SecDebugLog /var/log/nginx/modsec_debug.log
SecDebugLogLevel 0
SecAuditEngine RelevantOnly
SecAuditLog /var/log/nginx/modsec_audit.log
SecUploadDir /tmp
SecTmpDir /tmp
SecDataDir /tmp
SecTmpSaveUploadedFiles on
# Include file for cPGuard WAF
Include /etc/nginx/cpguard_waf.conf

Step 6: Configure cPGuard WAF Parameters

Once the above steps are completed successfully, you can use the following parameter values.

waf_server = nginx
waf_server_conf = /etc/nginx/cpguard_waf.conf
waf_server_restart_cmd = /usr/sbin/service nginx restart
waf_audit_log = /var/log/nginx/modsec_audit.log
That’s it

You should now have ModSecurity enabled and properly configured. With cPGuard WAF enabled, your server is now better protected against various web attacks. This guide on How to Install ModSecurity in Nginx provides a solid foundation.

Alternative Solutions for Web Application Firewall Protection

While the above method details a robust approach to implementing ModSecurity with Nginx, there are alternative strategies for achieving similar web application firewall protection. Here are two different approaches:

1. Using a Pre-built ModSecurity Nginx Module (Dynamic Modules)

Instead of compiling from source, you can leverage pre-built dynamic modules for Nginx. This approach significantly simplifies the installation process, especially for users who prefer avoiding manual compilation.

Explanation:

Many package repositories now offer pre-built dynamic modules for ModSecurity and Nginx. These modules are designed to be easily loaded into your Nginx configuration without the need for recompiling Nginx from source. This method relies on the dynamic module loading capabilities of Nginx.

Steps:

  1. Check your distribution’s repository: Search for a nginx-module-modsecurity or similar package within your distribution’s package manager (apt, yum, etc.).

    sudo apt search nginx-module-modsecurity
  2. Install the module: If found, install the package using your package manager.

    sudo apt install nginx-module-modsecurity
  3. Configure Nginx to load the module: The package installation should create a configuration file to load the module. It might be located in /etc/nginx/modules-available/ or /etc/nginx/conf.d/. Enable the module by creating a symbolic link to the /etc/nginx/modules-enabled/ directory.

    sudo ln -s /etc/nginx/modules-available/mod-http-modsecurity.conf /etc/nginx/modules-enabled/
  4. Configure ModSecurity: Follow steps 5 and 6 from the original guide to configure ModSecurity rules and parameters.

  5. Restart Nginx: Restart Nginx to load the newly installed module.

    sudo systemctl restart nginx

Advantages:

  • Simpler Installation: Eliminates the complexities of compiling from source.
  • Package Management: Benefits from automatic updates and dependency management provided by your distribution’s package manager.

Disadvantages:

  • Availability: Pre-built modules may not be available for all distributions or Nginx versions.
  • Version Compatibility: Ensure the module is compatible with your specific Nginx version.
  • Customization: May offer less flexibility for advanced customization compared to compiling from source.

2. Utilizing a Cloud-Based Web Application Firewall (WAF)

Instead of self-hosting and managing ModSecurity, you can leverage cloud-based WAF services. This offloads the complexity of WAF management to a specialized provider. This is another great way for How to Install ModSecurity in Nginx.

Explanation:

Cloud-based WAFs provide a managed security solution. Traffic to your web application is routed through the WAF provider’s infrastructure, where it is inspected for malicious activity before being forwarded to your origin server. This approach offers a number of benefits, including ease of deployment, scalability, and continuous rule updates.

Steps:

  1. Choose a Cloud WAF Provider: Research and select a cloud WAF provider that meets your needs (e.g., Cloudflare, AWS WAF, Azure Web Application Firewall).
  2. Configure DNS: Update your DNS records to point to the WAF provider’s infrastructure. This typically involves changing your domain’s A records or using a CNAME record. The specific steps will vary depending on the provider.
  3. Configure WAF Rules: The WAF provider will offer a dashboard or API for configuring WAF rules. You can choose from pre-defined rule sets or create custom rules to address specific threats. Many provide OWASP ModSecurity Core Rule Set support.
  4. Monitor and Tune: Continuously monitor your WAF logs and tune the rules as needed to optimize performance and security.

Code Example (Illustrative, specific to AWS WAF using AWS CLI):

This example demonstrates how to create a basic AWS WAF rule to block requests from a specific IP address.

aws wafv2 create-rule 
    --name BlockSpecificIP 
    --scope CLOUDFRONT 
    --visibility-config SampledRequestsEnabled=true,CloudWatchMetricsEnabled=true,MetricName=BlockSpecificIPMetric 
    --statement '{
        "IPSetReferenceStatement": {
            "ARN": "arn:aws:wafv2:us-east-1:123456789012:regional/ipset/MyIPSet/a1b2c3d4-e5f6-7890-1234-567890abcdef"
        }
    }' 
    --action '{ "Block": {} }' 
    --priority 1 
    --description "Blocks requests from a specific IP address"

Advantages:

  • Ease of Deployment: Quick setup compared to self-hosting ModSecurity.
  • Scalability: Handles large traffic volumes and scales automatically.
  • Managed Service: Reduces the operational burden of managing a WAF.
  • Continuous Updates: Providers typically update their rule sets regularly to address new threats.

Disadvantages:

  • Cost: Cloud WAFs are typically subscription-based services.
  • Vendor Lock-in: Migrating to a different provider can be complex.
  • Latency: Introducing a WAF can add a small amount of latency to requests.
  • Data Privacy: Traffic is routed through the WAF provider’s infrastructure, raising potential data privacy concerns.

These alternative solutions offer different trade-offs in terms of complexity, cost, and control. Carefully evaluate your specific needs and resources before choosing the best approach for protecting your web applications. Remember that the best method for How to Install ModSecurity in Nginx depends on your specific needs.