Set up ModSecurity with NGinx
published on
This tutorial is an addition to Install the latest version of NGinx, pagespeed and other modules and uses some of the same variables. If you have already installed NGinx from another source you may have to alter some of the variables and / or paths.
Build ModSecurity
First we need to build ModSecurity and this can be done by executing the following commands:
cd nginx-$NGX_VER/src/http/modulesgit clone https://github.com/SpiderLabs/ModSecuritycd ModSecuritygit submodule initgit submodule update./build.sh./configuremakesudo make install
Now download and build the ModSecurity NGinx connector
This won't take as long as the previous step and can be completed by executing the following instructions:
cd ..sudo git clone --depth 1 https://github.com/SpiderLabs/ModSecurity-nginx.gitcd ../../.../configure --with-compat --add-dynamic-module=./src/http/modules/ModSecurity-nginxmake modulessudo cp objs/ngx_http_modsecurity_module.so /etc/nginx/modules
Make sure the ModSecurity module laods with NGinx
Edit your nginx.conf file by executing sudo nano /etc/nginx/nginx.conf then add the following line at the top of the file near the pagespeed load_module command.
load_module /etc/nginx/modules/ngx_http_modsecurity_module.so;
Set up the OWASP ruleset
sudo rm -rf /usr/share/modsecurity-crssudo git clone https://github.com/coreruleset/coreruleset /usr/local/modsecurity-crssudo mv /usr/local/modsecurity-crs/crs-setup.conf.example /usr/local/modsecurity-crs/crs-setup.confsudo mv /usr/local/modsecurity-crs/rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf.example /usr/local/modsecurity-crs/rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.confsudo mkdir -p /etc/nginx/modsecsudo cp /opt/ModSecurity/unicode.mapping /etc/nginx/modsecsudo cp /opt/ModSecurity/modsecurity.conf-recommended /etc/nginx/modsec/modsecurity.confsudo sed -i 's/SecRuleEngine DetectionOnly/SecRuleEngine On/' /etc/nginx/modsec/modsecurity.confsudo nano /etc/nginx/modsec/main.conf
Add the following three lines into the nano window and save the file:
Include /etc/nginx/modsec/modsecurity.confInclude /usr/local/modsecurity-crs/crs-setup.confInclude /usr/local/modsecurity-crs/rules/*.conf
Configure NGinx
You just need to add the following two lines in any server block where you wish to use ModSecurity:
modsecurity on;modsecurity_rules_file /etc/nginx/modsec/main.conf;
Once done make sure to restart NGinx with sudo systemctl restart nginx.
Conclusion
You have now finished installing and setting up ModSecurity to work with NGinx. If you wish to test your installation run curl http://<SERVER-IP/DOMAIN>/index.html?exec=/bin/bash. This command should return an error.
