GUI editor to tame mod_security rules

⌈⌋ ⎇ branch:  modseccfg


Artifact [6011d40aec]

Artifact 6011d40aec79910d6c6776dce84b2e40df2a6d68a7c4e089ece300ecf08f3725:

  • File modseccfg/secoptions.py — part of check-in [0e3331e93e] at 2020-11-30 06:37:22 on branch trunk — Use SPDX id in license: (user: mario size: 44416)

# api: modseccfg
# encoding: utf-8
# type: function
# category: config
# title: SecOption directives
# description: config window for core mod_security directives
# version: 0.2
# config: -
# license: Apache-2.0
# author: Mod_Sec team (options and their documentation)
#
# Autogenerated list of mod_security directives and flags.
# Binds it to pluginconf.gui and writer.update
#
## WARNING: NEEDS PATCHED PLUGINCONF.GUI (plugins= param)



import re, json, os, copy
from collections import OrderedDict
import pluginconf.gui
from modseccfg import utils, writer, vhosts, icons
from modseccfg.utils import srvroot, conf


# autoconverted via dev/security2pmd.py
options = OrderedDict()
options['SecArgumentSeparator'] = {
    "name": "SecArgumentSeparator",
    "description": "Specifies which character to use as the separator for application/x-www-form- urlencoded content.",
    "type": "str",
    "value": "",
    "help": "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."
}
options['SecAuditEngine'] = {
    "name": "SecAuditEngine",
    "description": "Configures the audit logging engine. ",
    "type": "str",
    "value": "",
    "help": "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.\n\nThe possible values for the audit log engine are as follows:"
}
options['SecAuditLog'] = {
    "name": "SecAuditLog",
    "description": "Defines the path to the main audit log file (serial logging format) or the concurrent logging index file (concurrent logging format). When used in combination with mlogc (only possible with concurrent logging), this directive defines the mlogc location and command line.",
    "type": "str",
    "value": "",
    "help": "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:"
}
options['SecAuditLog2'] = {
    "name": "SecAuditLog2",
    "description": "Defines the path to the secondary audit log index file when concurrent logging is enabled. See SecAuditLog for more details.",
    "type": "str",
    "value": "",
    "help": "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."
}
options['SecAuditLogDirMode'] = {
    "name": "SecAuditLogDirMode",
    "description": "Configures the mode (permissions) of any directories created for the concurrent audit logs, using an octal mode value as parameter (as used in chmod).",
    "type": "select",
    "value": "",
    "help": "The default mode for new audit log directories (0600) only grants read/write access to the owner (typically the account under which Apache is running, for example apache). If access from other accounts is needed (e.g., for use with mpm-itk), then you may use this directive to grant additional read and/or write privileges. You should use this directive with caution to avoid exposing potentially sensitive data to unauthorized users. Using the value default as parameter reverts the configuration back to the default setting. This feature is not available on operating systems not supporting octal file modes.\n\nExample:",
    "select": {
        "0640": "0640",
        "\"default\"": "\"default\""
    }
}
options['SecAuditLogFormat'] = {
    "name": "SecAuditLogFormat",
    "description": "Select the output format of the AuditLogs. The format can be either the native AuditLogs format or JSON.",
    "type": "select",
    "value": "",
    "help": "",
    "select": {
        "JSON": "JSON",
        "Native": "Native"
    }
}
options['SecAuditLogFileMode'] = {
    "name": "SecAuditLogFileMode",
    "description": "Configures the mode (permissions) of any files created for concurrent audit logs using an octal mode (as used in chmod). See SecAuditLogDirMode for controlling the mode of created audit log directories.",
    "type": "select",
    "value": "",
    "help": "This feature is not available on operating systems not supporting octal file modes. The default mode (0600) only grants read/write access to the account writing the file. If access from another account is needed (using mpm-itk is a good example), then this directive may be required. However, use this directive with caution to avoid exposing potentially sensitive data to unauthorized users. Using the value \u201cdefault\u201d will revert back to the default setting.",
    "select": {
        "0640": "0640",
        "\"default\"": "\"default\""
    }
}
options['SecAuditLogParts'] = {
    "name": "SecAuditLogParts",
    "description": "Defines which parts of each transaction are going to be recorded in the audit log. Each part is assigned a single letter; when a letter appears in the list then the equivalent part will be recorded. See below for the list of all parts.",
    "type": "str",
    "value": "",
    "help": "The format of the audit log format is documented in detail in the Audit Log Data Format Documentation.\nAvailable audit log parts:\nA: Audit log header (mandatory).\nB: Request headers.\nC: 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).\nD: Reserved for intermediary response headers; not implemented yet.\nE: 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).\nF: Final response headers (excluding the Date and Server headers, which are always added by Apache in the late stage of content delivery).\nG: Reserved for the actual response body; not implemented yet.\nH: Audit log trailer.\nI: 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\u2019t want to have (often large) files stored in your audit logs.\nJ: This part contains information about the files uploaded using multipart/form-data encoding.\nK: 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.\nZ: Final boundary, signifies the end of the entry (mandatory)."
}
options['SecAuditLogRelevantStatus'] = {
    "name": "SecAuditLogRelevantStatus",
    "description": "Configures which response status code is to be considered relevant for the purpose of audit logging.",
    "type": "str",
    "value": "",
    "help": ""
}
options['SecAuditLogStorageDir'] = {
    "name": "SecAuditLogStorageDir",
    "description": "Configures the directory where concurrent audit log entries are to be stored. ",
    "type": "str",
    "value": "",
    "help": "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.\nAs 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."
}
options['SecAuditLogType'] = {
    "name": "SecAuditLogType",
    "description": "Configures the type of audit logging mechanism to be used. ",
    "type": "select",
    "value": "",
    "help": "The possible values are:",
    "select": {
        "Serial": "Serial",
        "Concurrent": "Concurrent",
        "HTTPS": "HTTPS"
    }
}
options['SecCacheTransformations'] = {
    "name": "SecCacheTransformations",
    "description": "Controls the caching of transformations, which may speed up the processing of complex rule sets. Caching is off by default starting with 2.5.6, when it was deprecated and downgraded back to experimental.",
    "type": "select",
    "value": "",
    "help": "The first directive parameter can be one of the following:",
    "select": {
        "On": "On",
        "Off [options]": "Off [options]"
    }
}
options['SecChrootDir'] = {
    "name": "SecChrootDir",
    "description": "Configures the directory path that will be used to jail the web server process. ",
    "type": "str",
    "value": "",
    "help": "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:"
}
options['SecCollectionTimeout'] = {
    "name": "SecCollectionTimeout",
    "description": "Specifies the collections timeout. Default is 3600 seconds.",
    "type": "str",
    "value": "",
    "help": ""
}
options['SecComponentSignature'] = {
    "name": "SecComponentSignature",
    "description": "Appends component signature to the ModSecurity signature. ",
    "type": "str",
    "value": "",
    "help": "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."
}
options['SecConnEngine'] = {
    "name": "SecConnEngine",
    "description": "Configures the connections engine. This directive affect the directives: SecConnReadStateLimit and SecConnWriteStateLimit.",
    "type": "select",
    "value": "",
    "help": "Possible values are (Same as SecRuleEngine): ",
    "select": {
        "On": "On",
        "Off": "Off",
        "DetectionOnly": "DetectionOnly"
    }
}
options['SecContentInjection'] = {
    "name": "SecContentInjection",
    "description": "Enables content injection using actions append and prepend. ",
    "type": "select",
    "value": "",
    "help": "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.",
    "select": {
        "On": "On",
        "Off": "Off"
    }
}
options['SecCookieFormat'] = {
    "name": "SecCookieFormat",
    "description": "Selects the cookie format that will be used in the current configuration context. ",
    "type": "select",
    "value": "",
    "help": "The possible values are:",
    "select": {
        "0": "0",
        "1": "1"
    }
}
options['SecCookieV0Separator'] = {
    "name": "SecCookieV0Separator",
    "description": "Specifies which character to use as the separator for cookie v0 content.",
    "type": "str",
    "value": "",
    "help": ""
}
options['SecDataDir'] = {
    "name": "SecDataDir",
    "description": "Path where persistent data (e.g., IP address data, session data, and so on) is to be stored.",
    "type": "str",
    "value": "",
    "help": "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."
}
options['SecDebugLog'] = {
    "name": "SecDebugLog",
    "description": "Path to the ModSecurity debug log file. ",
    "type": "str",
    "value": "",
    "help": ""
}
options['SecDebugLogLevel'] = {
    "name": "SecDebugLogLevel",
    "description": "Configures the verboseness of the debug log data. ",
    "type": "select",
    "value": "",
    "help": "Messages at levels 1\u20133 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.\n\nThe possible values for the debug log level are: ",
    "select": {
        "0": "0",
        "1": "1",
        "2": "2",
        "3": "3",
        "4": "4",
        "5": "5",
        "6": "6",
        "7": "7",
        "8": "8",
        "9": "9"
    }
}
options['SecDefaultAction'] = {
    "name": "SecDefaultAction",
    "description": "Defines the default list of actions, which will be inherited by the rules in the same configuration context.",
    "type": "str",
    "value": "",
    "help": "Every rule following a previous <code>SecDefaultAction</code> directive in the same configuration context will inherit its settings unless more specific actions are used. Every <code>SecDefaultAction</code> directive must specify a disruptive action and a processing phase and cannot contain metadata actions."
}
options['SecDisableBackendCompression'] = {
    "name": "SecDisableBackendCompression",
    "description": "Disables backend compression while leaving the frontend compression enabled. ",
    "type": "select",
    "value": "",
    "help": "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.",
    "select": {
        "On": "On",
        "Off": "Off"
    }
}
options['SecHashEngine'] = {
    "name": "SecHashEngine",
    "description": "Configures the hash engine. ",
    "type": "select",
    "value": "",
    "help": "The possible values are: ",
    "select": {
        "On": "On",
        "Off": "Off"
    }
}
options['SecHashKey'] = {
    "name": "SecHashKey",
    "description": "Define the key that will be used by HMAC. ",
    "type": "select",
    "value": "",
    "help": "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.",
    "select": {
        "rand": "rand",
        "TEXT KeyOnly": "TEXT KeyOnly",
        "SessionID": "SessionID",
        "RemoteIP": "RemoteIP"
    }
}
options['SecHashParam'] = {
    "name": "SecHashParam",
    "description": "Define the parameter name that will receive the MAC hash. ",
    "type": "str",
    "value": "",
    "help": "ModSecurity hash engine will add a new parameter to protected HTML elements containing the MAC hash."
}
options['SecHashMethodRx'] = {
    "name": "SecHashMethodRx",
    "description": "Configures what kind of HTML data the hash engine should sign based on regular expression.",
    "type": "str",
    "value": "",
    "help": "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.\n\nThe possible values for TYPE are:"
}
options['SecHashMethodPm'] = {
    "name": "SecHashMethodPm",
    "description": "Configures what kind of HTML data the hash engine should sign based on string search algoritm.",
    "type": "str",
    "value": "",
    "help": "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.\n\nThe possible values for TYPE are:"
}
options['SecGeoLookupDb'] = {
    "name": "SecGeoLookupDb",
    "description": "Defines the path to the database that will be used for geolocation lookups. ",
    "type": "str",
    "value": "",
    "help": "ModSecurity relies on the free geolocation databases (GeoLite City and GeoLite Country) that can be obtained from MaxMind [http://www.maxmind.com]. Currently ModSecurity only supports the legacy GeoIP format. Maxmind's newer GeoIP2 format is not yet currently supported. "
}
options['SecGsbLookupDb'] = {
    "name": "SecGsbLookupDb",
    "description": "Defines the path to the database that will be used for Google Safe Browsing (GSB) lookups. ",
    "type": "str",
    "value": "",
    "help": "ModSecurity relies on the free Google Safe Browsing database that can be obtained from the Google GSB API [http://code.google.com/apis/safebrowsing/]."
}
options['SecGuardianLog'] = {
    "name": "SecGuardianLog",
    "description": "Configures an external program that will receive the information about every transaction via piped logging.",
    "type": "select",
    "value": "",
    "help": "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.\n\nCurrently the only tool known to work with guardian logging is httpd-guardian, which is part of the Apache httpd tools project [http://apache-tools.cvs.sourceforge.net/viewvc/apache-tools/apache-tools/]. The httpd-guardian tool is designed to defend against denial of service attacks. It uses the blacklist tool (from the same project) to interact with an iptables-based (on a Linux system) or pf-based (on a BSD system) firewall, dynamically blacklisting the offending IP addresses. It can also interact with SnortSam [http://www.snortsam.net]. Assuming httpd-guardian is already configured (look into the source code for the detailed instructions), you only need to add one line to your Apache configuration to deploy it:",
    "select": {
        "": "",
        "/path/to/httpd-guardian": "/path/to/httpd-guardian"
    }
}
options['SecHttpBlKey'] = {
    "name": "SecHttpBlKey",
    "description": "Configures the user's registered Honeypot Project HTTP BL API Key to use with @rbl.",
    "type": "str",
    "value": "",
    "help": "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."
}
options['SecInterceptOnError'] = {
    "name": "SecInterceptOnError",
    "description": "Configures how to respond when rule processing fails.",
    "type": "select",
    "value": "",
    "help": "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.",
    "select": {
        "On": "On",
        "Off": "Off"
    }
}
options['SecPcreMatchLimit'] = {
    "name": "SecPcreMatchLimit",
    "description": "Sets the match limit in the PCRE library. ",
    "type": "str",
    "value": "",
    "help": "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.\nFor more information, refer to the pcre_extra field in the pcreapi man page."
}
options['SecPcreMatchLimitRecursion'] = {
    "name": "SecPcreMatchLimitRecursion",
    "description": "Sets the match limit recursion in the PCRE library. ",
    "type": "str",
    "value": "",
    "help": "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.\nFor more information, refer to the pcre_extra field in the pcreapi man page."
}
options['SecPdfProtect'] = {
    "name": "SecPdfProtect",
    "description": "Enables the PDF XSS protection functionality. ",
    "type": "select",
    "value": "",
    "help": "Once enabled access to PDF files is tracked. Direct access attempts are redirected to links that contain one-time tokens. Requests with valid tokens are allowed through, unmodified. Requests with invalid tokens are also allowed through, but with forced download of the PDF files. This implementation uses response headers to detect PDF files and thus can be used with dynamically generated PDF files that do not have the .pdf extension in the request URI.",
    "select": {
        "On": "On",
        "Off": "Off"
    }
}
options['SecPdfProtectMethod'] = {
    "name": "SecPdfProtectMethod",
    "description": "Configure desired protection method to be used when requests for PDF files are detected. ",
    "type": "str",
    "value": "",
    "help": "Possible values are TokenRedirection and ForcedDownload. The token redirection approach will attempt to redirect with tokens where possible. This allows PDF files to continue to be opened inline but works only for GET requests. Forced download always causes PDF files to be delivered as opaque binaries and attachments. The latter will always be used for non-GET requests. Forced download is considered to be more secure but may cause usability problems for users (\u201cThis PDF won\u2019t open anymore!\u201d)."
}
options['SecPdfProtectSecret'] = {
    "name": "SecPdfProtectSecret",
    "description": "Defines the secret that will be used to construct one-time tokens. ",
    "type": "str",
    "value": "",
    "help": "You should use a reasonably long value for the secret (e.g., 16 characters is good). Once selected, the secret should not be changed, as it will break the tokens that were sent prior to change. But it\u2019s not a big deal even if you change it. It will just force download of PDF files with tokens that were issued in the last few seconds."
}
options['SecPdfProtectTimeout'] = {
    "name": "SecPdfProtectTimeout",
    "description": "Defines the token timeout. ",
    "type": "str",
    "value": "",
    "help": "After token expires, it can no longer be used to allow access to a PDF file. Request will be allowed through but the PDF will be delivered as an attachment."
}
options['SecPdfProtectTokenName'] = {
    "name": "SecPdfProtectTokenName",
    "description": "Defines the name of the token. ",
    "type": "str",
    "value": "",
    "help": "The only reason you would want to change the name of the token is if you wanted to hide the fact that you are running ModSecurity. It\u2019s a good reason, but it won\u2019t really help, as the adversary can look into the algorithm used for PDF protection and figure it out anyway. It does raise the bar slightly, so go ahead if you want to."
}
options['SecReadStateLimit'] = {
    "name": "SecReadStateLimit",
    "description": "Establishes a per-IP address limit of how many connections are allowed to be in SERVER_BUSY_READ state. ",
    "type": "str",
    "value": "",
    "help": "For v2.8.0 or newest refer to SecConnReadStateLimit."
}
options['SecConnReadStateLimit'] = {
    "name": "SecConnReadStateLimit",
    "description": "Establishes a per-IP address limit of how many connections are allowed to be in SERVER_BUSY_READ state. ",
    "type": "str",
    "value": "",
    "help": "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."
}
options['SecSensorId'] = {
    "name": "SecSensorId",
    "description": "Define a sensor ID that will be present into log part H. ",
    "type": "str",
    "value": "",
    "help": ""
}
options['SecWriteStateLimit'] = {
    "name": "SecWriteStateLimit",
    "description": "Establishes a per-IP address limit of how many connections are allowed to be in SERVER_BUSY_WRITE state. ",
    "type": "str",
    "value": "",
    "help": "For v2.8.0 or newest refer to SecConnWriteStateLimit."
}
options['SecConnWriteStateLimit'] = {
    "name": "SecConnWriteStateLimit",
    "description": "Establishes a per-IP address limit of how many connections are allowed to be in SERVER_BUSY_WRITE state. ",
    "type": "str",
    "value": "",
    "help": "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."
}
options['SecRemoteRulesFailAction'] = {
    "name": "SecRemoteRulesFailAction",
    "description": "Action that will be taken if SecRemoteRules specify an URL that ModSecurity was not able to download.",
    "type": "select",
    "value": "",
    "help": "The default action is to Abort whenever there is a problem downloading a given URL.",
    "select": {
        "Abort": "Abort",
        "Warn": "Warn"
    }
}
options['SecRequestBodyAccess'] = {
    "name": "SecRequestBodyAccess",
    "description": "Configures whether request bodies will be buffered and processed by ModSecurity.",
    "type": "select",
    "value": "",
    "help": "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:",
    "select": {
        "On": "On",
        "Off": "Off"
    }
}
options['SecRequestBodyInMemoryLimit'] = {
    "name": "SecRequestBodyInMemoryLimit",
    "description": "Configures the maximum request body size that ModSecurity will store in memory.",
    "type": "str",
    "value": "",
    "help": "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."
}
options['SecRequestBodyLimit'] = {
    "name": "SecRequestBodyLimit",
    "description": "Configures the maximum request body size ModSecurity will accept for buffering.",
    "type": "str",
    "value": "",
    "help": "Anything over the limit will be rejected with status code 413 (Request Entity Too Large). There is a hard limit of 1 GB."
}
options['SecRequestBodyNoFilesLimit'] = {
    "name": "SecRequestBodyNoFilesLimit",
    "description": "Configures the maximum request body size ModSecurity will accept for buffering, excluding the size of any files being transported in the request. This directive is useful to reduce susceptibility to DoS attacks when someone is sending request bodies of very large sizes. Web applications that require file uploads must configure SecRequestBodyLimit to a high value, but because large files are streamed to disk, file uploads will not increase memory consumption. However, it\u2019s 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.",
    "type": "str",
    "value": "",
    "help": "Generally speaking, the default value is not small enough. For most applications, you should be able to reduce it down to 128 KB or lower. Anything over the limit will be rejected with status code 413 (Request Entity Too Large). There is a hard limit of 1 GB."
}
options['SecRequestBodyLimitAction'] = {
    "name": "SecRequestBodyLimitAction",
    "description": "Controls what happens once a request body limit, configured with SecRequestBodyLimit, is encountered",
    "type": "select",
    "value": "",
    "help": "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.",
    "select": {
        "Reject": "Reject",
        "ProcessPartial": "ProcessPartial"
    }
}
options['SecResponseBodyLimit'] = {
    "name": "SecResponseBodyLimit",
    "description": "Configures the maximum response body size that will be accepted for buffering.",
    "type": "str",
    "value": "",
    "help": "Anything over this limit will be rejected with status code 500 (Internal Server Error). This setting will not affect the responses with MIME types that are not selected for buffering. There is a hard limit of 1 GB."
}
options['SecResponseBodyLimitAction'] = {
    "name": "SecResponseBodyLimitAction",
    "description": "Controls what happens once a response body limit, configured with SecResponseBodyLimit, is encountered. ",
    "type": "select",
    "value": "",
    "help": "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.",
    "select": {
        "Reject": "Reject",
        "ProcessPartial": "ProcessPartial"
    }
}
options['SecResponseBodyMimeType'] = {
    "name": "SecResponseBodyMimeType",
    "description": "Configures which MIME types are to be considered for response body buffering. ",
    "type": "str",
    "value": "",
    "help": "Multiple SecResponseBodyMimeType directives can be used to add MIME types. Use SecResponseBodyMimeTypesClear to clear previously configured MIME types and start over."
}
options['SecResponseBodyMimeTypesClear'] = {
    "name": "SecResponseBodyMimeTypesClear",
    "description": "Clears the list of MIME types considered for response body buffering, allowing you to start populating the list from scratch.",
    "type": "str",
    "value": "",
    "help": ""
}
options['SecResponseBodyAccess'] = {
    "name": "SecResponseBodyAccess",
    "description": "Configures whether response bodies are to be buffered. ",
    "type": "select",
    "value": "",
    "help": "This directive is required if you plan to inspect HTML responses and implement response blocking.  Possible values are: ",
    "select": {
        "On": "On",
        "Off": "Off"
    }
}
options['SecRuleInheritance'] = {
    "name": "SecRuleInheritance",
    "description": "Configures whether the current context will inherit the rules from the parent context.",
    "type": "select",
    "value": "",
    "help": "Sometimes when you create a more specific configuration context (for example using the <Location> 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 <Location> configuration context. There are no limitations in that respect in the current development version (and there won\u2019t be in the next major version).\n\nThe possible values are: ",
    "select": {
        "On": "On",
        "Off": "Off"
    }
}
options['SecRuleEngine'] = {
    "name": "SecRuleEngine",
    "description": "Configures the rules engine. ",
    "type": "select",
    "value": "",
    "help": "The possible values are: ",
    "select": {
        "On": "On",
        "Off": "Off",
        "DetectionOnly": "DetectionOnly"
    }
}
options['SecRulePerfTime'] = {
    "name": "SecRulePerfTime",
    "description": "Set a performance threshold for rules. Rules that spend at least the time defined will be logged into audit log Part H as Rules-Performance-Info in the format id=usec, comma separated. ",
    "type": "str",
    "value": "",
    "help": "The rules hitting the threshold can be accessed via the collection PERF_RULES."
}
options['SecServerSignature'] = {
    "name": "SecServerSignature",
    "description": "Instructs ModSecurity to change the data presented in the \"Server:\" response header token.",
    "type": "str",
    "value": "",
    "help": "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."
}
options['SecStatusEngine'] = {
    "name": "SecStatusEngine",
    "description": "Controls Status Reporting functionality.  Uses DNS-based reporting to send software version information to the ModSecurity Project team.",
    "type": "select",
    "value": "",
    "help": "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:",
    "select": {
        "On": "On",
        "Off": "Off"
    }
}
options['SecStreamInBodyInspection'] = {
    "name": "SecStreamInBodyInspection",
    "description": "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. ",
    "type": "select",
    "value": "",
    "help": "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.",
    "select": {
        "On": "On",
        "Off": "Off"
    }
}
options['SecStreamOutBodyInspection'] = {
    "name": "SecStreamOutBodyInspection",
    "description": "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.",
    "type": "select",
    "value": "",
    "help": "This feature enables the creation of the STREAM_OUTPUT_BODY variable and is useful when you need to do data modification into response body.",
    "select": {
        "On": "On",
        "Off": "Off"
    }
}
options['SecTmpDir'] = {
    "name": "SecTmpDir",
    "description": "Configures the directory where temporary files will be created.",
    "type": "str",
    "value": "",
    "help": "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.\n\nAs 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."
}
options['SecUnicodeMapFile'] = {
    "name": "SecUnicodeMapFile",
    "description": "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 Point to use.",
    "type": "str",
    "value": "",
    "help": ""
}
options['SecUnicodeCodePage'] = {
    "name": "SecUnicodeCodePage",
    "description": "Defines which Unicode code point will be used by the urlDecodeUni transformation function during normalization.",
    "type": "str",
    "value": "",
    "help": ""
}
options['SecUploadDir'] = {
    "name": "SecUploadDir",
    "description": "Configures the directory where intercepted files will be stored.",
    "type": "str",
    "value": "",
    "help": "This directory must be on the same filesystem as the temporary directory defined with SecTmpDir. This directive is used with SecUploadKeepFiles."
}
options['SecUploadFileLimit'] = {
    "name": "SecUploadFileLimit",
    "description": "Configures the maximum number of file uploads processed in a multipart POST.",
    "type": "str",
    "value": "",
    "help": "The default is set to 100 files, but you are encouraged to reduce this value. 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."
}
options['SecUploadFileMode'] = {
    "name": "SecUploadFileMode",
    "description": "Configures the mode (permissions) of any uploaded files using an octal mode (as used in chmod).",
    "type": "select",
    "value": "",
    "help": "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.",
    "select": {
        "0640": "0640",
        "\"default\"": "\"default\""
    }
}
options['SecUploadKeepFiles'] = {
    "name": "SecUploadKeepFiles",
    "description": "Configures whether or not the intercepted files will be kept after transaction is processed.",
    "type": "select",
    "value": "",
    "help": "This directive requires the storage directory to be defined (using SecUploadDir).\n\nPossible values are:",
    "select": {
        "On": "On",
        "Off": "Off",
        "RelevantOnly": "RelevantOnly"
    }
}
options['SecWebAppId'] = {
    "name": "SecWebAppId",
    "description": "Creates an application namespace, allowing for separate persistent session and user storage.",
    "type": "str",
    "value": "",
    "help": "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\u2019t used, a collision between session IDs might occur."
}
options['SecXmlExternalEntity'] = {
    "name": "SecXmlExternalEntity",
    "description": "Enable or Disable the loading process of xml external entity. Loading external entity without correct verifying process can lead to a security issue.",
    "type": "select",
    "value": "",
    "help": "You must enable this directive if you need to use the <code>@validateSchema</code> or <code>@validateDtd</code> operators.",
    "select": {
        "On": "On",
        "Off": "Off"
    }
}


#-- group
def mk_groups():
    plugins = {}
    groups = [
        ["global", "module", "SecOptions", "Update mod_security directives in\n", "RuleEngine$|StatusEng|Pcre|Inherit|Intercept|Chroot|Sig|Default"],
        ["log", "log", "Logging", "Options pertaining the logs", "AuditLog|AuditEngine"],
        ["dir", "tmp", "Directories", "Temp storage", "TmpDir|DataDir"],
        ["body", "bodyaccess", "BodyAccess", "Access to HTTP payloads", "Body"],
        ["dbg", "debug", "Debug / Upload", "Debug log and upload inspection", "Upload|Debug"],
        ["hash", "hash", "Hash", "Hashing functions (forms and links signature)", "Hash"],
        ["pdf", "pdf", "PDF Engine", "PDF related options", "Pdf"],
        ["else", "else", "Other options", "Less common directives", "-"]
    ]
    groups[-1][-1] = "^(?!.*(" + ("|".join([d[4] for d in groups])) + "))"  # "else" gets opposite of other regexps
    for grp, cat, title, desc, rx in groups:
        plugins[grp] = {
            "id": grp,
            "api": "mod_security",
            "title": title,
            "description": desc,
            "version": "0.1",
            "type": "config",
            "category": cat,
            "config": [o for o in options.values() if re.search(rx, o["name"])]
        }
    return plugins


def window(confn):

    # prepare config list
    for k,c in options.items():
        if c["type"] == "int":
            c["type"] = "str"
        c["value"] = ""   # unset defaults
    plugins = mk_groups()
    plugins["global"]["description"] += confn
    plugin_states = {k:1 for k in plugins.keys()}

    # map config variables from extracted `vhosts.cfg{}` dict onto mixed-case `conf` dict here
    vh = vhosts.vhosts.get(confn) # existing *.conf
    if not vh:
        vh = read_vh(confn) # previously unknown *.conf
    conf = {}
    if vh.cfg:
        names = {k: k.lower() for k in options.keys()}
        for dir,id in names.items():
            if id in vh.cfg:
                conf[dir] = vh.cfg[id]
    prev = copy.copy(conf)

    # show
    #
    ## WARNING: NEEDS PATCHED PLUGINCONF.GUI (plugins= param)
    #
    save = pluginconf.gui.window(
        conf, plugin_states, files=[], plugins=plugins,
        title="mod_security option directives", icon=icons.apache,
        opt_label=True, size=(700,800)
    )
    if not save:
        return
    
    # update if there were any changes
    updated = {
        k:v for k,v in conf.items()
        if len(v) and v!=prev.get(k)
    }
    if updated:
        writer.update_or_add(confn, updated)
        # add updated config to global list
        if vhosts.vhosts.get(confn):
            vh.cfg = read_vh(confn).cfg


# rescan a *.conf file
def read_vh(fn):
    return vhosts.vhost(fn, srvroot.read(fn), cfg_only=True)