пятница, 5 ноября 2010 г.

Установка mod_security для Apache2

Началось всё с того, что в еррор логах апача начали появлятся строчки
[Sun Oct 31 07:25:52 2010] [error] [client 187.45.214.10] client sent HTTP/1.1 request without hostname (see RFC2616 section 14.23): /w00tw00t.at.ISC.SANS.DFind:)

Дабы обломать рога горе-хацкерам, которые щупают апач на предмет уязвимостей, я решил поставить специальный модуль для апача, который будет обламывать всякие шаловливые ручонки.
Называется он mod_security

Mod_security is an Apache module whose purpose is to tighten the Web application security. Effectively, it is an intrusion detection and prevention system for the web server.
At the moment its main features are:
* Audit log; store full request details in a separate file, including POST
    payloads.
  * Request filtering; incoming requests can be analysed and offensive requests
    can be rejected (or simply logged, if that is what you want). This feature
    can be used to prevent many types of attacks (e.g. XSS attacks, SQL
    injection, ...) and even allow you to run insecure applications on your
    servers (if you have no other choice, of course).
In addition to this package the mod-security-common package, which includes documentation and configuration examples, will be installed.

Установка

Итак, ставлю под Debian:
apt-get -y install libapache2-mod-security2

Reading package lists...
Building dependency tree...
Reading state information...
The following NEW packages will be installed:
libapache-mod-security
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 122 kB of archives.
After this operation, 324 kB of additional disk space will be used.
Get:1 http://ftp.de.debian.org/debian/ unstable/main libapache-mod-security amd64 2.5.12-1 [122 kB]
Fetched 122 kB in 0s (615 kB/s)
Selecting previously deselected package libapache-mod-security.
(Reading database ... 61659 files and directories currently installed.)
Unpacking libapache-mod-security (from .../libapache-mod-security_2.5.12-1_amd64.deb) ...
Setting up libapache-mod-security (2.5.12-1) ...
Reloading web server config: apache2.

Рестартую апач командой
apache2ctl restart
и после рестарта модуль уже активен и готов к работе.
Если модуль не активен вдруг, его можно включить вручную
a2enmod mod_security2

Так же нужно включить модули headers и unique_id

Настройка

Добавляем в конец конфига апача (/etc/apache2/apache2.conf)

<IfModule mod_security2.c>
# Basic configuration options
SecRuleEngine On
SecRequestBodyAccess On
SecResponseBodyAccess Off

# PCRE Tuning
SecPcreMatchLimit 1000
SecPcreMatchLimitRecursion 1000

# Handling of file uploads
# TODO Choose a folder private to Apache.
# SecUploadDir /opt/apache-frontend/tmp/
SecUploadKeepFiles Off
SecUploadFileLimit 10

# Debug log
SecDebugLog /var/log/apache2/modsec_debug.log
SecDebugLogLevel 0

# Serial audit log
SecAuditEngine RelevantOnly
SecAuditLogRelevantStatus ^5
SecAuditLogParts ABIFHZ
SecAuditLogType Serial
SecAuditLog /var/log/apache2/modsec_audit.log

# Maximum request body size we will
# accept for buffering
SecRequestBodyLimit 131072

# Store up to 128 KB in memory
SecRequestBodyInMemoryLimit 131072

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

# 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_PROCESSOR_ERROR "!@eq 0" \
"phase:2,t:none,log,deny,msg:'Failed to parse request body.',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.
SecRule MULTIPART_STRICT_ERROR "!@eq 0" \
"phase:2,t:none,log,deny,msg:'Multipart request body \
failed strict validation: \
PE %{REQBODY_PROCESSOR_ERROR}, \
BQ %{MULTIPART_BOUNDARY_QUOTED}, \
BW %{MULTIPART_BOUNDARY_WHITESPACE}, \
DB %{MULTIPART_DATA_BEFORE}, \
DA %{MULTIPART_DATA_AFTER}, \
HF %{MULTIPART_HEADER_FOLDING}, \
LF %{MULTIPART_LF_LINE}, \
SM %{MULTIPART_SEMICOLON_MISSING}, \
IQ %{MULTIPART_INVALID_QUOTING}, \
IH %{MULTIPART_INVALID_HEADER_FOLDING}, \
IH %{MULTIPART_FILE_LIMIT_EXCEEDED}'"

# Did we see anything that might be a boundary?
SecRule MULTIPART_UNMATCHED_BOUNDARY "!@eq 0" \
"phase:2,t:none,log,deny,msg:'Multipart parser detected a possible unmatched boundary.'"

# 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" \
"phase:2,t:none,deny,msg:'ModSecurity internal error flagged: %{MATCHED_VAR_NAME}'"

</IfModule>

Собственно и всё. mod_security готов к работе с минимальной конфигурацией.

Правила-Сигнатуры (Опционально)

С офф сайта или с сорцфорджа можно скачать уже готовые правила для этого модуля. Сами правила сидят в архиве с модулем.
Распаковываем их к примеру в /etc/mod_security (каталог необходимо создать самому).
Получится 2 папки:
/etc/mod_security/doc - документация
/etc/mod_security/rules - правила фильтрации

Теперь добавляем 3 строчки в конфиг модуля

<IfModule mod_security2.c>
...
Include /etc/mod_security/rules/*.conf
Include /etc/mod_security/rules/base_rules/*.conf
Include /etc/mod_security/rules/optional_rules/*.conf
</IfModule>

С подключенными сигнатурами конфиг модуля будет следующим:

<IfModule mod_security2.c>
# Basic configuration options
SecRuleEngine On
SecRequestBodyAccess On
SecResponseBodyAccess Off

# PCRE Tuning
SecPcreMatchLimit 1000
SecPcreMatchLimitRecursion 1000

# Handling of file uploads
# TODO Choose a folder private to Apache.
# SecUploadDir /opt/apache-frontend/tmp/
SecUploadKeepFiles Off
SecUploadFileLimit 10

# Debug log
SecDebugLog /var/log/apache2/modsec_debug.log
SecDebugLogLevel 0

# Serial audit log
SecAuditEngine RelevantOnly
SecAuditLogRelevantStatus ^5
SecAuditLogParts ABIFHZ
SecAuditLogType Serial
SecAuditLog /var/log/apache2/modsec_audit.log

# Maximum request body size we will
# accept for buffering
SecRequestBodyLimit 131072

# Store up to 128 KB in memory
SecRequestBodyInMemoryLimit 131072

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

Include /etc/mod_security/rules/*.conf
Include /etc/mod_security/rules/base_rules/*.conf
Include /etc/mod_security/rules/optional_rules/*.conf

</IfModule>

Теперь запускаем апач и радуемся спокойной жизни
apache2ctl start

PS Впрочем этот модуль не отменяет iptables и snort. Так что не расслабляйтесь.

Комментариев нет: