HugeServer Knowledgebase

How to install Mod Security on Nginx for CentOS 6 and 7

Introduction

ModSecurity is a toolkit for real-time web application monitoring, logging, and access control. you can consider it as an enabler, there are no hard rules telling you what to do, instead, it is up to you to choose your own path through the available features. The freedom to choose what to do is an essential part of ModSecurity’s identity and goes very well with its open source nature. With full access to the source code, your freedom to choose extends to the ability to customize and extend the tool itself to make it fit your needs.

We are assuming that you have root permission, otherwise, you may start commands with “sudo”.

Nginx+Mod_security

Attention

Building a ModSecurity on a Nginx server is kinda hard because you have to download and compile both of them yourself and installing them through a package installer is not possible for now, meanwhile, you have to install previous releases of the Nginx web server.

Download Nginx and ModSecurity

You can download the compatible version of Nginx and ModSecurity easily with “Wget”:

wget http://nginx.org/download/nginx-1.8.0.tar.gz

wget https://www.modsecurity.org/tarball/2.9.1/modsecurity-2.9.1.tar.gz

Extract them as well:

tar xvzf nginx-1.8.0.tar.gz

tar xvzf modsecurity-2.9.1.tar.gz

And you should download some dependencies so you can compile them:

yum install gcc make automake autoconf libtool pcre pcre-devel libxml2 libxml2-devel curl curl-devel httpd-devel

Compiling ModSecurity with Nginx

Enter the ModSecurity directory:

cd modsecurity-2.9.1

./configure --enable-standalone-module

make

Then we are going to install Nginx with ModSecurity module:

cd nginx-1.8.0
./configure \
> --user=nginx \
> --group=nginx \
> --sbin-path=/usr/sbin/nginx \
> --conf-path=/etc/nginx/nginx.conf \
> --pid-path=/var/run/nginx.pid \
> --lock-path=/var/run/nginx.lock \
> --error-log-path=/var/log/nginx/error.log \
> --http-log-path=/var/log/nginx/access.log \
> --add-module=../modsecurity-2.9.1/nginx/modsecurity

Now we can compile and install Nginx:

make

make install

Configure Nginx and ModSecurity

We have to move the ModSecurity config files to Nginx main directory, execute the commands below:

cp modsecurity-2.9.1/modsecurity.conf-recommended /etc/nginx/

cp modsecurity-2.9.1/unicode.mapping /etc/nginx/

Now we have to rename the ModSecurity config file;

cd /etc/nginx/

mv modsecurity.conf-recommended modsecurity.conf

Open the “nginx.conf” and add the following lines under the directive “location /” it’s about line 47:

nano nginx.conf

ModSecurityEnabled on;
ModSecurityConfig modsecurity.conf;

Save and Exit

Create Nginx user with the command below:

useradd -r nginx

We can test our Nginx config file to check if everything is ok:

cd /usr/sbin/

./nginx -t

You should get something like below:


nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Creating the Nginx Service

It’s time to create the Nginx Service so you can start, stop and see your service status:

Create the init.d script file with your text editor in the following path:

nano /etc/init.d/nginx

Paste the following script in your file then save and exit:


#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig:   - 85 15
# description:  NGINX is an HTTP(S) server, HTTP(S) reverse \
#               proxy and IMAP/POP3 proxy server
# processname: nginx
# config:      /etc/nginx/nginx.conf
# config:      /etc/sysconfig/nginx
# pidfile:     /var/run/nginx.pid

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

nginx="/usr/sbin/nginx"
prog=$(basename $nginx)

NGINX_CONF_FILE="/etc/nginx/nginx.conf"

[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx

lockfile=/var/lock/subsys/nginx

make_dirs() {
   # make required directories
   user=`$nginx -V 2>&1 | grep "configure arguments:.*--user=" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
   if [ -n "$user" ]; then
      if [ -z "`grep $user /etc/passwd`" ]; then
         useradd -M -s /bin/nologin $user
      fi
      options=`$nginx -V 2>&1 | grep 'configure arguments:'`
      for opt in $options; do
          if [ `echo $opt | grep '.*-temp-path'` ]; then
              value=`echo $opt | cut -d "=" -f 2`
              if [ ! -d "$value" ]; then
                  # echo "creating" $value
                  mkdir -p $value && chown -R $user $value
              fi
          fi
       done
    fi
}

start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    make_dirs
    echo -n $"Starting $prog: "
    daemon $nginx -c $NGINX_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

stop() {
    echo -n $"Stopping $prog: "
    killproc $prog -QUIT
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

restart() {
    configtest || return $?
    stop
    sleep 1
    start
}

reload() {
    configtest || return $?
    echo -n $"Reloading $prog: "
    killproc $nginx -HUP
    RETVAL=$?
    echo
}

force_reload() {
    restart
}

configtest() {
  $nginx -t -c $NGINX_CONF_FILE
}

rh_status() {
    status $prog
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart|configtest)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
            ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
        exit 2
esac

Create the “nginx.service” file in the following path:

nano /lib/systemd/system/nginx.service

Paste the following script then save and exit:

[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target

Now you can easily use the following commands to control your Nginx service:

systemctl enable nginx

systemctl start nginx

systemctl restart nginx

systemctl status nginx

Varify ModSecurity working with Nginx properly

 

cd /usr/sbin/

./nginx -V

if you get something like below it means that your Nginx compiled with ModSecurity successfully:


built by gcc 4.4.7 20120313 (Red Hat 4.4.7-18) (GCC)
configure arguments: --user=nginx --group=nginx --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --add-module=../modsecurity-2.9.1/nginx/modsecurity

If you want to check if the ModSecurity module has been loaded on your Nginx successfuly you have to check last lines of your Nginx’s error log:

cd /var/log/nginx/

tail error.log

You have to search for something like below:

[notice] 13285#0: ModSecurity: PCRE compiled version="7.8 "; loaded version="7.8 2008-09-05"

Rule-Set Recommendation

You can also use free ModSecurity  rules that provided by Cyber security companies like:

Comodo

OWASP

Atomic Corp
 

Also, you can find more information about ModSecurity on its official website!

Was this tutorial helpful?

Thank you for your vote.Thank you for your vote.

Similar Posts

6 thoughts on “How to install Mod Security on Nginx for CentOS 6 and 7”

  1. I worked through the documentation of Nginx + modsec
    The steps seemed to work
    When I want to restart Nginx
    I am having trouble
    I was not able to use
    #service nginx restart
    I am getting this error for the above command . help on this is appreciated
    Redirecting to /bin/systemctl start nginx.service
    Failed to get D-Bus connection: Operation not permitted
    I even tried to add nginx.service at the following location
    /lib/systemd/system/nginx.service
    Here is the reference for the script
    https://www.nginx.com/resources/wiki/start/topics/examples/systemd/

    1. Hello Manoj,
      Thanks for sharing your issue with us.
      The article is now updated, you can read the “Creating the Nginx Service” section to address your problem.

  2. Hi. I have start service Nginx successful.
    I try to test some Rule. Example:
    SecRule QUERY_STRING “dkkd” “deny,id:18478”
    But Modsercurity can’t Block URL http://dkkd…….
    Can you helo me fix it?

  3. hello I fallow your steps and work but nginx doesn’t have a number of pid
    centos-enginx systemd[1]: Failed to parse PID from file /run/nginx.pid: Invalid argument
    how can I solve this, thank yuo

Leave a Reply to Amir Alamani Cancel reply

Your email address will not be published. Required fields are marked *

*