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. The first version to use a given directive is given in the Version 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 evaluated 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,action3

Example Usage: SecAction nolog,phase:1,initcol:RESOURCE=%{REQUEST_FILENAME}

Processing Phase: Any

Scope: Any

Version: 2.0.0

Dependencies/Notes: None

SecAction is best used when you unconditionally 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 certain 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

Version: 2.0.0

Dependencies/Notes: None

This directive is needed if a backend web application is using a non-standard argument separator. If this directive is not set properly for each web application, then ModSecurity will not be able to parse the arguments 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

Version: 2.0.0

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 ^(?:5|4\d[^4])

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

Version: 2.0.0

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 or commercial ModSecurity Management Appliance, then you will need to configure and use the ModSecurity Log Collector (mlogc) and use the following format for the audit log:

SecAuditLog "|/path/to/mlogc /path/to/mlogc.conf"

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

Version: 2.1.2

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.

SecAuditLogDirMode

Description: Configures the mode (permissions) of any directories created for concurrent audit logs using an octal mode (as used in chmod). See SecAuditLogFileMode for controlling the mode of audit log files.

Syntax: SecAuditLogDirMode octal_mode|"default"

Example Usage: SecAuditLogDirMode 02750

Processing Phase: N/A

Scope: Any

Version: 2.5.10

Dependencies/Notes: This feature is not available on operating systems not supporting octal file modes. The default mode (0600) only grants read/write access to the account writing the file. If access from another account is needed (using mpm-itk is a good example), then this directive may be required. However, use this directive with caution to avoid exposing potentially sensitive data to unauthorized users. Using the value "default" will revert back to the default setting.

Note

The process umask may still limit the mode if it is being more restrictive than the mode set using this directive.

SecAuditLogFileMode

Description: Configures the mode (permissions) of any files created for concurrent audit logs using an octal mode (as used in chmod). See SecAuditLogDirMode for controlling the mode of created audit log directories.

Syntax: SecAuditLogFileMode octal_mode|"default"

Example Usage: SecAuditLogFileMode 00640

Processing Phase: N/A

Scope: Any

Version: 2.5.10

Dependencies/Notes: This feature is not available on operating systems not supporting octal file modes. The default mode (0600) only grants read/write access to the account writing the file. If access from another account is needed (using mpm-itk is a good example), then this directive may be required. However, use this directive with caution to avoid exposing potentially sensitive data to unauthorized users. Using the value "default" will revert back to the default setting.

Note

The process umask may still limit the mode if it is being more restrictive than the mode set using this directive.

SecAuditLogParts

Description: Defines which part of each transaction are going to be recorded in audit log. Each part is assigned a single letter. If a letter appears in the list then the equivalent part of each transactions will be recorded. See below for the list of all parts.

Syntax: SecAuditLogParts PARTS

Example Usage: SecAuditLogParts ABCFHZ

Processing Phase: N/A

Scope: Any

Version: 2.0.0

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.

Note

Please refer to the ModSecurity Data Formats document for a detailed description of every available part.

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.

  • K - This part contains a full list of every rule that matched (one per line) in the order they were matched. The rules are fully qualified and will thus show inherited actions and default operators. Supported as of v2.5.0

  • 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 ^(?:5|4\d[^4])

Processing Phase: N/A

Scope: Any

Version: 2.0.0

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

Version: 2.0.0

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

Version: 2.0.0

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.

SecCacheTransformations (Deprecated/Experimental)

Description: Controls caching of transformations. Caching is off by default starting with 2.5.6, when it was deprecated and downgraded back to experimental.

Syntax: SecCacheTransformations On|Off [options]

Example Usage: SecCacheTransformations On "minlen:64,maxlen:0"

Processing Phase: N/A

Scope: Any

Version: 2.5.0

Dependencies/Notes: N/A

First parameter:

  • On - cache transformations (per transaction, per phase) allowing identical transformations to be performed only once. (default)

  • Off - do not cache any transformations, forcing all transformations to be performed for each rule executed.

The following options are allowed (comma separated):

  • incremental:on|off - enabling this option will cache every transformation instead of just the final transformation. (default: off)

  • maxitems:N - do not allow more than N transformations to be cached. The cache will then be disabled. A zero value is interpreted as "unlimited". This option may be useful to limit caching for a form with a large number of ARGS. (default: 512)

  • minlen:N - do not cache the transformation if the value's length is less than N bytes. (default: 32)

  • maxlen:N - do not cache the transformation if the value's length is more than N bytes. A zero value is interpreted as "unlimited". (default: 1024)

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

Version: 2.0.0

Dependencies/Notes: This feature is not available on Windows builds. 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.builds. Some problems you might encounter with more complex setups:

  1. DNS lookups do not work (this is because this feature requires a shared library that is loaded on demand, after chroot takes place).

  2. You cannot send email from PHP because it uses sendmail and sendmail is outside the jail.

  3. In some cases Apache graceful (reload) no longer works.

You should be aware that the internal chroot feature might not be 100% reliable. 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. A module, working from within Apache, can do things that make it easy to break out of the jail. 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. Consider what your options are and make your own decision.

SecComponentSignature

Description: Appends component signature to the ModSecurity signature.

Syntax: SecComponentSignature "COMPONENT_NAME/X.Y.Z (COMMENT)"

Example usage: SecComponentSignature "Core Rules/1.2.3"

Processing Phase: N/A

Scope: Main

Version: 2.5.0

Dependencies/Notes: This directive should be used to make the presence of significant ModSecurity components known. The entire signature will be recorded in transaction audit log. It should be used by ModSecurity module and rule set writers to make debugging easier.

SecContentInjection

Description: Enables content injection using actions append and prepend.

Syntax: SecContentInjection (On|Off)

Example Usage: SecContentInjection On

Processing Phase: N/A

Scope: Any

Version: 2.5.0

Dependencies/Notes: N/A

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

Version: 2.0.0

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

Version: 2.0.0

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

Version: 2.0.0

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

Processing Phase: Any

Scope: Any

Version: 2.0.0

Dependencies/Notes: Rules following a SecDefaultAction directive will inherit this setting unless a specific action is specified for an individual rule or until another SecDefaultAction is specified. Take special note that in the logging disruptive actions are not allowed, but this can inadvertently be inherited using a disruptive action in SecDefaultAction.

The default value is minimal (differing from previous versions):

SecDefaultAction phase:2,log,auditlog,pass

Note

SecDefaultAction must specify a disruptive action and a processing phase and cannot contain metadata actions.

Warning

SecDefaultAction is not inherited across configuration contexts. (For an example of why this may be a problem for you, read the following ModSecurity Blog entry http://blog.modsecurity.org/2008/07/modsecurity-tri.html).

SecGeoLookupDb

Description: Defines the path to the geographical database file.

Syntax: SecGeoLookupDb /path/to/db

Example Usage: SecGeoLookupDb /usr/local/geo/data/GeoLiteCity.dat

Processing Phase: N/A

Scope: Any

Version: 2.5.0

Dependencies/Notes: Check out maxmind.com for free database files.

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

Version: 2.0.0

Dependencies/Notes: By default httpd-guardian will defend against clients that send more than 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

SecMarker

Description: Adds a fixed rule marker in the ruleset to be used as a target in a skipAfter action. A SecMarker directive essentially creates a rule that does nothing and whose only purpose it to carry the given ID.

Syntax: SecMarker ID

Example Usage: SecMarker 9999

Processing Phase: Any

Scope: Any

Version: 2.5.0

Dependencies/Notes: None

SecRule REQUEST_URI "^/$" \
    "chain,t:none,t:urlDecode,t:lowercase,t:normalisePath,skipAfter:99"
SecRule REMOTE_ADDR "^127\.0\.0\.1$" "chain"
SecRule REQUEST_HEADERS:User-Agent \
    "^Apache \(internal dummy connection\)$" "t:none"  
SecRule &REQUEST_HEADERS:Host "@eq 0" \
    "deny,log,status:400,id:08,severity:4,msg:'Missing a Host Header'"
SecRule &REQUEST_HEADERS:Accept "@eq 0" \
    "log,deny,log,status:400,id:15,msg:'Request Missing an Accept Header'"

SecMarker 99

SecPdfProtect

Description: Enables the PDF XSS protection functionality. Once enabled access to PDF files is tracked. Direct access attempts are redirected to links that contain one-time tokens. Requests with valid tokens are allowed through unmodified. Requests with invalid tokens are also allowed through but with forced download of the PDF files. This implementation uses response headers to detect PDF files and thus can be used with dynamically generated PDF files that do not have the .pdf extension in the request URI.

Syntax: SecPdfProtect On|Off

Example Usage: SecPdfProtect On

Processing Phase: N/A

Scope: Any

Version: 2.5.0

Dependencies/Notes: None

SecPdfProtectMethod

Description: Configure desired protection method to be used when requests for PDF files are detected. Possible values are TokenRedirection and ForcedDownload. The token redirection approach will attempt to redirect with tokens where possible. This allows PDF files to continue to be opened inline but only works for GET requests. Forced download always causes PDF files to be delivered as opaque binaries and attachments. The latter will always be used for non-GET requests. Forced download is considered to be more secure but may cause usability problems for users ("This PDF won't open anymore!").

Syntax: SecPdfProtectMethod method

Example Usage: SecPdfProtectMethod TokenRedirection

Processing Phase: N/A

Scope: Any

Version: 2.5.0

Dependencies/Notes: None

Default: TokenRedirection

SecPdfProtectSecret

Description: Defines the secret that will be used to construct one-time tokens. You should use a reasonably long value for the secret (e.g. 16 characters is good). Once selected the secret should not be changed as it will break the tokens that were sent prior to change. But it's not a big deal even if you change it. It will just force download of PDF files with tokens that were issued in the last few seconds.

Syntax: SecPdfProtectSecret secret

Example Usage: SecPdfProtectSecret MyRandomSecretString

Processing Phase: N/A

Scope: Any

Version: 2.5.0

Dependencies/Notes: None

SecPdfProtectTimeout

Description: Defines the token timeout. After token expires it can no longer be used to allow access to PDF file. Request will be allowed through but the PDF will be delivered as attachment.

Syntax: SecPdfProtectTimeout timeout

Example Usage: SecPdfProtectTimeout 10

Processing Phase: N/A

Scope: Any

Version: 2.5.0

Dependencies/Notes: None

Default: 10

SecPdfProtectTokenName

Description: Defines the name of the token. The only reason you would want to change the name of the token is if you wanted to hide the fact you are running ModSecurity. It's a good reason but it won't really help as the adversary can look into the algorithm used for PDF protection and figure it out anyway. It does raise the bar slightly so go ahead if you want to.

Syntax: SecPdfProtectTokenName name

Example Usage: SecPdfProtectTokenName PDFTOKEN

Processing Phase: N/A

Scope: Any

Version: 2.5.0

Dependencies/Notes: None

Default: PDFTOKEN

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

Version: 2.0.0

Dependencies/Notes: This directive is required if you plan to inspect POST_PAYLOAD. 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

Scope: Any

Version: 2.0.0

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.

SecRequestBodyNoFilesLimit

Description: Configures the maximum request body size ModSecurity will accept for buffering, excluding the size of files being transported in the request. This directive comes handy to further reduce susceptibility to DoS attacks when someone is sending request bodies of very large sizes. Web applications that require file uploads must configure SecRequestBodyLimit to a high value. Since large files are streamed to disk file uploads will not increase memory consumption. However, it's still possible for someone to take advantage of a large request body limit and send non-upload requests with large body sizes. This directive eliminates that loophole.

Syntax: SecRequestBodyNoFilesLimit NUMBER_IN_BYTES

Example Usage: SecRequestBodyLimit 131072

Scope: Any

Version: 2.5.0

Dependencies/Notes: 1 MB (1048576 bytes) is the default setting. This value is very conservative. For most applications you should be able to reduce it down to 128 KB or lower. Anything over the 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

Version: 2.0.0

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

Version: 2.0.0

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

SecResponseBodyLimitAction

Description: Controls what happens once a response body limit, configured with SecResponseBodyLimit, is encountered. By default ModSecurity will reject a response body that is longer than specified. Some web sites, however, will produce very long responses making it difficult to come up with a reasonable limit. Such sites would have to raise the limit significantly to function properly defying the purpose of having the limit in the first place (to control memory consumption). With the ability to choose what happens once a limit is reached site administrators can choose to inspect only the first part of the response, the part that can fit into the desired limit, and let the rest through. Some could argue that allowing parts of responses to go uninspected is a weakness. This is true in theory but only applies to cases where the attacker controls the output (e.g. can make it arbitrary long). In such cases, however, it is not possible to prevent leakage anyway. The attacker could compress, obfuscate, or even encrypt data before it is sent back, and therefore bypass any monitoring device.

Syntax: SecResponseBodyLimitAction Reject|ProcessPartial

Example Usage: SecResponseBodyLimitAction ProcessPartial

Processing Phase: N/A

Scope: Any

Version: 2.5.0

Dependencies/Notes: None

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

Version: 2.0.0

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

Version: 2.0.0

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

Version: 2.0.0

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" \

"phase:1,t:none,t:urlDecode,t:lowercase,t:normalisePath"

Processing Phase: Any

Scope: Any

Version: 2.0.0

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 ARGS dirty

Each rule can specify one or more variables:

SecRule ARGS|REQUEST_HEADERS:User-Agent 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

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.

Collections

A variable can contain one or many pieces of data, depending on the nature of the variable and the way it is used. We've seen examples of both approaches in the previous section. When a variable can contain more than one value we refer to it as a collection.

Collections are always expanded before a rule is run. For example, the following rule:

SecRule ARGS dirty

will be expanded to:

SecRule ARGS:p dirty
SecRule ARGS:q dirty

in a requests that has only two parameters, named p and q.

Collections come in several flavours:

Read-only

Created at runtime using transaction data. For example: ARGS (contains a list of all request parameter values) and REQUEST_HEADERS (contains a list of all request header values).

Transient Read/Write

The TX collection is created (empty) for every transaction. Rules can read from it and write to it (using the setvar action, for example), but the information stored in this collection will not survive the end of transaction.

Persistent Read/Write

There are several collections that can be written to, but which are persisted to the storage backend. These collections are used to track clients across transactions. Examples of collections that fall into this type are IP, SESSION and USER.

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 (regular expression) operator. You can also explicitly specify the operator you want to use by using @, followed by the name of an operator, at the beginning of the second SecRule parameter:

SecRule ARGS "@rx dirty"

Note how we had to use double quotes to delimit the second rule parameter. This is because the second parameter now has 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$"

Operator negation

Operator results can be negated by using an exclamation mark at the beginning of the second parameter. The following rule matches if the word dirty does not appear in the User-Agent request header:

SecRule REQUEST_HEADERS:User-Agent !dirty

You can use the exclamation mark in combination with any parameter. If you do, the exclamation mark needs to go first, followed by the explicit operator reference. The following rule has the same effect as the previous example:

SecRule REQUEST_HEADERS:User-Agent "!@rx dirty"

If you need to use negation in a rule that is going to be applied to several variables then it may not be immediately clear what will happen. Consider the following example:

SecRule ARGS:p|ARGS:q !dirty

The above rule is identical to:

SecRule ARGS:p !dirty
SecRule ARGS:q !dirty

Warning

Negation is applied to operations against individual operations, not agains the entire variable list.

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

Version: 2.0.0

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.

SecRuleEngine 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.

    Note

    Configuration contexts are an Apache concept. Directives <Directory>, <Files>, <Location> and <VirtualHost> are all used to create configuration contexts. For more information please go to the Apache documentation section Configuration Sections.

SecRuleEngine

Description: Configures the rules engine.

Syntax: SecRuleEngine On|Off|DetectionOnly

Example Usage: SecRuleEngine On

Processing Phase: Any

Scope: Any

Version: 2.0.0

Dependencies/Notes: This directive can also be controlled 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: SecRuleUpdateActionById RULEID ACTIONLIST

Example Usage: SecRuleRemoveByID 1 2 "9000-9010"

Processing Phase: Any

Scope: Any

Version: 2.0.0

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

Version: 2.0.0

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).

SecRuleScript (Experimental)

Description: This directive creates a special rule that executes a Lua script to decide whether to match or not. The main difference from SecRule is that there are no targets nor operators. The script can fetch any variable from the ModSecurity context and use any (Lua) operator to test them. The second optional parameter is the list of actions whose meaning is identical to that of SecRule.

Syntax: SecRuleScript /path/to/script.lua [ACTIONS]

Example Usage: SecRuleScript "/path/to/file.lua" "block"

Processing Phase: Any

Scope: Any

Version: 2.5.0

Dependencies/Notes: None

Note

All Lua scripts are compiled at configuration time and cached in memory. To reload scripts you must reload the entire ModSecurity configuration by restarting Apache.

Example script:

-- Your script must define the main entry
-- point, as below.
function main()
    -- Log something at level 1. Normally you shouldn't be
    -- logging anything, especially not at level 1, but this is
    -- just to show you can. Useful for debugging.
    m.log(1, "Hello world!");

    -- Retrieve one variable.
    local var1 = m.getvar("REMOTE_ADDR");

    -- Retrieve one variable, applying one transformation function.
    -- The second parameter is a string.
    local var2 = m.getvar("ARGS", "lowercase");

    -- Retrieve one variable, applying several transformation functions.
    -- The second parameter is now a list. You should note that m.getvar()
    -- requires the use of comma to separate collection names from
    -- variable names. This is because only one variable is returned.
    local var3 = m.getvar("ARGS.p", { "lowercase", "compressWhitespace" } );

    -- If you want this rule to match return a string
    -- containing the error message. The message must contain the name
    -- of the variable where the problem is located.
    -- return "Variable ARGS:p looks suspicious!"

    -- Otherwise, simply return nil.
    return nil;
end

In this first example we were only retrieving one variable at the time. In this case the name of the variable is known to you. In many cases, however, you will want to examine variables whose names you won't know in advance, for example script parameters.

Example showing use of m.getvars() to retrieve many variables at once:

function main()
    -- Retrieve script parameters.
    local d = m.getvars("ARGS", { "lowercase", "htmlEntityDecode" } );

    -- Loop through the paramters.
    for i = 1, #d do
        -- Examine parameter value.
        if (string.find(d[i].value, "<script")) then
            -- Always specify the name of the variable where the
            -- problem is located in the error message.
            return ("Suspected XSS in variable " .. d[i].name .. ".");
        end
    end

    -- Nothing wrong found.
    return nil;
end

Note

Go to http://www.lua.org/ to find more about the Lua programming language. The reference manual too is available online, at http://www.lua.org/manual/5.1/.

Note

Lua support is marked as experimental as the way the progamming interface may continue to evolve while we are working for the best implementation style. Any user input into the programming interface is appreciated.

SecRuleUpdateActionById

Description: Updates the action list of the specified rule.

Syntax: SecRuleRemoveById RULEID ACTIONLIST

Example Usage: SecRuleUpdateActionById 12345 deny,status:403

Processing Phase: Any

Scope: Any

Version: 2.5.0

Dependencies/Notes: This directive merges the specified action list with the rule's action list. There are two limitations. The rule ID cannot be changed, nor can the phase. Further note that actions that may be specified multiple times are appended to the original.

SecAction \
  "t:lowercase,phase:2,id:12345,pass,msg:'The Message',log,auditlog"
SecRuleUpdateActionById 12345 "t:compressWhitespace,deny,status:403,msg:'A new message'

The example above will cause the rule to be executed as if it was specified as follows:

SecAction \
  "t:lowercase,phase:2,id:12345,log,auditlog,t:compressWhitespace,deny,status:403,msg:'A new message'"

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

Version: 2.0.0

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

Version: 2.0.0

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

Version: 2.0.0

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

SecUploadFileMode

Description: Configures the mode (permissions) of any uploaded files using an octal mode (as used in chmod).

Syntax: SecUploadFileMode octal_mode|"default"

Example Usage: SecUploadFileMode 0640

Processing Phase: N/A

Scope: Any

Version: 2.1.6

Dependencies/Notes: This feature is not available on operating systems not supporting octal file modes. The default mode (0600) only grants read/write access to the account writing the file. If access from another account is needed (using clamd is a good example), then this directive may be required. However, use this directive with caution to avoid exposing potentially sensitive data to unauthorized users. Using the value "default" will revert back to the default setting.

Note

The process umask may still limit the mode if it is being more restrictive than the mode set using this directive.

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

Version: 2.0.0

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

Version: 2.0.0

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 conjunction 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.