nginx

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/modules
git clone https://github.com/SpiderLabs/ModSecurity
cd ModSecurity
git submodule init
git submodule update
./build.sh
./configure
make
sudo 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.git
cd ../../..
./configure --with-compat --add-dynamic-module=./src/http/modules/ModSecurity-nginx
make modules
sudo 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-crs
sudo git clone https://github.com/coreruleset/coreruleset /usr/local/modsecurity-crs
sudo mv /usr/local/modsecurity-crs/crs-setup.conf.example /usr/local/modsecurity-crs/crs-setup.conf
sudo 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.conf
sudo mkdir -p /etc/nginx/modsec
sudo cp /opt/ModSecurity/unicode.mapping /etc/nginx/modsec
sudo cp /opt/ModSecurity/modsecurity.conf-recommended /etc/nginx/modsec/modsecurity.conf
sudo sed -i 's/SecRuleEngine DetectionOnly/SecRuleEngine On/' /etc/nginx/modsec/modsecurity.conf
sudo nano /etc/nginx/modsec/main.conf

Add the following three lines into the nano window and save the file:

Include /etc/nginx/modsec/modsecurity.conf
Include /usr/local/modsecurity-crs/crs-setup.conf
Include /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.