Creating split version of Reference Manual

Martin Vierula
2022-09-01 07:18:06 -07:00
parent 3366f707bf
commit 854023958e
6 changed files with 4299 additions and 0 deletions

@@ -0,0 +1,869 @@
= ModSecurity® Reference Manual =
== Current as of v2.6 v2.7 v2.8 v2.9 v3.0 ==
=== Copyright © 2004-2022 [https://www.trustwave.com/ Trustwave Holdings, Inc.] ===
= Actions =
Each action belongs to one of five groups:
*'''Disruptive actions''' - Cause ModSecurity to do something. In many cases something means block transaction, but not in all. For example, the allow action is classified as a disruptive action, but it does the opposite of blocking. There can only be one disruptive action per rule (if there are multiple disruptive actions present, or inherited, only the last one will take effect), or rule chain (in a chain, a disruptive action can only appear in the first rule).
; Note : '''Disruptive actions will NOT be executed if the SecRuleEngine is set to DetectionOnly'''. If you are creating exception/whitelisting rules that use the allow action, you should also add the ctl:ruleEngine=On action to execute the action.
* '''Non-disruptive action'''s - Do something, but that something does not and cannot affect the rule processing flow. Setting a variable, or changing its value is an example of a non-disruptive action. Non-disruptive action can appear in any rule, including each rule belonging to a chain.
* '''Flow actions''' - These actions affect the rule flow (for example skip or skipAfter).
* '''Meta-data actions''' - Meta-data actions are used to provide more information about rules. Examples include id, rev, severity and msg.
* '''Data actions''' - Not really actions, these are mere containers that hold data used by other actions. For example, the status action holds the status that will be used for blocking (if it takes place).
== accuracy ==
'''Description:''' Specifies the relative accuracy level of the rule related to false positives/negatives. The value is a string based on a numeric scale (1-9 where 9 is very strong and 1 has many false positives).
'''Action Group:''' Meta-data
'''Version:''' 2.7
'''Example:'''
<pre>
SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/* "\bgetparentfolder\b" \
"phase:2,ver:'CRS/2.2.4,accuracy:'9',maturity:'9',capture,t:none,t:htmlEntityDecode,t:compressWhiteSpace,t:lowercase,ctl:auditLogParts=+E,block,msg:'Cross-site Scripting (XSS) Attack',id:'958016',tag:'WEB_ATTACK/XSS',tag:'WASCTC/WASC-8',tag:'WASCTC/WASC-22',tag:'OWASP_TOP_10/A2',tag:'OWASP_AppSensor/IE1',tag:'PCI/6.5.1',logdata:'% \
{TX.0}',severity:'2',setvar:'tx.msg=%{rule.msg}',setvar:tx.xss_score=+%{tx.critical_anomaly_score},setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},setvar:tx.%{rule.id}-WEB_ATTACK/XSS-%{matched_var_name}=%{tx.0}"
</pre>
== allow ==
'''Description:''' Stops rule processing on a successful match and allows the transaction to proceed.
'''Action Group:''' Disruptive
Example:
<pre>
# Allow unrestricted access from 192.168.1.100
SecRule REMOTE_ADDR "^192\.168\.1\.100$" phase:1,id:95,nolog,allow
</pre>
Prior to ModSecurity 2.5 the allow action would only affect the current phase. An allow in phase 1 would skip processing the remaining rules in phase 1 but the rules from phase 2 would execute. Starting with v2.5.0 allow was enhanced to allow for fine-grained control of what is done. The following rules now apply:
#If used one its own, like in the example above, allow will affect the entire transaction, stopping processing of the current phase but also skipping over all other phases apart from the logging phase. (The logging phase is special; it is designed to always execute.)
#If used with parameter "phase", allow will cause the engine to stop processing the current phase. Other phases will continue as normal.
#If used with parameter "request", allow will cause the engine to stop processing the current phase. The next phase to be processed will be phase RESPONSE_HEADERS.
Examples:
<pre>
# Do not process request but process response.
SecAction phase:1,allow:request,id:96
# Do not process transaction (request and response).
SecAction phase:1,allow,id:97
</pre>
If you want to allow a response through, put a rule in phase RESPONSE_HEADERS and simply use allow on its own:
<pre>
# Allow response through.
SecAction phase:3,allow,id:98
</pre>
== append ==
'''Description''': Appends text given as parameter to the end of response body. Content injection must be en- abled (using the SecContentInjection directive). No content type checks are made, which means that before using any of the content injection actions, you must check whether the content type of the response is adequate for injection.
'''Version:''' 2.x-2.9.x
'''Supported on libModSecurity:''' No
'''Action Group:''' Non-disruptive
'''Processing Phases:''' 3 and 4.
Example:
<pre>SecRule RESPONSE_CONTENT_TYPE "^text/html" "nolog,id:99,pass,append:'<hr>Footer'"</pre>
; Warning : Although macro expansion is allowed in the additional content, you are strongly cau- tioned against inserting user-defined data fields into output. Doing so would create a cross-site scripting vulnerability.
== auditlog ==
'''Description:''' Marks the transaction for logging in the audit log.
'''Action Group''': Non-disruptive
Example:
<code>SecRule REMOTE_ADDR "^192\.168\.1\.100$" auditlog,phase:1,id:100,allow</code>
; Note : The auditlog action is now explicit if log is already specified.
== block ==
'''Description:''' Performs the disruptive action defined by the previous SecDefaultAction.
'''Action Group:''' Disruptive
This action is essentially a placeholder that is intended to be used by rule writers to request a blocking action, but without specifying how the blocking is to be done. The idea is that such decisions are best left to rule users, as well as to allow users, to override blocking if they so desire.
In future versions of ModSecurity, more control and functionality will be added to define "how" to block.
Examples:
<pre>
# Specify how blocking is to be done
SecDefaultAction phase:2,deny,id:101,status:403,log,auditlog
# Detect attacks where we want to block
SecRule ARGS attack1 phase:2,block,id:102
# Detect attacks where we want only to warn
SecRule ARGS attack2 phase:2,pass,id:103
</pre>
It is possible to use the SecRuleUpdateActionById directive to override how a rule handles blocking. This is useful in three cases:
#If a rule has blocking hard-coded, and you want it to use the policy you determine
#If a rule was written to block, but you want it to only warn
#If a rule was written to only warn, but you want it to block
The following example demonstrates the first case, in which the hard-coded block is removed in favor of the user-controllable block:
<pre>
# Specify how blocking is to be done
SecDefaultAction phase:2,deny,status:403,log,auditlog,id:104
# Detect attacks and block
SecRule ARGS attack1 phase:2,id:1,deny
# Change how rule ID 1 blocks
SecRuleUpdateActionById 1 block
</pre>
== capture ==
'''Description:''' When used together with the regular expression operator (@rx), the capture action will create copies of the regular expression captures and place them into the transaction variable collection.
'''Action Group:''' Non-disruptive
Example:
<pre>
SecRule REQUEST_BODY "^username=(\w{25,})" phase:2,capture,t:none,chain,id:105
SecRule TX:1 "(?:(?:a(dmin|nonymous)))"
</pre>
Up to 10 captures will be copied on a successful pattern match, each with a name consisting of a digit from 0 to 9. The TX.0 variable always contains the entire area that the regular expression matched. All the other variables contain the captured values, in the order in which the capturing parentheses appear in the regular expression.
== chain ==
'''Description:''' Chains the current rule with the rule that immediately follows it, creating a rule chain. Chained rules allow for more complex processing logic.
'''Action Group:''' Flow
Example:
<pre>
# Refuse to accept POST requests that do not contain Content-Length header.
# (Do note that this rule should be preceded by a rule
# that verifies only valid request methods are used.)
SecRule REQUEST_METHOD "^POST$" phase:1,chain,t:none,id:105
SecRule &REQUEST_HEADERS:Content-Length "@eq 0" t:none
</pre>
; Note : Rule chains allow you to simulate logical AND. The disruptive actions specified in the first portion of the chained rule will be triggered only if all of the variable checks return positive hits. If any one aspect of a chained rule comes back negative, then the entire rule chain will fail to match. Also note that disruptive actions, execution phases, metadata actions (id, rev, msg, tag, severity, logdata), skip, and skipAfter actions can be specified only by the chain starter rule.
The following directives can be used in rule chains:
*SecAction
*SecRule
*SecRuleScript
Special rules control the usage of actions in chained rules:
*Any actions that affect the rule flow (i.e., the disruptive actions, skip and skipAfter) can be used only in the chain starter. They will be executed only if the entire chain matches.
*Non-disruptive rules can be used in any rule; they will be executed if the rule that contains them matches and not only when the entire chain matches.
*The metadata actions (e.g., id, rev, msg) can be used only in the chain starter.
== ctl ==
'''Description''': Changes ModSecurity configuration on transient, per-transaction basis. Any changes made using this action will affect only the transaction in which the action is executed. The default configuration, as well as the other transactions running in parallel, will be unaffected.
'''Action Group:''' Non-disruptive
'''Example:'''
<pre>
# Parse requests with Content-Type "text/xml" as XML
SecRule REQUEST_CONTENT_TYPE ^text/xml "nolog,pass,id:106,ctl:requestBodyProcessor=XML"
# white-list the user parameter for rule #981260 when the REQUEST_URI is /index.php
SecRule REQUEST_URI "@beginsWith /index.php" "phase:1,t:none,pass, \
nolog,ctl:ruleRemoveTargetById=981260;ARGS:user
</pre>
The following configuration options are supported:
#'''auditEngine'''
#'''auditLogParts'''
#'''debugLogLevel''' (Supported on libModSecurity: TBI)
#'''forceRequestBodyVariable'''
#'''requestBodyAccess'''
#'''requestBodyLimit''' (Supported on libModSecurity: TBI)
#'''requestBodyProcessor'''
#'''responseBodyAccess''' (Supported on libModSecurity: TBI)
#'''responseBodyLimit''' (Supported on libModSecurity: TBI)
#'''ruleEngine'''
#'''ruleRemoveById''' - since this action us triggered at run time, it should be specified '''before''' the rule in which it is disabling.
#'''ruleRemoveByMsg''' (Supported on libModSecurity: TBI)
#'''ruleRemoveByTag''' (Supported on libModSecurity: TBI)
#'''ruleRemoveTargetById''' - since this action is used to just remove targets, users don't need to use the char ! before the target list.
#'''ruleRemoveTargetByMsg''' - since this action is used to just remove targets, users don't need to use the char ! before the target list. (Supported on libModSecurity: TBI)
#'''ruleRemoveTargetByTag''' - since this action is used to just remove targets, users don't need to use the char ! before the target list.
#'''hashEngine''' (Supported on libModSecurity: TBI)
#'''hashEnforcement''' (Supported on libModSecurity: TBI)
With the exception of the requestBodyProcessor and forceRequestBodyVariable settings, each configuration option corresponds to one configuration directive and the usage is identical.
The requestBodyProcessor option allows you to configure the request body processor. By default, ModSecurity will use the URLENCODED and MULTIPART processors to process an application/x-www-form-urlencoded and a multipart/form-data body, respectively. Other two processors are also supported: JSON and XML, but they are never used implicitly. Instead, you must tell ModSecurity to use it by placing a few rules in the REQUEST_HEADERS processing phase. After the request body is processed as XML, you will be able to use the XML-related features to inspect it.
Request body processors will not interrupt a transaction if an error occurs during parsing. Instead, they will set the variables REQBODY_PROCESSOR_ERROR and REQBODY_PROCESSOR_ERROR_MSG. These variables should be inspected in the REQUEST_BODY phase and an appropriate action taken.
The forceRequestBodyVariable option allows you to configure the REQUEST_BODY variable to be set when there is no request body processor configured. This allows for inspection of request bodies of unknown types.
; Note : There was a ctl:ruleUpdateTargetById introduced in 2.6.0 and removed from the code in 2.7.0. JSON was added as part of v2.8.0-rc1
== deny ==
'''Description:''' Stops rule processing and intercepts transaction.
'''Action Group:''' Disruptive
Example:
<code>SecRule REQUEST_HEADERS:User-Agent "nikto" "log,deny,id:107,msg:'Nikto Scanners Identified'"</code>
== deprecatevar ==
'''Description''': Decrements numerical value over time, which makes sense only applied to the variables stored in persistent storage.
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
'''Action Group:''' Non-Disruptive
Example: The following example will decrement the counter by 60 every 300 seconds.
<pre>
SecAction phase:5,id:108,nolog,pass,deprecatevar:SESSION.score=60/300
</pre>
Counter values are always positive, meaning that the value will never go below zero. Unlike expirevar, the deprecate action must be executed on every request.
== drop ==
'''Description:''' Initiates an immediate close of the TCP connection by sending a FIN packet.
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
'''Action Group:''' Disruptive
'''Example:''' The following example initiates an IP collection for tracking Basic Authentication attempts. If the client goes over the threshold of more than 25 attempts in 2 minutes, it will DROP subsequent connections.
<pre>
SecAction phase:1,id:109,initcol:ip=%{REMOTE_ADDR},nolog
SecRule ARGS:login "!^$" "nolog,phase:1,id:110,setvar:ip.auth_attempt=+1,deprecatevar:ip.auth_attempt=25/120"
SecRule IP:AUTH_ATTEMPT "@gt 25" "log,drop,phase:1,id:111,msg:'Possible Brute Force Attack'"
</pre>
; Note : This action is currently not available on Windows based builds.
This action is extremely useful when responding to both Brute Force and Denial of Service attacks in that, in both cases, you want to minimize both the network bandwidth and the data returned to the client. This action causes error message to appear in the log "(9)Bad file descriptor: core_output_filter: writing data to the network"
== exec ==
'''Description:''' Executes an external script/binary supplied as parameter. As of v2.5.0, if the parameter supplied to exec is a Lua script (detected by the .lua extension) the script will be processed internally. This means you will get direct access to the internal request context from the script. Please read the SecRuleScript documentation for more details on how to write Lua scripts.
'''Action Group:''' Non-disruptive
'''Version:''' 2.x
'''Supported on libModSecurity:''' YES
'''Example:'''
<pre>
# Run external program on rule match
SecRule REQUEST_URI "^/cgi-bin/script\.pl" "phase:2,id:112,t:none,t:lowercase,t:normalizePath,block,\ exec:/usr/local/apache/bin/test.sh"
# Run Lua script on rule match
SecRule ARGS:p attack "phase:2,id:113,block,exec:/usr/local/apache/conf/exec.lua"
</pre>
The exec action is executed independently from any disruptive actions specified. External scripts will always be called with no parameters. Some transaction information will be placed in environment variables. All the usual CGI environment variables will be there. You should be aware that forking a threaded process results in all threads being replicated in the new process. Forking can therefore incur larger overhead in a multithreaded deployment. The script you execute must write something (anything) to stdout; if it doesnt, ModSecurity will assume that the script failed, and will record the failure.
== expirevar ==
'''Description:''' Configures a collection variable to expire after the given time period (in seconds).
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
'''Action Group:''' Non-disruptive
'''Example:'''
<pre>
SecRule REQUEST_COOKIES:JSESSIONID "!^$" "nolog,phase:1,id:114,pass,setsid:%{REQUEST_COOKIES:JSESSIONID}"
SecRule REQUEST_URI "^/cgi-bin/script\.pl" "phase:2,id:115,t:none,t:lowercase,t:normalizePath,log,allow,setvar:session.suspicious=1,expirevar:session.suspicious=3600,phase:1"
</pre>
You should use the expirevar actions at the same time that you use setvar actions in order to keep the intended expiration time. If they are used on their own (perhaps in a SecAction directive), the expire time will be reset.
== id ==
'''Description''': Assigns a unique ID to the rule or chain in which it appears. Starting with ModSecurity 2.7 this action is mandatory and must be numeric.
'''Action Group:''' Meta-data
'''Example:'''
<pre>
SecRule &REQUEST_HEADERS:Host "@eq 0" "log,id:60008,severity:2,msg:'Request Missing a Host Header'"
</pre>
; Note : The id action is required for all SecRule/SecAction directives as of v2.7.0
These are the reserved ranges:
*199,999: reserved for local (internal) use. Use as you see fit, but do not use this range for rules that are distributed to others
*100,000199,999: reserved for rules published by Oracle
*200,000299,999: reserved for rules published Comodo
*300,000399,999: reserved for rules published at gotroot.com
*400,000419,999: unused (available for reservation)
*420,000429,999: reserved for ScallyWhack [http://projects.otaku42.de/wiki/Scally-Whack]
*430,000439,999: reserved for rules published by Flameeyes [http://www.flameeyes.eu/projects/modsec]
*440.000-599,999: unused (available for reservation)
*600,000-699,999: reserved for use by Akamai [http://www.akamai.com/html/solutions/waf.html]
*700,000799,999: reserved for Ivan Ristic
*900,000999,999: reserved for the OWASP ModSecurity Core Rule Set [http://www.owasp.org/index.php/Category:OWASP_ModSecurity_Core_Rule_Set_Project] project
*1,000,000-1,009,999: reserved for rules published by Redhat Security Team
*1,010,000-1,999,999: reserved for WAF | Web Application Firewall and Load Balancer Security (kemptechnologies.com) [https://kemptechnologies.com/solutions/waf/]
*2,000,000-2,999,999: reserved for rules from Trustwave's SpiderLabs Research team
*3,000,000-3,999,999: reserved for use by Akamai [http://www.akamai.com/html/solutions/waf.html]
*4,000,000-4,099,999 reserved: in use by AviNetworks [https://kb.avinetworks.com/docs/latest/vantage-web-app-firewall-beta/]
*4,100,000-4,199,999 reserved: in use by Fastly [https://www.fastly.com/products/cloud-security/#products-cloud-security-web-application-firewall]
*4,200,000-4,299,999 reserved: in use by CMS-Garden [https://www.cms-garden.org/en]
*4,300,000-4,300,999 reserved: in use by Ensim.hu [http://ensim.hu/]
*4,301,000-19,999,999: unused (available for reservation)
*20,000,000-21,999,999: reserved for rules from Trustwave's SpiderLabs Research team
*22,000,000-69,999,999: unused (available for reservation)
*77,000,000-77,999,999 - reserved: in use by Imunify360 - production rules
*88,000,000-88,999,999 - reserved: in use by Imunify360 - beta users
*99,000,000-99,099,999 reserved for use by Microsoft https://azure.microsoft.com/en-us/services/web-application-firewall/
*99,100,000-99,199,999 reserved for use by WPScan/Jetpack
== initcol ==
'''Description:''' Initializes a named persistent collection, either by loading data from storage or by creating a new collection in memory.
'''Action Group:''' Non-disruptive
'''Example:''' The following example initiates IP address tracking, which is best done in phase 1:
<pre>
SecAction phase:1,id:116,nolog,pass,initcol:ip=%{REMOTE_ADDR}
</pre>
Collections are loaded into memory on-demand, when the initcol action is executed. A collection will be persisted only if a change was made to it in the course of transaction processing.
See the "Persistent Storage" section for further details.
== log ==
'''Description:''' Indicates that a successful match of the rule needs to be logged.
'''Action Group:''' Non-disruptive
'''Example:'''
<pre>
SecAction phase:1,id:117,pass,initcol:ip=%{REMOTE_ADDR},log
</pre>
This action will log matches to the Apache error log file and the ModSecurity audit log.
== logdata ==
'''Description:''' Logs a data fragment as part of the alert message.
'''Action Group:''' Non-disruptive
'''Example:'''
<pre>
SecRule ARGS:p "@rx <script>" "phase:2,id:118,log,pass,logdata:%{MATCHED_VAR}"
</pre>
The logdata information appears in the error and/or audit log files. Macro expansion is performed, so you may use variable names such as %{TX.0} or %{MATCHED_VAR}. The information is properly escaped for use with logging of binary data.
== maturity ==
'''Description:''' Specifies the relative maturity level of the rule related to the length of time a rule has been public and the amount of testing it has received. The value is a string based on a numeric scale (1-9 where 9 is extensively tested and 1 is a brand new experimental rule).
'''Action Group:''' Meta-data
'''Version:''' 2.7
'''Example:'''
<pre>
SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/* "\bgetparentfolder\b" \
"phase:2,ver:'CRS/2.2.4,accuracy:'9',maturity:'9',capture,t:none,t:htmlEntityDecode,t:compressWhiteSpace,t:lowercase,ctl:auditLogParts=+E,block,msg:'Cross-site Scripting (XSS) Attack',id:'958016',tag:'WEB_ATTACK/XSS',tag:'WASCTC/WASC-8',tag:'WASCTC/WASC-22',tag:'OWASP_TOP_10/A2',tag:'OWASP_AppSensor/IE1',tag:'PCI/6.5.1',logdata:'% \
{TX.0}',severity:'2',setvar:'tx.msg=%{rule.msg}',setvar:tx.xss_score=+%{tx.critical_anomaly_score},setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},setvar:tx.%{rule.id}-WEB_ATTACK/XSS-%{matched_var_name}=%{tx.0}"
</pre>
== msg ==
'''Description:''' Assigns a custom message to the rule or chain in which it appears. The message will be logged along with every alert.
'''Action Group:''' Meta-data
'''Example:'''
<pre>
SecRule &REQUEST_HEADERS:Host "@eq 0" "log,id:60008,severity:2,msg:'Request Missing a Host Header'"
</pre>
; Note : The msg information appears in the error and/or audit log files and is not sent back to the client in response headers.
== multiMatch ==
'''Description:''' If enabled, ModSecurity will perform multiple operator invocations for every target, before and after every anti-evasion transformation is performed.
'''Action Group:''' Non-disruptive
'''Example:'''
<pre>
SecRule ARGS "attack" "phase1,log,deny,id:119,t:removeNulls,t:lowercase,multiMatch"
</pre>
Normally, variables are inspected only once per rule, and only after all transformation functions have been completed. With multiMatch, variables are checked against the operator before and after every transformation function that changes the input.
== noauditlog ==
'''Description:''' Indicates that a successful match of the rule should not be used as criteria to determine whether the transaction should be logged to the audit log.
'''Action Group:''' Non-disruptive
'''Example:'''
<pre>
SecRule REQUEST_HEADERS:User-Agent "Test" allow,noauditlog,id:120
</pre>
If the SecAuditEngine is set to On, all of the transactions will be logged. If it is set to RelevantOnly, then you can control the logging with the noauditlog action.
The noauditlog action affects only the current rule. If you prevent audit logging in one rule only, a match in another rule will still cause audit logging to take place. If you want to prevent audit logging from taking place, regardless of whether any rule matches, use ctl:auditEngine=Off.
== nolog ==
'''Description:''' Prevents rule matches from appearing in both the error and audit logs.
'''Action Group:''' Non-disruptive
'''Example:'''
<pre>
SecRule REQUEST_HEADERS:User-Agent "Test" allow,nolog,id:121
</pre>
Although nolog implies noauditlog, you can override the former by using nolog,auditlog.
== pass ==
'''Description:''' Continues processing with the next rule in spite of a successful match.
'''Action Group:''' Disruptive
'''Example:'''
<pre>
SecRule REQUEST_HEADERS:User-Agent "Test" "log,pass,id:122"
</pre>
When using pass with a SecRule with multiple targets, all variables will be inspected and all non-disruptive actions trigger for every match. In the following example, the TX.test variable will be incremented once for every request parameter:
<pre>
# Set TX.test to zero
SecAction "phase:2,nolog,pass,setvar:TX.test=0,id:123"
# Increment TX.test for every request parameter
SecRule ARGS "test" "phase:2,log,pass,setvar:TX.test=+1,id:124"
</pre>
== pause ==
'''Description:''' Pauses transaction processing for the specified number of milliseconds. Starting with ModSecurity 2.7 this feature also supports macro expansion.
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
'''Action Group:''' Disruptive
'''Example:'''
<pre>
SecRule REQUEST_HEADERS:User-Agent "Test" "log,pause:5000,id:125"
</pre>
; Warning : This feature can be of limited benefit for slowing down brute force authentication attacks, but use with care. If you are under a denial of service attack, the pause feature may make matters worse, as it will cause an entire Apache worker (process or thread, depending on the deployment mode) to sit idle until the pause is completed.
== phase ==
'''Description''': Places the rule or chain into one of five available processing phases. It can also be used in SecDefaultAction to establish the rule defaults.
'''Action Group:''' Meta-data
'''Example:'''
<pre>
# Initialize IP address tracking in phase 1
SecAction phase:1,nolog,pass,id:126,initcol:IP=%{REMOTE_ADDR}
</pre>
Starting in ModSecurity version v2.7 there are aliases for some phase numbers:
*'''2 - request'''
*'''4 - response'''
*'''5 - logging'''
'''Example:'''
<pre>
SecRule REQUEST_HEADERS:User-Agent "Test" "phase:request,log,deny,id:127"
</pre>
; Warning : Keep in mind that if you specify the incorrect phase, the variable used in the rule may not yet be available. This could lead to a false negative situation where your variable and operator may be correct, but it misses malicious data because you specified the wrong phase.
== prepend ==
'''Description:''' Prepends the text given as parameter to response body. Content injection must be enabled (using the SecContentInjection directive). No content type checks are made, which means that before using any of the content injection actions, you must check whether the content type of the response is adequate for injection.
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
'''Action Group:''' Non-disruptive
'''Processing Phases:''' 3 and 4.
'''Example:'''
<pre>
SecRule RESPONSE_CONTENT_TYPE ^text/html \ "phase:3,nolog,pass,id:128,prepend:'Header<br>'"
</pre>
; Warning : Although macro expansion is allowed in the injected content, you are strongly cautioned against inserting user defined data fields int output. Doing so would create a cross-site scripting vulnerability.
== proxy ==
'''Description:''' Intercepts the current transaction by forwarding the request to another web server using the proxy backend. The forwarding is carried out transparently to the HTTP client (i.e., theres no external redirection taking place).
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
'''Action Group:''' Disruptive
'''Example:'''
<pre>
SecRule REQUEST_HEADERS:User-Agent "Test" log,id:129,proxy:http://honeypothost/
SecRule REQUEST_URI "@streq /test.txt" "phase:1,proxy:'[nocanon]http://$ENV{SERVER_NAME}:$ENV{SERVER_PORT}/test.txt',id:500005"
</pre>
For this action to work, mod_proxy must also be installed. This action is useful if you would like to proxy matching requests onto a honeypot web server, and especially in combination with IP address or session tracking.
; Note: As of v2.9.1 the proxy action can receive a special parameter named "[nocanon]". The "[nocanon]" parameter will make the url to be delivered to the backend on its original format (raw). Further information about "nocanon" is available here: https://httpd.apache.org/docs/2.2/pt-br/mod/mod_proxy.html.
== redirect ==
'''Description:''' Intercepts transaction by issuing an external (client-visible) redirection to the given location..
'''Action Group:''' Disruptive
'''Example:'''
<pre>
SecRule REQUEST_HEADERS:User-Agent "Test" "phase:1,id:130,log,redirect:http://www.example.com/failed.html"
</pre>
If the status action is present on the same rule, and its value can be used for a redirection (i.e., is one of the following: 301, 302, 303, or 307), the value will be used for the redirection status code. Otherwise, status code 302 will be used.
== rev ==
'''Description:''' Specifies rule revision. It is useful in combination with the id action to provide an indication that a rule has been changed.
'''Action Group:''' Meta-data
'''Example:'''
<pre>
SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/* "(?:(?:[\;\|\`]\W*?\bcc|\b(wget|curl))\b|\/cc(?:[\'\"\|\;\`\-\s]|$))" \
"phase:2,rev:'2.1.3',capture,t:none,t:normalizePath,t:lowercase,ctl:auditLogParts=+E,block,msg:'System Command Injection',id:'950907',tag:'WEB_ATTACK/COMMAND_INJECTION',tag:'WASCTC/WASC-31',tag:'OWASP_TOP_10/A1',tag:'PCI/6.5.2',logdata:'%{TX.0}',severity:'2',setvar:'tx.msg=%{rule.msg}',setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},setvar:tx.command_injection_score=+%{tx.critical_anomaly_score},setvar:tx.%{rule.id}-WEB_ATTACK/COMMAND_INJECTION-%{matched_var_name}=%{tx.0},skipAfter:END_COMMAND_INJECTION1"
</pre>
; Note : This action is used in combination with the id action to allow the same rule ID to be used after changes take place but to still provide some indication the rule changed.
== sanitiseArg ==
'''Description:''' Prevents sensitive request parameter data from being logged to audit log. Each byte of the named parameter(s) is replaced with an asterisk.
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
'''Action Group:''' Non-disruptive
'''Example:'''
<pre>
# Never log passwords
SecAction "nolog,phase:2,id:131,sanitiseArg:password,sanitiseArg:newPassword,sanitiseArg:oldPassword"
</pre>
; Note : The sanitize actions affect only the data as it is logged to audit log. High-level debug logs may contain sensitive data. Apache access log may contain sensitive data placed in the request URI.
== sanitiseMatched ==
'''Description:''' Prevents the matched variable (request argument, request header, or response header) from being logged to audit log. Each byte of the named parameter(s) is replaced with an asterisk.
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
'''Action Group:''' Non-disruptive
'''Example:''' This action can be used to sanitise arbitrary transaction elements when they match a condition. For example, the example below will sanitise any argument that contains the word password in the name.
<pre>
SecRule ARGS_NAMES password nolog,pass,id:132,sanitiseMatched
</pre>
; Note : The sanitize actions affect only the data as it is logged to audit log. High-level debug logs may contain sensitive data. Apache access log may contain sensitive data placed in the request URI.
== sanitiseMatchedBytes ==
'''Description:''' Prevents the matched string in a variable from being logged to audit log. Each or a range of bytes of the named parameter(s) is replaced with an asterisk.
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
'''Action Group:''' Non-disruptive
'''Example:''' This action can be used to sanitise arbitrary transaction elements when they match a condition. For example, the example below will sanitise the credit card number.
*sanitiseMatchedBytes -- This would x out only the bytes that matched.
*sanitiseMatchedBytes:1/4 -- This would x out the bytes that matched, but keep the first byte and last 4 bytes
<pre>
# Detect credit card numbers in parameters and
# prevent them from being logged to audit log
SecRule ARGS "@verifyCC \d{13,16}" "phase:2,id:133,nolog,capture,pass,msg:'Potential credit card number in request',sanitiseMatchedBytes"
SecRule RESPONSE_BODY "@verifyCC \d{13,16}" "phase:4,id:134,t:none,log,capture,block,msg:'Potential credit card number is response body',sanitiseMatchedBytes:0/4"
</pre>
; Note : The sanitize actions affect only the data as it is logged to audit log. High-level debug logs may contain sensitive data. Apache access log may contain sensitive data placed in the request URI. You must use capture action with sanitiseMatchedBytes, so the operator must support capture action. ie: @rx, @verifyCC.
== sanitiseRequestHeader ==
'''Description:''' Prevents a named request header from being logged to audit log. Each byte of the named request header is replaced with an asterisk..
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
'''Action Group:''' Non-disruptive
'''Example:''' This will sanitise the data in the Authorization header.
<pre>
SecAction "phase:1,nolog,pass,id:135,sanitiseRequestHeader:Authorization"
</pre>
; Note : The sanitize actions affect only the data as it is logged to audit log. High-level debug logs may contain sensitive data. Apache access log may contain sensitive data placed in the request URI.
== sanitiseResponseHeader ==
'''Description:''' Prevents a named response header from being logged to audit log. Each byte of the named response header is replaced with an asterisk.
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
'''Action Group:''' Non-disruptive
'''Example:''' This will sanitise the Set-Cookie data sent to the client.
<pre>
SecAction "phase:3,nolog,pass,id:136,sanitiseResponseHeader:Set-Cookie"
</pre>
; Note : The sanitize actions affect only the data as it is logged to audit log. High-level debug logs may contain sensitive data. Apache access log may contain sensitive data placed in the request URI.
== severity ==
'''Description:''' Assigns severity to the rule in which it is used.
'''Action Group:''' Meta-data
'''Example:'''
<pre>
SecRule REQUEST_METHOD "^PUT$" "id:340002,rev:1,severity:CRITICAL,msg:'Restricted HTTP function'"
</pre>
Severity values in ModSecurity follows the numeric scale of syslog (where 0 is the most severe). The data below is used by the OWASP ModSecurity Core Rule Set (CRS):
*'''0 - EMERGENCY''': is generated from correlation of anomaly scoring data where there is an inbound attack and an outbound leakage.
*'''1 - ALERT''': is generated from correlation where there is an inbound attack and an outbound application level error.
*'''2 - CRITICAL''': Anomaly Score of 5. Is the highest severity level possible without correlation. It is normally generated by the web attack rules (40 level files).
*'''3 - ERROR''': Error - Anomaly Score of 4. Is generated mostly from outbound leakage rules (50 level files).
*'''4 - WARNING''': Anomaly Score of 3. Is generated by malicious client rules (35 level files).
*'''5 - NOTICE''': Anomaly Score of 2. Is generated by the Protocol policy and anomaly files.
*'''6 - INFO'''
*'''7 - DEBUG'''
It is possible to specify severity levels using either the numerical values or the text values, but you should always specify severity levels using the text values, because it is difficult to remember what a number stands for. The use of the numerical values is deprecated as of version 2.5.0 and may be removed in one of the subsequent major updates.
== setuid ==
'''Description:''' Special-purpose action that initializes the USER collection using the username provided as parameter.
'''Action Group:''' Non-disruptive
'''Example:'''
<pre>
SecRule ARGS:username ".*" "phase:2,id:137,t:none,pass,nolog,noauditlog,capture,setvar:session.username=%{TX.0},setuid:%{TX.0}"
</pre>
After initialization takes place, the variable USERID will be available for use in the subsequent rules. This action understands application namespaces (configured using SecWebAppId), and will use one if it is configured.
== setrsc ==
'''Description:''' Special-purpose action that initializes the RESOURCE collection using a key provided as parameter.
'''Action Group:''' Non-disruptive
'''Version:''' 2.x-3.x
'''Supported on libModSecurity:''' Yes - as of 9cb3f2 [https://github.com/SpiderLabs/ModSecurity/commit/9cb3f23b5095cad7dfba8f140a44b9523f2be78b]
'''Example:'''
<pre>
SecAction "phase:1,pass,id:3,log,setrsc:'abcd1234'"
</pre>
This action understands application namespaces (configured using SecWebAppId), and will use one if it is configured.
== setsid ==
'''Description:''' Special-purpose action that initializes the SESSION collection using the session token provided as parameter.
'''Action Group:''' Non-disruptive
'''Example:'''
<pre>
# Initialise session variables using the session cookie value
SecRule REQUEST_COOKIES:PHPSESSID !^$ "nolog,pass,id:138,setsid:%{REQUEST_COOKIES.PHPSESSID}"
</pre>
Note
After the initialization takes place, the variable SESSION will be available for use in the subsequent rules. This action understands application namespaces (configured using SecWebAppId), and will use one if it is configured.
Setsid takes an individual variable, not a collection. Variables within an action, such as setsid, use the format [collection].[variable] .
== setenv ==
'''Description:''' Creates, removes, and updates environment variables that can be accessed by Apache.
'''Action Group:''' Non-disruptive
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
'''Examples:'''
<pre>
SecRule RESPONSE_HEADERS:/Set-Cookie2?/ "(?i:(j?sessionid|(php)?sessid|(asp|jserv|jw)?session[-_]?(id)?|cf(id|token)|sid))" "phase:3,t:none,pass,id:139,nolog,setvar:tx.sessionid=%{matched_var}"
SecRule TX:SESSIONID "!(?i:\;? ?httponly;?)" "phase:3,id:140,t:none,setenv:httponly_cookie=%{matched_var},pass,log,auditlog,msg:'AppDefect: Missing HttpOnly Cookie Flag.'"
Header set Set-Cookie "%{httponly_cookie}e; HTTPOnly" env=httponly_cookie
</pre>
; Note : When used in a chain this action will be execute when an individual rule matches and not the entire chain.
== setvar ==
'''Description:''' Creates, removes, or updates a variable. Variable names are case-insensitive.
'''Action Group:''' Non-disruptive
'''Examples:'''
To create a variable and set its value to 1 (usually used for setting flags), use: <code>setvar:TX.score</code>
To create a variable and initialize it at the same time, use: <code>setvar:TX.score=10</code>
To remove a variable, prefix the name with an exclamation mark: <code>setvar:!TX.score</code>
To increase or decrease variable value, use + and - characters in front of a numerical value: <code>setvar:TX.score=+5</code>
Example from OWASP CRS:
<pre>
SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/* "\bsys\.user_catalog\b" \
"phase:2,rev:'2.1.3',capture,t:none,t:urlDecodeUni,t:htmlEntityDecode,t:lowercase,t:replaceComments,t:compressWhiteSpace,ctl:auditLogParts=+E, \
block,msg:'Blind SQL Injection Attack',id:'959517',tag:'WEB_ATTACK/SQL_INJECTION',tag:'WASCTC/WASC-19',tag:'OWASP_TOP_10/A1',tag:'OWASP_AppSensor/CIE1', \
tag:'PCI/6.5.2',logdata:'%{TX.0}',severity:'2',setvar:'tx.msg=%{rule.msg}',setvar:tx.sql_injection_score=+%{tx.critical_anomaly_score}, \
setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},setvar:tx.%{rule.id}-WEB_ATTACK/SQL_INJECTION-%{matched_var_name}=%{tx.0}"
</pre>
; Note : When used in a chain this action will be executed when an individual rule matches and not the entire chain.This means that
```
SecRule REQUEST_FILENAME "@contains /test.php" "chain,id:7,phase:1,t:none,nolog,setvar:tx.auth_attempt=+1"
SecRule ARGS_POST:action "@streq login" "t:none"
```
; will increment every time that test.php is visited (regardless of the parameters submitted). If the desired goal is to set the variable only if the entire rule matches, it should be included in the last rule of the chain . For instance:
```
SecRule REQUEST_FILENAME "@streq test.php" "chain,id:7,phase:1,t:none,nolog"
SecRule ARGS_POST:action "@streq login" "t:none,setvar:tx.auth_attempt=+1"
```
== skip ==
'''Description:''' Skips one or more rules (or chains) on successful match.
'''Action Group:''' Flow
'''Example:'''
<pre>
# Require Accept header, but not from access from the localhost
SecRule REMOTE_ADDR "^127\.0\.0\.1$" "phase:1,skip:1,id:141"
# This rule will be skipped over when REMOTE_ADDR is 127.0.0.1
SecRule &REQUEST_HEADERS:Accept "@eq 0" "phase:1,id:142,deny,msg:'Request Missing an Accept Header'"
</pre>
The skip action works only within the current processing phase and not necessarily in the order in which the rules appear in the configuration file. If you place a phase 2 rule after a phase 1 rule that uses skip, it will not skip over the phase 2 rule. It will skip over the next phase 1 rule that follows it in the phase.
== skipAfter ==
Description: Skips one or more rules (or chains) on a successful match, resuming rule execution with the first rule that follows the rule (or marker created by SecMarker) with the provided ID.
'''Action Group:''' Flow
'''Example:''' The following rules implement the same logic as the skip example, but using skipAfter:
<pre>
# Require Accept header, but not from access from the localhost
SecRule REMOTE_ADDR "^127\.0\.0\.1$" "phase:1,id:143,skipAfter:IGNORE_LOCALHOST"
# This rule will be skipped over when REMOTE_ADDR is 127.0.0.1
SecRule &REQUEST_HEADERS:Accept "@eq 0" "phase:1,deny,id:144,msg:'Request Missing an Accept Header'"
SecMarker IGNORE_LOCALHOST
</pre>
Example from the OWASP ModSecurity CRS:
<pre>
SecMarker BEGIN_HOST_CHECK
SecRule &REQUEST_HEADERS:Host "@eq 0" \
"skipAfter:END_HOST_CHECK,phase:2,rev:'2.1.3',t:none,block,msg:'Request Missing a Host Header',id:'960008',tag:'PROTOCOL_VIOLATION/MISSING_HEADER_HOST',tag:'WASCTC/WASC-21', \
tag:'OWASP_TOP_10/A7',tag:'PCI/6.5.10',severity:'5',setvar:'tx.msg=%{rule.msg}',setvar:tx.anomaly_score=+%{tx.notice_anomaly_score}, \
setvar:tx.protocol_violation_score=+%{tx.notice_anomaly_score},setvar:tx.%{rule.id}-PROTOCOL_VIOLATION/MISSING_HEADER-%{matched_var_name}=%{matched_var}"
SecRule REQUEST_HEADERS:Host "^$" \
"phase:2,rev:'2.1.3',t:none,block,msg:'Request Missing a Host Header',id:'960008',tag:'PROTOCOL_VIOLATION/MISSING_HEADER_HOST',tag:'WASCTC/WASC-21',tag:'OWASP_TOP_10/A7', \
tag:'PCI/6.5.10',severity:'5',setvar:'tx.msg=%{rule.msg}',setvar:tx.anomaly_score=+%{tx.notice_anomaly_score},setvar:tx.protocol_violation_score=+%{tx.notice_anomaly_score}, \
setvar:tx.%{rule.id}-PROTOCOL_VIOLATION/MISSING_HEADER-%{matched_var_name}=%{matched_var}"
SecMarker END_HOST_CHECK
</pre>
The skipAfter action works only within the current processing phase and not necessarily the order in which the rules appear in the configuration file. If you place a phase 2 rule after a phase 1 rule that uses skip, it will not skip over the phase 2 rule. It will skip over the next phase 1 rule that follows it in the phase.
== status ==
'''Description:''' Specifies the response status code to use with actions deny and redirect.
'''Action Group:''' Data
'''Example:'''
<pre>
# Deny with status 403
SecDefaultAction "phase:1,log,deny,id:145,status:403"
</pre>
Status actions defined in Apache scope locations (such as Directory, Location, etc...) may be superseded by phase:1 action settings. The Apache ErrorDocument directive will be triggered if present in the configuration. Therefore if you have previously defined a custom error page for a given status then it will be executed and its output presented to the user.
== t ==
'''Description:''' This action is used to specify the transformation pipeline to use to transform the value of each variable used in the rule before matching.
'''Action Group:''' Non-disruptive
'''Example:'''
<pre>
SecRule ARGS "(asfunction|javascript|vbscript|data|mocha|livescript):" "id:146,t:none,t:htmlEntityDecode,t:lowercase,t:removeNulls,t:removeWhitespace"
</pre>
Any transformation functions that you specify in a SecRule will be added to the previous ones specified in SecDefaultAction. It is recommended that you always use t:none in your rules, which prevents them depending on the default configuration.
== tag ==
'''Description:''' Assigns a tag (category) to a rule or a chain.
'''Action Group:''' Meta-data
'''Example:'''
<pre>
SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/* "\bgetparentfolder\b" \
"phase:2,rev:'2.1.3',capture,t:none,t:htmlEntityDecode,t:compressWhiteSpace,t:lowercase,ctl:auditLogParts=+E,block,msg:'Cross-site Scripting (XSS) Attack',id:'958016',tag:'WEB_ATTACK/XSS',tag:'WASCTC/WASC-8',tag:'WASCTC/WASC-22',tag:'OWASP_TOP_10/A2',tag:'OWASP_AppSensor/IE1',tag:'PCI/6.5.1',logdata:'% \
{TX.0}',severity:'2',setvar:'tx.msg=%{rule.msg}',setvar:tx.xss_score=+%{tx.critical_anomaly_score},setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},setvar:tx.%{rule.id}-WEB_ATTACK/XSS-%{matched_var_name}=%{tx.0}"
</pre>
The tag information appears along with other rule metadata. The purpose of the tagging mechanism to allow easy automated categorization of events. Multiple tags can be specified on the same rule. Use forward slashes to create a hierarchy of categories (as in the example). Since ModSecurity 2.6.0 tag supports macro expansion.
== ver ==
'''Description:''' Specifies the rule set version.
'''Action Group:''' Meta-data
'''Version:''' 2.7
'''Example:'''
<pre>
SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/* "\bgetparentfolder\b" \
"phase:2,ver:'CRS/2.2.4,capture,t:none,t:htmlEntityDecode,t:compressWhiteSpace,t:lowercase,ctl:auditLogParts=+E,block,msg:'Cross-site Scripting (XSS) Attack',id:'958016',tag:'WEB_ATTACK/XSS',tag:'WASCTC/WASC-8',tag:'WASCTC/WASC-22',tag:'OWASP_TOP_10/A2',tag:'OWASP_AppSensor/IE1',tag:'PCI/6.5.1',logdata:'% \
{TX.0}',severity:'2',setvar:'tx.msg=%{rule.msg}',setvar:tx.xss_score=+%{tx.critical_anomaly_score},setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},setvar:tx.%{rule.id}-WEB_ATTACK/XSS-%{matched_var_name}=%{tx.0}"
</pre>
== xmlns ==
'''Description:''' Configures an XML namespace, which will be used in the execution of XPath expressions.
'''Action Group:''' Data
'''Example:'''
<pre>
SecRule REQUEST_HEADERS:Content-Type "text/xml" "phase:1,id:147,pass,ctl:requestBodyProcessor=XML,ctl:requestBodyAccess=On, \
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
SecRule XML:/soap:Envelope/soap:Body/q1:getInput/id() "123" phase:2,deny,id:148
</pre>

File diff suppressed because it is too large Load Diff

@@ -0,0 +1,659 @@
= ModSecurity&reg; Reference Manual =
== Current as of v2.6 v2.7 v2.8 v2.9 v3.0 ==
=== Copyright &copy; 2004-2022 [https://www.trustwave.com/ Trustwave Holdings, Inc.] ===
= Operators =
This section documents the operators currently available in ModSecurity.
== beginsWith ==
'''Description:''' Returns true if the parameter string is found at the beginning of the input. Macro expansion is performed on the parameter string before comparison.
'''Example:'''
<pre>
# Detect request line that does not begin with "GET"
SecRule REQUEST_LINE "!@beginsWith GET" "id:149"
</pre>
== contains ==
'''Description:''' Returns true if the parameter string is found anywhere in the input. Macro expansion is performed on the parameter string before comparison.
'''Example:'''
<pre>
# Detect ".php" anywhere in the request line
SecRule REQUEST_LINE "@contains .php" "id:150"
</pre>
== containsWord ==
'''Description:''' Returns true if the parameter string (with word boundaries) is found anywhere in the input. Macro expansion is performed on the parameter string before comparison.
'''Example:'''
<pre>
# Detect "select" anywhere in ARGS
SecRule ARGS "@containsWord select" "id:151"
</pre>
Would match on - <br>
-1 union '''select''' BENCHMARK(2142500,MD5(CHAR(115,113,108,109,97,112))) FROM wp_users WHERE ID=1 and (ascii(substr(user_login,1,1))&0x01=0) from wp_users where ID=1--
But not on - <br>
Your site has a wide '''select'''ion of computers.
== detectSQLi ==
'''Description:''' Returns true if SQL injection payload is found. This operator uses LibInjection to detect SQLi attacks.
'''Version:''' 2.7.4
'''Example:'''
<pre>
# Detect SQL Injection inside request uri data"
SecRule REQUEST_URI "@detectSQLi" "id:152"
</pre>
; Note : This operator supports the "capture" action.
== detectXSS ==
'''Description:''' Returns true if XSS injection is found. This operator uses LibInjection to detect XSS attacks.
'''Version:''' 2.8.0
'''Example:'''
<pre>
# Detect XSS Injection inside request body
SecRule REQUEST_BODY "@detectXSS" "id:12345,log,deny"
</pre>
; Note : This operator supports the "capture" action.
== endsWith ==
'''Description:''' Returns true if the parameter string is found at the end of the input. Macro expansion is performed on the parameter string before comparison.
'''Example:'''
<pre>
# Detect request line that does not end with "HTTP/1.1"
SecRule REQUEST_LINE "!@endsWith HTTP/1.1" "id:152"
</pre>
== fuzzyHash ==
'''Description:''' The fuzzyHash operator uses the ssdeep, which is a program for computing context triggered piecewise hashes (CTPH). Also called fuzzy hashes, CTPH can match inputs that have homologies. Such inputs have sequences of identical bytes in the same order, although bytes in between these sequences may be different in both content and length.
For further information on ssdeep, visit its site: http://ssdeep.sourceforge.net/
'''Version:''' v2.9.0-RC1-2.9.x
'''Supported on libModSecurity:''' TBI
'''Example:'''
<pre>
SecRule REQUEST_BODY "\@fuzzyHash /path/to/ssdeep/hashes.txt 6" "id:192372,log,deny"
</pre>
== eq ==
'''Description:''' Performs numerical comparison and returns true if the input value is equal to the provided parameter. Macro expansion is performed on the parameter string before comparison.
'''Example:'''
<pre>
# Detect exactly 15 request headers
SecRule &REQUEST_HEADERS_NAMES "@eq 15" "id:153"
</pre>
; Note : If a value is provided that cannot be converted to an integer (i.e a string) this operator will treat that value as 0.
== ge ==
'''Description:''' Performs numerical comparison and returns true if the input value is greater than or equal to the provided parameter. Macro expansion is performed on the parameter string before comparison.
'''Example:'''
<pre>
# Detect 15 or more request headers
SecRule &REQUEST_HEADERS_NAMES "@ge 15" "id:154"
</pre>
; Note : If a value is provided that cannot be converted to an integer (i.e a string) this operator will treat that value as 0.
== geoLookup ==
'''Description:''' Performs a geolocation lookup using the IP address in input against the geolocation database previously configured using SecGeoLookupDb. If the lookup is successful, the obtained information is captured in the GEO collection.
'''Example:'''
The geoLookup operator matches on success and is thus best used in combination with nolog,pass. If you wish to block on a failed lookup (which may be over the top, depending on how accurate the geolocation database is), the following example demonstrates how best to do it:
<pre>
# Configure geolocation database
SecGeoLookupDb /path/to/GeoLiteCity.dat
...
# Lookup IP address
SecRule REMOTE_ADDR "@geoLookup" "phase:1,id:155,nolog,pass"
# Block IP address for which geolocation failed
SecRule &GEO "@eq 0" "phase:1,id:156,deny,msg:'Failed to lookup IP'"
</pre>
See the GEO variable for an example and more information on various fields available.
== gsbLookup ==
'''Description:''' Performs a local lookup of Google's Safe Browsing using URLs in input against the GSB database previously configured using SecGsbLookupDb. When combined with capture operator it will save the matched url into tx.0 variable.
'''Syntax:''' <code>SecRule TARGET "@gsbLookup REGEX" ACTIONS</code>
'''Version:''' 2.6
'''Supported on libModSecurity:''' TBD
'''Example:'''
The gsbLookup operator matches on success and is thus best used in combination with a block or redirect action. If you wish to block on successful lookups, the following example demonstrates how best to do it:
<pre>
# Configure Google Safe Browsing database
SecGsbLookupDb /path/to/GsbMalware.dat
...
# Check response bodies for malicious links
SecRule RESPONSE_BODY "@gsbLookup =\"https?\:\/\/(.*?)\"" "phase:4,id:157,capture,log,block,msg:'Bad url detected in RESPONSE_BODY (Google Safe Browsing Check)',logdata:'http://www.google.com/safebrowsing/diagnostic?site=%{tx.0}'"
</pre>
; Note : This operator supports the "capture" action.
== gt ==
'''Description:''' Performs numerical comparison and returns true if the input value is greater than the operator parameter. Macro expansion is performed on the parameter string before comparison.
'''Example:'''
<pre>
# Detect more than 15 headers in a request
SecRule &REQUEST_HEADERS_NAMES "@gt 15" "id:158"
</pre>
; Note : If a value is provided that cannot be converted to an integer (i.e a string) this operator will treat that value as 0.
== inspectFile ==
'''Description:''' Executes an external program for every variable in the target list. The contents of the variable is provided to the script as the first parameter on the command line. The program must be specified as the first parameter to the operator. As of version 2.5.0, if the supplied program filename is not absolute, it is treated as relative to the directory in which the configuration file resides. Also as of version 2.5.0, if the filename is determined to be a Lua script (based on its .lua extension), the script will be processed by the internal Lua engine. Internally processed scripts will often run faster (there is no process creation overhead) and have full access to the transaction context of ModSecurity.
The @inspectFile operator was initially designed for file inspection (hence the name), but it can also be used in any situation that requires decision making using external logic.
The OWASP ModSecurity Core Rule Set (CRS) includes a utility script in the /util directory called runav.pl [http://mod-security.svn.sourceforge.net/viewvc/mod-security/crs/trunk/util/] that allows the file approval mechanism to integrate with the ClamAV virus scanner. This is especially handy to prevent viruses and exploits from entering the web server through file upload.
<pre>
#!/usr/bin/perl
#
# runav.pl
# Copyright (c) 2004-2011 Trustwave
#
# This script is an interface between ModSecurity and its
# ability to intercept files being uploaded through the
# web server, and ClamAV
$CLAMSCAN = "clamscan";
if ($#ARGV != 0) {
print "Usage: runav.pl <filename>\n";
exit;
}
my ($FILE) = shift @ARGV;
$cmd = "$CLAMSCAN --stdout --no-summary $FILE";
$input = `$cmd`;
$input =~ m/^(.+)/;
$error_message = $1;
$output = "0 Unable to parse clamscan output [$1]";
if ($error_message =~ m/: Empty file\.?$/) {
$output = "1 empty file";
}
elsif ($error_message =~ m/: (.+) ERROR$/) {
$output = "0 clamscan: $1";
}
elsif ($error_message =~ m/: (.+) FOUND$/) {
$output = "0 clamscan: $1";
}
elsif ($error_message =~ m/: OK$/) {
$output = "1 clamscan: OK";
}
print "$output\n";
</pre>
'''Example:''' Using the runav.pl script:
<pre>
# Execute external program to validate uploaded files
SecRule FILES_TMPNAMES "@inspectFile /path/to/util/runav.pl" "id:159"
</pre>
Example of using Lua script (placed in the same directory as the configuration file):
<pre>
SecRule FILES_TMPNAMES "@inspectFile inspect.lua" "id:160"
</pre>
The contents of inspect.lua:
<pre>
function main(filename)
-- Do something to the file to verify it. In this example, we
-- read up to 10 characters from the beginning of the file.
local f = io.open(filename, "rb");
local d = f:read(10);
f:close();
-- Return null if there is no reason to believe there is ansything
-- wrong with the file (no match). Returning any text will be taken
-- to mean a match should be trigerred.
return null;
end
</pre>
; Note : Starting in version 2.9 ModSecurity will not fill the FILES_TMPNAMES variable unless SecTmpSaveUploadedFiles directive is On, or the SecUploadKeepFiles directive is set to RelevantOnly.
; Note: Use @inspectFile with caution. It may not be safe to use @inspectFile with variables other than FILES_TMPNAMES. Other variables such as "FULL_REQUEST" may contains content that force your platform to fork process out of your control, making possible to an attacker to execute code using the same permissions of your web server. For other variables you may want to look at the Lua script engine. This observation was brought to our attention by "Gryzli", on our users mailing list.
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
'''Reference:''' http://blog.spiderlabs.com/2010/10/advanced-topic-of-the-week-preventing-malicious-pdf-file-uploads.html
'''Reference:''' http://sourceforge.net/p/mod-security/mailman/mod-security-users/?viewmonth=201512
== ipMatch ==
'''Description:''' Performs a fast ipv4 or ipv6 match of REMOTE_ADDR variable data. Can handle the following formats:
*Full IPv4 Address - 192.168.1.100
*Network Block/CIDR Address - 192.168.1.0/24
*Full IPv6 Address - 2001:db8:85a3:8d3:1319:8a2e:370:7348
*Network Block/CIDR Address - 2001:db8:85a3:8d3:1319:8a2e:370:0/24
'''Version:''' 2.7
'''Examples:'''
Individual Address:
<pre>
SecRule REMOTE_ADDR "@ipMatch 192.168.1.100" "id:161"
</pre>
Multiple Addresses w/network block:
<pre>
SecRule REMOTE_ADDR "@ipMatch 192.168.1.100,192.168.1.50,10.10.50.0/24" "id:162"
</pre>
== ipMatchF ==
short alias for ipMatchFromFile
'''Version:''' 2.7
== ipMatchFromFile ==
'''Description:''' Performs a fast ipv4 or ipv6 match of REMOTE_ADDR variable, loading data from a file. Can handle the following formats:
*Full IPv4 Address - 192.168.1.100
*Network Block/CIDR Address - 192.168.1.0/24
*Full IPv6 Address - 2001:db8:85a3:8d3:1319:8a2e:370:7348
*Network Block/CIDR Address - 2001:db8:85a3:8d3:1319:8a2e:370:0/24
'''Version:''' 2.7
'''Examples:'''
<pre>
SecRule REMOTE_ADDR "@ipMatchFromFile ips.txt" "id:163"
</pre>
The file ips.txt may contain:
<pre>
192.168.0.1
172.16.0.0/16
10.0.0.0/8
</pre>
; Note : As of v2.9.0-RC1 this operator also supports to load content served by an HTTPS server.
; Note : When used with content served by a HTTPS server, the directive SecRemoteRulesFailAction can be used to configure a warning instead of an abort, when the remote content could not be retrieved.
== le ==
'''Description:''' Performs numerical comparison and returns true if the input value is less than or equal to the operator parameter. Macro expansion is performed on the parameter string before comparison.
'''Example''':
<pre>
# Detect 15 or fewer headers in a request
SecRule &REQUEST_HEADERS_NAMES "@le 15" "id:164"
</pre>
; Note : If a value is provided that cannot be converted to an integer (i.e a string) this operator will treat that value as 0.
== lt ==
'''Description:''' Performs numerical comparison and returns true if the input value is less than to the operator parameter. Macro expansion is performed on the parameter string before comparison.
'''Example:'''
<pre>
# Detect fewer than 15 headers in a request
SecRule &REQUEST_HEADERS_NAMES "@lt 15" "id:165"
</pre>
; Note : If a value is provided that cannot be converted to an integer (i.e a string) this operator will treat that value as 0.
== noMatch ==
'''Description:''' Will force the rule to always return false.
== pm ==
'''Description:''' Performs a case-insensitive match of the provided phrases against the desired input value. The operator uses a set-based matching algorithm (Aho-Corasick), which means that it will match any number of keywords in parallel. When matching of a large number of keywords is needed, this operator performs much better than a regular expression.
'''Example:'''
<pre>
# Detect suspicious client by looking at the user agent identification
SecRule REQUEST_HEADERS:User-Agent "@pm WebZIP WebCopier Webster WebStripper ... SiteSnagger ProWebWalker CheeseBot" "id:166"
</pre>
; Note : Starting on ModSecurity v2.6.0 this operator supports a snort/suricata content style. ie: "@pm A|42|C|44|F".
; Note : This operator does not support macro expansion (as of ModSecurity v2.9.1).
; Note : This operator supports the "capture" action.
== pmf ==
Short alias for pmFromFile.
== pmFromFile ==
'''Description:''' Performs a case-insensitive match of the provided phrases against the desired input value. The operator uses a set-based matching algorithm (Aho-Corasick), which means that it will match any number of keywords in parallel. When matching of a large number of keywords is needed, this operator performs much better than a regular expression.
This operator is the same as @pm, except that it takes a list of files as arguments. It will match any one of the phrases listed in the file(s) anywhere in the target value.
'''Example:'''
<pre>
# Detect suspicious user agents using the keywords in
# the files /path/to/blacklist1 and blacklist2 (the latter
# must be placed in the same folder as the configuration file)
SecRule REQUEST_HEADERS:User-Agent "@pmFromFile /path/to/blacklist1 blacklist2" "id:167"
</pre>
Notes:
#Files must contain exactly one phrase per line. End of line markers (both LF and CRLF) will be stripped from each phrase and any whitespace trimmed from both the beginning and the end. Empty lines and comment lines (those beginning with the # character) will be ignored.
#To allow easier inclusion of phrase files with rule sets, relative paths may be used to the phrase files. In this case, the path of the file containing the rule is prepended to the phrase file path.
#The @pm operator phrases do not support metacharacters.
#Because this operator does not check for boundaries when matching, false positives are possible in some cases. For example, if you want to use @pm for IP address matching, the phrase 1.2.3.4 will potentially match more than one IP address (e.g., it will also match 1.2.3.40 or 1.2.3.41). To avoid the false positives, you can use your own boundaries in phrases. For example, use /1.2.3.4/ instead of just 1.2.3.4. Then, in your rules, also add the boundaries where appropriate. You will find a complete example in the example.
<pre>
# Prepare custom REMOTE_ADDR variable
SecAction "phase:1,id:168,nolog,pass,setvar:tx.REMOTE_ADDR=/%{REMOTE_ADDR}/"
# Check if REMOTE_ADDR is blacklisted
SecRule TX:REMOTE_ADDR "@pmFromFile blacklist.txt" "phase:1,id:169,deny,msg:'Blacklisted IP address'"
</pre>
The file blacklist.txt may contain:
<pre>
# ip-blacklist.txt contents:
# NOTE: All IPs must be prefixed/suffixed with "/" as the rules
# will add in this character as a boundary to ensure
# the entire IP is matched.
# SecAction "phase:1,id:170,pass,nolog,setvar:tx.remote_addr='/%{REMOTE_ADDR}/'"
/1.2.3.4/
/5.6.7.8/
</pre>
; Warning : Before ModSecurity 2.5.12, the @pmFromFile operator understood only the LF line endings and did not trim the whitespace from phrases. If you are using an older version of ModSecurity, you should take care when editing the phrase files to avoid using the undesired characters in patterns.e files should be one phrase per line. End of line markers will be stripped from the phrases (LF and CRLF), and whitespace is trimmed from both sides of the phrases. Empty lines and comment lines (beginning with a '#') are ignored. To allow easier inclusion of phrase files with rulesets, relative paths may be used to the phrase files. In this case, the path of the file containing the rule is prepended to the phrase file path.
; Note : Starting on ModSecurity v2.6.0 this operator supports a snort/suricata content style. ie: "A|42|C|44|F".
; Note II : As of v2.9.0-RC1 this operator also supports to load content served by an HTTPS server. However, only one url can be used at a time.
== rbl ==
'''Description:''' Looks up the input value in the RBL (real-time block list) given as parameter. The parameter can be an IPv4 address or a hostname.
'''Example:'''
<pre>
SecRule REMOTE_ADDR "@rbl sbl-xbl.spamhaus.org" "phase:1,id:171,t:none,pass,nolog,auditlog,msg:'RBL Match for SPAM Source',tag:'AUTOMATION/MALICIOUS',severity:'2',setvar:'tx.msg=%{rule.msg}',setvar:tx.automation_score=+%{tx.warning_anomaly_score},setvar:tx.anomaly_score=+%{tx.warning_anomaly_score}, \
setvar:tx.%{rule.id}-AUTOMATION/MALICIOUS-%{matched_var_name}=%{matched_var},setvar:ip.spammer=1,expirevar:ip.spammer=86400,setvar:ip.previous_rbl_check=1,expirevar:ip.previous_rbl_check=86400,skipAfter:END_RBL_CHECK"
</pre>
; Note : If the RBL used is dnsbl.httpbl.org (Honeypot Project RBL) then the SecHttpBlKey directive must specify the user's registered API key.
; Note : If the RBL used is either multi.uribl.com or zen.spamhaus.org combined RBLs, it is possible to also parse the return codes in the last octet of the DNS response to identify which specific RBL the IP was found in.
; Note : This operator supports the "capture" action.
== rsub ==
'''Description''': Performs regular expression data substitution when applied to either the STREAM_INPUT_BODY or STREAM_OUTPUT_BODY variables. This operator also supports macro expansion. Starting with ModSecurity 2.7.0 this operator supports the syntax |hex| allowing users to use special chars like \n \r
'''Syntax:''' <code>@rsub s/regex/str/[id]</code>
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
'''Examples:'''
Removing HTML Comments from response bodies:
<pre>
SecStreamOutBodyInspection On
SecRule STREAM_OUTPUT_BODY "@rsub s/<!--.*?-->/ /" "phase:4,id:172,t:none,nolog,pass"
</pre>
; Note : If you plan to manipulate live data by using @rsub with the STREAM_ variables, you must also enable SecContentInjection directive.
Regular expressions are handled by the PCRE library [http://www.pcre.org]. ModSecurity compiles its regular expressions with the following settings:
#The entire input is treated as a single line, even when there are newline characters present.
#All matches are case-sensitive. If you wish to perform case-insensitive matching, you can either use the lowercase transformation function or force case-insensitive matching by prefixing the regular expression pattern with the (?i) modifier (a PCRE feature; you will find many similar features in the PCRE documentation). Also a flag [d] should be used if you want to escape the regex string chars when use macro expansion.
#The PCRE_DOTALL and PCRE_DOLLAR_ENDONLY flags are set during compilation, meaning that a single dot will match any character, including the newlines, and a $ end anchor will not match a trailing newline character.
Regular expressions are a very powerful tool. You are strongly advised to read the PCRE documentation to get acquainted with its features.
; Note : This operator supports the "capture" action.
== rx ==
'''Description''': Performs a regular expression match of the pattern provided as parameter. '''This is the default operator; the rules that do not explicitly specify an operator default to @rx'''.
'''Examples:'''
<pre>
# Detect Nikto
SecRule REQUEST_HEADERS:User-Agent "@rx nikto" phase:1,id:173,t:lowercase
# Detect Nikto with a case-insensitive pattern
SecRule REQUEST_HEADERS:User-Agent "@rx (?i)nikto" phase:1,id:174,t:none
# Detect Nikto with a case-insensitive pattern
SecRule REQUEST_HEADERS:User-Agent "(?i)nikto" "id:175"
</pre>
Regular expressions are handled by the PCRE library [http://www.pcre.org]. ModSecurity compiles its regular expressions with the following settings:
#The entire input is treated as a single line, even when there are newline characters present.
#All matches are case-sensitive. If you wish to perform case-insensitive matching, you can either use the lowercase transformation function or force case-insensitive matching by prefixing the regular expression pattern with the (?i) modifier (a PCRE feature; you will find many similar features in the PCRE documentation).
#The PCRE_DOTALL and PCRE_DOLLAR_ENDONLY flags are set during compilation, meaning that a single dot will match any character, including the newlines, and a $ end anchor will not match a trailing newline character.
Regular expressions are a very powerful tool. You are strongly advised to read the PCRE documentation to get acquainted with its features.
; Note : This operator supports the "capture" action.
== streq ==
'''Description:''' Performs a string comparison and returns true if the parameter string is identical to the input string. Macro expansion is performed on the parameter string before comparison.
'''Example:'''
<pre>
# Detect request parameters "foo" that do not # contain "bar", exactly.
SecRule ARGS:foo "!@streq bar" "id:176"
</pre>
== strmatch ==
'''Description:''' Performs a string match of the provided word against the desired input value. The operator uses the pattern matching Boyer-Moore-Horspool algorithm, which means that it is a single pattern matching operator. This operator performs much better than a regular expression.
'''Example:'''
<pre>
# Detect suspicious client by looking at the user agent identification
SecRule REQUEST_HEADERS:User-Agent "@strmatch WebZIP" "id:177"
</pre>
; Note : Starting on ModSecurity v2.6.0 this operator supports a snort/suricata content style. ie: "@strmatch A|42|C|44|F".
== unconditionalMatch ==
'''Description:''' Will force the rule to always return true. This is similar to SecAction however all actions that occur as a result of a rule matching will fire such as the setting of MATCHED_VAR. This can also be part a chained rule.
'''Example:'''
<pre>
SecRule REMOTE_ADDR "@unconditionalMatch" "id:1000,phase:1,pass,nolog,t:hexEncode,setvar:TX.ip_hash=%{MATCHED_VAR}"
</pre>
== validateByteRange ==
'''Description:''' Validates that the byte values used in input fall into the range specified by the operator parameter. This operator matches on an input value that contains bytes that are not in the specified range.
'''Example:'''
<pre>
# Enforce very strict byte range for request parameters (only
# works for the applications that do not use the languages other
# than English).
SecRule ARGS "@validateByteRange 10, 13, 32-126" "id:178"
</pre>
The validateByteRange is most useful when used to detect the presence of NUL bytes, which dont have a legitimate use, but which are often used as an evasion technique.
<pre>
# Do not allow NUL bytes
SecRule ARGS "@validateByteRange 1-255" "id:179"
</pre>
; Note : You can force requests to consist only of bytes from a certain byte range. This can be useful to avoid stack overflow attacks (since they usually contain "random" binary content). Default range values are 0 and 255, i.e. all byte values are allowed. This directive does not check byte range in a POST payload when multipart/form-data encoding (file upload) is used. Doing so would prevent binary files from being uploaded. However, after the parameters are extracted from such request they are checked for a valid range.
validateByteRange is similar to the ModSecurity 1.X SecFilterForceByteRange Directive however since it works in a rule context, it has the following differences:
*You can specify a different range for different variables.
*It has an "event" context (id, msg....)
*It is executed in the flow of rules rather than being a built in pre-check.
== validateDTD ==
'''Description:''' Validates the XML DOM tree against the supplied DTD. The DOM tree must have been built previously using the XML request body processor. This operator matches when the validation fails.
'''Example:'''
<pre>
# Parse the request bodies that contain XML
SecRule REQUEST_HEADERS:Content-Type ^text/xml$ "phase:1,id:180,nolog,pass,t:lowercase,ctl:requestBodyProcessor=XML"
# Validate XML payload against DTD
SecRule XML "@validateDTD /path/to/xml.dtd" "phase:2,id:181,deny,msg:'Failed DTD validation'"
</pre>
'''NOTE:''' You must enable the <code>SecXmlExternalEntity</code> directive.
== validateHash ==
'''Description:''' Validates REQUEST_URI that contains data protected by the hash engine.
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
'''Example:'''
<pre>
# Validates requested URI that matches a regular expression.
SecRule REQUEST_URI "@validatehash "product_info|product_list" "phase:1,deny,id:123456"
</pre>
== validateSchema ==
'''Description:''' Validates the XML DOM tree against the supplied XML Schema. The DOM tree must have been built previously using the XML request body processor. This operator matches when the validation fails.
'''Example:'''
<pre>
# Parse the request bodies that contain XML
SecRule REQUEST_HEADERS:Content-Type ^text/xml$ "phase:1,id:190,nolog,pass,t:lowercase,ctl:requestBodyProcessor=XML"
# Validate XML payload against DTD
SecRule XML "@validateSchema /path/to/xml.xsd" "phase:2,id:191,deny,msg:'Failed DTD validation'"
</pre>
'''NOTE:''' You must enable the <code>SecXmlExternalEntity</code> directive.
== validateUrlEncoding ==
'''Description''': Validates the URL-encoded characters in the provided input string.
'''Example:'''
<pre>
# Validate URL-encoded characters in the request URI
SecRule REQUEST_URI_RAW "@validateUrlEncoding" "id:192"
</pre>
ModSecurity will automatically decode the URL-encoded characters in request parameters, which means that there is little sense in applying the @validateUrlEncoding operator to them —that is, unless you know that some of the request parameters were URL-encoded more than once. Use this operator against raw input, or against the input that you know is URL-encoded. For example, some applications will URL-encode cookies, although thats not in the standard. Because it is not in the standard, ModSecurity will neither validate nor decode such encodings.
== validateUtf8Encoding ==
'''Description:''' Check whether the input is a valid UTF-8 string.
'''Example:'''
<pre>
# Make sure all request parameters contain only valid UTF-8
SecRule ARGS "@validateUtf8Encoding" "id:193"
</pre>
The @validateUtf8Encoding operator detects the following problems:
; Not enough bytes : UTF-8 supports two-, three-, four-, five-, and six-byte encodings. ModSecurity will locate cases when one or more bytes is/are missing from a character.
; Invalid characters : The two most significant bits in most characters should be fixed to 0x80. Some attack techniques use different values as an evasion technique.
; Overlong characters : ASCII characters are mapped directly into UTF-8, which means that an ASCII character is one UTF-8 character at the same time. However, in UTF-8 many ASCII characters can also be encoded with two, three, four, five, and six bytes. This is no longer legal in the newer versions of Unicode, but many older implementations still support it. The use of overlong UTF-8 characters is common for evasion.
; Notes :
*Most, but not all applications use UTF-8. If you are dealing with an application that does, validating that all request parameters are valid UTF-8 strings is a great way to prevent a number of evasion techniques that use the assorted UTF-8 weaknesses. False positives are likely if you use this operator in an application that does not use UTF-8.
*Many web servers will also allow UTF-8 in request URIs. If yours does, you can verify the request URI using @validateUtf8Encoding.
== verifyCC ==
'''Description:''' Detects credit card numbers in input. This operator will first use the supplied regular expression to perform an initial match, following up with the Luhn algorithm calculation to minimize false positives.
'''Example:'''
<pre>
# Detect credit card numbers in parameters and
# prevent them from being logged to audit log
SecRule ARGS "@verifyCC \d{13,16}" "phase:2,id:194,nolog,pass,msg:'Potential credit card number',sanitiseMatched"
</pre>
; Note : This operator supports the "capture" action.
== verifyCPF ==
'''Description:''' Detects CPF numbers (Brazilian social number) in input. This operator will first use the supplied regular expression to perform an initial match, following up with an algorithm calculation to minimize false positives.
'''Example:'''
<pre>
# Detect CPF numbers in parameters and
# prevent them from being logged to audit log
SecRule ARGS "@verifyCPF /^([0-9]{3}\.){2}[0-9]{3}-[0-9]{2}$/" "phase:2,id:195,nolog,pass,msg:'Potential CPF number',sanitiseMatched"
</pre>
'''Version:''' 2.6-3.x
'''Supported on libModSecurity:''' Yes
; Note : This operator supports the "capture" action.
== verifySSN ==
'''Description:''' Detects US social security numbers (SSN) in input. This operator will first use the supplied regular expression to perform an initial match, following up with an SSN algorithm calculation to minimize false positives.
'''Example:'''
<pre>
# Detect social security numbers in parameters and
# prevent them from being logged to audit log
SecRule ARGS "@verifySSN \d{3}-?\d{2}-?\d{4}" "phase:2,id:196,nolog,pass,msg:'Potential social security number',sanitiseMatched"
</pre>
'''Version:''' 2.6-3.x
'''Supported on libModSecurity:''' Yes
'''SSN Format''':
A Social Security number is broken up into 3 sections:
*Area (3 digits)
*Group (2 digits)
*Serial (4 digits)
'''verifySSN checks:'''
*Must have 9 digits
*Cannot be a sequence number (ie,, 123456789, 012345678)
*Cannot be a repetition sequence number ( ie 11111111 , 222222222)
*Cannot have area and/or group and/or serial zeroed sequences
*Area code must be less than 740
*Area code must be different then 666
; Note : This operator supports the "capture" action.
== within ==
'''Description:''' Returns true if the input value (the needle) is found anywhere within the @within parameter (the haystack). Macro expansion is performed on the parameter string before comparison.
'''Example:'''
<pre>
# Detect request methods other than GET, POST and HEAD
SecRule REQUEST_METHOD "!@within GET,POST,HEAD"
</pre>
;NOTE: There are no delimiters for this operator, it is therefore often necessary to artificially impose some; this can be done using setvar. For instance in the example below, without the imposed delimiters (of '/') this rule would also match on the 'range' header (along with many other combinations), since 'range' is within the provided parameter. With the imposed delimiters, the rule would check for '/range/' when the range header is provided, and therefore would not match since '/range/ is not part of the @within parameter.
```
SecRule REQUEST_HEADERS_NAMES "@rx ^.*$" \
"chain,\
id:1,\
block,\
t:lowercase,\
setvar:'tx.header_name=/%{tx.0}/'"
SecRule TX:header_name "@within /proxy/ /lock-token/ /content-range/ /translate/ /if/" "t:none"
```

@@ -0,0 +1,52 @@
= ModSecurity&reg; Reference Manual =
== Current as of v2.6 v2.7 v2.8 v2.9 v3.0 ==
=== Copyright &copy; 2004-2022 [https://www.trustwave.com/ Trustwave Holdings, Inc.] ===
= Processing Phases =
ModSecurity 2.x allows rules to be placed in one of the following five phases of the Apache request cycle:
*Request headers (REQUEST_HEADERS)
*Request body (REQUEST_BODY)
*Response headers (RESPONSE_HEADERS)
*Response body (RESPONSE_BODY)
*Logging (LOGGING)
Below is a diagram of the standard Apache Request Cycle. In the diagram, the 5 ModSecurity processing phases are shown.
[[http://www.modsecurity.org/graphics/modsec-rotation.jpg]]
In order to select the phase a rule executes during, use the phase action either directly in the rule or in using the SecDefaultAction directive:
<pre>
SecDefaultAction "log,pass,phase:2,id:4"
SecRule REQUEST_HEADERS:Host "!^$" "deny,phase:1,id:5"
</pre>
; Note : The data available in each phase is cumulative. This means that as you move onto later phases, you have access to more and more data from the transaction.
; Note : Keep in mind that rules are executed according to phases, so even if two rules are adjacent in a configuration file, but are set to execute in different phases, they would not happen one after the other. The order of rules in the configuration file is important only within the rules of each phase. This is especially important when using the skip and skipAfter actions.
; Note : The LOGGING phase is special. It is executed at the end of each transaction no matter what happened in the previous phases. This means it will be processed even if the request was intercepted or the allow action was used to pass the transaction through.
== Phase Request Headers ==
Rules in this phase are processed immediately after Apache completes reading the request headers (post-read-request phase). At this point the request body has not been read yet, meaning not all request arguments are available. Rules should be placed in this phase if you need to have them run early (before Apache does something with the request), to do something before the request body has been read, determine whether or not the request body should be buffered, or decide how you want the request body to be processed (e.g. whether to parse it as XML or not).
; Note : Rules in this phase can not leverage Apache scope directives (Directory, Location, LocationMatch, etc...) as the post-read-request hook does not have this information yet. The exception here is the VirtualHost directive. If you want to use ModSecurity rules inside Apache locations, then they should run in Phase 2. Refer to the Apache Request Cycle/ModSecurity Processing Phases diagram.
== Phase Request Body ==
This is the general-purpose input analysis phase. Most of the application-oriented rules should go here. In this phase you are guaranteed to have received the request arguments (provided the request body has been read). ModSecurity supports three encoding types for the request body phase:
*'''application/x-www-form-urlencoded''' - used to transfer form data
*'''multipart/form-data''' - used for file transfers
*'''text/xml''' - used for passing XML data
Other encodings are not used by most web applications.
; Note : In order to access the Request Body phase data, you must have SecRequestBodyAccess set to On.
== Phase Response Headers ==
This phase takes place just before response headers are sent back to the client. Run here if you want to observe the response before that happens, and if you want to use the response headers to determine if you want to buffer the response body. Note that some response status codes (such as 404) are handled earlier in the request cycle by Apache and my not be able to be triggered as expected. Additionally, there are some response headers that are added by Apache at a later hook (such as Date, Server and Connection) that we would not be able to trigger on or sanitize. This should work appropriately in a proxy setup or within phase:5 (logging).
== Phase Response Body ==
This is the general-purpose output analysis phase. At this point you can run rules against the response body (provided it was buffered, of course). This is the phase where you would want to inspect the outbound HTML for information disclosure, error messages or failed authentication text.
; Note : In order to access the Response Body phase data, you must have SecResponseBodyAccess set to On
== Phase Logging ==
This phase is run just before logging takes place. The rules placed into this phase can only affect how the logging is performed. This phase can be used to inspect the error messages logged by Apache. You cannot deny/block connections in this phase as it is too late. This phase also allows for inspection of other response headers that weren't available during phase:3 or phase:4. Note that you must be careful not to inherit a disruptive action into a rule in this phase as this is a configuration error in ModSecurity 2.5.0 and later versions

@@ -0,0 +1,186 @@
= ModSecurity&reg; Reference Manual =
== Current as of v2.6 v2.7 v2.8 v2.9 v3.0 ==
=== Copyright &copy; 2004-2022 [https://www.trustwave.com/ Trustwave Holdings, Inc.] ===
= Transformation functions =
Transformation functions are used to alter input data before it is used in matching (i.e., operator execution). The input data is never modified, actually—whenever you request a transformation function to be used, ModSecurity will create a copy of the data, transform it, and then run the operator against the result.
; Note : There are no default transformation functions, as there were in the first generation of ModSecurity (1.x).
In the following example, the request parameter values are converted to lowercase before matching:
<code>SecRule ARGS "xp_cmdshell" "t:lowercase,id:91"</code>
Multiple transformation actions can be used in the same rule, forming a transformation pipeline. The transformations will be performed in the order in which they appear in the rule.
In most cases, the order in which transformations are performed is very important. In the following example, a series of transformation functions is performed to counter evasion. Performing the transformations in any other order would allow a skillful attacker to evade detection:
<code>SecRule ARGS "(asfunction|javascript|vbscript|data|mocha|livescript):" "id:92,t:none,t:htmlEntityDecode,t:lowercase,t:removeNulls,t:removeWhitespace"</code>
; Warning : It is currently possible to use SecDefaultAction to specify a default list of transformation functions, which will be applied to all rules that follow the SecDefaultAction directive. However, this practice is not recommended, because it means that mistakes are very easy to make. It is recommended that you always specify the transformation functions that are needed by a particular rule, starting the list with t:none (which clears the possibly inherited transformation functions).
The remainder of this section documents the transformation functions currently available in ModSecurity.
== base64Decode ==
Decodes a Base64-encoded string.
<pre>
SecRule REQUEST_HEADERS:Authorization "^Basic ([a-zA-Z0-9]+=*)$" "phase:1,id:93,capture,chain,logdata:%{TX.1}"
SecRule TX:1 ^(\w+): t:base64Decode,capture,chain
SecRule TX:1 ^(admin|root|backup)$
</pre>
; Note : Be careful when applying base64Decode with other transformations. The order of your transformation matters in this case as certain transformations may change or invalidate the base64 encoded string prior to being decoded (i.e t:lowercase, etc). This of course means that it is also very difficult to write a single rule that checks for a base64decoded value OR an unencoded value with transformations, it is best to write two rules in this situation.
== sqlHexDecode ==
Decode sql hex data. Example (0x414243) will be decoded to (ABC). Available as of 2.6.3
== base64DecodeExt ==
Decodes a Base64-encoded string. Unlike base64Decode, this version uses a forgiving implementation, which ignores invalid characters. Available as of 2.5.13.
See blog post on Base64Decoding evasion issues on PHP sites - http://blog.spiderlabs.com/2010/04/impedance-mismatch-and-base64.html
== base64Encode ==
Encodes input string using Base64 encoding.
== cmdLine ==
; Note : This is a community contribution developed by Marc Stern [http://www.linkedin.com/in/marcstern]
In Windows and Unix, commands may be escaped by different means, such as:
*c^ommand /c ...
*"command" /c ...
*command,/c ...
*backslash in the middle of a Unix command
The cmdLine transformation function avoids this problem by manipulating the variable contend in the following ways:
*deleting all backslashes [\]
*deleting all double quotes ["]
*deleting all single quotes [']
*deleting all carets [^]
*deleting spaces before a slash [/]
*deleting spaces before an open parentesis [(]
*replacing all commas [,] and semicolon [;] into a space
*replacing all multiple spaces (including tab, newline, etc.) into one space
*transform all characters to lowercase
'''Example Usage:'''
<pre>
SecRule ARGS "(?:command(?:.com)?|cmd(?:.exe)?)(?:/.*)?/[ck]" "phase:2,id:94,t:none, t:cmdLine"
</pre>
== compressWhitespace ==
Converts any of the whitespace characters (0x20, \f, \t, \n, \r, \v, 0xa0) to spaces (ASCII 0x20), compressing multiple consecutive space characters into one.
== cssDecode ==
Decodes characters encoded using the CSS 2.x escape rules [http://www.w3.org/TR/CSS2/ syndata.html#characters]. This function uses only up to two bytes in the decoding process, meaning that it is useful to uncover ASCII characters encoded using CSS encoding (that wouldnt normally be encoded), or to counter evasion, which is a combination of a backslash and non-hexadecimal characters (e.g., ja\vascript is equivalent to javascript).
== escapeSeqDecode ==
Decodes ANSI C escape sequences: \a, \b, \f, \n, \r, \t, \v, \\, \?, \', \", \xHH (hexadecimal), \0OOO (octal). Invalid encodings are left in the output.
== hexDecode ==
Decodes a string that has been encoded using the same algorithm as the one used in hexEncode (see following entry).
== hexEncode ==
Encodes string (possibly containing binary characters) by replacing each input byte with two hexadecimal characters. For example, xyz is encoded as 78797a.
== htmlEntityDecode ==
Decodes the characters encoded as HTML entities. The following variants are supported:
*&#xHH and &#xHH; (where H is any hexadecimal number)
*&#DDD and &#DDD; (where D is any decimal number)
*&quotand&quot;
*&nbspand&nbsp;
*&ltand&lt;
*&gtand&gt;
This function always converts one HTML entity into one byte, possibly resulting in a loss of information (if the entity refers to a character that cannot be represented with the single byte). It is thus useful to uncover bytes that would otherwise not need to be encoded, but it cannot do anything meaningful with the characters from the range above 0xff.
== jsDecode ==
Decodes JavaScript escape sequences. If a \uHHHH code is in the range of FF01-FF5E (the full width ASCII codes), then the higher byte is used to detect and adjust the lower byte. Otherwise, only the lower byte will be used and the higher byte zeroed (leading to possible loss of information).
== length ==
Looks up the length of the input string in bytes, placing it (as string) in output. For example, if it gets ABCDE on input, this transformation function will return 5 on output.
== lowercase ==
Converts all characters to lowercase using the current C locale.
== md5 ==
Calculates an MD5 hash from the data in input. The computed hash is in a raw binary form and may need encoded into text to be printed (or logged). Hash functions are commonly used in combination with hexEncode (for example: t:md5,t:hexEncode).
== none ==
Not an actual transformation function, but an instruction to ModSecurity to remove all transformation functions associated with the current rule.
== normalisePath ==
See normalizePath.
== normalizePath ==
Removes multiple slashes, directory self-references, and directory back-references (except when at the beginning of the input) from input string.
; Note : As of 2010 normalisePath has been renamed to normalizePath (MODSEC-103). NormalisePath is kept for backwards compatibility in current versions, but should not be used.
== normalisePathWin ==
See normalizePathWin.
== normalizePathWin ==
Same as normalizePath, but first converts backslash characters to forward slashes.
; Note : As of 2010 normalisePathWin has been renamed to normalizePathWin (MODSEC-103). NormalisePathWin is kept for backwards compatibility in current versions, but should not be used.
== parityEven7bit ==
Calculates even parity of 7-bit data replacing the 8th bit of each target byte with the calculated parity bit.
== parityOdd7bit ==
Calculates odd parity of 7-bit data replacing the 8th bit of each target byte with the calculated parity bit.
== parityZero7bit ==
Calculates zero parity of 7-bit data replacing the 8th bit of each target byte with a zero-parity bit, which allows inspection of even/odd parity 7-bit data as ASCII7 data.
== removeNulls ==
Removes all NUL bytes from input.
== removeWhitespace ==
Removes all whitespace characters from input.
== replaceComments ==
Replaces each occurrence of a C-style comment (/* ... */) with a single space (multiple consecutive occurrences of which will not be compressed). Unterminated comments will also be replaced with a space (ASCII 0x20). However, a standalone termination of a comment (*/) will not be acted upon.
== removeCommentsChar ==
Removes common comments chars (/*, */, --, #).
== removeComments ==
'''Version:''' 2.x-3.x
'''Supported on libModSecurity:''' Yes
Removes each occurrence of comment (/* ... */, --, #). Multiple consecutive occurrences of which will not be compressed.
; Note : '''This transformation is known to be unreliable, might cause some unexpected behaviour and could be deprecated soon in a future release. Refer to issue [https://github.com/SpiderLabs/ModSecurity/issues/1207 #1207] for further information.'''.
== replaceNulls ==
Replaces NUL bytes in input with space characters (ASCII 0x20).
== urlDecode ==
Decodes a URL-encoded input string. Invalid encodings (i.e., the ones that use non-hexadecimal characters, or the ones that are at the end of string and have one or two bytes missing) are not converted, but no error is raised. To detect invalid encodings, use the @validateUrlEncoding operator on the input data first. The transformation function should not be used against variables that have already been URL-decoded (such as request parameters) unless it is your intention to perform URL decoding twice!
== uppercase ==
Converts all characters to uppercase using the current C locale.
'''Version:''' 3.x
'''Supported on libModSecurity:''' Yes
== urlDecodeUni ==
Like urlDecode, but with support for the Microsoft-specific %u encoding. If the code is in the range of FF01-FF5E (the full-width ASCII codes), then the higher byte is used to detect and adjust the lower byte. Otherwise, only the lower byte will be used and the higher byte zeroed.
== urlEncode ==
Encodes input string using URL encoding.
== utf8toUnicode ==
Converts all UTF-8 characters sequences to Unicode. This help input normalization specially for non-english languages minimizing false-positives and false-negatives. (available with 2.7.0)
== sha1 ==
Calculates a SHA1 hash from the input string. The computed hash is in a raw binary form and may need encoded into text to be printed (or logged). Hash functions are commonly used in combination with hexEncode (for example, t:sha1,t:hexEncode).
== trimLeft ==
Removes whitespace from the left side of the input string.
== trimRight ==
Removes whitespace from the right side of the input string.
== trim ==
Removes whitespace from both the left and right sides of the input string.

@@ -0,0 +1,875 @@
= ModSecurity&reg; Reference Manual =
== Current as of v2.6 v2.7 v2.8 v2.9 v3.0 ==
=== Copyright &copy; 2004-2022 [https://www.trustwave.com/ Trustwave Holdings, Inc.] ===
= Variables =
The following variables are supported in ModSecurity 2.x:
== ARGS ==
ARGS is a collection and can be used on its own (means all arguments including the POST Payload), with a static parameter (matches arguments with that name), or with a regular expression (matches all arguments with name that matches the regular expression). To look at only the query string or body arguments, see the ARGS_GET and ARGS_POST collections.
Some variables are actually collections, which are expanded into more variables at runtime. The following example will examine all request arguments:
<code>SecRule ARGS dirty "id:7"</code>
Sometimes, however, you will want to look only at parts of a collection. This can be achieved with the help of the selection operator(colon). The following example will only look at the arguments named p (do note that, in general, requests can contain multiple arguments with the same name):
<code>SecRule ARGS:p dirty "id:8"</code>
It is also possible to specify exclusions. The following will examine all request arguments for the word dirty, except the ones named z (again, there can be zero or more arguments named z):
<code>SecRule ARGS|!ARGS:z dirty "id:9"</code>
There is a special operator that allows you to count how many variables there are in a collection. The following rule will trigger if there is more than zero arguments in the request (ignore the second parameter for the time being):
<code>SecRule &ARGS !^0$ "id:10"</code>
And sometimes you need to look at an array of parameters, each with a slightly different name. In this case you can specify a regular expression in the selection operator itself. The following rule will look into all arguments whose names begin with id_:
<code>SecRule ARGS:/^id_/ dirty "id:11"</code>
; Note : Using ARGS:p will not result in any invocations against the operator if argument p does not exist.
In ModSecurity 1.X, the ARGS variable stood for QUERY_STRING + POST_PAYLOAD, whereas now it expands to individual variables.
== ARGS_COMBINED_SIZE ==
Contains the combined size of all request parameters. Files are excluded from the calculation. This variable can be useful, for example, to create a rule to ensure that the total size of the argument data is below a certain threshold. The following rule detects a request whose para- meters are more than 2500 bytes long:
<code>SecRule ARGS_COMBINED_SIZE "@gt 2500" "id:12"</code>
== ARGS_GET ==
ARGS_GET is similar to ARGS, but contains only query string parameters.
== ARGS_GET_NAMES ==
ARGS_GET_NAMES is similar to ARGS_NAMES, but contains only the names of query string parameters.
== ARGS_NAMES ==
Contains all request parameter names. You can search for specific parameter names that you want to inspect. In a positive policy scenario, you can also whitelist (using an inverted rule with the exclamation mark) only the authorized argument names.
This example rule allows only two argument names: p and a:
<code>SecRule ARGS_NAMES "!^(p|a)$" "id:13"</code>
== ARGS_POST ==
ARGS_POST is similar to ARGS, but only contains arguments from the POST body.
== ARGS_POST_NAMES ==
ARGS_POST_NAMES is similar to ARGS_NAMES, but contains only the names of request body parameters.
== AUTH_TYPE ==
This variable holds the authentication method used to validate a user, if any of the methods built into HTTP are used. In a reverse-proxy deployment, this information will not be available if the authentication is handled in the backend web server.
<code>SecRule AUTH_TYPE "Basic" "id:14"</code>
== DURATION ==
Contains the number of milliseconds elapsed since the beginning of the current transaction. Available starting with 2.6.0.
; Note : Starting with ModSecurity 2.7.0 the time is microseconds.
== ENV ==
Collection that provides access to environment variables set by ModSecurity or other server modules. Requires a single parameter to specify the name of the desired variable.
<pre>
# Set environment variable
SecRule REQUEST_FILENAME "printenv" \
"phase:2,id:15,pass,setenv:tag=suspicious"
# Inspect environment variable
SecRule ENV:tag "suspicious" "id:16"
# Reading an environment variable from other Apache module (mod_ssl)
SecRule TX:ANOMALY_SCORE "@gt 0" "phase:5,id:16,msg:'%{env.ssl_cipher}'"
</pre>
; Note : Use setenv to set environment variables to be accessed by Apache.
== FILES ==
Contains a collection of original file names (as they were called on the remote users filesys- tem). Available only on inspected multipart/form-data requests.
<code>SecRule FILES "@rx \.conf$" "id:17"</code>
; Note : Only available if files were extracted from the request body.
== FILES_COMBINED_SIZE ==
Contains the total size of the files transported in request body. Available only on inspected multipart/form-data requests.
<code>SecRule FILES_COMBINED_SIZE "@gt 100000" "id:18"</code>
== FILES_NAMES ==
Contains a list of form fields that were used for file upload. Available only on inspected multipart/form-data requests.
<code>SecRule FILES_NAMES "^upfile$" "id:19"</code>
== FULL_REQUEST ==
Contains the complete request: Request line, Request headers and Request body (if any).
The last available only if SecRequestBodyAccess was set to On. Note that all properties of SecRequestBodyAccess will be respected here, such as: SecRequestBodyLimit.
<code>SecRule FULL_REQUEST "User-Agent: ModSecurity Regression Tests" "id:21"</code>
; Note : Available on version 2.8.0+
== FULL_REQUEST_LENGTH ==
Represents the amount of bytes that FULL_REQUEST may use.
<code>SecRule FULL_REQUEST_LENGTH "@eq 205" "id:21"</code>
; Note : Available on version 2.8.0+
== FILES_SIZES ==
Contains a list of individual file sizes. Useful for implementing a size limitation on individual uploaded files. Available only on inspected multipart/form-data requests.
<code>SecRule FILES_SIZES "@gt 100" "id:20"</code>
== FILES_TMPNAMES ==
Contains a list of temporary files names on the disk. Useful when used together with @inspectFile. Available only on inspected multipart/form-data requests.
<code>SecRule FILES_TMPNAMES "@inspectFile /path/to/inspect_script.pl" "id:21"</code>
== FILES_TMP_CONTENT ==
Contains a key-value set where value is the content of the file which was uploaded.
Useful when used together with @fuzzyHash.
<code>SecRule FILES_TMP_CONTENT "@fuzzyHash $ENV{CONF_DIR}/ssdeep.txt 1" "id:192372,log,deny"</code>
; Note : Available on version 2.9.0-RC1+
; Note II : SecUploadKeepFiles should be set to 'On' in order to have this collection filled.
== GEO ==
GEO is a collection populated by the results of the last @geoLookup operator. The collection can be used to match geographical fields looked from an IP address or hostname.
Available since ModSecurity 2.5.0.
Fields:
*COUNTRY_CODE: Two character country code. EX: US, GB, etc.
*COUNTRY_CODE3: Up to three character country code.
*COUNTRY_NAME: The full country name.
*COUNTRY_CONTINENT: The two character continent that the country is located. EX: EU
*REGION: The two character region. For US, this is state. For Canada, providence, etc.
*CITY: The city name if supported by the database.
*POSTAL_CODE: The postal code if supported by the database.
*LATITUDE: The latitude if supported by the database.
*LONGITUDE: The longitude if supported by the database.
*DMA_CODE: The metropolitan area code if supported by the database. (US only)
*AREA_CODE: The phone system area code. (US only)
Example:
<pre>
SecGeoLookupDb /usr/local/geo/data/GeoLiteCity.dat
...
SecRule REMOTE_ADDR "@geoLookup" "chain,id:22,drop,msg:'Non-GB IP address'"
SecRule GEO:COUNTRY_CODE "!@streq GB"
</pre>
== HIGHEST_SEVERITY ==
This variable holds the highest severity of any rules that have matched so far. Severities are numeric values and thus can be used with comparison operators such as @lt, and so on. A value of 255 indicates that no severity has been set.
<code>SecRule HIGHEST_SEVERITY "@le 2" "phase:2,id:23,deny,status:500,msg:'severity %{HIGHEST_SEVERITY}'"</code>
; Note : Higher severities have a lower numeric value.
== INBOUND_DATA_ERROR ==
This variable will be set to 1 when the request body size is above the setting configured by SecRequestBodyLimit directive. Your policies should always contain a rule to check this variable. Depending on the rate of false positives and your default policy you should decide whether to block or just warn when the rule is triggered.
The best way to use this variable is as in the example below:
<code>SecRule INBOUND_DATA_ERROR "@eq 1" "phase:1,id:24,t:none,log,pass,msg:'Request Body Larger than SecRequestBodyLimit Setting'"</code>
== MATCHED_VAR ==
This variable holds the value of the most-recently matched variable. It is similar to the TX:0, but it is automatically supported by all operators and there is no need to specify the capture action.
<pre>
SecRule ARGS pattern chain,deny,id:25
SecRule MATCHED_VAR "further scrutiny"
</pre>
; Note : Be aware that this variable holds data for the '''''last''''' operator match. This means that if there are more than one matches, only the last one will be populated. Use MATCHED_VARS variable if you want all matches.
== MATCHED_VARS ==
Similar to MATCHED_VAR except that it is a collection of '''''all matches''''' for the current operator check.
<pre>
SecRule ARGS pattern "chain,deny,id:26"
SecRule MATCHED_VARS "@eq ARGS:param"
</pre>
== MATCHED_VAR_NAME ==
This variable holds the full name of the variable that was matched against.
<pre>
SecRule ARGS pattern "chain,deny,id:27"
SecRule MATCHED_VAR_NAME "@eq ARGS:param"
</pre>
; Note : Be aware that this variable holds data for the '''''last''''' operator match. This means that if there are more than one matches, only the last one will be populated. Use MATCHED_VARS_NAMES variable if you want all matches.
== MATCHED_VARS_NAMES ==
Similar to MATCHED_VAR_NAME except that it is a collection of '''''all matches''''' for the current operator check.
<pre>
SecRule ARGS pattern "chain,deny,id:28"
SecRule MATCHED_VARS_NAMES "@eq ARGS:param"
</pre>
== MODSEC_BUILD ==
This variable holds the ModSecurity build number. This variable is intended to be used to check the build number prior to using a feature that is available only in a certain build. Example:
<pre>
SecRule MODSEC_BUILD "!@ge 02050102" "skipAfter:12345,id:29"
SecRule ARGS "@pm some key words" "id:12345,deny,status:500"
</pre>
== MULTIPART_CRLF_LF_LINES ==
This flag variable will be set to 1 whenever a multi-part request uses mixed line terminators. The multipart/form-data RFC requires CRLF sequence to be used to terminate lines. Since some client implementations use only LF to terminate lines you might want to allow them to proceed under certain circumstances (if you want to do this you will need to stop using MULTIPART_STRICT_ERROR and check each multi-part flag variable individually, avoiding MULTIPART_LF_LINE). However, mixing CRLF and LF line terminators is dangerous as it can allow for evasion. Therefore, in such cases, you will have to add a check for MULTIPART_CRLF_LF_LINES.
== MULTIPART_FILENAME ==
This variable contains the multipart data from field FILENAME.
== MULTIPART_NAME ==
This variable contains the multipart data from field NAME.
== MULTIPART_STRICT_ERROR ==
MULTIPART_STRICT_ERROR will be set to 1 when any of the following variables is also set to 1: REQBODY_PROCESSOR_ERROR, MULTIPART_BOUNDARY_QUOTED, MULTIPART_BOUNDARY_WHITESPACE, MULTIPART_DATA_BEFORE, MULTIPART_DATA_AFTER, MULTIPART_HEADER_FOLDING, MULTIPART_LF_LINE, MULTIPART_MISSING_SEMICOLON MULTIPART_INVALID_QUOTING MULTIPART_INVALID_HEADER_FOLDING MULTIPART_FILE_LIMIT_EXCEEDED. Each of these variables covers one unusual (although sometimes legal) aspect of the request body in multipart/form-data format. Your policies should always contain a rule to check either this variable (easier) or one or more individual variables (if you know exactly what you want to accomplish). Depending on the rate of false positives and your default policy you should decide whether to block or just warn when the rule is triggered.
The best way to use this variable is as in the example below:
<pre>
SecRule MULTIPART_STRICT_ERROR "!@eq 0" \
"phase:2,id:30,t:none,log,deny,msg:'Multipart request body \
failed strict validation: \
PE %{REQBODY_PROCESSOR_ERROR}, \
BQ %{MULTIPART_BOUNDARY_QUOTED}, \
BW %{MULTIPART_BOUNDARY_WHITESPACE}, \
DB %{MULTIPART_DATA_BEFORE}, \
DA %{MULTIPART_DATA_AFTER}, \
HF %{MULTIPART_HEADER_FOLDING}, \
LF %{MULTIPART_LF_LINE}, \
SM %{MULTIPART_MISSING_SEMICOLON}, \
IQ %{MULTIPART_INVALID_QUOTING}, \
IQ %{MULTIPART_INVALID_HEADER_FOLDING}, \
FE %{MULTIPART_FILE_LIMIT_EXCEEDED}'"
</pre>
The multipart/form-data parser was upgraded in ModSecurity v2.1.3 to actively look for signs of evasion. Many variables (as listed above) were added to expose various facts discovered during the parsing process. The MULTIPART_STRICT_ERROR variable is handy to check on all abnormalities at once. The individual variables allow detection to be fine-tuned according to your circumstances in order to reduce the number of false positives.
== MULTIPART_UNMATCHED_BOUNDARY ==
Set to 1 when, during the parsing phase of a multipart/request-body, ModSecurity encounters what feels like a boundary but it is not. Such an event may occur when evasion of ModSecurity is attempted.
The best way to use this variable is as in the example below:
<pre>
SecRule MULTIPART_UNMATCHED_BOUNDARY "!@eq 0" \
"phase:2,id:31,t:none,log,deny,msg:'Multipart parser detected a possible unmatched boundary.'"
</pre>
Change the rule from blocking to logging-only if many false positives are encountered.
== OUTBOUND_DATA_ERROR ==
This variable will be set to 1 when the response body size is above the setting configured by SecResponseBodyLimit directive. Your policies should always contain a rule to check this variable. Depending on the rate of false positives and your default policy you should decide whether to block or just warn when the rule is triggered.
The best way to use this variable is as in the example below:
<code>SecRule OUTBOUND_DATA_ERROR "@eq 1" "phase:1,id:32,t:none,log,pass,msg:'Response Body Larger than SecResponseBodyLimit Setting'"</code>
== PATH_INFO ==
Contains the extra request URI information, also known as path info. (For example, in the URI /index.php/123, /123 is the path info.) Available only in embedded deployments.
<code>SecRule PATH_INFO "^/(bin|etc|sbin|opt|usr)" "id:33"</code>
== PERF_ALL ==
This special variable contains a string thats a combination of all other performance variables, arranged in the same order in which they appear in the Stopwatch2 audit log header. Its intended for use in custom Apache logs
'''Version:''' 2.6.0-2.9.x
'''Supported on libModSecurity:''' TBI
== PERF_COMBINED ==
Contains the time, in microseconds, spent in ModSecurity during the current transaction. The value in this variable is arrived to by adding all the performance variables except PERF_SREAD (the time spent reading from persistent storage is already included in the phase measurements).
'''Version:''' 2.6.0-2.9.x
'''Supported on libModSecurity:''' TBI
== PERF_GC ==
Contains the time, in microseconds, spent performing garbage collection.
'''Version:''' 2.6.0-2.9.x
'''Supported on libModSecurity:''' TBI
== PERF_LOGGING ==
Contains the time, in microseconds, spent in audit logging. This value is known only after the handling of a transaction is finalized, which means that it can only be logged using mod_log_config and the %{VARNAME}M syntax.
'''Version:''' 2.6.0-2.9.x
'''Supported on libModSecurity:''' TBI
== PERF_PHASE1 ==
Contains the time, in microseconds, spent processing phase 1.
'''Version:''' 2.6.0-2.9.x
'''Supported on libModSecurity:''' TBI
== PERF_PHASE2 ==
Contains the time, in microseconds, spent processing phase 2.
'''Version:''' 2.6.0-2.9.x
'''Supported on libModSecurity:''' TBI
== PERF_PHASE3 ==
Contains the time, in microseconds, spent processing phase 3.
'''Version:''' 2.6.0-2.9.x
'''Supported on libModSecurity:''' TBI
== PERF_PHASE4 ==
Contains the time, in microseconds, spent processing phase 4.
'''Version:''' 2.6.0-2.9.x
'''Supported on libModSecurity:''' TBI
== PERF_PHASE5 ==
Contains the time, in microseconds, spent processing phase 5.
'''Version:''' 2.6.0-2.9.x
'''Supported on libModSecurity:''' TBI
== PERF_RULES ==
PERF_RULES is a collection, that is populated with the rules hitting
the performance threshold defined with SecRulePerfTime. The collection
contains the time, in microseconds, spent processing the individual
rule. The various items in the collection can be accessed via the
rule id.
'''Version:''' 2.7.0-2.9.x
'''Supported on libModSecurity:''' TBI
<pre>
SecRulePerfTime 100
SecRule FILES_TMPNAMES "@inspectFile /path/to/util/runav.pl" \
"phase:2,id:10001,deny,log,msg:'Virus scan detected an error.'"
SecRule &PERF_RULES "@eq 0" "phase:5,id:95000,\
pass,log,msg:'All rules performed below processing time limit.'"
SecRule PERF_RULES "@ge 1000" "phase:5,id:95001,pass,log,\
msg:'Rule %{MATCHED_VAR_NAME} spent at least 1000 usec.'"
SecAction "phase:5,id:95002,pass,log, msg:'File inspection took %{PERF_RULES.10001} usec.'"
</pre>
The rule with id 10001 defines an external file inspection rule.
The rule with id 95000 checks the size of the PERF_RULES collection.
If the collection is empty, it writes a note in the logfile.
Rule 95001 is executed for every item in the PERF_RULES collection.
Every item is thus being checked against the limit of 1000 microseconds.
If the rule spent at least that amount of time, then a note containing
the rule id is being written to the logfile.
The final rule 95002 notes the time spent in rule 10001 (the virus
inspection).
== PERF_SREAD ==
Contains the time, in microseconds, spent reading from persistent storage.
'''Version:''' 2.6.0-2.9.x
'''Supported on libModSecurity:''' TBI
== PERF_SWRITE ==
Contains the time, in microseconds, spent writing to persistent storage.
'''Version:''' 2.6.0-2.9.x
'''Supported on libModSecurity:''' TBI
== QUERY_STRING ==
Contains the query string part of a request URI. The value in QUERY_STRING is always provided raw, without URL decoding taking place.
<code>SecRule QUERY_STRING "attack" "id:34"</code>
== REMOTE_ADDR ==
This variable holds the IP address of the remote client.
<code>SecRule REMOTE_ADDR "@ipMatch 192.168.1.101" "id:35"</code>
== REMOTE_HOST ==
If the Apache directive HostnameLookups is set to On, then this variable will hold the remote hostname resolved through DNS. If the directive is set to Off, this variable it will hold the remote IP address (same as REMOTE_ADDR). Possible uses for this variable would be to deny known bad client hosts or network blocks, or conversely, to allow in authorized hosts.
<code>SecRule REMOTE_HOST "\.evil\.network\org$" "id:36"</code>
== REMOTE_PORT ==
This variable holds information on the source port that the client used when initiating the connection to our web server.
In the following example, we are evaluating to see whether the REMOTE_PORT is less than 1024, which would indicate that the user is a privileged user:
<code>SecRule REMOTE_PORT "@lt 1024" "id:37"</code>
== REMOTE_USER ==
This variable holds the username of the authenticated user. If there are no password access controls in place (Basic or Digest authentication), then this variable will be empty.
<code>SecRule REMOTE_USER "@streq admin" "id:38"</code>
; Note : In a reverse-proxy deployment, this information will not be available if the authentication is handled in the backend web server.
== REQBODY_ERROR ==
Contains the status of the request body processor used for request body parsing. The values can be 0 (no error) or 1 (error). This variable will be set by request body processors (typically the multipart/request-data parser, JSON or the XML parser) when they fail to do their work.
<code>SecRule REQBODY_ERROR "@eq 1" deny,phase:2,id:39 </code>
; Note : Your policies must have a rule to check for request body processor errors at the very beginning of phase 2. Failure to do so will leave the door open for impedance mismatch attacks. It is possible, for example, that a payload that cannot be parsed by ModSecurity can be successfully parsed by more tolerant parser operating in the application. If your policy dictates blocking, then you should reject the request if error is detected. When operating in detection-only mode, your rule should alert with high severity when request body processing fails.
; Related issues: #1475
== REQBODY_ERROR_MSG ==
If theres been an error during request body parsing, the variable will contain the following error message:
<code>SecRule REQBODY_ERROR_MSG "failed to parse" "id:40"</code>
== REQBODY_PROCESSOR ==
Contains the name of the currently used request body processor. The possible values are URLENCODED, MULTIPART, and XML.
<pre>
SecRule REQBODY_PROCESSOR "^XML$ chain,id:41
SecRule XML "@validateDTD /opt/apache-frontend/conf/xml.dtd"
</pre>
== REQUEST_BASENAME ==
This variable holds just the filename part of REQUEST_FILENAME (e.g., index.php).
<code>SecRule REQUEST_BASENAME "^login\.php$" phase:2,id:42,t:none,t:lowercase</code>
; Note : Please note that anti-evasion transformations are not applied to this variable by default. REQUEST_BASENAME will recognise both / and \ as path separators. You should understand that the value of this variable depends on what was provided in request, and that it does not have to correspond to the resource (on disk) that will be used by the web server.
== REQUEST_BODY ==
Holds the raw request body. This variable is available only if the URLENCODED request body processor was used, which will occur by default when the application/x-www-form-urlencoded content type is detected, or if the use of the URLENCODED request body parser was forced.
<code>SecRule REQUEST_BODY "^username=\w{25,}\&password=\w{25,}\&Submit\=login$" "id:43"</code>
As of 2.5.7, it is possible to force the presence of the REQUEST_BODY variable, but only when there is no request body processor defined using the ctl:forceRequestBodyVariable option in the REQUEST_HEADERS phase.
== REQUEST_BODY_LENGTH ==
Contains the number of bytes read from a request body. Available starting with v2.6
== REQUEST_COOKIES ==
This variable is a collection of all of request cookies (values only). Example: the following example is using the Ampersand special operator to count how many variables are in the collection. In this rule, it would trigger if the request does not include any Cookie headers.
<code>SecRule &REQUEST_COOKIES "@eq 0" "id:44"</code>
== REQUEST_COOKIES_NAMES ==
This variable is a collection of the names of all request cookies. For example, the following rule will trigger if the JSESSIONID cookie is not present:
<code>SecRule &REQUEST_COOKIES_NAMES:JSESSIONID "@eq 0" "id:45"</code>
== REQUEST_FILENAME ==
This variable holds the relative request URL without the query string part (e.g., /index.php).
<code>SecRule REQUEST_FILENAME "^/cgi-bin/login\.php$" phase:2,id:46,t:none,t:normalizePath</code>
; Note : Please note that anti-evasion transformations are not used on REQUEST_FILENAME, which means that you will have to specify them in the rules that use this variable.
== REQUEST_HEADERS ==
This variable can be used as either a collection of all of the request headers or can be used to inspect selected headers (by using the REQUEST_HEADERS:Header-Name syntax).
<code>SecRule REQUEST_HEADERS:Host "^[\d\.]+$" "deny,id:47,log,status:400,msg:'Host header is a numeric IP address'"</code>
; Note: ModSecurity will treat multiple headers that have identical names in accordance with how the webserver treats them. For Apache this means that they will all be concatenated into a single header with a comma as the deliminator.
== REQUEST_HEADERS_NAMES ==
This variable is a collection of the names of all of the request headers.
<code>SecRule REQUEST_HEADERS_NAMES "^x-forwarded-for" "log,deny,id:48,status:403,t:lowercase,msg:'Proxy Server Used'"</code>
== REQUEST_LINE ==
This variable holds the complete request line sent to the server (including the request method and HTTP version information).
<pre>
# Allow only POST, GET and HEAD request methods, as well as only
# the valid protocol versions
SecRule REQUEST_LINE "!(^((?:(?:POS|GE)T|HEAD))|HTTP/(0\.9|1\.0|1\.1)$)" "phase:1,id:49,log,block,t:none"
</pre>
== REQUEST_METHOD ==
This variable holds the request method used in the transaction.
<code>SecRule REQUEST_METHOD "^(?:CONNECT|TRACE)$" "id:50,t:none"</code>
== REQUEST_PROTOCOL ==
This variable holds the request protocol version information.
<code>SecRule REQUEST_PROTOCOL "!^HTTP/(0\.9|1\.0|1\.1)$" "id:51"</code>
== REQUEST_URI ==
This variable holds the full request URL including the query string data (e.g., /index.php? p=X). However, it will never contain a domain name, even if it was provided on the request line.
<code>SecRule REQUEST_URI "attack" "phase:1,id:52,t:none,t:urlDecode,t:lowercase,t:normalizePath"</code>
; Note : Please note that anti-evasion transformations are not used on REQUEST_URI, which means that you will have to specify them in the rules that use this variable.
== REQUEST_URI_RAW ==
Same as REQUEST_URI but will contain the domain name if it was provided on the request line (e.g., http://www.example.com/index.php?p=X).
<code>SecRule REQUEST_URI_RAW "http:/" "phase:1,id:53,t:none,t:urlDecode,t:lowercase,t:normalizePath"</code>
; Note : Please note that anti-evasion transformations are not used on REQUEST_URI_RAW, which means that you will have to specify them in the rules that use this variable.
== RESPONSE_BODY ==
This variable holds the data for the response body, but only when response body buffering is enabled.
<code>SecRule RESPONSE_BODY "ODBC Error Code" "phase:4,id:54,t:none"</code>
== RESPONSE_CONTENT_LENGTH ==
Response body length in bytes. Can be available starting with phase 3, but it does not have to be (as the length of response body is not always known in advance). If the size is not known, this variable will contain a zero. If RESPONSE_CONTENT_LENGTH contains a zero in phase 5 that means the actual size of the response body was 0. The value of this variable can change between phases if the body is modified. For example, in embedded mode, mod_deflate can compress the response body between phases 4 and 5.
== RESPONSE_CONTENT_TYPE ==
Response content type. Available only starting with phase 3. The value available in this variable is taken directly from the internal structures of Apache, which means that it may contain the information that is not yet available in response headers. In embedded deployments, you should always refer to this variable, rather than to RESPONSE_HEADERS:Content-Type.
== RESPONSE_HEADERS ==
This variable refers to response headers, in the same way as REQUEST_HEADERS does to request headers.
<code>SecRule RESPONSE_HEADERS:X-Cache "MISS" "id:55"</code>
This variable may not have access to some headers when running in embedded mode. Headers such as Server, Date, Connection, and Content-Type could be added just prior to sending the data to the client. This data should be available in phase 5 or when deployed in proxy mode.
== RESPONSE_HEADERS_NAMES ==
This variable is a collection of the response header names.
<code>SecRule RESPONSE_HEADERS_NAMES "Set-Cookie" "phase:3,id:56,t:none"</code>
The same limitations apply as the ones discussed in RESPONSE_HEADERS.
== RESPONSE_PROTOCOL ==
This variable holds the HTTP response protocol information.
<code>SecRule RESPONSE_PROTOCOL "^HTTP\/0\.9" "phase:3,id:57,t:none"</code>
== RESPONSE_STATUS ==
This variable holds the HTTP response status code:
<code>SecRule RESPONSE_STATUS "^[45]" "phase:3,id:58,t:none"</code>
This variable may not work as expected in embedded mode, as Apache sometimes handles certain requests differently, and without invoking ModSecurity (all other modules).
== RULE ==
This is a special collection that provides access to the id, rev, severity, logdata, and msg fields of the rule that triggered the action. It can be used to refer to only the same rule in which it resides.
<code>SecRule &REQUEST_HEADERS:Host "@eq 0" "log,deny,id:59,setvar:tx.varname=%{RULE.id}"</code>
== SCRIPT_BASENAME ==
This variable holds just the local filename part of SCRIPT_FILENAME.
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
<code>SecRule SCRIPT_BASENAME "^login\.php$" "id:60"</code>
; Note : Not available in proxy mode.
== SCRIPT_FILENAME ==
This variable holds the full internal path to the script that will be used to serve the request.
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
<code>SecRule SCRIPT_FILENAME "^/usr/local/apache/cgi-bin/login\.php$" "id:61"</code>
; Note : Not available in proxy mode.
== SCRIPT_GID ==
This variable holds the numerical identifier of the group owner of the script.
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
<code>SecRule SCRIPT_GID "!^46$" "id:62"</code>
; Note : Not available in proxy mode.
== SCRIPT_GROUPNAME ==
This variable holds the name of the group owner of the script.
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
<code>SecRule SCRIPT_GROUPNAME "!^apache$" "id:63"</code>
; Note : Not available in proxy mode.
== SCRIPT_MODE ==
This variable holds the scripts permissions mode data (e.g., 644).
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
<pre>
# Do not allow scripts that can be written to
SecRule SCRIPT_MODE "^(2|3|6|7)$" "id:64"
</pre>
; Note : Not available in proxy mode.
== SCRIPT_UID ==
This variable holds the numerical identifier of the owner of the script.
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
<pre>
# Do not run any scripts that are owned
# by Apache (Apache's user id is 46)
SecRule SCRIPT_UID "!^46$" "id:65"
</pre>
; Note : Not available in proxy mode.
== SCRIPT_USERNAME ==
This variable holds the username of the owner of the script.
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
<pre>
# Do not run any scripts owned by Apache SecRule
SCRIPT_USERNAME "^apache$" "id:66"
</pre>
; Note : Not available in proxy mode.
== SDBM_DELETE_ERROR ==
'''Version:''' 2.x
'''Supported on libModSecurity:''' No
This variable is set to 1 when APR fails to delete SDBM entries.
== SERVER_ADDR ==
This variable contains the IP address of the server.
<code>SecRule SERVER_ADDR "@ipMatch 192.168.1.100" "id:67"</code>
== SERVER_NAME ==
This variable contains the transactions hostname or IP address, taken from the request itself (which means that, in principle, it should not be trusted).
<code>SecRule SERVER_NAME "hostname\.com$" "id:68"</code>
== SERVER_PORT ==
This variable contains the local port that the web server (or reverse proxy) is listening on.
<code>SecRule SERVER_PORT "^80$" "id:69"</code>
== SESSION ==
This variable is a collection that contains session information. It becomes available only after setsid is executed.
The following example shows how to initialize SESSION using setsid, how to use setvar to increase the SESSION.score values, how to set the SESSION.blocked variable, and finally, how to deny the connection based on the SESSION:blocked value:
<pre>
# Initialize session storage
SecRule REQUEST_COOKIES:PHPSESSID !^$ "phase:2,id:70,nolog,pass,setsid:%{REQUEST_COOKIES.PHPSESSID}"
# Increment session score on attack
SecRule REQUEST_URI "^/cgi-bin/finger$" "phase:2,id:71,t:none,t:lowercase,t:normalizePath,pass,setvar:SESSION.score=+10"
# Detect too many attacks in a session
SecRule SESSION:score "@gt 50" "phase:2,id:72,pass,setvar:SESSION.blocked=1"
# Enforce session block
SecRule SESSION:blocked "@eq 1" "phase:2,id:73,deny,status:403"
</pre>
== SESSIONID ==
This variable contains the value set with setsid. See SESSION (above) for a complete example.
== STATUS_LINE ==
This variable holds the full status line sent by the server (including the request method and HTTP version information).
<pre>
# Generate an alert when the application generates 500 errors.
SecRule STATUS_LINE "@contains 500" "phase:3,id:49,log,pass,logdata:'Application error detected!,t:none"
</pre>
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
== STREAM_INPUT_BODY ==
'''Version:''' 2.6.0-2.9.x
'''Supported on libModSecurity:''' No
This variable give access to the raw request body content. This variable is best used for two use-cases:
#For fast pattern matching - using @pm/@pmf to prequalify large text strings against any kind of content-type data. This is more performant vs. using REQUEST_BODY/ARGS_POST/ARGS_POST_NAMES as it happens before ModSecurity parsing in phase:2 variable population.
#For data substitution - using @rsub against this variable allows you to manipulate live request body data. Example - to remove offending payloads or to substitute benign data.
; Note : You must enable the SecStreamInBodyInspection directive
; Note : This directive is NOT supported for libModSecurity (v3).
== STREAM_OUTPUT_BODY ==
This variable give access to the raw response body content. This variable is best used for case:
#For data substitution - using @rsub against this variable allows you to manipulate live request body data. Example - to remove offending payloads or to substitute benign data.
'''Version:''' 2.6.0-2.9.x
'''Supported on libModSecurity:''' TBD
; Note : You must enable the SecStreamOutBodyInspection directive
== TIME ==
This variable holds a formatted string representing the time (hour:minute:second).
<code>SecRule TIME "^(([1](8|9))|([2](0|1|2|3))):\d{2}:\d{2}$" "id:74"</code>
== TIME_DAY ==
This variable holds the current date (131). The following rule triggers on a transaction thats happening anytime between the 10th and 20th in a month:
<code>SecRule TIME_DAY "^(([1](0|1|2|3|4|5|6|7|8|9))|20)$" "id:75"</code>
== TIME_EPOCH ==
This variable holds the time in seconds since 1970.
== TIME_HOUR ==
This variable holds the current hour value (023). The following rule triggers when a request is made “off hours”:
<code>SecRule TIME_HOUR "^(0|1|2|3|4|5|6|[1](8|9)|[2](0|1|2|3))$" "id:76"</code>
== TIME_MIN ==
This variable holds the current minute value (059). The following rule triggers during the last half hour of every hour:
<code>SecRule TIME_MIN "^(3|4|5)" "id:77"</code>
== TIME_MON ==
This variable holds the current month value (011). The following rule matches if the month is either November (value 10) or December (value 11):
<code>SecRule TIME_MON "^1" "id:78"</code>
== TIME_SEC ==
This variable holds the current second value (059).
<code>SecRule TIME_SEC "@gt 30" "id:79"</code>
== TIME_WDAY ==
This variable holds the current weekday value (06). The following rule triggers only on Satur- day and Sunday:
<code>SecRule TIME_WDAY "^(0|6)$" "id:80"</code>
== TIME_YEAR ==
This variable holds the current four-digit year value.
<code>SecRule TIME_YEAR "^2006$" "id:81"</code>
== TX ==
This is the transient transaction collection, which is used to store pieces of data, create a transaction anomaly score, and so on. The variables placed into this collection are available only until the transaction is complete.
<pre>
# Increment transaction attack score on attack
SecRule ARGS attack "phase:2,id:82,nolog,pass,setvar:TX.score=+5"
# Block the transactions whose scores are too high
SecRule TX:SCORE "@gt 20" "phase:2,id:83,log,deny"
</pre>
Some variable names in the TX collection are reserved and cannot be used:
*TX:0: the matching value when using the @rx or @pm operator with the capture action
*TX:1-TX:9: the captured subexpression value when using the @rx operator with capturing parens and the capture action
*TX:MSC_.*: ModSecurity processing flags
*MSC_PCRE_LIMITS_EXCEEDED: Set to nonzero if PCRE match limits are exceeded. See SecPcreMatchLimit and SecPcreMatchLimitRecursion for more information.
== UNIQUE_ID ==
This variable holds the data created by mod_unique_id [http://httpd.apache.org/docs/2.2/mod/mod_unique_id.html]. This module provides a magic token for each request which is guaranteed to be unique across "all" requests under very specific conditions. The unique identifier is even unique across multiple machines in a properly configured cluster of machines. The environment variable UNIQUE_ID is set to the identifier for each request. The UNIQUE_ID environment variable is constructed by encoding the 112-bit (32-bit IP address, 32 bit pid, 32 bit time stamp, 16 bit counter) quadruple using the alphabet [A-Za-z0-9@-] in a manner similar to MIME base64 encoding, producing 19 characters.
== URLENCODED_ERROR ==
This variable is created when an invalid URL encoding is encountered during the parsing of a query string (on every request) or during the parsing of an application/x-www-form-urlencoded request body (only on the requests that use the URLENCODED request body processor).
== USERID ==
This variable contains the value set with setuid.
<pre>
# Initialize user tracking
SecAction "nolog,id:84,pass,setuid:%{REMOTE_USER}"
# Is the current user the administrator?
SecRule USERID "admin" "id:85"
</pre>
== USERAGENT_IP ==
This variable is created when running modsecurity with apache2.4 and will contains the client ip address set by mod_remoteip in proxied connections.
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
== WEBAPPID ==
This variable contains the current application name, which is set in configuration using SecWebAppId.
'''Version:''' 2.0.0-2.9.x
'''Supported on libModSecurity:''' TBI
== WEBSERVER_ERROR_LOG ==
'''Version:''' 2.x
'''Supported on libModSecurity:''' TBI
Contains zero or more error messages produced by the web server. This variable is best accessed from phase 5 (logging).
<code>SecRule WEBSERVER_ERROR_LOG "File does not exist" "phase:5,id:86,t:none,nolog,pass,setvar:TX.score=+5"</code>
== XML ==
Special collection used to interact with the XML parser. It can be used standalone as a target for the validateDTD and validateSchema operator. Otherwise, it must contain a valid XPath expression, which will then be evaluated against a previously parsed XML DOM tree.
<pre>
SecDefaultAction log,deny,status:403,phase:2,id:90
SecRule REQUEST_HEADERS:Content-Type ^text/xml$ "phase:1,id:87,t:lowercase,nolog,pass,ctl:requestBodyProcessor=XML"
SecRule REQBODY_PROCESSOR "!^XML$" skipAfter:12345,id:88
SecRule XML:/employees/employee/name/text() Fred "id:89"
SecRule XML:/xq:employees/employee/name/text() Fred "id:12345,xmlns:xq=http://www.example.com/employees"
</pre>
The first XPath expression does not use namespaces. It would match against payload such as this one:
<pre>
<employees>
<employee>
<name>Fred Jones</name>
<address location="home">
<street>900 Aurora Ave.</street>
<city>Seattle</city>
<state>WA</state>
<zip>98115</zip>
</address>
<address location="work">
<street>2011 152nd Avenue NE</street>
<city>Redmond</city>
<state>WA</state>
<zip>98052</zip>
</address>
<phone location="work">(425)555-5665</phone>
<phone location="home">(206)555-5555</phone>
<phone location="mobile">(206)555-4321</phone>
</employee>
</employees>
</pre>
The second XPath expression does use namespaces. It would match the following payload:
<pre>
<xq:employees xmlns:xq="http://www.example.com/employees">
<employee>
<name>Fred Jones</name>
<address location="home">
<street>900 Aurora Ave.</street>
<city>Seattle</city>
<state>WA</state>
<zip>98115</zip>
</address>
<address location="work">
<street>2011 152nd Avenue NE</street>
<city>Redmond</city>
<state>WA</state>
<zip>98052</zip>
</address>
<phone location="work">(425)555-5665</phone>
<phone location="home">(206)555-5555</phone>
<phone location="mobile">(206)555-4321</phone>
</employee>
</xq:employees>
</pre>
Note the different namespace used in the second example.