Модуль проверяет возможность принимать куки, есть боты которые полностью умеют имитировать поведение, но во первых не у всех они есть и так защитимся хотя бы от “тупых” атак. настройка проводится на debian.
Установка модуля Testcookie nginx module
-
Если у вас уже установлен nginx то приступаем, если нет то ставим его как обычно из оф репозитория или через панель управления.
-
Смотрим опции компиляции и версию у установленного nginx
nginx -V
У меня вывод команды следующий:
nginx version: nginx/1.16.1
built by gcc 6.3.0 20170516 (Debian 6.3.0-18+deb9u1)
built with OpenSSL 1.1.0f 25 May 2017 (running with OpenSSL 1.1.0l 10 Sep 2019)
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-g -O2 -fdebug-prefix-map=/home/jenkins/workspace/Nginx_packages/label/debian9amd64/nginx-1.16.1=. -fstack-protector-strong -Wformat -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -Wl,--as-needed -pie'
- сохраняем куда ни будь в текстовый редактор вывод команды нам пригодится в дальнейшем
- скачиваем модуль
cd /usr/src
git clone https://github.com/kyprizel/testcookie-nginx-module.git
- ставим зависимости
apt-get install -y libxml2-dev libxslt-dev libgd2-xpm-dev libgeoip-dev
- Собираем модуль:
cd /usr/src
- Не забываем во всех командах сменить версию nginx на ранее установленную.
wget 'http://nginx.org/download/nginx-1.16.1.tar.gz'
tar -xzvf nginx-1.16.1.tar.gz
cd nginx-1.16.1/
.configure
параметры берем из выдачи nginx -V, необходимо добавить:
–add-dynamic-module=/usr/src/testcookie-nginx-module
./configure --add-dynamic-module=/usr/src/testcookie-nginx-module --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt=‘-g -O2 -fdebug-prefix-map=/home/jenkins/workspace/Nginx_packages/label/debian9amd64/nginx-1.16.1=. -fstack-protector-strong -Wformat -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fPIC’ --with-ld-opt=‘-Wl,-z,relro -Wl,-z,now -Wl,–as-needed -pie’
- в процессе конфигурирования могут вылезти ошибки:
ошибки:
Ошибка:
./configure: error: the HTTP rewrite module requires the PCRE library.
You can either disable the module by using --without-http_rewrite_module
option, or install the PCRE library into the system, or build the PCRE library
statically from the source with nginx by using --with-pcre= option.
Для Debian/Ubunru исправляется установкой libpcre+±dev:
aptitude install libpcre++-dev
Для CentOS исправляется установкой pcre-devel:
yum install pcre-devel
Ошибка:
./configure: error: SSL modules require the OpenSSL library.
You can either do not enable the modules, or install the OpenSSL library
into the system, or build the OpenSSL library statically from the source
with nginx by using --with-openssl= option.
Для Debian/Ubunru:
aptitude install libssl-dev
Для CentOS:
yum install openssl-devel
Ошибка:
./configure: error: the GeoIP module requires the GeoIP library.
You can either do not enable the module or install the library.
Для Debian/Ubunru:
aptitude install libgeoip-dev
Для CentOS:
yum install GeoIP-devel
Ошибка:
./configure: error: the HTTP XSLT module requires the libxml2/libxslt
libraries. You can either do not enable the module or install the libraries.
Для Debian/Ubunru:
aptitude install libxslt1-dev
Для CentOS:
yum install libxslt-devel
-
Каждый раз после aptitude install или yum install недостающего пакета запускаем заново ./configure со всеми аргументами.
-
При успешном конфигурировании увидим что то похожее на это:
Configuration summary
+ using threads
+ using system PCRE library
+ using system OpenSSL library
+ using system zlib librarynginx path prefix: "/etc/nginx" nginx binary file: "/usr/sbin/nginx" nginx modules path: "/usr/lib/nginx/modules" nginx configuration prefix: "/etc/nginx" nginx configuration file: "/etc/nginx/nginx.conf" nginx pid file: "/var/run/nginx.pid" nginx error log file: "/var/log/nginx/error.log" nginx http access log file: "/var/log/nginx/access.log" nginx http client request body temporary files: "/var/cache/nginx/client_temp" nginx http proxy temporary files: "/var/cache/nginx/proxy_temp" nginx http fastcgi temporary files: "/var/cache/nginx/fastcgi_temp" nginx http uwsgi temporary files: "/var/cache/nginx/uwsgi_temp" nginx http scgi temporary files: "/var/cache/nginx/scgi_temp"
-
Собираем
make
make install
- перезагружаем nginx
service nginx restart
- проверяем что nginx собрался с нужным нам модулем
nginx -V
nginx version: nginx/1.16.1
built by gcc 6.3.0 20170516 (Debian 6.3.0-18+deb9u1)
built with OpenSSL 1.1.0l 10 Sep 2019
TLS SNI support enabled
configure arguments: –add-dynamic-module=/usr/src/testcookie-nginx-module --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt=‘-g -O2 -fdebug-prefix-map=/home/jenkins/workspace/Nginx_packages/label/debian9amd64/nginx-1.16.1=. -fstack-protector-strong -Wformat -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fPIC’ --with-ld-opt=‘-Wl,-z,relro -Wl,-z,now -Wl,–as-needed -pie’
- Далее необходимо настроить и включить модуль.
Настройка модуля
Основная настройка сводится к правке nginx.conf, особое внимание стоит уделить параметрам testcookie_secret и testcookie_arg .
- Генерируем значения. вводное слово может быть любое
echo label |md5sum
60dfc1df138fe8e01579587a404eaa0b -
echo defcon |md5sum
d34a804b22b5a9e378d6a2e04e9dd58b -
- Значения подставляем в качестве аргументов для testcookie_secret и testcookie_arg .
значение для testcookie_name устанавливайте произвольное.
nano /etc/nginx/nginx.conf
http {
...
testcookie off;
testcookie_name XSAE;
testcookie_secret 60dfc1df138fe8e01579587a404eaa0b;
testcookie_session $remote_addr;
testcookie_arg label_d34a804b22b5a9e378d6a2e04e9dd58b;
testcookie_max_attempts 3;
testcookie_get_only on;
testcookie_internal off;
# используем белые списки
include /etc/nginx/testcookie_whitelist.conf;
...
}
- Создаем движок rewrite’ов в /etc/nginx/testcookie.conf
Cуть в следующем, необходимо делать реврайт конечного урла, но не делать это так чтобы светился параметр редиректа (?label_*)
nano /etc/nginx/testcookie.conf
set $do_rewrite 0;
# проверяем наличие выданной куки
if ($http_cookie ~ "XSAE=[0-9a-f]+") {
set $do_rewrite 1;
}
# если в аргументах присутствует метка выданная модулем, выкусываем её
if ($args ~ "^((.*)(label_d34a804b22b5a9e378d6a2e04e9dd58b&|&label_d34a804b22b5a9e378d6a2e04e9dd58b(.*))|label_d34a804b22b5a9e378d6a2e04e9dd58b)$") {
set $target "$2$4";
set $do_rewrite "1${do_rewrite}";
}
# делаем правильный реврайт, подставляем только урл и другие возможные параметры (без метки)
if ($do_rewrite = 11) {
set $args $target;
rewrite ^.*$ http://$host$uri break;
}
- создаем белый список для поисковиков и систем мониторинга
nano /etc/nginx/testcookie_whitelist.conf
testcookie_whitelist {
# Yandex
77.88.0.0/18;
87.250.224.0/19;
}
- Вносим изменения в /etc/nginx/proxy_headers.conf
nano /etc/nginx/proxy_headers.conf
testcookie on;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
-
Затем в каждый из конфигурационных файлов виртуальных хостов прописываем в начало секции server.
Таким образом в каждом виртуальном хосте мы подгружаем rewrite-движок, и белые списки. Сам механизм testcookie будет работать в случаях когда запросы проксируются на бэкенды и подгружается proxy_headers.confserver {
…
include /etc/nginx/testcookie.conf;
include /etc/nginx/testcookie_whitelist.conf;
…
# пример локейшена
location / {
include /etc/nginx/proxy_headers.conf;
proxy_pass http://upstream;
} -
Перезапускаем.
nginx -t
service nginx reload