ModSecurity Documentation

ModSecurity is an open source, cross-platform web application firewall (WAF) engine, donated to OWASP in 2024. It has a robust event-based programming language which provides protection from a range of attacks against web applications and allows for HTTP traffic monitoring, logging and real-time analysis. Securing tens of millions of domains, ModSecurity is the most widely deployed WAF engine in existence.

Two engine generations are maintained:

  • ModSecurity v2 (current release 2.9.15) — the classic Apache module (mod_security2), also packaged for IIS.
  • libModSecurity v3 (current release 3.0.17) — a standalone library used through connectors for NGINX and Apache.
Warning

This site was migrated from the former GitHub wiki, which is partially outdated. Entries in the reference manual carry version badges for v2 and v3; text still marked for review is being updated against the source code.

Subsections of ModSecurity Documentation

Introduction

ModSecurity is an open source web application firewall (WAF). A WAF adds an external security layer in front of web applications to detect and, if configured to do so, prevent attacks before they reach the application. ModSecurity provides protection from a range of attacks against web applications and allows for HTTP traffic monitoring, logging and real-time analysis with little or no changes to existing infrastructure.

ModSecurity v2 and libModSecurity v3

ModSecurity is developed as two code lines. Both are maintained by the OWASP ModSecurity project (stewardship was transferred from Trustwave to OWASP in 2024) and both implement the same rule language, so rule sets such as the OWASP CRS run on either.

  • ModSecurity v2 (branch v2/master, latest release 2.9.15) is the original implementation: an Apache httpd module (mod_security2) and, built on the same code, a module for Microsoft IIS. Use it when you run Apache httpd or IIS. See ModSecurity v2 for Apache and ModSecurity v2 for Microsoft IIS.
  • libModSecurity v3 (branch v3/master, latest release 3.0.17) is a rewrite of the engine as a standalone C++ library with no Apache dependency. Web servers talk to it through separate connector projects: ModSecurity-nginx is the production-ready connector; ModSecurity-apache exists but its README states it is not production ready, so Apache users should stay on v2. Use v3 when you run NGINX or embed the library in your own application. See Building libModSecurity v3 from source and libModSecurity v3 with NGINX.

Where this manual describes behavior that differs between the two, the difference is called out in the text. Differences that matter when moving from v2 to v3 are collected in Migrating from v2 to v3.

HTTP Traffic Logging

Web servers are typically well-equipped to log traffic in a form useful for marketing analysis, but fall short logging traffic to web applications. In particular, most are not capable of logging the request bodies, which is where most attack payloads travel. 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.

Real-Time Monitoring and Attack Detection

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.

Attack Prevention and Virtual Patching

ModSecurity can also act immediately to prevent attacks from reaching your web applications. There are three commonly used approaches:

  1. Negative security model. A negative security model monitors requests for anomalies, unusual behavior, 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.
  2. 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.
  3. 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 organizations. With ModSecurity, applications can be patched from the outside, without touching the application source code (and even without any access to it), making your systems secure until a proper patch is applied to the application.

Flexible Rule Engine

A flexible rule engine sits in the heart of ModSecurity. It implements the ModSecurity Rule Language (SecLang), which is a specialized 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. ModSecurity ships with no rules of its own; the OWASP CRS is the commonly used general-purpose rule set and implements protocol validation and detection of common web application security issues. Heavily commented, these rules can be used as a learning tool.

Embedded-mode Deployment

ModSecurity is an embeddable web application firewall, which means it can be deployed as part of your existing web server infrastructure: Apache httpd and IIS with v2, NGINX with v3. This deployment method has certain advantages:

  1. 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.
  2. No single point of failure. Unlike with network-based deployments, you will not be introducing a new point of failure to your system.
  3. 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.
  4. 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.
  5. No problem with encrypted or compressed content. Many IDS systems have difficulties analyzing SSL traffic. This is not a problem for ModSecurity because it is positioned to work when the traffic is decrypted and decompressed.

Network-based Deployment

ModSecurity works equally well when deployed as part of a reverse proxy server. In this scenario, one installation of ModSecurity can protect any number of back-end web servers.

Portability

ModSecurity is known to work well on a wide range of operating systems, including Linux, Windows, FreeBSD, OpenBSD, NetBSD, Solaris, AIX and macOS.

Licensing

ModSecurity is available under the Apache Software License v2.

Subsections of Introduction

Frequently Asked Questions

Who Leads the ModSecurity Project?

ModSecurity was created by Ivan Ristić and was later developed and sponsored by Trustwave (SpiderLabs). In January 2024 Trustwave transferred stewardship of the code to the OWASP ModSecurity project, which maintains both the v2 and the v3 code lines today. The current project leaders are listed on the OWASP project page; the active maintainers are visible on the GitHub organization.

Background and Support

What exactly is ModSecurity?

ModSecurity is an open source, free web application firewall (WAF) engine. WAFs establish an external security layer that detects and prevents 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. See the Introduction.

Which version of ModSecurity should I be using? v2.9.x or v3.0.x?

Both code lines are supported and actively maintained by OWASP (current releases: v2.9.15 and v3.0.17). The web server you run decides:

  • Apache httpd: ModSecurity v2 (mod_security2, branch v2/master). The v3 Apache connector exists but is not production ready.
  • Microsoft IIS: ModSecurity v2 (the IIS module is built from the same v2 tree).
  • NGINX: libModSecurity v3 with the ModSecurity-nginx connector. NGINX support was removed from the v2 tree in 2.9.13.
  • Your own application or another server: libModSecurity v3, through its C or C++ API.

Both versions run the OWASP CRS. The rule language is the same; the differences in behavior and the features v3 does not implement are listed in Migrating from v2 to v3.

Where do I get more help on ModSecurity?

Commercial support is not offered by the project itself. Several vendors package ModSecurity and the CRS and support them as part of their products.

Is there anything that I should do prior to creating a new issue?

Yes. There is a good chance that the issue you are facing has already been discussed and, in many cases, either a fix has been produced or a workaround or mitigation has been suggested. Search open and closed issues first. If you cannot find an answer, create a new issue, follow the issue template and supply as much pertinent information as possible: ModSecurity version, connector or web server version, the rule involved and a debug log excerpt.

Will I always get an immediate response to my issue?

GitHub issues are handled on a best-effort basis by volunteers. You may also get assistance from other members of the ModSecurity community.

How do I report a security vulnerability?

Do not open a public issue. Report it privately by creating a draft security advisory on GitHub for the affected repository, for example ModSecurity, ModSecurity-nginx or ModSecurity-apache. The maintainers triage the report there, coordinate a fix and publish the advisory together with the fixed release. Reporters are credited in the advisory.

If you cannot use GitHub, email [email protected] instead.

What about the mailing lists?

The SourceForge mailing lists that the project used in the past are no longer in use. Use GitHub issues instead. Release announcements are published on the GitHub releases pages of each repository.

Where can I find books about Web Application Firewalls and ModSecurity?

The books below predate the v3 code line, but the rule language and the concepts they explain still apply.

ModSecurity Handbook

ModSecurity Handbook is “The definitive guide to the popular open source web application firewall”, written by Ivan Ristić (original author of ModSecurity), later updated by Christian Folini. The book is available from Feisty Duck in hard copy or digital form.

Web Application Defender’s Cookbook: Battling Hackers and Defending Users

The Web Application Defender’s Cookbook: Battling Hackers and Protecting Users is a book written by the former ModSecurity Project Lead Ryan Barnett. The book outlines critical defensive techniques to protect web applications and includes example ModSecurity rules/scripts.

ModSecurity 2.5

ModSecurity 2.5 is “A complete guide to using ModSecurity”, written by Magnus Mischel. The book is available from Packt Publishing in both hard copy and digital forms.

Apache Security

Apache Security is a comprehensive Apache Security resource, written by Ivan Ristić for O’Reilly.

Preventing Web Attacks with Apache

Preventing Web Attacks with Apache. Building on his groundbreaking SANS presentations on Apache security, Ryan C. Barnett reveals why your Web servers represent such a compelling target, how significant exploits are performed, and how they can be defended against.

Getting Started

What type(s) of security models does ModSecurity support?

There is a common misconception that ModSecurity can only be used for negative policy enforcement. This is not the case. ModSecurity does not have any default security model “out-of-the-box.” It is up to the user to implement appropriate rules to achieve the desired security model. That being said, these are the security models which are most often employed:

Negative Security Model - looks for known bad, malicious requests. This method is effective at blocking a large number of automated attacks, however it is not the best approach for identifying new attack vectors. Using too many negative rules may also negatively impact performance.

Positive Security Model - When positive security model is deployed, only requests that are known to be valid are accepted, with everything else rejected. This approach works best with applications that are heavily used but rarely updated.

Virtual Patching - Its rule language makes ModSecurity an ideal external patching tool. External patching is all about reducing the window of opportunity. Time needed to patch application vulnerabilities often runs to weeks in many organizations. With ModSecurity, applications can be patched from the outside, without touching the application source code (and even without any access to it), making your systems secure until a proper patch is produced.

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

I hear that ModSecurity can be run in embedded-mode, what does that mean exactly?

The term “embedded” simply refers to the fact that ModSecurity is running inside the webserver process. Most WAFs function as totally separate hosts and sit in front of the web servers. Running in embedded-mode has some tradeoffs that should be considered:

Advantages

  • Easy to add to an existing web server.
  • Not a point of failure with respect to traffic.

Disadvantages

  • ModSecurity can only protect the local web server.
  • ModSecurity will consume local resources such as CPU and RAM.
  • Management of log files and configurations can become difficult if you have multiple installations.

I hear that ModSecurity can be run in reverse-proxy mode. How does that differ from embedded-mode?

The only difference with this deployment vs. an embedded one is that the web server itself is configured to function as a reverse proxy.

Advantages

  • Single point of access functions as a choke point so you consolidate applying security settings and makes management easier.
  • Network topology is hidden from the outside world so it will be more difficult for attackers to enumerate your web platforms.
  • Increased performance if SSL accelerators/caching used.
  • You can implement vulnerability filters to protect any vulnerable web server or application on the back-end (IIS, ASP, PHP, etc.). See related section on Virtual Patching.

Disadvantages

  • A potential traffic bottleneck if the reverse proxy can not handle the network load.
  • A potential point of failure: if the reverse proxy goes down it may cause a denial of service to the web applications that are behind it.
  • Requires changes to the network.

Configuring ModSecurity

Should I initially set the SecRuleEngine to On?

No. Every rule set can have false positives in new environments. A new installation should initially run with SecRuleEngine set to DetectionOnly (the setting shipped in modsecurity.conf-recommended). After running ModSecurity in detection-only mode for a while, review the events generated and decide if any modification to the rule set should be made before moving to blocking mode.

How do I get ModSecurity to inspect request and response bodies?

You need to set the following two directives:

SecRequestBodyAccess On

SecResponseBodyAccess On

How can I verify exactly how ModSecurity is processing rules and requests?

You need to enable the debug log with SecDebugLog and increase the log level with SecDebugLogLevel. If you set the debug log level to 9, it will tell you exactly what tasks it is completing along with what data it is acting upon. Do be aware that while the increased debug log level does help from a troubleshooting perspective, it does negatively impact performance. See Debugging.

ModSecurity Rules Language

What are the OWASP ModSecurity Core Rules (CRS) and should I use them?

Using ModSecurity requires rules. Installations commonly use one or more of the following:

  • A generic rule set that provides generic protection from unknown vulnerabilities
  • A rule set addressing known CVEs in specific applications
  • Custom rules

The most widely used generic rule set is the OWASP CRS, which is managed by a separate OWASP project. It runs on both ModSecurity v2 and v3.

How do I allow an IP address to bypass ModSecurity?

The first issue to realize is that the allow action is only applied to the current phase. This means that if a rule matches in a subsequent phase it may still take a disruptive action. The recommended rule configuration to allow a remote IP address to bypass ModSecurity rules is to do the following (where 192.168.1.100 should be substituted with the desired IP address):

SecRule REMOTE_ADDR "@ipMatch 192.168.1.100" \
    "id:1000,\
    phase:1,\
    allow,\
    nolog,\
    ctl:ruleEngine=Off"

If you want to allow uninterrupted access to the remote IP address, however you still want to log rule alerts, then you can use this rule:

SecRule REMOTE_ADDR "@ipMatch 192.168.1.100" \
    "id:1000,\
    phase:1,\
    allow,\
    nolog,\
    ctl:ruleEngine=DetectionOnly"

If you want to disable both the rule and audit engines, then you can optionally add another ctl action:

SecRule REMOTE_ADDR "@ipMatch 192.168.1.100" \
    "id:1000,\
    phase:1,\
    allow,\
    nolog,\
    ctl:ruleEngine=Off,\
    ctl:auditEngine=Off"

How do I handle False Positives and creating Custom Rules?

It is inevitable; you will run into some False Positive hits when using web application firewalls. This is not something that is unique to ModSecurity. All web application firewalls will generate false positives from time to time. The directives SecRuleRemoveById, SecRuleUpdateTargetById and the ctl action are the tools for excluding rules or targets. If you use the OWASP CRS, follow the CRS documentation on false positives and tuning.

Will using a large amount of negative filtering rules impact performance?

Yes. Each and every rule that you implement will consume resources (RAM, CPU, etc…). The two most important factors to consider with creating ModSecurity rules are the total number of rules and the Regular Expression optimizations. A single rule with a complex regular expression is significantly faster than multiple rules with simple regular expressions. Unfortunately, it is quite easy to create inefficient RegEx patterns. Optimizing RegExs by utilizing Grouping Only/Non-Capturing Parentheses can cut the validation time by up to 50%. The OWASP CRS is optimized for performance.

What is a Virtual Patch and why should I care?

Fixing identified vulnerabilities in web applications always requires time. Organizations often do not have access to a commercial application’s source code and are at the vendor’s mercy while waiting for a patch. Even if they have access to the code, implementing a patch in development takes time. This leaves a window of opportunity for the attacker to exploit. External patching (also called “just-in-time patching” and “virtual patching”) is one of the biggest advantages of web application firewalls as they can fix this problem externally. A fix for a specific vulnerability is usually very easy to design and in most cases it can be done in less than 15 minutes.

https://cheatsheetseries.owasp.org/cheatsheets/Virtual_Patching_Cheat_Sheet.html

Managing Alerts

How do I manage ModSecurity logs if I have multiple installations?

If you have more than one ModSecurity installation, you have undoubtedly run into issues with consolidating, analyzing and responding to alert messages. The original “Serial” format of the audit log is multi-line with all records held within one file, which makes remote logging difficult. Two options exist:

  • Both v2 and v3 can write the audit log in JSON format (SecAuditLogFormat JSON), one entry per line, which any log shipper can forward to a central system.
  • ModSecurity v2 ships the ModSecurity Log Collector (mlogc), which sends individual audit log entries to a remote host in near real time. mlogc is not part of v3.

Can I send ModSecurity alert log data through Syslog?

Yes. If you already have a central Syslog infrastructure and/or a SIEM, you might want to forward the short ModSecurity alert messages that appear in the web server error log; both Apache and NGINX can send their error logs to syslog. However, the data being forwarded is a very small subset of the entire transaction. It is only a warning message and not enough information to conduct proper incident response to determine if there was a false positive or if it was a legitimate attack. In order to determine this information, you need access to the ModSecurity audit log files. See Logging and Data Formats.

Installation

How to build and install libModSecurity v3 with its connectors, and ModSecurity v2 for Apache and IIS.

Subsections of Installation

Building libModSecurity v3 from source

libModSecurity is a C++17 library. On Unix-like systems it is built with autotools; Windows builds use CMake and Conan and are described in the Windows build README. The library does nothing on its own: after installing it, add a connector for your web server, see libModSecurity v3 with NGINX and libModSecurity v3 with Apache.

If you only need a working installation, your distribution most likely packages the library and the NGINX connector already; see Distribution packages for libModSecurity v3. Build from source when you need the current release before your distribution ships it, a build option the package does not enable (LMDB, Lua, ssdeep), or the development branch.

Dependencies

LibraryStatusWhat it enables
C++17 compiler, GNU autotools, pkg-configrequiredthe build itself
YAJL 2.xrequiredJSON request bodies, JSON audit log, the test suite
PCRE2 (libpcre2-8)required, default@rx and every other regular-expression user. Legacy PCRE 8.x is used instead only with --with-pcre
libxml2 >= 2.6.29optional, auto-detectedXML request body processor, XML variable, @validateDTD, @validateSchema
libcurl >= 7.15.1optional, auto-detectedSecRemoteRules, remote @pmFromFile/@ipMatchFromFile files, the Status Engine
Lua 5.1 to 5.5 or LuaJIToptional, auto-detectedSecRuleScript, exec and @inspectFile with Lua scripts
libmaxminddboptional, auto-detected@geoLookup with GeoLite2/GeoIP2 databases
libfuzzy (ssdeep)optional, auto-detected@fuzzyHash
LMDBoptional, opt-inon-disk persistent collections (SecDataDir); without it collections live in process memory
Flex and Bisononly with --enable-parser-generationregenerating the SecLang parser; the release tarball and the git tree ship a generated parser

When an optional library is missing, the corresponding operator or directive is compiled out and a configuration using it fails to load. LMDB is special: even when the library is installed, it is not used unless you pass --with-lmdb explicitly.

Warning

The legacy MaxMind GeoIP C API (libGeoIP, --with-geoip) is still accepted but deprecated and no longer maintained upstream. Use libmaxminddb with a GeoLite2 or GeoIP2 database instead.

The git tree also carries submodules under others/: libinjection (@detectSQLi, @detectXSS) and mbedtls (hashing and base64 helpers). Both are required for a source build and must be initialized after cloning; the release tarball bundles them.

Package names for the development headers, for the two most common families:

# Debian and Ubuntu
sudo apt install build-essential automake libtool pkg-config libyajl-dev libpcre2-dev libxml2-dev \
    libcurl4-openssl-dev liblua5.4-dev libmaxminddb-dev libfuzzy-dev liblmdb-dev
# Fedora, RHEL and EPEL
sudo dnf install gcc-c++ automake libtool pkgconf yajl-devel pcre2-devel libxml2-devel \
    libcurl-devel lua-devel libmaxminddb-devel ssdeep-devel lmdb-devel

Get the source

Stable release (recommended). The current release is v3.0.17. The release tarball already bundles the git submodules and is signed:

wget https://github.com/owasp-modsecurity/ModSecurity/releases/download/v3.0.17/modsecurity-v3.0.17.tar.gz
wget https://github.com/owasp-modsecurity/ModSecurity/releases/download/v3.0.17/modsecurity-v3.0.17.tar.gz.sha256
wget https://github.com/owasp-modsecurity/ModSecurity/releases/download/v3.0.17/modsecurity-v3.0.17.tar.gz.asc
sha256sum -c modsecurity-v3.0.17.tar.gz.sha256
gpg --verify modsecurity-v3.0.17.tar.gz.asc modsecurity-v3.0.17.tar.gz
tar xzf modsecurity-v3.0.17.tar.gz
cd modsecurity-v3.0.17

Development branch. For the latest code, clone v3/master and initialize the submodules:

git clone --branch v3/master https://github.com/owasp-modsecurity/ModSecurity
cd ModSecurity
git submodule update --init --recursive

Verify that every submodule shows a commit hash in git submodule status; a leading - means it was not initialized and the build will fail.

Build

./build.sh        # git checkout only: generates the configure script
./configure
make
sudo make install

The library is installed under /usr/local/modsecurity by default (--prefix changes that). Because it is a dynamic library, that location must be known to the dynamic linker: add /usr/local/modsecurity/lib to /etc/ld.so.conf.d/ and run ldconfig, or set LD_LIBRARY_PATH. The modsecurity.pc file installed under lib/pkgconfig lets other software find the library through pkg-config.

Run the unit and regression tests after building:

make check

Configure options

Every optional library has a --with-NAME=PATH option that points at an installation prefix, and a --without-NAME form that disables the feature even when the library is present:

OptionDefaultEffect
--with-pcre2=PATHauto-detectedPCRE2, the regular-expression engine used by default
--with-pcre=PATHoffbuild against legacy PCRE 8.x instead of PCRE2
--with-yajl=PATHauto-detected, requiredYAJL location
--with-libxml=PATHauto-detectedlibxml2
--with-curl=PATHauto-detectedlibcurl; versions from 7.34.0 enable TLS 1.2 for remote rule downloads
--with-lua=PATHauto-detectedLua (5.1 to 5.5 or LuaJIT)
--with-maxmind=PATHauto-detectedlibmaxminddb for @geoLookup
--with-geoip=PATHauto-detectedlegacy libGeoIP for @geoLookup (deprecated)
--with-ssdeep=PATHauto-detectedlibfuzzy for @fuzzyHash
--with-lmdb[=PATH]offLMDB-backed persistent collections

Feature switches:

OptionDefaultEffect
--enable-parser-generationoffregenerate the SecLang parser with Flex and Bison instead of using the shipped one. Needed only when you change src/parser/*.yy or *.ll
--disable-examplesexamples builtskip the example programs in examples/
--disable-debug-logsdebug logs builtcompile SecDebugLog support out (NO_LOGS) for a slightly faster library; the regression tests cannot run without it
--enable-assertionsoffkeep assert() checks (undefines NDEBUG)
--enable-mutex-on-pmoffserialize @pm and @pmFromFile evaluation with a mutex; only for debugging suspected races in multi-threaded connectors
--enable-afl-fuzzoffbuild the AFL fuzzing utilities
--enable-valgrindoffrun the unit tests under Valgrind (--disable-valgrind-memcheck and friends select the tools)
--enable-doxygen-* / --disable-doxygen-*HTML onlywhich Doxygen outputs make doxygen-doc produces
Note

The output of ./configure --help is misleading for the library options: because of how they are generated, only --with-yajl is listed, but all of the --with-* options above are accepted. The summary that configure prints at the end shows which libraries were found.

libModSecurity v3 with NGINX

The ModSecurity-nginx connector links libModSecurity into NGINX as a third-party module. Unlike the old (v2-era) standalone module, it is a thin layer between NGINX and the library: the rules engine, the body processors and the logging all live in libModSecurity. The current connector release is v1.0.4.

Distribution packages

Most distributions ship the connector as a dynamic NGINX module built against their own nginx and libmodsecurity packages, which is the easiest way to get a working setup. Versions as of October 2026:

DistributionPackageConnectorlibModSecurity
Debian 12 (bookworm)libnginx-mod-http-modsecurity1.0.33.0.9
Debian 13 (trixie)libnginx-mod-http-modsecurity1.0.33.0.14
Ubuntu 24.04 LTSlibnginx-mod-http-modsecurity1.0.33.0.12
Ubuntu 26.04 LTSlibnginx-mod-http-modsecurity1.0.33.0.14
Fedora 43 and 44, EPEL 9nginx-mod-modsecurity1.0.43.0.16 / 3.0.17
Arch Linuxnginx-mod-modsecurity1.0.43.0.17
Gentoowww-nginx/ngx-modsecurity1.0.43.0.16
FreeBSD portssecurity/modsecurity3-nginx1.0.43.0.17

Ubuntu 22.04 has no connector package in the main archive. Debian, Ubuntu and the Red Hat family also have the current development builds of both the connector and the library in the digitalwave repository, maintained by one of the ModSecurity project leaders.

On Debian and Ubuntu:

sudo apt install libnginx-mod-http-modsecurity modsecurity-crs

The package enables the module through /etc/nginx/modules-enabled/50-mod-http-modsecurity.conf and installs modsecurity.conf (the recommended base configuration, SecRuleEngine DetectionOnly), unicode.mapping and modsecurity_includes.conf into /etc/nginx/, plus a sample site at /etc/nginx/sites-available/default-modsecurity.conf. Turn it on per server or location with modsecurity on; and modsecurity_rules_file /etc/nginx/modsecurity_includes.conf;, and include the CRS from that file by uncommenting the owasp-crs.load line. libModSecurity has no IncludeOptional, so replace that directive by Include in the files the CRS package installs. NGINX reports most CRS events at error_log ... info;.

On Fedora and EPEL:

sudo dnf install nginx-mod-modsecurity

The module is loaded from /usr/share/nginx/modules/mod-modsecurity.conf, the base configuration is installed as /etc/nginx/modsecurity.conf, and /etc/nginx/nginx.conf.modsecurity is a sample server configuration; add the modsecurity directives to your own server blocks as shown below.

Compilation

Get the connector source:

wget https://github.com/owasp-modsecurity/ModSecurity-nginx/releases/download/v1.0.4/ModSecurity-nginx-v1.0.4.tar.gz
wget https://github.com/owasp-modsecurity/ModSecurity-nginx/releases/download/v1.0.4/ModSecurity-nginx-v1.0.4.tar.gz.sha256
wget https://github.com/owasp-modsecurity/ModSecurity-nginx/releases/download/v1.0.4/ModSecurity-nginx-v1.0.4.tar.gz.asc
sha256sum -c ModSecurity-nginx-v1.0.4.tar.gz.sha256
gpg --verify ModSecurity-nginx-v1.0.4.tar.gz.asc ModSecurity-nginx-v1.0.4.tar.gz
tar xzf ModSecurity-nginx-v1.0.4.tar.gz

or clone the development branch with git clone https://github.com/owasp-modsecurity/ModSecurity-nginx. Install libModSecurity first (see Building libModSecurity v3 from source or your distribution’s libmodsecurity-dev / libmodsecurity-devel package). The connector’s config script looks for the library under /usr/local/modsecurity; for any other location export MODSECURITY_INC (the directory holding modsecurity/modsecurity.h) and MODSECURITY_LIB (the directory holding libmodsecurity.so) before running NGINX’s configure.

From the NGINX source directory, add the connector as a static module:

./configure --add-module=/path/to/ModSecurity-nginx
make
sudo make install

Or build it as a dynamic module. The NGINX source version and configure arguments must then match the NGINX binary you load it into (nginx -V prints them):

./configure --add-dynamic-module=/path/to/ModSecurity-nginx --with-compat
make modules

and load it with load_module modules/ngx_http_modsecurity_module.so; at the top of nginx.conf.

The connector runs ModSecurity phase 1 in NGINX’s rewrite phase, phase 2 in the preaccess phase (the development branch has moved it to the access phase, after allow/deny and auth_*), phases 3 and 4 in the header and body filters, and phase 5 in the log phase.

Configuration directives

The connector adds the following directives, all valid in the http, server and location contexts. The modsecurity_rules* directives may be repeated and accumulate; a location inherits the rules of its server.

modsecurity

Syntaxmodsecurity on | off
Defaultoff
ModSecurity v2not supported
libModSecurity v3supported

Turns ModSecurity on or off for the context. This flag only enables the module in NGINX; the rule engine state is controlled separately by SecRuleEngine.

modsecurity_rules_file

Syntaxmodsecurity_rules_file <path to rules file>
ModSecurity v2not supported
libModSecurity v3supported

Loads ModSecurity configuration and rules from a file:

server {
    modsecurity on;
    location / {
        root /var/www/html;
        modsecurity_rules_file /etc/my_modsecurity_rules.conf;
    }
}

modsecurity_rules_remote

Syntaxmodsecurity_rules_remote <key> <URL to rules>
ModSecurity v2not supported
libModSecurity v3supported

Downloads the configuration from a URL, authenticating with the given key, exactly like SecRemoteRules (libModSecurity must be built with libcurl):

server {
    modsecurity on;
    location / {
        root /var/www/html;
        modsecurity_rules_remote my-server-key https://my-own-server/rules/download;
    }
}

modsecurity_rules

Syntaxmodsecurity_rules <modsecurity rules>
ModSecurity v2not supported
libModSecurity v3supported

Embeds rules directly in the NGINX configuration, which is handy for per-location overrides:

server {
    modsecurity on;
    location / {
        root /var/www/html;
        modsecurity_rules_file /etc/my_modsecurity_rules.conf;
    }
    location /ops {
        root /var/www/html/opts;
        modsecurity_rules '
          SecRuleEngine On
          SecDebugLog /tmp/modsec_debug.log
          SecDebugLogLevel 9
          SecRuleRemoveById 10
        ';
    }
}

modsecurity_transaction_id

Syntaxmodsecurity_transaction_id string
ModSecurity v2not supported
libModSecurity v3supported

Supplies the transaction ID from NGINX instead of letting the library generate one. The string may contain NGINX variables, so access-log and audit-log entries can be correlated:

log_format extended '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent" $request_id';

server {
    server_name host1;
    modsecurity on;
    modsecurity_transaction_id "host1-$request_id";
    access_log logs/host1-access.log extended;
    error_log logs/host1-error.log;
    location / {
        ...
    }
}

modsecurity_use_error_log

Syntaxmodsecurity_use_error_log on | off
Defaulton
ModSecurity v2not supported
libModSecurity v3supported (connector development branch only, not in v1.0.4)

Controls whether ModSecurity alert messages are also written to the NGINX error log. This directive exists only on the connector’s master branch; the 1.0.4 release does not know it and refuses to start with it in the configuration. Distribution packages built from release tarballs do not have it either.

libModSecurity v3 with Apache

The ModSecurity-apache connector loads libModSecurity into Apache HTTP Server as the module mod_security3.

Warning

The Apache connector is not production ready. Its only release is v0.0.9-beta1 from December 2017, the master branch has not changed since 2021, request body handling is incomplete, and no distribution packages it. For Apache, use ModSecurity v2 (mod_security2), which is the maintained and recommended engine on that platform.

Compilation

Install libModSecurity first (see Building libModSecurity v3 from source), make sure apxs from the Apache development package is on the path, then:

git clone https://github.com/owasp-modsecurity/ModSecurity-apache
cd ModSecurity-apache
./autogen.sh
./configure
make
sudo make install

Usage

Load the module and point it at a rules file. The directives mirror the NGINX connector’s:

LoadModule security3_module modules/mod_security3.so

modsecurity on
modsecurity_rules_file /etc/my_modsecurity_rules.conf

modsecurity_rules_remote <key> <URL> and modsecurity_rules '<inline rules>' are also available, with the same meaning as in the NGINX connector. All of them are accepted in the server and virtual host configuration and in <Location> and <Directory> blocks.

Distribution packages for libModSecurity v3

Every major distribution packages libModSecurity, and most also package the NGINX connector built against it. The packaged versions lag behind the upstream release, sometimes by several minor versions, but the distributions backport security fixes to the version they ship. Versions in the package repositories as of October 2026:

DistributionLibrary packageVersionNGINX connector packageVersion
Debian 12 (bookworm)libmodsecurity33.0.9libnginx-mod-http-modsecurity1.0.3
Debian 13 (trixie)libmodsecurity3t643.0.14libnginx-mod-http-modsecurity1.0.3
Ubuntu 22.04 LTSlibmodsecurity33.0.6none
Ubuntu 24.04 LTSlibmodsecurity33.0.12libnginx-mod-http-modsecurity1.0.3
Ubuntu 26.04 LTSlibmodsecurity3t643.0.14libnginx-mod-http-modsecurity1.0.3
RHEL 8 family (EPEL 8)libmodsecurity3.0.15none
RHEL 9 family (EPEL 9)libmodsecurity3.0.17nginx-mod-modsecurity1.0.4
Fedora 43libmodsecurity3.0.16nginx-mod-modsecurity1.0.4
Fedora 44libmodsecurity3.0.17nginx-mod-modsecurity1.0.4
openSUSE Leap 15.6libmodsecurity3 (source modsecurity)3.0.10none
openSUSE Tumbleweedlibmodsecurity3 (source modsecurity)3.0.15none
Arch Linuxlibmodsecurity3.0.17nginx-mod-modsecurity1.0.4
Gentoodev-libs/modsecurity3.0.16www-nginx/ngx-modsecurity1.0.4
FreeBSD portssecurity/modsecurity33.0.17security/modsecurity3-nginx1.0.4
macOS (Homebrew)modsecurity3.0.17none

The development headers are in libmodsecurity-dev (Debian, Ubuntu) or libmodsecurity-devel (Fedora, EPEL, openSUSE); install them when you build a connector yourself. The OWASP CRS rule set is packaged as modsecurity-crs on Debian and Ubuntu and mod_security_crs on Fedora and EPEL. Alpine Linux and Amazon Linux 2023 do not package libModSecurity; use the container images or build from source there.

See libModSecurity v3 with NGINX for how the Debian and Fedora connector packages are laid out and enabled.

The digitalwave repository

modsecurity.digitalwave.hu is an APT repository for Debian and Ubuntu maintained by Ervin Hegedüs, co-leader of the ModSecurity project and the Debian maintainer of these packages. It builds the current v2/master and v3/master branches, the NGINX connector and the latest OWASP CRS release for every supported Debian and Ubuntu version, as the same packages the distributions ship, so you get the engine fixes months before they reach a distribution release. Packages are for amd64 only. As of October 2026 it provides:

PackageContentDebian 11, 12, 13 and Ubuntu 22.04, 24.04, 26.04
libapache2-mod-security2ModSecurity v2 for Apache2.9.16 pre-release
libmodsecurity3 / libmodsecurity3t64, libmodsecurity-devlibModSecurity3.0.18 pre-release
libnginx-mod-http-modsecurityNGINX connector1.0.5 pre-release (Debian 12, 13, Ubuntu 24.04, 26.04); on Ubuntu 22.04 as part of a rebuilt nginx 1.18.0
modsecurity-crsOWASP CRS3.3.10

The packages live in the <release>-backports suite of the repository. Ubuntu 22.04 also needs the plain <release> suite, which carries the rebuilt nginx packages the connector is part of there. Add the key, the suite and an APT pin so that only the ModSecurity packages come from this repository:

sudo apt install apt-transport-https lsb-release ca-certificates curl
# Debian 12 and later
sudo wget -qO - https://modsecurity.digitalwave.hu/archive.key | sudo tee /etc/apt/trusted.gpg.d/modsecurity-digitalwave.asc
# Ubuntu 24.04 and later
sudo wget -qO - https://modsecurity.digitalwave.hu/dwmodsec.gpg | sudo tee /etc/apt/trusted.gpg.d/modsecurity-digitalwave.gpg

# Debian (use .../ubuntu/ on Ubuntu)
echo "deb http://modsecurity.digitalwave.hu/debian/ $(lsb_release -sc)-backports main" | sudo tee /etc/apt/sources.list.d/dwmodsec.list

cat << EOF2 | sudo tee /etc/apt/preferences.d/99modsecurity
Package: *libnginx-mod-http-modsecurity*
Pin: origin modsecurity.digitalwave.hu
Pin-Priority: 900

Package: *libapache2-mod-security2*
Pin: origin modsecurity.digitalwave.hu
Pin-Priority: 900

Package: *modsecurity-crs*
Pin: origin modsecurity.digitalwave.hu
Pin-Priority: 900

Package: *libmodsecurity*
Pin: origin modsecurity.digitalwave.hu
Pin-Priority: 900
EOF2
sudo apt update
sudo apt install libnginx-mod-http-modsecurity modsecurity-crs   # or libapache2-mod-security2

Debian 11 and Ubuntu 22.04 use apt-key add - for the key and need both the <release> and <release>-backports lines; the repository page has the exact commands for every release, the full version matrix and the configuration walkthrough. Run apt-cache policy libmodsecurity3 afterwards to confirm the candidate comes from modsecurity.digitalwave.hu. If you previously installed the distribution’s own package, run apt clean first.

Containers

The OWASP CRS project publishes images with NGINX and libModSecurity. owasp/modsecurity contains NGINX with the connector and no rules (tags nginx, 3-<timestamp>, with -alpine variants); owasp/modsecurity-crs bundles the OWASP CRS on top of it and is the image most deployments want. See https://github.com/coreruleset/modsecurity-crs-docker for the tags and the environment variables that configure the engine.

docker run -p 8080:8080 owasp/modsecurity-crs:nginx

Building packages

To build a newer version as a distribution package, rebuild the distribution’s own packaging against the new release rather than starting from scratch; see Building distribution packages.

ModSecurity v2 for Apache

ModSecurity v2 is an Apache httpd module (mod_security2). The current release is v2.9.15. You can install it from your distribution’s package repository, which is the quickest route and gets you security updates through the normal package channels, or build it from source to get the latest release.

Prerequisites

Apache httpd 2.x

ModSecurity 2.x works with Apache httpd 2.0.x or later (2.4.x is the version in common use today). To build from source you need the Apache development files (the apxs tool and headers), which distributions package as httpd-devel or apache2-dev.

mod_unique_id

Make sure you have mod_unique_id loaded. It is packaged with Apache httpd and ModSecurity uses it for the UNIQUE_ID variable and audit log entry identifiers.

libapr and libapr-util

Required. https://apr.apache.org/. APR-util must be compiled with crypto support if you intend to use the crypto parameter of SecRemoteRules; otherwise configure prints a warning and continues.

libpcre2 (or libpcre)

Required. ModSecurity 2.9.x uses PCRE2 by default (https://www.pcre.org/). The legacy PCRE 8.x library is still supported: pass --with-pcre=PATH to configure to use it, in which case the PCRE2 check is skipped.

libxml2

Required. https://gitlab.gnome.org/GNOME/libxml2. Used by the XML request body processor and the @validateDTD/@validateSchema operators.

libyajl

Needed for the JSON request body processor. Configure detects it automatically (--with-yajl=PATH to point at a custom location); without it ModSecurity builds without JSON support.

liblua 5.x

Optional; only needed for SecRuleScript and the exec action with Lua scripts. Lua 5.1 through 5.5 are supported (--with-lua=PATH). https://www.lua.org/download.html

Note

ModSecurity requires the dynamic Lua library. It is not built by default in the Lua source distribution, so the binary package of your distribution is recommended.

libcurl

Optional. Needed for SecRemoteRules and for the ModSecurity Log Collector (mlogc), which sends audit logs to a central repository. Without libcurl, configure disables building mlogc. https://curl.se/libcurl/

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.

libfuzzy (ssdeep)

Optional; only needed for the @fuzzyHash operator (--with-ssdeep=PATH).

Distribution Packages

Every major distribution packages ModSecurity v2 for Apache. Packaged versions lag behind the upstream release, sometimes by several minor versions, but the distributions backport security fixes to the version they ship, so an older version number does not by itself mean an unpatched module. If you need a feature from a newer release, build from source instead.

Versions in the distributions’ package repositories as of October 2026:

DistributionPackageVersion
Debian 12 (bookworm)libapache2-mod-security22.9.7
Debian 13 (trixie)libapache2-mod-security22.9.11
Ubuntu 22.04 LTSlibapache2-mod-security22.9.5
Ubuntu 24.04 LTSlibapache2-mod-security22.9.7
Ubuntu 26.04 LTSlibapache2-mod-security22.9.12
RHEL 8 and 9, AlmaLinux, Rocky Linux, CentOS Stream (EPEL)mod_security2.9.6
RHEL 10 family (EPEL 10)mod_security2.9.14
Fedora 43 and 44mod_security2.9.14
openSUSE Leap 15.6apache2-mod_security22.9.4
openSUSE Tumbleweedapache2-mod_security22.9.12
FreeBSD portswww/mod_security (ap24-mod_security)2.9.15
Gentoowww-apache/mod_security2.9.14
macOS (MacPorts)www/mod_security22.9.15

Alpine Linux, Arch Linux and Amazon Linux 2023 do not package ModSecurity v2; build from source or use the container image there. The OWASP CRS project separately packages the OWASP CRS rule set for most of these distributions (modsecurity-crs on Debian and Ubuntu, mod_security_crs on Fedora and EPEL).

Debian and Ubuntu

sudo apt install libapache2-mod-security2
sudo cp /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf
sudo a2enmod security2
sudo systemctl restart apache2

The package enables the module through /etc/apache2/mods-available/security2.load and security2.conf. The latter sets SecDataDir /var/cache/modsecurity and includes every *.conf file in /etc/modsecurity/, so that directory is where your modsecurity.conf and any local rule files go; unicode.mapping is already installed there. The audit log goes to /var/log/apache2/modsec_audit.log by default. The shipped modsecurity.conf-recommended leaves the engine in DetectionOnly; switch SecRuleEngine to On once you have reviewed the logs.

Current builds from the digitalwave repository

For Debian 11 to 13 and Ubuntu 22.04 to 26.04, the digitalwave repository maintained by a ModSecurity project leader provides libapache2-mod-security2 built from the current v2/master branch (2.9.16 pre-release as of October 2026) together with the latest modsecurity-crs. It is the same package as the distribution’s, so the configuration layout above applies unchanged. Repository setup is described under Distribution packages for libModSecurity v3.

RHEL, AlmaLinux, Rocky Linux, CentOS Stream

The module comes from EPEL (Extra Packages for Enterprise Linux):

sudo dnf install epel-release        # on RHEL itself: dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-$(rpm -E %rhel).noarch.rpm
sudo dnf install mod_security
sudo systemctl restart httpd

Fedora

sudo dnf install mod_security
sudo systemctl restart httpd

On Fedora and EPEL the module is loaded by /etc/httpd/conf.modules.d/10-mod_security.conf (which also loads mod_unique_id if needed) and configured by /etc/httpd/conf.d/mod_security.conf. That file carries the recommended base configuration with SecRuleEngine On already set, response body access off, logs under /var/log/httpd/, persistent data under /var/lib/mod_security, and it includes /etc/httpd/modsecurity.d/*.conf, modsecurity.d/activated_rules/*.conf and modsecurity.d/local_rules/*.conf. Put your own rules in local_rules/.

openSUSE

sudo zypper install apache2-mod_security2
sudo a2enmod security2
sudo systemctl restart apache2

Run rpm -ql apache2-mod_security2 to see where the package placed its configuration and the recommended configuration file.

FreeBSD

pkg install ap24-mod_security

Or build the port from www/mod_security. The port installs the module into the Apache modules directory and the sample configuration files under /usr/local/etc/modsecurity/; add the LoadModule security2_module libexec/apache24/mod_security2.so line to httpd.conf and include your configuration from there.

Gentoo

emerge www-apache/mod_security

Add -D SECURITY to APACHE2_OPTS in /etc/conf.d/apache2 to load the module.

Containers

The OWASP CRS project publishes ready-to-run images for Docker and compatible runtimes. owasp/modsecurity contains Apache httpd with ModSecurity v2 and no rules (tags apache, 2-<timestamp>, with -alpine variants); owasp/modsecurity-crs bundles the OWASP CRS on top of it and is the image most deployments want. See https://github.com/coreruleset/modsecurity-crs-docker for the tags and the environment variables that configure the engine.

docker run -p 8080:8080 owasp/modsecurity-crs:apache

Building from Source

From the release tarball

Releases are published on GitHub as a signed source tarball (no binaries). Install the prerequisites above with their development headers first (for example apt install apache2-dev libpcre2-dev libxml2-dev libyajl-dev liblua5.4-dev libcurl4-openssl-dev on Debian and Ubuntu, or dnf install httpd-devel pcre2-devel libxml2-devel yajl-devel lua-devel libcurl-devel on Fedora and RHEL), then:

wget https://github.com/owasp-modsecurity/ModSecurity/releases/download/v2.9.15/modsecurity-v2.9.15.tar.gz
wget https://github.com/owasp-modsecurity/ModSecurity/releases/download/v2.9.15/modsecurity-v2.9.15.tar.gz.sha256
wget https://github.com/owasp-modsecurity/ModSecurity/releases/download/v2.9.15/modsecurity-v2.9.15.tar.gz.asc
sha256sum -c modsecurity-v2.9.15.tar.gz.sha256
gpg --verify modsecurity-v2.9.15.tar.gz.asc modsecurity-v2.9.15.tar.gz
tar xzf modsecurity-v2.9.15.tar.gz
cd modsecurity-v2.9.15
./configure
make
make install

From git

The repository is hosted on GitHub: https://github.com/owasp-modsecurity/ModSecurity. The v2 code lives on the v2/master branch (the default branch is v3). The list of changes made since the last stable release is in the file CHANGES. A git checkout needs the autotools (autoconf, automake, libtool) in addition to the prerequisites above, and the libinjection submodule:

git clone --branch v2/master https://github.com/owasp-modsecurity/ModSecurity
cd ModSecurity
git submodule update --init --recursive
./autogen.sh
./configure
make
make install

Configure options

Run the configure script to generate a Makefile. Typically no options are needed (./configure --help lists them all); the one you are most likely to need is the location of the apxs command installed by Apache httpd:

./configure --with-apxs=/path/to/httpd-2.x.y/bin/apxs

Options worth knowing:

  1. –enable-pcre-jit - Enables JIT support from PCRE >= 8.20 / PCRE2 that can improve regex performance.
  2. –enable-pcre-study - Enables PCRE pattern studying (WITH_PCRE_STUDY), which can give a slight performance edge.
  3. –enable-lua-cache - Enables Lua VM caching that can improve Lua script performance. The difference only appears if ModSecurity must run more than one script per transaction.
  4. –enable-request-early - Since ModSecurity 2.6 phase 1 runs in Apache’s fixups hook; this option moves it back to the post-read-request hook (see Processing Phases).
  5. –enable-htaccess-config - Allows the following directives to be used in .htaccess files when AllowOverride Options is set: SecAction, SecRule, SecRuleRemoveById, SecRuleRemoveByMsg, SecRuleRemoveByTag, SecRuleUpdateActionById, SecRuleUpdateTargetById, SecRuleUpdateTargetByMsg and SecRuleUpdateTargetByTag.
Note

There are certain configure options that are meant for debugging and other development use. If enabled, these options can substantially impact performance. These options include all --enable-debug-* options as well as the --enable-performance-measurement option.

Testing and installing

Optionally run the unit and regression tests before installing:

make test
Note

Most common test failures are related to not finding the required headers and/or libraries. If you have problems, open an issue with the full output and error from the build.

Optionally build the ModSecurity Log Collector with make mlogc; to install it, review the INSTALL file in the mlogc directory of the distribution. make install copies mod_security2.so into the Apache modules directory reported by apxs; if your layout differs, copy it by hand, for example cp /usr/local/modsecurity/lib/mod_security2.so /usr/local/apache/modules/.

Windows

ModSecurity for Apache httpd on Windows is built with CMake and Visual Studio. The steps and the tested dependency versions are described in README_WINDOWS.md in the v2 source tree; Apache must be built from source with the same compiler. For IIS see ModSecurity v2 for IIS.

Loading and Configuring the Module

Skip this section if you installed a distribution package: the package already loads the module and includes a configuration directory, as described above.

On UNIX (and on Windows if the DLLs are not in the Apache bin directory) you may need to load libxml2 and Lua before ModSecurity if they are not found automatically:

LoadFile /usr/lib/libxml2.so
LoadFile /usr/lib/liblua5.4.so

Load the ModSecurity module in httpd.conf with:

LoadModule security2_module modules/mod_security2.so

Copy modsecurity.conf-recommended from the source tree to your Apache configuration directory as modsecurity.conf, together with unicode.mapping, and include it from httpd.conf. See Recommended Base Configuration. Then add a rule set, typically the OWASP CRS, and restart Apache httpd. You should now have ModSecurity 2.x up and running.

Build Notes

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. Most vendor-packaged Apache distributions are 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 against the latest PCRE2 version downloaded from the PCRE site) using Apache’s --with-pcre configure switch. If you are not in a position to recompile Apache, then, to compile ModSecurity successfully, you need access to the bundled PCRE headers (they are available only in the Apache source code) and must point ModSecurity at them via its --with-pcre or --with-pcre2 configure option.

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, see Migrating from 1.x to 2.x.

ModSecurity v2 for Microsoft IIS

ModSecurity for IIS (ModSecurityIIS.dll) is an IIS native module built from the ModSecurity v2 source tree (v2/master, directory iis/). It shares the engine, the rule language and the configuration file format with the Apache module; only the way the module is loaded and configured differs.

Prerequisites

  • Windows Server with IIS 7 or later.
  • The Microsoft Visual C++ Redistributable matching the compiler the module was built with (the build scripts in the repository use Visual Studio 2019). Install the 32-bit or 64-bit version according to the application pool architecture.
  • The dependency DLLs that ship alongside the module: APR and APR-util, PCRE, libxml2, Lua, libcurl, YAJL, zlib and libfuzzy. The build scripts produce them together with ModSecurityIIS.dll and mlogc.exe.

Obtaining the Module

The project publishes source releases only (https://github.com/owasp-modsecurity/ModSecurity/releases); no Windows binaries or MSI installers are attached to current releases. To build the module and, optionally, the MSI installer, use the scripts in the iis/ directory of the v2 tree (build_release.bat builds the dependencies and the module for x86 and amd64, build_msi.bat builds the WiX installer). The general Windows build notes are in README_WINDOWS.md.

If you use a third-party installer or binary package, make sure it comes from a source you trust and matches the version you expect.

Any installation errors or warning messages from the MSI installer are logged in the Application event log under the ModSecurityIIS Installer source. The installer does not install the OWASP CRS; download it from the CRS project and include it from your ModSecurity configuration file.

Manually Installing and Troubleshooting Setup of ModSecurity Module on IIS

Configuration

After the installation the module will be running in all websites by default. To remove it from a website add to web.config:

<modules>
    <remove name="ModSecurityIIS" />
</modules>

To configure the module in a website add to web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <ModSecurity enabled="true" configFile="c:\inetpub\wwwroot\modsecurity.conf" />
    </system.webServer>
</configuration>

where configFile is a standard ModSecurity configuration file (start from modsecurity.conf-recommended, see Recommended Base Configuration). A relative path can also be used. To load the OWASP CRS, add Include directives for crs-setup.conf and the rules\*.conf files to that configuration file.

Events from the module will show up in the “Application” Windows event log.

Common Problems

If after installation the 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. A dependency walker tool such as Dependencies can be used to figure out which library is missing or cannot be loaded.

See also IIS Troubleshooting.

Building distribution packages

Distribution packages lag behind upstream releases, so it is common to need a package of a newer ModSecurity version, or one built with different options, for a distribution that does not ship it yet. The quickest way to get one is to rebuild the distribution’s own packaging against the newer source tarball rather than writing a spec or debian/ directory from scratch: the packaging already carries the configuration layout, the module loading snippets and the dependencies the distribution expects.

ModSecurity v2 (Apache)

Debian and Ubuntu

The packaging lives at https://salsa.debian.org/debian/modsecurity-apache (source package modsecurity-apache, binary libapache2-mod-security2). To rebuild it against a newer upstream release:

sudo apt install build-essential devscripts
sudo apt build-dep modsecurity-apache
apt source modsecurity-apache
cd modsecurity-apache-*/
uupdate --upstream-version 2.9.15 ../modsecurity-v2.9.15.tar.gz
cd ../modsecurity-apache-2.9.15/
dpkg-buildpackage -us -uc -b

The resulting libapache2-mod-security2_*.deb lands in the parent directory. Download the release tarball as described in ModSecurity v2 for Apache first; apt source needs a deb-src entry in your APT sources.

Fedora, RHEL and EPEL

The packaging lives at https://src.fedoraproject.org/rpms/mod_security (mod_security.spec, the mod_security.conf base configuration and the 10-mod_security.conf module snippet). To rebuild it against a newer upstream release:

sudo dnf install fedpkg rpm-build rpmdevtools
fedpkg clone -a rpms/mod_security
cd mod_security
sudo dnf builddep mod_security.spec
rpmdev-bumpspec --new 2.9.15 mod_security.spec
spectool -g -R mod_security.spec
fedpkg --release rawhide local      # or: rpmbuild -ba mod_security.spec

Use the branch that matches your target (epel9, epel10, f44, …). Check the spec’s %prep section for patches that no longer apply to the newer source; drop them if upstream already contains the fix.

Other systems

  • FreeBSD: the port is www/mod_security; bump PORTVERSION in its Makefile, run make makesum and build with make package.
  • openSUSE: the package is apache2-mod_security2 in the Apache:Modules project on the Open Build Service; branch it with osc branch and update the Version and source tarball in the spec.
  • Gentoo: copy the www-apache/mod_security ebuild to a local overlay under the new version and run ebuild ... manifest.

libModSecurity v3

The same approach applies to the v3 library and the nginx connector: Debian and Ubuntu package libmodsecurity3 (source package modsecurity) and libnginx-mod-http-modsecurity; Fedora and EPEL package libmodsecurity and nginx-mod-modsecurity. Rebuild those packaging sources against the newer release with the commands above.

Reference Manual

The rule language and configuration reference for ModSecurity v2 and libModSecurity v3.

Each directive, variable, transformation, action and operator is documented once. The metadata table under each entry shows the ModSecurity v2 version it first appeared in, and whether libModSecurity v3 supports it.

Badge legend:

BadgeMeaning
since 2.7.0available from that release on
supportedavailable, first release not recorded
not implemented yetaccepted by the parser or planned, but not functional in libModSecurity v3
not supportednot available in that engine
unknownnot verified yet

Subsections of Reference Manual

Processing Phases

ModSecurity, in both v2 and v3, allows rules to be placed in one of the following five phases of an HTTP transaction:

PhaseNameRuns afterData available
1Request headers (REQUEST_HEADERS)the request line and headers have been readREQUEST_*, ARGS_GET, REQUEST_HEADERS, REQUEST_COOKIES
2Request body (REQUEST_BODY)the request body has been read, if SecRequestBodyAccess is Oneverything in phase 1 plus ARGS_POST, ARGS, REQUEST_BODY, FILES*, XML, JSON
3Response headers (RESPONSE_HEADERS)the response status and headers are knownplus RESPONSE_STATUS, RESPONSE_HEADERS
4Response body (RESPONSE_BODY)the response body has been read, if SecResponseBodyAccess is On and the MIME type is inspectedplus RESPONSE_BODY
5Logging (LOGGING)the response has been senteverything; disruptive actions have no effect

In ModSecurity v2 the phases are hooks in the Apache request cycle. In libModSecurity v3 the phases are the process*() calls the connector (for example ModSecurity-nginx) makes on a transaction: processConnection, processURI, processRequestHeaders, processRequestBody, processResponseHeaders, processResponseBody and processLogging. The rule semantics are the same; the differences are listed at the end of this page.

In order to select the phase a rule executes during, use the phase action either directly in the rule or in the SecDefaultAction directive:

SecDefaultAction "phase:2,pass,log"
SecRule REQUEST_HEADERS:Host "!@rx ^$" "id:5,phase:1,deny"

The phase can be given by number or by name: phase:request is phase 2, phase:response is phase 4 and phase:logging is phase 5.

Note

The data available in each phase is cumulative. This means that as you move onto later phases, you have access to more and more data from the transaction.

Note

Keep in mind that rules are executed according to phases, so even if two rules are adjacent in a configuration file, but are set to execute in different phases, they would not happen one after the other. The order of rules in the configuration file is important only within the rules of each phase. This is especially important when using the skip and skipAfter actions.

Note

The LOGGING phase is special. It is executed at the end of each transaction no matter what happened in the previous phases. This means it will be processed even if the request was intercepted or the allow action was used to pass the transaction through.

Warning

Always set phase explicitly on every rule. A rule without a phase action runs in phase 2 in ModSecurity v2 (or in the phase named by the SecDefaultAction that precedes it), but in phase 1 in libModSecurity v3. The OWASP CRS sets the phase on every rule for this reason.

Phase Request Headers

Rules in this phase are processed immediately after the request headers have been received. At this point the request body has not been read yet, meaning not all request arguments are available. Rules should be placed in this phase if you need to have them run early, to do something before the request body has been read, determine whether or not the request body should be buffered, or decide how you want the request body to be processed (e.g. whether to parse it as XML or JSON).

ModSecurity v2 (Apache)

Since ModSecurity 2.6, phase 1 runs in Apache’s fixups hook, after Apache has mapped the request to its <Location>, <Directory> or <Files> context, so rules placed inside those scopes work in phase 1. If ModSecurity was compiled with --enable-request-early, phase 1 runs in the earlier post-read-request hook instead; Apache has not evaluated scope directives at that point, and only <VirtualHost> scope is available. See Miscellaneous Topics.

Phase Request Body

This is the general-purpose input analysis phase. Most of the application-oriented rules should go here. In this phase you are guaranteed to have received the request arguments (provided the request body has been read). Both versions support four request body processors:

  • application/x-www-form-urlencoded - used to transfer form data
  • multipart/form-data - used for file transfers
  • XML - used for passing XML data (ctl:requestBodyProcessor=XML)
  • JSON - used for passing JSON data (ctl:requestBodyProcessor=JSON, requires a build with YAJL)

Other encodings are not used by most web applications. The XML and JSON processors are not selected automatically; modsecurity.conf-recommended contains phase 1 rules that enable them based on the Content-Type header.

Note

In order to access the Request Body phase data, you must have SecRequestBodyAccess set to On.

Phase Response Headers

This phase takes place just before response headers are sent back to the client. Run here if you want to observe the response before that happens, and if you want to use the response headers to determine if you want to buffer the response body.

ModSecurity v2 (Apache)

Some response status codes (such as 404) are handled earlier in the request cycle by Apache and may not be able to be triggered as expected. Additionally, there are some response headers that are added by Apache at a later hook (such as Date, Server and Connection) that ModSecurity is not able to trigger on or sanitize. This should work appropriately in a proxy setup or within phase 5 (logging).

Phase Response Body

This is the general-purpose output analysis phase. At this point you can run rules against the response body (provided it was buffered, of course). This is the phase where you would want to inspect the outbound HTML for information disclosure, error messages or failed authentication text.

Note

In order to access the Response Body phase data, you must have SecResponseBodyAccess set to On and the response MIME type must be listed in SecResponseBodyMimeType. When the body is not inspected, ModSecurity v2 still evaluates phase 4 rules with an empty RESPONSE_BODY; libModSecurity v3 does not evaluate phase 4 at all.

Phase Logging

This phase is run just before logging takes place. The rules placed into this phase can only affect how the logging is performed. You cannot deny/block connections in this phase as it is too late. This phase also allows for inspection of other response headers that weren’t available during phase 3 or phase 4. In ModSecurity v2 this phase can also inspect the error messages logged by Apache (WEBSERVER_ERROR_LOG). Note that you must be careful not to inherit a disruptive action into a rule in this phase as this is a configuration error in ModSecurity 2.5.0 and later versions.

Differences between ModSecurity v2 and libModSecurity v3

  • Default phase. v2: phase 2, or the phase of the preceding SecDefaultAction. v3: phase 1. Always write phase: explicitly.
  • Phase 4 without body inspection. v2 runs phase 4 rules with an empty RESPONSE_BODY; v3 skips the phase entirely when SecResponseBodyAccess is not On or the MIME type is not inspected.
  • Phase 0. v3 accepts phase:0 (connection phase, evaluated when the connector calls processConnection, when only REMOTE_ADDR, REMOTE_HOST, REMOTE_PORT, SERVER_ADDR, SERVER_PORT and UNIQUE_ID are known). v2 has no phase 0.
  • skipAfter with a missing marker. In v2 a skip ends with the current phase. In v3 the pending marker persists across phases: if no SecMarker of that name exists, every remaining rule of every later phase is skipped. Always define the marker.
  • ctl:ruleEngine=Off mid-phase. v2 stops evaluating the rest of the current phase immediately; v3 checks the engine state only when a phase starts, so the remaining rules of the current phase are still evaluated (none of them can interrupt). Place such a rule last in its phase.
  • Web server scopes. In v2 rules can be placed in Apache <VirtualHost>, <Location>, <Directory> and (with --enable-htaccess-config) .htaccess contexts and are merged by Apache’s configuration inheritance. In v3 the connector decides the scopes: ModSecurity-nginx loads rules per http, server or location block via modsecurity_rules_file, modsecurity_rules_remote and modsecurity_rules.

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

Include

Loads another configuration file in place, as if its contents had been written at the position of the directive.

SyntaxInclude /path/to/file.conf
ExampleInclude /etc/modsecurity/rules/*.conf
ScopeAny
ModSecurity v2supported
libModSecurity v3since 3.0.0

In ModSecurity v2 this is the Apache httpd core Include directive; ModSecurity itself does not define it, and the rules files it names are processed by Apache. libModSecurity v3 implements its own Include in the SecLang parser: the parameter may be quoted, may contain a * wildcard matching several files, and may be a relative path, which is tried against the current working directory first and then against the directory of the file that contains the Include. A file that cannot be opened is a configuration error. Nested includes are permitted.

Include modsecurity.conf
Include "/etc/modsecurity/crs/rules/*.conf"

SecAction

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.

SyntaxSecAction "action1,action2,action3,..."
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.0.0

This directive is commonly used to set variables and initialize persistent collections using the initcol action. For example:

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

SecArgumentSeparator

Specifies which character to use as the separator for application/x-www-form- urlencoded content.

SyntaxSecArgumentSeparator character
Default&
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.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.

The parameter must be a single character. Before 2.7.0 the directive was only accepted in the main server configuration; since 2.7.0 it can be used in any configuration context.

SecArgumentsLimit

Configures the maximum number of ARGS that will be accepted for processing.

SyntaxSecArgumentsLimit LIMIT
ExampleSecArgumentsLimit 1000
Default1000 (v2); no limit (v3)
ScopeAny
ModSecurity v2since 2.9.7
libModSecurity v3since 3.0.5

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.

In ModSecurity v2 the default is 1000. libModSecurity v3 applies no limit unless the directive is set.

When using this setting, it is recommended to accompany it with a rule that will test for that same integer value and deny the request if it is reached, like rule 200007 in modsecurity.conf-recommended:

SecRule &ARGS "@ge 1000" \
    "id:'200007',\
    phase:2,\
    deny,\
    status:400,\
    t:none,\
    log,\
    msg:'Failed to fully parse request body due to large argument count'"

Without such a matching rule, an attacker could potentially evade detection by placing the attack payload in a parameter occurring beyond the limit.

SecAuditEngine

Configures the audit logging engine.

SyntaxSecAuditEngine On|Off|RelevantOnly
DefaultOff
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.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))

SecAuditLog

Defines the path to the main audit log file (serial logging format), the concurrent logging index file (concurrent logging format) or, in libModSecurity v3, the destination URL (HTTPS logging format). When used in combination with mlogc (only possible with concurrent logging), this directive defines the mlogc location and command line.

SyntaxSecAuditLog /path/to/audit.log
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.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"

libModSecurity v3 does not ship mlogc. When using SecAuditLogType HTTPS (v3 only), specify the destination URL instead of a path, e.g. SecAuditLog https://xxx.xxx.xxx.xxx:port/.

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.

SecAuditLog2

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

SyntaxSecAuditLog2 /path/to/audit.log
ScopeAny
ModSecurity v2since 2.1.2
libModSecurity v3since 3.0.0

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.

SecAuditLogDirMode

Configures the mode (permissions) of any directories created for the concurrent audit logs, using an octal mode value as parameter (as used in chmod).

SyntaxSecAuditLogDirMode octal_mode|"default"
ExampleSecAuditLogDirMode 02750
Default0750
ScopeAny
ModSecurity v2since 2.5.10
libModSecurity v3since 3.0.0

The default mode for new audit log directories (0750) grants full access to the owner (typically the account under which Apache is running, for example apache) and read/search access to the group. 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. libModSecurity v3 accepts only a numeric value here; the keyword default is a syntax error.

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.

SecAuditLogFormat

Select the output format of the AuditLogs. The format can be either the native AuditLogs format or JSON.

SyntaxSecAuditLogFormat JSON|Native
DefaultNative
ScopeAny
ModSecurity v2since 2.9.1
libModSecurity v3since 3.0.0
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. A libModSecurity v3 build without YAJL still accepts JSON, but every audit log entry is then written as {"error":"ModSecurity was not compiled with JSON support."}.

SecAuditLogFileMode

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.

SyntaxSecAuditLogFileMode octal_mode|"default"
ExampleSecAuditLogFileMode 00640
Default0640
ScopeAny
ModSecurity v2since 2.5.10
libModSecurity v3since 3.0.0

This feature is not available on operating systems not supporting octal file modes. The default mode (0640) grants read/write access to the account writing the file and read access to its group. 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. libModSecurity v3 accepts only a numeric value here; the keyword default is a syntax error.

Note

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

SecAuditLogParts

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.

SyntaxSecAuditLogParts PARTLETTERS
ExampleSecAuditLogParts ABCFHZ
DefaultABCFHZ
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.0.0

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. Not implemented in libModSecurity v3.
  • 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. Not implemented in libModSecurity v3.
  • Z: Final boundary, signifies the end of the entry (mandatory).

SecAuditLogRelevantStatus

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

SyntaxSecAuditLogRelevantStatus REGEX
ExampleSecAuditLogRelevantStatus "^(?:5|4(?!04))"
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.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.

SecAuditLogStorageDir

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

SyntaxSecAuditLogStorageDir /path/to/storage/dir
ExampleSecAuditLogStorageDir /usr/local/apache/logs/audit
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.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.

SecAuditLogType

Configures the type of audit logging mechanism to be used.

SyntaxSecAuditLogType Serial|Concurrent|HTTPS
ExampleSecAuditLogType Serial
DefaultSerial
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.0.0

The possible values are:

  • Serial: Audit log entries will be stored in a single file, specified by SecAuditLog. This is convenient 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). In ModSecurity v2 it is also the only choice if you need to use remote logging (with mlogc). libModSecurity v3 also accepts Parallel as an alias.
  • HTTPS: Only available in libModSecurity v3, and still considered experimental. Each audit log entry is POSTed to the URL given in SecAuditLog instead of being written to a file. Depending on the amount of requests that you have, it may be suitable.
Note

The HTTPS audit log type is not supported by ModSecurity v2.

SecAuditLogPrefix

Configures a text that will be prepended to each audit log line. This directive only exists in libModSecurity v3; ModSecurity v2 does not know it.

SyntaxSecAuditLogPrefix "text"
ExampleSecAuditLogPrefix "[audit.log]: "
ScopeAny
ModSecurity v2not supported
libModSecurity v3since 3.0.15

This parameter is only used when audit log format is set to native. Intended to be used in situations where the log target receives entries from multiple log sources (for example when the audit log is written to stdout using SecAuditLog /dev/stdout).

Example:

SecAuditEngine RelevantOnly
SecAuditLog /dev/stdout
SecAuditLogParts ABHZ
SecAuditLogType Serial
SecAuditLogRelevantStatus ^(?:5|4(?!04))
SecAuditLogPrefix "[audit.log]: "

Audit log:

[audit.log]: ---Lm20Vggw---A--
[audit.log]: [07/Aug/2025:18:00:57 +0200] 17545824577.300397 200.249.12.31 2313 200.249.12.31 80
[audit.log]: ---Lm20Vggw---B--
[audit.log]: GET /test.pl?param1=   test   ¶m2=test2 HTTP/1.1
[audit.log]: Host: www.modsecurity.org
[audit.log]: User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)
[audit.log]: Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
[audit.log]: Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
[audit.log]: Accept-Language: en-us,en;q=0.5
[audit.log]: Accept-Encoding: gzip,deflate
[audit.log]: Keep-Alive: 300
[audit.log]: Connection: keep-alive
[audit.log]: Pragma: no-cache
[audit.log]: Cache-Control: no-cache
[audit.log]:
[audit.log]:
[audit.log]: ---Lm20Vggw---H--
[audit.log]: ModSecurity: Access denied with code 403 (phase 1). Matched "Operator `Contains' with parameter `test' against variable `ARGS:param2' (Value: `test2' ) [file "auditlog.json"] [line "2"] [id "1"] [rev ""] [msg ""] [data ""] [severity "0"] [ver ""] [maturity "0"] [accuracy "0"] [hostname "200.249.12.31"] [uri "/test.pl"] [unique_id "17545824577.300397"] [ref "o0,4v20,10t:trimo0,4v38,5t:trim"]
[audit.log]:
[audit.log]: ---Lm20Vggw---Z--

SecCacheTransformations

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.

SyntaxSecCacheTransformations On|Off [options]
ExampleSecCacheTransformations On "minlen:64,maxlen:0"
ScopeAny
ModSecurity v2since 2.5.0
libModSecurity v3not supported

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.

libModSecurity v3 rejects this directive with a configuration error, so a configuration containing it cannot be shared between v2 and v3.

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.

SecChrootDir

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

SyntaxSecChrootDir /path/to/chroot/dir
ExampleSecChrootDir /chroot
ScopeMain
ModSecurity v2since 2.0.0
libModSecurity v3not supported

libModSecurity v3 rejects this directive with a configuration error, so a configuration containing it cannot be shared between v2 and v3. 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:

  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 wants to use sendmail and sendmail re- sides outside the jail.
  3. 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:

  1. Create /chroot to be your main jail directory.
  2. Create /chroot/opt/apache inside jail.
  3. Create a symlink from /opt/apache to /chroot/opt/apache.
  4. 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 initialization 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.

SecCollectionTimeout

Specifies the collections timeout. Default is 3600 seconds. ModSecurity v2 accepts values from 0 to 2592000 seconds (30 days).

libModSecurity v3 accepts the directive (so that crs-setup.conf loads) but ignores it: v3 collections do not expire through this setting.

SyntaxSecCollectionTimeout seconds
Default3600
ScopeAny
ModSecurity v2since 2.6.3
libModSecurity v3not supported (accepted by the parser but ignored)

SecComponentSignature

Appends component signature to the ModSecurity signature.

SyntaxSecComponentSignature "COMPONENT_NAME/X.Y.Z (COMMENT)"
ExampleSecComponentSignature "core ruleset/2.1.3"
ScopeMain
ModSecurity v2since 2.5.0
libModSecurity v3since 3.0.0

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.

Note

In libModSecurity v3 the component signature is currently only included in the audit log output when the JSON option is used with the SecAuditLogFormat directive.

SecConnEngine

Configures the connections engine. This directive affect the directives: SecConnReadStateLimit and SecConnWriteStateLimit.

SyntaxSecConnEngine On|Off|DetectionOnly
ExampleSecConnEngine On
DefaultOff
ScopeAny
ModSecurity v2since 2.8.0
libModSecurity v3not supported (only Off is accepted)

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

libModSecurity v3 accepts only Off (and ignores it); On and DetectionOnly are rejected with a configuration error.

SecContentInjection

Enables content injection using actions append and prepend.

SyntaxSecContentInjection On|Off
ExampleSecContentInjection On
DefaultOff
ScopeAny
ModSecurity v2since 2.5.0
libModSecurity v3not supported (only Off is accepted)

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. libModSecurity v3 accepts only Off (and ignores it); On is rejected with a configuration error.

Note

This directive must be enabled if you want to use @rsub + the STREAM_ variables to manipulate live transactional data.

SecCookieFormat

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

SyntaxSecCookieFormat 0|1
ExampleSecCookieFormat 0
Default0
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.0.0 (value 0 only)

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.

Since 2.7.0 the directive can be used in any configuration context; before that it was only accepted in the main server configuration.

Note

Only version 0 (Netscape) cookies is currently supported on libModSecurity (v3)

SecCookieV0Separator

Specifies which character to use as the separator for cookie v0 content.

SyntaxSecCookieV0Separator character
Default;
ScopeAny
ModSecurity v2since 2.7.0
libModSecurity v3not supported

The parameter must be a single character. When the directive is not set, ModSecurity v2 splits version 0 cookies on ;, falling back to , when the Cookie header contains no semicolon but a comma followed by a space. The source registers the directive as SecCookiev0Separator; Apache matches directive names case-insensitively, so both spellings work. libModSecurity v3 rejects this directive with a configuration error, so a configuration containing it cannot be shared between v2 and v3.

SecDataDir

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

SyntaxSecDataDir /path/to/dir
ExampleSecDataDir /usr/local/apache/logs/data
ScopeMain
ModSecurity v2since 2.0.0
libModSecurity v3not supported (accepted by the parser but ignored)

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.

libModSecurity v3 accepts the directive (so that modsecurity.conf-recommended loads) but ignores it: collections are kept in memory per process, or, when a backend such as LMDB is compiled in, the storage path is defined by the backend.

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.

SecDebugLog

Path to the ModSecurity debug log file.

SyntaxSecDebugLog /path/to/modsec-debug.log
ExampleSecDebugLog /usr/local/apache/logs/modsec-debug.log
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.0.0

SecDebugLogLevel

Configures the verboseness of the debug log data.

SyntaxSecDebugLogLevel 0|1|2|3|4|5|6|7|8|9
ExampleSecDebugLogLevel 4
Default0
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.0.0

In ModSecurity v2, 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. In libModSecurity v3, always having the debug log active in a production environment is typically not advised; even when investigating a specific issue be aware that using a value of 4 or higher can impact performance significantly.

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

SecDefaultAction

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.

SyntaxSecDefaultAction "action1,action2,action3"
ExampleSecDefaultAction "phase:2,log,auditlog,deny,status:403,tag:'SLA 24/7'"
Defaultphase:2,log,auditlog,pass
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.0.0

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. In ModSecurity v2 it must not contain the chain, skip or skipAfter actions either, and using severity, logdata or transformations (t:) in it is deprecated and logs a warning at startup. In libModSecurity v3 the phase is optional (it defaults to phase 1), only one SecDefaultAction is allowed per phase, t:none is rejected, and block does not count as the required disruptive action.

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

SecDisableBackendCompression

Disables backend compression while leaving the frontend compression enabled.

SyntaxSecDisableBackendCompression On|Off
DefaultOff
ScopeAny
ModSecurity v2since 2.6.0
libModSecurity v3not supported (only Off is accepted)

libModSecurity v3 accepts only Off (and ignores it); On is rejected with a configuration error. 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.

SecHashEngine

Configures the hash engine.

SyntaxSecHashEngine On|Off
ExampleSecHashEngine On
DefaultOff
ScopeAny
ModSecurity v2since 2.7.1
libModSecurity v3not supported (only Off is accepted)

The possible values are:

  • On: Hash engine can process the request/response data.
  • Off: Hash engine will not process any data.

libModSecurity v3 accepts only Off (and ignores it); On is rejected with a configuration error.

Note

Users must enable stream output variables and content injection.

SecHashKey

Define the key that will be used by HMAC.

SyntaxSecHashKey rand|TEXT KeyOnly|SessionID|RemoteIP
ExampleSecHashKey "this_is_my_key" KeyOnly
Defaultrand KeyOnly
ScopeAny
ModSecurity v2since 2.7.1
libModSecurity v3not supported

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. libModSecurity v3 rejects this directive with a configuration error, so a configuration containing it cannot be shared between v2 and v3.

SecHashParam

Define the parameter name that will receive the MAC hash.

SyntaxSecHashParam TEXT
ExampleSecHashParam "hmac"
Defaultcrypt
ScopeAny
ModSecurity v2since 2.7.1
libModSecurity v3not supported

ModSecurity hash engine will add a new parameter to protected HTML elements containing the MAC hash. libModSecurity v3 rejects this directive with a configuration error, so a configuration containing it cannot be shared between v2 and v3.

SecHashMethodRx

Configures what kind of HTML data the hash engine should sign based on regular expression.

SyntaxSecHashMethodRx TYPE REGEX
ExampleSecHashMethodRx HashHref "product_info|list_product"
ScopeAny
ModSecurity v2since 2.7.1
libModSecurity v3not supported

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. libModSecurity v3 rejects this directive with a configuration error, so a configuration containing it cannot be shared between v2 and v3.

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.

SecHashMethodPm

Configures what kind of HTML data the hash engine should sign based on string search algorithm.

SyntaxSecHashMethodPm TYPE "string1 string2 string3..."
ExampleSecHashMethodPm HashHref "product_info list_product"
ScopeAny
ModSecurity v2since 2.7.1
libModSecurity v3not supported

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. libModSecurity v3 rejects this directive with a configuration error, so a configuration containing it cannot be shared between v2 and v3.

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.

SecGeoLookupDb

Defines the path to the database that will be used for geolocation lookups.

SyntaxSecGeoLookupDb /path/to/db
ExampleSecGeoLookupDb /path/to/GeoLiteCity.dat
ScopeMain
ModSecurity v2since 2.5.0
libModSecurity v3since 3.0.0

ModSecurity v2 relies on the free geolocation databases (GeoLite City and GeoLite Country) that can be obtained from MaxMind 1. ModSecurity v2 only supports the legacy GeoIP format; MaxMind’s newer GeoIP2 format is not supported there. The v2 source registers the directive as SecGeoLookupDB (Apache matches directive names case-insensitively). A relative path is resolved against the directory of the configuration file that contains the directive.

libModSecurity v3 supports the newer GeoIP2 (.mmdb) format through libmaxminddb (since 3.0.1), and the legacy GeoIP format when built with --with-geoip. The build must enable one of them, otherwise the directive fails to load.

Note

Recent versions of libModSecurity v3 require libmaxminddb >= 1.4.2 (libmaxminddb-dev and libmaxminddb0 packages). Some users have reported difficulties if libgeoip-dev and libgeoip1 are also installed; removing these latter packages resolved the problem (see issue #2829).

SecGsbLookupDb

Defines the path to the database that will be used for Google Safe Browsing (GSB) lookups.

SyntaxSecGsbLookupDb /path/to/db
ExampleSecGsbLookupDb /path/to/GsbMalware.dat
ScopeMain
ModSecurity v2since 2.6.0
libModSecurity v3not supported

ModSecurity relies on the free Google Safe Browsing database that can be obtained from the Google GSB API 1. The source registers the directive as SecGsbLookupDB (Apache matches directive names case-insensitively). A relative path is resolved against the directory of the configuration file that contains the directive. libModSecurity v3 rejects this directive with a configuration error, so a configuration containing it cannot be shared between v2 and v3.

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

SecGuardianLog

Configures an external program that will receive the information about every transaction via piped logging.

SyntaxSecGuardianLog |/path/to/httpd-guardian [env=[!]VARIABLE]
ExampleSecGuardianLog |/usr/local/apache/bin/httpd-guardian
ScopeMain
ModSecurity v2since 2.0.0
libModSecurity v3not supported

libModSecurity v3 rejects this directive with a configuration error, so a configuration containing it cannot be shared between v2 and v3. 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 1. 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 2. 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. The optional second parameter restricts guardian logging to requests for which the given environment variable is set (or, with the ! prefix, not set), as with Apache’s CustomLog:

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.

SecHttpBlKey

Configures the user’s registered Honeypot Project HTTP BL API Key to use with @rbl.

SyntaxSecHttpBlKey [12 char access key]
ExampleSecHttpBlKey whdkfieyhtnf
ScopeAny
ModSecurity v2since 2.7.0
libModSecurity v3since 3.0.0

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.

SecInterceptOnError

Configures how to respond when rule processing fails.

SyntaxSecInterceptOnError On|Off
ExampleSecInterceptOnError On
DefaultOff
ScopeAny
ModSecurity v2since 2.6.0
libModSecurity v3not supported (only Off is accepted)

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. libModSecurity v3 accepts only Off (and ignores it); On is rejected with a configuration error.

SecMarker

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.

SyntaxSecMarker ID|TEXT
ExampleSecMarker 9999
ScopeAny
ModSecurity v2since 2.5.0
libModSecurity v3since 3.0.0

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 OWASP CRS:

SecMarker BEGIN_HOST_CHECK

SecRule &REQUEST_HEADERS:Host "@eq 0" \
    "id:'960008',\
    phase:2,\
    block,\
    t:none,\
    msg:'Request Missing a Host Header',\
    tag:'PROTOCOL_VIOLATION/MISSING_HEADER_HOST',\
    tag:'WASCTC/WASC-21',\
    tag:'OWASP_TOP_10/A7',\
    tag:'PCI/6.5.10',\
    rev:'2.1.1',\
    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},\
    skipAfter:END_HOST_CHECK"
SecRule REQUEST_HEADERS:Host "@rx ^$" \
    "id:'960008',\
    phase:2,\
    block,\
    t:none,\
    msg:'Request Missing a Host Header',\
    tag:'PROTOCOL_VIOLATION/MISSING_HEADER_HOST',\
    tag:'WASCTC/WASC-21',\
    tag:'OWASP_TOP_10/A7',\
    tag:'PCI/6.5.10',\
    rev:'2.1.1',\
    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

SecPcreMatchLimit

Sets the match limit in the PCRE library.

SyntaxSecPcreMatchLimit value
ExampleSecPcreMatchLimit 1500
Default1500 (v2); PCRE library default (v3)
ScopeMain
ModSecurity v2since 2.5.12
libModSecurity v3since 3.0.10

In ModSecurity v2 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

In ModSecurity v2 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.

libModSecurity v3 accepts the directive since 3.0.0 but only honors it since 3.0.10, where it sets the PCRE match limit for executions of the @rx and @rxGlobal operators. Unless the directive is set, the PCRE library default applies. If the configured limit is exceeded, the variable MSC_PCRE_LIMITS_EXCEEDED will be set.

SecPcreMatchLimitRecursion

Sets the match limit recursion in the PCRE library.

SyntaxSecPcreMatchLimitRecursion value
ExampleSecPcreMatchLimitRecursion 1500
Default1500
ScopeMain
ModSecurity v2since 2.5.12
libModSecurity v3not supported (accepted by the parser but ignored)

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. libModSecurity v3 accepts the directive (so that modsecurity.conf-recommended loads) but ignores it; the PCRE library default applies.

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.

SecReadStateLimit

Establishes a per-IP address limit of how many connections are allowed to be in SERVER_BUSY_READ state.

SyntaxSecReadStateLimit LIMIT
ExampleSecReadStateLimit 50
Default0 (no limit)
ScopeAny
ModSecurity v2since 2.5.13
libModSecurity v3not supported

Deprecated since 2.8.0: it is an alias of SecConnReadStateLimit, accepts the same parameters (including the optional IP match operator) and logs a deprecation warning at startup. libModSecurity v3 does not know this directive; a configuration containing it fails to load.

SecConnReadStateLimit

Establishes a per-IP address limit of how many connections are allowed to be in SERVER_BUSY_READ state.

SyntaxSecConnReadStateLimit LIMIT OPTIONAL_IP_MATCH_OPERATOR
ExampleSecConnReadStateLimit 50 "!@ipMatch 127.0.0.1"
Default0 (no limit)
ScopeAny
ModSecurity v2since 2.8.0
libModSecurity v3not supported

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.

LIMIT must be greater than zero.

Note: This functionality is Apache only.

Note 2: Make sure SecConnEngine is on prior to use this feature.

libModSecurity v3 rejects this directive with a configuration error, so a configuration containing it cannot be shared between v2 and v3.

SecSensorId

Define a sensor ID that will be present into log part H.

SyntaxSecSensorId TEXT
ExampleSecSensorId WAFSensor01
Defaultdefault
ScopeMain
ModSecurity v2since 2.7.0
libModSecurity v3not supported

libModSecurity v3 rejects this directive with a configuration error, so a configuration containing it cannot be shared between v2 and v3.

SecWriteStateLimit

Establishes a per-IP address limit of how many connections are allowed to be in SERVER_BUSY_WRITE state.

SyntaxSecWriteStateLimit LIMIT
ExampleSecWriteStateLimit 50
Default0 (no limit)
ScopeAny
ModSecurity v2since 2.6.0
libModSecurity v3not supported

Deprecated since 2.8.0: it is an alias of SecConnWriteStateLimit, accepts the same parameters (including the optional IP match operator) and logs a deprecation warning at startup. libModSecurity v3 does not know this directive; a configuration containing it fails to load.

SecConnWriteStateLimit

Establishes a per-IP address limit of how many connections are allowed to be in SERVER_BUSY_WRITE state.

SyntaxSecConnWriteStateLimit LIMIT OPTIONAL_IP_MATCH_OPERATOR
ExampleSecConnWriteStateLimit 50 "!@ipMatch 127.0.0.1"
Default0 (no limit)
ScopeAny
ModSecurity v2since 2.8.0
libModSecurity v3not supported

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.

LIMIT must be greater than zero.

Note: This functionality is Apache only.

Note 2: Make sure SecConnEngine is on prior to use this feature.

libModSecurity v3 rejects this directive with a configuration error, so a configuration containing it cannot be shared between v2 and v3.

SecParseXmlIntoArgs

Controls how XML processing is done. If you turn it on with On or OnlyArgs, then XML nodes will appear in ARGS.

SyntaxSecParseXmlIntoArgs Off|On|OnlyArgs
ExampleSecParseXmlIntoArgs Off
DefaultOff
ScopeAny
ModSecurity v2since 2.9.9
libModSecurity v3since 3.0.15

In these cases, the SecArgumentsLimit directive will set the limit to number of loadable arguments.

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:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <level1>
        <level2>foo</level2>
        <level2>bar</level2>
    </level1>
</root>

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)

SecRemoteRules

Load rules from a given file hosted on a HTTPS site.

SyntaxSecRemoteRules [crypto] key https://url
ExampleSecRemoteRules some-key https://www.yourserver.com/plain-text-rules.txt
ScopeAny
ModSecurity v2since 2.9.0
libModSecurity v3since 3.0.0

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.

In ModSecurity v2 the directive can appear only once, the URL must begin with https, and the crypto option requires a build with APR crypto support. libModSecurity v3 takes exactly two parameters, the key and the URL (the crypto option is not accepted), downloads the file with libcurl requiring TLS 1.2 or newer and a verifiable certificate, and parses the content in place; a SecRemoteRulesFailAction must precede the directive to take effect.

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.

SecRemoteRulesFailAction

Action that will be taken if SecRemoteRules specify an URL that ModSecurity was not able to download.

SyntaxSecRemoteRulesFailAction Abort|Warn
ExampleSecRemoteRulesFailAction Abort
DefaultAbort (v2); unset (v3)
ScopeAny
ModSecurity v2since 2.9.0
libModSecurity v3since 3.0.0

In ModSecurity v2 the default action is to Abort whenever there is a problem downloading a given URL. libModSecurity v3 only aborts when the directive is explicitly set to Abort before the SecRemoteRules directive; otherwise (unset or Warn) a failed download is ignored and the configuration loads without the remote rules, with nothing logged.

Note

This directive also influences the behavior of @ipMatchFromFile when used with a HTTPS URI to retrieve the remote file.

SecRequestBodyAccess

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

SyntaxSecRequestBodyAccess On|Off
ExampleSecRequestBodyAccess On
DefaultOff (v2); unset (v3)
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.0.0

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

libModSecurity v3 skips request body processing only when the directive is explicitly set to Off; when it is unset, whatever body the connector hands over is processed. Set it explicitly.

SecRequestBodyInMemoryLimit

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

SyntaxSecRequestBodyInMemoryLimit LIMIT_IN_BYTES
ExampleSecRequestBodyInMemoryLimit 131072
Default131072 (128 KB)
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3not supported

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.

libModSecurity v3 rejects this directive with a configuration error, so a configuration containing it cannot be shared between v2 and v3.

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 1) . If it is a file, ModSecurity will use the file to perform the inspection. If not, the buffer will be used.

SecRequestBodyJsonDepthLimit

Configures the maximum parsing depth that is allowed when parsing a JSON object.

SyntaxSecRequestBodyJsonDepthLimit LIMIT
ExampleSecRequestBodyJsonDepthLimit 5000
Default10000
ScopeAny
ModSecurity v2since 2.9.5
libModSecurity v3since 3.0.6

During parsing of a JSON object, if nesting exceeds the configured depth limit then parsing will halt and REQBODY_ERROR will be set.

SecRequestBodyLimit

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

SyntaxSecRequestBodyLimit LIMIT_IN_BYTES
ExampleSecRequestBodyLimit 134217728
Default134217728 (128 MB) (v2); no limit (v3)
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.0.0

Anything over the limit will be rejected with status code 413 (Request Entity Too Large). ModSecurity v2 enforces the 1 GB hard limit only on ctl:requestBodyLimit; the directive itself accepts any positive value.

In ModSecurity v2 the default is 134217728 bytes (128 MB). libModSecurity v3 applies no limit unless the directive is set; when the limit is exceeded it sets INBOUND_DATA_ERROR and, with SecRequestBodyLimitAction Reject and SecRuleEngine On, rejects the request with status 403.

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.

SecRequestBodyNoFilesLimit

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.

SyntaxSecRequestBodyNoFilesLimit NUMBER_IN_BYTES
ExampleSecRequestBodyNoFilesLimit 131072
Default1048576 (1 MB) (v2); no limit (v3)
ScopeAny
ModSecurity v2since 2.5.0
libModSecurity v3since 3.0.7

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). ModSecurity v2 accepts any positive value; no hard limit is enforced for this directive.

In ModSecurity v2 the default is 1048576 bytes (1 MB). libModSecurity v3 accepts the directive since 3.0.0 but only enforces it since 3.0.7, and applies no limit unless the directive is set.

SecRequestBodyLimitAction

Controls what happens once a request body limit, configured with SecRequestBodyLimit, is encountered

SyntaxSecRequestBodyLimitAction Reject|ProcessPartial
ExampleSecRequestBodyLimitAction ProcessPartial
DefaultReject (v2); unset (v3)
ScopeAny
ModSecurity v2since 2.6.0
libModSecurity v3since 3.0.0

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.

libModSecurity v3 has no default: when the directive is unset, data beyond the limit is discarded and INBOUND_DATA_ERROR is set, but the request is not rejected. Reject only takes effect when SecRuleEngine is On. Set the directive explicitly.

SecRequestEncoding

Declares the character encoding used in requests.

SyntaxSecRequestEncoding ENCODING
ExampleSecRequestEncoding utf-8
ScopeAny
ModSecurity v2supported
libModSecurity v3not supported

ModSecurity v2 accepts and stores the value but never uses it: the encoding is not validated and no request processing depends on it, so the directive has no effect. libModSecurity v3 does not accept it. It is documented only because it still appears in old configurations.

SecResponseBodyLimit

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

SyntaxSecResponseBodyLimit LIMIT_IN_BYTES
ExampleSecResponseBodyLimit 524228
Default524288 (512 KB) (v2); no limit (v3)
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.0.0

Anything over this limit will be rejected; ModSecurity v2 uses status code 500 (Internal Server Error), libModSecurity v3 uses 403 (only when SecRuleEngine is On and SecResponseBodyLimitAction is Reject; OUTBOUND_DATA_ERROR is set in any case). This setting will not affect the responses with MIME types that are not selected for buffering. There is a hard limit of 1 GB.

In ModSecurity v2 the default is 524288 bytes (512 KB). libModSecurity v3 applies no limit unless the directive is set.

SecResponseBodyLimitAction

Controls what happens once a response body limit, configured with SecResponseBodyLimit, is encountered.

SyntaxSecResponseBodyLimitAction Reject|ProcessPartial
ExampleSecResponseBodyLimitAction ProcessPartial
DefaultReject (v2); unset (v3)
ScopeAny
ModSecurity v2since 2.5.0
libModSecurity v3since 3.0.0

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.

Note

When SecRuleEngine is set to DetectionOnly, ModSecurity v2 forces SecResponseBodyLimitAction to ProcessPartial, as it does for SecRequestBodyLimitAction. libModSecurity v3 has no default (unset: data beyond the limit is discarded without rejecting) and only rejects when SecRuleEngine is On.

SecResponseBodyMimeType

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

SyntaxSecResponseBodyMimeType MIMETYPE MIMETYPE ...
ExampleSecResponseBodyMimeType text/plain text/html text/xml
Defaulttext/plain text/html (v2); all types (v3)
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.0.0

Multiple SecResponseBodyMimeType directives can be used to add MIME types. Use SecResponseBodyMimeTypesClear to clear previously configured MIME types and start over.

In ModSecurity v2 the default list is text/plain text/html. libModSecurity v3 has no default list: when the directive is not set, every response type is considered for buffering. libModSecurity v3 compares the configured types verbatim against the lowercased response Content-Type (3.0.17; newer builds also lowercase the configured types), so write them in lowercase.

Note

Users that wish to perform JSON body inspection on response (phase 4) need to add application/json to SecResponseBodyMimeType.

SecResponseBodyMimeTypesClear

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

Note

In libModSecurity v3 the clear is applied when configurations are merged, so it discards every SecResponseBodyMimeType of the same configuration, including those written after it. Put the directive in a parent configuration (e.g. modsecurity.conf) and the new MIME types in a later one.

SyntaxSecResponseBodyMimeTypesClear
ExampleSecResponseBodyMimeTypesClear
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.0.0

SecResponseBodyAccess

Configures whether response bodies are to be buffered.

SyntaxSecResponseBodyAccess On|Off
ExampleSecResponseBodyAccess On
DefaultOff
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.0.0

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.

SecRule

Creates a rule that will analyze the selected variables using the selected operator.

SyntaxSecRule VARIABLES OPERATOR [ACTIONS]
ExampleSecRule ARGS "@rx attack" "phase:1,log,deny,id:1"
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.0.0

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.

SecRuleInheritance

Configures whether the current context will inherit the rules from the parent context.

SyntaxSecRuleInheritance On|Off
ExampleSecRuleInheritance Off
DefaultOn
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3not supported (only Off is accepted)

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

libModSecurity v3 accepts only Off (and ignores it); On is rejected with a configuration error.

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 1. This directive does not affect how configuration options are inherited.

SecRuleEngine

Configures the rules engine.

SyntaxSecRuleEngine On|Off|DetectionOnly
ExampleSecRuleEngine On
DefaultOff (v2); unset (v3)
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.0.0

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)

In ModSecurity v2 the default is Off. libModSecurity v3 leaves the value unset, in which state rules are evaluated and logged but never interrupt the transaction (equivalent to DetectionOnly). Always set it explicitly.

SecRulePerfTime

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.

SyntaxSecRulePerfTime USECS
ExampleSecRulePerfTime 1000
Default0 (off)
ScopeAny
ModSecurity v2since 2.7.0
libModSecurity v3not supported

The rules hitting the threshold can be accessed via the collection PERF_RULES. libModSecurity v3 rejects this directive with a configuration error, so a configuration containing it cannot be shared between v2 and v3.

SecRuleRemoveById

Removes the matching rules from the current configuration context.

SyntaxSecRuleRemoveById ID ID RANGE ...
ExampleSecRuleRemoveByID 1 2 "9000-9010"
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.0.0

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.

SecRuleRemoveByMsg

Removes the matching rules from the current configuration context.

SyntaxSecRuleRemoveByMsg REGEX [REGEX ...]
ExampleSecRuleRemoveByMsg "FAIL"
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.0.0

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

In libModSecurity v3 the parameter is not a regular expression: it is compared against the rule’s msg by case-sensitive string equality.

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.

SecRuleRemoveByTag

Removes the matching rules from the current configuration context.

SyntaxSecRuleRemoveByTag REGEX [REGEX ...]
ExampleSecRuleRemoveByTag "WEB_ATTACK/XSS"
ScopeAny
ModSecurity v2since 2.6.0
libModSecurity v3since 3.0.0

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

In libModSecurity v3 the parameter is not a regular expression: it is compared against each tag of the rule by case-sensitive string equality.

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.

SecRuleScript

SyntaxSecRuleScript /path/to/script.lua [ACTIONS]
ExampleSecRuleScript "/path/to/file.lua" "block"
ScopeAny
ModSecurity v2since 2.5.0
libModSecurity v3since 3.0.0

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. In ModSecurity v2 a relative script path is resolved against the directory of the configuration file that contains the directive, and a build without Lua support ignores the directive with a startup warning instead of failing. libModSecurity v3 resolves a relative path against the working directory, and a build without Lua support refuses to load the configuration (“Lua support was not enabled”).

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 the web server.

Note

Although the software does not enforce including the ‘id’ action, including it is strongly advised. Omitting an id can cause problems.

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, "<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/ (ModSecurity v2) and http://www.lua.org/manual/5.2/ (libModSecurity v3).

Note

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

Note

libModSecurity (aka v3) is compatible with Lua 5.2+.

SecRuleUpdateActionById

Updates the action list of the specified rule.

SyntaxSecRuleUpdateActionById RULEID[:offset] ACTIONLIST
ExampleSecRuleUpdateActionById 12345 "deny,status:403"
ScopeAny
ModSecurity v2since 2.5.0
libModSecurity v3since 3.0.0

This directive will overwrite the action list of the specified rule with the actions provided in the second parameter. It has two limitations: it cannot be used to change the ID or phase of a rule. Only the actions that can appear only once are overwritten. The actions that are allowed to appear multiple times in a list, will be appended to the end of the list.

SecRule ARGS "@rx attack" \
    "id:12345,\
    phase:2,\
    pass,\
    t:lowercase,\
    log,\
    msg:'Message text'"
SecRuleUpdateActionById 12345 \
    "t:none,\
    t:compressWhitespace,\
    deny,\
    status:403,\
    msg:'New message text'"

The effective resulting rule in the previous example will be as follows:

SecRule ARGS "@rx attack" \
    "id:12345,\
    phase:2,\
    deny,\
    status:403,\
    t:lowercase,\
    t:none,\
    t:compressWhitespace,\
    msg:'New Message text'"

The addition of t:none will neutralize any previous transformation functions specified (t:lowercase, in the example).

Note

In ModSecurity v2, if the target rule is a chained rule, you must currently specify chain in the SecRuleUpdateActionById action list as well. In libModSecurity v3, action updates to a chained rule may only be made to the main (first) rule in the chain, and the :offset suffix is not supported (the ID is parsed as a number).

SecRuleUpdateTargetById

Updates the target (variable) list of the specified rule.

SyntaxSecRuleUpdateTargetById RULEID TARGET1[,TARGET2,TARGET3] REPLACED_TARGET
ExampleSecRuleUpdateTargetById 12345 "!ARGS:foo"
ScopeAny
ModSecurity v2since 2.6.0
libModSecurity v3since 3.0.0

This directive will append (or replace) variables to the current target list of the specified rule with the targets provided in the second parameter. Starting with 2.7.0 this feature supports id range.

Explicitly Appending Targets

This is useful for implementing exceptions where you want to externally update a target list to exclude inspection of specific variable(s).

SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/* "@rx [\;\|\`]\W*?\bmail\b" \
    "id:'958895',\
    phase:2,\
    block,\
    capture,\
    t:none,\
    t:htmlEntityDecode,\
    t:compressWhitespace,\
    t:lowercase,\
    msg:'System Command Injection',\
    logdata:'%{TX.0}',\
    tag:'WEB_ATTACK/COMMAND_INJECTION',\
    tag:'WASCTC/WASC-31',\
    tag:'OWASP_TOP_10/A1',\
    tag:'PCI/6.5.2',\
    ctl:auditLogParts=+E,\
    rev:'2.1.1',\
    severity:'2',\
    setvar:'tx.msg=%{rule.msg}',\
    setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},\
    setvar:tx.command_injection_score=+%{tx.critical_anomaly_score},\
    setvar:tx.%{rule.id}-WEB_ATTACK/COMMAND_INJECTION-%{matched_var_name}=%{tx.0}"

SecRuleUpdateTargetById 958895 !ARGS:email

The effective resulting rule in the previous example will append the target to the end of the variable list as follows:

SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/*|!ARGS:email "@rx [\;\|\`]\W*?\bmail\b" \
    "id:'958895',\
    phase:2,\
    block,\
    capture,\
    t:none,\
    t:htmlEntityDecode,\
    t:compressWhitespace,\
    t:lowercase,\
    msg:'System Command Injection',\
    logdata:'%{TX.0}',\
    tag:'WEB_ATTACK/COMMAND_INJECTION',\
    tag:'WASCTC/WASC-31',\
    tag:'OWASP_TOP_10/A1',\
    tag:'PCI/6.5.2',\
    ctl:auditLogParts=+E,\
    rev:'2.1.1',\
    severity:'2',\
    setvar:'tx.msg=%{rule.msg}',\
    setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},\
    setvar:tx.command_injection_score=+%{tx.critical_anomaly_score},\
    setvar:tx.%{rule.id}-WEB_ATTACK/COMMAND_INJECTION-%{matched_var_name}=%{tx.0}""

Note that is is also possible to use regular expressions in the target specification:

SecRuleUpdateTargetById 981172 "!REQUEST_COOKIES:/^appl1_.*/"

Explicitly Replacing Targets

You can also entirely replace the target list to something more appropriate for your environment. For example, lets say you want to inspect REQUEST_URI instead of REQUEST_FILENAME, you could do this:

SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/* "@rx [\;\|\`]\W*?\bmail\b" \
    "id:'958895',\
    phase:2,\
    block,\
    capture,\
    t:none,\
    t:htmlEntityDecode,\
    t:compressWhitespace,\
    t:lowercase,\
    msg:'System Command Injection',\
    logdata:'%{TX.0}',\
    tag:'WEB_ATTACK/COMMAND_INJECTION',\
    tag:'WASCTC/WASC-31',\
    tag:'OWASP_TOP_10/A1',\
    tag:'PCI/6.5.2',\
    ctl:auditLogParts=+E,\
    rev:'2.1.1',\
    severity:'2',\
    setvar:'tx.msg=%{rule.msg}',\
    setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},\
    setvar:tx.command_injection_score=+%{tx.critical_anomaly_score},\
    setvar:tx.%{rule.id}-WEB_ATTACK/COMMAND_INJECTION-%{matched_var_name}=%{tx.0}"

SecRuleUpdateTargetById 958895 REQUEST_URI REQUEST_FILENAME

The effective resulting rule in the previous example replaces the target in the begin of the variable list as follows:

SecRule REQUEST_URI|ARGS_NAMES|ARGS|XML:/* "@rx [\;\|\`]\W*?\bmail\b" \
    "id:'958895',\
    phase:2,\
    block,\
    capture,\
    t:none,\
    t:htmlEntityDecode,\
    t:compressWhitespace,\
    t:lowercase,\
    msg:'System Command Injection',\
    logdata:'%{TX.0}',\
    tag:'WEB_ATTACK/COMMAND_INJECTION',\
    tag:'WASCTC/WASC-31',\
    tag:'OWASP_TOP_10/A1',\
    tag:'PCI/6.5.2',\
    ctl:auditLogParts=+E,\
    rev:'2.1.1',\
    severity:'2',\
    setvar:'tx.msg=%{rule.msg}',\
    setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},\
    setvar:tx.command_injection_score=+%{tx.critical_anomaly_score},\
    setvar:tx.%{rule.id}-WEB_ATTACK/COMMAND_INJECTION-%{matched_var_name}=%{tx.0}""
Note

You could also do the same by using the ctl action with the ruleRemoveById directive. That would be useful if you want to only update the targets for a particular URL, thus conditionally appending targets.

Note

libModSecurity v3 takes only a single rule ID (no ranges) and the target list; the third REPLACED_TARGET parameter is not supported. To replace a target in v3, negate the old one and add the new one in the same list, e.g. SecRuleUpdateTargetById 958895 !REQUEST_FILENAME,REQUEST_URI. If you want to use grouping in a regular expression target, you must enclose it in single quotes:

SecRuleUpdateTargetById 981172 "!REQUEST_COOKIES:/^appl1_.*/"
SecRuleUpdateTargetById 981173 "!REQUEST_COOKIES:'/^(appl1_.*|foo_.*)/'"

SecRuleUpdateTargetByMsg

Updates the target (variable) list of the specified rule by rule message.

SyntaxSecRuleUpdateTargetByMsg TEXT TARGET1[,TARGET2,TARGET3] REPLACED_TARGET
ExampleSecRuleUpdateTargetByMsg "Cross-site Scripting (XSS) Attack" "!ARGS:foo"
ScopeAny
ModSecurity v2since 2.7.0
libModSecurity v3since 3.0.0

This directive will append (or replace) variables to the current target list of the specified rule with the targets provided in the second parameter.

Explicitly Appending Targets

This is useful for implementing exceptions where you want to externally update a target list to exclude inspection of specific variable(s).

SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/* "@rx [\;\|\`]\W*?\bmail\b" \
    "id:'958895',\
    phase:2,\
    block,\
    capture,\
    t:none,\
    t:htmlEntityDecode,\
    t:compressWhitespace,\
    t:lowercase,\
    msg:'System Command Injection',\
    logdata:'%{TX.0}',\
    tag:'WEB_ATTACK/COMMAND_INJECTION',\
    tag:'WASCTC/WASC-31',\
    tag:'OWASP_TOP_10/A1',\
    tag:'PCI/6.5.2',\
    ctl:auditLogParts=+E,\
    rev:'2.1.1',\
    severity:'2',\
    setvar:'tx.msg=%{rule.msg}',\
    setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},\
    setvar:tx.command_injection_score=+%{tx.critical_anomaly_score},\
    setvar:tx.%{rule.id}-WEB_ATTACK/COMMAND_INJECTION-%{matched_var_name}=%{tx.0}"

SecRuleUpdateTargetByMsg "System Command Injection" !ARGS:email

The effective resulting rule in the previous example will append the target to the end of the variable list as follows:

SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/*|!ARGS:email "@rx [\;\|\`]\W*?\bmail\b" \
    "id:'958895',\
    phase:2,\
    block,\
    capture,\
    t:none,\
    t:htmlEntityDecode,\
    t:compressWhitespace,\
    t:lowercase,\
    msg:'System Command Injection',\
    logdata:'%{TX.0}',\
    tag:'WEB_ATTACK/COMMAND_INJECTION',\
    tag:'WASCTC/WASC-31',\
    tag:'OWASP_TOP_10/A1',\
    tag:'PCI/6.5.2',\
    ctl:auditLogParts=+E,\
    rev:'2.1.1',\
    severity:'2',\
    setvar:'tx.msg=%{rule.msg}',\
    setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},\
    setvar:tx.command_injection_score=+%{tx.critical_anomaly_score},\
    setvar:tx.%{rule.id}-WEB_ATTACK/COMMAND_INJECTION-%{matched_var_name}=%{tx.0}""

Explicitly Replacing Targets

You can also entirely replace the target list to something more appropriate for your environment. For example, lets say you want to inspect REQUEST_URI instead of REQUEST_FILENAME, you could do this:

SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/* "@rx [\;\|\`]\W*?\bmail\b" \
    "id:'958895',\
    phase:2,\
    block,\
    capture,\
    t:none,\
    t:htmlEntityDecode,\
    t:compressWhitespace,\
    t:lowercase,\
    msg:'System Command Injection',\
    logdata:'%{TX.0}',\
    tag:'WEB_ATTACK/COMMAND_INJECTION',\
    tag:'WASCTC/WASC-31',\
    tag:'OWASP_TOP_10/A1',\
    tag:'PCI/6.5.2',\
    ctl:auditLogParts=+E,\
    rev:'2.1.1',\
    severity:'2',\
    setvar:'tx.msg=%{rule.msg}',\
    setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},\
    setvar:tx.command_injection_score=+%{tx.critical_anomaly_score},\
    setvar:tx.%{rule.id}-WEB_ATTACK/COMMAND_INJECTION-%{matched_var_name}=%{tx.0}"

SecRuleUpdateTargetByMsg "System Command Injection" REQUEST_URI REQUEST_FILENAME

The effective resulting rule in the previous example will append the target to the end of the variable list as follows:

SecRule REQUEST_URI|ARGS_NAMES|ARGS|XML:/* "@rx [\;\|\`]\W*?\bmail\b" \
    "id:'958895',\
    phase:2,\
    block,\
    capture,\
    t:none,\
    t:htmlEntityDecode,\
    t:compressWhitespace,\
    t:lowercase,\
    msg:'System Command Injection',\
    logdata:'%{TX.0}',\
    tag:'WEB_ATTACK/COMMAND_INJECTION',\
    tag:'WASCTC/WASC-31',\
    tag:'OWASP_TOP_10/A1',\
    tag:'PCI/6.5.2',\
    ctl:auditLogParts=+E,\
    rev:'2.1.1',\
    severity:'2',\
    setvar:'tx.msg=%{rule.msg}',\
    setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},\
    setvar:tx.command_injection_score=+%{tx.critical_anomaly_score},\
    setvar:tx.%{rule.id}-WEB_ATTACK/COMMAND_INJECTION-%{matched_var_name}=%{tx.0}""
Note

libModSecurity v3 takes only the message and the target list; the third REPLACED_TARGET parameter is not supported. To replace a target in v3, negate the old one and add the new one in the same list, e.g. SecRuleUpdateTargetByMsg "System Command Injection" !REQUEST_FILENAME|REQUEST_URI. The message is compared by case-sensitive string equality.

SecRuleUpdateTargetByTag

Updates the target (variable) list of the specified rule by rule tag.

SyntaxSecRuleUpdateTargetByTag TEXT TARGET1[,TARGET2,TARGET3] REPLACED_TARGET
ExampleSecRuleUpdateTargetByTag "WEB_ATTACK/XSS" "!ARGS:foo"
ScopeAny
ModSecurity v2since 2.7.0
libModSecurity v3since 3.0.0

This directive will append (or replace) variables to the current target list of the specified rule with the targets provided in the second parameter.

Explicitly Appending Targets

This is useful for implementing exceptions where you want to externally update a target list to exclude inspection of specific variable(s).

SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/* "@rx [\;\|\`]\W*?\bmail\b" \
    "id:'958895',\
    phase:2,\
    block,\
    capture,\
    t:none,\
    t:htmlEntityDecode,\
    t:compressWhitespace,\
    t:lowercase,\
    msg:'System Command Injection',\
    logdata:'%{TX.0}',\
    tag:'WEB_ATTACK/COMMAND_INJECTION',\
    tag:'WASCTC/WASC-31',\
    tag:'OWASP_TOP_10/A1',\
    tag:'PCI/6.5.2',\
    ctl:auditLogParts=+E,\
    rev:'2.1.1',\
    severity:'2',\
    setvar:'tx.msg=%{rule.msg}',\
    setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},\
    setvar:tx.command_injection_score=+%{tx.critical_anomaly_score},\
    setvar:tx.%{rule.id}-WEB_ATTACK/COMMAND_INJECTION-%{matched_var_name}=%{tx.0}"

SecRuleUpdateTargetByTag "WASCTC/WASC-31" !ARGS:email

The effective resulting rule in the previous example will append the target to the end of the variable list as follows:

SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/*|!ARGS:email "@rx [\;\|\`]\W*?\bmail\b" \
    "id:'958895',\
    phase:2,\
    block,\
    capture,\
    t:none,\
    t:htmlEntityDecode,\
    t:compressWhitespace,\
    t:lowercase,\
    msg:'System Command Injection',\
    logdata:'%{TX.0}',\
    tag:'WEB_ATTACK/COMMAND_INJECTION',\
    tag:'WASCTC/WASC-31',\
    tag:'OWASP_TOP_10/A1',\
    tag:'PCI/6.5.2',\
    ctl:auditLogParts=+E,\
    rev:'2.1.1',\
    severity:'2',\
    setvar:'tx.msg=%{rule.msg}',\
    setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},\
    setvar:tx.command_injection_score=+%{tx.critical_anomaly_score},\
    setvar:tx.%{rule.id}-WEB_ATTACK/COMMAND_INJECTION-%{matched_var_name}=%{tx.0}""

Explicitly Replacing Targets

You can also entirely replace the target list to something more appropriate for your environment. For example, lets say you want to inspect REQUEST_URI instead of REQUEST_FILENAME, you could do this:

SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/* "@rx [\;\|\`]\W*?\bmail\b" \
    "id:'958895',\
    phase:2,\
    block,\
    capture,\
    t:none,\
    t:htmlEntityDecode,\
    t:compressWhitespace,\
    t:lowercase,\
    msg:'System Command Injection',\
    logdata:'%{TX.0}',\
    tag:'WEB_ATTACK/COMMAND_INJECTION',\
    tag:'WASCTC/WASC-31',\
    tag:'OWASP_TOP_10/A1',\
    tag:'PCI/6.5.2',\
    ctl:auditLogParts=+E,\
    rev:'2.1.1',\
    severity:'2',\
    setvar:'tx.msg=%{rule.msg}',\
    setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},\
    setvar:tx.command_injection_score=+%{tx.critical_anomaly_score},\
    setvar:tx.%{rule.id}-WEB_ATTACK/COMMAND_INJECTION-%{matched_var_name}=%{tx.0}"

SecRuleUpdateTargetByTag "WASCTC/WASC-31" REQUEST_URI REQUEST_FILENAME

The effective resulting rule in the previous example will append the target to the end of the variable list as follows:

SecRule REQUEST_URI|ARGS_NAMES|ARGS|XML:/* "@rx [\;\|\`]\W*?\bmail\b" \
    "id:'958895',\
    phase:2,\
    block,\
    capture,\
    t:none,\
    t:htmlEntityDecode,\
    t:compressWhitespace,\
    t:lowercase,\
    msg:'System Command Injection',\
    logdata:'%{TX.0}',\
    tag:'WEB_ATTACK/COMMAND_INJECTION',\
    tag:'WASCTC/WASC-31',\
    tag:'OWASP_TOP_10/A1',\
    tag:'PCI/6.5.2',\
    ctl:auditLogParts=+E,\
    rev:'2.1.1',\
    severity:'2',\
    setvar:'tx.msg=%{rule.msg}',\
    setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},\
    setvar:tx.command_injection_score=+%{tx.critical_anomaly_score},\
    setvar:tx.%{rule.id}-WEB_ATTACK/COMMAND_INJECTION-%{matched_var_name}=%{tx.0}""
Note

libModSecurity v3 takes only the tag and the target list; the third REPLACED_TARGET parameter is not supported. To replace a target in v3, negate the old one and add the new one in the same list, e.g. SecRuleUpdateTargetByTag "WASCTC/WASC-31" !REQUEST_FILENAME|REQUEST_URI. The tag is compared by case-sensitive string equality.

SecServerSignature

Instructs ModSecurity to change the data presented in the “Server:” response header token.

SyntaxSecServerSignature "WEB SERVER SOFTWARE"
ExampleSecServerSignature "Microsoft-IIS/6.0"
ScopeMain
ModSecurity v2since 2.0.0
libModSecurity v3not supported

libModSecurity v3 rejects this directive with a configuration error, so a configuration containing it cannot be shared between v2 and v3. 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.

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.

SecStatusEngine

Controls Status Reporting functionality. Uses DNS-based reporting to send software version information to the ModSecurity Project team.

SyntaxSecStatusEngine On|Off
ExampleSecStatusEngine On
DefaultOff
ScopeAny
ModSecurity v2since 2.8.0
libModSecurity v3not supported (accepted by the parser but ignored)

libModSecurity v3 accepts the directive (so that modsecurity.conf-recommended loads) but ignores it: nothing is ever sent. If SecStatusEngine directive is not present, it is disabled. If SecStatusEngine is marked as On, the following information will be shared with the ModSecurity project team when the web server is started:

  • Anonymous unique id for the server
  • Version of:
    • ModSecurity
    • Web Server Software (Apache, IIS, Nginx, Java)
    • APR
    • Libxml2
    • Lua
    • PCRE
Note

This is an example of the information presented in the Apache error_log representing what data will be sent:

[Mon Jan 20 10:55:22.001020 2014] [:notice] [pid 18231:tid 140735189168512] ModSecurity: StatusEngine call: "2.7.7,Apache/2.4.4 (Unix),1.4.6/1.4.6, 8.32 /8.32 2012-11-30,Lua 5.1/(null),2.7.8/(null),96ce9ba3c2fb71f7a8bb92a88d560d44dbe459b8"
[Mon Jan 20 10:55:22.089012 2014] [:notice] [pid 18231:tid 140735189168512] ModSecurity: StatusEngine call successfully submitted.

SecStreamInBodyInspection

Configures the ability to use stream inspection for inbound request data in a re-allocable buffer. For security reasons we are still buffering the stream.

SyntaxSecStreamInBodyInspection On|Off
ExampleSecStreamInBodyInspection On
DefaultOff
ScopeAny
ModSecurity v2since 2.6.0
libModSecurity v3not supported

This feature enables the creation of the STREAM_INPUT_BODY variable and is useful for data modification or to match data in raw data for any content-types.

Note

This directive provides full access to REQUEST_BODY payload data. It does not include REQUEST_URI or REQUEST_HEADER data. Also it provides data to all kind of content types, different than REQUEST_BODY.

Note

This directive is NOT supported for libModSecurity (v3): it is rejected with a configuration error, so a configuration containing it cannot be shared between v2 and v3. Naturally, STREAM_INPUT_BODY is also NOT supported on libModSecurity.

Note

This directive may significantly impact file upload times. The impact depends on server resources and the nature of operations being performed on the request bodies being streamed in.

SecStreamOutBodyInspection

Configures the ability to use stream inspection for outbound request data in a re-allocable buffer. For security reasons we are still buffering the stream.

SyntaxSecStreamOutBodyInspection On|Off
ExampleSecStreamOutBodyInspection On
DefaultOff
ScopeAny
ModSecurity v2since 2.6.0
libModSecurity v3not supported

This feature enables the creation of the STREAM_OUTPUT_BODY variable and is useful when you need to do data modification into response body. libModSecurity v3 rejects this directive with a configuration error, so a configuration containing it cannot be shared between v2 and v3.

Note

This directive provides access to RESPONSE_BODY payload data. It does not include RESPONSE_HEADER data.

SecTmpDir

Configures the directory where temporary files will be created.

SyntaxSecTmpDir /path/to/dir
ExampleSecTmpDir /tmp
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3not supported (accepted by the parser but ignored)

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

As of ModSecurity version 3.0, SecTmpDir is no longer supported. libModSecurity is able to deal with request body in a file or in a buffer (chunked or not). 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.

SecTmpSaveUploadedFiles

Configures whether or not files uploaded via a multipart POST request will be temporarily saved to the file system.

SyntaxSecTmpSaveUploadedFiles On|Off
ExampleSecTmpSaveUploadedFiles On
DefaultOff
ScopeAny
ModSecurity v2supported
libModSecurity v3since 3.0.0

When set to On, uploaded files are extracted to the upload directory (SecUploadDir) while the transaction is processed, even when SecUploadKeepFiles is Off, so that operators such as @inspectFile can examine them. The files are automatically deleted after the transaction is complete. If you wish to retain the files, see SecUploadKeepFiles. Both ModSecurity v2 and libModSecurity v3 implement this directive.

SecUnicodeMapFile

Defines the path to the file that will be used by the urlDecodeUni transformation function to map Unicode code points during normalization and specifies the code page to use.

In ModSecurity v2 the code page parameter is optional (accepted since 2.7.5; before that it was set with SecUnicodeCodePage), and a relative path is resolved against the directory of the configuration file that contains the directive. In libModSecurity v3 the code page parameter is mandatory, and a relative path is tried against the working directory first and then against the directory of the configuration file.

SyntaxSecUnicodeMapFile /path/to/unicode.mapping [CODEPAGE]
ExampleSecUnicodeMapFile unicode.mapping 20127
ScopeMain
ModSecurity v2since 2.6.1
libModSecurity v3since 3.0.0
Note

With libModSecurity v3 you may need to place the unicode.mapping file in the same directory where the modsecurity.conf file is located.

SecUnicodeCodePage

Defines which Unicode code point will be used by the urlDecodeUni transformation function during normalization.

SyntaxSecUnicodeCodePage XXXXX
ExampleSecUnicodeCodePage 20127
ScopeMain
ModSecurity v2since 2.6.1
libModSecurity v3not supported

Deprecated in ModSecurity 2.7.5: SecUnicodeMapFile now accepts the code page as its second parameter. libModSecurity v3 does not accept this directive.

SecUploadDir

Configures the directory where intercepted files will be stored.

SyntaxSecUploadDir /path/to/dir
ExampleSecUploadDir /tmp
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.0.0

This directory must be on the same filesystem as the temporary directory defined with SecTmpDir. This directive is used with SecUploadKeepFiles. In ModSecurity v2 the value none unsets the directory (useful in a child configuration context).

SecUploadFileLimit

Configures the maximum number of file uploads processed in a multipart POST.

SyntaxSecUploadFileLimit number|"default"
ExampleSecUploadFileLimit 10
Default100 (v2); no limit (v3)
ScopeAny
ModSecurity v2since 2.5.12
libModSecurity v3since 3.0.0

In ModSecurity v2 the default is set to 100 files, but you are encouraged to reduce this value; the value default reverts to it. libModSecurity v3 applies no limit unless the directive is set, accepts only a numeric value (the keyword default is a syntax error), and only counts files when they are being extracted (SecUploadKeepFiles or SecTmpSaveUploadedFiles On). Any file over the limit will not be extracted and the MULTIPART_FILE_LIMIT_EXCEEDED and MULTIPART_STRICT_ERROR flags will be set. To prevent bypassing any file checks, you must check for one of these flags.

Note

If the limit is exceeded, the part name and file name will still be recorded in FILES_NAME and FILES, the file size will be recorded in FILES_SIZES, but there will be no record in FILES_TMPNAMES as a temporary file was not created.

SecUploadFileMode

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

SyntaxSecUploadFileMode octal_mode|"default"
ExampleSecUploadFileMode 0640
Default0600
ScopeAny
ModSecurity v2since 2.1.6
libModSecurity v3since 3.0.0

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. libModSecurity v3 accepts only a numeric value (the keyword default is a syntax error); when unset, files are created with mode 0600. Releases 3.0.15 through 3.0.17 parse the value as a decimal number rather than octal, so 0640 is applied as mode 01200; earlier releases parse it as octal.

Note

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

SecUploadKeepFiles

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

SyntaxSecUploadKeepFiles On|Off|RelevantOnly
ExampleSecUploadKeepFiles On
DefaultOff
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.0.0 (RelevantOnly is rejected)

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

RelevantOnly is not yet supported on libModSecurity

SecWebAppId

Creates an application namespace, allowing for separate persistent session and user storage.

SyntaxSecWebAppId "NAME"
ExampleSecWebAppId "WebApp1"
Defaultdefault
ScopeAny
ModSecurity v2since 2.0.0
libModSecurity v3since 3.0.0

Application namespaces are used to avoid collisions between session IDs and user IDs when multiple applications are deployed on the same server. If it isn’t used, a collision between session IDs might occur.

<VirtualHost *:80> 
ServerName app1.example.com 
SecWebAppId "App1" ...
</VirtualHost>

<VirtualHost *:80> 
ServerName app2.example.com 
SecWebAppId "App2" ...
</VirtualHost>

In the two examples configurations shown, SecWebAppId is being used in conjunction with the Apache VirtualHost directives. Applications namespace information is also recorded in the audit logs (using the WebApp-Info header of the H part).

With libModSecurity v3 the same separation is achieved through the connector’s configuration, for example nginx server blocks. The configured value is available in the WEBAPPID variable.

server {
    listen 80;
    server_name app1.example.com;
    modsecurity_rules 'SecWebAppId "App1"';
    ...
}

server {
    listen 80;
    server_name app2.example.com;
    modsecurity_rules 'SecWebAppId "App2"';
    ...
}

SecXmlExternalEntity

Enable or Disable the loading process of xml external entity. Loading external entity without correct verifying process can lead to a security issue.

SyntaxSecXmlExternalEntity On|Off
ExampleSecXmlExternalEntity Off
DefaultOff
ScopeAny
ModSecurity v2since 2.7.3
libModSecurity v3since 3.0.0

NOTE: You must enable this directive if you need to use the @validateSchema or @validateDtd operators.

Variables

The following variables are supported in ModSecurity v2 and libModSecurity v3. Each entry states which engine supports it; where the two engines behave differently, the difference is described in the entry.

ARGS

ModSecurity v2supported
libModSecurity v3supported

ARGS is a collection and can be used on its own (means all arguments including the POST Payload), with a static parameter (matches arguments with that name), or with a regular expression (matches all arguments with name that matches the regular expression). To look at only the query string or body arguments, see the ARGS_GET and ARGS_POST collections.

Some variables are actually collections, which are expanded into more variables at runtime. The following example will examine all request arguments:

SecRule ARGS dirty "id:7"

Sometimes, however, you will want to look only at parts of a collection. This can be achieved with the help of the selection operator(colon). The following example will only look at the arguments named p (do note that, in general, requests can contain multiple arguments with the same name):

SecRule ARGS:p dirty "id:8"

It is also possible to specify exclusions. The following will examine all request arguments for the word dirty, except the ones named z (again, there can be zero or more arguments named z):

SecRule ARGS|!ARGS:z dirty "id:9"

There is a special operator that allows you to count how many variables there are in a collection. The following rule will trigger if there is more than zero arguments in the request (ignore the second parameter for the time being):

SecRule &ARGS !^0$ "id:10"

And sometimes you need to look at an array of parameters, each with a slightly different name. In this case you can specify a regular expression in the selection operator itself. The following rule will look into all arguments whose names begin with id_:

SecRule ARGS:/^id_/ dirty "id:11"

Note

Using ARGS:p will not result in any invocations against the operator if argument p does not exist.

Note

Matching in the selection operator (both string and regular expression forms) is performed in a case-insensitive manner.

In ModSecurity 1.X, the ARGS variable stood for QUERY_STRING + POST_PAYLOAD, whereas now it expands to individual variables.

ARGS_COMBINED_SIZE

ModSecurity v2supported
libModSecurity v3supported

Contains the combined size of all request parameters. Files are excluded from the calculation. This variable can be useful, for example, to create a rule to ensure that the total size of the argument data is below a certain threshold. The following rule detects a request whose parameters are more than 2500 bytes long:

SecRule ARGS_COMBINED_SIZE "@gt 2500" "id:12"

libModSecurity v3 renders the value as a floating-point number (for example 2512.000000), so compare it with numeric operators such as @gt rather than with @eq or a regular expression on the digits.

ARGS_GET

ModSecurity v2since 2.5.0
libModSecurity v3supported

ARGS_GET is similar to ARGS, but contains only query string parameters.

ARGS_GET_NAMES

ModSecurity v2since 2.5.0
libModSecurity v3supported

ARGS_GET_NAMES is similar to ARGS_NAMES, but contains only the names of query string parameters.

ARGS_NAMES

ModSecurity v2supported
libModSecurity v3supported

Contains all request parameter names. You can search for specific parameter names that you want to inspect. In a positive policy scenario, you can also whitelist (using an inverted rule with the exclamation mark) only the authorized argument names. This example rule allows only two argument names: p and a:

SecRule ARGS_NAMES "!^(p|a)$" "id:13"

ARGS_POST

ModSecurity v2since 2.5.0
libModSecurity v3supported

ARGS_POST is similar to ARGS, but only contains arguments from the POST body.

ARGS_POST_NAMES

ModSecurity v2since 2.5.0
libModSecurity v3supported

ARGS_POST_NAMES is similar to ARGS_NAMES, but contains only the names of request body parameters.

AUTH_TYPE

ModSecurity v2supported
libModSecurity v3supported

This variable holds the authentication method used to validate a user, if any of the methods built into HTTP are used. In a reverse-proxy deployment, this information will not be available if the authentication is handled in the backend web server.

SecRule AUTH_TYPE "Basic" "id:14"

libModSecurity v3 takes the value from the request itself: the first word of the Authorization request header, if any.

DURATION

ModSecurity v2since 2.6.0
libModSecurity v3supported

Contains the time elapsed since the beginning of the current transaction. The unit differs between engines and versions: ModSecurity 2.6.0 reported milliseconds, ModSecurity 2.7.0 and later report microseconds, and libModSecurity v3 reports a floating-point number of seconds (CPU time consumed by the process since the transaction was created, not wall-clock time).

ENV

ModSecurity v2supported
libModSecurity v3supported

Collection that provides access to environment variables set by ModSecurity (via the setenv action) or other server modules. Requires a single parameter to specify the name of the desired variable; a regular-expression selector (ENV:/…/) is not accepted.

libModSecurity v3 reads the environment of its own process (plus anything written there by setenv); the name is matched case-sensitively, a bare ENV returns every environment variable, and ENV:/regex/ is accepted by the parser but treated as a literal name.

# Set environment variable
SecRule REQUEST_FILENAME "@rx printenv" \
    "id:15,\
    phase:2,\
    pass,\
    setenv:tag=suspicious"

# Inspect environment variable
SecRule ENV:tag "@rx suspicious" "id:16"

# Reading an environment variable from other Apache module (mod_ssl)
SecRule TX:ANOMALY_SCORE "@gt 0" "id:16,phase:5,msg:'%{env.ssl_cipher}'"
Note

Use setenv to set environment variables to be accessed by Apache.

FILES

ModSecurity v2supported
libModSecurity v3supported

Contains a collection of original file names (as they were called on the remote user’s filesystem). Available only on inspected multipart/form-data requests.

SecRule FILES "@rx \.conf$" "id:17"

Note

Only available if files were extracted from the request body.

FILES_COMBINED_SIZE

ModSecurity v2supported
libModSecurity v3supported

Contains the total size of the files transported in request body. Available only on inspected multipart/form-data requests.

SecRule FILES_COMBINED_SIZE "@gt 100000" "id:18"

FILES_NAMES

ModSecurity v2supported
libModSecurity v3supported

Contains a list of form fields that were used for file upload. Available only on inspected multipart/form-data requests.

SecRule FILES_NAMES "^upfile$" "id:19"

FULL_REQUEST

ModSecurity v2since 2.8.0
libModSecurity v3supported

Contains the complete request: Request line, Request headers and Request body (if any). The last available only if SecRequestBodyAccess was set to On. Note that all properties of SecRequestBodyAccess will be respected here, such as: SecRequestBodyLimit.

SecRule FULL_REQUEST "User-Agent: ModSecurity Regression Tests" "id:21"

Note

Available on version 2.8.0+

Note

The libModSecurity v3 implementation omits the request line: FULL_REQUEST contains the request headers followed by the request body.

FULL_REQUEST_LENGTH

ModSecurity v2since 2.8.0
libModSecurity v3supported

Contains the size, in bytes, of the request headers plus the request body (the request line is not counted).

SecRule FULL_REQUEST_LENGTH "@eq 205" "id:21"

Note

Available on version 2.8.0+

FILES_SIZES

ModSecurity v2supported
libModSecurity v3supported

Contains a list of individual file sizes. Useful for implementing a size limitation on individual uploaded files. Available only on inspected multipart/form-data requests.

SecRule FILES_SIZES "@gt 100" "id:20"

FILES_TMPNAMES

ModSecurity v2supported
libModSecurity v3supported

Contains a list of temporary files’ names on the disk. Useful when used together with @inspectFile: the executed script can use the provided filename to open the file and examine the contents. Available only on inspected multipart/form-data requests.

SecRule FILES_TMPNAMES "@inspectFile /path/to/inspect_script.pl" "id:21"

libModSecurity v3 writes temporary files only when SecUploadKeepFiles or SecTmpSaveUploadedFiles is On (RelevantOnly is rejected there); @inspectFile alone does not create them, so this collection is otherwise empty.

FILES_TMP_CONTENT

ModSecurity v2since 2.9.0
libModSecurity v3supported

Contains a key-value set where value is the content of the file which was uploaded. Useful when used together with @fuzzyHash.

SecRule FILES_TMP_CONTENT "@fuzzyHash $ENV{CONF_DIR}/ssdeep.txt 1" "id:192372,log,deny"

Note

Available on version 2.9.0-RC1+

Note

In ModSecurity v2 the temporary files only exist when SecUploadKeepFiles is On or RelevantOnly, or when a rule uses @inspectFile; otherwise this collection is empty. libModSecurity v3 keeps the file content in memory but only while it is also writing the temporary file, that is when SecUploadKeepFiles or SecTmpSaveUploadedFiles is On; the collection is keyed by the part name (since 3.0.9).

GEO

ModSecurity v2since 2.5.0
libModSecurity v3supported

GEO is a collection populated by the results of the last @geoLookup operator. The collection can be used to match geographical fields looked from an IP address or hostname.

Available since ModSecurity 2.5.0.

Fields:

  • COUNTRY_CODE: Two character country code. EX: US, GB, etc.
  • COUNTRY_CODE3: Up to three character country code.
  • COUNTRY_NAME: The full country name.
  • COUNTRY_CONTINENT: The two character continent that the country is located. EX: EU
  • REGION: The two character region. For US, this is state. For Canada, providence, etc.
  • CITY: The city name if supported by the database.
  • POSTAL_CODE: The postal code if supported by the database.
  • LATITUDE: The latitude if supported by the database.
  • LONGITUDE: The longitude if supported by the database.
  • DMA_CODE: The metropolitan area code if supported by the database. (US only)
  • AREA_CODE: The phone system area code. (US only)

Example:

SecGeoLookupDb /usr/local/geo/data/GeoLiteCity.dat
...
SecRule REMOTE_ADDR "@geoLookup" "id:22,drop,msg:'Non-GB IP address',chain"
    SecRule GEO:COUNTRY_CODE "!@streq GB"

With libModSecurity v3 (MaxMind GeoLite2 database; a build that uses the legacy GeoIP library instead fills the full field list above, while the MaxMind lookup only sets COUNTRY_CODE, COUNTRY_NAME, COUNTRY_CONTINENT, CITY, POSTAL_CODE, LATITUDE and LONGITUDE):

SecGeoLookupDB /usr/share/GeoIP/GeoLite2-Country.mmdb
...
SecRule REMOTE_ADDR "@geoLookup" "id:22,drop,msg:'Non-GB IP address',chain"
    SecRule GEO:COUNTRY_CODE "!@streq GB" ""

GLOBAL

ModSecurity v2supported
libModSecurity v3supported

Persistent collection shared by all transactions, in the same configuration namespace (see SecWebAppId). It must be initialized with the initcol action before it can be read or written; the collection is stored by SecDataDir (v2) or the persistent storage backend (v3) and the values survive across requests. In ModSecurity v2 a selector is mandatory (GLOBAL:name or GLOBAL:/regex/).

libModSecurity v3 keeps GLOBAL, IP, RESOURCE, SESSION and USER in memory, per process, by default: the data is not shared between worker processes and is lost on restart. A build configured with –with-lmdb stores them in an LMDB database (./modsec-shared-collections in the working directory) instead. SecDataDir is rejected by the v3 parser, SecCollectionTimeout is not supported, and expirevar is the only expiry mechanism.

SecAction "id:91,phase:1,pass,nolog,initcol:global=global"
SecRule REQUEST_URI "@rx ^/login" \
    "id:92,\
    phase:1,\
    pass,\
    nolog,\
    setvar:global.login_attempts=+1"

HIGHEST_SEVERITY

ModSecurity v2supported
libModSecurity v3supported

This variable holds the highest severity of any rules that have matched so far. Severities are numeric values and thus can be used with comparison operators such as @lt, and so on. A value of 255 indicates that no severity has been set. In ModSecurity v2 a severity of 0 (EMERGENCY) is never recorded, and within a chain only the final rule of the chain updates this variable.

SecRule HIGHEST_SEVERITY "@le 2" "phase:2,id:23,deny,status:500,msg:'severity %{HIGHEST_SEVERITY}'"

Note

Higher severities have a lower numeric value.

INBOUND_DATA_ERROR

ModSecurity v2supported
libModSecurity v3supported

This variable will be set to 1 when the request body size is above the setting configured by SecRequestBodyLimit directive. libModSecurity v3 (3.0.7 and later) also sets it, together with REQBODY_ERROR, when a body without files exceeds SecRequestBodyNoFilesLimit. Your policies should always contain a rule to check this variable. Depending on the rate of false positives and your default policy you should decide whether to block or just warn when the rule is triggered.

The best way to use this variable is as in the example below:

SecRule INBOUND_DATA_ERROR "@eq 1" "phase:2,id:24,t:none,log,pass,msg:'Request Body Larger than SecRequestBodyLimit Setting'"

IP

ModSecurity v2supported
libModSecurity v3supported

Persistent collection keyed by a client address, typically initialized with the initcol action using REMOTE_ADDR. It is commonly used to track per-client state (for example, anomaly scores or request rates) across transactions. In ModSecurity v2 a selector is mandatory (IP:name or IP:/regex/). For where libModSecurity v3 stores the data, see GLOBAL.

SecAction "id:93,phase:1,pass,nolog,initcol:ip=%{REMOTE_ADDR}"
SecRule ARGS "@rx attack" \
    "id:94,\
    phase:2,\
    pass,\
    nolog,\
    setvar:ip.score=+5,\
    expirevar:ip.score=3600"
SecRule IP:score "@gt 20" "id:95,phase:2,deny"

MATCHED_VAR

ModSecurity v2since 2.5.0
libModSecurity v3supported

This variable holds the value of the most-recently matched variable. It is similar to the TX:0, but it is automatically supported by all operators and there is no need to specify the capture action.

SecRule ARGS "@rx pattern" "id:25,deny,chain"
    SecRule MATCHED_VAR "@rx further scrutiny"
Note

Be aware that this variable holds data for the last operator match. This means that if there are more than one matches, only the last one will be populated. Use MATCHED_VARS variable if you want all matches.

MATCHED_VARS

ModSecurity v2since 2.6.0
libModSecurity v3supported

Similar to MATCHED_VAR except that it is a collection of all matches for the current operator check.

SecRule ARGS "@rx pattern" "id:26,deny,chain"
    SecRule MATCHED_VARS "@eq ARGS:param"

MATCHED_VAR_NAME

ModSecurity v2since 2.5.0
libModSecurity v3supported

This variable holds the full name of the variable that was matched against.

SecRule ARGS "@rx pattern" "id:27,deny,chain"
    SecRule MATCHED_VAR_NAME "@eq ARGS:param"
Note

Be aware that this variable holds data for the last operator match. This means that if there are more than one matches, only the last one will be populated. Use MATCHED_VARS_NAMES variable if you want all matches.

MATCHED_VARS_NAMES

ModSecurity v2since 2.6.0
libModSecurity v3supported

Similar to MATCHED_VAR_NAME except that it is a collection of all matches for the current operator check.

SecRule ARGS "@rx pattern" "id:28,deny,chain"
    SecRule MATCHED_VARS_NAMES "@eq ARGS:param"

MODSEC_BUILD

ModSecurity v2since 2.5.0
libModSecurity v3supported

This variable holds the ModSecurity build number. This variable is intended to be used to check the build number prior to using a feature that is available only in a certain build. Example:

SecRule MODSEC_BUILD "!@ge 02050102" "id:29,skipAfter:12345"
SecRule ARGS "@pm some key words" "id:12345,deny,status:500"

libModSecurity v3 build numbers follow the same scheme: two digits each for the major, minor and patch level, followed by the three-digit tag number 100 (for example 030017100 for 3.0.17):

SecRule MODSEC_BUILD "!@ge 030017100" "id:29,skipAfter:12345"
SecRule ARGS "@pm some key words" "id:12345,deny,status:500"

MSC_PCRE_ERROR

ModSecurity v2not supported
libModSecurity v3since 3.0.10

libModSecurity v3 only: set to 1 when the @rx or @rxGlobal operator fails with any PCRE error, for example an invalid pattern after macro expansion or a match-limit error (in the latter case MSC_PCRE_LIMITS_EXCEEDED is set as well). ModSecurity v2 has no equivalent variable.

MSC_PCRE_LIMITS_EXCEEDED

ModSecurity v2not supported
libModSecurity v3since 3.0.10

MSC_PCRE_LIMITS_EXCEEDED will be set to 1 if an execution of either the @rx or @rxGlobal operator exceeds the limits set by SecPcreMatchLimit.

ModSecurity v2 does not provide this as a standalone variable (SecRule MSC_PCRE_LIMITS_EXCEEDED is a configuration error). Since 2.5.12, when @rx, @validateHash or the hash engine (SecHashEngine) hits SecPcreMatchLimit or SecPcreMatchLimitRecursion, v2 sets the transaction variable TX:MSC_PCRE_LIMITS_EXCEEDED to 1; test it with SecRule TX:/^MSC_/ "!@streq 0", as rule 200005 in modsecurity.conf-recommended does. For compatibility, libModSecurity v3 (since 3.0.10) also sets the synonym TX:MSC_PCRE_LIMITS_EXCEEDED.

MULTIPART_BOUNDARY_QUOTED

ModSecurity v2supported
libModSecurity v3supported

Flag variable set to 1 when the boundary parameter of the multipart/form-data Content-Type header was quoted. One of the flags aggregated by MULTIPART_STRICT_ERROR.

MULTIPART_BOUNDARY_WHITESPACE

ModSecurity v2supported
libModSecurity v3supported

Flag variable set to 1 when whitespace was found around the boundary parameter of the multipart/form-data Content-Type header. One of the flags aggregated by MULTIPART_STRICT_ERROR.

MULTIPART_CRLF_LF_LINES

ModSecurity v2supported
libModSecurity v3supported

This flag variable will be set to 1 whenever a multi-part request uses mixed line terminators. The multipart/form-data RFC requires CRLF sequence to be used to terminate lines. Since some client implementations use only LF to terminate lines you might want to allow them to proceed under certain circumstances (if you want to do this you will need to stop using MULTIPART_STRICT_ERROR and check each multi-part flag variable individually, avoiding MULTIPART_LF_LINE). However, mixing CRLF and LF line terminators is dangerous as it can allow for evasion. Therefore, in such cases, you will have to add a check for MULTIPART_CRLF_LF_LINES.

MULTIPART_CRLF_LINE

ModSecurity v2supported
libModSecurity v3not supported

Flag variable set to 1 when the multipart parser encountered a line terminated with CRLF. It is informational (the RFC requires CRLF) and is mainly useful together with MULTIPART_LF_LINE and MULTIPART_CRLF_LF_LINES. ModSecurity v2 only; libModSecurity v3 does not provide it.

MULTIPART_DATA_AFTER

ModSecurity v2supported
libModSecurity v3supported

Flag variable set to 1 when data was found after the final multipart boundary. One of the flags aggregated by MULTIPART_STRICT_ERROR.

MULTIPART_DATA_BEFORE

ModSecurity v2supported
libModSecurity v3supported

Flag variable set to 1 when data was found before the first multipart boundary. One of the flags aggregated by MULTIPART_STRICT_ERROR.

MULTIPART_DUPLICATE_PART_HEADER

ModSecurity v2since 2.9.15
libModSecurity v3since 3.0.17

Flag variable set to 1 when a multipart part repeats a part header, or when the Content-Disposition header repeats its name, filename or filename* parameter (a part carrying both filename and filename* is not flagged). The part is also rejected as a parsing error, so REQBODY_ERROR is set as well. One of the flags aggregated by MULTIPART_STRICT_ERROR. Added together with MULTIPART_FILENAME_CHARSET and MULTIPART_FILENAME_LANGUAGE in ModSecurity 2.9.15 and libModSecurity 3.0.17.

MULTIPART_FILENAME

ModSecurity v2since 2.7.3
libModSecurity v3supported

This variable contains the multipart data from field FILENAME. In ModSecurity 2.9.15 and later, when the part carries an RFC 5987 filename* parameter, its percent-decoded value is used instead of filename.

MULTIPART_FILENAME_CHARSET

ModSecurity v2since 2.9.15
libModSecurity v3since 3.0.17

Collection (keyed by part name) holding the charset given in an RFC 5987 filename* parameter of a multipart Content-Disposition header (for example UTF-8 in filename*=UTF-8’‘report.pdf). Only populated for parts that use filename*. Available in ModSecurity 2.9.15 and libModSecurity 3.0.17 and later.

MULTIPART_FILENAME_LANGUAGE

ModSecurity v2since 2.9.15
libModSecurity v3since 3.0.17

Collection (keyed by part name) holding the optional language tag given in an RFC 5987 filename* parameter of a multipart Content-Disposition header (for example en in filename*=UTF-8’en’report.pdf). Only populated for parts that use filename*; the value is empty when no language is given. Available in ModSecurity 2.9.15 and libModSecurity 3.0.17 and later.

MULTIPART_FILE_LIMIT_EXCEEDED

ModSecurity v2supported
libModSecurity v3supported (accepted by the parser but never populated)

Flag variable set to 1 when the number of files in a multipart/form-data request exceeded SecUploadFileLimit. One of the flags aggregated by MULTIPART_STRICT_ERROR.

libModSecurity v3 accepts the variable but never assigns it a value: the condition is only visible through MULTIPART_STRICT_ERROR and REQBODY_ERROR, and it is only detected while files are being written to disk (SecUploadKeepFiles or SecTmpSaveUploadedFiles On).

MULTIPART_HEADER_FOLDING

ModSecurity v2supported
libModSecurity v3supported

Flag variable set to 1 when a multipart part header used header folding (a continuation line starting with whitespace). One of the flags aggregated by MULTIPART_STRICT_ERROR.

MULTIPART_INVALID_HEADER_FOLDING

ModSecurity v2supported
libModSecurity v3supported

Flag variable set to 1 when a multipart part header used invalid header folding. One of the flags aggregated by MULTIPART_STRICT_ERROR.

MULTIPART_INVALID_PART

ModSecurity v2since 2.7.0
libModSecurity v3supported

Flag variable set to 1 when the multipart parser found a part it could not parse (for example a part without a proper header block). It is checked by rule 200002 in modsecurity.conf-recommended together with the other multipart flags.

MULTIPART_INVALID_QUOTING

ModSecurity v2since 2.5.11
libModSecurity v3supported

Flag variable set to 1 when invalid quoting was found in a multipart Content-Disposition header. One of the flags aggregated by MULTIPART_STRICT_ERROR.

MULTIPART_LF_LINE

ModSecurity v2supported
libModSecurity v3supported

Flag variable set to 1 when the multipart parser encountered a line terminated with a bare LF instead of CRLF. One of the flags aggregated by MULTIPART_STRICT_ERROR; see also MULTIPART_CRLF_LF_LINES.

MULTIPART_MISSING_SEMICOLON

ModSecurity v2supported
libModSecurity v3supported

Flag variable set to 1 when the Content-Disposition header of a multipart part lacked the semicolon after form-data. One of the flags aggregated by MULTIPART_STRICT_ERROR. libModSecurity v3 also accepts the misspelled alias MULTIPART_SEMICOLON_MISSING.

MULTIPART_NAME

ModSecurity v2since 2.7.3
libModSecurity v3supported

This variable contains the multipart data from field NAME.

MULTIPART_PART_HEADERS

ModSecurity v2since 2.9.6
libModSecurity v3since 3.0.8

This variable is a collection of all part headers found within the request body with Content-Type multipart/form-data. The key of each item in the collection is the name of the part in which it was found, while the value is the entire part-header line – including both the part-header name and the part-header value.

SecRule MULTIPART_PART_HEADERS:parm1 "@rx content-type:.*jpeg" "phase:2,deny,status:403,id:500074,t:lowercase"

Note

Available in ModSecurity v2.9.6 and libModSecurity v3.0.8 and later.

MULTIPART_STRICT_ERROR

ModSecurity v2since 2.1.3
libModSecurity v3supported

MULTIPART_STRICT_ERROR will be set to 1 when any of the following variables is also set to 1: REQBODY_ERROR, MULTIPART_BOUNDARY_QUOTED, MULTIPART_BOUNDARY_WHITESPACE, MULTIPART_DATA_BEFORE, MULTIPART_DATA_AFTER, MULTIPART_DUPLICATE_PART_HEADER, MULTIPART_HEADER_FOLDING, MULTIPART_LF_LINE, MULTIPART_MISSING_SEMICOLON, MULTIPART_INVALID_QUOTING, MULTIPART_INVALID_PART, MULTIPART_INVALID_HEADER_FOLDING, MULTIPART_FILE_LIMIT_EXCEEDED. Each of these variables covers one unusual (although sometimes legal) aspect of the request body in multipart/form-data format. Your policies should always contain a rule to check either this variable (easier) or one or more individual variables (if you know exactly what you want to accomplish). Depending on the rate of false positives and your default policy you should decide whether to block or just warn when the rule is triggered.

The best way to use this variable is as in the example below:

SecRule MULTIPART_STRICT_ERROR "!@eq 0" \
    "id:30,\
    phase:2,\
    deny,\
    t:none,\
    log,\
    msg:'Multipart request body failed strict validation: PE %{REQBODY_ERROR}, BQ %{MULTIPART_BOUNDARY_QUOTED}, BW %{MULTIPART_BOUNDARY_WHITESPACE}, DB %{MULTIPART_DATA_BEFORE}, DA %{MULTIPART_DATA_AFTER}, DH %{MULTIPART_DUPLICATE_PART_HEADER}, HF %{MULTIPART_HEADER_FOLDING}, LF %{MULTIPART_LF_LINE}, SM %{MULTIPART_MISSING_SEMICOLON}, IQ %{MULTIPART_INVALID_QUOTING}, IP %{MULTIPART_INVALID_PART}, IH %{MULTIPART_INVALID_HEADER_FOLDING}, FE %{MULTIPART_FILE_LIMIT_EXCEEDED}'"
Note

Older versions of this example used REQBODY_PROCESSOR_ERROR, which ModSecurity v2 removed in 2.9.14; REQBODY_ERROR is the current name. libModSecurity v3 still accepts both names.

The multipart/form-data parser was upgraded in ModSecurity v2.1.3 to actively look for signs of evasion. Many variables (as listed above) were added to expose various facts discovered during the parsing process. The MULTIPART_STRICT_ERROR variable is handy to check on all abnormalities at once. The individual variables allow detection to be fine-tuned according to your circumstances in order to reduce the number of false positives.

MULTIPART_UNMATCHED_BOUNDARY

ModSecurity v2supported
libModSecurity v3supported

Set to 1 when, during the parsing phase of a multipart/request-body, ModSecurity encounters what feels like a boundary but it is not. Such an event may occur when evasion of ModSecurity is attempted.

The best way to use this variable is as in the example below:

SecRule MULTIPART_UNMATCHED_BOUNDARY "!@eq 0" \
    "id:31,\
    phase:2,\
    deny,\
    t:none,\
    log,\
    msg:'Multipart parser detected a possible unmatched boundary.'"

Change the rule from blocking to logging-only if many false positives are encountered.

The intention of this variable is to identify possible evasion attempts by identifying lines that begin with ‘–’ but are followed by characters such that it is not a match to the boundary. Even in its original implementation (in ModSecurity v2) this detection was known to be prone to false positives. libModSecurity v3 sets the variable to either 1 or 2: a change made in v3 (3.0.3) resulted in two detection variations, one that is still prone to false positives (1) and a revised detection that will detect very little (2). The ongoing utility and suitability of this detection is subject to review. See the description of rule 200004 in modsecurity.conf-recommended for more detail.

OUTBOUND_DATA_ERROR

ModSecurity v2supported
libModSecurity v3supported

This variable will be set to 1 when the response body size is above the setting configured by SecResponseBodyLimit directive. Your policies should always contain a rule to check this variable. Depending on the rate of false positives and your default policy you should decide whether to block or just warn when the rule is triggered.

The best way to use this variable is as in the example below:

SecRule OUTBOUND_DATA_ERROR "@eq 1" "phase:1,id:32,t:none,log,pass,msg:'Response Body Larger than SecResponseBodyLimit Setting'"

PATH_INFO

ModSecurity v2supported
libModSecurity v3supported

Contains the extra request URI information, also known as path info. (For example, in the URI /index.php/123, /123 is the path info.) Available only in embedded deployments.

SecRule PATH_INFO "^/(bin|etc|sbin|opt|usr)" "id:33"

In libModSecurity v3 there is no embedded-mode path info; PATH_INFO instead contains the part of the request URI that precedes any ‘?’ character.

SecRule PATH_INFO "^/(php)" "id:33"

PERF_ALL

ModSecurity v2supported
libModSecurity v3not supported

This special variable contains a string that’s a combination of all other performance variables, arranged in the same order in which they appear in the Stopwatch2 audit log header. It’s intended for use in custom Apache logs

PERF_COMBINED

ModSecurity v2since 2.6.0
libModSecurity v3not supported

Contains the time, in microseconds, spent in ModSecurity during the current transaction. The value in this variable is arrived to by adding all the performance variables except PERF_SREAD (the time spent reading from persistent storage is already included in the phase measurements).

PERF_GC

ModSecurity v2since 2.6.0
libModSecurity v3not supported

Contains the time, in microseconds, spent performing garbage collection.

PERF_LOGGING

ModSecurity v2since 2.6.0
libModSecurity v3not supported

Contains the time, in microseconds, spent in audit logging. This value is known only after the handling of a transaction is finalized, which means that it can only be logged using mod_log_config and the %{VARNAME}M syntax.

PERF_PHASE1

ModSecurity v2since 2.6.0
libModSecurity v3not supported

Contains the time, in microseconds, spent processing phase 1.

PERF_PHASE2

ModSecurity v2since 2.6.0
libModSecurity v3not supported

Contains the time, in microseconds, spent processing phase 2.

PERF_PHASE3

ModSecurity v2since 2.6.0
libModSecurity v3not supported

Contains the time, in microseconds, spent processing phase 3.

PERF_PHASE4

ModSecurity v2since 2.6.0
libModSecurity v3not supported

Contains the time, in microseconds, spent processing phase 4.

PERF_PHASE5

ModSecurity v2since 2.6.0
libModSecurity v3not supported

Contains the time, in microseconds, spent processing phase 5.

PERF_RULES

ModSecurity v2since 2.7.0
libModSecurity v3not supported

PERF_RULES is a collection, that is populated with the rules hitting the performance threshold defined with SecRulePerfTime. The collection contains the time, in microseconds, spent processing the individual rule. The various items in the collection can be accessed via the rule id.

SecRulePerfTime            100

SecRule FILES_TMPNAMES "@inspectFile /path/to/util/runav.pl" \
    "id:10001,\
    phase:2,\
    deny,\
    log,\
    msg:'Virus scan detected an error.'"

SecRule &PERF_RULES "@eq 0" \
    "id:95000,\
    phase:5,\
    pass,\
    log,\
    msg:'All rules performed below processing time limit.'"
SecRule PERF_RULES "@ge 1000" \
    "id:95001,\
    phase:5,\
    pass,\
    log,\
    msg:'Rule %{MATCHED_VAR_NAME} spent at least 1000 usec.'"
SecAction \
    "id:95002,\
    phase:5,\
    pass,\
    log,\
    msg:'File inspection took %{PERF_RULES.10001} usec.'"

The rule with id 10001 defines an external file inspection rule. The rule with id 95000 checks the size of the PERF_RULES collection. If the collection is empty, it writes a note in the logfile. Rule 95001 is executed for every item in the PERF_RULES collection. Every item is thus being checked against the limit of 1000 microseconds. If the rule spent at least that amount of time, then a note containing the rule id is being written to the logfile. The final rule 95002 notes the time spent in rule 10001 (the virus inspection).

PERF_SREAD

ModSecurity v2since 2.6.0
libModSecurity v3not supported

Contains the time, in microseconds, spent reading from persistent storage.

PERF_SWRITE

ModSecurity v2since 2.6.0
libModSecurity v3not supported

Contains the time, in microseconds, spent writing to persistent storage.

QUERY_STRING

ModSecurity v2supported
libModSecurity v3supported

Contains the query string part of a request URI. The value in QUERY_STRING is always provided raw, without URL decoding taking place.

SecRule QUERY_STRING "attack" "id:34"

REMOTE_ADDR

ModSecurity v2supported
libModSecurity v3supported

This variable holds the IP address of the remote client. In ModSecurity v2 on Apache 2.4 with mod_remoteip loaded, it holds the client address as determined by mod_remoteip (see USERAGENT_IP). In libModSecurity v3 it is whatever address the connector hands to the library when the connection is processed.

SecRule REMOTE_ADDR "@ipMatch 192.168.1.101" "id:35"

REMOTE_HOST

ModSecurity v2supported
libModSecurity v3supported

If the Apache directive HostnameLookups is set to On, then this variable will hold the remote hostname resolved through DNS. If the directive is set to Off, this variable it will hold the remote IP address (same as REMOTE_ADDR). Possible uses for this variable would be to deny known bad client hosts or network blocks, or conversely, to allow in authorized hosts.

SecRule REMOTE_HOST "\.evil\.network\org$" "id:36"

libModSecurity v3 performs no hostname lookup: there, this variable is a synonym for REMOTE_ADDR.

REMOTE_PORT

ModSecurity v2supported
libModSecurity v3supported

This variable holds information on the source port that the client used when initiating the connection to our web server.

In the following example, we are evaluating to see whether the REMOTE_PORT is less than 1024, which would indicate that the user is a privileged user:

SecRule REMOTE_PORT "@lt 1024" "id:37"

REMOTE_USER

ModSecurity v2supported
libModSecurity v3supported

This variable holds the username of the authenticated user. If there are no password access controls in place (Basic or Digest authentication), then this variable will be empty.

SecRule REMOTE_USER "@streq admin" "id:38"

Note

In a reverse-proxy deployment, this information will not be available if the authentication is handled in the backend web server.

libModSecurity v3 extracts the username from the Authorization request header (Basic authentication), if present.

REQBODY_ERROR

ModSecurity v2supported
libModSecurity v3supported

Contains the status of the request body processor used for request body parsing. The values can be 0 (no error) or 1 (error). This variable will be set by request body processors (typically the multipart/request-data parser, JSON or the XML parser) when they fail to do their work.

SecRule REQBODY_ERROR "@eq 1" deny,phase:2,id:39

Note

Your policies must have a rule to check for request body processor errors at the very beginning of phase 2. Failure to do so will leave the door open for impedance mismatch attacks. It is possible, for example, that a payload that cannot be parsed by ModSecurity can be successfully parsed by more tolerant parser operating in the application. If your policy dictates blocking, then you should reject the request if error is detected. When operating in detection-only mode, your rule should alert with high severity when request body processing fails.

  • Related issues: #1475

REQBODY_ERROR_MSG

ModSecurity v2supported
libModSecurity v3supported

If there has been an error during request body parsing that resulted in REQBODY_ERROR getting set to 1, this variable will contain a text message with additional information about the error that was encountered. The variable can be tested just as any other variable:

SecRule REQBODY_ERROR_MSG "failed to parse" "id:40"

It is more common, however, simply to output the content in a log line, as in rule 200002 in modsecurity.conf-recommended.

REQBODY_PROCESSOR

ModSecurity v2supported
libModSecurity v3supported

Contains the name of the currently used request body processor. If set, the possible values are URLENCODED, MULTIPART, XML, and JSON; it is an empty string when no processor is in use. Both engines select URLENCODED and MULTIPART automatically from the Content-Type; XML and JSON must be selected with ctl:requestBodyProcessor.

SecRule REQBODY_PROCESSOR "@rx ^XML$" "id:41,chain"
    SecRule XML "@validateDTD /opt/apache-frontend/conf/xml.dtd"

REQBODY_PROCESSOR_ERROR

ModSecurity v2not supported
libModSecurity v3supported

Older name for REQBODY_ERROR. ModSecurity v2 provided it as a deprecated alias up to 2.9.13; it was removed in 2.9.14, so use REQBODY_ERROR there. libModSecurity v3 still sets both names when a request body processor fails.

REQBODY_PROCESSOR_ERROR_MSG

ModSecurity v2not supported
libModSecurity v3supported

Older name for REQBODY_ERROR_MSG. ModSecurity v2 provided it as a deprecated alias up to 2.9.13; it was removed in 2.9.14, so use REQBODY_ERROR_MSG there. libModSecurity v3 still sets both names.

REQUEST_BASENAME

ModSecurity v2supported
libModSecurity v3supported

This variable holds just the filename part of REQUEST_FILENAME (e.g., index.php).

SecRule REQUEST_BASENAME "^login\.php$" phase:2,id:42,t:none,t:lowercase

Note

Please note that anti-evasion transformations are not applied to this variable by default. REQUEST_BASENAME will recognize both / and \ as path separators. You should understand that the value of this variable depends on what was provided in request, and that it does not have to correspond to the resource (on disk) that will be used by the web server.

REQUEST_BODY

ModSecurity v2supported
libModSecurity v3supported

Holds the raw request body. This variable is available only if the URLENCODED request body processor was used, which will occur by default when the application/x-www-form-urlencoded content type is detected, or if the use of the URLENCODED request body parser was forced.

SecRule REQUEST_BODY "^username=\w{25,}\&password=\w{25,}\&Submit\=login$" "id:43"

As of 2.5.7, it is possible to force the presence of the REQUEST_BODY variable, but only when there is no request body processor defined using the ctl:forceRequestBodyVariable option in the REQUEST_HEADERS phase.

libModSecurity v3 always fills REQUEST_BODY with the raw request body (subject to SecRequestBodyAccess and the body limits), whichever processor is in use; ctl:forceRequestBodyVariable is accepted by the parser but ignored.

REQUEST_BODY_LENGTH

ModSecurity v2since 2.6.0
libModSecurity v3supported

Contains the number of bytes read from a request body. Available starting with v2.6

REQUEST_COOKIES

ModSecurity v2supported
libModSecurity v3supported

This variable is a collection of all of request cookies (values only). Example: the following example is using the Ampersand special operator to count how many variables are in the collection. In this rule, it would trigger if the request does not include any Cookie headers.

SecRule &REQUEST_COOKIES "@eq 0" "id:44"

REQUEST_COOKIES_NAMES

ModSecurity v2supported
libModSecurity v3supported

This variable is a collection of the names of all request cookies. For example, the following rule will trigger if the JSESSIONID cookie is not present:

SecRule &REQUEST_COOKIES_NAMES:JSESSIONID "@eq 0" "id:45"

REQUEST_FILENAME

ModSecurity v2supported
libModSecurity v3supported

This variable holds the relative request URL without the query string part (e.g., /index.php).

SecRule REQUEST_FILENAME "^/cgi-bin/login\.php$" phase:2,id:46,t:none,t:normalizePath

Note

Please note that anti-evasion transformations are not used on REQUEST_FILENAME, which means that you will have to specify them in the rules that use this variable.

REQUEST_HEADERS

ModSecurity v2supported
libModSecurity v3supported

This variable can be used as either a collection of all of the request headers or can be used to inspect selected headers (by using the REQUEST_HEADERS:Header-Name syntax).

SecRule REQUEST_HEADERS:Host "^[\d\.]+$" "deny,id:47,log,status:400,msg:'Host header is a numeric IP address'"

Note

ModSecurity will treat multiple headers that have identical names in accordance with how the webserver treats them. For Apache this means that they will all be concatenated into a single header with a comma as the deliminator. libModSecurity v3 stores every header the connector passes as a separate entry of the collection, so a repeated header name yields several values.

REQUEST_HEADERS_NAMES

ModSecurity v2supported
libModSecurity v3supported

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

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

REQUEST_LINE

ModSecurity v2supported
libModSecurity v3supported

This variable holds the complete request line sent to the server (including the request method and HTTP version information).

# Allow only POST, GET and HEAD request methods, as well as only
# the valid protocol versions
SecRule REQUEST_LINE "!@rx (^((?:(?:POS|GE)T|HEAD))|HTTP/(0\.9|1\.0|1\.1)$)" \
    "id:49,\
    phase:1,\
    block,\
    t:none,\
    log"

REQUEST_METHOD

ModSecurity v2supported
libModSecurity v3supported

This variable holds the request method used in the transaction.

SecRule REQUEST_METHOD "^(?:CONNECT|TRACE)$" "id:50,t:none"

REQUEST_PROTOCOL

ModSecurity v2supported
libModSecurity v3supported

This variable holds the request protocol version information.

SecRule REQUEST_PROTOCOL "!^HTTP/(0\.9|1\.0|1\.1)$" "id:51"

REQUEST_URI

ModSecurity v2supported
libModSecurity v3supported

This variable holds the full request URL including the query string data (e.g., /index.php? p=X). However, it will never contain a domain name, even if it was provided on the request line.

SecRule REQUEST_URI "attack" "phase:1,id:52,t:none,t:urlDecode,t:lowercase,t:normalizePath"

Note

Please note that anti-evasion transformations are not used on REQUEST_URI, which means that you will have to specify them in the rules that use this variable.

REQUEST_URI_RAW

ModSecurity v2supported
libModSecurity v3supported

Same as REQUEST_URI but will contain the domain name if it was provided on the request line (e.g., http://www.example.com/index.php?p=X).

SecRule REQUEST_URI_RAW "http:/``" "phase:1,id:53,t:none,t:urlDecode,t:lowercase,t:normalizePath"

Note

Please note that anti-evasion transformations are not used on REQUEST_URI_RAW, which means that you will have to specify them in the rules that use this variable.

RESOURCE

ModSecurity v2supported
libModSecurity v3supported

Persistent collection keyed by a resource identifier (typically the request path), within the namespace set by SecWebAppId. It is initialized with the setrsc action (ModSecurity 2.7.0 and later) or with initcol, and can be used to keep per-resource state across transactions. In ModSecurity v2 a selector is mandatory (RESOURCE:name or RESOURCE:/regex/). For where libModSecurity v3 stores the data, see GLOBAL.

SecAction "id:96,phase:1,pass,nolog,setrsc:%{REQUEST_FILENAME}"
SecRule RESPONSE_STATUS "@rx ^5" \
    "id:97,\
    phase:3,\
    pass,\
    nolog,\
    setvar:resource.errors=+1"

RESPONSE_BODY

ModSecurity v2supported
libModSecurity v3supported

This variable holds the data for the response body, but only when response body buffering is enabled.

SecRule RESPONSE_BODY "ODBC Error Code" "phase:4,id:54,t:none"

RESPONSE_CONTENT_LENGTH

ModSecurity v2supported
libModSecurity v3supported

Response body length in bytes. Can be available starting with phase 3, but it does not have to be (as the length of response body is not always known in advance). If the size is not known, this variable will contain a zero. If RESPONSE_CONTENT_LENGTH contains a zero in phase 5 that means the actual size of the response body was 0. The value of this variable can change between phases if the body is modified. For example, in embedded mode, mod_deflate can compress the response body between phases 4 and 5.

libModSecurity v3 sets it only when the response body is processed (phase 4), to the number of buffered body bytes; it does not read the Content-Length response header.

RESPONSE_CONTENT_TYPE

ModSecurity v2supported
libModSecurity v3supported

Response content type. Available only starting with phase 3. The value available in this variable is taken directly from the internal structures of Apache, which means that it may contain the information that is not yet available in response headers. In embedded deployments, you should always refer to this variable, rather than to RESPONSE_HEADERS:Content-Type.

libModSecurity v3 derives it from the Content-Type response header passed by the connector, with the parameters (for example charset=UTF-8) stripped.

RESPONSE_HEADERS

ModSecurity v2supported
libModSecurity v3supported

This variable refers to response headers, in the same way as REQUEST_HEADERS does to request headers.

SecRule RESPONSE_HEADERS:X-Cache "MISS" "id:55"

This variable may not have access to some headers when running in embedded mode. Headers such as Server, Date, Connection, and Content-Type could be added just prior to sending the data to the client. This data should be available in phase 5 or when deployed in proxy mode.

RESPONSE_HEADERS_NAMES

ModSecurity v2supported
libModSecurity v3supported

This variable is a collection of the response header names.

SecRule RESPONSE_HEADERS_NAMES "Set-Cookie" "phase:3,id:56,t:none"

The same limitations apply as the ones discussed in RESPONSE_HEADERS.

RESPONSE_PROTOCOL

ModSecurity v2supported
libModSecurity v3supported

This variable holds the HTTP response protocol information.

SecRule RESPONSE_PROTOCOL "^HTTP\/0\.9" "phase:3,id:57,t:none"

RESPONSE_STATUS

ModSecurity v2supported
libModSecurity v3supported

This variable holds the HTTP response status code:

SecRule RESPONSE_STATUS "^[45]" "phase:3,id:58,t:none"

This variable may not work as expected in embedded mode, as Apache sometimes handles certain requests differently, and without invoking ModSecurity (all other modules).

RULE

ModSecurity v2supported
libModSecurity v3supported

This is a special collection that provides access to the id, rev, severity, msg, logdata, ver, maturity, and accuracy fields of the rule that triggered the action. It can be used to refer to only the same rule in which it resides; a field name is mandatory (RULE:id, or %{RULE.id} in macros), and inside a chain the fields are those of the chain starter.

libModSecurity v3 exposes only id, rev, severity, msg and logdata (ver, maturity and accuracy are not available); it also accepts a bare RULE, which returns all five, and a regular-expression selector.

SecRule &REQUEST_HEADERS:Host "@eq 0" "log,deny,id:59,setvar:tx.varname=%{RULE.id}"

SCRIPT_BASENAME

ModSecurity v2supported
libModSecurity v3not supported

This variable holds just the local filename part of SCRIPT_FILENAME.

SecRule SCRIPT_BASENAME "^login\.php$" "id:60"

Note

Not available in proxy mode.

SCRIPT_FILENAME

ModSecurity v2supported
libModSecurity v3not supported

This variable holds the full internal path to the script that will be used to serve the request.

SecRule SCRIPT_FILENAME "^/usr/local/apache/cgi-bin/login\.php$" "id:61"

Note

Not available in proxy mode.

SCRIPT_GID

ModSecurity v2supported
libModSecurity v3not supported

This variable holds the numerical identifier of the group owner of the script.

SecRule SCRIPT_GID "!^46$" "id:62"

Note

Not available in proxy mode.

SCRIPT_GROUPNAME

ModSecurity v2supported
libModSecurity v3not supported

This variable holds the name of the group owner of the script.

SecRule SCRIPT_GROUPNAME "!^apache$" "id:63"

Note

Not available in proxy mode.

SCRIPT_MODE

ModSecurity v2supported
libModSecurity v3not supported

This variable holds the script’s permissions mode data as four hexadecimal digits of the APR protection bits, which for ordinary Unix permissions reads like the octal mode with a leading zero (e.g., 0644).

# Do not allow scripts that can be written to by everyone
SecRule SCRIPT_MODE "@rx [2367]$" "id:64"
Note

Not available in proxy mode.

SCRIPT_UID

ModSecurity v2supported
libModSecurity v3not supported

This variable holds the numerical identifier of the owner of the script.

# Do not run any scripts that are owned
# by Apache (Apache's user id is 46)
SecRule SCRIPT_UID "!@rx ^46$" "id:65"
Note

Not available in proxy mode.

SCRIPT_USERNAME

ModSecurity v2supported
libModSecurity v3not supported

This variable holds the username of the owner of the script.

# Do not run any scripts owned by Apache
SecRule SCRIPT_USERNAME "@rx ^apache$" "id:66"
Note

Not available in proxy mode.

SDBM_DELETE_ERROR

ModSecurity v2since 2.7.4
libModSecurity v3not supported

This variable is set to 1 when APR fails to delete SDBM entries.

SERVER_ADDR

ModSecurity v2supported
libModSecurity v3supported

This variable contains the IP address of the server.

SecRule SERVER_ADDR "@ipMatch 192.168.1.100" "id:67"

SERVER_NAME

ModSecurity v2supported
libModSecurity v3supported

This variable contains the transaction’s hostname or IP address, taken from the request itself (which means that, in principle, it should not be trusted).

SecRule SERVER_NAME "hostname\.com$" "id:68"

SERVER_PORT

ModSecurity v2supported
libModSecurity v3supported

This variable contains the local port that the web server (or reverse proxy) is listening on.

SecRule SERVER_PORT "^80$" "id:69"

SESSION

ModSecurity v2supported
libModSecurity v3supported

This variable is a collection that contains session information. It becomes available only after setsid is executed. In ModSecurity v2 a selector is mandatory (SESSION:name or SESSION:/regex/). For where libModSecurity v3 stores the data, see GLOBAL.

The following example shows how to initialize SESSION using setsid, how to use setvar to increase the SESSION.score values, how to set the SESSION.blocked variable, and finally, how to deny the connection based on the SESSION:blocked value:

# Initialize session storage
SecRule REQUEST_COOKIES:PHPSESSID "!@rx ^$" \
    "id:70,\
    phase:2,\
    pass,\
    nolog,\
    setsid:%{REQUEST_COOKIES.PHPSESSID}"

# Increment session score on attack
SecRule REQUEST_URI "@rx ^/cgi-bin/finger$" \
    "id:71,\
    phase:2,\
    pass,\
    t:none,\
    t:lowercase,\
    t:normalizePath,\
    setvar:SESSION.score=+10"

# Detect too many attacks in a session
SecRule SESSION:score "@gt 50" "id:72,phase:2,pass,setvar:SESSION.blocked=1"

# Enforce session block
SecRule SESSION:blocked "@eq 1" "id:73,phase:2,deny,status:403"

SESSIONID

ModSecurity v2supported
libModSecurity v3supported

This variable contains the value set with setsid. See SESSION (above) for a complete example.

STATUS

ModSecurity v2not supported
libModSecurity v3supported

libModSecurity v3 only: the HTTP response status code, the same value as RESPONSE_STATUS. STATUS_LINE is accepted by v3 as another alias of this variable. ModSecurity v2 does not have STATUS; use RESPONSE_STATUS there.

STATUS_LINE

ModSecurity v2supported
libModSecurity v3since 3.0.3 accepted as an alias of STATUS

This variable holds the response status line generated by the server, that is the status code followed by the reason phrase (for example 500 Internal Server Error); the protocol version is not included. In libModSecurity v3 it is an alias of STATUS and therefore holds only the status code.

# Generate an alert when the application generates 500 errors.
SecRule STATUS_LINE "@contains 500" \
    "id:49,\
    phase:3,\
    pass,\
    log,\
    logdata:'Application error detected!,t:none"

STREAM_INPUT_BODY

ModSecurity v2since 2.6.0
libModSecurity v3not supported

This variable give access to the raw request body content. This variable is best used for two use-cases:

  1. For fast pattern matching - using @pm/@pmf to prequalify large text strings against any kind of content-type data. This is more performant vs. using REQUEST_BODY/ARGS_POST/ARGS_POST_NAMES as it happens before ModSecurity parsing in phase:2 variable population.
  2. For data substitution - using @rsub against this variable allows you to manipulate live request body data. Example - to remove offending payloads or to substitute benign data.
Note

You must enable the SecStreamInBodyInspection directive

Note

This variable is not supported by libModSecurity v3.

STREAM_OUTPUT_BODY

ModSecurity v2since 2.6.0
libModSecurity v3not supported

This variable give access to the raw response body content. This variable is best used for case:

  1. For data substitution - using @rsub against this variable allows you to manipulate live request body data. Example - to remove offending payloads or to substitute benign data.
Note

You must enable the SecStreamOutBodyInspection directive

TIME

ModSecurity v2supported
libModSecurity v3supported

This variable holds a formatted timestamp. The format differs between the engines: in ModSecurity v2 it is the 14-digit local time YYYYMMDDHHMMSS (for example 20261013183045), not hour:minute:second as older manuals stated, while libModSecurity v3 produces the local time as HH:MM:SS (for example 18:30:45). The following rules match between 18:00 and 23:59.

ModSecurity v2:

SecRule TIME "^\d{8}(1[89]|2[0-3])\d{4}$" "id:74"

libModSecurity v3:

SecRule TIME "^(1[89]|2[0-3]):" "id:74"

TIME_DAY

ModSecurity v2supported
libModSecurity v3supported

This variable holds the current day of the month as two zero-padded digits (01–31). The following rule triggers on a transaction that’s happening anytime between the 10th and 20th in a month:

SecRule TIME_DAY "^(([1](0|1|2|3|4|5|6|7|8|9))|20)$" "id:75"

TIME_EPOCH

ModSecurity v2supported
libModSecurity v3supported

This variable holds the time in seconds since 1970.

TIME_HOUR

ModSecurity v2supported
libModSecurity v3supported

This variable holds the current hour as two zero-padded digits (00–23). The following rule triggers when a request is made “off hours”:

SecRule TIME_HOUR "^(0[0-6]|1[89]|2[0-3])$" "id:76"

TIME_MIN

ModSecurity v2supported
libModSecurity v3supported

This variable holds the current minute as two zero-padded digits (00–59). The following rule triggers during the last half hour of every hour:

SecRule TIME_MIN "^(3|4|5)" "id:77"

TIME_MON

ModSecurity v2supported
libModSecurity v3supported

This variable holds the current month as two zero-padded digits (01–12). libModSecurity v3 does not zero-pad it (1–12; before 3.0.14 it was zero-based, 0–11). The following rule matches if the month is either November (value 11) or December (value 12):

SecRule TIME_MON "^1[12]$" "id:78"

TIME_SEC

ModSecurity v2supported
libModSecurity v3supported

This variable holds the current second as two zero-padded digits (00–59).

SecRule TIME_SEC "@gt 30" "id:79"

TIME_WDAY

ModSecurity v2supported
libModSecurity v3supported

This variable holds the current weekday value. The numbering differs between the engines: ModSecurity v2 uses 0–6 with Sunday as 0, while libModSecurity v3 uses 1–7 with Monday as 1. The following rules trigger only on Saturday and Sunday.

ModSecurity v2:

SecRule TIME_WDAY "^(0|6)$" "id:80"

libModSecurity v3:

SecRule TIME_WDAY "^(6|7)$" "id:80"

TIME_YEAR

ModSecurity v2supported
libModSecurity v3supported

This variable holds the current four-digit year value.

SecRule TIME_YEAR "^2006$" "id:81"

TX

ModSecurity v2supported
libModSecurity v3supported

This is the transient transaction collection, which is used to store pieces of data, create a transaction anomaly score, and so on. The variables placed into this collection are available only until the transaction is complete. In ModSecurity v2 a selector is mandatory (TX:name or TX:/regex/); a bare TX target is a configuration error.

# Increment transaction attack score on attack
SecRule ARGS "@rx attack" "id:82,phase:2,pass,nolog,setvar:TX.score=+5"

# Block the transactions whose scores are too high
SecRule TX:SCORE "@gt 20" "id:83,phase:2,deny,log"

Some variable names in the TX collection are reserved and cannot be used:

  • TX:0: the matching value when using the @rx or @pm operator with the capture action
  • TX:1-TX:9: the captured subexpression value when using the @rx operator with capturing parens and the capture action. ModSecurity v2 stores at most nine captures (TX:1 to TX:9); libModSecurity v3 stores every capturing group of the expression (the v3 manual documents TX:1 to TX:99).
  • TX:MSC_.*: ModSecurity processing flags
  • MSC_PCRE_LIMITS_EXCEEDED: Set to nonzero if PCRE match limits are exceeded. See SecPcreMatchLimit and SecPcreMatchLimitRecursion for more information.

UNIQUE_ID

ModSecurity v2since 2.6.0
libModSecurity v3supported

This variable holds the data created by mod_unique_id 1. This module provides a magic token for each request which is guaranteed to be unique across “all” requests under very specific conditions. The unique identifier is even unique across multiple machines in a properly configured cluster of machines. The environment variable UNIQUE_ID is set to the identifier for each request. The UNIQUE_ID environment variable is constructed by encoding the 112-bit (32-bit IP address, 32 bit pid, 32 bit time stamp, 16 bit counter) quadruple using the alphabet [A-Za-z0-9@-] in a manner similar to MIME base64 encoding, producing 19 characters.

libModSecurity v3 does not depend on mod_unique_id: unless the connector supplies its own transaction identifier, it generates one made of the Unix timestamp in seconds immediately followed by a random floating-point number between 0 and 100 (for example 176020000042.123456). The random part was restored in 3.0.7; the value is not guaranteed to be unique.

URLENCODED_ERROR

ModSecurity v2since 2.6.0
libModSecurity v3supported

This variable is created when an invalid URL encoding is encountered during the parsing of a query string (on every request) or during the parsing of an application/x-www-form-urlencoded request body (only on the requests that use the URLENCODED request body processor).

USER

ModSecurity v2supported
libModSecurity v3supported

Persistent collection keyed by the user identifier set with setuid (see USERID). It must be initialized with setuid or initcol before it can be used. In ModSecurity v2 a selector is mandatory (USER:name or USER:/regex/). For where libModSecurity v3 stores the data, see GLOBAL.

SecAction "id:98,phase:1,pass,nolog,setuid:%{REMOTE_USER}"
SecRule ARGS "@rx attack" "id:99,phase:2,pass,nolog,setvar:user.score=+5"
SecRule USER:score "@gt 20" "id:100,phase:2,deny"

USERID

ModSecurity v2supported
libModSecurity v3supported

This variable contains the value set with setuid.

# Initialize user tracking
SecAction "id:84,pass,nolog,setuid:%{REMOTE_USER}"

# Is the current user the administrator?
SecRule USERID "@rx admin" "id:85"

USERAGENT_IP

ModSecurity v2since 2.7.0
libModSecurity v3not supported

Only compiled in when ModSecurity v2 is built against Apache 2.4 or later. It holds Apache’s useragent_ip, the client address after mod_remoteip has substituted the real client address in proxied connections (without mod_remoteip it equals REMOTE_ADDR). It contains 0.0.0.0 when Apache did not set the address.

WEBAPPID

ModSecurity v2supported
libModSecurity v3supported

This variable contains the current application name, which is set in configuration using SecWebAppId.

WEBSERVER_ERROR_LOG

ModSecurity v2supported
libModSecurity v3not supported

Contains zero or more error messages produced by the web server. This variable is best accessed from phase 5 (logging).

SecRule WEBSERVER_ERROR_LOG "File does not exist" "phase:5,id:86,t:none,nolog,pass,setvar:TX.score=+5"

libModSecurity v3 rejects any rule that uses this variable at configuration load (“Variable VARIABLE_WEBSERVER_ERROR_LOG is not supported by libModSecurity”).

XML

ModSecurity v2supported
libModSecurity v3supported

Special collection used to interact with the XML parser. It can be used standalone as a target for the validateDTD and validateSchema operator. Otherwise, it must contain a valid XPath expression, which will then be evaluated against a previously parsed XML DOM tree.

libModSecurity v3 supports it only when built with libxml2; without it the variable parses but never yields a value. XPath selection works the same way (XML:/xpath, with namespaces registered through the xmlns action), and a bare XML yields a placeholder value for the validation operators.

SecDefaultAction "id:90,phase:2,deny,status:403,log"
SecRule REQUEST_HEADERS:Content-Type "@rx ^text/xml$" \
    "id:87,\
    phase:1,\
    pass,\
    t:lowercase,\
    nolog,\
    ctl:requestBodyProcessor=XML"
SecRule REQBODY_PROCESSOR "!@rx ^XML$" "id:88,skipAfter:12345"

SecRule XML:/employees/employee/name/text() "@rx Fred" "id:89"
SecRule XML:/xq:employees/employee/name/text() "@rx Fred" \
    "id:12345,\
    xmlns:xq=http://www.example.com/employees"

The first XPath expression does not use namespaces. It would match against payload such as this one:

<employees>
    <employee>
        <name>Fred Jones</name>
        <address location="home">
            <street>900 Aurora Ave.</street>
            <city>Seattle</city>
            <state>WA</state>
            <zip>98115</zip>
        </address>
        <address location="work">
            <street>2011 152nd Avenue NE</street>
            <city>Redmond</city>
            <state>WA</state>
            <zip>98052</zip>
        </address>
        <phone location="work">(425)555-5665</phone>
        <phone location="home">(206)555-5555</phone>
        <phone location="mobile">(206)555-4321</phone>
    </employee>
</employees>

The second XPath expression does use namespaces. It would match the following payload:

<xq:employees xmlns:xq="http://www.example.com/employees">
    <employee>
        <name>Fred Jones</name>
        <address location="home">
            <street>900 Aurora Ave.</street>
            <city>Seattle</city>
            <state>WA</state>
            <zip>98115</zip>
        </address>
        <address location="work">
            <street>2011 152nd Avenue NE</street>
            <city>Redmond</city>
            <state>WA</state>
            <zip>98052</zip>
        </address>
        <phone location="work">(425)555-5665</phone>
        <phone location="home">(206)555-5555</phone>
        <phone location="mobile">(206)555-4321</phone>
    </employee>
</xq:employees>

Note the different namespace used in the second example.

Transformation Functions

Transformation functions are used to alter input data before it is used in matching (i.e., operator execution). The input data is never modified, actually—whenever you request a transformation function to be used, ModSecurity will create a copy of the data, transform it, and then run the operator against the result.

Note

There are no default transformation functions, as there were in the first generation of ModSecurity (1.x).

In the following example, the request parameter values are converted to lowercase before matching:

SecRule ARGS "xp_cmdshell" "t:lowercase,id:91"

Multiple transformation actions can be used in the same rule, forming a transformation pipeline. The transformations will be performed in the order in which they appear in the rule.

In most cases, the order in which transformations are performed is very important. In the following example, a series of transformation functions is performed to counter evasion. Performing the transformations in any other order would allow a skillful attacker to evade detection:

SecRule ARGS "(asfunction|javascript|vbscript|data|mocha|livescript):" "id:92,t:none,t:htmlEntityDecode,t:lowercase,t:removeNulls,t:removeWhitespace"

Warning

It is currently possible to use SecDefaultAction to specify a default list of transformation functions, which will be applied to all rules that follow the SecDefaultAction directive. However, this practice is not recommended, because it means that mistakes are very easy to make. It is recommended that you always specify the transformation functions that are needed by a particular rule, starting the list with t:none (which clears the possibly inherited transformation functions).

Transformation names are matched case-insensitively by both engines (for example t:cmdline and t:cmdLine are the same function).

ModSecurity v2 can cache transformation results per transaction and phase through SecCacheTransformations; the feature was deprecated in 2.5.6 and is off by default. libModSecurity v3 does not implement transformation caching and rejects the directive with “SecCacheTransformations is not supported”.

The remainder of this section documents the transformation functions currently available in ModSecurity.

base64Decode

ModSecurity v2supported
libModSecurity v3since 3.0.1

Decodes a Base64-encoded string.

SecRule REQUEST_HEADERS:Authorization "@rx ^Basic ([a-zA-Z0-9]+=*)$" \
    "id:93,\
    phase:1,\
    capture,\
    logdata:%{TX.1},\
    chain"
    SecRule TX:1 "@rx ^(\w+):" "capture,t:base64Decode,chain"
        SecRule TX:1 "@rx ^(admin|root|backup)$"

The two engines treat malformed input differently. ModSecurity v2 (apr_base64_decode) decodes up to the first byte outside the Base64 alphabet and discards the rest. libModSecurity v3 (which uses a strict decoder) rejects the whole input and leaves the value unchanged when it contains a byte outside the alphabet, when its length is not a multiple of four (missing padding), or when data follows the padding; it does ignore line breaks (and spaces right before one or at the end of the value). It also stops at the first NUL byte in the input. Use base64DecodeExt when a forgiving decoder is wanted.

Note

Be careful when applying base64Decode with other transformations. The order of your transformation matters in this case as certain transformations may change or invalidate the base64 encoded string prior to being decoded (i.e t:lowercase, etc). This of course means that it is also very difficult to write a single rule that checks for a base64decoded value OR an unencoded value with transformations, it is best to write two rules in this situation.

sqlHexDecode

ModSecurity v2since 2.6.3
libModSecurity v3supported

Decode sql hex data. Example (0x414243) will be decoded to (ABC). Available as of 2.6.3.

Both engines decode 0x (or 0X) followed by at least one complete pair of hexadecimal digits, and keep a bare 0x that is not followed by a complete pair. ModSecurity v2 processes the value as a C string: it copies the byte that follows a decoded literal without examining it (so 0x410x42 yields A0x42), and the value is truncated at a decoded NUL byte. libModSecurity v3 re-examines every byte and preserves decoded NUL bytes.

base64DecodeExt

ModSecurity v2since 2.6.0
libModSecurity v3since 3.0.1

Decodes a Base64-encoded string. Unlike base64Decode, this version uses a more forgiving implementation that ignores whitespace and misplaced padding. Available under this name as of 2.6.0 (earlier development releases called it decodeBase64Ext).

Both engines accept the URL-safe alphabet (- and _) since ModSecurity 2.9.15 and libModSecurity 3.0.17. ModSecurity v2 skips only space, tab, CR, LF and padding (=) characters: any other byte outside the Base64 alphabet makes the whole decode fail and the output is an empty string. It also stops decoding at the first NUL byte in the input. libModSecurity v3 skips every byte outside the alphabet and processes every byte.

See blog post on Base64Decoding evasion issues on PHP sites - http://blog.spiderlabs.com/2010/04/impedance-mismatch-and-base64.html

base64Encode

ModSecurity v2supported
libModSecurity v3since 3.0.1

Encodes input string using Base64 encoding.

cmdLine

ModSecurity v2since 2.6.0
libModSecurity v3supported
Note

This is a community contribution developed by Marc Stern 1

In Windows and Unix, commands may be escaped by different means, such as:

  • c^ommand /c …
  • “command” /c …
  • command,/c …
  • backslash in the middle of a Unix command

The cmdLine transformation function avoids this problem by manipulating the variable content in the following ways:

  • deleting all backslashes [\
  • deleting all double quotes ["]
  • deleting all single quotes [']
  • deleting all carets [^]
  • deleting spaces before a slash [/]
  • deleting spaces before an open parenthesis [(]
  • replacing all commas [,] and semicolon [;] into a space
  • replacing all multiple spaces (including tab, carriage return and newline) into one space
  • transform all characters to lowercase

ModSecurity v2 registers this function as cmdline; because transformation names are matched case-insensitively, t:cmdLine works as well. libModSecurity v3 accepts t:cmdLine in rules in any letter case too; only its internal transformation factory, which the Lua API (m.getvar, m.getvars) uses to look up transformation names, compares names case-sensitively and knows this function solely as cmd_line (compressWhitespace is also accepted there as compress_whitespace; every other name is spelled as in this manual). ModSecurity v2 processes the value as a C string and stops at the first NUL byte; libModSecurity v3 processes every byte.

Example Usage:

SecRule ARGS "@rx (?:command(?:.com)?|cmd(?:.exe)?)(?:/.*)?/[ck]" \
    "id:94,\
    phase:2,\
    t:none,\
    t:cmdLine"

compressWhitespace

ModSecurity v2supported
libModSecurity v3supported

Converts any of the whitespace characters (0x20, \f, \t, \n, \r, \v, 0xa0) to spaces (ASCII 0x20), compressing multiple consecutive space characters into one.

libModSecurity v3 does not treat the byte 0xa0 (non-breaking space) as whitespace in this function; only ModSecurity v2 compresses it. Both engines treat 0xa0 as whitespace in removeWhitespace.

cssDecode

ModSecurity v2since 2.5.7
libModSecurity v3supported

Decodes characters encoded using the CSS 2.x escape rules syndata.html#characters. This function uses only up to two bytes in the decoding process, meaning that it is useful to uncover ASCII characters encoded using CSS encoding (that wouldn’t normally be encoded), or to counter evasion, which is a combination of a backslash and non-hexadecimal characters (e.g., ja\vascript is equivalent to javascript).

escapeSeqDecode

ModSecurity v2supported
libModSecurity v3since 3.0.3

Decodes ANSI C escape sequences: \a, \b, \f, \n, \r, \t, \v, \\, \?, \', \", \xHH (exactly two hexadecimal digits, \XHH is also accepted), \OOO (one to three octal digits, producing a single byte). A backslash before a byte that does not begin a recognized sequence is dropped and the byte is kept (\8 becomes 8, \xag becomes xag); only a lone trailing backslash is left in the output. Both engines behave the same way; libModSecurity v3 accepts the function since 3.0.3 (earlier 3.0.x releases fail to parse it).

hexDecode

ModSecurity v2supported
libModSecurity v3supported

Decodes a string that has been encoded using the same algorithm as the one used in hexEncode (see following entry).

Neither engine validates the input: every pair of characters is converted to a byte even when it contains non-hexadecimal characters (which yield meaningless bytes), and a trailing unpaired character is dropped.

hexEncode

ModSecurity v2supported
libModSecurity v3supported

Encodes string (possibly containing binary characters) by replacing each input byte with two hexadecimal characters. For example, xyz is encoded as 78797a.

htmlEntityDecode

ModSecurity v2supported
libModSecurity v3supported

Decodes the characters encoded as HTML entities. The following variants are supported:

  • &#xHH and &#xHH; (where H is any hexadecimal number)
  • &#DDD and &#DDD; (where D is any decimal number)
  • &quot; and &quot
  • &nbsp; and &nbsp
  • &lt; and &lt
  • &gt; and &gt
  • &amp; and &amp

This function always converts one HTML entity into one byte, possibly resulting in a loss of information (if the entity refers to a character that cannot be represented with the single byte). It is thus useful to uncover bytes that would otherwise not need to be encoded, but it cannot do anything meaningful with the characters from the range above 0xff.

Since ModSecurity 2.9.15 and libModSecurity 3.0.17 both engines decode every named entity that expands to a single ASCII character (U+0000–U+007F, for example &colon;, &lpar; and &sol;) plus &nbsp; and &shy;, matched case-insensitively against the full entity name; earlier releases only knew quot, amp, lt, gt and nbsp, which allowed evasions such as javascript&colon; (GHSA-cxqf-vgrr-xxrv). Named entities for characters outside that range are left as is.

jsDecode

ModSecurity v2since 2.5.0
libModSecurity v3supported

Decodes JavaScript escape sequences: \uHHHH, \xHH, \OOO (one to three octal digits, producing a single byte), \a, \b, \f, \n, \r, \t, \v; a backslash before any other byte is removed and the byte is kept. If a \uHHHH code is in the range of FF01-FF5E (the full width ASCII codes), then the higher byte is used to detect and adjust the lower byte. Otherwise, only the lower byte will be used and the higher byte zeroed (leading to possible loss of information).

length

ModSecurity v2since 2.5.0
libModSecurity v3supported

Looks up the length of the input string in bytes, placing it (as string) in output. For example, if it gets ABCDE on input, this transformation function will return 5 on output.

lowercase

ModSecurity v2supported
libModSecurity v3supported

Converts all characters to lowercase using the current C locale.

md5

ModSecurity v2supported
libModSecurity v3supported

Calculates an MD5 hash from the data in input. The computed hash is in a raw binary form and may need encoded into text to be printed (or logged). Hash functions are commonly used in combination with hexEncode (for example: t:md5,t:hexEncode).

none

ModSecurity v2supported
libModSecurity v3supported

Not an actual transformation function, but an instruction to ModSecurity to remove all transformation functions associated with the current rule.

normalisePath

ModSecurity v2supported
libModSecurity v3supported

See normalizePath. Both spellings are accepted by ModSecurity v2 and libModSecurity v3.

normalizePath

ModSecurity v2since 2.6.0
libModSecurity v3supported

Removes multiple slashes, directory self-references, and directory back-references (except when at the beginning of the input) from input string.

Note

As of ModSecurity 2.6.0 normalisePath has been renamed to normalizePath (MODSEC-103). NormalisePath is kept for backwards compatibility in current versions of both engines, but should not be used.

normalisePathWin

ModSecurity v2supported
libModSecurity v3supported

See normalizePathWin. Both spellings are accepted by ModSecurity v2 and libModSecurity v3.

normalizePathWin

ModSecurity v2since 2.6.0
libModSecurity v3supported

Same as normalizePath, but first converts backslash characters to forward slashes.

Note

As of ModSecurity 2.6.0 normalisePathWin has been renamed to normalizePathWin (MODSEC-103). NormalisePathWin is kept for backwards compatibility in current versions of both engines, but should not be used.

parityEven7bit

ModSecurity v2since 2.5.7
libModSecurity v3supported

Calculates even parity of 7-bit data replacing the 8th bit of each target byte with the calculated parity bit.

parityOdd7bit

ModSecurity v2since 2.5.7
libModSecurity v3supported

Calculates odd parity of 7-bit data replacing the 8th bit of each target byte with the calculated parity bit.

parityZero7bit

ModSecurity v2since 2.5.7
libModSecurity v3supported

Calculates zero parity of 7-bit data replacing the 8th bit of each target byte with a zero-parity bit, which allows inspection of even/odd parity 7-bit data as ASCII7 data.

removeNulls

ModSecurity v2supported
libModSecurity v3supported

Removes all NUL bytes from input.

removeWhitespace

ModSecurity v2supported
libModSecurity v3supported

Removes all whitespace characters from input.

libModSecurity v3 removes the C-locale whitespace characters (space, \t, \n, \v, \f, \r), the byte 0xa0 and also every 0xc2 byte (the UTF-8 lead byte of the non-breaking space U+00A0), so it also strips the lead byte of any other UTF-8 character in the range U+0080–U+00BF.

replaceComments

ModSecurity v2supported
libModSecurity v3supported

Replaces each occurrence of a C-style comment (/* … /) with a single space (multiple consecutive occurrences of which will not be compressed). Unterminated comments will also be replaced with a space (ASCII 0x20). However, a standalone termination of a comment (/) will not be acted upon.

removeCommentsChar

ModSecurity v2since 2.6.2
libModSecurity v3supported

Removes common comments chars (/*, */, <!--, -->, --, #).

removeComments

ModSecurity v2since 2.6.2
libModSecurity v3supported

Removes each occurrence of comment (/* ... */, <!-- ... -->, --, #). Multiple consecutive occurrences of which will not be compressed.

In both engines, /* ... */ and <!-- ... --> comments are removed entirely (an unterminated one is replaced with a single space), while -- and # start a comment that extends to the end of the input, so everything from that point on is removed. Adjacent comments (for example /**//**/) are handled correctly since ModSecurity 2.9.15 and libModSecurity 3.0.17.

Note

This transformation is known to be unreliable, might cause some unexpected behavior and could be deprecated soon in a future release. Refer to issue #1207 for further information..

replaceNulls

ModSecurity v2supported
libModSecurity v3supported

Replaces NUL bytes in input with space characters (ASCII 0x20).

urlDecode

ModSecurity v2supported
libModSecurity v3supported

Decodes a URL-encoded input string. Invalid encodings (i.e., the ones that use non-hexadecimal characters, or the ones that are at the end of string and have one or two bytes missing) are not converted, but no error is raised. To detect invalid encodings, use the @validateUrlEncoding operator on the input data first. The transformation function should not be used against variables that have already been URL-decoded (such as request parameters) unless it is your intention to perform URL decoding twice!

uppercase

ModSecurity v2not supported
libModSecurity v3supported

Converts all characters to uppercase using the current C locale.

This function exists only in libModSecurity v3; ModSecurity v2 does not register it and a rule using t:uppercase fails to load there.

urlDecodeUni

ModSecurity v2supported
libModSecurity v3supported

Like urlDecode, but with support for the Microsoft-specific %u encoding. If the code is in the range of FF01-FF5E (the full-width ASCII codes), then the higher byte is used to detect and adjust the lower byte. Otherwise, only the lower byte will be used and the higher byte zeroed.

When a SecUnicodeMapFile is loaded and a code page is selected, both engines map the %uHHHH code point through that table before falling back to the rules above. ModSecurity v2 takes the code page from the second argument of SecUnicodeMapFile or from SecUnicodeCodePage; libModSecurity v3 requires it as the second argument of SecUnicodeMapFile and does not recognize SecUnicodeCodePage (a configuration error). Invalid % sequences are left as is.

urlEncode

ModSecurity v2supported
libModSecurity v3since 3.0.3

Encodes input string using URL encoding. Letters, digits and * are kept as they are, a space becomes +, and every other byte becomes %HH (lowercase hexadecimal).

utf8toUnicode

ModSecurity v2since 2.7.0
libModSecurity v3supported

Converts all UTF-8 character sequences to Unicode (using ‘%uHHHH’ format, lowercase hexadecimal). This help input normalization specially for non-english languages minimizing false-positives and false-negatives. ModSecurity v2 registers this function as Utf8toUnicode; because transformation names are matched case-insensitively, t:utf8toUnicode works as well.

Malformed input is handled differently: ModSecurity v2 leaves malformed bytes (invalid lead or continuation bytes, overlong forms, surrogates and code points above U+10FFFF) unchanged, while libModSecurity v3 drops a lead byte whose sequence is incomplete or invalid and, for an overlong form or a surrogate (U+D800–U+DFFF), emits the %uHHHH code anyway followed by the raw lead byte. ModSecurity v2 encodes a NUL byte together with the byte that follows it as %u00HH; libModSecurity v3 drops a NUL byte that is followed by another byte. libModSecurity v3 writes code points above U+FFFF with five hexadecimal digits (for example %u1f600).

sha1

ModSecurity v2supported
libModSecurity v3supported

Calculates a SHA1 hash from the input string. The computed hash is in a raw binary form and may need encoded into text to be printed (or logged). Hash functions are commonly used in combination with hexEncode (for example, t:sha1,t:hexEncode).

trimLeft

ModSecurity v2since 2.5.0
libModSecurity v3since 3.0.3

Removes whitespace from the left side of the input string.

trimRight

ModSecurity v2since 2.5.0
libModSecurity v3since 3.0.3

Removes whitespace from the right side of the input string.

trim

ModSecurity v2since 2.5.0
libModSecurity v3supported

Removes whitespace from both the left and right sides of the input string.

Actions

Each action belongs to one of five groups:

  • Disruptive actions - Cause ModSecurity to do something. In many cases something means block transaction, but not in all. For example, the allow action is classified as a disruptive action, but it does the opposite of blocking. There can only be one disruptive action per rule (if there are multiple disruptive actions present, or inherited, only the last one will take effect), or rule chain (in a chain, a disruptive action can only appear in the first rule).
Note

Disruptive actions will NOT be executed if the SecRuleEngine is set to DetectionOnly. If you are creating exception/whitelisting rules that use the allow action, you should also add the ctl:ruleEngine=On action to execute the action.

  • Non-disruptive actions - Do something, but that something does not and cannot affect the rule processing flow. Setting a variable, or changing its value is an example of a non-disruptive action. Non-disruptive action can appear in any rule, including each rule belonging to a chain.
  • Flow actions - These actions affect the rule flow (for example chain, skip and skipAfter).
  • Meta-data actions - Meta-data actions are used to provide more information about rules. Examples include id, rev, severity and msg.
  • Data actions - Not really actions, these are mere containers that hold data used by other actions. For example, the status action holds the status that will be used for blocking (if it takes place).

accuracy

Specifies the relative accuracy level of the rule related to false positives/negatives. The value is a string based on a numeric scale (1-9 where 9 is very strong and 1 has many false positives). libModSecurity v3 rejects a non-numeric value.

Action groupMeta-data
ModSecurity v2since 2.7
libModSecurity v3supported

Example:

SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/* "@rx \bgetparentfolder\b" \
    "id:'958016',\
    phase:2,\
    block,\
    capture,\
    t:none,\
    t:htmlEntityDecode,\
    t:compressWhiteSpace,\
    t:lowercase,\
    msg:'Cross-site Scripting (XSS) Attack',\
    logdata:'% {TX.0}',\
    tag:'WEB_ATTACK/XSS',\
    tag:'WASCTC/WASC-8',\
    tag:'WASCTC/WASC-22',\
    tag:'OWASP_TOP_10/A2',\
    tag:'OWASP_AppSensor/IE1',\
    tag:'PCI/6.5.1',\
    ctl:auditLogParts=+E,\
    ver:'CRS/2.2.4',\
    accuracy:'9',\
    maturity:'9',\
    severity:'2',\
    setvar:'tx.msg=%{rule.msg}',\
    setvar:tx.xss_score=+%{tx.critical_anomaly_score},\
    setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},\
    setvar:tx.%{rule.id}-WEB_ATTACK/XSS-%{matched_var_name}=%{tx.0}"

allow

Stops rule processing on a successful match and allows the transaction to proceed.

Action groupDisruptive
ModSecurity v2supported
libModSecurity v3supported

Example:

# Allow unrestricted access from 192.168.1.100
SecRule REMOTE_ADDR "@rx ^192\.168\.1\.100$" "id:95,phase:1,allow,nolog"

Prior to ModSecurity 2.5 the allow action would only affect the current phase. An allow in phase 1 would skip processing the remaining rules in phase 1 but the rules from phase 2 would execute. Starting with v2.5.0 allow was enhanced to allow for fine-grained control of what is done. The following rules now apply:

  1. If used on its own, like in the example above, allow will affect the entire transaction, stopping processing of the current phase but also skipping over all other phases apart from the logging phase. (The logging phase is special; it is designed to always execute.)
  2. If used with parameter “phase”, allow will cause the engine to stop processing the current phase. Other phases will continue as normal.
  3. If used with parameter “request”, allow will cause the engine to stop processing the current phase. The next phase to be processed will be phase RESPONSE_HEADERS.

Examples:

# Do not process request but process response.
SecAction "id:96,phase:1,allow:request"

# Do not process transaction (request and response).
SecAction "id:97,phase:1,allow"

If you want to allow a response through, put a rule in phase RESPONSE_HEADERS and simply use allow on its own:

# Allow response through.
SecAction "id:98,phase:3,allow"

libModSecurity v3 implements the same three forms (allow, allow:phase and allow:request) with the same semantics.

append

Appends text given as parameter to the end of response body. Content injection must be enabled (using the SecContentInjection directive). No content type checks are made, which means that before using any of the content injection actions, you must check whether the content type of the response is adequate for injection.

Action groupNon-disruptive
Processing phases3 and 4.
ModSecurity v2supported
libModSecurity v3not supported

Example:

SecRule RESPONSE_CONTENT_TYPE "@rx ^text/html" \
    "id:99,\
    pass,\
    nolog,\
    append:'<hr>Footer'"

A rule can carry only one append action (a second one replaces the first), and a later matching rule that uses append replaces the text set by an earlier one. libModSecurity v3 refuses the rule at configuration load (Action: Append is not yet supported.).

Warning

Although macro expansion is allowed in the additional content, you are strongly cautioned against inserting user-defined data fields into output. Doing so would create a cross-site scripting vulnerability.

auditlog

Marks the transaction for logging in the audit log.

Action groupNon-disruptive
ModSecurity v2supported
libModSecurity v3supported

Example:

SecRule REMOTE_ADDR "^192\.168\.1\.100$" auditlog,phase:1,id:100,allow

Note

The auditlog action is now explicit if log is already specified.

block

Performs the disruptive action defined by the previous SecDefaultAction.

Action groupDisruptive
ModSecurity v2supported
libModSecurity v3supported

This action is essentially a placeholder that is intended to be used by rule writers to request a blocking action, but without specifying how the blocking is to be done. The idea is that such decisions are best left to rule users, as well as to allow users, to override blocking if they so desire. In future versions of ModSecurity, more control and functionality will be added to define “how” to block.

Examples:

# Specify how blocking is to be done
SecDefaultAction "id:101,phase:2,deny,status:403,log,auditlog"

# Detect attacks where we want to block
SecRule ARGS "@rx attack1" "id:102,phase:2,block"

# Detect attacks where we want only to warn
SecRule ARGS "@rx attack2" "id:103,phase:2,pass"

It is possible to use the SecRuleUpdateActionById directive to override how a rule handles blocking. This is useful in three cases:

  1. If a rule has blocking hard-coded, and you want it to use the policy you determine
  2. If a rule was written to block, but you want it to only warn
  3. If a rule was written to only warn, but you want it to block

The following example demonstrates the first case, in which the hard-coded block is removed in favor of the user-controllable block:

# Specify how blocking is to be done
SecDefaultAction "id:104,phase:2,deny,status:403,log,auditlog"

# Detect attacks and block
SecRule ARGS "@rx attack1" "id:1,phase:2,deny"

# Change how rule ID 1 blocks
SecRuleUpdateActionById 1 "block"

libModSecurity v3 runs the disruptive action of the SecDefaultAction defined for the rule’s phase; if there is none for that phase, block does nothing. v3 requires SecDefaultAction to name a real disruptive action (block is not accepted there) and allows it only once per phase.

capture

When used together with the regular expression operator (@rx), the capture action will create copies of the regular expression captures and place them into the transaction variable collection.

Action groupNon-disruptive
ModSecurity v2supported
libModSecurity v3supported

Example:

SecRule REQUEST_BODY "@rx ^username=(\w{25,})" \
    "id:105,\
    phase:2,\
    capture,\
    t:none,\
    chain"
    SecRule TX:1 "@rx (?:(?:a(dmin|nonymous)))"

The TX.0 variable always contains the entire area that the regular expression matched. All the other variables contain the captured values, in the order in which the capturing parentheses appear in the regular expression.

  • ModSecurity v2: up to 10 captures are copied on a successful pattern match, each with a name consisting of a digit from 0 to 9.
  • libModSecurity v3: every capturing group of the match is copied (TX.0, TX.1, TX.2, …); there is no fixed limit of ten. Besides @rx, v3 honors capture for @rxGlobal, @pm, @detectSQLi, @detectXSS, @rbl, @verifyCC, @verifyCPF, @verifySSN and @verifySVNR.

chain

Chains the current rule with the rule that immediately follows it, creating a rule chain. Chained rules allow for more complex processing logic.

Action groupFlow
ModSecurity v2supported
libModSecurity v3supported

Example:

# Refuse to accept POST requests that do not contain Content-Length header.
# (Do note that this rule should be preceded by a rule
# that verifies only valid request methods are used.)
SecRule REQUEST_METHOD "@rx ^POST$" "id:105,phase:1,t:none,chain"
    SecRule &REQUEST_HEADERS:Content-Length "@eq 0" "t:none"
Note

Rule chains allow you to simulate logical AND. The disruptive actions specified in the first portion of the chained rule will be triggered only if all of the variable checks return positive hits. If any one aspect of a chained rule comes back negative, then the entire rule chain will fail to match. Also note that disruptive actions, execution phases, metadata actions (id, rev, msg, tag, severity, logdata), skip, and skipAfter actions can be specified only by the chain starter rule.

The following directives can be used in rule chains:

  • SecAction
  • SecRule
  • SecRuleScript

Special rules control the usage of actions in chained rules:

  • Any actions that affect the rule flow (i.e., the disruptive actions, skip and skipAfter) can be used only in the chain starter. They will be executed only if the entire chain matches.
  • Non-disruptive actions can be used in any rule; they will be executed if the rule that contains them matches and not only when the entire chain matches. In libModSecurity v3 this is true only for setvar: every other non-disruptive action in a chained rule (ctl, setenv, exec, log, …) runs only once the whole chain has matched.
  • The metadata actions (e.g., id, rev, msg) can be used only in the chain starter.

ctl

Changes ModSecurity configuration on transient, per-transaction basis. Any changes made using this action will affect only the transaction in which the action is executed. The default configuration, as well as the other transactions running in parallel, will be unaffected.

Action groupNon-disruptive
ModSecurity v2supported
libModSecurity v3supported

Example:

# Parse requests with Content-Type "text/xml" as XML
SecRule REQUEST_CONTENT_TYPE "@rx ^text/xml" \
    "id:106,\
    pass,\
    nolog,\
    ctl:requestBodyProcessor=XML"

# white-list the user parameter for rule #981260 when the REQUEST_URI is /index.php
SecRule REQUEST_URI "@beginsWith /index.php" \
    "phase:1,\
    pass,\
    t:none,\
    nolog,\
    ctl:ruleRemoveTargetById=981260;ARGS:user"

The following configuration options are supported. Unless noted otherwise an option is available in both ModSecurity v2 and libModSecurity v3:

  1. auditEngine - v2: yes. v3: since 3.0.7.
  2. auditLogParts - v2: yes. v3: yes, but only the +/- forms (+E, -E); an absolute part list is a parse error.
  3. debugLogLevel - v2: yes. v3: no.
  4. forceRequestBodyVariable - v2: since 2.5.7. v3: accepted by the parser but has no effect (REQUEST_BODY is always populated in v3).
  5. hashEnforcement - v2: since 2.7.1 (named EncryptionEnforcement in 2.7.0). v3: no.
  6. hashEngine - v2: since 2.7.1 (named EncryptionEngine in 2.7.0). v3: no.
  7. parseXmlIntoArgs - v2: since 2.9.9 (On, Off or OnlyArgs). v3: since 3.0.15. Controls XML nodes’ parsing into ARGS, see SecParseXmlIntoArgs.
  8. requestBodyAccess - v2: yes. v3: yes.
  9. requestBodyLimit - v2: yes. v3: no.
  10. requestBodyProcessor - v2: yes. v3: yes (XML, JSON, and since 3.0.3 URLENCODED).
  11. responseBodyAccess - v2: yes. v3: no.
  12. responseBodyLimit - v2: yes. v3: no.
  13. ruleEngine - v2: yes. v3: yes.
  14. ruleRemoveById - v2: since 2.5.0; the value is a rule ID, a range (1000-1999) or a comma-separated list of IDs and ranges. v3: yes, but one ID or one range per action (no list); repeat the action to remove several (since 3.0.4). Since this action is triggered at run time, it should be specified before the rule which it is disabling.
  15. ruleRemoveByMsg - v2: since 2.7.0; the value is a regular expression matched against the rule message. v3: no.
  16. ruleRemoveByTag - v2: since 2.6.0; the value is a regular expression matched against the rule tags. v3: since 3.0.1, compared literally against each tag (not a regular expression).
  17. ruleRemoveTargetById - v2: since 2.6.7. v3: yes, with the target compared literally against the variable name (ARGS:user; no regular-expression targets). Since this action is used to just remove targets, users don’t need to use the char ! before the target list.
  18. ruleRemoveTargetByMsg - v2: since 2.7.0. v3: no. Since this action is used to just remove targets, users don’t need to use the char ! before the target list.
  19. ruleRemoveTargetByTag - v2: since 2.7.0. v3: yes, with both the tag and the target compared literally. Since this action is used to just remove targets, users don’t need to use the char ! before the target list.

ctl:forceResponseBodyVariable and ctl:responseBodyProcessor exist only in Coraza; neither ModSecurity v2 nor libModSecurity v3 accepts them. libModSecurity v3 recognizes only the options marked “v3: yes” above; any other ctl option (for example ctl:responseBodyAccess=Off) is a parse error that rejects the configuration.

With the exception of the requestBodyProcessor and forceRequestBodyVariable settings, each configuration option corresponds to one configuration directive and the usage is identical.

The requestBodyProcessor option allows you to configure the request body processor. By default, ModSecurity will use the URLENCODED and MULTIPART processors to process an application/x-www-form-urlencoded and a multipart/form-data body, respectively. Other two processors are also supported: JSON and XML, but they are never used implicitly. Instead, you must tell ModSecurity to use it by placing a few rules in the REQUEST_HEADERS processing phase. After the request body is processed as XML, you will be able to use the XML-related features to inspect it.

Request body processors will not interrupt a transaction if an error occurs during parsing. Instead, they will set the variables REQBODY_PROCESSOR_ERROR and REQBODY_PROCESSOR_ERROR_MSG. These variables should be inspected in the REQUEST_BODY phase and an appropriate action taken. The forceRequestBodyVariable option allows you to configure the REQUEST_BODY variable to be set when there is no request body processor configured. This allows for inspection of request bodies of unknown types.

Note

There was a ctl:ruleUpdateTargetById introduced in 2.6.0 and removed from the code in 2.7.0. JSON was added as part of v2.8.0-rc1

deny

Stops rule processing and intercepts transaction.

Action groupDisruptive
ModSecurity v2supported
libModSecurity v3supported

Example: SecRule REQUEST_HEADERS:User-Agent "nikto" "log,deny,id:107,msg:'Nikto Scanners Identified'"

deprecatevar

Decrements numerical value over time, which makes sense only applied to the variables stored in persistent storage.

Action groupNon-disruptive
ModSecurity v2supported
libModSecurity v3not supported

Example: The following example will decrement the counter by 60 every 300 seconds.

SecAction "id:108,phase:5,pass,nolog,deprecatevar:SESSION.score=60/300"

Counter values are always positive, meaning that the value will never go below zero. Unlike expirevar, the deprecate action must be executed on every request. libModSecurity v3 refuses the rule at configuration load (Action: DeprecateVar is not yet supported.).

drop

Initiates an immediate close of the TCP connection by sending a FIN packet.

Action groupDisruptive
ModSecurity v2supported
libModSecurity v3since 3.0.4 (behaves like deny, see below)

Example: The following example initiates an IP collection for tracking Basic Authentication attempts. If the client goes over the threshold of more than 25 attempts in 2 minutes, it will DROP subsequent connections.

SecAction "id:109,phase:1,nolog,initcol:ip=%{REMOTE_ADDR}"
SecRule ARGS:login "!@rx ^$" \
    "id:110,\
    phase:1,\
    nolog,\
    setvar:ip.auth_attempt=+1,\
    deprecatevar:ip.auth_attempt=25/120"
SecRule IP:AUTH_ATTEMPT "@gt 25" \
    "id:111,\
    phase:1,\
    drop,\
    log,\
    msg:'Possible Brute Force Attack'"
Note

This action is currently not available on Windows based builds.

This action is extremely useful when responding to both Brute Force and Denial of Service attacks in that, in both cases, you want to minimize both the network bandwidth and the data returned to the client. This action causes error message to appear in the log “(9)Bad file descriptor: core_output_filter: writing data to the network”

Unlike in v2, in libModSecurity v3 (since 3.0.4) this action currently functions the same as the deny action: the transaction is intercepted with a 403 status instead of the connection being closed.

exec

Executes an external script/binary supplied as parameter. As of v2.5.0, if the parameter supplied to exec is a Lua script (detected by the .lua extension) the script will be processed internally. This means you will get direct access to the internal request context from the script. Please read the SecRuleScript documentation for more details on how to write Lua scripts.

Action groupNon-disruptive
ModSecurity v2supported
libModSecurity v3supported (Lua scripts only)

Example:

# Run external program on rule match
SecRule REQUEST_URI "@rx ^/cgi-bin/script\.pl" \
    "id:112,\
    phase:2,\
    block,\
    t:none,\
    t:lowercase,\
    t:normalizePath,\
    \ exec:/usr/local/apache/bin/test.sh"

# Run Lua script on rule match
SecRule ARGS:p "@rx attack" \
    "id:113,\
    phase:2,\
    block,\
    exec:/usr/local/apache/conf/exec.lua"

The exec action is executed independently from any disruptive actions specified. External scripts will always be called with no parameters. Some transaction information will be placed in environment variables. All the usual CGI environment variables will be there. You should be aware that forking a threaded process results in all threads being replicated in the new process. Forking can therefore incur larger overhead in a multithreaded deployment. The script you execute must write something (anything) to stdout; if it doesn’t, ModSecurity will assume that the script failed, and will record the failure.

libModSecurity v3 only supports Lua scripts (detected by the .lua extension); it does not fork external binaries. The library must be built with Lua support (--with-lua, detected automatically by configure), and the script is loaded when the configuration is parsed, so a missing or non-Lua script is a configuration error.

expirevar

Configures a collection variable to expire after the given time period (in seconds).

Action groupNon-disruptive
ModSecurity v2supported
libModSecurity v3since 3.0.11

Example:

SecRule REQUEST_COOKIES:JSESSIONID "!@rx ^$" \
    "id:114,\
    phase:1,\
    pass,\
    nolog,\
    setsid:%{REQUEST_COOKIES:JSESSIONID}"
SecRule REQUEST_URI "@rx ^/cgi-bin/script\.pl" \
    "id:115,\
    phase:2,\
    phase:1,\
    allow,\
    t:none,\
    t:lowercase,\
    t:normalizePath,\
    log,\
    setvar:session.suspicious=1,\
    expirevar:session.suspicious=3600"

You should use the expirevar actions at the same time that you use setvar actions in order to keep the intended expiration time. If they are used on their own (perhaps in a SecAction directive), the expire time will be reset.

libModSecurity v3 supports expirevar since 3.0.11, for the ip, global, resource, session and user collections.

id

Assigns a unique, numeric ID to the rule or chain in which it appears. Starting with ModSecurity 2.7 this action is mandatory; libModSecurity v3 rejects any SecRule or SecAction without an id, and also rejects a rule whose id is already in use.

Action groupMeta-data
ModSecurity v2supported
libModSecurity v3supported

Example:

SecRule &REQUEST_HEADERS:Host "@eq 0" \
    "id:60008,\
    log,\
    msg:'Request Missing a Host Header',\
    severity:2"
Note

The id action is required for all SecRule/SecAction directives as of v2.7.0

These are the reserved ranges:

  • 1–99,999: reserved for local (internal) use. Use as you see fit, but do not use this range for rules that are distributed to others
  • 100,000–199,999: reserved for rules published by Oracle
  • 200,000–299,999: reserved for rules published Comodo
  • 300,000–399,999: reserved for rules published at gotroot.com
  • 400,000–419,999: unused (available for reservation)
  • 420,000–429,999: reserved for ScallyWhack 1
  • 430,000–439,999: reserved for rules published by Flameeyes 2
  • 440.000-599,999: unused (available for reservation)
  • 600,000-699,999: reserved for use by Akamai 3
  • 700,000–799,999: reserved for Ivan Ristic
  • 900,000–999,999: reserved for the OWASP CRS 4 project
  • 1,000,000-1,009,999: reserved for rules published by Redhat Security Team
  • 1,010,000-1,999,999: reserved for WAF | Web Application Firewall and Load Balancer Security (kemptechnologies.com) 5
  • 2,000,000-2,999,999: reserved for rules from Trustwave’s SpiderLabs Research team
  • 3,000,000-3,999,999: reserved for use by Akamai 6
  • 4,000,000-4,099,999 reserved: in use by AviNetworks 7
  • 4,100,000-4,199,999 reserved: in use by Fastly 8
  • 4,200,000-4,299,999 reserved: in use by CMS-Garden 9
  • 4,300,000-4,300,999 reserved: in use by Ensim.hu 10
  • 4,301,000-19,999,999: unused (available for reservation)
  • 8,000,000-8,999,999 reserved: in use by Yandex
  • 20,000,000-21,999,999: reserved for rules from Trustwave’s SpiderLabs Research team
  • 22,000,000-69,999,999: unused (available for reservation)
  • 77,000,000-77,999,999 - reserved: in use by Imunify360 - production rules
  • 88,000,000-88,999,999 - reserved: in use by Imunify360 - beta users
  • 99,000,000-99,099,999 reserved for use by Microsoft https://azure.microsoft.com/en-us/services/web-application-firewall/
  • 99,100,000-99,199,999 reserved for use by WPScan/Jetpack
  • 99,200,000-99,209,999 reserved for use by SKUDONET 11
Note

The id is an identifier only; it does not determine the relative order in which rules are executed. I.e. a rule with id 5001 will not be executed before rule 5002 just because the former is numerically smaller.

initcol

Initializes a named persistent collection, either by loading data from storage or by creating a new collection in memory.

Action groupNon-disruptive
ModSecurity v2supported
libModSecurity v3supported

Example: The following example initiates IP address tracking, which is best done in phase 1:

SecAction "id:116,phase:1,pass,nolog,initcol:ip=%{REMOTE_ADDR}"

Collections are loaded into memory on-demand, when the initcol action is executed. A collection will be persisted only if a change was made to it in the course of transaction processing.

libModSecurity v3 accepts only ip, global and resource as the collection name (SESSION and USER are initialized with setsid and setuid); any other name is a configuration error.

See the “Persistent Storage” section for further details.

log

Indicates that a successful match of the rule needs to be logged.

Action groupNon-disruptive
ModSecurity v2supported
libModSecurity v3supported

Example:

SecAction "id:117,phase:1,pass,log,initcol:ip=%{REMOTE_ADDR}"

This action will log matches to the web server’s error log file (the Apache error log in v2) and the ModSecurity audit log.

logdata

Logs a data fragment as part of the alert message.

Action groupNon-disruptive
ModSecurity v2since 2.5.0
libModSecurity v3supported

Example:

SecRule ARGS:p "@rx <script>" "id:118,phase:2,pass,log,logdata:%{MATCHED_VAR}"

The logdata information appears in the error and/or audit log files. Macro expansion is performed, so you may use variable names such as %{TX.0} or %{MATCHED_VAR}. The information is properly escaped for use with logging of binary data.

marker

Internal meta-data action created by the SecMarker directive; it carries the marker label used as a skipAfter target. It is never written by rule authors.

Action groupMeta-data
ModSecurity v2since 2.5.0
libModSecurity v3not supported

In ModSecurity v2, SecMarker LABEL is expanded into the rule SecRule REMOTE_ADDR "@noMatch" "t:none,pass,marker:LABEL", so marker shows up as an action in the rule set. libModSecurity v3 does not have a marker action: SecMarker is implemented as a dedicated marker rule, and the directive and skipAfter work the same way in both engines.

maturity

Specifies the relative maturity level of the rule related to the length of time a rule has been public and the amount of testing it has received. The value is a string based on a numeric scale (1-9 where 9 is extensively tested and 1 is a brand new experimental rule). libModSecurity v3 rejects a non-numeric value.

Action groupMeta-data
ModSecurity v2since 2.7
libModSecurity v3supported

Example:

SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/* "@rx \bgetparentfolder\b" \
    "id:'958016',\
    phase:2,\
    block,\
    capture,\
    t:none,\
    t:htmlEntityDecode,\
    t:compressWhiteSpace,\
    t:lowercase,\
    msg:'Cross-site Scripting (XSS) Attack',\
    logdata:'% {TX.0}',\
    tag:'WEB_ATTACK/XSS',\
    tag:'WASCTC/WASC-8',\
    tag:'WASCTC/WASC-22',\
    tag:'OWASP_TOP_10/A2',\
    tag:'OWASP_AppSensor/IE1',\
    tag:'PCI/6.5.1',\
    ctl:auditLogParts=+E,\
    ver:'CRS/2.2.4',\
    accuracy:'9',\
    maturity:'9',\
    severity:'2',\
    setvar:'tx.msg=%{rule.msg}',\
    setvar:tx.xss_score=+%{tx.critical_anomaly_score},\
    setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},\
    setvar:tx.%{rule.id}-WEB_ATTACK/XSS-%{matched_var_name}=%{tx.0}"

msg

Assigns a custom message to the rule or chain in which it appears. The message will be logged along with every alert.

Action groupMeta-data
ModSecurity v2supported
libModSecurity v3supported

Example:

SecRule &REQUEST_HEADERS:Host "@eq 0" \
    "id:60008,\
    log,\
    msg:'Request Missing a Host Header',\
    severity:2"
Note

The msg information appears in the error and/or audit log files and is not sent back to the client in response headers.

multiMatch

If enabled, ModSecurity will perform multiple operator invocations for every target, before and after every anti-evasion transformation is performed.

Action groupNon-disruptive
ModSecurity v2supported
libModSecurity v3supported

Example:

SecRule ARGS "@rx attack" \
    "id:119,\
    phase:1,\
    deny,\
    t:removeNulls,\
    t:lowercase,\
    log,\
    multiMatch"

Normally, variables are inspected only once per rule, and only after all transformation functions have been completed. With multiMatch, variables are checked against the operator before and after every transformation function that changes the input.

noauditlog

Indicates that a successful match of the rule should not be used as criteria to determine whether the transaction should be logged to the audit log.

Action groupNon-disruptive
ModSecurity v2supported
libModSecurity v3supported

Example:

SecRule REQUEST_HEADERS:User-Agent "@rx Test" "id:120,allow,noauditlog"

If the SecAuditEngine is set to On, all of the transactions will be logged. If it is set to RelevantOnly, then you can control the logging with the noauditlog action.

The noauditlog action affects only the current rule. If you prevent audit logging in one rule only, a match in another rule will still cause audit logging to take place. If you want to prevent audit logging from taking place, regardless of whether any rule matches, use ctl:auditEngine=Off.

nolog

Prevents rule matches from appearing in both the error and audit logs.

Action groupNon-disruptive
ModSecurity v2supported
libModSecurity v3supported

Example:

SecRule REQUEST_HEADERS:User-Agent "@rx Test" "id:121,allow,nolog"

Although nolog implies noauditlog, you can override the former by using nolog,auditlog.

pass

Continues processing with the next rule in spite of a successful match.

Action groupDisruptive
ModSecurity v2supported
libModSecurity v3supported

Example:

SecRule REQUEST_HEADERS:User-Agent "@rx Test" "id:122,pass,log"

When using pass with a SecRule with multiple targets, all variables will be inspected and all non-disruptive actions trigger for every match. In the following example, the TX.test variable will be incremented once for every request parameter:

# Set TX.test to zero
SecAction "id:123,phase:2,pass,nolog,setvar:TX.test=0"

# Increment TX.test for every request parameter
SecRule ARGS "@rx test" "id:124,phase:2,pass,log,setvar:TX.test=+1"

pause

Pauses transaction processing for the specified number of milliseconds. Starting with ModSecurity 2.7 this feature also supports macro expansion.

Action groupDisruptive
ModSecurity v2supported
libModSecurity v3not supported

Example:

SecRule REQUEST_HEADERS:User-Agent "@rx Test" "id:125,pause:5000,log"

In ModSecurity v2 pause is a disruptive action in its own right: when it is the disruptive action that takes effect, the transaction is paused and then allowed through, exactly like allow. To pause and then block, place pause before the blocking action, for example pause:5000,deny. Values that are not a positive integer result in no pause. libModSecurity v3 refuses the rule at configuration load (Action: Pause is not yet supported.).

Warning

This feature can be of limited benefit for slowing down brute force authentication attacks, but use with care. If you are under a denial of service attack, the pause feature may make matters worse, as it will cause an entire Apache worker (process or thread, depending on the deployment mode) to sit idle until the pause is completed.

phase

Places the rule or chain into one of five available processing phases. It can also be used in SecDefaultAction to establish the rule defaults for that phase. Internally ModSecurity v2 registers phase with the disruptive action type, which is why it is accepted only in the chain starter; it never intercepts the transaction.

Action groupMeta-data
ModSecurity v2supported
libModSecurity v3supported

Example:

# Initialize IP address tracking in phase 1
SecAction "id:126,phase:1,pass,nolog,initcol:IP=%{REMOTE_ADDR}"

libModSecurity v3 additionally accepts phase:0, a connection phase run when the connector calls processConnection(), before any request data has been read; only REMOTE_ADDR, REMOTE_HOST, REMOTE_PORT, SERVER_ADDR, SERVER_PORT and UNIQUE_ID are populated there.

Starting in ModSecurity version v2.7 (and in all libModSecurity v3 releases) there are aliases for three of the five phase numbers:

  • 2 - request
  • 4 - response
  • 5 - logging

Example:

SecRule REQUEST_HEADERS:User-Agent "@rx Test" "id:127,phase:2,deny,log"
Warning

Keep in mind that if you specify the incorrect phase, the variable used in the rule may not yet be available. This could lead to a false negative situation where your variable and operator may be correct, but it misses malicious data because you specified the wrong phase.

prepend

Prepends the text given as parameter to response body. Content injection must be enabled (using the SecContentInjection directive). No content type checks are made, which means that before using any of the content injection actions, you must check whether the content type of the response is adequate for injection.

Action groupNon-disruptive
Processing phases3 and 4.
ModSecurity v2supported
libModSecurity v3not supported

Example:

SecRule RESPONSE_CONTENT_TYPE "@rx ^text/html" \
    "id:128,\
    phase:3,\
    pass,\
    nolog,\
    prepend:'Header<br>'"

A rule can carry only one prepend action (a second one replaces the first), and a later matching rule that uses prepend replaces the text set by an earlier one. libModSecurity v3 refuses the rule at configuration load (Action: Prepend is not yet supported.).

Warning

Although macro expansion is allowed in the injected content, you are strongly cautioned against inserting user defined data fields into output. Doing so would create a cross-site scripting vulnerability.

proxy

Intercepts the current transaction by forwarding the request to another web server using the proxy backend. The forwarding is carried out transparently to the HTTP client (i.e., there’s no external redirection taking place).

Action groupDisruptive
ModSecurity v2supported
libModSecurity v3not supported

Example:

SecRule REQUEST_HEADERS:User-Agent "@rx Test" \
    "id:129,\
    proxy:http://honeypothost/,\
    log"
SecRule REQUEST_URI "@streq /test.txt" \
    "id:500005,\
    phase:1,\
    proxy:'[nocanon]http://$ENV{SERVER_NAME}:$ENV{SERVER_PORT}/test.txt'"

For this action to work, mod_proxy must also be installed, and the rule must run in phase 1 or 2; in the output phases, or without mod_proxy, ModSecurity v2 responds with status 500 instead. This action is useful if you would like to proxy matching requests onto a honeypot web server, and especially in combination with IP address or session tracking. libModSecurity v3 refuses the rule at configuration load (Action: Proxy is not yet supported.).

Note

As of v2.9.1 the proxy action can receive a special parameter named “[nocanon]”. The “[nocanon]” parameter will make the url to be delivered to the backend on its original format (raw). Further information about “nocanon” is available here: https://httpd.apache.org/docs/2.2/pt-br/mod/mod_proxy.html.

redirect

Intercepts transaction by issuing an external (client-visible) redirection to the given location..

Action groupDisruptive
ModSecurity v2supported
libModSecurity v3supported

Example:

SecRule REQUEST_HEADERS:User-Agent "@rx Test" \
    "id:130,\
    phase:1,\
    redirect:http://www.example.com/failed.html,\
    log"

If the status action is present on the same rule, and its value can be used for a redirection (i.e., is one of the following: 301, 302, 303, or 307), the value will be used for the redirection status code. Otherwise, status code 302 will be used. libModSecurity v3 (since 3.0.3) keeps any status in the 301-307 range and macro-expands the location.

rev

Specifies rule revision. It is useful in combination with the id action to provide an indication that a rule has been changed.

Action groupMeta-data
ModSecurity v2supported
libModSecurity v3supported

Example:

SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/* "@rx (?:(?:[\;\|\`]\W*?\bcc|\b(wget|curl))\b|\/cc(?:[\'\"\|\;\`\-\s]|$))" \
    "id:'950907',\
    phase:2,\
    block,\
    capture,\
    t:none,\
    t:normalizePath,\
    t:lowercase,\
    msg:'System Command Injection',\
    logdata:'%{TX.0}',\
    tag:'WEB_ATTACK/COMMAND_INJECTION',\
    tag:'WASCTC/WASC-31',\
    tag:'OWASP_TOP_10/A1',\
    tag:'PCI/6.5.2',\
    ctl:auditLogParts=+E,\
    rev:'2.1.3',\
    severity:'2',\
    setvar:'tx.msg=%{rule.msg}',\
    setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},\
    setvar:tx.command_injection_score=+%{tx.critical_anomaly_score},\
    setvar:tx.%{rule.id}-WEB_ATTACK/COMMAND_INJECTION-%{matched_var_name}=%{tx.0},\
    skipAfter:END_COMMAND_INJECTION1"
Note

This action is used in combination with the id action to allow the same rule ID to be used after changes take place but to still provide some indication the rule changed.

sanitiseArg

Prevents sensitive request parameter data from being logged to audit log. Each byte of the named parameter(s) is replaced with an asterisk. Since 2.6.0 ModSecurity v2 also accepts the American spelling sanitizeArg.

Action groupNon-disruptive
ModSecurity v2supported
libModSecurity v3not supported

Example:

# Never log passwords
SecAction \
    "id:131,\
    phase:2,\
    nolog,\
    sanitiseArg:password,\
    sanitiseArg:newPassword,\
    sanitiseArg:oldPassword"

libModSecurity v3 refuses the rule at configuration load (Action: SanitiseArg is not yet supported.).

Note

The sanitize actions affect only the data as it is logged to audit log. High-level debug logs may contain sensitive data. Apache access log may contain sensitive data placed in the request URI.

sanitiseMatched

Prevents the matched variable (request argument, request header, or response header) from being logged to audit log. Each byte of the named parameter(s) is replaced with an asterisk. Since 2.6.0 ModSecurity v2 also accepts the American spelling sanitizeMatched.

Action groupNon-disruptive
ModSecurity v2supported
libModSecurity v3not supported

Example: This action can be used to sanitize arbitrary transaction elements when they match a condition. For example, the example below will sanitize any argument that contains the word password in the name.

SecRule ARGS_NAMES "@rx password" "id:132,pass,nolog,sanitiseMatched"

libModSecurity v3 refuses the rule at configuration load (Action: SanitiseMatched is not yet supported.).

Note

The sanitize actions affect only the data as it is logged to audit log. High-level debug logs may contain sensitive data. Apache access log may contain sensitive data placed in the request URI.

sanitiseMatchedBytes

Prevents the matched string in a variable from being logged to audit log. Each or a range of bytes of the named parameter(s) is replaced with an asterisk. ModSecurity v2 also accepts the American spelling sanitizeMatchedBytes.

Action groupNon-disruptive
ModSecurity v2since 2.6.0
libModSecurity v3not supported

Example: This action can be used to sanitize arbitrary transaction elements when they match a condition. For example, the example below will sanitize the credit card number.

  • sanitiseMatchedBytes – This would x out only the bytes that matched.
  • sanitiseMatchedBytes:1/4 – This would x out the bytes that matched, but keep the first byte and last 4 bytes. Both numbers must be a single digit (0-9); any other parameter is ignored and the whole match is sanitized.
# Detect credit card numbers in parameters and
# prevent them from being logged to audit log
SecRule ARGS "@verifyCC \d{13,16}" \
    "id:133,\
    phase:2,\
    pass,\
    capture,\
    nolog,\
    msg:'Potential credit card number in request',\
    sanitiseMatchedBytes"
SecRule RESPONSE_BODY "@verifyCC \d{13,16}" \
    "id:134,\
    phase:4,\
    block,\
    capture,\
    t:none,\
    log,\
    msg:'Potential credit card number is response body',\
    sanitiseMatchedBytes:0/4"

libModSecurity v3 refuses the rule at configuration load (Action: SanitiseMatchedBytes is not yet supported.).

Note

The sanitize actions affect only the data as it is logged to audit log. High-level debug logs may contain sensitive data. Apache access log may contain sensitive data placed in the request URI. You must use capture action with sanitiseMatchedBytes, so the operator must support capture action. ie: @rx, @verifyCC.

sanitiseRequestHeader

Prevents a named request header from being logged to audit log. Each byte of the named request header is replaced with an asterisk. Since 2.6.0 ModSecurity v2 also accepts the American spelling sanitizeRequestHeader.

Action groupNon-disruptive
ModSecurity v2supported
libModSecurity v3not supported

Example: This will sanitize the data in the Authorization header.

SecAction "id:135,phase:1,pass,nolog,sanitiseRequestHeader:Authorization"

libModSecurity v3 refuses the rule at configuration load (Action: SanitiseRequestHeader is not yet supported.).

Note

The sanitize actions affect only the data as it is logged to audit log. High-level debug logs may contain sensitive data. Apache access log may contain sensitive data placed in the request URI.

sanitiseResponseHeader

Prevents a named response header from being logged to audit log. Each byte of the named response header is replaced with an asterisk. Since 2.6.0 ModSecurity v2 also accepts the American spelling sanitizeResponseHeader.

Action groupNon-disruptive
ModSecurity v2supported
libModSecurity v3not supported

Example: This will sanitize the Set-Cookie data sent to the client.

SecAction "id:136,phase:3,pass,nolog,sanitiseResponseHeader:Set-Cookie"

libModSecurity v3 refuses the rule at configuration load (Action: SanitiseResponseHeader is not yet supported.).

Note

The sanitize actions affect only the data as it is logged to audit log. High-level debug logs may contain sensitive data. Apache access log may contain sensitive data placed in the request URI.

severity

Assigns severity to the rule in which it is used.

Action groupMeta-data
ModSecurity v2supported
libModSecurity v3supported

Example:

SecRule REQUEST_METHOD "@rx ^PUT$" \
    "id:340002,\
    msg:'Restricted HTTP function',\
    rev:1,\
    severity:CRITICAL"

Severity values in ModSecurity follows the numeric scale of syslog (where 0 is the most severe). The data below is used by the OWASP CRS:

  • 0 - EMERGENCY: is generated from correlation of anomaly scoring data where there is an inbound attack and an outbound leakage.
  • 1 - ALERT: is generated from correlation where there is an inbound attack and an outbound application level error.
  • 2 - CRITICAL: Anomaly Score of 5. Is the highest severity level possible without correlation. It is normally generated by the web attack rules (40 level files).
  • 3 - ERROR: Error - Anomaly Score of 4. Is generated mostly from outbound leakage rules (50 level files).
  • 4 - WARNING: Anomaly Score of 3. Is generated by malicious client rules (35 level files).
  • 5 - NOTICE: Anomaly Score of 2. Is generated by the Protocol policy and anomaly files.
  • 6 - INFO
  • 7 - DEBUG

Both ModSecurity v2 (text values since 2.7.5, matched case-insensitively) and libModSecurity v3 accept either the numerical values or the text values, but you should always specify severity levels using the text values, because it is difficult to remember what a number stands for.

setuid

Special-purpose action that initializes the USER collection using the username provided as parameter.

Action groupNon-disruptive
ModSecurity v2supported
libModSecurity v3supported

Example:

SecRule ARGS:username "@rx .*" \
    "id:137,\
    phase:2,\
    pass,\
    capture,\
    t:none,\
    nolog,\
    noauditlog,\
    setuid:%{TX.0},\
    setvar:session.username=%{TX.0}"

After initialization takes place, the variable USERID will be available for use in the subsequent rules. This action understands application namespaces (configured using SecWebAppId), and will use one if it is configured.

setrsc

Special-purpose action that initializes the RESOURCE collection using a key provided as parameter.

Action groupNon-disruptive
ModSecurity v2since 2.7.0
libModSecurity v3supported

Example:

SecAction "id:3,phase:1,pass,log,setrsc:'abcd1234'"

This action understands application namespaces (configured using SecWebAppId), and will use one if it is configured.

setsid

Special-purpose action that initializes the SESSION collection using the session token provided as parameter.

Action groupNon-disruptive
ModSecurity v2supported
libModSecurity v3supported

Example:

# Initialize session variables using the session cookie value
SecRule REQUEST_COOKIES:PHPSESSID "!@rx ^$" \
    "id:138,\
    pass,\
    nolog,\
    setsid:%{REQUEST_COOKIES.PHPSESSID}"

Note

After the initialization takes place, the variable SESSION will be available for use in the subsequent rules. This action understands application namespaces (configured using SecWebAppId), and will use one if it is configured.

Setsid takes an individual variable, not a collection. Variables within an action, such as setsid, use the format [collection].[variable] .

setenv

Creates, removes, and updates environment variables that can be accessed by the web server (Apache in v2; in libModSecurity v3, since 3.0.3, by both ModSecurity and the web server).

Action groupNon-disruptive
ModSecurity v2supported
libModSecurity v3since 3.0.3

Examples:

SecRule RESPONSE_HEADERS:/Set-Cookie2?/ "@rx (?i:(j?sessionid|(php)?sessid|(asp|jserv|jw)?session[-_]?(id)?|cf(id|token)|sid))" \
    "id:139,\
    phase:3,\
    pass,\
    t:none,\
    nolog,\
    setvar:tx.sessionid=%{matched_var}"
SecRule TX:SESSIONID "!@rx (?i:\;? ?httponly;?)" \
    "id:140,\
    phase:3,\
    pass,\
    t:none,\
    log,\
    auditlog,\
    msg:'AppDefect: Missing HttpOnly Cookie Flag.',\
    setenv:httponly_cookie=%{matched_var}"

Header set Set-Cookie "%{httponly_cookie}e; HTTPOnly" env=httponly_cookie
Note

In ModSecurity v2, when used in a chain this action will be executed when an individual rule matches and not the entire chain. In libModSecurity v3 only setvar runs independently of the chain result, so setenv on the first rule of a chain will only execute if the entire chain matches.

setvar

Creates, removes, or updates a variable. Variable names are case-insensitive. libModSecurity v3 stores setvar only in the TX, IP, GLOBAL, RESOURCE, SESSION and USER collections; a setvar on any other variable is accepted by the parser but does nothing.

Action groupNon-disruptive
ModSecurity v2supported
libModSecurity v3supported

Examples: To create a variable and set its value to 1 (usually used for setting flags), use: setvar:TX.score

To create a variable and initialize it at the same time, use: setvar:TX.score=10

To remove a variable, prefix the name with an exclamation mark: setvar:!TX.score

To increase or decrease variable value, use + and - characters in front of a numerical value: setvar:TX.score=+5

Example from OWASP CRS:

SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/* "@rx \bsys\.user_catalog\b" \
    "id:'959517',\
    phase:2,\
    block,\
    capture,\
    t:none,\
    t:urlDecodeUni,\
    t:htmlEntityDecode,\
    t:lowercase,\
    t:replaceComments,\
    t:compressWhiteSpace,\
    msg:'Blind SQL Injection Attack',\
    logdata:'%{TX.0}',\
    tag:'WEB_ATTACK/SQL_INJECTION',\
    tag:'WASCTC/WASC-19',\
    tag:'OWASP_TOP_10/A1',\
    tag:'OWASP_AppSensor/CIE1',\
    tag:'PCI/6.5.2',\
    ctl:auditLogParts=+E,\
    rev:'2.1.3',\
    severity:'2',\
    setvar:'tx.msg=%{rule.msg}',\
    setvar:tx.sql_injection_score=+%{tx.critical_anomaly_score},\
    setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},\
    setvar:tx.%{rule.id}-WEB_ATTACK/SQL_INJECTION-%{matched_var_name}=%{tx.0}"
Note

When used in a chain this action will be executed when an individual rule matches and not the entire chain. This means that

SecRule REQUEST_FILENAME "@contains /test.php" \
    "id:7,\
    phase:1,\
    t:none,\
    nolog,\
    setvar:tx.auth_attempt=+1,\
    chain"
    SecRule ARGS_POST:action "@streq login" "t:none"
  • will increment every time that test.php is visited (regardless of the parameters submitted). If the desired goal is to set the variable only if the entire rule matches, it should be included in the last rule of the chain . For instance:
SecRule REQUEST_FILENAME "@streq test.php" "id:7,phase:1,t:none,nolog,chain"
    SecRule ARGS_POST:action "@streq login" "t:none,setvar:tx.auth_attempt=+1"

skip

Skips one or more rules (or chains) on successful match. Internally ModSecurity v2 registers skip with the disruptive action type (chain starter only, not allowed in SecDefaultAction), although it never intercepts the transaction; a value below 1 is treated as 1.

Action groupFlow
ModSecurity v2supported
libModSecurity v3supported

Example:

# Require Accept header, but not from access from the localhost
SecRule REMOTE_ADDR "@rx ^127\.0\.0\.1$" "id:141,phase:1,skip:1"

# This rule will be skipped over when REMOTE_ADDR is 127.0.0.1
SecRule &REQUEST_HEADERS:Accept "@eq 0" \
    "id:142,\
    phase:1,\
    deny,\
    msg:'Request Missing an Accept Header'"

The skip action works only within the current processing phase and not necessarily in the order in which the rules appear in the configuration file. If you place a phase 2 rule after a phase 1 rule that uses skip, it will not skip over the phase 2 rule. It will skip over the next phase 1 rule that follows it in the phase.

In libModSecurity v3 skip:0 skips nothing, and the counter is not reset at the end of a phase: a count larger than the number of rules left in the phase carries over and skips the first rules of the next phase.

skipAfter

Action groupFlow
ModSecurity v2since 2.5.0
libModSecurity v3supported

Description: Skips one or more rules (or chains) on a successful match, resuming rule execution with the first rule that follows the rule (or marker created by SecMarker) with the provided ID. Internally ModSecurity v2 registers skipAfter with the disruptive action type (chain starter only, not allowed in SecDefaultAction), although it never intercepts the transaction.

Example: The following rules implement the same logic as the skip example, but using skipAfter:

# Require Accept header, but not from access from the localhost
SecRule REMOTE_ADDR "@rx ^127\.0\.0\.1$" \
    "id:143,\
    phase:1,\
    skipAfter:IGNORE_LOCALHOST"

# This rule will be skipped over when REMOTE_ADDR is 127.0.0.1
SecRule &REQUEST_HEADERS:Accept "@eq 0" \
    "id:144,\
    phase:1,\
    deny,\
    msg:'Request Missing an Accept Header'"
SecMarker IGNORE_LOCALHOST

Example from the OWASP ModSecurity CRS:

SecMarker BEGIN_HOST_CHECK

SecRule &REQUEST_HEADERS:Host "@eq 0" \
    "id:'960008',\
    phase:2,\
    block,\
    t:none,\
    msg:'Request Missing a Host Header',\
    tag:'PROTOCOL_VIOLATION/MISSING_HEADER_HOST',\
    tag:'WASCTC/WASC-21',\
    tag:'OWASP_TOP_10/A7',\
    tag:'PCI/6.5.10',\
    rev:'2.1.3',\
    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},\
    skipAfter:END_HOST_CHECK"

SecRule REQUEST_HEADERS:Host "@rx ^$" \
    "id:'960008',\
    phase:2,\
    block,\
    t:none,\
    msg:'Request Missing a Host Header',\
    tag:'PROTOCOL_VIOLATION/MISSING_HEADER_HOST',\
    tag:'WASCTC/WASC-21',\
    tag:'OWASP_TOP_10/A7',\
    tag:'PCI/6.5.10',\
    rev:'2.1.3',\
    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

The skipAfter action works only within the current processing phase and not necessarily the order in which the rules appear in the configuration file. If you place a phase 2 rule after a phase 1 rule that uses skipAfter, it will not skip over the phase 2 rule. It will skip over the next phase 1 rule that follows it in the phase.

libModSecurity v3 places every SecMarker in all phases and does not clear an active skipAfter at the end of a phase: if the marker is not reached in the current phase, the rules of the following phases are also skipped until it is.

status

Specifies the response status code to use with actions deny and redirect. ModSecurity v2 registers status as a disruptive-type action (chain starter only) although it only stores the code; the default is 403.

Action groupData
ModSecurity v2supported
libModSecurity v3supported

Example:

# Deny with status 403
SecDefaultAction "id:145,phase:1,deny,status:403,log"

Status actions defined in Apache scope locations (such as Directory, Location, etc…) may be superseded by phase:1 action settings. The Apache ErrorDocument directive will be triggered if present in the configuration. Therefore if you have previously defined a custom error page for a given status then it will be executed and its output presented to the user.

t

This action is used to specify the transformation pipeline to use to transform the value of each variable used in the rule before matching.

Action groupNon-disruptive
ModSecurity v2supported
libModSecurity v3supported

Example:

SecRule ARGS "@rx (asfunction|javascript|vbscript|data|mocha|livescript):" \
    "id:146,\
    t:none,\
    t:htmlEntityDecode,\
    t:lowercase,\
    t:removeNulls,\
    t:removeWhitespace"

Any transformation functions that you specify in a SecRule will be added to the previous ones specified in SecDefaultAction. It is recommended that you always use t:none in your rules, which prevents them depending on the default configuration. In ModSecurity v2 t:-name removes a previously added transformation from the pipeline; t is the only action that accepts the +/- prefix.

tag

Assigns a tag (category) to a rule or a chain.

Action groupMeta-data
ModSecurity v2since 2.1.0
libModSecurity v3supported

Example:

SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/* "@rx \bgetparentfolder\b" \
    "id:'958016',\
    phase:2,\
    block,\
    capture,\
    t:none,\
    t:htmlEntityDecode,\
    t:compressWhiteSpace,\
    t:lowercase,\
    msg:'Cross-site Scripting (XSS) Attack',\
    logdata:'% {TX.0}',\
    tag:'WEB_ATTACK/XSS',\
    tag:'WASCTC/WASC-8',\
    tag:'WASCTC/WASC-22',\
    tag:'OWASP_TOP_10/A2',\
    tag:'OWASP_AppSensor/IE1',\
    tag:'PCI/6.5.1',\
    ctl:auditLogParts=+E,\
    rev:'2.1.3',\
    severity:'2',\
    setvar:'tx.msg=%{rule.msg}',\
    setvar:tx.xss_score=+%{tx.critical_anomaly_score},\
    setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},\
    setvar:tx.%{rule.id}-WEB_ATTACK/XSS-%{matched_var_name}=%{tx.0}"

The tag information appears along with other rule metadata. The purpose of the tagging mechanism to allow easy automated categorization of events. Multiple tags can be specified on the same rule. Use forward slashes to create a hierarchy of categories (as in the example). Since ModSecurity 2.6.0 (and in all libModSecurity v3 releases) tag supports macro expansion.

ver

Specifies the rule set version. libModSecurity v3 requires the value to be single-quoted (ver:'CRS/2.2.4'); the unquoted form is a parse error.

Action groupMeta-data
ModSecurity v2since 2.7
libModSecurity v3supported

Example:

SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/* "@rx \bgetparentfolder\b" \
    "id:'958016',\
    phase:2,\
    block,\
    capture,\
    t:none,\
    t:htmlEntityDecode,\
    t:compressWhiteSpace,\
    t:lowercase,\
    msg:'Cross-site Scripting (XSS) Attack',\
    logdata:'% {TX.0}',\
    tag:'WEB_ATTACK/XSS',\
    tag:'WASCTC/WASC-8',\
    tag:'WASCTC/WASC-22',\
    tag:'OWASP_TOP_10/A2',\
    tag:'OWASP_AppSensor/IE1',\
    tag:'PCI/6.5.1',\
    ctl:auditLogParts=+E,\
    ver:'CRS/2.2.4',\
    severity:'2',\
    setvar:'tx.msg=%{rule.msg}',\
    setvar:tx.xss_score=+%{tx.critical_anomaly_score},\
    setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},\
    setvar:tx.%{rule.id}-WEB_ATTACK/XSS-%{matched_var_name}=%{tx.0}"

xmlns

Configures an XML namespace, which will be used in the execution of XPath expressions. The parameter has the form prefix=uri; several xmlns actions may be given on one rule. libModSecurity v3 requires the URI to start with http:// and to be unquoted or single-quoted (xmlns:soap='http://...').

Action groupData
ModSecurity v2supported
libModSecurity v3supported

Example:

SecRule REQUEST_HEADERS:Content-Type "@rx text/xml" \
    "id:147,\
    phase:1,\
    pass,\
    ctl:requestBodyProcessor=XML,\
    ctl:requestBodyAccess=On,\
    xmlns:xsd=" http://www.w3.org/2001/XMLSchema"
SecRule XML:/soap:Envelope/soap:Body/q1:getInput/id() "@rx 123" \
    "id:148,\
    phase:2,\
    deny"

Operators

This section documents the operators currently available in ModSecurity.

ModSecurity v2 and libModSecurity v3 both look operator names up case-insensitively (@ipmatch, @ipMatch and @IPMATCH all resolve to the same operator); the spellings below are the documented ones.

beginsWith

Returns true if the parameter string is found at the beginning of the input. Macro expansion is performed on the parameter string before comparison.

ModSecurity v2since 2.5.0
libModSecurity v3supported

Example:

# Detect request line that does not begin with "GET"
SecRule REQUEST_LINE "!@beginsWith GET" "id:149"

contains

Returns true if the parameter string is found anywhere in the input. Macro expansion is performed on the parameter string before comparison.

ModSecurity v2since 2.5.0
libModSecurity v3supported

Example:

# Detect ".php" anywhere in the request line
SecRule REQUEST_LINE "@contains .php" "id:150"

containsWord

Returns true if the parameter string (with word boundaries) is found anywhere in the input. Macro expansion is performed on the parameter string before comparison.

ModSecurity v2since 2.5.0
libModSecurity v3supported

Example:

# Detect "select" anywhere in ARGS
SecRule ARGS "@containsWord select" "id:151"

Would match on -
-1 union select BENCHMARK(2142500,MD5(CHAR(115,113,108,109,97,112))) FROM wp_users WHERE ID=1 and (ascii(substr(user_login,1,1))&0x01=0) from wp_users where ID=1–

But not on -
Your site has a wide selection of computers.

detectSQLi

Returns true if SQL injection payload is found. This operator uses LibInjection to detect SQLi attacks. ModSecurity v2 bundles libinjection 4 since 2.9.13. libModSecurity v3 bundles libinjection 4 (updated to v4.0.0 in 3.0.15); since 3.0.15 a libinjection parser error counts as a match, and with capture the libinjection fingerprint is stored in TX:0.

ModSecurity v2since 2.7.4
libModSecurity v3supported

Example:

# Detect SQL Injection inside request uri data"
SecRule REQUEST_URI "@detectSQLi" "id:152"
Note

This operator supports the “capture” action.

detectXSS

Returns true if XSS injection is found. This operator uses LibInjection to detect XSS attacks. ModSecurity v2 bundles libinjection 4 since 2.9.13. libModSecurity v3 bundles libinjection 4 (updated to v4.0.0 in 3.0.15); since 3.0.15 a libinjection parser error counts as a match, and with capture the matched input is stored in TX:0.

ModSecurity v2since 2.8.0
libModSecurity v3supported

Example:

# Detect XSS Injection inside request body
SecRule REQUEST_BODY "@detectXSS" "id:12345,deny,log"
Note

This operator supports the “capture” action.

endsWith

Returns true if the parameter string is found at the end of the input. Macro expansion is performed on the parameter string before comparison.

ModSecurity v2since 2.5.0
libModSecurity v3supported

Example:

# Detect request line that does not end with "HTTP/1.1"
SecRule REQUEST_LINE "!@endsWith HTTP/1.1" "id:152"

eq

Performs numerical comparison and returns true if the input value is equal to the provided parameter. Macro expansion is performed on the parameter string before comparison.

ModSecurity v2supported
libModSecurity v3supported

Example:

# Detect exactly 15 request headers
SecRule &REQUEST_HEADERS_NAMES "@eq 15" "id:153"
Note

If a value is provided that cannot be converted to an integer (i.e a string) this operator will treat that value as 0.

fuzzyHash

The fuzzyHash operator uses the ssdeep, which is a program for computing context triggered piecewise hashes (CTPH). Also called fuzzy hashes, CTPH can match inputs that have homologies. Such inputs have sequences of identical bytes in the same order, although bytes in between these sequences may be different in both content and length.

ModSecurity v2since 2.9.0
libModSecurity v3supported

The operator takes two parameters: the path of a file containing one ssdeep hash per line (a relative path is resolved against the directory of the configuration file) and a similarity threshold between 1 and 100; the operator matches when any hash scores at least the threshold. ModSecurity v2 must be built with ssdeep support, otherwise the operator fails at run time. libModSecurity v3 must be built with ssdeep support, otherwise the rule is rejected at configuration load; v3 does not check that the threshold lies between 1 and 100 and does not skip comment lines in the hash file.

For further information on ssdeep, visit its site: http://ssdeep.sourceforge.net/

Example:

SecRule REQUEST_BODY "@rx \@fuzzyHash /path/to/ssdeep/hashes.txt 6" \
    "id:192372,\
    deny,\
    log"

ge

Performs numerical comparison and returns true if the input value is greater than or equal to the provided parameter. Macro expansion is performed on the parameter string before comparison.

ModSecurity v2supported
libModSecurity v3supported

Example:

# Detect 15 or more request headers
SecRule &REQUEST_HEADERS_NAMES "@ge 15" "id:154"
Note

If a value is provided that cannot be converted to an integer (i.e a string) this operator will treat that value as 0.

geoLookup

Performs a geolocation lookup using the IP address in input against the geolocation database previously configured using SecGeoLookupDb. If the lookup is successful, the obtained information is captured in the GEO collection. ModSecurity v2 reads the legacy MaxMind GeoIP binary format (GeoIP/GeoLiteCity .dat) with its own parser. libModSecurity v3 reads the MaxMind DB format (GeoIP2/GeoLite2 .mmdb) through libmaxminddb (since 3.0.1), or the legacy .dat format through libGeoIP, depending on which library it was built with. With libmaxminddb v3 fills GEO:COUNTRY_CODE, COUNTRY_NAME, COUNTRY_CONTINENT (the continent name), CITY, POSTAL_CODE, LATITUDE and LONGITUDE; COUNTRY_CODE3, REGION, DMA_CODE and AREA_CODE are only filled by the libGeoIP build. A v3 build with neither library rejects any rule using @geoLookup at configuration load, and a lookup without a configured database does not match.

ModSecurity v2since 2.5.0
libModSecurity v3supported

Example: The geoLookup operator matches on success and is thus best used in combination with nolog,pass. If you wish to block on a failed lookup (which may be over the top, depending on how accurate the geolocation database is), the following example demonstrates how best to do it:

# Configure geolocation database
SecGeoLookupDb /path/to/GeoLiteCity.dat
...
# Lookup IP address
SecRule REMOTE_ADDR "@geoLookup" "id:155,phase:1,pass,nolog"

# Block IP address for which geolocation failed
SecRule &GEO "@eq 0" "id:156,phase:1,deny,msg:'Failed to lookup IP'"

See the GEO variable for an example and more information on various fields available.

gsbLookup

Performs a local lookup of Google’s Safe Browsing using URLs in input against the GSB database previously configured using SecGsbLookupDb. When combined with capture operator it will save the matched url into tx.0 variable.

SyntaxSecRule TARGET "@gsbLookup REGEX" ACTIONS
ModSecurity v2since 2.6.0
libModSecurity v3not supported (the parser rejects the rule with Operator: GsbLookup is not yet supported)

Example: The gsbLookup operator matches on success and is thus best used in combination with a block or redirect action. If you wish to block on successful lookups, the following example demonstrates how best to do it:

# Configure Google Safe Browsing database
SecGsbLookupDb /path/to/GsbMalware.dat
...
# Check response bodies for malicious links
SecRule RESPONSE_BODY "@gsbLookup =\"https?\:\/\/(.*?)\"" \
    "id:157,\
    phase:4,\
    block,\
    capture,\
    log,\
    msg:'Bad url detected in RESPONSE_BODY (Google Safe Browsing Check)',\
    logdata:'http://www.google.com/safebrowsing/diagnostic?site=%{tx.0}'"
Note

This operator supports the “capture” action.

gt

Performs numerical comparison and returns true if the input value is greater than the operator parameter. Macro expansion is performed on the parameter string before comparison.

ModSecurity v2supported
libModSecurity v3supported

Example:

# Detect more than 15 headers in a request
SecRule &REQUEST_HEADERS_NAMES "@gt 15" "id:158"
Note

If a value is provided that cannot be converted to an integer (i.e a string) this operator will treat that value as 0.

inspectFile

Executes an external program for every variable in the target list. The contents of the variable is provided to the script as the first parameter on the command line. The program must be specified as the first parameter to the operator. As of version 2.5.0, if the supplied program filename is not absolute, it is treated as relative to the directory in which the configuration file resides. Also as of version 2.5.0, if the filename is determined to be a Lua script (based on its .lua extension), the script will be processed by the internal Lua engine. Internally processed scripts will often run faster (there is no process creation overhead) and have full access to the transaction context of ModSecurity. libModSecurity v3 behaves the same way: a relative path is tried against the current working directory and then the configuration file directory, and .lua scripts are run by the built-in Lua engine when v3 was built with Lua support (since 3.0.4 the Lua script receives the FILES_TMPNAMES value as its argument, as in v2); without Lua support a .lua file is executed as an external program.

ModSecurity v2supported
libModSecurity v3supported

The @inspectFile operator was initially designed for file inspection (hence the name), but it can also be used in any situation that requires decision making using external logic.

An external program must print one line: output starting with 1 means the file is accepted (no match), anything else is treated as a rejection and the operator matches (the output is logged as the reason). A Lua script matches when its main function returns a string and does not match when it returns nil. In libModSecurity v3 the program must exit with status 0 and print at least two characters for a match to be possible, the output is not logged, and a Lua script matches only when main returns a non-empty string.

The OWASP CRS includes a utility script in the /util directory called runav.pl (util/av-scanning/runav.pl in CRS 3.3; CRS 4 no longer ships it) that allows the file approval mechanism to integrate with the ClamAV virus scanner. This is especially handy to prevent viruses and exploits from entering the web server through file upload.

#!/usr/bin/perl
#
# runav.pl
# Copyright (c) 2004-2011 Trustwave
#
# This script is an interface between ModSecurity and its
# ability to intercept files being uploaded through the
# web server, and ClamAV

$CLAMSCAN = "clamscan";

if ($#ARGV != 0) {
    print "Usage: runav.pl <filename>\n";
    exit;
}

my ($FILE) = shift @ARGV;

$cmd = "$CLAMSCAN --stdout --no-summary $FILE";
$input = `$cmd`;
$input =~ m/^(.+)/;
$error_message = $1;

$output = "0 Unable to parse clamscan output [$1]";

if ($error_message =~ m/: Empty file\.?$/) {
    $output = "1 empty file";
}
elsif ($error_message =~ m/: (.+) ERROR$/) {
    $output = "0 clamscan: $1";
}
elsif ($error_message =~ m/: (.+) FOUND$/) {
    $output = "0 clamscan: $1";
}
elsif ($error_message =~ m/: OK$/) {
    $output = "1 clamscan: OK";
}

print "$output\n";

Example: Using the runav.pl script:

# Execute external program to validate uploaded files
SecRule FILES_TMPNAMES "@inspectFile /path/to/util/runav.pl" "id:159"

Example of using Lua script (placed in the same directory as the configuration file):

SecRule FILES_TMPNAMES "@inspectFile inspect.lua" "id:160"

The contents of inspect.lua:

function main(filename)
    -- Do something to the file to verify it. In this example, we
    -- read up to 10 characters from the beginning of the file.
    local f = io.open(filename, "rb");
    local d = f:read(10);
    f:close();
   
    -- Return null if there is no reason to believe there is anything
    -- wrong with the file (no match). Returning any text will be taken
    -- to mean a match should be triggered.
    return null;
end
Note

Starting in version 2.9 ModSecurity will not fill the FILES_TMPNAMES variable unless SecTmpSaveUploadedFiles directive is On, or the SecUploadKeepFiles directive is set to RelevantOnly. libModSecurity v3 fills FILES_TMPNAMES when SecTmpSaveUploadedFiles or SecUploadKeepFiles is On (the v3 parser rejects SecUploadKeepFiles RelevantOnly).

Note

Use @inspectFile with caution. It may not be safe to use @inspectFile with variables other than FILES_TMPNAMES. Other variables such as “FULL_REQUEST” may contains content that force your platform to fork process out of your control, making possible to an attacker to execute code using the same permissions of your web server. For other variables you may want to look at the Lua script engine. This observation was brought to our attention by “Gryzli”, on our users mailing list.

Reference: http://blog.spiderlabs.com/2010/10/advanced-topic-of-the-week-preventing-malicious-pdf-file-uploads.html

Reference: http://sourceforge.net/p/mod-security/mailman/mod-security-users/?viewmonth=201512

ipMatch

Performs a fast ipv4 or ipv6 match of REMOTE_ADDR variable data. Can handle the following formats:

ModSecurity v2since 2.6.0
libModSecurity v3supported
  • Full IPv4 Address - 192.168.1.100
  • Network Block/CIDR Address - 192.168.1.0/24
  • Full IPv6 Address - 2001:db8:85a3:8d3:1319:8a2e:370:7348
  • Network Block/CIDR Address - 2001:db8:85a3:8d3:1319:8a2e:370:0/24

Examples:

Individual Address:

SecRule REMOTE_ADDR "@ipMatch 192.168.1.100" "id:161"

Multiple Addresses w/network block:

SecRule REMOTE_ADDR "@ipMatch 192.168.1.100,192.168.1.50,10.10.50.0/24" "id:162"

ipMatchF

ModSecurity v2since 2.7.0
libModSecurity v3supported

short alias for ipMatchFromFile

ipMatchFromFile

Performs a fast ipv4 or ipv6 match of REMOTE_ADDR variable, loading data from a file. Can handle the following formats:

ModSecurity v2since 2.7.0
libModSecurity v3supported
  • Full IPv4 Address - 192.168.1.100
  • Network Block/CIDR Address - 192.168.1.0/24
  • Full IPv6 Address - 2001:db8:85a3:8d3:1319:8a2e:370:7348
  • Network Block/CIDR Address - 2001:db8:85a3:8d3:1319:8a2e:370:0/24

Examples:

SecRule REMOTE_ADDR "@ipMatchFromFile ips.txt" "id:163"

The file ips.txt may contain:

192.168.0.1
172.16.0.0/16
10.0.0.0/8
Note

As of v2.9.0-RC1 this operator also supports to load content served by an HTTPS server (https:// URL instead of a path). libModSecurity v3 supports this in all releases when built with libcurl.

Note

When used with content served by a HTTPS server, the directive SecRemoteRulesFailAction can be used to configure a warning instead of an abort, when the remote content could not be retrieved. This applies to ModSecurity v2 only: in libModSecurity v3 a failed download rejects the rule at configuration load regardless of SecRemoteRulesFailAction.

Note

Empty lines are ignored. Comment lines (beginning with the # character) are ignored by ModSecurity v2 and by libModSecurity v3 since 3.0.9; v3 also strips a trailing # comment from a line, and tries a relative file name against the current working directory before the directory of the rules file.

le

Performs numerical comparison and returns true if the input value is less than or equal to the operator parameter. Macro expansion is performed on the parameter string before comparison.

ModSecurity v2supported
libModSecurity v3supported

Example:

# Detect 15 or fewer headers in a request
SecRule &REQUEST_HEADERS_NAMES "@le 15" "id:164"
Note

If a value is provided that cannot be converted to an integer (i.e a string) this operator will treat that value as 0.

lt

Performs numerical comparison and returns true if the input value is less than to the operator parameter. Macro expansion is performed on the parameter string before comparison.

ModSecurity v2supported
libModSecurity v3supported

Example:

# Detect fewer than 15 headers in a request
SecRule &REQUEST_HEADERS_NAMES "@lt 15" "id:165"
Note

If a value is provided that cannot be converted to an integer (i.e a string) this operator will treat that value as 0.

noMatch

Will force the rule to always return false.

ModSecurity v2supported
libModSecurity v3supported

pm

Performs a case-insensitive match of the provided phrases against the desired input value. The operator uses a set-based matching algorithm (Aho-Corasick), which means that it will match any number of keywords in parallel. When matching of a large number of keywords is needed, this operator performs much better than a regular expression.

ModSecurity v2since 2.5.0
libModSecurity v3supported

Example:

# Detect suspicious client by looking at the user agent identification
SecRule REQUEST_HEADERS:User-Agent "@pm WebZIP WebCopier Webster WebStripper ... SiteSnagger ProWebWalker CheeseBot" \
    "id:166"
Note

Starting on ModSecurity v2.6.0 this operator supports a snort/suricata content style. ie: “@pm A|42|C|44|F”.

Note

This operator does not support macro expansion (as of ModSecurity v2.9.1; neither does libModSecurity v3).

Note

This operator supports the “capture” action.

pmf

ModSecurity v2supported
libModSecurity v3supported

Short alias for pmFromFile.

pmFromFile

Performs a case-insensitive match of the provided phrases against the desired input value. The operator uses a set-based matching algorithm (Aho-Corasick), which means that it will match any number of keywords in parallel. When matching of a large number of keywords is needed, this operator performs much better than a regular expression.

ModSecurity v2since 2.5.0
libModSecurity v3supported

This operator is the same as @pm, except that it takes a list of files as arguments. It will match any one of the phrases listed in the file(s) anywhere in the target value.

Example:

# Detect suspicious user agents using the keywords in
# the files /path/to/blacklist1 and blacklist2 (the latter
# must be placed in the same folder as the configuration file)
SecRule REQUEST_HEADERS:User-Agent "@pmFromFile /path/to/blacklist1 blacklist2" \
    "id:167"

Notes:

  1. Files must contain exactly one phrase per line. End of line markers (both LF and CRLF) will be stripped from each phrase and any whitespace trimmed from both the beginning and the end. Empty lines and comment lines (those beginning with the # character) will be ignored.
  2. To allow easier inclusion of phrase files with rule sets, relative paths may be used to the phrase files. In this case, the path of the file containing the rule is prepended to the phrase file path.
  3. The @pm operator phrases do not support metacharacters.
  4. Because this operator does not check for boundaries when matching, false positives are possible in some cases. For example, if you want to use @pm for IP address matching, the phrase 1.2.3.4 will potentially match more than one IP address (e.g., it will also match 1.2.3.40 or 1.2.3.41). To avoid the false positives, you can use your own boundaries in phrases. For example, use /1.2.3.4/ instead of just 1.2.3.4. Then, in your rules, also add the boundaries where appropriate. You will find a complete example in the example.
# Prepare custom REMOTE_ADDR variable
SecAction "id:168,phase:1,pass,nolog,setvar:tx.REMOTE_ADDR=/%{REMOTE_ADDR}/"

# Check if REMOTE_ADDR is blacklisted
SecRule TX:REMOTE_ADDR "@pmFromFile blacklist.txt" \
    "id:169,\
    phase:1,\
    deny,\
    msg:'Blacklisted IP address'"

The file blacklist.txt may contain:

# ip-blacklist.txt contents:
# NOTE: All IPs must be prefixed/suffixed with "/" as the rules
#   will add in this character as a boundary to ensure
#   the entire IP is matched.
# SecAction "phase:1,id:170,pass,nolog,setvar:tx.remote_addr='/%{REMOTE_ADDR}/'"
/1.2.3.4/ 
/5.6.7.8/
Warning

Before ModSecurity 2.5.12, the @pmFromFile operator understood only the LF line endings and did not trim the whitespace from phrases. If you are using an older version of ModSecurity, you should take care when editing the phrase files to avoid using the undesired characters in patterns.e files should be one phrase per line. End of line markers will be stripped from the phrases (LF and CRLF), and whitespace is trimmed from both sides of the phrases. Empty lines and comment lines (beginning with a ‘#’) are ignored. To allow easier inclusion of phrase files with rulesets, relative paths may be used to the phrase files. In this case, the path of the file containing the rule is prepended to the phrase file path.

Note

Starting on ModSecurity v2.6.0 this operator supports a snort/suricata content style. ie: “A|42|C|44|F”.

Note

As of v2.9.0-RC1 this operator also supports to load content served by an HTTPS server. However, only one url can be used at a time.

Note

libModSecurity v3 differences: phrases are read verbatim (no whitespace trimming, so a CRLF file leaves a trailing carriage return in every phrase), the |hex| notation is not interpreted inside phrase files, a relative file name is tried against the current working directory before the rules file directory, every argument may be an https:// URL (libcurl build), and a file or URL that cannot be read rejects the rule at configuration load regardless of SecRemoteRulesFailAction. Empty lines and # comment lines are skipped since 3.0.4.

rbl

Looks up the input value in the RBL (real-time block list) given as parameter. The input value can be an IPv4 address or a hostname; IPv6 addresses are not supported.

ModSecurity v2supported
libModSecurity v3supported

Example:

SecRule REMOTE_ADDR "@rbl sbl-xbl.spamhaus.org" \
    "id:171,\
    phase:1,\
    pass,\
    t:none,\
    nolog,\
    auditlog,\
    msg:'RBL Match for SPAM Source',\
    tag:'AUTOMATION/MALICIOUS',\
    severity:'2',\
    setvar:'tx.msg=%{rule.msg}',\
    setvar:tx.automation_score=+%{tx.warning_anomaly_score},\
    setvar:tx.anomaly_score=+%{tx.warning_anomaly_score},\
    setvar:tx.%{rule.id}-AUTOMATION/MALICIOUS-%{matched_var_name}=%{matched_var},\
    setvar:ip.spammer=1,\
    setvar:ip.previous_rbl_check=1,\
    expirevar:ip.spammer=86400,\
    expirevar:ip.previous_rbl_check=86400,\
    skipAfter:END_RBL_CHECK"
Note

If the RBL used is dnsbl.httpbl.org (Honeypot Project RBL) then the SecHttpBlKey directive must specify the user’s registered API key.

Note

If the RBL used is either multi.uribl.com or zen.spamhaus.org combined RBLs, it is possible to also parse the return codes in the last octet of the DNS response to identify which specific RBL the IP was found in. libModSecurity v3 recognizes the provider by the substrings httpbl.org, uribl.com and spamhaus.org in the parameter and writes the decoded reason to the debug log only.

Note

This operator supports the “capture” action.

rsub

Performs regular expression data substitution when applied to either the STREAM_INPUT_BODY or STREAM_OUTPUT_BODY variables. This operator also supports macro expansion. Starting with ModSecurity 2.7.0 this operator supports the syntax |hex| allowing users to use special chars like \n \r

Syntax@rsub s/regex/str/[id]
ModSecurity v2since 2.6.0
libModSecurity v3not supported (the parser rejects the rule with Operator: Rsub is not yet supported; the STREAM_* variables do not exist in v3 either)

Examples: Removing HTML Comments from response bodies:

SecStreamOutBodyInspection On
SecRule STREAM_OUTPUT_BODY "@rsub s/<!--.*?-->/ /" \
    "id:172,\
    phase:4,\
    pass,\
    t:none,\
    nolog"
Note

If you plan to manipulate live data by using @rsub with the STREAM_ variables, you must also enable SecContentInjection directive.

Unlike @rx, the regular expression is compiled through Apache’s ap_regex API as a POSIX extended regular expression (no DOTALL or DOLLAR_ENDONLY settings). The optional flags after the last delimiter are i (case-insensitive match) and d (escape the regex metacharacters of the expanded macros when the pattern contains %{...}); any other flag is an error. The replacement string may reference the subexpressions of the match with \1 to \9. Patterns containing macros are expanded and compiled on every evaluation.

rx

Performs a regular expression match of the pattern provided as parameter. This is the default operator; the rules that do not explicitly specify an operator default to @rx. ModSecurity v2 builds against PCRE2 by default since 2.9.9 (PCRE2 is supported since 2.9.7; PCRE is used only when --with-pcre is given at build time); libModSecurity v3 uses PCRE2 (since 3.0.7, with PCRE only when explicitly requested at build time).

ModSecurity v2supported
libModSecurity v3supported

Examples:

# Detect Nikto
SecRule REQUEST_HEADERS:User-Agent "@rx nikto" "id:173,phase:1,t:lowercase"

# Detect Nikto with a case-insensitive pattern
SecRule REQUEST_HEADERS:User-Agent "@rx (?i)nikto" "id:174,phase:1,t:none"

# Detect Nikto with a case-insensitive pattern
SecRule REQUEST_HEADERS:User-Agent "@rx (?i)nikto" "id:175"

Regular expressions are handled by the PCRE library 1. ModSecurity compiles its regular expressions with the following settings:

  1. The entire input is treated as a single line, even when there are newline characters present.
  2. All matches are case-sensitive. If you wish to perform case-insensitive matching, you can either use the lowercase transformation function or force case-insensitive matching by prefixing the regular expression pattern with the (?i) modifier (a PCRE feature; you will find many similar features in the PCRE documentation).
  3. The PCRE_DOTALL and PCRE_DOLLAR_ENDONLY flags are set during compilation, meaning that a single dot will match any character, including the newlines, and a $ end anchor will not match a trailing newline character.

Regular expressions are a very powerful tool. You are strongly advised to read the PCRE documentation to get acquainted with its features.

Macro expansion is supported since ModSecurity 2.6.2: a pattern containing %{...} is expanded and compiled on every evaluation instead of once at startup.

Note

libModSecurity v3 compiles patterns with PCRE2_DOTALL and PCRE2_MULTILINE instead, so ^ and $ also match at inner line boundaries. Rules that need line anchors should write (?m) explicitly to behave the same in both versions. In v3 a pattern that is invalid at load time rejects the rule, a pattern that becomes invalid after macro expansion does not match and sets MSC_PCRE_ERROR, and an empty pattern matches everything. SecPcreMatchLimit is honored since 3.0.10: when the limit is exceeded the operator does not match and MSC_PCRE_LIMITS_EXCEEDED and TX:MSC_PCRE_LIMITS_EXCEEDED are set to 1.

Note

This operator supports the “capture” action. ModSecurity v2 stores the whole match in TX:0 and up to nine subexpressions in TX:1 to TX:9; further subexpressions are not captured. libModSecurity v3 stores every subexpression of the pattern.

rxGlobal

Performs a global regular expression match of the pattern provided as parameter. This emulates standard regular expression ‘/g’ functionality, which means that, after a regular expression has been fully matched in a string, the operator will continue searching the string for additional matches of the pattern. This global matching is only useful if the additional captures are desired.

ModSecurity v2not supported
libModSecurity v3since 3.0.5

Example:

# From a query argument 'aaa12bbb45ccc', both '12' and '45' will be returned as captures
SecRule ARGS_GET "@rxGlobal [0-9]+" "id:174,phase:1,capture"

This operator is more expensive than @rx. Users are advised to use @rxGlobal only when the full captures are needed and prefer @rx in other cases. @rxGlobal exists only in libModSecurity v3 (added in 3.0.5); ModSecurity v2 has no equivalent.

streq

Performs a string comparison and returns true if the parameter string is identical to the input string. Macro expansion is performed on the parameter string before comparison.

ModSecurity v2since 2.5.0
libModSecurity v3supported

Example:

# Detect request parameters "foo" that do not # contain "bar", exactly.
SecRule ARGS:foo "!@streq bar" "id:176"

strmatch

Performs a string match of the provided word against the desired input value. In ModSecurity v2 the operator uses the pattern matching Boyer-Moore-Horspool algorithm, which means that it is a single pattern matching operator. This operator performs much better than a regular expression. In libModSecurity v3 the implementation is a plain substring search, comparable to the contains operator, with macro expansion performed on the parameter.

ModSecurity v2supported
libModSecurity v3supported

Example:

# Detect suspicious client by looking at the user agent identification
SecRule REQUEST_HEADERS:User-Agent "@strmatch WebZIP" "id:177"
Note

Starting on ModSecurity v2.6.0 this operator supports a snort/suricata content style. ie: “@strmatch A|42|C|44|F”. libModSecurity v3 does not parse this notation for @strmatch (it does for @pm).

unconditionalMatch

Will force the rule to always return true. This is similar to SecAction however all actions that occur as a result of a rule matching will fire such as the setting of MATCHED_VAR. This can also be part a chained rule.

ModSecurity v2supported
libModSecurity v3supported

Example:

SecRule REMOTE_ADDR "@unconditionalMatch" \
    "id:1000,\
    phase:1,\
    pass,\
    t:hexEncode,\
    nolog,\
    setvar:TX.ip_hash=%{MATCHED_VAR}"

validateByteRange

Validates that the byte values used in input fall into the range specified by the operator parameter. This operator matches on an input value that contains bytes that are not in the specified range.

ModSecurity v2supported
libModSecurity v3supported

Example:

# Enforce very strict byte range for request parameters (only
# works for the applications that do not use the languages other
# than English).
SecRule ARGS "@validateByteRange 10, 13, 32-126" "id:178"

The validateByteRange is most useful when used to detect the presence of NUL bytes, which don’t have a legitimate use, but which are often used as an evasion technique.

# Do not allow NUL bytes
SecRule ARGS "@validateByteRange 1-255" "id:179"
Note

You can force requests to consist only of bytes from a certain byte range. This can be useful to avoid stack overflow attacks (since they usually contain “random” binary content). The parameter is mandatory: a comma-separated list of byte values and start-end ranges, each between 0 and 255; whitespace around the values is tolerated by atoi() and anything not listed is reported as outside the range. libModSecurity v3 (since 3.0.14) rejects the rule at configuration load when a value is outside 0 to 255 or a range start is greater than its end.

validateByteRange is similar to the ModSecurity 1.X SecFilterForceByteRange Directive however since it works in a rule context, it has the following differences:

  • You can specify a different range for different variables.
  • It has an “event” context (id, msg….)
  • It is executed in the flow of rules rather than being a built in pre-check.

validateDTD

Validates the XML DOM tree against the supplied DTD. The DOM tree must have been built previously using the XML request body processor. This operator matches when the validation fails. libModSecurity v3 requires a build with libxml2 (otherwise the operator is accepted but always matches), resolves the DTD path at configuration load, and also matches when no XML tree was built or the document is not well formed.

ModSecurity v2supported
libModSecurity v3supported

Example:

# Parse the request bodies that contain XML
SecRule REQUEST_HEADERS:Content-Type "@rx ^text/xml$" \
    "id:180,\
    phase:1,\
    pass,\
    t:lowercase,\
    nolog,\
    ctl:requestBodyProcessor=XML"

# Validate XML payload against DTD
SecRule XML "@validateDTD /path/to/xml.dtd" \
    "id:181,\
    phase:2,\
    deny,\
    msg:'Failed DTD validation'"

NOTE: You must enable the SecXmlExternalEntity directive.

validateHash

Validates REQUEST_URI that contains data protected by the hash engine. Added in ModSecurity 2.7.0 as @validateEncryption and renamed to @validateHash in 2.7.1.

ModSecurity v2since 2.7.1
libModSecurity v3not supported (the parser rejects the rule with Operator: ValidateHash is not yet supported; the hash engine does not exist in v3)

Example:

# Validates requested URI that matches a regular expression.
SecRule REQUEST_URI "@validateHash product_info|product_list" \
    "id:123456,\
    phase:1,\
    deny"

validateSchema

Validates the XML DOM tree against the supplied XML Schema. The DOM tree must have been built previously using the XML request body processor. This operator matches when the validation fails. libModSecurity v3 requires a build with libxml2 (otherwise the operator is accepted but always matches), resolves the schema path at configuration load, and also matches when no XML tree was built or the document is not well formed.

ModSecurity v2supported
libModSecurity v3supported

Example:

# Parse the request bodies that contain XML
SecRule REQUEST_HEADERS:Content-Type "@rx ^text/xml$" \
    "id:190,\
    phase:1,\
    pass,\
    t:lowercase,\
    nolog,\
    ctl:requestBodyProcessor=XML"

# Validate XML payload against DTD
SecRule XML "@validateSchema /path/to/xml.xsd" \
    "id:191,\
    phase:2,\
    deny,\
    msg:'Failed DTD validation'"

NOTE: You must enable the SecXmlExternalEntity directive.

validateUrlEncoding

Validates the URL-encoded characters in the provided input string.

ModSecurity v2supported
libModSecurity v3supported

Example:

# Validate URL-encoded characters in the request URI
SecRule REQUEST_URI_RAW "@validateUrlEncoding" "id:192"

ModSecurity will automatically decode the URL-encoded characters in request parameters, which means that there is little sense in applying the @validateUrlEncoding operator to them —that is, unless you know that some of the request parameters were URL-encoded more than once. Use this operator against raw input, or against the input that you know is URL-encoded. For example, some applications will URL-encode cookies, although that’s not in the standard. Because it is not in the standard, ModSecurity will neither validate nor decode such encodings.

validateUtf8Encoding

Check whether the input is a valid UTF-8 string.

ModSecurity v2supported
libModSecurity v3supported

Example:

# Make sure all request parameters contain only valid UTF-8
SecRule ARGS "@validateUtf8Encoding" "id:193"

The @validateUtf8Encoding operator detects the following problems:

  • Not enough bytes: ModSecurity accepts one- to four-byte encodings (RFC 3629; a lead byte announcing a five- or six-byte sequence is reported as an invalid character). ModSecurity will locate cases when one or more bytes is/are missing from a character.

  • Invalid characters: The two most significant bits in most characters should be fixed to 0x80. Some attack techniques use different values as an evasion technique.

  • Overlong characters: ASCII characters are mapped directly into UTF-8, which means that an ASCII character is one UTF-8 character at the same time. However, in UTF-8 many ASCII characters can also be encoded with two, three, four, five, and six bytes. This is no longer legal in the newer versions of Unicode, but many older implementations still support it. The use of overlong UTF-8 characters is common for evasion.

  • Restricted characters: code points above U+10FFFF (lead byte 0xF5 or higher) and the UTF-16 surrogate range U+D800 to U+DFFF.

  • Most, but not all applications use UTF-8. If you are dealing with an application that does, validating that all request parameters are valid UTF-8 strings is a great way to prevent a number of evasion techniques that use the assorted UTF-8 weaknesses. False positives are likely if you use this operator in an application that does not use UTF-8.

  • Many web servers will also allow UTF-8 in request URIs. If yours does, you can verify the request URI using @validateUtf8Encoding.

verifyCC

Detects credit card numbers in input. This operator will first use the supplied regular expression to perform an initial match, following up with the Luhn algorithm calculation to minimize false positives.

ModSecurity v2supported
libModSecurity v3supported

Example:

# Detect credit card numbers in parameters and
# prevent them from being logged to audit log
SecRule ARGS "@verifyCC \d{13,16}" \
    "id:194,\
    phase:2,\
    pass,\
    nolog,\
    msg:'Potential credit card number',\
    sanitiseMatched"
Note

This operator supports the “capture” action.

verifyCPF

Detects CPF numbers (Brazilian social number) in input. This operator will first use the supplied regular expression to perform an initial match, following up with an algorithm calculation to minimize false positives.

ModSecurity v2since 2.6.0
libModSecurity v3supported

Example:

# Detect CPF numbers in parameters and
# prevent them from being logged to audit log
SecRule ARGS "@verifyCPF /^([0-9]{3}\.){2}[0-9]{3}-[0-9]{2}$/" \
    "id:195,\
    phase:2,\
    pass,\
    nolog,\
    msg:'Potential CPF number',\
    sanitiseMatched"
Note

This operator supports the “capture” action.

verifySSN

Detects US social security numbers (SSN) in input. This operator will first use the supplied regular expression to perform an initial match, following up with an SSN algorithm calculation to minimize false positives.

ModSecurity v2since 2.6.0
libModSecurity v3supported

Example:

# Detect social security numbers in parameters and
# prevent them from being logged to audit log
SecRule ARGS "@verifySSN \d{3}-?\d{2}-?\d{4}" \
    "id:196,\
    phase:2,\
    pass,\
    nolog,\
    msg:'Potential social security number',\
    sanitiseMatched"

SSN Format:

A Social Security number is broken up into 3 sections:

  • Area (3 digits)
  • Group (2 digits)
  • Serial (4 digits)

verifySSN checks:

  • Must have 9 digits
  • Cannot be a sequence number (ie,, 123456789, 012345678)
  • Cannot be a repetition sequence number ( ie 11111111 , 222222222)
  • Cannot have area and/or group and/or serial zeroed sequences
  • Area code must be less than 740
  • Area code must be different then 666
Note

This operator supports the “capture” action.

verifySVNR

Detects Austrian social insurance numbers (Sozialversicherungsnummer, SVNR) in input. This operator will first use the supplied regular expression to perform an initial match, following up with the SVNR check digit calculation to minimize false positives.

ModSecurity v2not supported
libModSecurity v3since 3.0.4

Example:

# Detect Austrian social insurance numbers in parameters and
# prevent them from being logged to audit log
SecRule ARGS "@verifySVNR \d{4}\s?\d{6}" \
    "id:198,\
    phase:2,\
    pass,\
    nolog,\
    msg:'Potential SVNR number',\
    sanitiseMatched"

verifySVNR checks:

  • Must have 10 digits (a 4 digit serial number including the check digit, followed by the 6 digit date of birth DDMMYY); other characters are skipped
  • Cannot be a sequence number (ie, 0123456789, 1234567890) or a repetition sequence number (ie 1111111111)
  • The fourth digit must equal the weighted sum of the other digits modulo 11 (weights 3, 7, 9 for the serial number and 5, 8, 4, 2, 1, 6 for the date of birth; a result of 10 counts as 0)

This operator exists only in libModSecurity v3 (added in 3.0.4); ModSecurity v2 has no equivalent.

Note

This operator supports the “capture” action.

within

Returns true if the input value (the needle) is found anywhere within the @within parameter (the haystack). Macro expansion is performed on the parameter string before comparison.

ModSecurity v2since 2.5.0
libModSecurity v3supported

Example:

# Detect request methods other than GET, POST and HEAD
SecRule REQUEST_METHOD "!@within GET,POST,HEAD"
Note

There are no delimiters for this operator, it is therefore often necessary to artificially impose some; this can be done using setvar. For instance in the example below, without the imposed delimiters (of ‘/’) this rule would also match on the ‘range’ header (along with many other combinations), since ‘range’ is within the provided parameter. With the imposed delimiters, the rule would check for ‘/range/’ when the range header is provided, and therefore would not match since ‘/range/ is not part of the @within parameter.

SecRule REQUEST_HEADERS_NAMES "@rx ^.*$" \
    "id:1,\
    block,\
    t:lowercase,\
    setvar:'tx.header_name=/%{tx.0}/',\
    chain"
    SecRule TX:header_name "@within /proxy/ /lock-token/ /content-range/ /translate/ /if/" \
        "t:none"

Macro Expansion

Macros allow for using placeholders in rules that will be expanded out to their values at runtime. Only variable expansion is supported; the syntax is the same in ModSecurity v2 and libModSecurity v3.

Format:

%{VARIABLE}
%{COLLECTION.VARIABLE}

Macro expansion can be used in actions such as initcol, setsid, setuid, setvar, setenv, logdata and msg. Operators that are evaluated at runtime support expansion in their parameter; the entries in Operators note where this applies. Such operators include @beginsWith, @endsWith, @contains, @within, @streq, @eq, @ge, @gt, @le and @lt. You can use macro expansion in operators that are “compiled” at load time, such as @rx, but the pattern is then recompiled on every evaluation, which has an impact on efficiency.

Some values you may want to expand include: TX, REMOTE_ADDR, USERID, HIGHEST_SEVERITY, MATCHED_VAR, MATCHED_VAR_NAME, MULTIPART_STRICT_ERROR, RULE, SESSION and SESSIONID, among others.

Persistent Storage

Five collections can hold data persistently, that is, data available to multiple requests: GLOBAL, RESOURCE, IP, SESSION and USER. They are available in both ModSecurity v2 and libModSecurity v3, but the storage behind them differs (see below).

Every collection contains several built-in variables that are available and are read-only unless otherwise specified:

  1. CREATE_TIME - date/time of the creation of the collection.
  2. IS_NEW - set to 1 if the collection is new (not yet persisted) otherwise set to 0.
  3. KEY - the value of the initcol variable (the client’s IP address in the example).
  4. LAST_UPDATE_TIME - date/time of the last update to the collection.
  5. TIMEOUT - date/time in seconds when the collection will be updated on disk from memory (if no other updates occur). This variable may be set if you wish to specify an explicit expiration time (default is 3600 seconds, configurable with SecCollectionTimeout). The TIMEOUT is updated every time that the values of an entry is changed.
  6. UPDATE_COUNTER - how many times the collection has been updated since creation.
  7. UPDATE_RATE - is the average rate updates per minute since creation.

To create a collection to hold session variables (SESSION) use action setsid. To create a collection to hold user variables (USER) use action setuid. To create a collection to hold client address variables (IP), global data or resource-specific data, use action initcol.

Note

Persistent collections can only be initialized once per transaction.

Note

ModSecurity implements atomic updates of persistent variables only for integer variables (counters) at this time. Variables are read from storage whenever initcol is encountered in the rules and persisted at the end of request processing. Counters are adjusted by applying a delta generated by re-reading the persisted data just before being persisted. This keeps counter data consistent even if the counter was modified and persisted by another thread/process during the transaction.

Storage backends

ModSecurity v2

ModSecurity v2 stores each collection in an SDBM database file (APR’s apr_sdbm) in the directory set by SecDataDir; the directory must be writable by the web server user. SDBM is limited to storing a maximum of 1008 bytes per key, which may be a limitation if you are attempting to store a considerable amount of data in variables for a single key. The files are shared by all Apache worker processes on the host.

libModSecurity v3

libModSecurity v3 keeps the collections in memory, per process by default (src/collection/backend/in_memory-per_process.cc). The data does not survive a restart and is not shared between worker processes, so with NGINX each worker sees its own copy of IP, GLOBAL and the other collections. SecDataDir is accepted by the parser for compatibility with modsecurity.conf-recommended but has no effect.

If the library is built with --with-lmdb, the collections are stored in an LMDB database instead, which is shared by all processes on the host. The database file is modsec-shared-collections in the working directory of the process (the path is fixed by the backend; SecDataDir is not consulted). LMDB has, by default, a maximum key length of 511 bytes.

Warning

In libModSecurity v3, setvar actions in a rule are executed before initcol in the same rule, so a variable written by the rule that initializes a collection is lost when the collection did not exist yet. Initialize the collection in one rule and write to it in a later rule.

Miscellaneous Topics

The topics on this page apply to ModSecurity v2 running as an Apache module. libModSecurity v3 has no Apache dependency; the equivalent integration points belong to the connector (for example the modsecurity_transaction_id directive of ModSecurity-nginx, which ties the audit log entry to the NGINX access log).

Logging in Apache via mod_log_config

ModSecurity v2 registers the M log handler with mod_log_config, so any ModSecurity variable can be written to the Apache access log as %{VARIABLE}M. A collection member is addressed with a dot, as in %{TX.ANOMALY_SCORE}M; the colon form used in rules is not accepted there. ModSecurity asks Apache to run its logging hook before mod_log_config, so the access log entry is written after phase 5 has run and the audit log record has been written, and every variable set during the transaction is available to it.

Example Apache mod_log_config:

LogFormat "%t %{UNIQUE_ID}e %{MULTIPART_STRICT_ERROR}M %{TX.ANOMALY_SCORE}M" custom-format

Precedence of ModSecurity over other Apache modules

ModSecurity rules run in one of five phases. Phase 1 runs once the request headers have been read and Apache has mapped the request, phase 2 after ModSecurity has read the request body, phases 3 and 4 in an output filter while the response is being generated, and phase 5 in Apache’s logging hook after the response has been sent, before the access log entry is written.

The various phases are hooked into the Apache request lifecycle together with the other Apache modules. On each hook, there can be more than one module being executed. This is where precedence comes into play.

Precedence is assigned at compile time and hard-coded into the ModSecurity source code. Phase 1 runs in the fixups hook by default, ahead of mod_env, and the compile-time option --enable-request-early moves it to the post-read-request hook (see Processing Phases). ModSecurity’s startup runs after mod_unique_id and mod_ssl, and its logging hook runs before mod_log_config.

When examining the response, ModSecurity tries to be as early as possible: its output filter is registered ahead of the content-set filters of mod_headers, mod_deflate, mod_cache and mod_expires, so phases 3 and 4 see the response before mod_headers applies its Header directive, before compression and before caching. However, when calling Header with the keyword early, the precedence is raised and the directive is executed before ModSecurity phase 3. So if you want to edit HTTP response headers with mod_headers (adding the secure-flag to cookies springs to mind), you will usually have to wait until ModSecurity phase 5, before you can examine the effect of the header manipulation with ModSecurity.

Recommended Base Configuration

Each release ships a modsecurity.conf-recommended file with the engine settings an administrator is expected to own: engine mode, body handling, limits, logging and file locations. Rule sets such as the OWASP CRS build on top of it and must not repeat these settings. Both code lines carry their own copy:

Copy the file to your configuration directory as modsecurity.conf, together with unicode.mapping from the same tree, and include it before any rule set. Distribution packages install both files for you (see the installation chapter). The sections below walk through the file as shipped in v2.9.15; the examples are reformatted per the site’s conventions and the v3 differences are called out where they occur.

Rule engine

SecRuleEngine DetectionOnly

The engine starts in detection-only mode so that a fresh installation cannot disrupt the application. Rules are evaluated and logged but never block. Switch to On once the logs look clean. See SecRuleEngine.

Request body handling

SecRequestBodyAccess On

SecRule REQUEST_HEADERS:Content-Type "@rx ^(?:application(?:/soap\+|/)|text/)xml" \
    "id:'200000',\
    phase:1,\
    pass,\
    t:none,\
    t:lowercase,\
    nolog,\
    ctl:requestBodyProcessor=XML"

SecRule REQUEST_HEADERS:Content-Type "@rx ^application/json" \
    "id:'200001',\
    phase:1,\
    pass,\
    t:none,\
    t:lowercase,\
    nolog,\
    ctl:requestBodyProcessor=JSON"

#SecRule REQUEST_HEADERS:Content-Type "^application/[a-z0-9.-]+[+]json" \
#    "id:'200006',phase:1,t:none,t:lowercase,pass,nolog,ctl:requestBodyProcessor=JSON"

Without request body access ModSecurity never sees POST parameters, which leaves a large hole, so it is on. The engine selects the application/x-www-form-urlencoded and multipart/form-data parsers on its own; the XML and JSON parsers must be chosen by a phase 1 rule from the Content-Type header, which rules 200000 and 200001 do. Rule 200006 is shipped commented out; enable or adapt it if your application sends +json subtypes such as application/problem+json. The JSON parser requires a build with YAJL.

SecRequestBodyLimit 13107200
SecRequestBodyNoFilesLimit 131072
SecRequestBodyInMemoryLimit 131072
SecRequestBodyLimitAction Reject
SecRequestBodyJsonDepthLimit 512

The first limit (12.5 MB) is the largest request body that will be buffered and must be as large as the biggest file upload you accept; the second (128 KB) applies to bodies without file parts and should stay as low as the application allows. SecRequestBodyLimitAction Reject rejects bodies over the limit, but the engine forces ProcessPartial while SecRuleEngine is DetectionOnly, so nothing is rejected during the initial deployment. The JSON depth limit keeps deeply nested documents from exhausting the parser.

libModSecurity v3

SecRequestBodyInMemoryLimit is absent from the v3 file: the library does not buffer to disk and rejects the directive. The v3 file instead adds SecArgumentsLimit 1000 and rule 200007, which denies a request whose argument count reaches that limit, because v3 stops parsing arguments silently once the limit is hit:

SecArgumentsLimit 1000

SecRule &ARGS "@ge 1000" \
    "id:'200007',\
    phase:2,\
    deny,\
    status:400,\
    t:none,\
    log,\
    msg:'Failed to fully parse request body due to large argument count',\
    severity:2"

ModSecurity v2 applies the same default limit of 1000 arguments without the directive, and also sets REQBODY_ERROR when it is exceeded, so rule 200002 below covers it there.

SecRule REQBODY_ERROR "!@eq 0" \
    "id:'200002',\
    phase:2,\
    deny,\
    status:400,\
    t:none,\
    log,\
    msg:'Failed to parse request body.',\
    logdata:'%{reqbody_error_msg}',\
    severity:2"

SecRule MULTIPART_STRICT_ERROR "!@eq 0" \
    "id:'200003',\
    phase:2,\
    deny,\
    status:400,\
    t:none,\
    log,\
    msg:'Multipart request body failed strict validation: RE %{REQBODY_ERROR}, BQ %{MULTIPART_BOUNDARY_QUOTED}, BW %{MULTIPART_BOUNDARY_WHITESPACE}, DB %{MULTIPART_DATA_BEFORE}, DA %{MULTIPART_DATA_AFTER}, DH %{MULTIPART_DUPLICATE_PART_HEADER}, HF %{MULTIPART_HEADER_FOLDING}, LF %{MULTIPART_LF_LINE}, SM %{MULTIPART_MISSING_SEMICOLON}, IQ %{MULTIPART_INVALID_QUOTING}, IP %{MULTIPART_INVALID_PART}, IH %{MULTIPART_INVALID_HEADER_FOLDING}, FL %{MULTIPART_FILE_LIMIT_EXCEEDED}'"

SecRule MULTIPART_UNMATCHED_BOUNDARY "!@eq 0" \
    "id:'200004',\
    phase:2,\
    deny,\
    t:none,\
    log,\
    msg:'Multipart parser detected a possible unmatched boundary.'"

A request body the engine could not parse is a request the rules cannot inspect, so rule 200002 denies it with a 400 and logs the parser’s message. Rule 200003 enforces strict multipart/form-data validation and lists every MULTIPART_* flag in its message so the audit log shows which check failed; if it proves too strict for an application, switch it to detection rather than removing it. Rule 200004 catches lines that look like a boundary but do not match the declared one.

libModSecurity v3

The v3 file’s rule 200003 reports PE %{REQBODY_PROCESSOR_ERROR} instead of RE %{REQBODY_ERROR} (v2 removed REQBODY_PROCESSOR_ERROR in 2.9.14) and has no DH item, since MULTIPART_DUPLICATE_PART_HEADER arrived in 3.0.17 after the file was last changed. Its rule 200004 is @eq 1 rather than !@eq 0: since 3.0.3 the v3 parser sets the variable to 1 when a mandatory boundary line is missing or out of order and to 2 when extra lines merely start with --, so @eq 1 is the permissive form that lets PEM files and similar content through, and !@eq 0 is the strict form.

SecPcreMatchLimit 1000
SecPcreMatchLimitRecursion 1000

SecRule TX:/^MSC_/ "!@streq 0" \
    "id:'200005',\
    phase:2,\
    deny,\
    t:none,\
    log,\
    msg:'ModSecurity internal error flagged: %{MATCHED_VAR_NAME}'"

The PCRE limits cap the work a single regular expression may do, against regular-expression denial of service. When a limit is hit the engine sets TX:MSC_PCRE_LIMITS_EXCEEDED instead of matching, and rule 200005 turns any such MSC_ flag into a denial. In v3 SecPcreMatchLimitRecursion is accepted but ignored, and the match limit is honored since 3.0.10.

Response body handling

SecResponseBodyAccess On
SecResponseBodyMimeType text/plain text/html text/xml
SecResponseBodyLimit 524288
SecResponseBodyLimitAction ProcessPartial

Response inspection is what catches error pages and data leakage, at the price of memory and latency. Only the listed MIME types are buffered, so static files are not; adjust the list to the documents your application produces (JSON responses need application/json added). Bodies over 512 KB are processed as far as the limit and the rest is passed through, which is less secure but never breaks a legitimate page.

File system locations

SecTmpDir /tmp/
SecDataDir /tmp/

#SecUploadDir /opt/modsecurity/var/upload/
#SecUploadKeepFiles RelevantOnly
#SecUploadFileMode 0600

Temporary files (request bodies over the in-memory limit) and persistent collections go to /tmp only because every system has it; both should point at a directory private to the web server user. The upload directives are commented out: set SecUploadDir to a private directory and SecUploadKeepFiles RelevantOnly when you add a file inspection rule (@inspectFile), which is what decides which files are relevant.

libModSecurity v3

v3 accepts SecTmpDir and SecDataDir but ignores them: collections live in process memory unless the library was built with LMDB (see Persistent Storage), and there is no disk buffering of request bodies. SecUploadKeepFiles RelevantOnly is rejected by v3; use On.

Debug and audit logging

#SecDebugLog /opt/modsecurity/var/log/debug.log
#SecDebugLogLevel 3

SecAuditEngine RelevantOnly
SecAuditLogRelevantStatus "^(?:5|4(?!04))"
SecAuditLogParts ABIJDEFHZ
SecAuditLogType Serial
SecAuditLog /var/log/modsec_audit.log
#SecAuditLogStorageDir /opt/modsecurity/var/audit/

The debug log stays off; at level 3 it would only duplicate the error log. The audit log records the transactions a rule marked as relevant plus every server error, meaning 5xx and 4xx responses except 404. All parts are logged, including request and response bodies, to a single serial file, which is convenient to read but meant for occasional use; switch to Concurrent with a storage directory for busy servers. Distribution packages change the log path to their own log directory.

Miscellaneous

SecArgumentSeparator &
SecCookieFormat 0
SecUnicodeMapFile unicode.mapping 20127
SecStatusEngine Off

The argument separator and cookie format match what almost every application uses; a wrong cookie format exposes rules that examine named cookies to evasion. unicode.mapping with code page 20127 (US-ASCII) drives t:urlDecodeUni; pick the code page of your application’s language to reduce false positives and negatives. The status engine, which used to report version information to the project, is off because there has been no receiver for it since April 2022; v3 accepts the directive and ignores it.

Differences between the two files

Settingv2 (v2.9.15)v3 (v3.0.17)
SecRequestBodyInMemoryLimit 131072presentabsent; the directive is rejected by v3
SecArgumentsLimit 1000 plus rule 200007absent; v2 applies the limit by defaultpresent
Rule 200003 messageRE %{REQBODY_ERROR} and a DH itemPE %{REQBODY_PROCESSOR_ERROR}, no DH item
Rule 200004 operator!@eq 0@eq 1 (permissive mode)
SecTmpDir, SecDataDirusedaccepted but ignored

Everything else is identical, including the rule IDs 200000 to 200007, which rule sets must not reuse.

Impedance Mismatch

Web application firewalls have a difficult job trying to make sense of data that passes by, without any knowledge of the application and its business logic. The protection they provide comes from having an independent layer of security on the outside. Because data validation is done twice, security can be increased without having to touch the application. In some cases, however, the fact that everything is done twice brings problems. Problems can arise in the areas where the communication protocols are not well specified, or where either the device or the application do things that are not in the specification. In such cases it may be possible to design payload that will be interpreted in one way by one device and in another by the other device. This problem is better known as Impedance Mismatch. It can be exploited to evade the security devices.

While we will continue to enhance ModSecurity to deal with various evasion techniques the problem can only be minimized, but never solved. With so many different application backends chances are some will always do something completely unexpected. The only solution is to be aware of the technologies in the backend when writing rules, adapting the rules to remove the mismatch. See the next section for some examples.

Impedance Mismatch with PHP Apps

When writing rules to protect PHP applications you need to pay attention to the following facts:

  1. When “register_globals” is set to “On” request parameters are automatically converted to script variables. In some PHP versions it is even possible to override the $GLOBALS array.
  2. Whitespace at the beginning of parameter names is ignored. (This is very dangerous if you are writing rules to target specific named variables.)
  3. The remaining whitespace (in parameter names) is converted to underscores. The same applies to dots and to a “[” if the variable name does not contain a matching closing bracket. (Meaning that if you want to exploit a script through a variable that contains an underscore in the name you can send a parameter with a whitespace or a dot instead.)
  4. Cookies can be treated as request parameters.
  5. The discussion about variable names applies equally to the cookie names.
  6. The order in which parameters are taken from the request and the environment is EGPCS (environment, GET, POST, Cookies, built-in variables). This means that a POST parameter will overwrite the parameters transported on the request line (in QUERY_STRING).
  7. When “magic_quotes_gpc” is set to “On” PHP will use backslash to escape the following characters: single quote, double quote, backslash, and the nul byte.
  8. If “magic_quotes_sybase” is set to “On” only the single quote will be escaped using another single quote. In this case the “magic_quotes_gpc” setting becomes irrelevant. The “magic_quotes_sybase” setting completely overrides the “magic_quotes_gpc” behavior but “magic_quotes_gpc” still must be set to “On” for the Sybase-specific quoting to work.
  9. PHP will also automatically create nested arrays for you. For example “p[x][y]=1” results in a total of three variables.

Logging and Data Formats

The purpose of this document is to describe the formats of the ModSecurity alert messages, transaction logs and communication protocols, which would not only allow for a better understanding what ModSecurity does but also for an easy integration with third-party tools and products.

Alerts

As part of its operations ModSecurity will emit alerts, which are either warnings (non-fatal) or errors (fatal, usually leading to the interception of the transaction in question). Below is an example of a ModSecurity alert entry:

Access denied with code 505 (phase 1). Match of "rx
  ^HTTP/(0\\.9|1\\.[01])$" against "REQUEST_PROTOCOL" required.
  [id "960034"] [msg "HTTP protocol version is not allowed by policy"]
  [severity "CRITICAL"] [uri "/"] [unique_id "PQaTTVBEUOkAAFwKXrYAAAAM"]
Note

Alerts will only ever contain one line of text but we’ve broken the above example into multiple lines to make it fit into the page.

Each alert entry begins with the engine message, which describes what ModSecurity did and why. For example:

Access denied with code 505 (phase 1). Match of "rx ^HTTP/(0\\.9|1\\.[01])$" against "REQUEST_PROTOCOL" required.

Alert Action Description

The first part of the engine message tells you whether ModSecurity acted to interrupt transaction or rule processing:

  1. If the alert is only a warning, the first sentence will simply say Warning.
  2. If the transaction was intercepted, the first sentence will begin with Access denied. What follows is the list of possible messages related to transaction interception:
    • Access denied with code %0 - a response with status code %0 was sent.
    • Access denied with connection close - connection was abruptly closed.
    • Access denied with redirection to %0 using status %1 - a redirection to URI %0 was issued using status %1.
  3. There is also a special message that ModSecurity emits where an allow action is executed. There are three variations of this type of message:
    • Access allowed - rule engine stopped processing rules (transaction was unaffected).
    • Access to phase allowed - rule engine stopped processing rules in the current phase only. Subsequent phases will be processed normally. Transaction was not affected by this rule but it may be affected by any of the rules in the subsequent phase.
    • Access to request allowed - rule engine stopped processing rules in the current phase. Phases prior to request execution in the backend (currently phases 1 and 2) will not be processed. The response phases (currently phases 3 and 4) and others (currently phase 5) will be processed as normal. Transaction was not affected by this rule but it may be affected by any of the rules in the subsequent phase.

Alert Justification Description

The second part of the engine message explains why the alert was generated. Since it is automatically generated from the rules it will be very technical in nature, talking about operators and their parameters and give you insight into what the rule looked like. But this message cannot give you insight into the reasoning behind the rule. A well-written rule will always specify a human-readable message (using the msg action) to provide further information.

The format of the second part of the engine message depends on whether it was generated by the operator (which happens on a match) or by the rule processor (which happens where there is not a match, but the negation was used):

  • @beginsWith - String match %0 at %1.
  • @contains - String match %0 at %1.
  • @containsWord - String match %0 at %1.
  • @endsWith - String match %0 at %1.
  • @eq - Operator EQ matched %0 at %1.
  • @ge - Operator GE matched %0 at %1.
  • @geoLookup - Geo lookup for %0 succeeded at %1.
  • @inspectFile - File %0 rejected by the approver script %1: %2
  • @le - Operator LE matched %0 at %1.
  • @lt - Operator LT matched %0 at %1.
  • @rbl - RBL lookup of %0 succeeded at %1.
  • @rx - Pattern match %0 at %1.
  • @streq - String match %0 at %1.
  • @validateByteRange - Found %0 byte(s) in %1 outside range: %2.
  • @validateDTD - XML: DTD validation failed.
  • @validateSchema - XML: Schema validation failed.
  • @validateUrlEncoding
    • Invalid URL Encoding: Non-hexadecimal digits used at %0.
    • Invalid URL Encoding: Not enough characters at the end of input at %0.
  • @validateUtf8Encoding
    • Invalid UTF-8 encoding: not enough bytes in character at %0.
    • Invalid UTF-8 encoding: invalid byte value in character at %0.
    • Invalid UTF-8 encoding: overlong character detected at %0.
    • Invalid UTF-8 encoding: use of restricted character at %0.
    • Invalid UTF-8 encoding: decoding error at %0.
  • @verifyCC - CC# match %0 at %1.

Messages not related to operators:

  • When the SecAction directive is processed - Unconditional match in SecAction.
  • When SecRule does not match but negation is used - Match of %0 against %1 required.
Note

The parameters to the operators @rx and @pm (regular expression and text pattern, respectively) will be truncated to 252 bytes if they are longer than this limit. In this case the parameter in the alert message will be terminated with three dots.

Meta-data

The metadata fields are always placed at the end of the alert entry. Each metadata field is a text fragment that consists of an open bracket followed by the metadata field name, followed by the value and the closing bracket. What follows is the text fragment that makes up the id metadata field.

[id "960034"]

The following metadata fields are currently used:

  1. offset - The byte offset where a match occurred within the target data. This is not always available.
  2. id - Unique rule ID, as specified by the id action.
  3. rev - Rule revision, as specified by the rev action.
  4. msg - Human-readable message, as specified by the msg action.
  5. severity - Event severity as text, as specified by the severity action. The possible values (with theircorresponding numberical values in brackets) areEMERGENCY(0),ALERT(1),CRITICAL(2),ERROR(3),WARNING(4),NOTICE(5),INFO(6) andDEBUG(7).
  6. unique_id - Unique event ID, generated automatically.
  7. uri - Request URI.
  8. logdata - contains transaction data fragment, as specified by the logdata action.

Escaping

ModSecurity alerts will always contain text fragments that were taken from configuration or the transaction. Such text fragments escaped before they are user in messages, in order to sanitize the potentially dangerous characters. They are also sometimes surrounded using double quotes. The escaping algorithm is as follows:

  1. Characters 0x08 (BACKSPACE), 0x0a (NEWLINE), 0x10 (CARRIAGE RETURN), 0x09 (HORIZONTAL TAB) and 0x0b (VERTICAL TAB) will berepresented as\b, \n, \r, \tand\v, respectively.
  2. Bytes from the ranges 0-0x1f and 0x7f-0xff (inclusive) will be represented as \xHH, where HH is the hexadecimal` value of the byte.
  3. Backslash characters (\) will be represented as \\.
  4. Each double quote character will be represented as \", but only if the entire fragment is surrounded with double quotes.

Alerts in the Apache Error Log

Every ModSecurity alert conforms to the following format when it appears in the Apache error log:

[Sun Jun 24 10:19:58 2007] [error] [client 192.168.0.1]
            ModSecurity: ALERT_MESSAGE

The above is a standard Apache error log format. The ModSecurity: prefix is specific to ModSecurity. It is used to allow quick identification of ModSecurity alert messages when they appear in the same file next to other Apache messages. The actual message (ALERT_MESSAGE in the example above) is in the same format as described in the Alerts section.

Note

Apache further escapes ModSecurity alert messages before writing them to the error log. This means that all backslash characters will be doubled in the error log. In practice, since ModSecurity will already represent a single backslash within an untrusted text fragment as two backslashes, the end result in the Apache error log will be four backslashes. Thus, if you need to interpret a ModSecurity message from the error log, you should decode the message part after the ModSecurity: prefix first. This step will peel the first encoding layer.

Alerts in Audit Logs

Alerts are transported in the H section of the ModSecurity Audit Log. Alerts will appear each on a separate line and in the order they were generated by ModSecurity. Each line will be in the following format:

Message: ALERT_MESSAGE

Below is an example of an H section that contains two alert messages:

--c7036611-H--
Message: Warning. Match of "rx ^apache.*perl" against
  "REQUEST_HEADERS:User-Agent" required. [id "990011"] [msg "Request
  Indicates an automated program explored the site"] [severity "NOTICE"]
Message: Warning. Pattern match "(?:\\b(?:(?:s(?:elect\\b(?:.{1,100}?\\b
  (?:(?:length|count|top)\\b.{1,100}?\\bfrom|from\\b.{1,100}?\\bwhere)
  |.*?\\b(?:d(?:ump\\b.*\\bfrom|ata_type)|(?:to_(?:numbe|cha)|inst)r))|p_
  (?:(?:addextendedpro|sqlexe)c|(?:oacreat|prepar)e|execute(?:sql)?|
  makewebt ..." at ARGS:c. [id "950001"] [msg "SQL Injection Attack.
  Matched signature: union select"] [severity "CRITICAL"]
Stopwatch: 1199881676978327 2514 (396 2224 -)
Producer: ModSecurity v2.x.x (Apache 2.x)
Server: Apache/2.x.x
 
--c7036611-Z--

Audit Log

ModSecurity records one transaction in a single audit log file. Below is an example:

--c7036611-A--
[09/Jan/2008:12:27:56 +0000] OSD4l1BEUOkAAHZ8Y3QAAAAH 209.90.77.54 64995
  80.68.80.233 80
--c7036611-B--
GET //EvilBoard_0.1a/index.php?c='/**/union/**/select/**/1,concat(username,
  char(77),password,char(77),email_address,char(77),info,char(77),user_level,
  char(77))/**/from/**/eb_members/**/where/**/userid=1/*http://kamloopstutor.
  com/images/banners/on.txt? HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, cslose
Host: www.example.com
User-Agent: libwww-perl/5.808
 
--c7036611-F--
HTTP/1.1 404 Not Found
Content-Length: 223
Connection: close
Content-Type: text/html; charset=iso-8859-1
 
--c7036611-H--
Message: Warning. Match of "rx ^apache.*perl" against
  "REQUEST_HEADERS:User-Agent" required. [id "990011"] [msg "Request
  Indicates an automated program explored the site"] [severity "NOTICE"]
Message: Warning. Pattern match "(?:\\b(?:(?:s(?:elect\\b(?:.{1,100}?\\b
  (?:(?:length|count|top)\\b.{1,100}?\\bfrom|from\\b.{1,100}?\\bwhere)
  |.*?\\b(?:d(?:ump\\b.*\\bfrom|ata_type)|(?:to_(?:numbe|cha)|inst)r))|p_
  (?:(?:addextendedpro|sqlexe)c|(?:oacreat|prepar)e|execute(?:sql)?|
  makewebt ..." at ARGS:c. [id "950001"] [msg "SQL Injection Attack.
  Matched signature: union select"] [severity "CRITICAL"]
Stopwatch: 1199881676978327 2514 (396 2224 -)
Producer: ModSecurity v2.x.x (Apache 2.x)
Server: Apache/2.x.x
 
--c7036611-Z--

The file consist of multiple sections, each in different format. Separators are used to define sections:

--c7036611-A--

A separator always begins on a new line and conforms to the following format:

  1. Two dashes
  2. Unique boundary, which consists from several hexadecimal characters.
  3. One dash character.
  4. Section identifier, currently a single uppercase letter.
  5. Two trailing dashes.

Refer to the documentation for SecAuditLogParts for the explanation of each part.

Parts

This section documents the audit log parts available in ModSecurity 2.x. They are:

  • A - audit log header
  • B - request headers
  • C - request body
  • D - intended response headers (NOT IMPLEMENTED)
  • E - intended response body
  • F - response headers
  • G - response body (NOT IMPLEMENTED)
  • H - audit log trailer
  • I - reduced multipart request body
  • J - multipart files information (NOT IMPLEMENTED)
  • K - matched rules information
  • Z - audit log footer

Audit Log Header (A)

ModSecurity 2.x audit log entries always begin with the header part. For example:

--c7036611-A--
[09/Jan/2008:12:27:56 +0000] OSD4l1BEUOkAAHZ8Y3QAAAAH 209.90.77.54 64995
  80.68.80.233 80

The header contains only one line, with the following information on it:

  1. Timestamp
  2. Unique transaction ID
  3. Source IP address (IPv4 or IPv6)
  4. Source port
  5. Destination IP address (IPv4 or IPv6)
  6. Destination port

Request Headers (B)

The request headers part contains the request line and the request headers. The information present in this part will not be identical to that sent by the client responsible for the transaction. ModSecurity 2.x for Apache does not have access to the raw data; it sees what Apache itself sees. While the end result may be identical to the raw request, differences are possible in some areas:

  1. If any of the fields are NUL-terminated, Apache will only see the content prior to the NUL.
  2. Headers that span multiple lines (feature known as header folding) will be collapsed into a single line.
  3. Multiple headers with the same name will be combined into a single header (as allowed by the HTTP RFC).

Request Body (C)

This part contains the request body of the transaction, after dechunking and decompression (if applicable).

Intended Response Headers (D)

This part contains the status line and the request headers that would have been delivered to the client had ModSecurity not intervened. Thus this part makes sense only for transactions where ModSecurity altered the data flow. By differentiating before the intended and the final response headers, we are able to record what was internally ready for sending, but also what was actually sent.

Note

This part is reserved for future use. It is not implemented in ModSecurity 2.x.

Intended Response Body (E)

This part contains the transaction response body (before compression and chunking, where used) that was either sent or would have been sent had ModSecurity not intervened. You can find whether interception took place by looking at the Action header of the part H. If that header is present, and the interception took place in phase 3 or 4 then the E part contains the intended response body. Otherwise, it contains the actual response body.

Note

Once the G (actual response body) part is implemented, part E will be present only in audit logs that contain a transaction that was intercepted, and there will be no need for further analysis.

Response Headers (F)

This part contains the actual response headers sent to the client. Since ModSecurity 2.x for Apache does not access the raw connection data, it constructs part F out of the internal Apache data structures that hold the response headers. Some headers (the Date and Server response headers) are generated just before they are sent and ModSecurity is not able to record those. You should note than ModSecurity is working as part of a reverse proxy, the backend web server will have generated these two servers, and in that case they will be recorded.

Response Body (G)

When implemented, this part will contain the actual response body before compression and chunking.

Note

This part is reserved for future use. It is not implemented in ModSecurity 2.x.

Audit Log Trailer (H)

Part H contains additional transaction meta-data that was obtained from the web server or from ModSecurity itself. The part contains a number of trailer headers, which are similar to HTTP headers (without support for header folding):

  1. Action
  2. Apache-Error
  3. Message
  4. Producer
  5. Response-Body-Transformed
  6. Sanitised-Args
  7. Sanitised-Request-Headers
  8. Sanitised-Response-Headers
  9. Server
  10. Stopwatch
  11. WebApp-Info
Action

The Action header is present only for the transactions that were intercepted:

Action: Intercepted (phase 2)

The phase information documents the phase in which the decision to intercept took place.

Apache-Error

The Apache-Error header contains Apache error log messages observed by ModSecurity, excluding those sent by ModSecurity itself. For example:

Apache-Error: [file "/tmp/buildd/apache2-2.0.54/build-tree/apache2/server/
  core.c"] [line 3505] [level 3] File does not exist: /var/www/www.
  modsecurity.org/fst/documentation/modsecurity-apache/2.5.0-dev2
Message

Zero or more Message headers can be present in any trailer, and each such header will represent a single ModSecurity warning or error, displayed in the order they were raised. The example below was broken into multiple lines to make it fit this page:

Message: Access denied with code 400 (phase 2). Pattern match "^\w+:/" at
  REQUEST_URI_RAW. [file "/etc/apache2/rules-1.6.1/modsecurity_crs_20_
  protocol_violations.conf"] [line "74"] [id "960014"] [msg "Proxy access
  attempt"] [severity "CRITICAL"] [tag "PROTOCOL_VIOLATION/PROXY_ACCESS"]
Producer

The Producer header identifies the product that generated the audit log. For example:

Producer: ModSecurity for Apache/2.5.5 (http://www.modsecurity.org/).

ModSecurity allows rule sets to add their own signatures to the Producer information (this is done using the SecComponentSignature directive). Below is an example of the Producer header with the signature of one component (all one line):

Producer: ModSecurity for Apache/2.5.5 (http://www.modsecurity.org/);
    MyComponent/1.0.0 (Beta).
Response-Body-Transformed

This header will appear in every audit log that contains a response body:

Response-Body-Transformed: Dechunked

The contents of the header is constant at present, so the header is only useful as a reminder that the recorded response body is not identical to the one sent to the client. The actual content is the same, except that Apache may further compress the body and deliver it in chunks.

Sanitised-Args

The Sanitised-Args header contains a list of arguments that were sanitized (each byte of their content replaced with an asterisk) before logging. For example:

Sanitised-Args: "old_password", "new_password", "new_password_repeat".
Sanitised-Request-Headers

The Sanitised-Request-Headers header contains a list of request headers that were sanitized before logging. For example:

Sanitised-Request-Headers: "Authentication".
Sanitised-Response-Headers

The Sanitised-Response-Headers header contains a list of response headers that were sanitized before logging. For example:

Sanitised-Response-Headers: "My-Custom-Header".
Server

The Server header identifies the web server. For example:

Server: Apache/2.0.54 (Debian GNU/Linux) mod_ssl/2.0.54 OpenSSL/0.9.7e

This information may sometimes be present in any of the parts that contain response headers, but there are a few cases when it isn’t:

  1. None of the response headers were recoreded.
  2. The information in the response headers is not accurate because server signature masking was used.
Stopwatch

The Stopwatch header provides certain diagnostic information that allows you to determine the performance of the web server and of ModSecurity itself. It will typically look like this:

Stopwatch: 1222945098201902 2118976 (770* 4400 -)

Each line can contain up to 5 different values. Some values can be absent; each absent value will be replaced with a dash. The meanings of the values are as follows (all values are in microseconds):

  1. Transaction timestamp in microseconds since January 1st, 1970.
  2. Transaction duration.
  3. The time between the moment Apache started processing the request and until phase 2 of ModSecurity began. If an asterisk is present that means the time includes the time it took ModSecurity to read the request body from the client (typically slow). This value can be used to provide a rough estimate of the client speed, but only with larger request bodies (the smaller request bodies may arrive in a single TCP/IP packet).
  4. The time between the start of processing and until phase 2 was completed. If you substract the previous value from this value you will get the exact duration of phase 2 (which is the main rule processing phase).
  5. The time between the start of request processing and util we began sending a fully-buffered response body to the client. If you substract this value from the total transaction duration and divide with the response body size you may get a rough estimate of the client speed, but only for larger response bodies.
WebApp-Info

The WebApp-Info header contains information on the application to which the recorded transaction belongs. This information will appear only if it is known, which will happen if SecWebAppId was set, or setsid or setuid executed in the transaction. The header uses the following format:

WebApp-Info: "WEBAPPID" "SESSIONID" "USERID"

Each unknown value is replaced with a dash.

Reduced Multipart Request Body (I)

Transactions that deal with file uploads tend to be large, yet the file contents is not always relevant from the security point of view. The I part was designed to avoid recording raw multipart/form-data request bodies, replacing them with a simulated application/x-www-form-urlencoded body that contains the same key-value parameters. The reduced multipart request body will not contain any file information. The J part (currently not implemented) is intended to carry the file metadata.

Multipart Files Information (J)

The purpose of part J is to record the information on the files contained in a multipart/form-data request body. This is handy in the cases when the original request body was not recorded, or when only a reduced version was recorded (e.g. when part I was used instead of part C).

Note

This part is reserved for future use. It is not implemented in ModSecurity 2.x.

Matched Rules (K)

The matched rules part contains a record of all ModSecurity rules that matched during transaction processing. You should note that if a rule that belongs to a chain matches then the entire chain will be recorded. This is because, even though the disruptive action may not have executed, other per-rule actions have, and you will need to see the entire chain in order to understand the rules. This part is available starting with ModSecurity 2.5.x.

Part Z is a special part that only has a boundary but no content. Its only purpose is to signal the end of an audit log.

Storage Formats

ModSecurity supports two audit log storage formats:

  1. Serial audit log format - multiple audit log entries stored in the same file.
  2. Concurrent audit log format - one file is used for every audit log entry.

Serial Audit Log Format

The serial audit log format stores multiple audit log entries within the same file (one after another). This is often very convinent (audit log entries are easy to find) but this format is only suitable for light logging in the current ModSecurity implementation because writing to the file is serialized: only one audit log entry can be written at any one time.

Concurrent Audit Log Format

The concurrent audit log format uses one file per audit log entry, and allows many transactions to be recorded at once. A hierarchical directory structure is used to ensure that the number of files created in any one directory remains relatively small. For example:

$LOGGING-HOME/20081128/20081128-1414/20081128-141417-
  egDKy38AAAEAAAyMHXsAAAAA

The current time is used to work out the directory structure. The file name is constructed using the current time and the transaction ID. The creation of every audit log in concurrent format is recorded with an entry in the concurrent audit log index file. The format of each line resembles the common web server access log format. For example:

192.168.0.111 192.168.0.1 - - [28/Nov/2008:15:06:32 +0000]
  "GET /?p=\\ HTTP/1.1" 200 69 "-" "-" NOfRx38AAAEAAAzcCU4AAAAA
  "-" /20081128/20081128-1506/20081128-150632-NOfRx38AAAEAAAzcCU4AAAAA
  0 1183 md5:ffee2d414cd43c2f8ae151652910ed96

The tokens on the line are as follows:

  1. Hostname (or IP address, if the hostname is not known)
  2. Source IP address
  3. Remote user (from HTTP Authentication)
  4. Local user (from identd)
  5. Timestamp
  6. Request line
  7. Response status
  8. Bytes sent (in the response body)
  9. Referrer information
  10. User-Agent information
  11. Transaction ID
  12. Session ID
  13. Audit log file name (relative to the audit logging home, as configured using the SecAuditLogStorageDir directive)
  14. Audit log offset
  15. Audit log size
  16. Audit log hash (the has begins with the name of the algorithm used, followed by a colon, followed by the hexadecimal representation of the hash itself); this hash can be used to verify that the transaction was correctly recorded and that it hasn’t been modified since.
Note

Lines in the index file will be up to 3980 bytes long, and the information logged will be reduced to fit where necessary. Reduction will occur within the individual fields, but the overall format will remain the same. The character L will appear as the last character on a reduced line. A space will be the last character on a line that was not reduced to stay within the limit.

Transport Protocol

Audit logs generated in multi-sensor deployments are of little use if left on the sensors. More commonly, they will be transported to a central logging server using the transport protocol described in this section:

  1. The transport protocol is based on the HTTP protocol.
  2. The server end is an SSL-enabled web server with HTTP Basic Authentication configured.
  3. Clients will open a connection to the centralisation web server and authenticate (given the end-point URI, the username and the password).
  4. Clients will submit every audit log in a single PUT transaction, placing the file in the body of the request and additional information in the request headers (see below for details).
  5. Server will process each submission and respond with an appropriate status code:
    1. 200 (OK) - the submission was processed; the client can delete the corresponding audit log entry if it so desires. The same audit log entry must not be submitted again.
    2. 409 (Conflict) - if the submission is in invalid format and cannot be processed. The client should attempt to fix the problem with the submission and attempt delivery again at a later time. This error is generally going to occur due to a programming error in the protocol implementation, and not because of the content of the audit log entry that is being transported.
    3. 500 (Internal Server Error) - if the server was unable to correctly process the submission, due to its own fault. The client should re-attempt delivery at a later time. A client that starts receiving 500 reponses to all its submission should suspend its operations for a period of time before continuing.
Note

Server implementations are advised to accept all submissions that correctly implement the protocol. Clients are unlikely to be able to overcome problems within audit log entries, so such problems are best resolved on the server side.

Note

When en error occurs, the server may place an explanation of the problem in the text part of the response line.

Request Headers Information

Each audit log entry submission must contain additional information in the request headers:

  1. Header X-Content-Hash must contain the audit log entry hash. Clients should expect the audit log entries to be validated against the hash by the server.
  2. Header X-ForensicLog-Summary must contain the entire concurrent format index line.
  3. The Content-Lenght header must be present and contain the length of the audit log entry.

Troubleshooting

Debugging crashes and misbehavior with gdb, and diagnosing the IIS installer.

Subsections of Troubleshooting

Debugging ModSecurity

This page contains information about how to debug ModSecurity. This is not a complete guide or a developer guide, this contains basic information that may help the bug reporting process. Sometimes reproducing problems is not easy due to platform specific issues or even configurations. It is even worse when log files do not contain a specific reference to what might be leading ModSecurity to fail (process is killed before log is saved for instance). In this kind of situation we recommend the utilization of tools such as GDB, which is able to acquire details on the faulty function.

Here we explain some debugging techniques that are applicable to Nginx and Apache in a Linux environment. Debugging in other platforms are is possible, however, they are not covered by this specific post. For more information about IIS, visit the IIS Troubleshooting guide.

General debug instructions

Debugging ModSecurity means debugging the HTTP server. ModSecurity works as a server add-on/module/plugin/extension, as a result, it is part of the same process ID (PID) of the server.

Before starting the debug process, make sure that ModSecurity is compiled with the debugging parameter ("-g" for those who are using gcc). Another gcc parameter that is desired is the "-O0", which will disable the compiler optimization, making GDB’s output more friendly. Independent of the target HTTP server, ModSecurity should be compiled with those special flags. These flags can be added during the configuration phase, as follows:

CFLAGS="-g -O0" ./configure ...normal configure parameters...

It is recommended that one keeps the debugging process as simple as possible, to do so, the elimination of features such as multi-threading by the HTTP server is recommended. The instructions on how to disable threads/workers is dependent on your server, as explained on the sub-sections bellow.

Apache

Apache webservers accept a special command line parameter: “-X”, that starts the server in debug mode and doesn’t detach it from the console. This flag should be passed straight to the apache2 or httpd binary, along with any other options, such as the configuration file that should be used. The parameter should not be passed to the apachectl script, instead, the http/apache2 file should be used directly. If you are using Ubuntu your Apache will probably be at: /usr/sbin/apache2. If you are using Fedora this will probably be at: /usr/sbin/httpd.

This setup may affect the behavior of the HTTP server in a way that makes impossible or more difficult to reproduce a given bug, if this is the case, you may wish to ask for help in our mailing list and check out Apache’s debugging instructions at: https://httpd.apache.org/dev/debugging.html.

Nginx

Different from Apache where a parameter is expected to place the server in debugging mode, Nginx expects debugging information within the configuration files. To keep Nginx attached to the console, a user can set daemon to off. Threads can be disabled by having master_process set to off. As demonstrated below:

daemon off;
master_process off;

By adding a directives similar to the above to Nginx’s configuration, it will be executed as a single thread and it won’t detach from the console. If the problem is not reproducible under these circumstances other techniques can be used as discussed at: http://wiki.nginx.org/Debugging. Besides the debugging parameters that should be passed to gcc, it is also recommend to use the option –with-debug in the Nginx’s configuration script. The recommended configuration options are illustrated bellow:

CFLAGS="-g -O0" ./configure --with-debug ...normal paramanters...

Running GDB

As defined on GDB’s website: “GDB, the GNU Project debugger, allows you to see what is going on `inside’ another program while it executes – or what another program was doing at the moment it crashed.” The utilization of GDB is recommended to understand and report ModSecurity crashes. This section is not intend to give an advanced usage guide of GDB, instead, it is just about how print a stack trace in a situation where the HTTP server died.

GDB can be attached to process that are already running or it can be attached in the beginning of the execution. In this document the second option will be explained. It is very simple to get GDB to “watch” a process; the target binary should be passed as a parameter to GDB, for instance:

$ gdb /usr/sbin/apache2
GNU gdb (GDB) 7.6.1-ubuntu
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
...

Notice that this does not start the target software yet. In order to start the software “run” most be typed in the GDB console. Parameters to the target process are expected to be pasts in the GDB console, as parameters of the command: “run”, as demonstrated bellow:

(gdb) run -X
Starting program: /usr/sbin/apache2 -X
[Thread debugging using libthread_db enabled]
...

After really starting the process (that is, after executing the “run” command), the HTTP server should be working as if there is no GDB. The next step is try to reproduce the bug. Once the bug is reproduced the process will crash and as a result, the GDB command “bt full” can be used to extract information about the crash.A Demonstration of all these steps can be found below:

(zimmerle@zlinux)-(~/core/spider-modsec/tests)$ gdb /usr/sbin/apache2
GNU gdb (GDB) 7.6.1-ubuntu
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /usr/sbin/apache2...(no debugging symbols found)...done.
(gdb) run -d -X -f /home/zimmerle/core/spider-modsec/tests/regression/server_root/conf/httpd.conf -c 'Listen localhost:8088' -c 'Include /home/zimmerle/core/spider-modsec/tests/regression/server_root/conf/config_10-request-directives.t_000003.conf' -k start
Starting program: /usr/sbin/apache2 -d -X -f /home/zimmerle/core/spider-modsec/tests/regression/server_root/conf/httpd.conf -c 'Listen localhost:8088' -c 'Include /home/zimmerle/core/spider-modsec/tests/regression/server_root/conf/config_10-request-directives.t_000003.conf' -k start
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Program received signal SIGABRT, Aborted.
0x00007ffff7196f77 in __GI_raise (sig=sig@entry=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
56	../nptl/sysdeps/unix/sysv/linux/raise.c: No such file or directory.
(gdb) bt full
#0  0x00007ffff7196f77 in __GI_raise (sig=sig@entry=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
        resultvar = 0
        pid = 62396
        selftid = 62396
#1  0x00007ffff719a5e8 in __GI_abort () at abort.c:90
        save_stage = 2
        act = {__sigaction_handler = {sa_handler = 0x7ffff7163d18, sa_sigaction = 0x7ffff7163d18}, sa_mask = {__val = {0, 140737353784168, 140737338818848, 140737488346464, 140737339657820, 0, 6, 28, 0, 140737354072104, 140737353784208, 140737353784216, 140737345047185,
              1, 140733193388080, 140737488346216}}, sa_flags = -9232, sa_restorer = 0x12}
        sigs = {__val = {32, 0 <repeats 15 times>}}
#2  0x00007ffff603eac0 in msc_escape (string=0x7ffff7faa490 "phase:2,deny,chain,id:500219", buff=0x0, buff_length=0, opt=20) at msc_escape.c:133
        i = 28
        length_only = 1
        escaped_string_length = 28
#3  0x00007ffff605250f in _log_escape (mp=0x7ffff7ff0028, input=0x7ffff7faa490 "phase:2,deny,chain,id:500219", input_len=28, escape_quotes=1, escape_colon=0, escape_re=0) at msc_util.c:1335
        length = 0
        res = 0
        options = 20
        buffer = 0x0
#4  0x00007ffff605209a in log_escape (mp=0x7ffff7ff0028, text=0x7ffff7faa470 "phase:2,deny,chain,id:500219") at msc_util.c:1210
No locals.
#5  0x00007ffff6064651 in msre_rule_generate_unparsed (pool=0x7ffff7ff0028, rule=0x7ffff7faa088, targets=0x7ffff7fa9b90 "ARGS:a", args=0x7ffff7fa9b98 "@streq 1", actions=0x0) at re.c:2240
        unparsed = 0x0
        r_targets = 0x7ffff7fa9b90 "ARGS:a"
        r_args = 0x7ffff7fa9b98 "@streq 1"
        r_actions = 0x7ffff7faa470 "phase:2,deny,chain,id:500219"
#6  0x00007ffff6064b41 in msre_rule_create (ruleset=0x7ffff7fa9bc8, type=0, fn=0x7ffff7facdc0 "/home/zimmerle/core/spider-modsec/tests/regression/server_root/conf/config_10-request-directives.t_000003.conf", line=5, targets=0x7ffff7fa9b90 "ARGS:a",
    args=0x7ffff7fa9b98 "@streq 1", actions=0x7ffff7fa9ba8 "phase:2,deny,chain,id:500219", error_msg=0x7fffffffdde8) at re.c:2353
        rule = 0x7ffff7faa088
        my_error_msg = 0x0
        argsp = 0x7ffff7fa9b98 "@streq 1"
        rc = 1
#7  0x00007ffff602737c in add_rule (cmd=0x7fffffffe140, dcfg=0x7ffff7fb0810, type=0, p1=0x7ffff7fa9b90 "ARGS:a", p2=0x7ffff7fa9b98 "@streq 1", p3=0x7ffff7fa9ba8 "phase:2,deny,chain,id:500219") at apache2_config.c:759
        my_error_msg = 0x0
        rid = 0x0
        rule = 0x0
        offset = 0
#8  0x00007ffff6029ca9 in cmd_rule (cmd=0x7fffffffe140, _dcfg=0x7ffff7fb0810, p1=0x7ffff7fa9b90 "ARGS:a", p2=0x7ffff7fa9b98 "@streq 1", p3=0x7ffff7fa9ba8 "phase:2,deny,chain,id:500219") at apache2_config.c:2043
No locals.
#9  0x00005555555a7083 in ?? ()
No symbol table info available.
#10 0x00005555555a96ff in ap_walk_config ()
No symbol table info available.
#11 0x00005555555aa859 in ap_process_config_tree ()
No symbol table info available.
#12 0x00005555555888d6 in main ()
No symbol table info available.
(gdb)

IIS Troubleshooting

This topic introduces tools and options to troubleshooting the IIS version of ModSecurity. It covers the installation process but it was not only limited to that.

Running the installer in verbose mode

ModSecurity installer was created using the Wix Toolset, a popular tool to produce msi installers. The idea of the installer is to provide an easy way to install and configure ModSecurity on a given machine. If one of those (install or configure) fails, the installer aborts and it should revert any changes that it has made on the system.

Sometimes the installer aborts the installation process but it is not verbose enough to help the developers to fix or even identify a eventual problems. It is intend to be that way avoiding confusing a regular user. There is a option to run the installer in a fashion that it does produce textual log that can be attached to bugs or eventually be read by the user in order to identify what was the real problem behind the error dialog.

In order the generate such log, open a command prompt as administrator, go the msi folder and type:

msiexec /i ModSecurityIIS_A.B.C-Zb.msi /l*v log.txt

Proceed normally on the installation steps. After the installation halts, have a look at log.txt in the same folder of the installer. There should be valuable information to identify problems. If you don’t feel confortable to identify the problem, open an issue with the message that was presented on the error dialog box and attach the log.txt to the Issue.

Broken Uninstall

This should not happens to regular users, but, developers playing around the installer may be in a situation that the uninstall process is broken and he is not able to uninstall ModSecurity or even install a newest version. In that situation we recommend the utilization of Microsoft FixIt to force the removal of the package. Keep in mind that file may be left behind. Manual check is necessary after the forced removal.

In order to use the Microsoft FixIt visit the website: http://support.microsoft.com/mats/program_install_and_uninstall

Looking for missing dependencies

ModSecurity itself is distributed along with some dependencies, as an example but not limited to the libapr. Dependencies may changed according to the version. Not all dependencies are part of ModSecurity as an example of the Visual C++ Redistribution files which is not part of the currently release (see bug #627, to check if your version contains those C++ Redistribution files). Some dependencies are expected to be loaded from the system but sometimes, due to version changes or specific configuration of the server those dependencies are not found, leading ModSecurity to fail to be loaded. While not loaded the error messages are not verbose enough to help the user to identify the missing symbol or library.

In order to identify that all dependencies are match, we recommend the utilization of dumpbin. Dumpbin is a utility that is part of the Visual Studio package and it should be in your path after the execution of the vcvars batch script. The path to the script and the mane may vary from version to version of Visual Studio, on Win 8.1 using Visual Studio 2013, here is the path:

C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\x86_amd64\vcvarsx86_amd64.bat

After execute such batch script the dumpbin should be available in your path. Having dumpbin on path, change the directory to the path where the ModSecurityIIS.dll is installed and type:

dumpbin /imports /dependents ModSecurityIIS.dll libapr-1.dll libaprutil-1.dll libxml2.dll lua5.1.dll pcre.dll > c:\somedir\deps.txt

After that, this deps.txt file should be generated. Have a look at this file, it should contains information if there is a missing symbol or not. If there is a missing symbol or library try to install it. If you have problems on these steps or to identify the missing library ask for support in our development mailing list.

Add/Removes ModSecurity from IIS using AppCmd.

The installer makes usage of AppCmd to add/remove ModSecurity from IIS, the installer process is divided into two different steps: Module Installation and Site Configuration, as explained in the sub sections bellow.

The installer uses AppCmd to configure ModSecurity, there are other methods to perform the configuration, those are described at: IIS Modules Overview.

Module Installation

The first part of the ModSecurityIIS setup, is to inform the IIS to load the ModSecurityIIS as a global module, for that, the following commands are use to add/remove it:

Add

appcmd.exe install module /name:"ModSecurity IIS" /image:"C:\Program Files (x86)\ModSecurity IIS\inetsrv\ModSecurityIIS.dll"

Remove

appcmd.exe uninstall module /module.name:"ModSecurity IIS"

Site Configuration

The second part of this IIS configuration is to enable ModSecurity for a site. Note that the first step must be completed prior to the second step, otherwise it will not be possible. In order to enable ModSecurity, the following commands are used by the installer:

Add

appcmd.exe set config /section:"system.webServer/ModSecurity" /"enabled:true" /"configFile:C:\Program Files (x86)\ModSecurity IIS\modsecurity_iis.conf"

Remove

appcmd.exe clear config -section:"system.webServer/ModSecurity"

Looking at ModSecurity event Logs

While running or even during the installation phase, ModSecurityIIS produces valuable information on the Windows Logs’. To check on those event logs, open the Event Viwer and have a look at Application under the Windows Logs folder.

During the installation the logs were generated from the MsiInstaller source. After that, at runtime, logs were generated using ModSecurutyIIS as source.

Accessing data on Network Shares

In order to access shares via an IIS ModSecurity configuration file they must included with quad slashes.

For instance:

SecAuditLog \\\\192.168.1.120\test\temp\index2.log
SecAuditLogStorageDir \\\\192.168.1.120\test\temp
Include \\\\192.168.1.120\test\temp.conf

Accessing shares via mapped drives does not work.

Migration

Moving rules and configuration between ModSecurity generations.

Subsections of Migration

Migrating from v2 to v3

This page is for administrators moving a working ModSecurity v2 (Apache mod_security2 or IIS) deployment to libModSecurity v3, typically because the web server changes to NGINX. Both versions are maintained by OWASP and implement the same rule language, so rule sets such as the OWASP CRS run on both; the differences are in the architecture, in a few evaluation details and in the legacy features v3 does not implement. If you stay on Apache httpd or IIS there is no need to migrate: v2 remains the supported choice there (current release 2.9.15).

What changed architecturally

Library plus connectors. v2 is a web server module and contains the engine, the Apache glue and the IIS module in one tree. v3 (current release 3.0.17) is only the engine, libmodsecurity, with a C and a C++ API. The web server integration is a separate connector project with its own release cycle: ModSecurity-nginx for NGINX (production ready) and ModSecurity-apache (not production ready, so Apache users should stay on v2). All Apache dependencies (APR, apxs) are gone from the engine. See Building libModSecurity v3 from source and libModSecurity v3 with NGINX.

Configuration scopes. In v2 the rules live in Apache’s configuration and inherit through <VirtualHost>, <Location>, <Directory> and .htaccess contexts. In v3 the connector loads the rules: with ModSecurity-nginx you point modsecurity_rules_file (or modsecurity_rules / modsecurity_rules_remote) at a file in an http, server or location block, and you can refine the global set per location with SecRuleRemoveById and similar directives. SecRuleInheritance On is rejected by the v3 parser.

Persistent storage. v2 keeps the IP, GLOBAL, RESOURCE, SESSION and USER collections in SDBM files under SecDataDir, shared by all worker processes. v3 keeps them in memory per process by default; the data is not shared between NGINX workers and is lost on restart. Build with --with-lmdb for an LMDB-backed shared store. SecDataDir is accepted but ignored. See Persistent Storage.

Request body buffering. SecRequestBodyInMemoryLimit is rejected at load time by v3, which follows the web server’s own buffering configuration (client_body_buffer_size in NGINX). Remove the directive from a configuration copied from v2.

Logging. v3 writes the same audit log formats (native and JSON, serial and concurrent) and a debug log, but there is no Apache error log: alerts go through the connector to the web server’s error log. mlogc, the v2 log collector, is not part of v3; ship the JSON audit log with a generic log forwarder instead. See Logging and Data Formats.

Base configuration. Start from the v3 modsecurity.conf-recommended, not the v2 file; the differences are listed in Recommended Base Configuration.

Rule evaluation differences to check in custom rules

  • Default phase. A rule without phase: runs in phase 2 in v2 but in phase 1 in v3. Set phase: on every rule.
  • SecDefaultAction. v3 allows one SecDefaultAction per phase and rejects a second one, requires it to name a real disruptive action (block is not accepted there), and applies its disruptive action to a rule only through block; a rule without any disruptive action does not inherit one. v2 lets a later SecDefaultAction replace an earlier one and applies its disruptive action to every rule that has none.
  • Phase 4 without body inspection. v2 runs phase 4 rules with an empty RESPONSE_BODY; v3 skips phase 4 when SecResponseBodyAccess is Off or the MIME type is not inspected.
  • skipAfter. If the named SecMarker does not exist, v3 skips every remaining rule of every later phase; v2 ends the skip with the phase.
  • ctl:ruleEngine=Off. v2 stops the current phase immediately; v3 only checks the engine state when a phase starts.
  • SecRuleRemoveByTag / SecRuleRemoveByMsg. v2 matches the parameter as an unanchored regular expression; v3 compares the whole tag or message literally.
  • initcol and setvar in one rule. v3 runs setvar before initcol within the same rule; initialize the collection in a separate, earlier rule.
  • SecUploadKeepFiles RelevantOnly is rejected by v3; use On or Off.
  • SecCookieFormat 1 is not supported by v3.
  • SecCollectionTimeout, SecStatusEngine and SecPcreMatchLimitRecursion are accepted by v3 but ignored, so a configuration that relies on collection expiry needs expirevar instead.

See Processing Phases for details.

Not supported in v3

The lists below contain the v2 features that libModSecurity v3 does not implement, verified against the v3.0.17 parser and cross-checked with the compatibility matrix of the SecLang specification (see SecLang specification). Most of them are tied to Apache internals or to retired services and are marked deprecated in the specification; no current rule set uses them.

Directives

Rejected by the v3 parser at load time (remove them from the configuration):

Variables

Actions

  • append and prepend (content injection)
  • deprecatevar
  • marker
  • pause
  • proxy - relied on Apache mod_proxy.
  • sanitiseArg, sanitiseMatched, sanitiseMatchedBytes, sanitiseRequestHeader, sanitiseResponseHeader - audit log masking.
  • The following ctl options, which the v3 parser rejects: debugLogLevel, hashEnforcement, hashEngine, requestBodyLimit, responseBodyAccess, responseBodyLimit, ruleRemoveByMsg, ruleRemoveTargetByMsg. v3 implements auditEngine, auditLogParts, parseXmlIntoArgs, requestBodyAccess, requestBodyProcessor, ruleEngine, ruleRemoveById, ruleRemoveByTag, ruleRemoveTargetById and ruleRemoveTargetByTag, and accepts forceRequestBodyVariable as a no-op (REQUEST_BODY is always populated).

Operators

  • gsbLookup, rsub and validateHash are rejected by the v3 parser at load time (Operator: ... is not yet supported). No other v2 operator is missing.

Transformations

All v2 transformation functions are available in v3. (t:uppercase exists in v3 but not in v2.)

Checklist

  1. Install libmodsecurity and the connector for your web server.
  2. Start from the v3 modsecurity.conf-recommended; copy only your site-specific values (limits, audit log location, MIME types) from the old file.
  3. Remove the directives listed above from your configuration; the v3 parser refuses to load a file that contains most of them.
  4. Grep your custom rules for the variables, actions and ctl options listed above and for rules without phase:.
  5. If you depend on IP, GLOBAL or other persistent collections (for example the CRS DoS-protection plugin), build with --with-lmdb or accept per-worker counters.
  6. Run in SecRuleEngine DetectionOnly, compare the audit log with the v2 deployment, then switch to On.
  7. Report anything that behaves differently and is not listed here at https://github.com/owasp-modsecurity/ModSecurity/issues.

Migrating from v1 to v2

If you are already using an older version of ModSecurity and want to upgrade/migrate your existing custom rules, you will need to ensure that you properly translate all of your Directives to their corresponding 2.x counterparts. Some directives have simply changed names, however some directives actually behave differently so it is important that you also review the entire 2.0 Reference Manual.

The migration matrix show below should help you to translate ModSecurity 1.X directives to the 2.0 values. There are also some notes that provide additional information is a directive significantly changed how it operates.

Apache Version Supported

ModSecurity 1.x

Apache 1.x/2.x

ModSecurity 2.x

Apache 2.x Only

Notes

ModSecurity 2.0 will only work with Apache 2.x and not the older 1.3 version.

How To Upgrade

If you are mainly an Apache 1.3 shop and/or you have other web servers that you want to protect (such as IIS) an alternative solution is to deploy an Apache 2.x reverse proxy server and implement ModSecurity 2.x on it.

Installation

ModSecurity 1.x

Can be installed as either a DSO module or as a statically compiled module.

ModSecurity 2.x

Can currently only be installed as a DSO module.

Notes

In 1.x, you could use apxs directly, while in 2.x you must use the provided Makefile.

How To Upgrade

If you can not use DSOs in your current Apache configs, you may look at implementing a front-end Apache reverse proxy server.

Configuration - IfModule

ModSecurity 1.x

Apache 1.x - Apache 2.x -

ModSecurity 2.x

Notes

The syntax of using IfModule has changed between Apache 1.x and 2.x

How To Upgrade

Make sure that any existing directives uses the correct syntax.

Processing Phases Supported

ModSecurity 1.x

2

ModSecurity 2.x

5

Notes

ModSecurity 1.x supports:

  • Inbound - which corresponds to current Mod 2.x Request Body phase and the Apache “fixups” phase.

  • Outbound - which corresponds to current Mod 2.x Response Body phase and just after the Apache “response” processing phase.

ModSecurity 2.x supports:

  • Request Headers – which corresponds with the Apache “post-read-request” phase.

  • Request Body – which corresponds with the Apache “fixups” phase.

  • Response Headers – which corresponds to the Apache “response” phase.

  • Response Body – which corresponds to just after the Apache “response” phase.

  • Logging - which is the Apache logging phase.

How To Upgrade

If you are translating existing 1.x rules (SecFilter/SecFilterSelective) then you should use phase:2 in the new rule syntax. Translate existing OUTPUT rules to run in phase:4.

Directive to turn On/Off the Rule Engine

ModSecurity 1.x

SecFilterEngine

ModSecurity 2.x

SecRuleEngine ctl:ruleEngine=

Notes

  • 1.x – values were On, Off and DynamicOnly and was a Global directive.

  • 2.x - values are On, Off or DetectionOnly.

  • 2.x – the “ctl” action can control the RuleEngine dynamically for individual requests.

How To Upgrade

Replace SecFilterEngine with SecRuleEngine. The DynamicOnly mode is not supported in ModSecurity 2.x because it was sometimes difficult for ModSecurity to determine if a particular request was dynamic in nature or not. Use of AddType vs. AddHandler would cause problems. Since this logic relies on the internal (and not entirely documented) workings of Apache and on the chosen configuration it also makes it somewhat unpredictable.

Directive to handle the Audit Engine

ModSecurity 1.x

SecAuditEngine On, Off, RelevantOnly, DynamicOrRelevant

ModSecurity 2.x

SecAuditEngine On, Off, RelevantOnly

Notes

In 2.x, the DynamicOrRelevant option was discontinued.

How To Upgrade

If you are using DynamicOrRelevant then switch it to RelevantOnly.

Default Rule Action

ModSecurity 1.x

SecFilterDefaultAction

ModSecurity 2.x

SecDefaultAction

Notes

  • 1.x – SecFilterDefaultAction could be used anywhere in the config and it would be picked up by all rules.

  • 2.x – SecDefaultAction must come before rules and be specified in each context. The default setting for this directive (if it is not specified otherwise) is – SecDefaultAction phase:2,log,deny,status:403,\

    t:lowercase,t:replaceNulls,\

    t:compressWhitespace

How To Upgrade

Replace SecFilterDefaultAction with SecDefaultAction. Optionally, you can group rules together where you would like to use the same action and then specify a SecDefaultAction line before each group. Also keep in mind that while most actions specified on individual rules will supersede those specified in SecDefaultAction, transformation functions are additive. So, if you specify a “t:base64Decode” transformation function to a rule, it will be added after the lowercase, replaceNulls and compressWhitespace transformation functions.

Debug Logging

ModSecurity 1.x

SecFilterDebugLog SecFilterDebugLogLevel

ModSecurity 2.x

SecDebugLog SecDebugLogLevel

Notes

Name change only.

How To Upgrade

Change the names of these directives to their 2.x counterparts.

Rule Directive(s)

ModSecurity 1.x

SecFilter SecFilterSelective

ModSecurity 2.x

SecRule

Notes

  • In Mod 1.x, SecFilter and SecFilterSelective were case insensitive.

  • In Mod 2.x, the case of data is not altered unless the lowercase transformation funce is used. SecRule has essentially the same rule syntax as SecFilterSelective.

How To Upgrade

Replace SecFilterSelective with SecRule and make sure to translate the variable tested according to this list. Replace any SecFilter with a new SecRule directive. You will need to specify a new Variable location and a phase. You can optionally specify a disruptive action, otherwise it will be inherited from a previous SecDefaultAction.

Rule Exceptions

ModSecurity 1.x

Whitelist approach – use pass, allow actions False Positive Approach – use SecFilterRemove

ModSecurity 2.x

Whitelist approach – use pass, allow and ctl actions. False Positive Approach – use SecRuleRemoveById and Apache Scope context

Notes

In Mod 2.x, using the “allow” action may not be enough to truly let a request through as “allow” only applies to the current processing phase. This means that rules in subsequent phases may act on the request. This is why you need to also use the “ctl:ruleEngine=Off” action if you really want to let a request through.

How To Upgrade

See Blog post on handling false positives and creating custom rules - http://blog.spiderlabs.com/2010/11/modsecurity-advanced-topic-of-the-week-exception-handling.html

Directive to control rule inheritance to Apache Scope locations (Virtual Hosts, Location, Directory)

ModSecurity 1.x

SecFilterInheritance

ModSecurity 2.x

SecRuleInheritance

Notes

The best use of this directive is when you want to start with a “clean slate” so you can use SecRuleInheritance Off and then specify your new rule sets. Note – Rule Inheritance does not work across Apache Scope directives (such as Vhosts, Location and Directory directives). This means that you can not use SecRuleInheritance On to inherit a SecDefaultAction directive within these new contexts. This is an issue with the way that Apache inherits contexts. It is for this reason that we recommend that you specify new SecDefaultAction directives within each Apache scope location that you create.

How To Upgrade

Translate any existing “SecFilterInheritance Off” rules directly to “SecRuleInheritance Off”. Then replace any “SecFilterInheritance On” directives inside Apache Scope context locations with a new SecDefaultAction directive and then import the rules that you want with standard Apache Include directives.

Ability to manage rules in Apache Scope locations

ModSecurity 1.x

SecFilterImport SecFilterRemove

ModSecurity 2.x

SecRuleRemoveById SecRuleRemoveByMsg

Notes

SecFilterRemove is now SecRuleRemoveById or SecRuleRemoveByMsg. SecFilterImport is no longer supported.

How To Upgrade

Change all of your existing SecFilterRemove rules to SecRuleRemoveById. For any existing SecFilterImport rules, you will need to either copy the rule into the context or use an Apache Include Directive to include entire files (such as including the Core Rules files).

Ability to verify URL/UTF8 Encodings

ModSecurity 1.x

SecFilterCheckURLEncoding SecFilterCheckUnicodeEncoding

ModSecurity 2.x

@validateUrlEncoding @validateUtf8Encoding

Notes

In Mod 1.x, these were Global Directives and in Mod 2.x they are Operators that can be applied selectively to each rule.

How To Upgrade

Add the rules that will do exactly the same as the directives

Ability to enforce a Byte Range (allowed character set)

ModSecurity 1.x

SecFilterForceByteRange

ModSecurity 2.x

@validateByteRange

Notes

In Mod 1.x, this was a Global Directive and in Mod 2.x it is an Operator that can be applied selectively to each rule. In Mod 1.x, this directive did not check POST payloads when multipart/form-data encoding was used.

How To Upgrade

You can now add @validateByteRange operators to individual rules. This helps if you have differences in allowed character sets for different portions of the web application.

Ability to Normalize/Transform Request Data

ModSecurity 1.x

ModSecurity 1.x automatically applied the following transformations:

  • On Windows only, convert \ to /

  • Reduce /./ to /

  • Reduce // to /

  • Decode URL-encoded characters

  • Converts Null Bytes to Space character

ModSecurity 2.x

  • base64Decode

  • base64Encode

  • compressWhitespace

  • escapeSeqDecode

  • hexDecode

  • hexEncode

  • htmlEntityDecode

  • lowercase

  • md5

  • none

  • normalisePath

  • normalisePathWin

  • removeNulls

  • removeWhitespace

  • replaceComments

  • replaceNulls

  • urlDecode

  • urlDecodeUni

  • urlEncode

  • sha1

Notes

In Mod 1.x, the normalization functions were implicit and you could not control them. In Mod 2.x, not normalization is done by default. There are now “Transformation Functions” that allow you to selectively apply normalizations and other features.

How To Upgrade

You should add the appropriate transformation functions to either SecDefaultAction directive or each individual rule. See the Core Rules files for examples. Keep in mind that transformation functions are inherited from parent SecDefaultAction directives. Care should be taken to ensure that RegEx patterns match the data after transformation functions are applied. In order to avoid possible unwanted inherited transformation functions, use “t:none” to either not apply any transformation functions or you can then specify specific transformation functions after “t:none”.

Ability to specify an arbitrary Request Header in a rule

ModSecurity 1.x

HEADER_headername HTTP_headername

ModSecurity 2.x

REQUEST_HEADERS REQUEST_HEADERS:headername REQUEST_HEADERS:/RegEx/

Notes

The HTTP_headername syntax has been superseded by the new REQUEST_HEADERS:headername syntax and will not be supported in future releases. The advantage to using the new syntax is that you can also use RegEx in the headername portion.

How To Upgrade

Translate any existing HTTP_headername directives to REQUEST_HEADERS:headername. Also consider consolidating header checks by using Regular Expressions in the header name portion of the Variable.

Variable/Location for the entire URL Request Line

ModSecurity 1.x

THE_REQUEST

ModSecurity 2.x

REQUEST_LINE

Notes

Functions the same. The variable includes the Request Method, URI and HTTP version data.

How To Upgrade

Translate any existing THE_REQUEST directives to REQUEST_LINE directives.

Variable/Location for Arguments

ModSecurity 1.x

ARG_name

ModSecurity 2.x

ARGS:name ARGS:/RegEx/

Notes

Similar to the HTTP_headername situation, the advantage of the new syntax is the ability to use RegEx in the argument name.

How To Upgrade

Translate any existing ARG_name directives to ARGS:name directives.

Accessing Request Bodies

ModSecurity 1.x

SecFilterScanPOST POST_PAYLOAD

ModSecurity 2.x

SecRequestBodyAccess Phase:2 REQUEST_BODY

Notes

In 2.x, the directive is now called SecRequestBodyAccess and it is more flexible than SecFilterScanPOST as it is able to inspect all request bodies (such as PUT and XML, etc…) and not just POST payloads.

How To Upgrade

Replace the existing SecFilterScanPOST directive with SecRequestBodyAccess. For individual rules where you want to inspect the request bodies, you must specify REQUEST_BODY as the variable and you also must ensure that it is running in phase:2 (by either an inherited SecDefaultAction setting or by explicitly specifying the phase within the rule action).

Ability to disable POST/Request buffering dynamically

ModSecurity 1.x

MODSEC_NOPOSTBUFFERING

ModSecurity 2.x

ctl:requestBodyAccess=Off

Notes

In 2.x, you can use the ctl action to turn on/off request body access on a per rule basis.

How To Upgrade

Take any existing entries in the httpd.conf file that set the MODSEC_NOPOSTBUFFERING Env variable and translate them to Mod 2.x rules.

Accessing Cookies

ModSecurity 1.x

COOKIES COOKIES_COUNT COOKIES_NAMES COOKIES_VALUES COOKIE_name

ModSecurity 2.x

REQUEST_HEADERS:Cookie REQUEST_COOKIES_NAMES REQUEST_COOKIES_NAMES:name REQUEST_COOKIES_NAMES:/RegEx/ REQUEST_COOKIES REQUEST_COOKIES:name REQUEST_COOKIES:/RegEx/

Notes

In 2.x, you can use the “&” character to “count” the number of variables. While there are different ways to access request cookies, the main difference between them are that REQUEST_HEADERS:Cookie will include all of the “raw” Cookie data while any of the REQUEST_COOKIES variable values are parsed.

How To Upgrade

Translate rules as follows – Mod 1.x -> Mod 2.x COOKIES -> REQUEST_COOKIES COOKIES_COUNT -> &REQUEST_COOKIES COOKIES_NAMES -> REQUEST_COOKIES_NAMES COOKIES_VALUES -> REQUEST_COOKIES COOKIE_name -> REQUEST_COOKIES:name

Counting Variables

ModSecurity 1.x

ARGS_COUNT COOKIES_COUNT HEADERS_COUNT FILES_COUNT

ModSecurity 2.x

&ARGS &REQUEST_COOKIES &REQUEST_HEADERS &FILES

Notes

In 2.x, prepending the “&” character will count the number of variables. Example – 1.x – HEADERS_COUNT 2.x - &REQUEST_HEADERS

How To Upgrade

Translate existing 1.x rules as listed.

Accessing HTTP Status Code

ModSecurity 1.x

OUTPUT_STATUS

ModSecurity 2.x

RESPONSE_STATUS Phase:3

Notes

In 2.x, you need to specify both the RESPONSE_STATUS variable and phase:3 with the rule.

How To Upgrade

Translate any existing 1.x OUTPUT STATUS rules to use RESPONSE_STATUS and phase:3.

Accessing Response Bodies/Post Payloads

ModSecurity 1.x

SecFilterScanOutput SecFilterOutputMimeTypes OUTPUT

ModSecurity 2.x

SecResponseBodyAccess SecResponseBodyMimeTypes RESPONSE_BODY Phase:4

Notes

In 1.x, neither skipnext nor chain could be used on the OUTPUT location. In 2.x, both actions can be used on RESPONSE_BODY

How To Upgrade

Translate directives/rules as follows – Mod 1.x -> Mod 2.x SecFilterScanOutput -> SecResponseBodyAccess SecFilterOutputMimeTypes -> SecResponseBodyMimeTypes OUTPUT -> RESPONSE_BODY/Phase:4

ModSecurity 1.x

SecFilterCookieFormat SecFilterNormalizeCookies

ModSecurity 2.x

SecCookieFormat

Notes

SecFilterNormalizeCookies is no longer supported as Mod 2.x transformation functions can now be used to normalize all Variables including Cookie data.

How To Upgrade

Change SecFilterCookieFormat to SecCookieFormat. When specifying Cookie variables, then apply the applicable transformation functions in the action field of the rule.

Ability to skip rules

ModSecurity 1.x

skipnext

ModSecurity 2.x

skip

Notes

In Mod 2.x – skip takes into account chained rulesets and treats them as 1 rule. In Mod 1.x – skipnext treated each rule directive as an individual rule regardless of whether or not they were tied together as a chained ruleset.

How To Upgrade

Translate all skipnext rules to skip, however make sure to factor in any chained rulesets that may follow and adjust the skip number accordingly.

Adding/Removing Audit Log Data on a per rule basis

ModSecurity 1.x

logparts

ModSecurity 2.x

clt:auditLogParts=

Notes

The rules function the same.

How To Upgrade

Translate any existing logparts actions to the ctl:auditLogParts equivalent.

Inspecting uploaded files

ModSecurity 1.x

SecUploadApproveScript

ModSecurity 2.x

@inspectFile FILES_TMPNAMES

Notes

The main difference here is that now @inspectFile is an Operator vs. a global Directive. This means that you can apply @inspectFile to individual rules and use different scripts as appropriate. Also, the return codes are now reversed – In 1.x, a return code of “1” means that the file would be allowed. In 2.x, a return code of “1” means that the file would be denied.

How To Upgrade

In order to scan/inspect uploaded files in 2.x, you need to create specific rules that use the FILES_TMPNAMES variable (as these are the names of the files that are temporarily stored on disk) and then use the @inspectFile Operator on each rule. Also, make sure to swap your return codes in existing scripts as mentioned in the notes column.

Memory limits for uploaded files

ModSecurity 1.x

SecUploadInMemoryLimit

ModSecurity 2.x

SecRequestBodyInMemoryLimit

Notes

These two directives function the same.

How To Upgrade

Change the SecUploadInMemoryLimit directive to SecRequestBodyInMemoryLimit.

SecLang specification

The rules language that ModSecurity v2 and libModSecurity v3 implement, usually called SecLang, is also implemented by other engines, most notably OWASP Coraza. Rather than a porting checklist maintained here, the language is specified independently of any engine at https://seclang.org/:

  • The specification describes every directive, variable, operator, action and transformation with its syntax and semantics.
  • The compatibility matrix records, for each item, whether ModSecurity v2, libModSecurity v3 and Coraza implement it, and marks the items that are deprecated. It is the authoritative answer to “will this rule work on engine X” and the source of the lists in Migrating from v2 to v3.
  • The Coraza playground runs a rule against a request in the browser and is a quick way to check syntax before deploying.

If you are porting the language to a new engine, start from the matrix: the items every engine implements (SecRule, SecRuleEngine, the request and response variables, @rx and the numeric operators, the core actions and transformations) are the ones rule sets such as the OWASP CRS depend on everywhere, and the rest can follow the matrix’s deprecation marks.

Development

Contributing to ModSecurity, the roadmap, and related tools.

Subsections of Development

Contributing

ModSecurity was transferred from Trustwave to OWASP in January 2024 and is developed by a small group of maintainers together with the community. Contributions of every kind are welcome: bug reports, fixes, features, tests, packaging, documentation and help for other users. This page explains how the project works and what a good contribution looks like.

Where things happen

Reporting a bug

Open an issue at https://github.com/owasp-modsecurity/ModSecurity/issues after checking that it has not been reported. Include the engine version (2.9.x or 3.0.x), the connector and its version for v3, the web server version, the operating system or package, the smallest rule that reproduces the problem, the request that triggers it, and the relevant debug log at level 9 (SecDebugLogLevel 9). A failing regression test case (see below) is the most useful report of all, since it becomes the test that keeps the bug fixed.

Reporting a security issue

Do not open a public issue, pull request or mailing list thread for a vulnerability. Report it privately through a draft security advisory on GitHub, where the maintainers triage it, coordinate the fix with you and publish the advisory together with the fixed release, crediting the reporter. If you cannot use GitHub, email [email protected]. The current policy is in SECURITY.md.

Proposing a feature

Open an issue describing the problem the feature solves and, if you have one, the SecLang syntax you propose. Both engines are maintained in parallel, so a new directive, variable, operator or action normally has to be implemented in both v2 and v3 and reflected in the SecLang specification; say early which parts you can take on. Discussing the design before writing code saves everyone time.

Sending a pull request

  • Fork the repository and branch from v2/master or v3/master. A fix that applies to both engines is two pull requests, one per branch; link them to each other.
  • One logical change per commit, and nothing outside the scope of the change (no drive-by reformatting). The first line of the commit message says what changed; the body says why and how, since that is what reviewers and future maintainers read.
  • Reference the issue with Fixes #NNN in the pull request description.
  • Add or update tests (see the next section). Pull requests without a test for the change need a reason.
  • CI runs the build and the test suites on Linux (gcc and clang, 32 and 64 bit, with every optional dependency on and off), macOS and Windows, plus cppcheck. All checks must pass; the cppcheck job is the one most often surprised by new code.
  • Expect review comments and a request or two for changes; that is the normal course of a pull request.
  • The release notes are written from the pull requests, so a clear title matters.

Coding guidelines

ModSecurity v2

  • C, built with autotools against the Apache APR and httpd headers; the module must keep building against Apache 2.4 and the IIS module in iis/ against Visual Studio (CMake).
  • Memory comes from APR pools; follow the existing allocation pattern of the function you are changing and never mix pool and malloc memory.
  • New directives are registered in apache2/apache2_config.c, variables in apache2/re_variables.c, actions in apache2/re_actions.c, operators in apache2/re_operators.c and transformations in apache2/re_tfns.c; each registry entry needs a unit test under tests/ and an entry in this documentation.
  • Keep changes free of compiler warnings and run make test (unit tests via tests/msc_test) and make test-regression (the Apache-based regression suite, which needs a local httpd) before sending.

libModSecurity v3

  • C++17, built with autotools (./build.sh, ./configure, make), CMake on Windows. The code follows the Chromium C++ style that the project adopted; make check-static runs cppcheck and cpplint is part of the lint target.
  • The SecLang grammar lives in src/parser/seclang-scanner.ll and src/parser/seclang-parser.yy; the generated parser is committed, so regenerate it with ./configure --enable-parser-generation (Flex and Bison required) and commit the result together with the grammar change.
  • Operators are classes under src/operators/, transformations under src/actions/transformations/, actions under src/actions/, variables under src/variables/. Each is registered in the parser and, for operators and transformations, in the factory in operator.cc or transformation.cc.
  • The public API lives in headers/modsecurity/; changes there affect every connector and binding, so keep binary compatibility whenever possible and say so in the pull request when you cannot.
  • Use assertions for invariants and build with --enable-assertions while developing; CFLAGS="-g -O0" gives readable backtraces in gdb and Valgrind.

Tests

Both trees carry their tests in the repository and in the shared secrules-language-tests submodule, so a clone needs git submodule update --init --recursive.

  • v2: make test builds tests/msc_test and runs the unit tests in tests/op/*.t, tests/tfn/*.t and tests/action/*.t (Perl hashes with input, output and ret). make test-regression runs tests/regression/*.t through a local Apache httpd.
  • v3: make check builds and runs test/unit_tests (JSON cases under test/test-cases/unit/) and test/regression_tests (JSON cases under test/test-cases/regression/, each a request, a response, the rules to load and the expected http_code, debug_log, error_log, audit_log or parser_error). A single file can be run with test/regression_tests test/test-cases/regression/<file>.json, and test/benchmark measures throughput against a rule set.
  • A new operator or transformation needs a unit test; any other change is expected to come with a regression test that fails before the fix and passes after it. State in the pull request that you ran it both ways.

Documentation

This site is built with Hugo from Markdown in the documentation repository; hugo serve renders it locally. Every reference-manual entry carries metadata saying in which v2 and v3 versions it is available, so a code change that adds, removes or alters a directive, variable, action, operator or transformation should come with a pull request here, and corrections to the text are welcome on their own. The conventions (American English, the secmeta block, the seclang code fences formatted per the CRS guidelines) are described in the repository’s CLAUDE.md and enforced by its CI.

Packaging and bindings

Packages for the major distributions and the digitalwave repository are maintained by community members and the maintainers; if you package ModSecurity for another distribution, tell the project so it can be listed. The same goes for bindings to libModSecurity: the C and C++ API is kept stable so that bindings keep working across releases.

Roadmap

ModSecurity has no separate roadmap document. Planned work, release targets and open design questions are tracked in the open on GitHub, where you can comment and vote:

Both engines are maintained: v2 for Apache httpd and IIS, v3 as the library behind the NGINX connector. There is no plan to retire v2, and features are added to both when they make sense on both; the compatibility matrix of the SecLang specification shows where they differ. Larger discussions happen on the OWASP Slack in #project-modsecurity and at the project’s monthly community calls announced there; see Contributing.

The roadmap that used to live on this page described the goals of the 2.6 to 3.0 era (stream inspection, IP reputation, data modification, the connector architecture); all of it has either shipped or been superseded.

Tools

Tools that are useful when writing, testing and operating ModSecurity rules. Projects are listed with the organization that maintains them; the OWASP CRS project and the digitalwave team (one of the ModSecurity maintainers) produce most of the current tooling.

Rule sets

  • OWASP CRS - the rule set almost every ModSecurity deployment runs. Repository, documentation, plugin registry for application-specific exclusions (WordPress, Nextcloud, Drupal, phpBB, phpMyAdmin, DokuWiki, cPanel, XenForo) and add-ons such as the DoS-protection, antivirus, body-decompress, fake-bot and auto-decoding plugins.
  • Comodo free ModSecurity rules - a commercial vendor’s free rule set.

Writing and checking rules

  • SecLang specification - the engine-independent specification of the rules language, with a compatibility matrix for ModSecurity v2, libModSecurity v3 and Coraza.
  • Coraza playground - run a rule against a request in the browser.
  • crs-toolchain - the CRS developers’ command-line tool: assembles regular expressions from .ra files, renumbers and updates rules. Installable from the CRS Homebrew tap.
  • crs-linter - checks rules files against the CRS formatting and naming conventions.
  • msc_pyparser - a Python parser for SecLang that produces an abstract syntax tree and writes rules back, for bulk edits, linting and analysis.
  • secrules_parsing and seclang_parser - the CRS project’s Python and ANTLR parsers for the language.
  • msc_retest - measures how long a regular expression takes in the PCRE and PCRE2 engines, for spotting patterns that are slow or vulnerable to regular-expression denial of service.
  • vscode-language-modsecurity - SecLang syntax highlighting for Visual Studio Code, and regexp-assemble-syntax for the .ra files.

Testing rules and engines

  • go-ftw - the Framework for Testing WAFs: sends the HTTP requests described in YAML test files to a web server running ModSecurity and checks the logs for the expected rule matches. It is how the CRS test suite runs; the YAML format is defined by ftw-tests-schema. The older Python ftw is no longer developed.
  • ftwrunner - runs the same FTW test files directly against libModSecurity, without a web server.
  • secrules-language-tests - the regression test cases shared by ModSecurity v2 and v3 (a git submodule of the engine) that any SecLang implementation can use to check itself.
  • MRTS - the ModSecurity Regression Test Set.
  • modsecurity-crs-docker - the official container images with ModSecurity v2 on Apache httpd or libModSecurity on NGINX and the OWASP CRS preinstalled, the quickest way to get a test instance.
  • The engine’s own test tools: tests/msc_test and run-unit-tests.pl in the v2 tree, test/regression_tests, test/unit_tests and test/benchmark in the v3 tree (see Contributing).

Working with logs

  • libmsclogparser - a C library (with Python bindings) that parses ModSecurity audit and error log entries.
  • modsecurity-parser - analyzes native and JSON audit logs and produces JSON, Excel and chart summaries.
  • ModSecurity-log-utilities - command-line tools from the former maintainer that turn audit logs into summaries.
  • logstash-modsecurity - Logstash filters for the native audit log format. With SecAuditLogFormat JSON most log pipelines need no special parser.
  • modsec-sdbm-util - inspects and shrinks the SDBM files that ModSecurity v2 uses for persistent collections.
  • WAF-FLE - a web console for audit logs; no longer maintained but still used.

Integrating the engine

Archive

Historical pages kept for reference. Their content is not maintained.

Subsections of Archive

Google Summer of Code 2016 ideas

Below are a number of suggestions for students interested in the ModSecurity project during Google Summer of Code. These are just suggestions, feel free to submit your own proposal. If you are looking for more information (or just someone to talk to about ideas) feel free to email security [at] modsecurity.org, join #Modsecurity on freenode, join the mailing lists, or open a github ticket! We look forward to working with you.

  • @csanders-git and @zimmerle

###ModSecurity Ruby support Brief explanation: Adding the capability of rapid prototyping to ModSecurity functionalities through scripts will open the possibility for easy rules production and customization, It also opens the possibility for a large community such as Ruby developers to create their own customization on the top of ModSecurity and so customize their own rules, analogous of today’s Lua support. Expected results: An implementation able to handle Ruby scripts which will interact to ModSecurity as Lua does. References:

###ModSecurity JavaScript support Brief explanation: Adding the capability of rapid prototyping to ModSecurity functionalities trough scripts will open the possibility for easy rules production and customization, It also opens the possibility for a large community such as JavaScript developers to create their own customization on the top of ModSecurity and so customize their own rules, analogous of today’s Lua support. Expected results: An implementation able to handle JavaScripts scripts which will interact to ModSecurity as Lua does. References:

  • ModSecurity Reference Manual, Lua:/docs/3-reference-manual/3-2-configuration-directives/#secrulescript"

###ModSecurity connector for node.js Brief explanation: As of ModSecurity version 3, ModSecurity is splited into core and connectors. The connector, as the name suggests, create an interface between the webserver (or other ModSecurity comsumer) to the libModSecurity. By create a connector the target application will be able to apply ModSecurity inspections and actions. The idea of this project is to extend node.js to add ModSecurity support to it. Expected results: A connector which will allow ModSecurity to be used inside node.js References:

###ModSecurity connector for Apache Brief explanation: As of ModSecurity version 3, ModSecurity is splited into core and connectors. The connector, as the name suggests, create an interface between the webserver (or other ModSecurity comsumer) to the libModSecurity. By create a connector the target application will be able to apply ModSecurity inspections and actions. The idea of this project is to extend Apache to add ModSecurity v3 support to it. Notice: ModSecurity version 2.x is avalable inside Apache, but not v3 Expected results: A workable but no feature complete connector which will allow ModSecurity v3 to be used inside Apache References:

###ModSecurity Data persistance layer Brief explanation: Currently ModSecurity can write audit logs to a file or support logging via a callback function. While this is fantastic if you are building a connector for ModSecurity v3 it doesn’t work well if you are an end user. The suggestion is to build a modular system that allows for new persistence layers (mySQL, ElasticSearch, Web Request, File) to be added quickly in plugin format. The connection details would be supplied by the user via new ModSecurity Directives. This would replace older less extendable methods such as mlogc Expected results: An implementation that has hooks for various persistence platforms as well as a few example plugins

###ModSecurity Unicode Correctness Brief explanation: Currently ModSecurity has a number of open issues regarding the parsing of Cyrillic characters. It is unclear if this is a problem with how CRS rules are written or the underlying PCRE engine. This project requires investigating how regular expressions with non-ASCII characters should be handled specifically what the ramifications of switching to the Oniguruma, RE2, or other regex platform. Expected results: An implementation that can properly handle all unicode characters

###ModSecurityv3 Streaming Brief explanation: Currently ModSecurity attempts to buffer whole communications before processing them. The current trend within HTTP (HTTP/2) is to use streams for communication. Switching ModSecurity to this model presents some issues but overall will offer better performance and more future proofing Expected results: An implementation that treats HTTP Requests and Responses and streams instead of buffering them

###ModSecurityv3 IDS connector Brief explanation: IDSs like snort support web in a limited way. With the advent of V3 it is possible to put modsecurity into these in a full form. This will allow these other open source projects to leverage a single web parsing framework for better results Expected results: An implementation of Snort that supports ModSecurity parsing

###ModSecurity Icap Connector Brief explanation: Adding the capability to connect to a an external malware scanner or content filter via the icap protocol. Antivirus functionality is usually added via the directive @inspectFile, which will then fork a process, or via mod_lua. A proper icap interface would simplify things. Expected results: An interface / directive to interact with a icap enabled scanner / content filter References:

###ModSecurity transformation functions: allow parameters
Brief explanation: Currently, transformations cannot use parameters. This would allow more flexibility.
Expected results: Support parameters
t:encrypt(%{TX.mykey}%)

###ModSecurity sub-phases Brief explanation: ModSecurity supports real phases 1-4 and the ‘virtual’ one 5. Having intermediate virtual phases, like phase:2.2, would allow to order rules inside a real phase. This is especially useful for configurations integrating rules provided, for example, by a hoster and customs ones.
Expected results: Rules will be ordered, inside a phase, not only based on their occurence but also based on their sub-phase.
References: https://github.com/SpiderLabs/ModSecurity/issues/371
Example:

  • SecRule … phase:2.6,id:1
  • SecRule … phase:2,id:2
  • SecRule … phase:2.3,id:3
    Execution order: 2, 3, 1

###ModSecurity Engine-Mode status Brief explanation: Engine-Mode status is not available for testing nor using (logging in msg, assigning as value).
Expected results: A variable “ENGINE-MODE” could be added.

libModSecurity v3 early release-candidate notes

What is the version 3 earlier release candidate

ModSecurity version 3 (earlier-rc1) was not released yet. This wikipage highlights the most important differences between ModSecurity version 2 and v3-erc1 (earlier release candidate 1) [to be released].

The earlier release candidate of ModSecurity version 3 does not target all the features from version 2. Instead, it is targeting to fully support the “OWASP Core Rules Set version 3”. Some of the missing pieces have a very low audience, and they will be target in the upcoming releases candidates. The missing pieces are listed in this wikipage.

Collections update interval.

ModSecurity’s persistent collections are saved per thread (or process). From time to time the different values from each thread (or process) are merged into a global storage. A simple counter (for instance: IP:counter) will have different values for the different web server “workers”, depending on the process that answers the request. That behavior happens in both versions of ModSecurity (2 and 3). But, the time that is expected to merge the collections is higher in ModSecurity version 2. In practical aspect it means that in ModSecurity version 3 the values for the threads should me more precise.

Another important point to notice is the fact that ModSecurity version 3 does not expire the values for the collections. The collection was built to be very small, thus no need to expire. The expiration maybe taken in care by the backend, once it considers the database to be bigger than expected.

Missing pieces (Towards version 3 feature complete).

All the missing features belong to a milestone: Feature complete. This milestone can be listed here: https://github.com/SpiderLabs/ModSecurity/milestone/9 For easy reading, they are also listed below.

Actions

Variables

Operators

Others

What we don’t want to support anymore

The list of unsupported features is very minimal at this point, although it may be bigger till the feature complete milestone. The single item is listed below.