Apache - mod_security

最後更新: 2015-09-1


mod_security =WAF - application firewall

HomePage: http://www.modsecurity.org/documentation/


  • 抵擋 SQL injection attacks, cross-site scripting, path traversal attacks
  • HTTP Denial of Service Protections
  • Detecting common web application security attack
  • Integration with AV Scanning for File Uploads
  • Tracking Sensitive Data - Tracks Credit Card usage and blocks leakages
  • Identification of Application Defects


  • Centos 6 Installation
  • Basic Configure
  • Disable "mod_security" Per Folder
  • Filter Setting
     - Body
     - PCRE library
     - Debug
     - AuditLog
     - SecRule
  • Variables
  • Security Model
  • Log Example
  • Five processing phases
  • mod_unique_id
  • Core ModSecurity Rule
  • Doc




C6 /C7

yum install mod_security





LoadModule security2_module modules/mod_security2.so

<IfModule !mod_unique_id.c>
    LoadModule unique_id_module modules/mod_unique_id.so

 * Make sure you have mod_unique_id installed. mod_unique_id is packaged with Apache httpd.


Include modsecurity.d/*.conf
Include modsecurity.d/activated_rules/*.conf


Basic Settings



<IfModule mod_security2.c>
    SecRuleEngine DetectionOnly
    SecRequestBodyAccess Off
    SecResponseBodyAccess Off

    SecPcreMatchLimit 1000
    SecPcreMatchLimitRecursion 1000
    SecTmpDir /var/lib/mod_security
    SecDataDir /var/lib/mod_security


SecPcreMatchLimit 1500                             # Default

Description: Sets the match limit in the PCRE library.

SecPcreMatchLimitRecursion 1500               # Default

Description: Sets the match limit recursion in the PCRE library.

SecTmpDir /var/lib/mod_security

As of ModSecurity version 3.0, SecTmpDir is no longer supported.

libModSecurity is able to deal with request body in a file or in a buffer (chunked or not).

(e.g. nginx 's client_body_buffer_size)

Supported on libModSecurity: No

SecDataDir /var/lib/mod_security

Description: Path where persistent data (e.g., IP address data, session data, and so on) is to be stored.

The directory to which the directive points must be writable by the web server user.

Supported on libModSecurity: No


Disable "mod_security" Per Folder


# For a particular directory:

<Directory "/var/www/wp-admin">
    <IfModule security2_module>
        SecRuleEngine Off


# Remove a particular rule

<LocationMatch "/wp-admin/update.php">
    <IfModule security2_module>
        SecRuleRemoveById 981173


Rule 入門





SecRule REQUEST_HEADERS:TEST "@eq 0" "id:8888,phase:1,log,deny,status:417"






multiple headers that have identical names

Apache: concatenated into a single header with a comma as the deliminator.


"TEST" 是不分有細階的


This variable is a collection of the names of all of the request headers.


SecRule REQUEST_HEADERS_NAMES "^x-forwarded-for" "log,deny,id:48,status:403,t:lowercase,msg:'Proxy Server Used'"


  • "@eq 0"
  • "^$"
  • ...



If no actions are provided, the default list will be used.

"SecRuleEngine On" 時 deny 才有效

不是所有 "status codes" 都可以用 ! ie. 488

417: Expectation Failed

The server cannot meet the requirements of the Expect request-header field.




Virtual Patching


* just-in-time patching

Fixing identified vulnerabilities in web applications always requires time.


Security Model


Negative Security Model - looks for known bad, malicious requests.

This method is effective at blocking a large number of automated attacks,

however it is not the best approach for identifying new attack vectors.

Using too many negative rules may also negatively impact performance.

Positive Security Model - When positive security model is deployed,

only requests that are known to be valid are accepted, with everything else rejected.

This approach works best with applications that are heavily used but rarely updated.

Virtual Patching - Its rule language makes ModSecurity an ideal external patching tool.

External patching is all about reducing the window of opportunity.

Time needed to patch application vulnerabilities often runs to weeks in many organizations.

With ModSecurity, applications can be patched from the outside, without touching the application source code (and even without any access to it),

making your systems secure until a proper patch is produced.

Extrusion Detection Model - ModSecurity can also monitor outbound data and identify and block information disclosure issues such as leaking detailed error messages or Social Security Numbers or Credit Card Numbers.


Rule Five processing phases



  • phase:1 request headers
  • phase:2 request body
  • phase:3 response headers
  • phase:4 response body
  • phase:5 logging

 * Keep in mind that rules are executed according to phases

 * The order of rules in the configuration file is important only within the rules of each phase.
    (so even if two rules are adjacent in a configuration file, but are set to execute in different phases)


  • XML support (parsing, validation, XPath).
  • Regular Expression back-references (allows one to create custom variables using transaction content).
  • Data persistence(feature to track IP addresses, application sessions, and application users)
  • Transaction variables. This can be used to store pieces of data, create a transaction anomaly score, and so on.




UNIQUE_ID is set to the identifier for each request.

This module provides a magic token for each request which is guaranteed to be unique across "all" requests under very specific conditions.

The UNIQUE_ID environment variable is constructed by

encoding the 144-bit (32-bit IP address, 32 bit pid, 32 bit time stamp, 16 bit counter, 32 bit thread index)

quadruple using the alphabet [A-Za-z0-9@-] in a manner similar to MIME base64 encoding, producing 24 characters.


Centos 6 Install Core ModSecurity Rule Set ver.2.2.9


Core Rule Set (CRS)

License: ASLv2


A set of generic attack detection rules for use with ModSecurity


mkdir /usr/src/coreruleset; cd /usr/src/coreruleset

wget https://github.com/coreruleset/coreruleset/archive/refs/tags/v3.3.2.zip

unzip v3.3.2.zip

cd coreruleset-3.3.2


由於 /etc/httpd/conf.d/mod_security.conf 有以下設定

<IfModule mod_security2.c>
    # ModSecurity Core Rules Set configuration
        Include modsecurity.d/*.conf
        Include modsecurity.d/activated_rules/*.conf

所以我們 copy 相應的 file 到指定目錄即可

cp modsecurity_crs_10_setup.conf.example /etc/httpd/modsecurity.d/modsecurity_crs_10_setup.conf

for f in `ls base_rules/` ; do cp base_rules/$f /etc/httpd/modsecurity.d/activated_rules/$f ; done

apache error log

... [notice] ModSecurity for Apache/2.7.3 (http://www.modsecurity.org/) configured.
... [notice] ModSecurity: APR compiled version="1.3.9"; loaded version="1.3.9"
... [notice] ModSecurity: PCRE compiled version="7.8 "; loaded version="7.8 2008-09-05"
... [notice] ModSecurity: LUA compiled version="Lua 5.1"
... [notice] ModSecurity: LIBXML compiled version="2.7.6"

Default Setting

SecRuleEngine On

# - To log to both the Apache error_log and ModSecurity audit_log file use: "log"
# - To log *only* to the ModSecurity audit_log file use: "nolog,auditlog"
# - To log *only* to the Apache error_log file use: "log,noauditlog"

SecDefaultAction "phase:1,deny,log"
SecDefaultAction "phase:2,deny,log"

The 49 inbound blocking and 59 outbound blocking rules files use the "block" action

For test

SecDefaultAction "phase:1,pass"
SecDefaultAction "phase:2,pass"



  $content = file_get_contents($_GET['path']);
  echo nl2br($content);



# 960017

[Thu Sep 17 16:36:32 2015] [error] [client] ModSecurity: Access denied with code 403 (phase 2). Pattern match "^[\\\\d.:]+$" at REQUEST_HEADERS:Host. [file "/etc/httpd/modsecurity.d/activated_rules/modsecurity_crs_21_protocol_anomalies.conf"] [line "98"] [id "960017"] [rev "2"] [msg "Host header is a numeric IP address"] [data ""] [severity "WARNING"] [ver "OWASP_CRS/2.2.9"] [maturity "9"] [accuracy "9"] [tag "OWASP_CRS/PROTOCOL_VIOLATION/IP_HOST"] [tag "WASCTC/WASC-21"] [tag "OWASP_TOP_10/A7"] [tag "PCI/6.5.10"] [tag "http://technet.microsoft.com/en-us/magazine/2005.01.hackerbasher.aspx"] [hostname ""] [uri "/test.php"] [unique_id "Vfp7kMCoWLcAAAYuBhQAAAAD"]

# 960024

[Thu Sep 17 16:44:19 2015] [error] [client] ModSecurity: Access denied with code 403 (phase 2). Pattern match "\\\\W{4,}" at ARGS:path. [file "/etc/httpd/modsecurity.d/activated_rules/modsecurity_crs_40_generic_attacks.conf"] [line "37"] [id "960024"] [rev "2"] [msg "Meta-Character Anomaly Detection Alert - Repetative Non-Word Characters"] [data "Matched Data: ../../../../ found within ARGS:path: ../../../../etc/passwd"] [ver "OWASP_CRS/2.2.9"] [maturity "9"] [accuracy "8"] [hostname "test.loc"] [uri "/"] [unique_id "Vfp9Y8CoWLcAAAZMA5gAAAAH"]