modsecurity.conflooks like the following code:
Now, let’s look at some basic configuration directives:
SecFilterEngine: When set to On (that is,
SecFilterEngine On), it starts monitoring requests. It is
Off(disabled) by default.
On, enables scanning the request body/POST payload.
On, enables scanning the response body also.
Similarly, to check URL encoding, you can use
SecFilterCheckURLEncoding; to control request body buffering, use
SecRequestBodyAccess; to control what happens once the response body limit is reached, use
SecResponseBodyLimitAction; and to specify the response body buffering limit, use
The full list of configuration directives, their usage and syntax is at available on modsecurity.org.
Rules — the basics
mod_securityrule engine is where gathered data is checked for any malicious or particular content. Rules are directives in the configuration file that decide what to do with the data parsed by the configuration directives. The rule language is a vast topic; we’ll only discuss basic rule-writing syntax, and rule directives to secure Web applications from all the attacks we’ve discussed so far.
The main directive used to create rules is
SecRule, whose syntax is as follows:
VARIABLES: Specify which places to check in an HTTP transaction.
mod_securitypreprocesses raw transaction data, making it easy for rules to focus on the logic of detection. Currently, variables are divided into request, server, and response variables, parsing flags and time variables. You can use multiple variables in a single rule with the
OPERATORS: Specify a regular expression, pattern or keyword to be checked in the variable(s). There are four types of operators: string-matching, numerical, validation and miscellaneousoperators. Operators always begin with a
@character, and are always followed by a space.
ACTIONS: Specify what to do if the rule evaluates to “true” — step on to another rule, display an error message, or any other task. Actions are divided into seven categories: disruptive,flow, metadata, variable, logging, special and miscellaneous actions.
Here is a simple example of a rule:
REQUEST_HEADERSare variables (request parameters and request headers, respectively);
@rxis the operator used to match a pattern in the variables (here, this pattern is
statusare all actions to be performed if the pattern is matched. This rule is used to avoid XSS attacks by checking for a
<scriptpattern in the request parameters and header, and generates an
'XSS Attack'message. The
id:101is given to the rule; it will deny any matching request with a
Let’s look at another example, for more clarity:
This is an example of chaining two rules, and the transfer of control to another rule if the first rule holds true. The first rule checks for the string admin in the request’s username parameter. If found, the second rule will be activated, which denies all such requests that are not from the
192.168.1.1IP address. Thus, chaining rules help to create complex rules.
Now, writing filtering rules for each attack will be very cumbersome, and also prone to human error. Here,
mod_securityprovides users with another directive,
SecFilter. This looks for a keyword in the request. It will be applied to the first line of the request (the one that looks like
GET /index.php?parameter=value HTTP/1.0). In case of POST requests, the body of the request will be searched too (provided request body buffering is enabled). All pattern matches are case-insensitive, by default. The syntax for
Rules against major attacks
Let’s look at some rules to prevent major attacks on Web applications.
Suppose you have an application that is vulnerable to SQL-injection attacks. An attacker could try to delete all records from a MySQL table, like this:
This can be prevented with the following directive:
Whenever such a request is caught by the filter, something similar to the following code is logged to
In response to the attack,
SecFilterDefaultActionis applied (the request is denied, logged, and the attacker gets a
500error). If you want a different action to take place (like, redirect the request to a HTML page that can provide customised warning content), you can specify this in the rule, as follows:
To prevent more SQL injection attacks, we can add a few other directives like:
The last five are particularly used for MS SQL server-specific injection attacks.
The only problem with
SecFilteris that it scans the whole request instead of particular fields. Here,
SecFilterSelectiveis useful; it allows you to choose exactly what to search. The syntax is:
LOCATIONdecides which area of the request to be filtered. Hence, for SQL injection, you can also use:
The above code will validate the user parameter, and allow only the white-list of characters we have given. If for some reason you cannot take this approach, and must use a deny-what-is-badmethod, then at least remove single quotes (
'), semicolons (
;), dashes, hyphens (
-), and parenthesis (
For XSS attacks, we can use the following directives:
And also, some additional filters like:
Though these filters will detect a large number of XSS attacks, they are not foolproof. Due to the multitude of different scripting languages, it is possible for an attacker to create many different methods for implementing an XSS attack that would bypass these filters. Hence, here it is advised that you also keep on adding your own filters.
To protect against an XSS attack done via PHP session cookies, you can use the following:
Command execution attacks
For command execution attacks, you can use the following directives:
Here, the attacker may try to use a string like
/bin/./shto bypass the filter — but
/, and also decodes URL-encoded characters. You can also use the white-list approach:
This chained rule-set will only allow letters, numbers, underscore, dash, forward slash, and period in the
dirparameter. Filtering out command directory names is also a good option, and can be done as follows:
During session fixation, in one of its phases, the attacker needs to somehow inject the desired session ID into the victim’s browser. We can mitigate these issues by implementing the following:
Directory traversal attacks
For path/directory traversal attacks, the following directives are mostly used:
The last two filters are chained, and will reject all parameters to the
homeargument that is a filename of more than 15 alpha characters, and that doesn’t have a
Similarly, you can prevent predictable resource location attacks also, and protect against sensitive file misuse, with two recommended solutions. First, remove files that are not intended for public viewing from all Web server-accessible directories. After this, you can create security filters to identify if someone probes for these files:
These two filters will deny access to both — unused, but commonly scanned for directories, and files with common backup extensions.
Web pages that are dynamically created by the directory-indexing function will have a title that starts with “Index of /”. We can use this as a signature, and add the following directives to catch and deny access to this data:
Here, we are introduced to the OUTPUT filtering capabilities of mod_security, which you should enable by adding
SecFilterScanOutput Onin the configuration file. We can easily set up a filter to watch for common database error messages being sent to the client, and then generate a generic 500 status code instead of the verbose message:
Output filtering can also be used to detect successful intrusions. These rules will monitor output, and detect typical keywords resulting from a command execution on the server.
Secure file uploads
mod_securityis capable of intercepting files uploaded through POST requests and multi-part/form-data encoding through PUT requests. It will always upload files to a temporary directory. You can choose the directory using the
It is better to choose a private directory for file storage, somewhere that only the Web server user account is allowed access. Otherwise, other server users may be able to access files uploaded through the Web server. You can choose to execute an external script to verify a file before it is allowed to go through to the application. The
SecUploadApproveScriptdirective enables this, like the following example:
RFI attacks are generally easy to detect, with something like the following directive:
Miscellaneous security features
You can also block IP addresses by the following command:
If you have an input field URL in your comment form, and you want to scan the value of URL for the string
c99, you do it as follows:
The following configuration helps fight HTTP fingerprinting, and accepts only valid protocol versions:
The following configuration allows supported request methods only, and helps fight XST attacks:
Often during the reconnaissance phase, attackers look for the Web server identity and version. Web servers typically send their identity with every HTTP response, in the Server header. Apache is particularly helpful here; it not only sends its name and full version, by default, but also allows server modules to append their versions. Here, you can confuse the attackers by using something like:
PHP code cannot be injected directly, but it may be possible to have code recorded on disk to be executed later, using an LFI attack. The following rule will detect such an injection attempt, but will ignore XML documents, which use similar syntax:
There are three places where, depending on the configuration, you may find
mod_securitydebug log: If enabled via the
SecFilterDebugLogdirectives, it contains a large number of entries for every request processed. Each log entry is associated with a log level, which is a number from 0 (no messages at all) to 4 (maximum logging). You normally keep the debug log level at 0, and increase it only when you are debugging your rule set.
- Apache error log: Some of the messages from the debug log will make it into the Apache error log (even if you set
mod_securitydebug log level to 0). These are the messages that require an administrator’s attention, such as information about requests being rejected.
mod_securityaudit log: When audit logging is enabled (using the
mod_securitycan record each request (and its body, provided request body buffering is enabled) and the corresponding response headers.
Here is an example of an error message resulting from invalid content discovered in a cookie:
The message indicates that the request was rejected (“Access denied”) with an HTTP
500response because the content of the cookie sessionid contained content that matched the pattern
!(^$|^[a-zA-Z0-9]+$). (The pattern allows a cookie to be empty, but if it is not, it must consist only of one or more letters and digits.)
Note: I once again stress that neither LFY nor myself are responsible for the misuse of the information given here. Any attack techniques described here are meant to give you the knowledge that you need to protect your own infrastructure. Please use the tools and techniques sensibly.
This article has just scratched the surface of
mod_security. For more details on rule writing and other important directives, please refer to ModSecurity Handbook by Ivan Ristic — a must-read book for anyone interested in this topic.
We will deal with other ways to secure Apache in the next article. Always remember: Know hacking, but no hacking.