ModSecurity
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
- Request Interception: Captures incoming HTTP requests
- Rule Processing: Applies security rules to the request
- Action Execution: Blocks, allows, or modifies requests based on rules
- Logging: Records security events and transaction details
- 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
- Phase 1: Request Headers - Inspect request headers before body processing
- Phase 2: Request Body - Inspect request body after it's received
- Phase 3: Response Headers - Inspect response headers before body processing
- Phase 4: Response Body - Inspect response body before sending to client
- 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
| Feature | ModSecurity | Commercial WAFs |
|---|---|---|
| Cost | Free (open-source) | Paid (licensing fees) |
| Support | Community-based | Vendor support |
| Ease of Use | Complex configuration | User-friendly interfaces |
| Rule Management | Manual rule creation | Pre-built rule sets |
| Performance | Depends on configuration | Optimized for performance |
| Integration | Requires manual setup | Pre-integrated with platforms |
| Updates | Community-driven | Vendor-provided |
| Features | Basic WAF functionality | Advanced 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.
Memory Corruption (Buffer Overflow, Heap Overflow)
Memory corruption vulnerabilities occur when programs improperly access or manipulate memory, leading to crashes, data leaks, or arbitrary code execution.
Multi-Factor Authentication (MFA)
Enhance security by requiring multiple verification methods to access accounts, protecting against unauthorized access and credential theft.
