Book Image

ModSecurity 2.5

Book Image

ModSecurity 2.5

Overview of this book

With more than 67% of web servers running Apache and web-based attacks becoming more and more prevalent, web security has become a critical area for web site managers. Most existing tools work on the TCP/IP level, failing to use the specifics of the HTTP protocol in their operation. Mod_security is a module running on Apache, which will help you overcome the security threats prevalent in the online world. A complete guide to using ModSecurity, this book will show you how to secure your web application and server, and does so by using real-world examples of attacks currently in use. It will help you learn about SQL injection, cross-site scripting attacks, cross-site request forgeries, null byte attacks, and many more so that you know how attackers operate. Using clear, step-by-step instructions this book starts by teaching you how to install and set up ModSecurity, before diving into the rule language with examples. It assumes no prior knowledge of ModSecurity, so as long as you are familiar with basic Linux administration, you can start to learn right away. Real-life case studies are used to illustrate the dangers on the Web today ñ you will for example learn how the recent worm that hit Twitter works, and how you could have used ModSecurity to stop it in its tracks. The mechanisms behind these and other attacks are described in detail, and you will learn everything you need to know to make sure your server and web application remain unscathed on the increasingly dangerous web. Have you ever wondered how attackers figure out the exact web server version running on a system? They use a technique called HTTP fingerprinting, and you will learn about this in depth and how to defend against it by flying your web server under a "false flag". The last part of the book shows you how to really lock down a web application by implementing a positive security model that only allows through requests that conform to a specific, pre-approved model, and denying anything that is even the slightest bit out of line.
Table of Contents (17 chapters)
ModSecurity 2.5
Credits
About the Author
About the Reviewers
Preface
Directives and Variables
Index

Directives


This section contains a list of the directives available for use in your ModSecurity configuration file. These directives can be used in the main Apache configuration file, but as we have seen in previous chapters, placing your ModSecurity directives in a separate file is recommended as this makes it much easier to maintain your configuration.

SecAction

SecAction lets you unconditionally execute actions. This essentially makes it a SecRule statement without the conditional part.

Syntax: SecAction action1,action2,action3
Example: SecAction setuid:%{REMOTE_USER},nolog

SecArgumentSeparator

Specifies which character to use as a separator in forms and other content that uses the MIME type application/x-www-form-urlencoded. Also used to determine the separator in query strings. Most applications use the default value of & as the separator, but some may use another character.

Syntax: SecArgumentSeparator "<character>"
Example: SecArgumentSeparator ";"
Default value: "&"

SecAuditEngine

Turns the audit engine on or off, or configures it to log only relevant requests.

Syntax: SecAuditEngine On|Off|RelevantOnly
Example: SecAuditEngine On

In the On setting, all transactions are logged, while in the Off setting the audit engine is disabled and no audit logging is performed. When the RelevantOnly setting is used, transactions logged are limited to those that have generated an error or a warning, or that have a status code that matches the regular expression provided to the SecAuditLogRelevantStatus directive.

See Chapter 4, Logging and Auditing for more on audit logging.

SecAuditLog

Sets the path to the audit log file. Also used to configure mlogc to send audit logs to a ModSecurity console.

Syntax: SecAuditLog <path to file>
Example: SecAuditLog logs/modsec_audit.log

If you are using the ModSecurity Log Collector (mlogc) to send data to a ModSecurity Console, then the SecAuditLog directive is used in the following manner to send data to the console using mlogc:

SecAuditLog "/usr/local/bin/mlogc /etc/mlogc.conf"

This causes ModSecurity to invoke mlogc and pass the audit log data to it. The data will then be sent to the ModSecurity Console, provided that you have configured mlogc correctly (see Chapter 4, Logging and Auditing for more information on this).

SecAuditLog2

Sets the path to a second audit log index file when concurrent logging is used.

Syntax: SecAuditLog2 <path to file>
Example: SecAuditLog2 logs/modsec_audit2.log

SecAuditLogParts

Determines what information is included with each audit log entry. Each part is represented by a character, as described in the following table below. The audit log header (A) and trailer (Z) are mandatory and must be included with each log entry.

Syntax: SecAuditLogParts <parts>
Example: SecAuditLog ABCFHZ

Character

Description

A

Audit log header

Boundary that signifies the start of the audit log entry.

Contains the time and date stamp of the log entry as well as the client and server IP address. Also contains the unique ID for the log entry, which makes it easy to find the request in the Apache log files.

This option is mandatory and will be implicitly included if you don't specify it.

B

Request headers

Contains all of the headers in the request, as sent by the client.

C

Request body

Contains the request body. Only available if request body access is enabled in ModSecurity.

E

Response body

Contains the response body of the request. Only available if response body access is enabled in ModSecurity. If the request was denied by a rule, this instead contains the error page sent to the client.

F

Response headers

Contains the response headers, excluding the date and server headers as these are added late in the response delivery process by Apache.

H

Audit log trailer

Contains information on whether the request was allowed or denied, and with what HTTP status code as well as the ModSecurity message as it appears in the Apache error log. Also contains a timestamp and the server string (as it would appear without any of the modifications that may have been made to it using SecServerSignature).

I

Request body without files

Contains the same information as C—the request body—except when the encoding used is multipart/form-data, in which case this will exclude any encoded files in the POST data.

K

Matched rules

A list of all rules that matched this event, one per line, in the order that the rules matched. Each listed rule includes any default action lists.

Z

End of audit log entry

Boundary that signifies the end of the audit log entry. This option is mandatory and will be implicitly included if you don't specify it.

SecAuditLogRelevantStatus

A regular expression for the HTTP response code that determines which requests to log when SecAuditEngine is set to RelevantOnly.

Syntax: SecAuditLogRelevantStatus <regular expression>
Example: SecAuditLogRelevantStatus ^(4|5)

SecAuditLogStorageDir

Specifies the directory where ModSecurity stores each individual audit log entry file when SecAuditLogType is set to Concurrent. Make sure the directory exists and is writable by the Apache user.

Syntax: SecAuditLogStorageDir <directory>
Example: SecAuditLogStorageDir /var/log/httpd/audit

SecAuditLogType

Sets the type of audit logging to use. This can be either Serial or Concurrent. In serial mode, all audit log data is stored in a single file whereas in concurrent mode, each log entry is stored in a separate file, and the main audit log file is used as an index for the individual files for each request. Concurrent logging is required if you want to send audit log data to a ModSecurity console.

Syntax: SecAuditLogType Serial|Concurrent
Example: SecAuditLogType Concurrent
Default value: Serial

If concurrent logging is used, you must use SecAuditLogStorageDir to specify the directory where ModSecurity should store the individual log entry files.

SecCacheTransformations (deprecated/experimental)

This directive enables or disables caching of transformations. Transformation caching can potentially speed up rule processing, however this feature is off by default as of version 2.5.6 of ModSecurity and is marked as experimental.

Syntax: SecCacheTransformations On|Off [options]
Example: SecCacheTransformations On "minlen:0,maxlen:256"
Default value: Off

Transformation caching, when enabled, is done on a per transaction basis. Following the On or Off statement, a number of options can be provided in a comma-separated list. These options control what transformations are cached, and the maximum number of transformations in the cache. The following options are available:

  • incremental:on|off

    Setting incremental to on will cache every intermediate transformation as well as the final transformation. If set to off, only the final transformation is cached.

  • maxitems:n

    Sets the maximum number of transformations to be cached. After this number of transformations have been cached, no further caching will take place.

  • minlen:n

    Sets the minimum length of a transformation for it to be considered for caching.

  • maxlen:n

    Sets the maximum length of a transformation for it to be considered for caching.

SecChrootDir

Changes the root directory of the Apache process to the specified directory. This creates a "jail" for the Apache process, making it much more difficult for any attacker who is able to exploit a vulnerability in the web application or the web server to gain further access to the server. See Chapter 7, Chroot Jails for a complete explanation of chroot jails and the SecChrootDir command.

Syntax: SecChrootDir <new root directory>
Example: SecChrootDir /chroot

SecComponentSignature

This directive appends an additional signature to the ModSecurity version string. This makes it possible for creators of independent rulesets to make the inclusion of the ruleset known since the component signature will be visible in the audit and debug logs.

Syntax: SecComponentSignature <signature>
Example: SecComponentSignature "ModSecurity Book Rules/1.0"

SecContentInjection

Enables injection of content into the data that is output by the web server. Content can be injected either at the start of the output, using the prepend action, or at the end of the output, using the append action.

Syntax: SecContentInjection On|Off
Example: SecContentInjection On
Default value: Off

SecCookieFormat

Set the cookie format used. This is either the original Netscape format cookies (when the value 0 is provided) or as defined by RFC 2109 (when the value 1 is provided). Most applications use old format cookies, and the default is set to 0.

Syntax: SecCookieFormat 0|1
Example: SecCookieFormat 0
Default value: 0

SecDataDir

Sets the directory where ModSecurity can store persistent data, such as collections pertaining to IP addresses and sessions. This kind of data is created when the initcol, setsid, and setuid actions are used. Make sure that the directory exists and is writable by the Apache user.

Syntax: SecDataDir <directory>
Example: SecDataDir /usr/local/apache/modsec_data

SecDebugLog

Specifies where to store the debug log. This can be a relative path, in which case it is relative to the Apache base directory (for example, if you specify SecDebugLog logs/msd.log and the Apache base directory is /etc/httpd, then the log file will be stored in /etc/httpd/logs/msd.log).

Syntax: SecDebugLog /path/to/modsec_debug.log
Example: SecDebugLog /var/log/httpd/modsec_debug.log

SecDebugLogLevel

Configures the verbosity of the debug log. A value of 0 means no debug log data is recorded while a value of 9 provides the maximum amount of debug information.

Syntax: SecDebugLogLevel 0..9
Example: SecDebugLogLevel 4
Default value: 0

SecDefaultAction

Specifies the default action to take when a rule matches. This is a comma-separated list of actions that are essentially prepended to all rules and will be performed when a rule matches. This means that if SecDefaultAction is specified and a rule without its own action list matches, the default actions will still be taken.

Most rulesets will specify a default action of deny, to make sure that requests will be denied if a rule matches. The default action is overridden by any actions specified in a rule, so even with a default action of deny in place, an allow or pass in a rule will take precedence over the default action.

Syntax: SecDefaultAction <action list>
Example: SecDefaultAction "phase:2,deny,log,auditlog"
Default value: "phase:2,log,auditlog,pass"

SecGeoLookupDb

Path to the database file containing information to match IP addresses to geographical locations. For an example on how to use this, refer to Chapter 2.

Syntax: SecGeoLookupDb <path to file>
Example: SecGeoLookupDb /usr/local/geoip/GeoIP.dat

SecGuardianLog

Allows ModSecurity to interact with the httpd-guardian script to detect and block denial of service attacks. This script was developed by Ivan Ristic, and will block clients that request an excessive amount of pages from the server (more than 120 requests in a minute or 360 requests in five minutes).

Syntax: SecGuardianLog "|/path/to/httpd-guardian"
Example: SecGuardianLog "|/etc/httpd/apache/httpd-guardian"

SecMarker

Sets a marker in the ruleset for use with the skipAfter action. You can think of a SecMarker as a rule that only contains an id and has no other effect.

Syntax: SecMarker <id>
Example: SecMarker 1000

SecPdfProtect

Enables cross-site scripting protection for PDF files. See the PDF XSS Protection section in Chapter 6 for more information on this and details on the vulnerability it protects against.

Syntax: SecPdfProtect On|Off
Example: SecPdfProtect On
Default value: Off

When set to On, you also need to configure SecPdfProtectMethod and SecPdfProtectSecret.

SecPdfProtectMethod

Sets the method to use for PDF XSS protection. You can choose between TokenRedirection and ForcedDownload. When set to TokenRedirection, attempts to access a PDF file will result in a redirection to protect against cross-site scripting attacks. Read more about this in the PDF XSS Protection section of Chapter 6. When the ForcedDownload setting is used, ModSecurity sets the MIME type of PDF files that are accessed to application/x-octet-stream, which causes browsers to download the file instead of allowing users to view it embedded in a page. This also protects against the cross-site scripting vulnerability, but will cause some inconvenience to visitors of your site, as they will no longer be able to view PDF files from within their browser.

Syntax: SecPdfProtectMethod TokenRedirection|ForcedDownload
Example: SecPdfProtectMethod TokenRedirection
Default Value: TokenRedirection

SecPdfProtectSecret

Sets the secret to use for PDF cross-site scripting protection. This is used to generate the unique tokens involved in the redirection that takes place when PDF protection is enabled. You can use any reasonably long string you like (16 characters or more is good).

Syntax: SecPdfProtectSecret <string>
Example: SecPdfProtectSecret ILoveModSecurity

SecPdfProtectTimeout

Defines the timeout to use for PDF protection tokens. After the timeout, the tokens expire and can no longer be used to view PDF files embedded in the browser—they will instead be offered as downloads.

Syntax: SecPdfProtectTimeout <timeout>
Example: SecPdfProtectTimeout 20
Default value: 10

SecPdfProtectTokenName

The name of the token used to protect PDF files.

Syntax: SecPdfProtectTokenName <string>
Example: SecPdfProtectTokenName "pdftok"

SeqRequestBodyAccess

Controls processing of request bodies. If set to On, request bodies will be buffered and available for processing in ModSecurity. If set to Off, no request body buffering takes place.

Syntax: SeqRequestBodyAccess On|Off
Example: SeqRequestBodyAccess On
Default value: Off

SecRequestBodyLimit

Configures the maximum size of a request body. Any request with a body over this limit will be rejected with status code 413—Request Entity Too Large. The default value is 128 MB, and ModSecurity has a hard-coded limit of 1 GB.

Syntax: SecRequestBodyLimit <Number of Bytes>
Example: SeqRequestBodyLimit 64000000
Default value: 134217728 (128 MB)

SecRequestBodyNoFilesLimit

Sets the maximum size of request bodies that ModSecurity will accept for buffering when any files included in the request are excluded.

Syntax: SecRequestBodyNoFilesLimit <size in bytes>
Example: SecRequestBodyLimit 131072
Default value: 1048576 (1 MB)

SecRequestBodyInMemoryLimit

Configures the maximum size of a request body to be held in memory. Anything over the size specified will be buffered by creating a temporary file on disk. The default value is set conservatively at 128 KB. If you have a reasonable amount of memory on your system, you may want to increase this limit to something like 5 MB.

Syntax: SecRequestBodyInMemoryLimit <Number of Bytes>
Example: SecRequestBodyInMemoryLimit 67108864
Default value: 131072 (128 KB)

SecResponseBodyLimit

Sets the maximum size of the response body for response body buffering. If the response body is larger than this size, then what happens is determined by the setting provided for SecResponseBodyLimitAction (shown next). Requests whose MIME type does not match the MIME types provided to SecResponseBodyMimeTypes are not affected by this.

Syntax: SecResponseBodyLimit <size in bytes>
Example: SecResponseBodyLimit 512000

SecResponseBodyLimitAction

Controls what happens when response body buffering is enabled and the response body exceeds the size set for SecResponseBodyLimit. If Reject is set, the request will be rejected with a 500—Internal Server Error message if it exceeds the limit. If ProcessPartial setting is in effect, then the part of the response body that fits into the buffer is inspected and the entire response is sent to the client (if no rule denies the response after inspecting the part of it that fits in the buffer).

Syntax: SecResponseBodyLimitAction Reject|ProcessPartial
Example: SecResponseBodyLimitAction ProcessPartial

SecResponseBodyMimeType

This setting controls which requests are considered for response body buffering. Requests that have one of the MIME types set using this directive are buffered while all other requests are not. Each MIME type in the list is separated by whitespace.

Syntax: SecResponseBodyMimeType <mime types>
Example: SecResponseBodyMimeType text/html text/plain

SecResponseBodyMimeTypesClear

This directive clears the list of MIME types for which response body buffering should be enabled.

SecResponseBodyAccess

Enables or disables access to the HTTP response body. When turned on, this allows the response body to be inspected in rules using the RESPONSE_BODY variable.

Syntax: SecResponseBodyAccess On|Off
Example: SecResponseBodyAccess On
Default value: Off

SecRule

The main ModSecurity directive. Rules are used to determine what to do with HTTP requests such as block, allow, forward or a multitude of other conceivable actions. Each rule consists of three parts—the target, which is a variable or collection, which is what the rule is matched against, and operators, which is usually a regular expression used to match against the target.

Finally, a list of actions are used to determine what to do if a rule matches.

For a complete description of SecRule and all the aspects involved in writing rules, please see Chapter 2.

Syntax: SecRule <target> <operators> <actions>
Example: SecRule REQUEST_URI "/secret.jsp" deny

SecRuleInheritance

Configures whether or not virtual hosts inherit the main ModSecurity configuration and rules.

Syntax: SecRuleInheritance On|Off
Example: SecRuleInheritance On

SecRuleEngine

Turns the rule engine on or off, or configures it to run in detection-only mode. Possible values are On, which turns the rule engine on, Off, which disables the rule engine, or DetectionOnly,which turns the rule engine on, but does not take any action (such as blocking requests) even if a rule matches. This latter directive is useful in combination with debug logging.

Syntax: SecRuleEngine On|Off|DetectionOnly
Default value: Off

SecRuleRemoveById

Removes rules with a matching ID from the ruleset. Several IDs, or even a range of IDs, can be provided.

Syntax: SecRuleRemoveById <list of rule ids>
Example: SecRuleRemoveById 1 20 30 400-500

SecRuleRemoveByMsg

Removes rules whose msg string matches the regular expression from the parent context.

Syntax: SecRuleRemoveByMsg <regular expression>
Example: SecRuleRemoveByMsg "access denied"

SecRuleUpdateActionById

Amends the specified rule's action list by appending the specified action list to the rule's action list. The only things that cannot be changed are a rule's phase and rule ID.

Syntax: SecRuleUpdateActionById <id> <action list>
Example: SecRuleUpdateActionById 280 "t:urlDecode,msg:'Access denied'"

SecServerSignature

Instructs ModSecurity to change the web server signature as returned by the HTTP response headers. For this to work, ServerTokens Full must be specified in the Apache configuration file.

Syntax: SecServerSignature: "<New server signature>"
Example: SecServerSignature "Microsoft-IIS/5.0"

SecTmpDir

Configures the directory used for creating temporary files. ModSecurity uses temporary files when the data held in memory exceeds the configured memory limits (such as with the directive SecRequestBodyInMemoryLimit). The Apache user must have write access to the directory specified here.

Syntax: SecTmpDir <directory>
Example: SecTmpDir /tmp/modsecurity
Default value: Temp directory specified by environment variable

SecUploadDir

Sets the directory where files that have been intercepted are stored.

Syntax: SecUploadDir <directory>
Example: SecUploadDir /tmp/modsecurity/

SecUploadFileMode

Sets the mode to use for uploaded files that have been intercepted. The mode refers to the Linux file permissions as used with the Linux chmod command.

Syntax: SecUploadFileMode mode
Example: SecUploadFileMode 644

SecUploadKeepFiles

Determines whether intercepted files should be kept after the HTTP request has been completed.

Syntax: SecUploadKeepFiles On|Off|RelevantOnly
Example: SecUploadKeepFiles On
Default value: Off

The RelevantOnly setting keeps only files that are associated with requests that are considered relevant.

SecWebAppId

Used to avoid conflicts for session and user data between different web applications. SecWebAppId is used inside an Apache <VirtualHost> section to create a separate ID for the virtual host.

Syntax: SecWebAppId "<id string>"
Example: SecWebAppId "accounting"