How to Implement ModSecurity OWASP Core Rule Set in Nginx

The OWASP ModSecurity Core Rule Set (CRS) provides extensive protections against the top application vulnerabilities and automated threats facing web applications today. Originally developed to power Linux web application firewalls, these rules encode expertise against the OWASP Top 10 risks, platform-specific attacks, bots, policy violations and more.

Integrating the CRS ruleset into Nginx via the ModSecurity module converts Nginx into a full featured Web Application Firewall. This guides provides in-depth configuration, customization and management guidance to realize the full benefits of the OWASP CRS protections.

Background on ModSecurity and OWASP Core Rule Set

First launched in 2002, ModSecurity pioneered the web application firewall concept. By interceding within the web server itself, ModSecurity allowed deep analysis of all application traffic to detect and block threats. The open source code base enabled the community to contribute protections against an expanding range of attack types.

In 2009, Trustwave SpiderLabs began sponsorship and maintenance of a consolidated rule set – the OWASP ModSecurity Core Rule Set. Bringing together hundreds of the best open source rules, the Core Rule Set (CRS) provides:

  • Comprehensive coverage – 10,000+ data points across 14 rule categories detecting the OWASP Top 10, bots, geography, compliance and more
  • High precision – Low false positive rates via negative security model and exception handling
  • Easy portability – Works across web servers with ModSecurity module (Nginx, Apache)
  • Ongoing support – Constant rule enhancements by SpiderLabs team

The CRS project maintains documentation on the dozens of included rule files spanning:

Rule Category Description # Rules
Request Limits Traffic throttling 17
HTTP Policy Protocol checks 491
Protocol Attacks Request smuggling, slowloris 24

And many more categories around bot detection, DDoS protection, malware attacks, file injections, directory traversals, code executions, data exfiltrations, and web frameworks like Java, PHP, .NET and more.

Implementing this robust CRS ruleset on Nginx transforms it into a highly accurate web application firewall protecting against the primary threats targeting internet-facing systems today.

Benefits of Adding ModSecurity CRS to Nginx

Integrating the OWASP Core Rule Set into your Nginx environment provides immediate security and compliance benefits:

Stops automated attacks – Credential stuffing, SQL injection tools, vulnerability scanners
Prevents data loss – Detects theft attempts, blocks file injections
Enforces policies – Validates headers, encodings, protocols
Protects origin servers – Stops events reaching backends entirely
Increases visibility – Centralized logging at machine speed
Demonstrates compliance – Reports against key standards like PCI DSS

Per Incapsula research, sites deploying ModSecurity CRS show a 90% drop in successful attacks. Over 75% of unlawful access attempts were blocked completely.

Implementing OWASP CRS in Nginx

With thousands of curated rules protecting against just about any web-based attack vector, integrating ModSecurity CRS into your Nginx environment delivers immediate security returns.

Major steps covered in this guide:

  1. Confirming installation prerequisites
  2. Downloading and configuring OWASP CRS packages
  3. Essential configuration for enforcement
  4. Customizing rules and exclusions
  5. Monitoring blocked requests and events
  6. Updating rules and optimizations

Prerequisites

Before starting, confirm you have a working Nginx installation with the headers-more and ModSecurity modules installed and enabled. Compiling from source is the typical approach in order to utilize the latest supported features.

See How to Install ModSecurity on Nginx for the specifics on obtaining dependencies, custom module compilation, and initial configuration.

Other key prerequisites:

  • Supported Nginx version
  • desired site/vhost has ModSecurity enabled
  • Baseline ModSecurity configuration directives

With a working ModSecurity implementation in Nginx, we can proceed to downloading and configuring the OWASP CRS packages.

Downloading and Configuring the OWASP Core Rule Set

To enable the OWASP CRS protection, we first need to pull down the latest rules package:

1. Grab Files from GitHub

Download or use wget to grab the OWASP ModSecurity CRS archive.

2. Review Contents

The package includes:

  • Base Rules – Actual detection and protection logic
  • Data Set Files – External data for geo lists, signatures, etc used in rules
  • Main Configuration File – Primary settings

3. Unpack and Copy to Nginx Configuration Area

Unpack and copy:

  • modsecurity_crs_10_setup.conf
  • base_rules folder
  • .data files

into /etc/nginx or wherever Nginx is reading configuration from.

4. Merge Configuration Together

Unlike Apache, Nginx requires a single combined configuration file.

We concatenate the key files together:

cat modsecurity_crs_10_setup.conf base_rules/*.conf > modsecurity.conf

5. Configure Nginx to Load Rules

Adjust the Nginx vhost to point to this merged configuration:

ModSecurityEnabled on; 
ModSecurityConfig modsecurity.conf;

This will load the OWASP CRS ruleset and prepare ModSecurity for enforcement and protection!

Now we need to complete essential runtime configuration.

Essential ModSecurity Configuration

With the OWASP CRS rules deployed, we need to update settings for blocking, logging, and customization:

Enable Logging

Get visibility by sending audit logs to a dedicated CRS log file:

SecAuditLog /var/log/modsec_audit.log

Turn On the Rules Engine

Flip the switch to activate request analysis and intervention:

SecRuleEngine On

Set Default Action to Block

Make violations actually block traffic instead of just detect:

SecDefaultAction "phase:1,deny,log"

Change Exposed Server Header

Mask precise version to avoid targeting:

SecServerSignature "Nginx"

This essential configuration ensures the OWASP CRS is active and protecting web application traffic per policy requirements.

Further customization helps improve performance and reduce false positives.

Customizing Rules and Settings

While the CRS works well out of the box, tuning is needed for:

  • Performance optimization
  • Reducing false positives
  • Updating rule logic
  • Excluding application specific patterns

Common examples include:

Performance Tuning

SecRuleUpdateTargetById 950130 "!@contains"  

SecAction "id:900001 ctl:ruleEngine= tx.sql_injection_score=0 tx.crs_setup_version=3.0.0"

Excluding Rules

Disable unneeded path checks for example:

SecRuleRemoveById 950117

Change Rule Actions

SecRule REQUEST_COOKIES|!@streq "vistor_id=" \
  "phase:request,\  
  t:none, \ 
  nolog,
  pass,
  ctl:ruleRemoveTargetById=942450;REQUEST_COOKIES:vistor"

Run New Rules in Detection Mode First

Monitor impact before blocking:

SecDefaultAction "phase:1,log,auditlog"  

Properly tuning performance and accuracy is key to CRS success!

Monitoring and Alerting

With requests now blocked per policy by the CRS, capturing and monitoring these events is critical for visibility and response.

Central Log Analysis

Tools like ELK, Splunk, SumoLogic enable aggregating logs across servers and in-depth analytics.

Dashboards

Build CRS dashboards in Grafana Cloud to monitor blocked attacks, triggered rules, traffic analytics and more.

Integrate into SIEM and Ticketing

Send logs to security orchestration tools like Demisto for automated response actions.

Regulatory Reporting

Produce compliance reports showing enforcement of PCI, HIPAA standards.

Effective monitoring transforms raw logs into continuous insight into attack campaigns, operationalimpact, and risk reduction.

Ongoing Rule Management

To sustain protections, we need to stay up to date on:

Regular Ruleset Updates

  • Review release notes
  • Pull down incremental rule changes
  • Load updated logic per process

Performance Optimization

  • Load test after major updates
  • Balance overhead of checks
  • Tune thresholds and limits

Log Analysis and Tuning

Analyze logs for tuning opportunities:

  • False vs true positives
  • New application denial events
  • Attack signatures

Develop Custom Rules

Extend core ruleset with app-specific input validation checks for stronger protections.

Proactively managing rules preserves protection capabilities over time as attacks evolve.

Conclusion

Implementing the industry-standard OWASP CRS rules for Nginx elevates defenses while providing detailed blocking and visibility capabilities. Rule maintenance and customization balances robust protections with application availability needs.

Integrating ModSecurity also paves the way for further controls like IDS, fraud checks, compliance policy enforcement, and ancillary protections to extend the WAF capabilities even further across the application environment.