Ugacomp

How to Configure ModSecurity in Nginx

Where necessary, you may need to have access to a VPS server so you can follow how to implement the steps in this article.  You can get a cheaper VPS Server from Contabo with 4vCPU cores, 8GM RAM, and 32TB Bandwidth for less than $5.50 per month. Get this deal here now

Table of Contents

Cloud VPS S

$5.50 Monthly
  • 4 vCPU Cores | 8GB RAM

CLOUD VPS M

$15.50 Monthly
  • 6 vCPU Cores | 16GB RAM

CLOUD VPS L

$17.50 Monthly
  • 8 vCPU Cores | 24GB RAM

ModSecurity is a web application firewall that provides an additional layer of security for web applications. When integrated with Nginx, it helps protect against various web application attacks. In this article, we will guide you through the process of configuring ModSecurity in Nginx, ensuring a robust defense mechanism for your web server.

Installing ModSecurity for Nginx

Before configuring ModSecurity, you need to install the necessary components. You can use package managers like apt or yum for Linux distributions. For example:

For Ubuntu/Debian:

Here is the command to install ModSecurity on Ubuntu/Debian Linux systems:

sudo apt-get install libnginx-mod-security

For CentOS/RHEL

You can install ModSecurity on CentOS/RHEL Linux platforms using the following commands:

sudo yum install epel-release
sudo yum install nginx-mod-security

Enabling ModSecurity in Nginx

Once installed, enable the ModSecurity module in your Nginx configuration. Open your Nginx configuration file, commonly found at /etc/nginx/nginx.conf, and include the ModSecurity configurations.

sudo nano /etc/nginx/nginx.conf

Include ModSecurity Configuration:

Put the following ModSecurity code snippet into the nginx.conf file

http {
    # Other configurations...

    modsecurity on;
    modsecurity_rules_file /etc/nginx/modsec/main.conf;

    # Additional settings based on your requirements
}

In the above example, modsecurity on enables ModSecurity, and modsecurity_rules_file specifies the location of the main ModSecurity configuration file.

Configuring ModSecurity Rules

ModSecurity uses rules to identify and block malicious activities. Create a rules file (e.g., main.conf) to define your security policies. Below is a simplified example:

Create ModSecurity Rules File:

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

Example ModSecurity Rules:

SecRuleEngine On
SecRequestBodyAccess On
SecDataDir /var/cache/modsecurity

It’s important to understand that ModSecurity allows you to customize the rules based on your application or website security requirements.

Blocking Threats and Attacks with ModSecurity in Nginx

ModSecurity, when integrated with Nginx, becomes a powerful tool for blocking a wide range of threats and attacks on your web applications. let’s explore how to configure ModSecurity in Nginx to proactively defend against common web threats and attacks.

Blocking SQL Injection Attempts

SQL injection is a prevalent attack vector where an attacker injects malicious SQL code into input fields to manipulate a database. ModSecurity can be configured to detect and block such attempts.

For example, The following rule looks for common SQL injection patterns in the request arguments and denies access with a 403 Forbidden status if detected.

# /etc/nginx/modsec/sql_injection.conf

SecRule ARGS "@rx (['\"]|\\b(?:d(?:e(?:clare|vice|lete)|rop)|s(?:elect|leep|ub(?:str(?:ing)?)?|um)|c(?:o(?:ncat|n(?:v(?:ert|hex)|f(?:ert|rom)|tro(?:c|l)l)|mpress|unt)|reate)|u(?:n(?:i(?:on(?:\\s+all)?|q(?:ue(?:ry)?)?)?)?|p(?:d(?:ate)?|load)|x(?:ec(?:ute)?|pand)|ser(?:\\s+ascii)?)|i(?:n(?:sert(?:\\s+into)?|to)?)?|alter|e(?:l(?:evate(?:\\s+to)?|ect|if)|xp(?:_(?:c(?:md)?|reg)|and)|mpty|nd|val(?:uate)?|tc)?" \
  "id:1002,phase:2,deny,status:403,msg:'SQL injection attempt blocked'"

Blocking Cross-Site Scripting (XSS) Attacks

XSS attacks involve injecting malicious scripts into web pages that are then executed by the victim’s browser. ModSecurity can be configured to detect and block XSS attempts.

For example, the following rule checks request arguments, headers, and body for common XSS patterns and denies access with a 403 Forbidden status if detected.

# /etc/nginx/modsec/xss_attack.conf

SecRule ARGS|REQUEST_HEADERS|REQUEST_BODY "(\b(?:on(?:abort|blur|error|focus|load|resize|scroll)|key(?:press|down|up)|mouse(?:enter|leave|move|over)|submit|change|contextmenu)|javascript:|<\s*script\s*>)" \
  "id:1003,phase:2,deny,status:403,msg:'XSS attack attempt blocked'"

Blocking Brute Force Login Attempts

Brute force attacks involve repeated login attempts to gain unauthorized access. ModSecurity can help block these attacks by monitoring login patterns.

For example, The following rule targets login requests, specifically those with the username “admin” and password “password,” and denies access with a 403 Forbidden status if detected.

# /etc/nginx/modsec/brute_force.conf

SecRule REQUEST_URI "@contains /login" "chain,id:1004,phase:2,deny,status:403,msg:'Brute force attack attempt blocked'"
SecRule REQUEST_METHOD "@streq POST" "chain"
SecRule ARGS:login "@rx ^admin$" "chain"
SecRule ARGS:password "@rx ^password$"

Include Rules in Nginx Configuration

Include the custom rules in your main Nginx configuration file to ensure that they are applied.

sudo nano /etc/nginx/nginx.conf

You will need to paste the following block to include all the rules you created in nginx.conf configuration file

http {
    # Other configurations...

    modsecurity on;
    modsecurity_rules_file /etc/nginx/modsec/main.conf;
    modsecurity_rules_file /etc/nginx/modsec/sql_injection.conf;
    modsecurity_rules_file /etc/nginx/modsec/xss_attack.conf;
    modsecurity_rules_file /etc/nginx/modsec/brute_force.conf;

    # Additional settings based on your requirements
}

Create a Custom Rules File

To create custom ModSecurity rules, you can leverage the SecRule directive. This directive is used to define rules that specify conditions and actions to be taken when those conditions are met.

For example, let’s create custom_rules.conf file:

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

In this file, let’s add the following custom rules:

# /etc/nginx/modsec/custom_rules.conf

SecRule REQUEST_URI "@contains /admin/" "id:1001,phase:1,deny,status:403,msg:'Access to admin area is restricted'"

In this example, the rule checks if the requested URI contains “/admin/” and, if so, denies access with a 403 Forbidden status and logs a message.

Include Custom Rules in Main Configuration

Once you’ve created your custom rules, include the file in your main Nginx configuration.

sudo nano /etc/nginx/nginx.conf

Here is an example block you’re going to include:

http {
    # Other configurations...

    modsecurity on;
    modsecurity_rules_file /etc/nginx/modsec/main.conf;
    modsecurity_rules_file /etc/nginx/modsec/custom_rules.conf;
    
    # Additional settings based on your requirements
}

Including the custom rules file ensures that your specific security policies are applied alongside the main ModSecurity rules

Testing ModSecurity

After configuring ModSecurity, it’s crucial to test whether it’s working as expected. You can intentionally trigger a rule violation and check the logs for ModSecurity alerts.

Example Rule Violation:

curl -X POST -d "malicious_payload" http://your_domain.com/path/to/vulnerable/endpoint

Check ModSecurity logs for any alerts or rule violations:

sudo tail -f /var/log/modsec_audit.log

Conclusion

Configuring ModSecurity in Nginx enhances your web server’s security posture by providing real-time protection against web application attacks. Regularly update your rules and monitor ModSecurity logs to adapt to emerging threats and ensure a proactive defense mechanism for your web applications.

Hire us to handle what you want

Hire us through our Fiverr Profile and leave all the complicated & technical stuff to us. Here are some of the things we can do for you:

  • Website migration, troubleshooting, and maintenance.
  • Server & application deployment, scaling, troubleshooting, and maintenance
  • Deployment of Kubernetes, Docker, Cloudron, Ant Media, Apache, Nginx,  OpenVPN, cPanel, WHMCS, WordPress, and more
  • Everything you need on AWS, IBM Cloud, GCP, Azure, Oracle Cloud, Alibaba Cloud, Linode, Contabo, DigitalOcean, Ionos, Vultr, GoDaddy, HostGator, Namecheap, DreamHost, and more.
 

We will design, configure, deploy, or troubleshoot anything you want. Starting from $10, we will get your job done in the shortest time possible. Your payment is safe with Fiverr as we will only be paid once your project is completed.