Blogs & Stories

SpiderLabs Blog

Attracting more than a half-million annual readers, this is the security community's go-to destination for technical breakdowns of the latest threats, critical vulnerability disclosures and cutting-edge research.

ModSecurity 2: Variables, Collections and Transaction Scoring

Variables and collections are concepts new to ModSecurity 2. ModSecurity 1.x does allow you to use the "setvar" and "setnote" actions to create, change, or remove the request environment variables and request notes (request notes are an Apache facility that can be used to communicate with other modules). In v2 the concept was further extended with the introduction of transaction variables.

Variables are grouped into a collection, which is essentially a separate name space you can work with. Transaction variables are part of the transaction collection, which is a built-in collection called "TX". This collection is created automatically in the request initialisation phase and thus always available to your rules. It is also automatically deleted at the end of each request. ModSecurity 2 also supports persistent collections (variables placed in them will be available to you across requests) but in order to use them you have to manage them manually. This is something I will cover in a separate blog post shortly.

Collection variables are manipulated with the "setvar" action. To create a new variable simply assign value to it. To delete it, prefix the name with an exclamation mark. You must prefix each variable name with the name of the collection it belongs to.

setvar:tx.score=10 setvar:!tx.score

There are two variable types: strings and counters. Strings are just text; you can create them, access them, or delete them. Counters are positive integers. In addition to the operations supported by the sting variable type, counters can be incremented or decremented.

setvar:tx.score=+5 setvar:tx.score=-10

Transaction variables allow you to employ a fundamentally different approach in your rule sets. In ModSecurity 1.9.x. you could either interrupt a transaction or issue a warning. In ModSecurity 2 you can use scoring-based rule sets. The idea is to assign a score to every transaction and set it to zero initially. Then you write a series of rules to inspect transactions. But you don't want the rules to interrupt transactions straight away. Instead, you want them to just increment the transaction score. At the end of your rule set you can evaluate the transaction score and decide what to do with the transaction. Here is a complete example:

# A series of rules to evaluate transaction SecRule ARGS KEYWORD1 pass,setvar:tx.score=+5 SecRule ARGS KEYWORD2 pass,setvar:tx.score=+5 SecRule ARGS KEYWORD3 pass,setvar:tx.score=+5 SecRule ARGS KEYWORD4 pass,setvar:tx.score=+5   # Decide what to do with transaction SecRule TX:SCORE "@gt 15" deny