Introduction
In this guide, we’ll walk you through the installation of Nginx, ModSecurity 3, and CoreRuleSet 4.8.0, providing a robust security setup to protect your server from a wide range of web attacks. ModSecurity is a web application firewall (WAF) that helps defend against common vulnerabilities like SQL injection, XSS, and more. CoreRuleSet provides a comprehensive set of rules for real-time attack detection and prevention.
Prerequisites
Before starting, ensure you have the following:
- A Linux server (Ubuntu 20.04 or higher).
- Root or sudo access to the server.
- Nginx installed and running (we’ll cover this in the first step).
- Basic knowledge of the command line.
Step 1: Install Nginx
First, we need to install Nginx on your server. Nginx will be used as the reverse proxy and web server.
- Update your package list:
sudo apt update
- Install Nginx:
sudo apt install nginx
- Start and enable Nginx:
sudo systemctl start nginx
sudo systemctl enable nginx
- Verify the installation by visiting your server’s IP address:
http://<your-server-ip>
You should see the Nginx default welcome page.
Step 2: Install ModSecurity 3 (with Nginx)
ModSecurity 3 is the latest version of the Web Application Firewall (WAF). To integrate ModSecurity with Nginx, we’ll need to compile it from source.
- Install required dependencies:
sudo apt install build-essential libtool libpcre3 libpcre3-dev libxml2 libxml2-dev \
libyajl-dev libgeoip-dev libcurl4-openssl-dev libkrb5-dev zlib1g-dev libssl-dev \
git automake autoconf
- Clone ModSecurity 3:
cd /usr/local/src
sudo git clone --branch v3/master https://github.com/SpiderLabs/ModSecurity
cd ModSecurity
- Compile and install ModSecurity:
sudo ./build.sh
sudo make
sudo make install
- Download and install the ModSecurity-nginx connector:
cd /usr/local/src
sudo git clone https://github.com/SpiderLabs/ModSecurity-nginx.git
cd ModSecurity-nginx
- Install Nginx with ModSecurity: You’ll need to recompile Nginx with the ModSecurity module enabled:
sudo apt install nginx-module-modsecurity
cd /etc/nginx
sudo nginx -V 2>&1 | grep -- --with-http_modsecurity
- Restart Nginx to apply the changes:
sudo systemctl restart nginx
Step 3: Install and Configure CoreRuleSet (CRS) 4.8.0
CoreRuleSet (CRS) is a set of security rules for ModSecurity, designed to protect against a wide range of web application vulnerabilities.
- Download CRS version 4.8.0:
cd /usr/local/src
sudo git clone --branch v4.8.0 https://github.com/coreruleset/coreruleset
- Configure ModSecurity to use CRS:
- Create a directory to store the CRS rules:
sudo mkdir /etc/modsecurity sudo cp -r /usr/local/src/coreruleset/rules/ /etc/modsecurity/
- Configure ModSecurity to load the CRS rules. Edit the ModSecurity configuration file:
sudo nano /etc/modsecurity/modsecurity.conf
Add the following to enable CRS:IncludeOptional /etc/modsecurity/rules/*.conf
- Enable ModSecurity in Nginx:
- Open the Nginx configuration file for editing:
sudo nano /etc/nginx/nginx.conf
- Add the following configuration to enable ModSecurity:
http { include /etc/nginx/mime.types; default_type application/octet-stream; modsecurity on; modsecurity_rules_file /etc/modsecurity/modsecurity.conf; ... }
- Restart Nginx to apply the configuration:
sudo systemctl restart nginx
Step 4: Advanced Configuration for Security
Now, let’s configure ModSecurity and CRS to block a variety of attacks and enhance the overall security of your web server.
Enable Logging and Audit
- Enable ModSecurity logging in
/etc/modsecurity/modsecurity.conf
:
SecAuditEngine On
SecAuditLog /var/log/modsec_audit.log
- Define audit log format: In
/etc/modsecurity/modsecurity.conf
, add:
SecAuditLogFormat JSON
- Create necessary directories:
sudo mkdir /var/log/modsec
sudo touch /var/log/modsec_audit.log
sudo chmod 600 /var/log/modsec_audit.log
Blocking Specific Attacks
ModSecurity and CRS provide out-of-the-box protection against several types of attacks. However, you can fine-tune these protections as per your needs:
- SQL Injection Prevention: ModSecurity has built-in rules to block SQL injection attempts. To enhance this, ensure that the CRS SQL Injection rules are enabled. You can view these in
/etc/modsecurity/rules/REQUEST-950-APPLICATION-ATTACK-SQLI.conf
.
SecRule REQUEST_URI|ARGS|ARGS_NAMES|REQUEST_HEADERS|XML:/* "@rx select.*from.*information_schema.tables" \
"id:1000001,phase:2,deny,status:403,msg:'SQL Injection Detected'"
- Cross-Site Scripting (XSS) Prevention: CRS provides protection against XSS by matching potentially dangerous patterns in URLs and headers. For additional protection, add custom XSS rules:
SecRule ARGS|ARGS_NAMES|REQUEST_HEADERS|XML:/* "@rx <script.*?>" \
"id:1000002,phase:2,deny,status:403,msg:'XSS Detected'"
- Cross-Site Request Forgery (CSRF): Prevent CSRF attacks by inspecting the request headers and ensuring that a token is present. Add the following rule:
SecRule REQUEST_HEADERS:Referer "!@rx ^https?://(.*)yourdomain\.com" \
"id:1000003,phase:2,deny,status:403,msg:'CSRF Detected'"
- File Upload Restrictions: Add rules to prevent the upload of dangerous file types, such as PHP, JSP, and other executable files:
SecRule FILES|FILES_NAMES "@rx \.(php|jsp|asp)$" \
"id:1000004,phase:2,deny,status:403,msg:'Forbidden File Type Uploaded'"
Step 5: Monitor and Analyze Logs
ModSecurity and Nginx will generate logs that provide insight into blocked attacks and other activities:
- Monitor the ModSecurity audit log: Use the following command to view the audit logs:
tail -f /var/log/modsec_audit.log
- Analyze the logs for blocked attacks: You can analyze specific attack types by filtering the logs with
grep
. For example, to see SQL Injection attempts:
grep 'SQL Injection' /var/log/modsec_audit.log
- Set up log rotation: To prevent log files from growing indefinitely, configure log rotation. Create a configuration file
/etc/logrotate.d/modsec
:
/var/log/modsec_audit.log {
daily
rotate 7
compress
missingok
notifempty
}
Conclusion
By following this guide, you have successfully set up Nginx with ModSecurity 3 and CoreRuleSet 4.8.0, providing robust security for your web applications. You’ve also configured advanced protections against common web attacks and set up monitoring and logging for ongoing security management.
For optimal security, regularly update ModSecurity rules, monitor logs, and fine-tune your configuration as new attack vectors emerge. This setup ensures a secure, responsive environment for your web server.
Advanced ModSecurity Rules to Block Common Web Attacks
In this section, we’ll integrate specific ModSecurity rules to block a wide variety of attacks, including SQL Injection (SQLi), Cross Site Scripting (XSS), Local File Inclusion (LFI), Remote File Inclusion (RFI), PHP Code Injection, Java Code Injection, HTTPoxy, Shellshock, Unix/Windows Shell Injection, Session Fixation, Scanner/Bot Detection, and Metadata/Error Leakages. These rules will enhance your ModSecurity and CoreRuleSet (CRS) configuration, protecting your server against a range of dangerous web application vulnerabilities.
1. SQL Injection (SQLi)
SQL injection attacks are one of the most common web vulnerabilities. ModSecurity and CRS provide protection against SQLi by inspecting user input and identifying malicious patterns.
ModSecurity Rule:
SecRule REQUEST_URI|ARGS|ARGS_NAMES|REQUEST_HEADERS|XML:/* "@rx select.*from.*information_schema.tables" \
"id:1000001,phase:2,deny,status:403,msg:'SQL Injection Detected'"
SecRule ARGS|ARGS_NAMES|REQUEST_HEADERS|XML:/* "@rx union.*select.*from.*information_schema.columns" \
"id:1000002,phase:2,deny,status:403,msg:'SQL Injection Detected'"
These rules detect SQL keywords like select
, union
, and from
used in unauthorized contexts. They block requests containing these patterns, which are common indicators of SQLi attacks.
2. Cross Site Scripting (XSS)
XSS attacks occur when malicious scripts are injected into web pages viewed by other users. ModSecurity can block potentially dangerous scripts in HTTP requests.
ModSecurity Rule:
SecRule ARGS|ARGS_NAMES|REQUEST_HEADERS|XML:/* "@rx <script.*?>" \
"id:1000003,phase:2,deny,status:403,msg:'Cross-Site Scripting (XSS) Detected'"
SecRule ARGS|ARGS_NAMES|REQUEST_HEADERS|XML:/* "@rx <img.*src=.*onerror.*>" \
"id:1000004,phase:2,deny,status:403,msg:'XSS Image Tag Injection Detected'"
These rules block suspicious <script>
and <img>
tags, which are common XSS vectors. XSS is often used to inject malicious JavaScript, so blocking these patterns helps mitigate risks.
3. Local File Inclusion (LFI)
LFI vulnerabilities occur when user input is used to include local files on the server, which can lead to code execution.
ModSecurity Rule:
SecRule ARGS|ARGS_NAMES|REQUEST_HEADERS|XML:/* "@rx (\.\./|\.\.\\)" \
"id:1000005,phase:2,deny,status:403,msg:'Local File Inclusion (LFI) Detected'"
SecRule ARGS|ARGS_NAMES|REQUEST_HEADERS|XML:/* "@rx /etc/passwd" \
"id:1000006,phase:2,deny,status:403,msg:'Local File Inclusion (LFI) Detected (etc/passwd)'"
These rules block attempts to traverse directories (../
or ..\
) and access sensitive system files such as /etc/passwd
, which are common indicators of LFI attacks.
4. Remote File Inclusion (RFI)
RFI vulnerabilities occur when a web application allows user input to include files from remote locations. This can lead to the execution of malicious code.
ModSecurity Rule:
SecRule ARGS|ARGS_NAMES|REQUEST_HEADERS|XML:/* "@rx http[s]?://.*\.(php|jsp|asp|cgi)" \
"id:1000007,phase:2,deny,status:403,msg:'Remote File Inclusion (RFI) Detected'"
SecRule ARGS|ARGS_NAMES|REQUEST_HEADERS|XML:/* "@rx \.php\?http[s]?://.*" \
"id:1000008,phase:2,deny,status:403,msg:'Remote File Inclusion (RFI) Detected'"
These rules block attempts to include remote files with .php
, .jsp
, .asp
, or .cgi
extensions. Remote files should not be allowed unless explicitly intended.
5. PHP Code Injection
PHP code injection attacks occur when malicious PHP code is injected into requests, which the server later executes.
ModSecurity Rule:
SecRule ARGS|ARGS_NAMES|REQUEST_HEADERS|XML:/* "@rx <\?php.*\?>" \
"id:1000009,phase:2,deny,status:403,msg:'PHP Code Injection Detected'"
SecRule ARGS|ARGS_NAMES|REQUEST_HEADERS|XML:/* "@rx eval\(.*\)" \
"id:1000010,phase:2,deny,status:403,msg:'PHP eval() Injection Detected'"
These rules detect PHP code snippets like <?php ... ?>
and eval()
, which are common in PHP code injection attacks.
6. Java Code Injection
Java code injection happens when an attacker injects malicious Java code into web applications, potentially leading to arbitrary code execution.
ModSecurity Rule:
SecRule ARGS|ARGS_NAMES|REQUEST_HEADERS|XML:/* "@rx System\.exec\(" \
"id:1000011,phase:2,deny,status:403,msg:'Java Code Injection Detected'"
SecRule ARGS|ARGS_NAMES|REQUEST_HEADERS|XML:/* "@rx Runtime\.getRuntime\(\)" \
"id:1000012,phase:2,deny,status:403,msg:'Java Code Injection Detected'"
This rule blocks the use of Java code execution functions like System.exec()
and Runtime.getRuntime()
.
7. HTTPoxy
HTTPoxy exploits vulnerabilities in applications using HTTP proxies, allowing attackers to inject a proxy header into HTTP requests.
ModSecurity Rule:
SecRule REQUEST_HEADERS:Proxy "@rx ^.*$" \
"id:1000013,phase:1,deny,status:403,msg:'HTTPoxy Attack Detected'"
This rule blocks requests containing any proxy header, which is a typical indicator of an HTTPoxy attack.
8. Shellshock
Shellshock is a vulnerability in Bash that allows attackers to execute arbitrary commands through specially crafted environment variables.
ModSecurity Rule:
SecRule REQUEST_HEADERS|ARGS|ARGS_NAMES "@rx \(\)\s*\{\s*.*\}" \
"id:1000014,phase:2,deny,status:403,msg:'Shellshock Exploit Detected'"
This rule blocks requests containing Shellshock payloads, which exploit Bash command injection.
9. Unix/Windows Shell Injection
Shell injection occurs when user input is used to execute shell commands, leading to potential system compromise.
ModSecurity Rule:
SecRule ARGS|ARGS_NAMES|REQUEST_HEADERS|XML:/* "@rx (|;|\&\&|\|\|)" \
"id:1000015,phase:2,deny,status:403,msg:'Unix/Windows Shell Injection Detected'"
SecRule ARGS|ARGS_NAMES|REQUEST_HEADERS|XML:/* "@rx (exec\(|system\(|passthru\() " \
"id:1000016,phase:2,deny,status:403,msg:'Shell Command Injection Detected'"
These rules block attempts to inject shell commands by looking for special characters like |
, ;
, or functions such as exec()
and system()
.
10. Session Fixation
Session fixation attacks occur when an attacker sets a valid session ID for the victim, potentially hijacking their session.
ModSecurity Rule:
SecRule REQUEST_COOKIES:PHPSESSID "@rx ^[0-9a-fA-F]{32}$" \
"id:1000017,phase:2,deny,status:403,msg:'Session Fixation Attack Detected'"
This rule blocks attempts to use predefined session IDs that match the format of a typical session ID.
11. Scanner/Bot Detection
Web scanners and bots often probe websites for vulnerabilities. These bots can be identified and blocked by analyzing patterns of requests.
ModSecurity Rule:
SecRule REQUEST_HEADERS:User-Agent "@rx (bot|crawl|spider|scan|curl)" \
"id:1000018,phase:1,deny,status:403,msg:'Scanner/Bot Detected'"
This rule blocks requests with suspicious User-Agent
headers indicating web crawlers or bots.
12. Metadata/Error Leakages
Error leakages expose sensitive server information. This rule prevents sensitive error messages from being returned to the client.
ModSecurity Rule:
SecRule RESPONSE_STATUS "@rx ^(5|4)" \
"id:1000019,phase:4,deny,status:403,msg:'Potential Error Leakage Detected'"
SecRule RESPONSE_BODY "@rx (phpinfo\(\)|eval\()|\bselect\b" \
"id:1000020,phase:4,deny,status:403,msg:'Potential Information Leak Detected'"
This rule detects and blocks error messages or leaked metadata in HTTP responses.
Conclusion
These advanced ModSecurity rules are designed to prevent a wide range of web attacks, including SQL Injection, XSS, RFI/LFI, code injection (PHP/Java), Shellshock, and others. By implementing these rules, your web application firewall (WAF)
will be able to detect and block common and sophisticated attack techniques, securing your server from external threats.
Always monitor your logs, adjust rules as needed, and keep ModSecurity and CRS up-to-date to ensure your environment remains secure.
Leave a Reply