ModSecurity

Configuration Directives

The following section outlines all of the ModSecurity directives. Most of the ModSecurity directives can be used inside the various Apache Scope Directives such as VirtualHost, Location, LocationMatch, Directory, etc... There are others, however, that can only be used once in the main configuration file. This information is specified in the Scope sections below.

These rules, along with the Core rules files, should be contained is files outside of the httpd.conf file and called up with Apache "Include" directives. This allows for easier updating/migration of the rules. If you create your own custom rules that you would like to use with the Core rules, you should create a file called - modsecurity_crs_15_customrules.conf and place it in the same directory as the Core rules files. By using this file name, your custom rules will be called up after the standard ModSecurity Core rules configuration file but before the other Core rules. This allows your rules to be evaluate first which can be useful if you need to implement specific "allow" rules or to correct any false positives in the Core rules as they are applied to your site.

Note

It is highly encouraged that you do not edit the Core rules files themselves but rather place all changes (such as SecRuleRemoveByID, etc...) in your custom rules file. This will allow for easier upgrading as newer Core rules are released by Breach Security on the ModSecurity website.

SecAction

Description: Unconditionally processes the action list it receives as the first and only parameter. It accepts one parameter, the syntax of which is identical to the third parameter of SecRule.

Syntax: SecAction action1,action2,action2

Example Usage: SecAction nolog,redirect:http://www.hostname.com

ProcessingPhase: Any

Scope: Any

Dependencies/Notes: None

SecAction is best used when you uncondiationally execute an action. This is explicit triggering whereas the normal Actions are conditional based on data inspection of the request/response. This is a useful directive when you want to run certian actions such as initcol to initialize collections.

SecArgumentSeparator

Description: Specifies which character to use as separator for application/x-www-form-urlencoded content. Defaults to &. Applications are sometimes (very rarely) written to use a semicolon (;).

Syntax: SecArgumentSeparator character

Example Usage: SecArgumentSeparator ;

Processing Phase: Any

Scope: Main

Dependencies/Notes: None

This directive is needed if a backend web appliaction is using a non-standard argument separator. If this directive is not set properly for each web app, then ModSecurity will not be able to parse the arguements appropriately and the effectiveness of the rule matching will be significantly decreased.

SecAuditEngine

Description: Configures the audit logging engine.

Syntax: SecAuditEngine On|Off|RelevantOnly

Example Usage: SecAuditEngine On

Processing Phase: N/A

Scope: Any

Dependencies/Notes: Can be set/changed with the "ctl" action for the current transaction.

Example: The following example shows the various audit directives used together.

SecAuditEngine RelevantOnly 
SecAuditLog logs/audit/audit.log
SecAuditLogParts ABCFHZ
SecAuditLogType concurrent
SecAuditLogStorageDir logs/audit
SecAuditLogRelevantStatus ^[45]

Possible values are:

  • On - log all transactions by default.

  • Off - do not log transactions by default.

  • RelevantOnly - by default only log transactions that have triggered a warning or an error, or have a status code that is considered to be relevant (see SecAuditLogRelevantStatus).

SecAuditLog

Description: Defines the path to the main audit log file.

Syntax: SecAuditLog /path/to/auditlog

Example Usage: SecAuditLog /usr/local/apache/logs/audit.log

Processing Phase: N/A

Scope: Any

Dependencies/Notes: This file is open on startup when the server typically still runs as root. You should not allow non-root users to have write privileges for this file or for the directory it is stored in..

This file will be used to store the audit log entries if serial audit logging format is used. If concurrent audit logging format is used this file will be used as an index, and contain a record of all audit log files created. If you are planning to use Concurrent audit logging and sending your audit log data off to a remote Console host, then you will need to use the modsec-auditlog-collector.pl script and use the following format:

SecAuditLog \
  "|/path/modsec-auditlog-collector.pl /path/SecAuditLogDataDir /path/SecAuditLog"

SecAuditLog2

Description: Defines the path to the secondary audit log index file when concurrent logging is enabled. See SecAuditLog2 for more details.

Syntax: SecAuditLog2 /path/to/auditlog2

Example Usage: SecAuditLog2 /usr/local/apache/logs/audit2.log

Processing Phase: N/A

Scope: Any

Dependencies/Notes: A main audit log must be defined via SecAuditLog before this directive may be used. Additionally, this log is only used for replicating the main audit log index file when concurrent audit logging is used. It will not be used for non-concurrent audit logging.

SecAuditLogParts

Description: Defines the path to the main audit log file.

Syntax: SecAuditLogParts PARTS

Example Usage: SecAuditLogParts ABCFHZ

Processing Phase: N/A

Scope: Any

Dependencies/Notes: At this time ModSecurity does not log response bodies of stock Apache responses (e.g. 404), or the Server and Date response headers.

Default: ABCFHZ.

Available audit log parts:

  • A - audit log header (mandatory)

  • B - request headers

  • C - request body (present only if the request body exists and ModSecurity is configured to intercept it)

  • D - RESERVED for intermediary response headers, not implemented yet.

  • E - intermediary response body (present only if ModSecurity is configured to intercept response bodies, and if the audit log engine is configured to record it). Intermediary response body is the same as the actual response body unless ModSecurity intercepts the intermediary response body, in which case the actual response body will contain the error message (either the Apache default error message, or the ErrorDocument page).

  • F - final response headers (excluding the Date and Server headers, which are always added by Apache in the late stage of content delivery).

  • G - RESERVED for the actual response body, not implemented yet.

  • H - audit log trailer

  • I - This part is a replacement for part C. It will log the same data as C in all cases except when multipart/form-data encoding in used. In this case it will log a fake application/x-www-form-urlencoded body that contains the information about parameters but not about the files. This is handy if you don't want to have (often large) files stored in your audit logs.

  • J - RESERVED. This part, when implemented, will contain information about the files uploaded using multipart/form-data encoding.

  • Z - final boundary, signifies the end of the entry (mandatory)

SecAuditLogRelevantStatus

Description: Configures which response status code is to be considered relevant for the purpose of audit logging.

Syntax: SecAuditLogRelevantStatus REGEX

Example Usage: SecAuditLogRelevantStatus ^[45]

Processing Phase: N/A

Scope: Any

Dependencies/Notes: Must have the SecAuditEngine set to RelevantOnly. The parameter is a regular expression.

The main purpose of this directive is to allow you to configure audit logging for only transactions that generate the specified HTTP Response Status Code. This directive is often used to the decrease the total size of the audit log file. Keep in mind that if this parameter is used, then successful attacks that result in a 200 OK status code will not be logged.

SecAuditLogStorageDir

Description: Configures the storage directory where concurrent audit log entries are to be stored.

Syntax: SecAuditLogStorageDir /path/to/storage/dir

Example Usage: SecAuditLogStorageDir /usr/local/apache/logs/audit

Processing Phase: N/A

Scope: Any

Dependencies/Notes: SecAuditLogType must be set to Concurrent. The directory must already be created before starting Apache and it must be writable by the web server user as new files are generated at runtime.

As with all logging mechanisms, ensure that you specify a file system location that has adequate disk space and is not on the root partition.

SecAuditLogType

Description: Configures the type of audit logging mechanism to be used.

Syntax: SecAuditLogType Serial|Concurrent

Example Usage: SecAuditLogType Serial

Processing Phase: N/A

Scope: Any

Dependencies/Notes: Must specify SecAuditLogStorageDir if you use concurrent logging.

Possible values are:

  1. Serial - all audit log entries will be stored in the main audit logging file. This is more convenient for casual use but it is slower as only one audit log entry can be written to the file at any one file.

  2. Concurrent - audit log entries will be stored in separate files, one for each transaction. Concurrent logging is the mode to use if you are going to send the audit log data off to a remote ModSecurity Console host.

SecChrootDir

Description: Configures the directory path that will be used to jail the web server process.

Syntax: SecChrootDir /path/to/chroot/dir

Example Usage: SecChrootDir /chroot

Processing Phase: N/A

Scope: Main

Dependencies/Notes: The internal chroot functionality provided by ModSecurity works great for simple setups. One example of a simple setup is Apache serving static files only, or running scripts using modules. For more complex setups you should consider building a jail the old-fashioned way. The internal chroot feature should be treated as somewhat experimental. Due to the large number of default and third-party modules available for the Apache web server, it is not possible to verify the internal chroot works reliably with all of them. You are advised to think about your option and make your own decision. In particular, if you are using any of the modules that fork in the module initialisation phase (e.g. mod_fastcgi, mod_fcgid, mod_cgid), you are advised to examine each Apache process and observe its current working directory, process root, and the list of open files.

SecCookieFormat

Description: Selects the cookie format that will be used in the current configuration context.

Syntax: SecCookieFormat 0|1

Example Usage: SecCookieFormat 0

Processing Phase: N/A

Scope: Any

Dependencies/Notes: None

Possible values are:

  • 0 - use version 0 (Netscape) cookies. This is what most applications use. It is the default value.

  • 1 - use version 1 cookies.

SecDataDir

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

Syntax: SecDataDir /path/to/dir

Example Usage: SecDataDir /usr/local/apache/logs/data

Processing Phase: N/A

Scope: Main

Dependencies/Notes: This directive is needed when initcol, setsid an setuid are used. Must be writable by the web server user.

SecDebugLog

Description: Path to the ModSecurity debug log file.

Syntax: SecDebugLog /path/to/modsec-debug.log

Example Usage: SecDebugLog /usr/local/apache/logs/modsec-debug.log

Processing Phase: N/A

Scope: Any

Dependencies/Notes: None

SecDebugLogLevel

Description: Configures the verboseness of the debug log data.

Syntax: SecDebugLogLevel 0|1|2|3|4|5|6|7|8|9

Example Usage: SecDebugLogLevel 4

Processing Phase: N/A

Scope: Any

Dependencies/Notes: Levels 1 - 3 are always sent to the Apache error log. Therefore you can always use level 0 as the default logging level in production. Level 5 is useful when debugging. It is not advisable to use higher logging levels in production as excessive logging can slow down server significantly.

Possible values are:

  • 0 - no logging.

  • 1 - errors (intercepted requests) only.

  • 2 - warnings.

  • 3 - notices.

  • 4 - details of how transactions are handled.

  • 5 - as above, but including information about each piece of information handled.

  • 9 - log everything, including very detailed debugging information.

SecDefaultAction

Description: Defines the default action to take on a rule match.

Syntax: SecDefaultAction action1,action2,action3

Example Usage: SecDefaultAction log,auditlog,deny,status:403,phase:2,t:lowercase

Processing Phase: Any

Scope: Any

Dependencies/Notes: Rules following a SecDefaultAction directive will inherit this setting unless a specific action is specified for an indivdual rule or until another SecDefaultAction is specified.

The default value is:

SecDefaultAction log,auditlog,deny,status:403,phase:2,t:lowercase,t:replaceNulls,t:compressWhitespace

Note

SecDefaultAction must specify a disruptive action and a processing phase.

SecGuardianLog

Description: Configuration directive to use the httpd-guardian script to monitor for Denial of Service (DoS) attacks.

Syntax: SecGuardianLog |/path/to/httpd-guardian

Example Usage: SecGuardianLog |/usr/local/apache/bin/httpd-guardian

Processing Phase: N/A

Scope: Main

Dependencies/Notes: By default httpd-guardian will defend against clients that send more 120 requests in a minute, or more than 360 requests in five minutes.

Since 1.9, ModSecurity supports a new directive, SecGuardianLog, that is designed to send all access data to another program using the piped logging feature. Since Apache is typically deployed in a multi-process fashion, making information sharing difficult, the idea is to deploy a single external process to observe all requests in a stateful manner, providing additional protection.

Development of a state of the art external protection tool will be a focus of subsequent ModSecurity releases. However, a fully functional tool is already available as part of the Apache httpd tools project. The tool is called httpd-guardian and can be used to defend against Denial of Service attacks. It uses the blacklist tool (from the same project) to interact with an iptables-based (Linux) or pf-based (*BSD) firewall, dynamically blacklisting the offending IP addresses. It can also interact with SnortSam (http://www.snortsam.net). Assuming httpd-guardian is already configured (look into the source code for the detailed instructions) you only need to add one line to your Apache configuration to deploy it:

SecGuardianLog |/path/to/httpd-guardian

SecRequestBodyAccess

Description: Configures whether request bodies will be buffered and processed by ModSecurity by default.

Syntax: SecRequestBodyAccess On|Off

Example Usage: SecRequestBodyAccess On

Processing Phase: N/A

Scope: Any

Dependencies/Notes: This directive is required if you plan to inspect POST_PAYLOADS of requests. This directive must be used along with the "phase:2" processing phase action and REQUEST_BODY variable/location. If any of these 3 parts are not configured, you will not be able to inspect the request bodies.

Possible values are:

  • On - access request bodies.

  • Off - do not attempt to access request bodies.

SecRequestBodyLimit

Description: Configures the maximum request body size ModSecurity will accept for buffering.

Syntax: SecRequestBodyLimit NUMBER_IN_BYTES

Example Usage: SecRequestBodyLimit 134217728

Processing Phase: N/A

Scope: Any

Dependencies/Notes: 131072 KB (134217728 bytes) is the default setting. Anything over this limit will be rejected with status code 413 Request Entity Too Large. There is a hard limit of 1 GB.

SecRequestBodyInMemoryLimit

Description: Configures the maximum request body size ModSecurity will store in memory.

Syntax: SecRequestBodyInMemoryLimit NUMBER_IN_BYTES

Example Usage: SecRequestBodyInMemoryLimit 131072

Processing Phase: N/A

Scope: Any

Dependencies/Notes: None

By default the limit is 128 KB:

# Store up to 128 KB in memory
SecRequestBodyInMemoryLimit 131072

SecResponseBodyLimit

Description: Configures the maximum response body size that will be accepted for buffering.

Syntax: SecResponseBodyLimit NUMBER_IN_BYTES

Example Usage: SecResponseBodyLimit 524228

Processing Phase: N/A

Scope: Any

Dependencies/Notes: Anything over this limit will be rejected with status code 500 Internal Server Error. This setting will not affect the responses with MIME types that are not marked for buffering. There is a hard limit of 1 GB.

By default this limit is configured to 512 KB:

# Buffer response bodies of up to 512 KB in length 
SecResponseBodyLimit 524288

SecResponseBodyMimeType

Description: Configures which MIME types are to be considered for response body buffering.

Syntax: SecResponseBodyMimeType mime/type

Example Usage: SecResponseBodyMimeType text/plain text/html

Processing Phase: N/A

Scope: Any

Dependencies/Notes: Multiple SecResponseBodyMimeType directives can be used to add MIME types.

The default value is text/plaintext/html:

SecResponseBodyMimeType text/plain text/html

SecResponseBodyMimeTypesClear

Description: Clears the list of MIME types considered for response body buffering, allowing you to start populating the list from scratch.

Syntax: SecResponseBodyMimeTypesClear

Example Usage: SecResponseBodyMimeTypesClear

Processing Phase: N/A

Scope: Any

Dependencies/Notes: None

SecResponseBodyAccess

Description: Configures whether response bodies are to be buffer and analysed or not.

Syntax: SecResponseBodyAccess On|Off

Example Usage: SecResponseBodyAccess On

Processing Phase: N/A

Scope: Any

Dependencies/Notes: This directive is required if you plan to inspect html responses. This directive must be used along with the "phase:4" processing phase action and RESPONSE_BODY variable/location. If any of these 3 parts are not configured, you will not be able to inspect the response bodies.

Possible values are:

  • On - access response bodies (but only if the MIME type matches, see above).

  • Off - do not attempt to access response bodies.

SecRule

Description: SecRule is the main ModSecurity directive. It is used to analyse data and perform actions based on the results.

Syntax: SecRule VARIABLES OPERATOR [ACTIONS]

Example Usage: SecRule REQUEST_URI "attack"

Processing Phase: Any

Scope: Any

Dependencies/Notes: None

In general, the format of this rule is as follows:

SecRule VARIABLES OPERATOR [ACTIONS]

The second part, OPERATOR, specifies how they are going to be checked. The third (optional) part, ACTIONS, specifies what to do whenever the operator used performs a successful match against a variable.

Variables in rules

The first part, VARIABLES, specifies which variables are to be checked. For example, the following rule will reject a transaction that has the word dirty in the URI:

SecRule REQUEST_URI dirty

Each rule can specify one or more variables:

SecRule REQUEST_URI|QUERY_STRING dirty

There is a third format supported by the selection operator - XPath expression. XPath expressions can only used against the special variable XML, which is available only of the request body was processed as XML.

SecRule XML:/xPath/Expression dirty

Note

As you have just seen, not all collections support all selection operator format types. You should refer to the documentation of each collection to determine what is and isn't supported.

Operators in rules

In the simplest possible case you will use a regular expression pattern as the second rule parameter. This is what we've done in the examples above. If you do this ModSecurity assumes you want to use the rx operator. You can explicitly specify the operator you want to use by using @ as the first character in the second rule parameter:

SecRule REQUEST_URI "@rx dirty"

Note how we had to use double quotes to delimit the second rule parameter. This is because the second parameter now has a whitespace in it. Any number of whitespace characters can follow the name of the operator. If there are any non-whitespace characters there, they will all be treated as a special parameter to the operator. In the case of the regular expression operator the special parameter is the pattern that will be used for comparison.

The @ can be the second character if you are using negation to negate the result returned by the operator:

SecRule &ARGS "!@rx ^0$"

Actions in rules

The third parameter, ACTIONS, can be omitted only because there is a helper feature that specifies the default action list. If the parameter isn't omitted the actions specified in the parameter will be merged with the default action list to create the actual list of actions that will be processed on a rule match.

SecRuleInheritance

Description: Configures whether the current context will inherit rules from the parent context (configuration options are inherited in most cases - you should look up the documentation for every directive to determine if it is inherited or not).

Syntax: SecRuleInheritance On|Off

Example Usage: SecRuleInheritance Off

Processing Phase: Any

Scope: Any

Dependencies/Notes: Resource-specific contexts (e.g. Location, Directory, etc) cannot override phase1 rules configured in the main server or in the virtual server. This is because phase 1 is run early in the request processing process, before Apache maps request to resource. Virtual host context can override phase 1 rules configured in the main server.

Example: The following example shows where ModSecurity may be enabled in the main Apache configuration scope, however you might want to configure your VirtualHosts differently. In the first example, the first virtualhost is not inheriting the ModSecurity main config directives and in the second one it is.

SecRuleEnine On
SecDefaultAction log,pass,phase:2
...  

<VirtualHost *:80>
ServerName app1.com 
ServerAlias www.app1.com
SecRuleInheritance Off
SecDefaultAction log,deny,phase:1,redirect:http://www.site2.com 
... 
</VirtualHost>  

<VirtualHost *:80> 
ServerName app2.com 
ServerAlias www.app2.com
SecRuleInheritance On SecRule ARGS "attack" 
... 
</VirtualHost>

Possible values are:

  • On - inherit rules from the parent context.

  • Off - do not inherit rules from the parent context.

SecRuleEngine

Description: Configures the rules engine.

Syntax: SecRuleEngine On|Off|DetectionOnly

Example Usage: SecRuleEngine On

Processing Phase: Any

Scope: Any

Dependencies/Notes: Thisdirective can also be controled by the ctl action (ctl:ruleEngine=off) for per rule processing.

Possible values are:

  • On - process rules.

  • Off - do not process rules.

  • DetectionOnly - process rules but never intercept transactions, even when rules are configured to do so.

SecRuleRemoveById

Description: Removes matching rules from the parent contexts.

Syntax: SecRuleRemoveById RULEID

Example Usage: SecRuleRemoveByID 1 2 "9000-9010"

Processing Phase: Any

Scope: Any

Dependencies/Notes: This directive supports multiple parameters, where each parameter can either be a rule ID, or a range. Parameters that contain spaces must be delimited using double quotes.

SecRuleRemoveById 1 2 5 10-20 "400-556" 673

SecRuleRemoveByMsg

Description: Removes matching rules from the parent contexts.

Syntax: SecRuleRemoveByMsg REGEX

Example Usage: SecRuleRemoveByMsg "FAIL"

Processing Phase: Any

Scope: Any

Dependencies/Notes: This directive supports multiple parameters. Each parameter is a regular expression that will be applied to the message (specified using the msg action).

SecServerSignature

Description: Instructs ModSecurity to change the data presented in the "Server:" response header token.

Syntax: SecServerSignature "WEB SERVER SOFTWARE"

Example Usage: SecServerSignature "Netscape-Enterprise/6.0"

Processing Phase: N/A

Scope: Main

Dependencies/Notes: In order for this directive to work, you must set the Apache ServerTokens directive to Full. ModSecurity will overwrite the server signature data held in this memory space with the data set in this directive. If ServerTokens is not set to Full, then the memory space is most likely not large enough to hold the new data we are looking to insert.

SecTmpDir

Description: Configures the directory where temporary files will be created.

Syntax: SecTmpDir /path/to/dir

Example Usage: SecTmpDir /tmp

Processing Phase: N/A

Scope: Any

Dependencies/Notes: Needs to be writable by the Apache user process. This is the directory location where Apache will swap data to disk if it runs out of memory (more data than what was specified in the SecRequestBodyInMemoryLimit directive) during inspection.

SecUploadDir

Description: Configures the directory where intercepted files will be stored.

Syntax: SecUploadDir /path/to/dir

Example Usage: SecUploadDir /tmp

Processing Phase: N/A

Scope: Any

Dependencies/Notes: This directory must be on the same filesystem as the temporary directory defined with SecTmpDir. This directive is used with SecUploadKeepFiles.

SecUploadKeepFiles

Description: Configures whether or not the intercepted files will be kept after transaction is processed.

Syntax: SecUploadKeepFiles On|Off|RelevantOnly

Example Usage: SecUploadKeepFiles On

Processing Phase: N/A

Scope: Any

Dependencies/Notes: This directive requires the storage directory to be defined (using SecUploadDir).

Possible values are:

  • On - Keep uploaded files.

  • Off - Do not keep uploaded files.

  • RelevantOnly - This will keep only those files that belong to requests that are deemed relevant.

SecWebAppId

Description: Creates a partition on the server that belongs to one web application.

Syntax: SecWebAppId "NAME"

Example Usage: SecWebAppId "WebApp1"

Processing Phase: N/A

Scope: Any

Dependencies/Notes: Partitions are used to avoid collisions between session IDs and user IDs. This directive must be used if there are multiple applications deployed on the same server. If it isn't used, a collision between session IDs might occur. The default value is default. Example:

<VirtualHost *:80> 
ServerName app1.com 
ServerAlias www.app1.com
SecWebAppId "App1"
SecRule REQUEST_COOKIES:PHPSESSID !^$ chain,nolog,pass 
SecAction setsid:%{REQUEST_COOKIES.PHPSESSID} 
... 
</VirtualHost>  

<VirtualHost *:80> 
ServerName app2.com 
ServerAlias www.app2.com
SecWebAppId "App2"
SecRule REQUEST_COOKIES:PHPSESSID !^$ chain,nolog,pass 
SecAction setsid:%{REQUEST_COOKIES.PHPSESSID} 
... 
</VirtualHost>

In the two examples configurations shown, SecWebAppId is being used in conjuction with the Apache VirtualHost directives. What this achieves is to create more unique collection names when being hosted on one server. Normally, when setsid is used, ModSecurity will create a collection with the name "SESSION" and it will hold the value specified. With using SecWebAppId as shown in the examples, however, the name of the collection would become "App1_SESSION" and "App2_SESSION".

SecWebAppId is relevant in two cases:

  1. You are logging transactions/alerts to the ModSecurity Console and you want to use the web application ID to search only the transactions belonging to that application.

  2. You are using the data persistence facility (collections SESSION and USER) and you need to avoid collisions between sessions and users belonging to different applications.