ModSecurity

Open-source web application firewall engine for real-time HTTP traffic monitoring and filtering.

What is ModSecurity?

ModSecurity is an open-source web application firewall (WAF) engine that provides real-time HTTP traffic monitoring, logging, and filtering. Originally developed as an Apache module, ModSecurity has evolved into a cross-platform WAF engine that can be integrated with various web servers and reverse proxies to protect web applications from a wide range of attacks.

Key Features of ModSecurity

  • Open-Source: Free to use and modify under the Apache License 2.0
  • Cross-Platform: Compatible with Apache, Nginx, IIS, and other web servers
  • Rule-Based Engine: Uses flexible rule language for security policy definition
  • Real-Time Monitoring: Inspects HTTP traffic as it occurs
  • Logging Capabilities: Comprehensive audit logging for security analysis
  • Modular Architecture: Extensible through modules and plugins
  • OWASP CRS Support: Compatible with the OWASP Core Rule Set

How ModSecurity Works

  1. Request Interception: Captures incoming HTTP requests
  2. Rule Processing: Applies security rules to the request
  3. Action Execution: Blocks, allows, or modifies requests based on rules
  4. Logging: Records security events and transaction details
  5. Response Processing: Inspects and modifies outgoing responses

ModSecurity Architecture

graph TD
    A[Client] -->|HTTP Request| B[Web Server]
    B -->|Request| C[ModSecurity Engine]
    C -->|Rule Processing| D[Rule Set]
    D -->|Action| C
    C -->|Allowed| B
    C -->|Blocked| E[Error Response]
    B -->|Response| C
    C -->|Response Processing| B
    B -->|HTTP Response| A
    C -->|Audit Log| F[Log Storage]

ModSecurity Rule Language

ModSecurity uses a powerful rule language that allows administrators to define complex security policies:

SecRule REQUEST_FILENAME "@detectSQLi" \
    "id:1000,\
    phase:2,\
    deny,\
    status:403,\
    msg:'SQL Injection Detected',\
    logdata:'Matched Data: %{MATCHED_VAR}'"

Rule Components

  • Variables: Define what to inspect (REQUEST_FILENAME, ARGS, etc.)
  • Operators: Define how to inspect (@detectSQLi, @rx, @pm, etc.)
  • Actions: Define what to do (deny, allow, log, etc.)
  • Phases: Define when to execute (1-5)
  • Metadata: Additional information (id, msg, severity, etc.)

ModSecurity Phases

  1. Phase 1: Request Headers - Inspect request headers before body processing
  2. Phase 2: Request Body - Inspect request body after it's received
  3. Phase 3: Response Headers - Inspect response headers before body processing
  4. Phase 4: Response Body - Inspect response body before sending to client
  5. Phase 5: Logging - Final logging phase after transaction completion

Common Use Cases

  • Web Application Protection: Defense against OWASP Top 10 vulnerabilities
  • Virtual Patching: Temporary fixes for known vulnerabilities
  • Compliance Enforcement: PCI DSS, HIPAA, and other regulatory requirements
  • API Security: Protection for REST, SOAP, and GraphQL APIs
  • Bot Mitigation: Identification and blocking of malicious bots
  • DDoS Protection: Rate limiting and connection control
  • Data Loss Prevention: Monitoring and blocking sensitive data exfiltration

ModSecurity with OWASP Core Rule Set (CRS)

The OWASP Core Rule Set (CRS) is a set of generic attack detection rules for use with ModSecurity:

  • SQL Injection Protection: Detects and blocks SQLi attempts
  • Cross-Site Scripting (XSS): Identifies and mitigates XSS attacks
  • Local File Inclusion (LFI): Prevents unauthorized file access
  • Remote File Inclusion (RFI): Blocks remote file execution attempts
  • PHP Injection: Detects PHP code injection attempts
  • HTTP Protocol Violations: Enforces HTTP protocol compliance
  • Web Shell Detection: Identifies web shell uploads and execution

ModSecurity Configuration

Basic Configuration Directives

SecRuleEngine On
SecRequestBodyAccess On
SecResponseBodyAccess On
SecAuditEngine RelevantOnly
SecAuditLog /var/log/modsec_audit.log
SecDebugLog /var/log/modsec_debug.log
SecDebugLogLevel 3

Common Configuration Options

  • SecRuleEngine: Enable/disable ModSecurity (On/Off/DetectOnly)
  • SecRequestBodyAccess: Enable request body inspection
  • SecResponseBodyAccess: Enable response body inspection
  • SecAuditEngine: Configure audit logging (On/Off/RelevantOnly)
  • SecAuditLog: Specify audit log location
  • SecDebugLog: Configure debug logging
  • SecDebugLogLevel: Set debug verbosity (0-9)
  • SecRuleRemoveById: Disable specific rules

ModSecurity Performance Considerations

  • Rule Optimization: Disable unnecessary rules to reduce overhead
  • Phase Selection: Apply rules in appropriate phases to minimize processing
  • Rule Ordering: Place most frequently triggered rules first
  • Sampling: Use sampling for high-volume traffic
  • Caching: Cache rule processing results when possible
  • Hardware Acceleration: Use specialized hardware for rule processing

ModSecurity Integration

Web Servers

  • Apache: Native module (mod_security)
  • Nginx: Third-party module (ngx_http_modsecurity_module)
  • IIS: Commercial version (ModSecurity IIS)
  • Lighttpd: Third-party module

Reverse Proxies

  • Varnish: Through VCL integration
  • HAProxy: Using Lua scripts
  • Traefik: Plugin integration

Cloud Platforms

  • AWS: Integration with ALB and API Gateway
  • Azure: Application Gateway WAF
  • Google Cloud: Cloud Armor integration

ModSecurity vs. Commercial WAFs

FeatureModSecurityCommercial WAFs
CostFree (open-source)Paid (licensing fees)
SupportCommunity-basedVendor support
Ease of UseComplex configurationUser-friendly interfaces
Rule ManagementManual rule creationPre-built rule sets
PerformanceDepends on configurationOptimized for performance
IntegrationRequires manual setupPre-integrated with platforms
UpdatesCommunity-drivenVendor-provided
FeaturesBasic WAF functionalityAdvanced features (AI, bot detection)

ModSecurity Best Practices

  • Start in Detection Mode: Run in DetectOnly mode initially to avoid false positives
  • Use OWASP CRS: Implement the OWASP Core Rule Set as a baseline
  • Customize Rules: Tailor rules to your specific application needs
  • Monitor Logs: Regularly review audit and debug logs
  • Tune Rules: Adjust rule sensitivity based on false positives/negatives
  • Update Regularly: Keep ModSecurity and rule sets updated
  • Test Changes: Validate rule changes in staging environments
  • Implement Rate Limiting: Protect against brute force and DDoS attacks
  • Secure Configuration: Protect ModSecurity configuration files
  • Document Policies: Maintain documentation of security policies

ModSecurity Evasion Techniques

  • Encoding Attacks: URL, Unicode, or hex encoding to bypass rules
  • Case Variation: Changing letter case in attack payloads
  • Comment Injection: Using comments to break up attack patterns
  • Parameter Pollution: Duplicating or manipulating parameters
  • HTTP Header Manipulation: Modifying headers to bypass checks
  • Protocol-Level Evasion: Exploiting HTTP protocol quirks
  • Fragmentation: Splitting attacks across multiple requests
  • Behavioral Evasion: Mimicking legitimate user behavior

ModSecurity Logging and Monitoring

Audit Log Format

--a1b2c3d4-A--
[12/Dec/2025:15:30:45 +0100] WZq1Xm8AAQEAAFNJ-B4AAAAA 192.168.1.1 54321 10.0.0.1 80
--a1b2c3d4-B--
GET /login.php?user=admin'-- HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0
Accept: text/html

--a1b2c3d4-C--
HTTP/1.1 403 Forbidden
Content-Type: text/html
Connection: close

--a1b2c3d4-D--
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head><title>403 Forbidden</title></head><body></body></html>

--a1b2c3d4-E--
ModSecurity: Warning. Pattern match "(?i:(?:\\b(?:(?:s(?:elect\\b(?:.{1,100}?\\b(?:(?:length|count|top)\\b.{1,100}?\\bfrom|from\\b.{1,100}?\\bwhere)|.*?\\b(?:d(?:ump\\b.*\\bfrom|ata_type)|(?:to_(?:numbe|cha)|inst)r))|p_(?:(?:addextendedpro|sqlexe)c|(?:oacreat|prepar)e|execute(?:sql)?|makewebtask)|ql_(?:longvarchar|type)| ... [file "/etc/modsecurity/crs/rules/REQUEST-942-APPLICATION-ATTACK-SQLI.conf"] [line "64"] [id "942100"] [rev "2"] [msg "SQL Injection Attack Detected via libinjection"] [data "Matched Data: admin'-- found within ARGS:user"] [severity "CRITICAL"] [ver "OWASP_CRS/3.3.0"] [maturity "9"] [accuracy "8"] [tag "application-multi"] [tag "language-multi"] [tag "platform-multi"] [tag "attack-sqli"] [tag "OWASP_CRS"] [tag "OWASP_CRS/WEB_ATTACK/SQL_INJECTION"] [hostname "example.com"] [uri "/login.php"] [unique_id "WZq1Xm8AAQEAAFNJ-B4AAAAA"]

--a1b2c3d4-F--
HTTP/1.1 403 Forbidden
Content-Type: text/html
Connection: close

--a1b2c3d4-H--
ModSecurity: Warning. Access denied with code 403 (phase 2). Pattern match "(?i:(?:\\b(?:(?:s(?:elect\\b(?:.{1,100}?\\b(?:(?:length|count|top)\\b.{1,100}?\\bfrom|from\\b.{1,100}?\\bwhere)|.*?\\b(?:d(?:ump\\b.*\\bfrom|ata_type)|(?:to_(?:numbe|cha)|inst)r))|p_(?:(?:addextendedpro|sqlexe)c|(?:oacreat|prepar)e|execute(?:sql)?|makewebtask)|ql_(?:longvarchar|type)| ... [file "/etc/modsecurity/crs/rules/REQUEST-942-APPLICATION-ATTACK-SQLI.conf"] [line "64"] [id "942100"] [rev "2"] [msg "SQL Injection Attack Detected via libinjection"] [data "Matched Data: admin'-- found within ARGS:user"] [severity "CRITICAL"] [ver "OWASP_CRS/3.3.0"] [maturity "9"] [accuracy "8"] [tag "application-multi"] [tag "language-multi"] [tag "platform-multi"] [tag "attack-sqli"] [tag "OWASP_CRS"] [tag "OWASP_CRS/WEB_ATTACK/SQL_INJECTION"] [hostname "example.com"] [uri "/login.php"] [unique_id "WZq1Xm8AAQEAAFNJ-B4AAAAA"]

Monitoring Tools

  • SIEM Integration: Splunk, ELK Stack, QRadar
  • Log Analyzers: GoAccess, AWStats
  • Alerting Systems: Nagios, Zabbix
  • Dashboard Tools: Grafana, Kibana

ModSecurity in DevOps and CI/CD

  • Automated Testing: Integrate ModSecurity testing in CI pipelines
  • Rule Validation: Validate rules before deployment
  • Security Gates: Block deployments with security vulnerabilities
  • Infrastructure as Code: Manage ModSecurity configurations with IaC tools
  • Container Security: Deploy ModSecurity in containerized environments
  • Serverless Integration: Use ModSecurity with serverless architectures

Future of ModSecurity

  • AI-Powered Rules: Machine learning for adaptive security
  • Cloud-Native Integration: Better support for cloud environments
  • API-First Approach: Enhanced API security capabilities
  • Automated Rule Generation: AI-driven rule creation
  • Behavioral Analysis: Advanced user behavior monitoring
  • Zero Trust Integration: ModSecurity as part of zero trust architectures
  • Enhanced Performance: Optimized rule processing
  • Improved Usability: Better management interfaces

ModSecurity remains a powerful and flexible open-source solution for web application security, offering organizations the ability to implement robust WAF capabilities without the cost of commercial solutions.