How to Setup ModSecurity on Apache2

A comprehensive guide to configuring ModSecurity Web Application Firewall (WAF) in Apache2 for enhanced security.

Prerequisites

Before configuring ModSecurity on Apache2, ensure you have:

  • Apache2 installed and running
  • Root or sudo access to the server
  • Basic understanding of web security concepts
  • Required modules enabled (mod_security2, mod_unique_id)

Installation

Installation Steps
# For Ubuntu/Debian
sudo apt-get update
sudo apt-get install libapache2-mod-security2

# For CentOS/RHEL
sudo yum install mod_security

# Enable the module
sudo a2enmod security2
sudo systemctl restart apache2

Basic Configuration

Core Configuration
# /etc/apache2/mods-available/security2.conf
SecRuleEngine On
SecRequestBodyAccess On
SecResponseBodyAccess On
SecRequestBodyLimit 13107200
SecRequestBodyNoFilesLimit 131072
SecRequestBodyInMemoryLimit 131072
SecRequestBodyLimitAction Reject
SecRule REQUEST_HEADERS:Content-Type "text/xml" \
     "id:'200000',phase:1,t:none,t:lowercase,pass,nolog,ctl:requestBodyProcessor=XML"

Key directives explained:

  • SecRuleEngine: Controls the WAF engine (On/Off/DetectionOnly)
  • SecRequestBodyAccess: Enables request body inspection
  • SecRequestBodyLimit: Maximum request body size
  • SecRule: Defines security rules

Rule Sets

OWASP Core Rule Set
# Download OWASP CRS
cd /etc/apache2/
sudo git clone https://github.com/coreruleset/coreruleset.git

# Include in Apache configuration
Include /etc/apache2/coreruleset/crs-setup.conf
Include /etc/apache2/coreruleset/rules/*.conf

Common rule categories:

  • SQL Injection Protection
  • Cross-Site Scripting (XSS)
  • Remote Code Execution
  • File Upload Protection
  • HTTP Protocol Violations

Configuration Generator

Generated Configuration
# ModSecurity configuration will appear here

Best Practices

Recommended Practices
  • Initial Setup:
    • Start in DetectionOnly mode to monitor impact
    • Gradually enable blocking rules
    • Regularly update rule sets
  • Rule Management:
    • Customize rules for your application
    • Maintain a whitelist of false positives
    • Document custom rules and exceptions
  • Monitoring:
    • Regularly review audit logs
    • Set up alerts for critical events
    • Monitor performance impact
  • Maintenance:
    • Keep ModSecurity and rules updated
    • Regular security assessments
    • Backup configurations before changes