Server settings documentation!!

ホストOS:Debian GNU/Linux 10.7
ゲストOS:FreeBSD 12.2-RELEASE r366954 GENERIC amd64 
Apacheバージョン:Apache/2.4.46 (FreeBSD)

参考URL:ModSecurity Open Source Web Application Firewall

Apacheの設定が全て完了している状態でApache モジュールとして動くWAF(ModSecurity)を導入する。

1)pkg でモジュール群をインストールする

# pkg install ap24-mod_security-2.9.3
Updating FreeBSD repository catalogue...
FreeBSD repository is up to date.
All repositories are up to date.
The following 2 package(s) will be affected (of 0 checked):

New packages to be INSTALLED:
        ap24-mod_security: 2.9.3
        yajl: 2.1.0

Number of packages to be installed: 2

The process will require 3 MiB more space.
328 KiB to be downloaded.

Proceed with this action? [y/N]: y
[1/2] Fetching ap24-mod_security-2.9.3.txz: 100%  272 KiB 278.5kB/s    00:01
[2/2] Fetching yajl-2.1.0.txz: 100%   56 KiB  57.0kB/s    00:01
Checking integrity... done (0 conflicting)
[1/2] Installing yajl-2.1.0...
[1/2] Extracting yajl-2.1.0: 100%
[2/2] Installing ap24-mod_security-2.9.3...
[2/2] Extracting ap24-mod_security-2.9.3: 100%
Message from ap24-mod_security-2.9.3:

You have installed ModSecurity.
To enable ModSecurity in Apache, follow the instructions in


Most users will use the signatures from the OWASP Core Rule Set (CRS).
For configuration instructions, see /usr/local/share/doc/mod_security2/README.


# cat /usr/local/share/doc/mod_security2/README
Configuring ModSecurity on FreeBSD

To enable ModSecurity in Apache, follow the instructions in


ModSecurity has various configuration options.
To change them, edit the following file:


Getting the Core Rule Set

ModSecurity requires firewall rule definitions. Most people use the
OWASP ModSecurity Core Rule Set (CRS). The easiest way to track the
OWASP CRS repository right now is to use Git. Let's make a directory
for all our ModSecurity related stuff, and clone the CRS repository
under it.

  pkg install git
  cd /usr/local/etc/modsecurity
  git clone
  cp owasp-modsecurity-crs/modsecurity_crs_10_setup.conf.example \

The CRS has various config options. To change them, edit crs.conf.

To activate the CRS base rules, add the following to your httpd.conf:

  Include etc/modsecurity/owasp-modsecurity-crs/base_rules/*.conf

You can also add custom configuration and CRS exceptions here.
For instance, you might want to disable rules that generate false
positives. Example:

  SecRuleRemoveById 960015

Starting ModSecurity

When the configuration is all set, simply restart Apache and confirm
that ModSecurity is loaded by checking Apache's log file:

  apachectl restart
  tail /var/log/httpd-error.log

Configuring blocking mode

Now that ModSecurity is active, try making a suspicious request to
your web server, for instance browse to a URL: The CRS has a rule against
this type of request. After browsing to the URL, you should now see
the request logged in /var/log/modsec_audit.log.

You'll notice that the request succeeds, and the response is sent to
the browser normally. The reason is that ModSecurity runs in
"DetectionOnly" mode by default, in order to prevent downtime from
misconfiguration or heavy-handed blocking. You can enable blocking
mode simply by editing modsecurity.conf and changing the following

  SecRuleEngine On

Again, restart Apache. Now, make the same suspicious request to your
web server. You should now see a "403 Forbidden" error!

In practice, it's probably best to keep SecRuleEngine DetectionOnly
for some time, while your users exercise the web applications.
Meanwhile, you should keep an eye on /var/log/modsec_audit.log to see
what is being blocked. If there are any false positives, you need to
mitigate this by writing custom exceptions.


An essential resource for working with ModSecurity is the ModSecurity
Handbook by Ivan Ristic. ModSecurity exposes quite some internals, and
it's good to scan this book before you start writing custom rules and

You probably want to keep the CRS updated from time to time. You can
do this with Git:

  cd /usr/local/etc/modsecurity/owasp-modsecurity-crs
  git pull
  apachectl restart


# pkg install git
# cd /usr/local/etc/modsecurity

# git clone
Cloning into 'owasp-modsecurity-crs'...
remote: Enumerating objects: 10486, done.
remote: Total 10486 (delta 0), reused 0 (delta 0), pack-reused 10486
Receiving objects: 100% (10486/10486), 3.34 MiB | 1.11 MiB/s, done.
Resolving deltas: 100% (7687/7687), done.


cp owasp-modsecurity-crs/crs-setup.conf.example crs.conf


# ls -l
total 116
-rw-r--r--  1 root  wheel  32933 Jan  7 16:25 crs.conf
-rw-r--r--  1 root  wheel   8440 Dec 16 09:19 modsecurity.conf
-rw-r--r--  1 root  wheel   8440 Dec 16 09:19 modsecurity.conf.sample
drwxr-xr-x  8 root  wheel    512 Jan  1 16:38 owasp-modsecurity-crs
-rw-r--r--  1 root  wheel  53146 Dec 16 09:19 unicode.mapping

2)Apache httpd.confの設定



## apache modules for mod_security
# LoadModule unique_id_module libexec/apache24/
# LoadModule security2_module libexec/apache24/
# Include /usr/local/etc/modsecurity/*.conf


## apache modules for mod_security
LoadModule unique_id_module /usr/local/libexec/apache24/
LoadModule security2_module /usr/local/libexec/apache24/
Include /usr/local/etc/modsecurity/*.conf


vi /usr/local/etc/apache24/httpd.conf
# Third party modules
modules.dOptional etc/apache24/modules.d/[0-9][0-9][0-9]_*.conf


/usr/local/etc/modsecurity/modsecurity.confをSecRuleEngine OnからSecRuleEngine DetectionOnlyに変更する。

# vi /usr/local/etc/modsecurity/modsecurity.conf
# -- Rule engine initialization ----------------------------------------------

# Enable ModSecurity, attaching it to every transaction. Use detection
# only to start with, because that minimises the chances of post-installation
# disruption.
SecRuleEngine DetectionOnly

# -- Request body handling ---------------------------------------------------

# Allow ModSecurity to access request bodies. If you don't, ModSecurity
# won't be able to see any POST parameters, which opens a large security
# hole for attackers to exploit.
SecRequestBodyAccess On

# Enable XML request body parser.
# Initiate XML Processor in case of xml content-type
SecRule REQUEST_HEADERS:Content-Type "(?:application(?:/soap\+|/)|text/)xml" \

# Enable JSON request body parser.
# Initiate JSON Processor in case of JSON content-type; change accordingly
# if your application does not use 'application/json'
SecRule REQUEST_HEADERS:Content-Type "application/json" \

# Maximum request body size we will accept for buffering. If you support
# file uploads then the value given on the first line has to be as large
# as the largest file you are willing to accept. The second value refers
# to the size of data, with files excluded. You want to keep that value as
# low as practical.
SecRequestBodyLimit 13107200
SecRequestBodyNoFilesLimit 131072

# Store up to 128 KB of request body data in memory. When the multipart
# parser reaches this limit, it will start using your hard disk for
# storage. That is slow, but unavoidable.
SecRequestBodyInMemoryLimit 131072

# What do do if the request body size is above our configured limit.
# Keep in mind that this setting will automatically be set to ProcessPartial
# when SecRuleEngine is set to DetectionOnly mode in order to minimize
# disruptions when initially deploying ModSecurity.
SecRequestBodyLimitAction Reject

# Verify that we've correctly processed the request body.
# As a rule of thumb, when failing to process a request body
# you should reject the request (when deployed in blocking mode)
# or log a high-severity alert (when deployed in detection-only mode).
SecRule REQBODY_ERROR "!@eq 0" \
"id:'200002', phase:2,t:none,log,deny,status:400,msg:'Failed to parse request body.',logdata:'%{reqbody_error_msg}',severity:2"

# By default be strict with what we accept in the multipart/form-data
# request body. If the rule below proves to be too strict for your
# environment consider changing it to detection-only. You are encouraged
# _not_ to remove it altogether.
"id:'200003',phase:2,t:none,log,deny,status:400, \
msg:'Multipart request body failed strict validation: \

# Did we see anything that might be a boundary?
"id:'200004',phase:2,t:none,log,deny,msg:'Multipart parser detected a possible unmatched boundary.'"

# PCRE Tuning
# We want to avoid a potential RegEx DoS condition
SecPcreMatchLimit 1000
SecPcreMatchLimitRecursion 1000

# Some internal errors will set flags in TX and we will need to look for these.
# All of these are prefixed with "MSC_".  The following flags currently exist:
# MSC_PCRE_LIMITS_EXCEEDED: PCRE match limits were exceeded.
SecRule TX:/^MSC_/ "!@streq 0" \
        "id:'200005',phase:2,t:none,deny,msg:'ModSecurity internal error flagged: %{MATCHED_VAR_NAME}'"

# -- Response body handling --------------------------------------------------

# Allow ModSecurity to access response bodies.
# You should have this directive enabled in order to identify errors
# and data leakage issues.
# Do keep in mind that enabling this directive does increases both
# memory consumption and response latency.
SecResponseBodyAccess On

# Which response MIME types do you want to inspect? You should adjust the
# configuration below to catch documents but avoid static files
# (e.g., images and archives).
SecResponseBodyMimeType text/plain text/html text/xml

# Buffer response bodies of up to 512 KB in length.
SecResponseBodyLimit 524288

# What happens when we encounter a response body larger than the configured
# limit? By default, we process what we have and let the rest through.
# That's somewhat less secure, but does not break any legitimate pages.
SecResponseBodyLimitAction ProcessPartial

# -- Filesystem configuration ------------------------------------------------

# The location where ModSecurity stores temporary files (for example, when
# it needs to handle a file upload that is larger than the configured limit).
# This default setting is chosen due to all systems have /tmp available however,
# this is less than ideal. It is recommended that you specify a location that's private.
SecTmpDir /tmp/

# The location where ModSecurity will keep its persistent data.  This default setting
# is chosen due to all systems have /tmp available however, it
# too should be updated to a place that other users can't access.
SecDataDir /tmp/

# -- File uploads handling configuration -------------------------------------

# The location where ModSecurity stores intercepted uploaded files. This
# location must be private to ModSecurity. You don't want other users on
# the server to access the files, do you?
#SecUploadDir /opt/modsecurity/var/upload/

# By default, only keep the files that were determined to be unusual
# in some way (by an external inspection script). For this to work you
# will also need at least one file inspection rule.
#SecUploadKeepFiles RelevantOnly

# Uploaded files are by default created with permissions that do not allow
# any other user to access them. You may need to relax that if you want to
# interface ModSecurity to an external program (e.g., an anti-virus).
#SecUploadFileMode 0600

# -- Debug log configuration -------------------------------------------------

# The default debug log configuration is to duplicate the error, warning
# and notice messages from the error log.
#SecDebugLog /opt/modsecurity/var/log/debug.log
#SecDebugLogLevel 3

# -- Audit log configuration -------------------------------------------------

# Log the transactions that are marked by a rule, as well as those that
# trigger a server error (determined by a 5xx or 4xx, excluding 404,
# level response status codes).
SecAuditEngine RelevantOnly
SecAuditLogRelevantStatus "^(?:5|4(?!04))"

# Log everything we know about a transaction.
SecAuditLogParts ABIJDEFHZ

# Use a single file for logging. This is much easier to look at, but
# assumes that you will use the audit log only ocassionally.
SecAuditLogType Serial
SecAuditLog /var/log/modsec_audit.log

# Specify the path for concurrent audit logging.
#SecAuditLogStorageDir /opt/modsecurity/var/audit/

# -- Miscellaneous -----------------------------------------------------------

# Use the most commonly used application/x-www-form-urlencoded parameter
# separator. There's probably only one application somewhere that uses
# something else so don't expect to change this value.
SecArgumentSeparator &

# Settle on version 0 (zero) cookies, as that is what most applications
# use. Using an incorrect cookie version may open your installation to
# evasion attacks (against the rules that examine named cookies).
SecCookieFormat 0

# Specify your Unicode Code Point.
# This mapping is used by the t:urlDecodeUni transformation function
# to properly map encoded data to your language. Properly setting
# these directives helps to reduce false positives and negatives.
SecUnicodeMapFile unicode.mapping 20127

# Improve the quality of ModSecurity by sharing information about your
# current ModSecurity version and dependencies versions.
# The following information will be shared: ModSecurity version,
# Web Server version, APR version, PCRE version, Lua version, Libxml2
# version, Anonymous unique id for host.
SecStatusEngine On



# httpd -t
Syntax OK


# service apache24 restart
Performing sanity check on apache24 configuration:
Syntax OK
Stopping apache24.
Waiting for PIDS: 4495.
Performing sanity check on apache24 configuration:
Syntax OK
Starting apache24.



# tail -200 modsec_audit.log
Apache-Handler: application/x-httpd-php
Stopwatch: 1614227315725030 440860 (- - -)
Stopwatch2: 1614227315725030 440860; combined=269, p1=128, p2=36, p3=29, p4=15, p5=46, sr=0, sw=15, l=0, gc=0
Response-Body-Transformed: Dechunked
Producer: ModSecurity for Apache/2.9.3 (
Server: Apache