-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Reference Manual (v2.x)
Copyright © 2004-2022 Trustwave Holdings, Inc.
ModSecurity is a web application firewall (WAF). With over 70% of attacks now carried out over the web application level, organisations need all the help they can get in making their systems secure. WAFs are deployed to establish an increased external security layer to detect and/or prevent attacks before they reach web applications. ModSecurity provides protection from a range of attacks against web applications and allows for HTTP traffic monitoring and real-time analysis with little or no changes to existing infrastructure.
Web servers are typically well-equipped to log traffic in a form useful for marketing analyses, but fall short logging traffic to web applications. In particular, most are not capable of logging the request bodies. Your adversaries know this, and that is why most attacks are now carried out via POST requests, rendering your systems blind. ModSecurity makes full HTTP transaction logging possible, allowing complete requests and responses to be logged. Its logging facilities also allow fine-grained decisions to be made about exactly what is logged and when, ensuring only the relevant data is recorded. As some of the request and/or response may contain sensitive data in certain fields, ModSecurity can be configured to mask these fields before they are written to the audit log.
In addition to providing logging facilities, ModSecurity can monitor the HTTP traffic in real time in order to detect attacks. In this case, ModSecurity operates as a web intrusion detection tool, allowing you to react to suspicious events that take place at your web systems.
ModSecurity can also act immediately to prevent attacks from reaching your web applications. There are three commonly used approaches:
- Negative security model. A negative security model monitors requests for anomalies, unusual behaviour, and common web application attacks. It keeps anomaly scores for each request, IP addresses, application sessions, and user accounts. Requests with high anomaly scores are either logged or rejected altogether.
- Positive security model. When a positive security model is deployed, only requests that are known to be valid are accepted, with everything else rejected. This model requires knowledge of the web applications you are protecting. Therefore a positive security model works best with applications that are heavily used but rarely updated so that maintenance of the model is minimized.
- Known weaknesses and vulnerabilities. Its rule language makes ModSecurity an ideal external patching tool. External patching (sometimes referred to as Virtual Patching) is about reducing the window of opportunity. Time needed to patch application vulnerabilities often runs to weeks in many organisations. With ModSecurity, applications can be patched from the outside, without touching the application source code (and even without any access to it), making your systems secure until a proper patch is applied to the application.
A flexible rule engine sits in the heart of ModSecurity. It implements the ModSecurity Rule Language, which is a specialised programming language designed to work with HTTP transaction data. The ModSecurity Rule Language is designed to be easy to use, yet flexible: common operations are simple while complex operations are possible. Certified ModSecurity Rules, included with ModSecurity, contain a comprehensive set of rules that implement general-purpose hardening, protocol validation and detection of common web application security issues. Heavily commented, these rules can be used as a learning tool.
ModSecurity is an embeddable web application firewall, which means it can be deployed as part of your existing web server infrastructure provided your web servers are either Apache, IIS7 or Nginx. This deployment method has certain advantages:
- No changes to existing network. It only takes a few minutes to add ModSecurity to your existing web servers. And because it was designed to be completely passive by default, you are free to deploy it incrementally and only use the features you need. It is equally easy to remove or deactivate it if required.
- No single point of failure. Unlike with network-based deployments, you will not be introducing a new point of failure to your system.
- Implicit load balancing and scaling. Because it works embedded in web servers, ModSecurity will automatically take advantage of the additional load balancing and scalability features. You will not need to think of load balancing and scaling unless your existing system needs them.
- Minimal overhead. Because it works from inside the web server process there is no overhead for network communication and minimal overhead in parsing and data exchange.
- No problem with encrypted or compressed content. Many IDS systems have difficulties analysing SSL traffic. This is not a problem for ModSecurity because it is positioned to work when the traffic is decrypted and decompressed.
ModSecurity works equally well when deployed as part of a reverse proxy server, and many of our customers choose to do so. In this scenario, one installation of ModSecurity can protect any number of back-end web servers.
ModSecurity is known to work well on a wide range of operating systems. Our customers are successfully running it on Linux, Windows, Solaris, FreeBSD, OpenBSD, NetBSD, AIX, Mac OS X, and HP-UX.
ModSecurity is available under the Apache Software License v2 http://www.apache.org/licenses/LICENSE-2.0.txt
- Note : ModSecurity, mod_security, ModSecurity Pro, and ModSecurity Core Rules are trademarks or registered trademarks of Trustwave Holdings, Inc.
The ModSecurity team works hard to ensure that ModSecurity version 2.x will work with all versions of Apache 2.x and higher. If you find incompatibilities on any version (2.2.x, 2.4.x, or 2.6.x) please immediately inform the ModSecurity team
Make sure you have mod_unique_id
installed.
mod_unique_id is packaged with Apache httpd.
libapr and libapr-util - http://apr.apache.org/
http://xmlsoft.org/downloads.html
This library is optional and only needed if you will be using the new Lua engine - http://www.lua.org/download.html
- Note : that ModSecurity requires the dynamic libraries. These are not built by default in the source distribution, so the binary distribution is recommended.
- Note : libModSecurity (aka v3) is compatible with Lua 5.2+.
If you will be using the ModSecurity Log Collector (mlogc) to send audit logs to a central repository, then you will also need the curl library.
- Note : Many have had issues with libcurl linked with the GnuTLS library for SSL/TLS support. It is recommended that the openssl library be used for SSL/TLS support in libcurl.
Before you begin with installation you will need to choose your preferred installation method. First you need to choose whether to install the latest version of ModSecurity directly from git (best features, but possibly unstable) or use the latest stable release (recommended). If you choose a stable release, it might be possible to install ModSecurity from binary. It is always possible to compile it from source code.
The following few pages will give you more information on benefits of choosing one method over another.
If you want to access the latest version of the module you need to get it from the git repository. The list of changes made since the last stable release is normally available on the web site (and in the file CHANGES). The git repository for ModSecurity is hosted by GitHub (http://www.github.com). You can access it directly or view if through web using this address: https://github.com/SpiderLabs/ModSecurity
To download the lastest TRUNK source code to your computer you need to execute the following command:
git
$git clone git://github.com/SpiderLabs/ModSecurity.git $git checkout remotes/trunk
For v2.6.0 and above, the installation process has changed. Follow these steps:
- cd into the directory -
$cd ModSecurity
- Run autogen.sh script -
$./autogen.sh
- Run configure script -
$./configure
- Run make -
$make
- Run make install -
$make install
- Copy the new mod_security2.so file into the proper Apache modules directory -
$cp /usr/local/modsecurity/lib/mod_security2.so /usr/local/apache/modules/
To download the stable release go to http://www.modsecurity.org/download/. Binary distributions are sometimes available. If they are, they are listed on the download page. If not download the source code distribution.
- Stop Apache httpd
- Unpack the ModSecurity archive
- Build
Run the configure script to generate a Makefile. Typically no options are needed.
./configureOptions are available for more customization (use ./configure --help for a full list), but typically you will only need to specify the location of the apxs command installed by Apache httpd with the --with-apxs option.
./configure --with-apxs=/path/to/httpd-2.x.y/bin/apxs
- Note : There are certain configure options that are meant for debugging an other development use. If enabled, these options can substantially impact performance. These options include all --debug-* options as well as the --enable-performance-measurements options.
makeOptionally test with:
make CFLAGS=-DMSC_TEST test
- Note : This is step is still a bit experimental. If you have problems, please send the full output and error from the build to the support list. Most common issues are related to not finding the required headers and/or libraries.
make mlogcOptionally install mlogc: Review the INSTALL file included in the apache2/mlogc-src directory in the distribution. Install the ModSecurity module with:
make install
Edit Makefile.win to configure the Apache base and library paths.
Compile with: nmake -f Makefile.win
Install the ModSecurity module with: nmake -f Makefile.win install
Copy the libxml2.dll and lua5.1.dll to the Apache bin directory. Alternatively you can follow the step below for using LoadFile to load these libraries.
- Note : Users should follow the steps present in README_WINDOWS.txt into ModSecurity tarball.
On UNIX (and Windows if you did not copy the DLLs as stated above) you must load libxml2 and lua5.1 before ModSecurity with something like this:
LoadFile /usr/lib/libxml2.so LoadFile /usr/lib/liblua5.1.soLoad the ModSecurity module with:
LoadModule security2_module modules/mod_security2.so
You should now have ModSecurity 2.x up and running.
- Note : If you have compiled Apache yourself you might experience problems compiling ModSecurity against PCRE. This is because Apache bundles PCRE but this library is also typically provided by the operating system. I would expect most (all) vendor-packaged Apache distributions to be configured to use an external PCRE library (so this should not be a problem).
- You want to avoid Apache using the bundled PCRE library and ModSecurity linking against the one provided by the operating system. The easiest way to do this is to compile Apache against the PCRE library provided by the operating system (or you can compile it against the latest PCRE version you downloaded from the main PCRE distribution site). You can do this at configure time using the --with-pcre switch. If you are not in a position to recompile Apache, then, to compile ModSecurity successfully, you'd still need to have access to the bundled PCRE headers (they are available only in the Apache source code) and change the include path for ModSecurity (as you did in step 7 above) to point to them (via the --with-pcre ModSecurity configure option).
- Do note that if your Apache is using an external PCRE library you can compile ModSecurity with WITH_PCRE_STUDY defined,which would possibly give you a slight performance edge in regular expression processing.
- Non-gcc compilers may have problems running out-of-the-box as the current build system was designed around the gcc compiler and some compiler/linker flags may differ. To use a non-gcc compiler you may need some manual Makefile tweaks if issues cannot be solved by exporting custom CFLAGS and CPPFLAGS environment variables.
- If you are upgrading from ModSecurity 1.x, please refer to the migration matrix at http://www.modsecurity.org/documentation/ModSecurity-Migration-Matrix.pdf
- Starting with ModSecurity 2.7.0 there are a few important configuration options
- --enable-pcre-jit - Enables JIT support from pcre >= 8.20 that can improve regex performance.
- --enable-lua-cache - Enables lua vm caching that can improve lua script performance. Difference just appears if ModSecurity must run more than one script per transaction.
- --enable-request-early - On ModSecurity 2.6 phase one has been moved to phase 2 hook, if you want to play around it use this option.
- --enable-htaccess-config - It will allow the follow directives to be used into .htaccess files when AllowOverride Options is set :
- SecAction - SecRule - SecRuleRemoveByMsg - SecRuleRemoveByTag - SecRuleRemoveById - SecRuleUpdateActionById - SecRuleUpdateTargetById - SecRuleUpdateTargetByTag - SecRuleUpdateTargetByMsg
Use of ModSecurity v2 with NGINX is not supported. Please use ModSecurity v3 (libModSecurity) instead.
Before installing ModSecurity make sure you have Visual Studio 2013 Runtime (vcredist) installed. Vcredist can be downloaded here: http://www.visualstudio.com/downloads/download-visual-studio-vs (note that, there are two different versions 32 and 64b).
The source code of ModSecurity’s IIS components is fully published and the binary building process is described (see README_WINDOWS.TXT). For quick installation it is highly recommended to use standard MSI installer available from SourceForge files repository of ModSecurity project or use binary package and follow the manual installation steps.
Any installation errors or warning messages are logged in the application event log under 'ModSecurityIIS Installer' source.
The OWASP CRS is also installed on the system drive, on the selected folder. It can be included in any website by adding the following line to the web.config file, in system.webServer section:
(relative path can also be used accordingly)
- After the installation the module will be running in all websites by default. To remove it from a website add to web.config:
- To configure module in a website add to web.config:
- where configFile is standard ModSecurity config file.
- Events from the module will show up in "Application" Windows log.
- If after installation protected website responds with HTTP 503 error and event ID 2280 keeps getting logged in the application event log:
Log Name: Application Source: Microsoft-Windows-IIS-W3SVC-WP Event ID: 2280 Task Category: None Level: Error Keywords: Classic User: N/A Description: The Module DLL C:\Windows\system32\inetsrv\modsecurityiis.dll failed to load. The data is the error.
most likely it means that the installation process has failed and the ModSecurityIIS.dll module is missing one or more libraries that it depends on. Repeating installation of the prerequisites and the module files should fix the problem. The dependency walker tool:
can be used to figure out which library is missing or cannot be loaded.
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 in 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.
Description: Unconditionally processes the action list it receives as the first and only parameter. The syntax of the parameter is identical to that of the third parameter of SecRule
.
Syntax: SecAction "action1,action2,action3,...“
Scope: Any
Version: 2.0.0
This directive is commonly used to set variables and initialize persistent collections using the initcol action. For example:
SecAction nolog,phase:1,initcol:RESOURCE=%{REQUEST_FILENAME}
Description: Specifies which character to use as the separator for application/x-www-form- urlencoded content.
Syntax: SecArgumentSeparator character
Default: &
Scope: Main(< 2.7.0), Any(2.7.0)
Version: 2.0.0
This directive is needed if a backend web application is using a nonstandard argument separator. Applications are sometimes (very rarely) written to use a semicolon separator. You should not change the default setting unless you establish that the application you are working with requires a different 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.
Description: Configures the maximum number of ARGS that will be accepted for processing.
Syntax: SecArgumentsLimit LIMIT
Example Usage: SecArgumentsLimit 1000
Version: 2.9.7
Default: 1000
Exceeding the limit will set the REQBODY_ERROR variable, and additional arguments beyond the limit will not be included. With JSON body processing, there is an additional short-circuit to halt parsing once the limit is breached. As with the enforcement of other issues that signal REQBODY_ERROR, a rule should be in place to test this value, like rule 200002 in modsecurity.conf-recommended.
Description: Configures the audit logging engine.
Syntax: SecAuditEngine RelevantOnly
Default: Off
Scope: Any
Version: 2.0.0
The SecAuditEngine directive is used to configure the audit engine, which logs complete transactions. ModSecurity is currently able to log most, but not all transactions. Transactions involving errors (e.g., 400 and 404 transactions) use a different execution path, which ModSecurity does not support.
The possible values for the audit log engine are as follows:
- On: log all transactions
- Off: do not log any transactions
- RelevantOnly: only the log transactions that have triggered a warning or an error, or have a status code that is considered to be relevant (as determined by the SecAuditLogRelevantStatus directive)
- Note : If you need to change the audit log engine configuration on a per-transaction basis (e.g., in response to some transaction data), use the ctl action.
The following example demonstrates how SecAuditEngine is used:
SecAuditEngine RelevantOnly SecAuditLog logs/audit/audit.log SecAuditLogParts ABCFHZ SecAuditLogType concurrent SecAuditLogStorageDir logs/audit SecAuditLogRelevantStatus ^(?:5|4(?!04))
Description: Defines the path to the main audit log file (serial logging format) or the concurrent logging index file (concurrent logging format). When used in combination with mlogc (only possible with concurrent logging), this directive defines the mlogc location and command line.
Syntax: SecAuditLog /path/to/audit.log
Scope: Any Version: 2.0.0
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 to send your audit log data off to a remote server you will need to deploy the ModSecurity Log Collector (mlogc), like this:
SecAuditLog "|/path/to/mlogc /path/to/mlogc.conf"
- Note : This audit log file is opened 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.
Description: Defines the path to the secondary audit log index file when concurrent logging is enabled. See SecAuditLog for more details.
Syntax: SecAuditLog2 /path/to/audit.log
Scope: Any
Version: 2.1.2
The purpose of SecAuditLog2 is to make logging to two remote servers possible, which is typically achieved by running two instances of the mlogc tool, each with a different configuration (in addition, one of the instances will need to be instructed not to delete the files it submits). This directive can be used only if SecAuditLog was previously configured and only if concurrent logging format is used.
Description: Configures the mode (permissions) of any directories created for the concurrent audit logs, using an octal mode value as parameter (as used in chmod).
Syntax: SecAuditLogDirMode octal_mode|"default"
Default: 0600
Scope: Any
Version: 2.5.10
The default mode for new audit log directories (0600) only grants read/write access to the owner (typically the account under which Apache is running, for example apache). If access from other accounts is needed (e.g., for use with mpm-itk), then you may use this directive to grant additional read and/or write privileges. You should use this directive with caution to avoid exposing potentially sensitive data to unauthorized users. Using the value default as parameter reverts the configuration back to the default setting. This feature is not available on operating systems not supporting octal file modes.
Example:
SecAuditLogDirMode 02750
- Note : The process umask may still limit the mode if it is being more restrictive than the mode set using this directive.
Description: Select the output format of the AuditLogs. The format can be either the native AuditLogs format or JSON.
Syntax: SecAuditLogFormat JSON|Native
Default: Native
Scope: Any
Version: 2.9.1
- Note : The JSON format is only available if ModSecurity was compiled with support to JSON via the YAJL library. During the compilation time, the yajl-dev package (or similar) must be part of the system. The configure scripts provides information if the YAJL support was enabled or not.
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"
Default: 0600
Scope: Any
Version: 2.5.10
Example Usage: SecAuditLogFileMode 00640
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.
Description: Defines which parts of each transaction are going to be recorded in the audit log. Each part is assigned a single letter; when a letter appears in the list then the equivalent part will be recorded. See below for the list of all parts.
Syntax: SecAuditLogParts PARTLETTERS
Example Usage: SecAuditLogParts ABCFHZ
Scope: Any Version: 2.0.0
Default: ABCFHZ Note
The format of the audit log format is documented in detail in the Audit Log Data Format Documentation.
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. This would require SecRequestBodyAccess to be set to on).
- 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. Intercepting response bodies requires SecResponseBodyAccess to be enabled). 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: This part contains 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).
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(?!04))"
Scope: Any
Version: 2.0.0
Dependencies/Notes: Must have SecAuditEngine set to RelevantOnly. Additionally, the auditlog action is present by default in rules, this will make the engine bypass the 'SecAuditLogRelevantStatus' and send rule matches to the audit log regardless of status. You must specify noauditlog in the rules manually or set it in SecDefaultAction.
The main purpose of this directive is to allow you to configure audit logging for only the transactions that have the status code that matches the supplied regular expression. The example provided would log all 5xx and 4xx level status codes, except for 404s. Although you could achieve the same effect with a rule in phase 5, SecAuditLogRelevantStatus is sometimes better, because it continues to work even when SecRuleEngine is disabled.
Description: Configures the directory where concurrent audit log entries are to be stored.
Syntax: SecAuditLogStorageDir /path/to/storage/dir
Example Usage: SecAuditLogStorageDir /usr/local/apache/logs/audit
Scope: Any
Version: 2.0.0
This directive is only needed when concurrent audit logging is used. The directory must already exist and must be writable by the web server user. Audit log entries are created at runtime, after Apache switches to a non-root account. As with all logging mechanisms, ensure that you specify a file system location that has adequate disk space and is not on the main system partition.
Description: Configures the type of audit logging mechanism to be used.
Syntax: SecAuditLogType Serial|Concurrent|HTTPS
Example Usage: SecAuditLogType Serial
Scope: Any
Version: 2.0.0
The possible values are:
- Serial : Audit log entries will be stored in a single file, specified by SecAuditLog. This is conve- nient for casual use, but it can slow down the server, because only one audit log entry can be written to the file at any one time.
- Concurrent : One file per transaction is used for audit logging. This approach is more scalable when heavy logging is required (multiple transactions can be recorded in parallel). It is also the only choice if you need to use remote logging.
- HTTPS : This functionality is only available on libModSecurity and its currently in testing phase. Depending on the amount of request that you have, it may be suitable. Use the URL of your endpoint instead of the path to a file.
- Note : HTTPS audit log type is currently only supported on libModSecurity.
Description: Controls the caching of transformations, which may speed up the processing of complex rule sets. 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"
Scope: Any
Version: 2.5.0; deprecated in 2.5.6.
Supported on libModSecurity: No (Deprecated)
The first directive parameter can be one of the following:
- On: Cache transformations (per transaction, per phase) allowing identical transforma- tions to be performed only once.
- Off: Do not cache any transformations, leaving all transformations to be performed every time they are needed.
The following options are allowed (multiple options must be comma-separated):
- incremental:on|off: Enabling this option will cache every transformation instead of just the final transformation. The default is off.
- maxitems:N: Do not allow more than N transformations to be cached. Cache will be disabled once this number is reached. A zero value is interpreted as unlimited. This option may be useful to limit caching for a form with a large number of variables. The default value is 512.
- minlen:N: Do not cache the transformation if the variable’s length is less than N bytes. The default setting is 32.
- maxlen:N: Do not cache the transformation if the variable’s length is more than N bytes. A zero value is interpreted as unlimited. The default setting is 1024.
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
Scope: Main
Version: 2.0.0-2.9.x
Supported on libModSecurity: TBI
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 only static files, or running applications using built-in modules. Some problems you might encounter with more complex setups:
- DNS lookups do not work (this is because this feature requires a shared library that is loaded on demand, after chroot takes place).
- You cannot send email from PHP, because it wants to use sendmail and sendmail re- sides outside the jail.
- In some cases, when you separate Apache from its configuration, restarts and graceful reloads no longer work.
The best way to use SecChrootDir is the following:
- Create /chroot to be your main jail directory.
- Create /chroot/opt/apache inside jail.
- Create a symlink from /opt/apache to /chroot/opt/apache.
- Now install Apache into /chroot/opt/apache.
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.
- Note : This directive is not allowed inside VirtualHosts. If enabled, it must be placed in a global server-wide configuration file such as your default modsecurity.conf.
Description: Specifies the collections timeout. Default is 3600 seconds.
Syntax: SecCollectionTimeout seconds
Default: 3600
Scope: Any
Version: 2.6.3-2.9.x
Supported on libModSecurity: No
Description: Appends component signature to the ModSecurity signature.
Syntax: SecComponentSignature "COMPONENT_NAME/X.Y.Z (COMMENT)"
Example usage: SecComponentSignature "core ruleset/2.1.3"
Scope: Main
Version: 2.5.0-3.x
Supported on libModSecurity: Yes
This directive should be used to make the presence of significant rule sets known. The entire signature will be recorded in the transaction audit log.
Description: Configures the connections engine. This directive affect the directives: SecConnReadStateLimit and SecConnWriteStateLimit.
Syntax: SecConnEngine On|Off|DetectionOnly
Example Usage: SecConnEngine On
Scope: Any
Version: 2.8.0-2.9.x
Supported on libModSecurity: TBI
Possible values are (Same as SecRuleEngine):
- On: process SecConn[Read|Write]StateLimit.
- Off: Ignore the directives SecConn[Read|Write]StateLimit
- DetectionOnly: process SecConn[Read|Write]StateLimit definitions in verbose mode but never executes any disruptive actions
Description: Enables content injection using actions append and prepend.
Syntax: SecContentInjection On|Off
Example Usage: SecContentInjection On
Scope: Any
Version: 2.5.0-2.9.x
Supported on libModSecurity: TBI
This directive provides an easy way to control content injection, no matter what the rules want to do. It is not necessary to have response body buffering enabled in order to use content injection.
- Note : This directive must ben enabled if you want to use @rsub + the STREAM_ variables to manipulate live transactional data.
Description: Selects the cookie format that will be used in the current configuration context.
Syntax: SecCookieFormat 0|1
Example Usage: SecCookieFormat 0
Scope: Any
Version: 2.0.0-2.9.x
Supported on libModSecurity: TBD
The 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.
- Note : Only version 0 (Netscape) cookies is currently supported on libModSecurity (v3)
Description: Specifies which character to use as the separator for cookie v0 content.
Syntax: SecCookieV0Separator character
Scope: Any
Version: 2.7.0-2.9.x
Supported on libModSecurity: TBI
Description: Path where persistent data (e.g., IP address data, session data, and so on) is to be stored.
Syntax: SecDataDir /path/to/dir
Example Usage: SecDataDir /usr/local/apache/logs/data
Scope: Main
Version: 2.0.0-2.9.x
Supported on libModSecurity: No
This directive must be provided before initcol, setsid, and setuid can be used. The directory to which the directive points must be writable by the web server user.
- Note : This directive is not allowed inside VirtualHosts. If enabled, it must be placed in a global server-wide configuration file such as your default modsecurity.conf.
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
Scope: Any
Version: 2.0.0
Supported on libModSecurity: Yes
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
Scope: Any
Version: 2.0.0
Supported on libModSecurity: Yes
Messages at levels 1–3 are always copied to the Apache error log. Therefore you can always use level 0 as the default logging level in production if you are very concerned with performance. Having said that, the best value to use is 3. Higher logging levels are not recommended in production, because the heavy logging affects performance adversely.
The possible values for the debug log level 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
Description: Defines the default list of actions for a particular phase, which will be inherited by the rules in the same phase and in the same configuration context.
Syntax: SecDefaultAction "action1,action2,action3“
Example Usage: SecDefaultAction "phase:2,log,auditlog,deny,status:403,tag:'SLA 24/7'“
Scope: Any
Version: 2.0.0
Supported on libModSecurity: Yes
Default: phase:2,log,auditlog,pass
Every rule following a previous SecDefaultAction
directive in the same configuration context will inherit its settings unless more specific actions are used. Every SecDefaultAction
directive 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, read the following ModSecurity Blog entry https://www.trustwave.com/en-us/resources/blogs/spiderlabs-blog/three-modsecurity-rule-language-annoyances/ .)
Description: Disables backend compression while leaving the frontend compression enabled.
Syntax: SecDisableBackendCompression On|Off
Scope: Any
Version: 2.6.0-2.9.x
Supported on libModSecurity: TBI
Default: Off
This directive is necessary in reverse proxy mode when the backend servers support response compression, but you wish to inspect response bodies. Unless you disable backend compression, ModSecurity will only see compressed content, which is not very useful. This directive is not necessary in embedded mode, because ModSecurity performs inspection before response compression takes place.
Description: Configures the hash engine.
Syntax: SecHashEngine On|Off
Example Usage: SecHashEngine On
Scope: Any
Version: 2.7.1-2.9.x
Supported on libModSecurity: TBI
Default: Off
The possible values are:
- On: Hash engine can process the request/response data.
- Off: Hash engine will not process any data.
- Note : Users must enable stream output variables and content injection.
Description: Define the key that will be used by HMAC.
Syntax: SecHashKey rand|TEXT KeyOnly|SessionID|RemoteIP
Example Usage: SecHashKey "this_is_my_key" KeyOnly
Scope: Any
Version: 2.7.1-2.9.x
Supported on libModSecurity: TBI
ModSecurity hash engine will append, if specified, the user's session id or remote ip to the key before the MAC operation. If the first parameter is "rand" then a random key will be generated and used by the engine.
Description: Define the parameter name that will receive the MAC hash.
Syntax: SecHashParam TEXT
Example Usage: SecHashParam "hmac"
Scope: Any
Version: 2.7.1-2.9.x
Supported on libModSecurity: TBI
ModSecurity hash engine will add a new parameter to protected HTML elements containing the MAC hash.
Description: Configures what kind of HTML data the hash engine should sign based on regular expression.
Syntax: SecHashMethodRx TYPE REGEX
Example Usage: SecHashMethodRx HashHref "product_info|list_product"
Scope: Any
Version: 2.7.1-2.9.x
Supported on libModSecurity: TBI
As a initial support is possible to protect HREF, FRAME, IFRAME and FORM ACTION html elements as well response Location header when http redirect code are sent.
The possible values for TYPE are:
- HashHref: Used to sign href= html elements
- HashFormAction: Used to sign form action= html elements
- HashIframeSrc: Used to sign iframe src= html elements
- HashframeSrc: Used to sign frame src= html elements
- HashLocation: Used to sign Location response header
- Note : This directive is used to sign the elements however user must use the @validateHash operator to enforce data integrity.
Description: Configures what kind of HTML data the hash engine should sign based on string search algoritm.
Syntax: SecHashMethodPm TYPE "string1 string2 string3..."
Example Usage: SecHashMethodPm HashHref "product_info list_product"
Scope: Any
Version: 2.7.1-2.9.x
Supported on libModSecurity: TBI
As a initial support is possible to protect HREF, FRAME, IFRAME and FORM ACTION html elements as well response Location header when http redirect code are sent.
The possible values for TYPE are:
- HashHref: Used to sign href= html elements
- HashFormAction: Used to sign form action= html elements
- HashIframeSrc: Used to sign iframe src= html elements
- HashframeSrc: Used to sign frame src= html elements
- HashLocation: Used to sign Location response header
- Note : This directive is used to sign the elements however user must use the @validateHash operator to enforce data integrity.
Description: Defines the path to the database that will be used for geolocation lookups.
Syntax: SecGeoLookupDb /path/to/db
Example Usage: SecGeoLookupDb /path/to/GeoLiteCity.dat
Scope: Any
Version: 2.5.0
Supported on libModSecurity: Yes
ModSecurity relies on the free geolocation databases (GeoLite City and GeoLite Country) that can be obtained from MaxMind http://www.maxmind.com. Currently ModSecurity only supports the legacy GeoIP format. Maxmind's newer GeoIP2 format is not yet currently supported.
Description: Defines the path to the database that will be used for Google Safe Browsing (GSB) lookups.
Syntax: SecGsbLookupDb /path/to/db
Example Usage: SecGsbLookupDb /path/to/GsbMalware.dat
Scope: Any
Version: 2.6.0
Supported on libModSecurity: TBD
ModSecurity relies on the free Google Safe Browsing database that can be obtained from the Google GSB API http://code.google.com/apis/safebrowsing/.
- Note : Deprecated in 2.7.0 after Google dev team decided to not allow the database download anymore. After registering and obtaining a Safe Browsing API key, you can automatically download the GSB using a tool like wget. For further information on how to proceed with the download, please visit Google's website: https://developers.google.com/safe-browsing/v3/update-guide
Description: Configures an external program that will receive the information about every transaction via piped logging.
Syntax: SecGuardianLog |/path/to/httpd-guardian
Example Usage: SecGuardianLog |/usr/local/apache/bin/httpd-guardian
Scope: Main
Version: 2.0.0-2.9.x
Supported on libModSecurity: TBI
Guardian logging is designed to send the information about every request to an external program. Because Apache is typically deployed in a multiprocess fashion, which makes information sharing between processes difficult, the idea is to deploy a single external process to observe all requests in a stateful manner, providing additional protection.
Currently the only tool known to work with guardian logging is httpd-guardian, which is part of the Apache httpd tools project http://apache-tools.cvs.sourceforge.net/viewvc/apache-tools/apache-tools/. The httpd-guardian tool is designed to defend against denial of service attacks. It uses the blacklist tool (from the same project) to interact with an iptables-based (on a Linux system) or pf-based (on a BSD system) 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
- Note : This directive is not allowed inside VirtualHosts. If enabled, it must be placed in a global server-wide configuration file such as your default modsecurity.conf.
Description: Configures the user's registered Honeypot Project HTTP BL API Key to use with @rbl.
Syntax: SecHttpBlKey [12 char access key]
Example Usage: SecHttpBlKey whdkfieyhtnf
Scope: Main
Version: 2.7.0
Supported on libModSecurity: Yes
If the @rbl operator uses the dnsbl.httpbl.org RBL (http://www.projecthoneypot.org/httpbl_api.php) you must provide an API key. This key is registered to individual users and is included within the RBL DNS requests.
Description: Configures how to respond when rule processing fails.
Syntax: SecInterceptOnError On|Off
Example Usage: SecInterceptOnError On
Scope: Main
Version: 2.6-2.9.x
Supported on libModSecurity: TBI
When an operator execution fails, that is it returns greater than 0, this directive configures how to react. When set to "Off", the rule is just ignored and the engine will continue executing the rules in phase. When set to "On", the rule will be just dropped and no more rules will be executed in the same phase, also no interception is made.
Description: Adds a fixed rule marker that can be used as a target in a skipAfter action. A SecMarker directive essentially creates a rule that does nothing and whose only purpose is to carry the given ID.
Syntax: SecMarker ID|TEXT
Example Usage: SecMarker 9999
Scope: Any
Version: 2.5.0-3.x
Supported on libModSecurity: Yes
The value can be either a number or a text string. The SecMarker directive is available to allow you to choose the best way to implement a skip-over. Here is an example used from the Core Rule Set:
SecMarker BEGIN_HOST_CHECK SecRule &REQUEST_HEADERS:Host "@eq 0" \ "skipAfter:END_HOST_CHECK,phase:2,rev:'2.1.1',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.1',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
Description: Sets the match limit in the PCRE library.
Syntax: SecPcreMatchLimit value
Example Usage: SecPcreMatchLimit 1500
Scope: Main
Version: 2.5.12-2.9.x
Supported on libModSecurity: TBI
Default: 1500
The default can be changed when ModSecurity is prepared for compilation: the --enable-pcre-match-limit=val configure option will set a custom default and the --disable-pcre-match-limit option will revert back to the default of the PCRE library. For more information, refer to the pcre_extra field in the pcreapi man page.
- Note : This directive is not allowed inside VirtualHosts. If enabled, it must be placed in a global server-wide configuration file such as your default modsecurity.conf.
Description: Sets the match limit recursion in the PCRE library.
Syntax: SecPcreMatchLimitRecursion value
Example Usage: SecPcreMatchLimitRecursion 1500
Scope: Main
Version: 2.5.12-2.9.x
Supported on libModSecurity: TBI
Default: 1500
The default can be changed when ModSecurity is prepared for compilation: the --enable-pcre-match-limit-recursion=val configure option will set a custom default and the --disable-pcre-match-limit-recursion option will revert back to the default of the PCRE library. For more information, refer to the pcre_extra field in the pcreapi man page.
- Note : This directive is not allowed inside VirtualHosts. If enabled, it must be placed in a global server-wide configuration file such as your default modsecurity.conf.
Description: Establishes a per-IP address limit of how many connections are allowed to be in SERVER_BUSY_READ state.
Syntax: SecReadStateLimit LIMIT
Example Usage: SecReadStateLimit 50
Scope: Main
Version: 2.5.13, DEPRECATED as of v2.8.0.
Supported on libModSecurity: No (Deprecated)
Default: 0 (no limit)
For v2.8.0 or newest refer to SecConnReadStateLimit.
Description: Establishes a per-IP address limit of how many connections are allowed to be in SERVER_BUSY_READ state.
Syntax: SecConnReadStateLimit LIMIT OPTIONAL_IP_MATCH_OPERATOR
Example Usage: SecConnReadStateLimit 50 "!@ipMatch 127.0.0.1"
Scope: Main
Version: v2.8.0-2.9.x (Apache only)
Supported on libModSecurity: TBI
Default: 0 (no limit)
This measure is effective against Slowloris-style attacks from a single IP address, but it may not be as good against modified attacks that work by slowly sending request body content. This is because Apache to switches state to SERVER_BUSY_WRITE once request headers have been read. As an alternative, consider mod_reqtimeout (part of Apache as of 2.2.15), which is expected be effective against both attack types. See Blog post on mitigating slow DoS attacks - http://blog.spiderlabs.com/2010/11/advanced-topic-of-the-week-mitigating-slow-http-dos-attacks.html. v2.8.0 and newest supports the @ipMatch, @ipMatchF and @ipMatchFromFile operator along with the its negative (e.g. !@ipMatch) these were used to create suspicious or whitelist. When a suspicious list is informed, just the IPs that belongs to the list will be filtered. A combination of suspicious and whitelist is possible by using multiple definitions of SecConnReadStateLimit, note, however, that the limit will be always overwrite by its successor.
Note: This functionality is Apache only.
Note 2: Make sure Reference-Manual#secconnengine is on prior to use this feature.
Description: Define a sensor ID that will be present into log part H.
Syntax: SecSensorId TEXT
Example Usage: SecSensorId WAFSensor01
Scope: Main
Version: 2.7.0-2.9.x
Supported on libModSecurity: TBI
Description: Establishes a per-IP address limit of how many connections are allowed to be in SERVER_BUSY_WRITE state.
Syntax: SecWriteStateLimit LIMIT
Example Usage: SecWriteStateLimit 50
Scope: Main
Version: 2.6.0, DEPRECATED as of v2.8.0.
Supported on libModSecurity: No (Deprecated)
Default: 0 (no limit)
For v2.8.0 or newest refer to SecConnWriteStateLimit.
Description: Establishes a per-IP address limit of how many connections are allowed to be in SERVER_BUSY_WRITE state.
Syntax: SecConnWriteStateLimit LIMIT OPTIONAL_IP_MATCH_OPERATOR
Example Usage: SecConnWriteStateLimit 50 "!@ipMatch 127.0.0.1"
Scope: Main
Version: 2.6.0-2.9.x (Apache only)
Supported on libModSecurity: TBI
Default: 0 (no limit)
This measure is effective against Slow DoS request body attacks. v2.8.0 and newest supports the @ipMatch, @ipMatchF and @ipMatchFromFile operator along with the its negative (e.g. !@ipMatch) these were used to create suspicious or whitelist. When a suspicious list is informed, just the IPs that belongs to the list will be filtered. A combination of suspicious and whitelist is possible by using multiple definitions of SecConnReadStateLimit, note, however, that the limit will be always overwrite by its successor.
Note: This functionality is Apache only.
Note 2: Make sure Reference-Manual#secconnengine is on prior to use this feature.
Description: Controls how XML processing is done. If you turn it on with On
or OnlyArgs
, then XML nodes will
appear in ARGS
. In these cases, the SecArgumentsLimit directive will set the limit to number of loadable arguments.
Syntax: SecParseXmlIntoArgs Off|On|OnlyArgs
Example Usage: SecParseXmlIntoArgs Off
Scope: Any
Version: 2.9.9
Supported on libModSecurity: Yes
Default: default is Off
NOTE: You must enable this directive with On
or OnlyArgs
if you want to load XML nodes into ARGS
.
This is an optional directive that allow the user to load XML payload's nodes into ARGS
(and XML tags into ARGS_NAMES
). The default value is Off
. If the user set it to On
then XML nodes will appear in ARGS
collection with key xml.tag.chain
, but the XML
target will fill too. If the value is OnlyArgs
, then XML
will be empty. Notice that in this case the @validateDTD and @validateSchema operators will return with false value (because the XML
target is empty).
ctl:parseXmlIntoArgs
action's behavior is the same, you can control it during the transaction.
Example
Consider the XML payload:
This payload will generate value for XML
target like this:
foo bar
.
If you turn on this feature, the nodes will apear under ARGS
:
Adding XML argument 'xml.root.level1.level2' with value 'foo'
Adding XML argument 'xml.root.level1.level2' with value 'bar'
(These lines are from debug.log)
Description: Load rules from a given file hosted on a HTTPS site.
Syntax: SecRemoteRules [crypto] key https://url
Example Usage: SecRemoteRules some-key https://www.yourserver.com/plain-text-rules.txt
Scope: Any
Version: 2.9.0-RC1+
Supported on libModSecurity: Yes
This is an optional directive that allow the user to load rules from a remote server. Notice that besides the URL the user also needs to supply a key, which could be used by the target server to provide different content for different keys.
Along with the key, supplied by the users, ModSecurity will also send its Unique ID and the `status call' in the format of headers to the target web server. The following headers are used:
- ModSec-status - ModSec-unique-id - ModSec-key
The optional option "crypto" tells ModSecurity to expect some encrypted content from server. The utilization of SecRemoteRules is only allowed over TLS, thus, this option may not be necessary.
- Note : A valid and trusted digital certificate is expected on the end server. It is also expected that the server uses TLS, preferable TLS 1.2.
Description: Action that will be taken if SecRemoteRules specify an URL that ModSecurity was not able to download.
Syntax: SecRemoteRulesFailAction Abort|Warn
Example Usage: SecRemoteRulesFailAction Abort
Scope: Any
Version: 2.9.0-RC1+
Supported on libModSecurity: Yes
The default action is to Abort whenever there is a problem downloading a given URL.
- Note : This directive also influences the behaviour of @ipMatchFromFile when used with a HTTPS URI to retrieve the remote file.
Description: Configures whether request bodies will be buffered and processed by ModSecurity.
Syntax: SecRequestBodyAccess On|Off
Example Usage: SecRequestBodyAccess On
Scope: Any
Version: 2.0.0
Supported on libModSecurity: Yes
This directive is required if you want to inspect the data transported request bodies (e.g., POST parameters). Request buffering is also required in order to make reliable blocking possible. The possible values are:
- On: buffer request bodies
- Off: do not buffer request bodies
Description: Configures the maximum request body size that ModSecurity will store in memory.
Syntax: SecRequestBodyInMemoryLimit LIMIT_IN_BYTES
Example Usage: SecRequestBodyInMemoryLimit 131072
Scope: Any
Version: 2.0.0-2.9.x
Supported on libModSecurity: No
Default: 131072 (128 KB)
When a multipart/form-data request is being processed, once the in-memory limit is reached, the request body will start to be streamed into a temporary file on disk.
- Note : libModSecurity is able to deal with request body in a file or in a buffer (chunked or not). Web servers have properties which controls whenever a request should be saved to a file or used as a buffer (e.g. client_body_buffer_size https://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size) . If it is a file, ModSecurity will use the file to perform the inspection. If not, the buffer will be used.
Description: Configures the maximum parsing depth that is allowed when parsing a JSON object.
Syntax: SecRequestBodyJsonDepthLimit LIMIT
Example Usage: SecRequestBodyJsonDepthLimit 5000
Scope: Any
Version: 2.9.5- , 3.0.6-
Supported on libModSecurity: Yes - as of 3.0.6
Default: 10000
During parsing of a JSON object, if nesting exceeds the configured depth limit then parsing will halt and REQBODY_ERROR will be set.
Description: Configures the maximum request body size ModSecurity will accept for buffering.
Syntax: SecRequestBodyLimit LIMIT_IN_BYTES
Example Usage: SecRequestBodyLimit 134217728
Scope: Any
Version: 2.0.0
Supported on libModSecurity: Yes
Default: 134217728 (131072 KB)
Anything over the limit will be rejected with status code 413 (Request Entity Too Large). There is a hard limit of 1 GB.
- Note : In ModSecurity 2.5.x and earlier, SecRequestBodyLimit works only when used in the main server configuration, or a VirtualHost container. In these versions, request body limit is enforced immediately after phase 1, but before phase 2 configuration (i.e. whatever is placed in a Location container) is resolved. You can work around this limitation by using a phase 1 rule that changes the request body limit dynamically, using the ctl:requestBodyLimit action. ModSecurity 2.6.x (currently in the trunk only) and better do not have this limitation.
Description: Configures the maximum request body size ModSecurity will accept for buffering, excluding the size of any files being transported in the request. This directive is useful to 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, but because 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: SecRequestBodyNoFilesLimit 131072
Scope: Any
Version: 2.5.0
Supported on libModSecurity: No
Default: 1048576 (1 MB)
Generally speaking, the default value is not small enough. 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.
Description: Controls what happens once a request body limit, configured with SecRequestBodyLimit, is encountered
Syntax: SecRequestBodyLimitAction Reject|ProcessPartial
Example Usage: SecRequestBodyLimitAction ProcessPartial
Scope: Any
Version: 2.6.0
Supported on libModSecurity: Yes
By default, ModSecurity will reject a request body that is longer than specified. This is problematic especially when ModSecurity is being run in DetectionOnly mode and the intent is to be totally passive and not take any disruptive actions against the transaction. With the ability to choose what happens once a limit is reached, site administrators can choose to inspect only the first part of the request, the part that can fit into the desired limit, and let the rest through. This is not ideal from a possible evasion issue perspective, however it may be acceptable under certain circumstances.
- Note : When the SecRuleEngine is set to DetectionOnly, SecRequestBodyLimitAction is automatically set to ProcessPartial in order to not cause any disruptions. If you want to know if/when a request body size is over your limit, you can create a rule to check for the existence of the INBOUND_DATA_ERROR variable.
Description: Configures the maximum response body size that will be accepted for buffering.
Syntax: SecResponseBodyLimit LIMIT_IN_BYTES
Example Usage: SecResponseBodyLimit 524228
Scope: Any
Version: 2.0.0
Supported on libModSecurity: Yes
Default: 524288 (512 KB)
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 selected for buffering. There is a hard limit of 1 GB.
Description: Controls what happens once a response body limit, configured with SecResponseBodyLimit, is encountered.
Syntax: SecResponseBodyLimitAction Reject|ProcessPartial
Example Usage: SecResponseBodyLimitAction ProcessPartial
Scope: Any
Version: 2.5.0
Supported on libModSecurity: Yes
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 applies only to cases in which 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.
Description: Configures which MIME types are to be considered for response body buffering.
Syntax: SecResponseBodyMimeType MIMETYPE MIMETYPE ...
Example Usage: SecResponseBodyMimeType text/plain text/html text/xml
Scope: Any
Version: 2.0.0
Supported on libModSecurity: Yes
Default: text/plain text/html
Multiple SecResponseBodyMimeType directives can be used to add MIME types. Use SecResponseBodyMimeTypesClear to clear previously configured MIME types and start over.
- Note : Users that wish to perform JSON body inspection on response (phase 4) need to add _application/json_ to SecResponseBodyMimeType.
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
Scope: Any
Version: 2.0.0-2.9.x
Supported on libModSecurity: TBI
Description: Configures whether response bodies are to be buffered.
Syntax: SecResponseBodyAccess On|Off
Example Usage: SecResponseBodyAccess On
Scope: Any
Version: 2.0.0
Supported on libModSecurity: Yes
Default: Off
This directive is required if you plan to inspect HTML responses and implement response blocking. Possible values are:
- On: buffer response bodies (but only if the response MIME type matches the list configured with SecResponseBodyMimeType).
- Off: do not buffer response bodies.
Description: Creates a rule that will analyze the selected variables using the selected operator.
Syntax: SecRule VARIABLES OPERATOR [ACTIONS]
Example Usage: SecRule ARGS "@rx attack" "phase:1,log,deny,id:1"
Scope: Any
Version: 2.0.0
Supported on libModSecurity: Yes
Every rule must provide one or more variables along with the operator that should be used to inspect them. If no actions are provided, the default list will be used. (There is always a default list, even if one was not explicitly set with SecDefaultAction.) If there are actions specified in a rule, they will be merged with the default list to form the final actions that will be used. (The actions in the rule will overwrite those in the default list.) Refer to SecDefaultAction for more information.
Description: Configures whether the current context will inherit the rules from the parent context.
Syntax: SecRuleInheritance On|Off
Example Usage: SecRuleInheritance Off
Scope: Any
Version: 2.0.0-2.9.x
Supported on libModSecurity: TBI
Default: On
Sometimes when you create a more specific configuration context (for example using the container), you may wish to use a different set of rules than those used in the parent context. By setting SecRuleInheritance to Off, you prevent the parent rules to be inherited, which allows you to start from scratch. In ModSecurity 2.5.x it is not possible to override phase 1 rules from a configuration context. There are no limitations in that respect in the current development version (and there won’t be in the next major version).
The 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 , , , and are all used to create configuration contexts. For more information, please go to the Apache documentation, under Configuration Sections http://httpd.apache.org/docs/2.0/sections.html. This directive does not affect how configuration options are inherited.
Description: Configures the rules engine.
Syntax: SecRuleEngine On|Off|DetectionOnly
Example Usage: SecRuleEngine On
Scope: Any
Version: 2.0.0
Supported on libModSecurity: Yes
Default: Off
The possible values are:
- On: process rules
- Off: do not process rules
- DetectionOnly: process rules but never executes any disruptive actions (block, deny, drop, allow, proxy and redirect)
Description: Set a performance threshold for rules. Rules that spend at least the time defined will be logged into audit log Part H as Rules-Performance-Info in the format id=usec, comma separated.
Syntax: SecRulePerfTime USECS
Example Usage: SecRulePerfTime 1000
Scope: Any
Version: 2.7-2.9.x
Supported on libModSecurity: TBI
The rules hitting the threshold can be accessed via the collection PERF_RULES.
Description: Removes the matching rules from the current configuration context.
Syntax: SecRuleRemoveById ID ID RANGE ...
Example Usage: SecRuleRemoveByID 1 2 "9000-9010"
Scope: Any
Version: 2.0.0 - 3.x
Supported on libModSecurity: Yes
This directive supports multiple parameters, each of which can be a rule ID or a range. Parameters that contain spaces must be delimited using double quotes.
- Note : This directive must be specified after the rule in which it is disabling. This should be used within local custom rule files that are processed after third party rule sets. Example file - modsecurity_crs_60_customrules.conf.
Description: Removes the matching rules from the current configuration context.
Syntax: SecRuleRemoveByMsg REGEX
Example Usage: SecRuleRemoveByMsg "FAIL"
Scope: Any
Version: 2.0.0-3.x
Supported on libModSecurity: Yes
Normally, you would use SecRuleRemoveById to remove rules, but that requires the rules to have IDs defined. If they don’t, then you can remove them with SecRuleRemoveByMsg, which matches a regular expression against rule messages.
- Note : This directive must be specified after the rule in which it is disabling. This should be used within local custom rule files that are processed after third party rule sets. Example file - modsecurity_crs_60_customrules.conf.
Description: Removes the matching rules from the current configuration context.
Syntax: SecRuleRemoveByTag REGEX
Example Usage: SecRuleRemoveByTag "WEB_ATTACK/XSS"
Scope: Any
Version: 2.6-3.x
Supported on libModSecurity: Yes
Normally, you would use SecRuleRemoveById to remove rules, but that requires the rules to have IDs defined. If they don’t, then you can remove them with SecRuleRemoveByTag, which matches a regular expression against rule tag data. This is useful if you want to disable entire groups of rules based on tag data. Example tags used in the OWASP ModSecurity CRS include:
- AUTOMATION/MALICIOUS
- AUTOMATION/MISC
- AUTOMATION/SECURITY_SCANNER
- LEAKAGE/SOURCE_CODE_ASP_JSP
- LEAKAGE/SOURCE_CODE_CF
- LEAKAGE/SOURCE_CODE_PHP
- WEB_ATTACK/CF_INJECTION
- WEB_ATTACK/COMMAND_INJECTION
- WEB_ATTACK/FILE_INJECTION
- WEB_ATTACK/HTTP_RESPONSE_SPLITTING
- WEB_ATTACK/LDAP_INJECTION
- WEB_ATTACK/PHP_INJECTION
- WEB_ATTACK/REQUEST_SMUGGLING
- WEB_ATTACK/SESSION_FIXATION
- WEB_ATTACK/SQL_INJECTION
- WEB_ATTACK/SSI_INJECTION
- WEB_ATTACK/XSS
- Note : This directive must be specified after the rule in which it is disabling. This should be used within local custom rule files that are processed after third party rule sets. Example file - modsecurity_crs_60_customrules.conf.
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"
Scope: Any
Version: 2.5.0-3.x
Supported on libModSecurity: Yes
- 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 parameters. for i = 1, #d do -- Examine parameter value. if (string.find(d[i].value, "