ModSecurity-nginx Connector

repository·master·Indexed 23 days ago

https://github.com/owasp-modsecurity/modsecurity-nginx

An nginx module that acts as a bridge allowing nginx to use libmodsecurity (ModSecurity v3) for web application firewall (WAF) capabilities. It includes documentation for compilation as a standard or dynamic module, configuration of ModSecurity directives (such as modsecurity_rules and modsecurity_transaction_id), and detailed build instructions for Windows environments using MSVC, MSYS2, and Docker.

Tokens
2.6K
Snippets
4
Records
8
Agent score
84%

What's inside ModSecurity-nginx

  1. Build ModSecurity-nginx using a Windows Docker container

    master

    A Dockerfile is provided in the docker subdirectory to automate the installation of prerequisites and the building of libModSecurity v3 and nginx with the ModSecurity-nginx module.

    Build the image (run from the win32\docker directory):

    docker build -t modsecurity_nginx:latest -m 4GB .

    Extract built binaries:

    1. Create a container: docker container create --name [container_name] modsecurity_nginx
    2. Copy nginx.exe: docker cp [container_name]:C:\src\nginx\objs\nginx.exe .
    3. Copy libModSecurity.dll: docker cp [container_name]:C:\src\nginx\objs\libModSecurity.dll .

    Run interactively:

    docker run -it modsecurity_nginx
  2. Prerequisites for building ModSecurity-nginx on Windows

    master

    To build ModSecurity-nginx on Windows, you must install the following tools. Note that the build steps assume specific installation paths:

    • Build Tools for Visual Studio 2022: Install the Desktop development with C++ workload (includes MSVC C++ compiler, Windows SDK, and CMake). Assumed path: C:\BuildTools.
    • MSYS2: Required for the nginx build. Assumed path: C:\msys64.
    • Conan package manager 2.2.2: Required to build libModSecurity v3. After installation, you must set up the default Conan profile using the MSVC C++ compiler:
      1. Open a command prompt and execute: C:\BuildTools\VC\Auxiliary\Build\vcvars64.bat
      2. Execute: conan profile detect --force
    • Git for Windows 2.44.0
    • Strawberry Perl for Windows: Required because the MSYS2 Perl implementation does not produce Windows-compatible paths. Assumed path: C:\Strawberry\perl.
  3. Compile and install the ModSecurity-nginx connector

    master

    The ModSecurity-nginx connector is an nginx module that acts as a communication channel between nginx and libmodsecurity (ModSecurity v3).

    Prerequisite: You must have libmodsecurity installed before compiling this connector.

    To install as a standard third-party module, run the following from your nginx source directory:

    ./configure --add-module=/path/to/ModSecurity-nginx

    To build it as a dynamic module (requires the nginx source version to match the version you are compiling for):

    ./configure --add-dynamic-module=/path/to/ModSecurity-nginx --with-compat
  4. Build ModSecurity-nginx on Windows

    master

    Follow these steps to build the ModSecurity-nginx module and nginx on Windows using MSVC and MSYS2:

    1. Initialize Environment: Open a command prompt and set the MSVC environment:
      C:\BuildTools\VC\Auxiliary\Build\vcvars64.bat
    2. Launch MSYS2: From that same prompt, launch the UCRT64 shell to inherit the MSVC environment:
      c:\msys64\ucrt64.exe
    3. Prepare nginx and dependencies: Clone nginx, create an objs/lib directory, and download PCRE2, zlib, and OpenSSL using wget and tar.
    4. Build libModSecurity v3: Clone the ModSecurity repository, initialize submodules, and run vcbuild.bat.
    5. Clone ModSecurity-nginx: Clone the ModSecurity-nginx repository.
    6. Configure Environment Variables: Set up paths for the build process:
      • Remove /usr/bin/link to avoid conflicts with link.exe.
      • Set PATH to include Strawberry Perl.
      • Set LC_ALL=C to avoid locale warnings.
      • Set MODSECURITY_INC and MODSECURITY_LIB to point to the libModSecurity headers and libraries.
    7. Configure and Build nginx: Run the auto/configure script with the appropriate flags (including --add-module=objs/lib/ModSecurity-nginx) and execute nmake to build.
    # 1. Set MSVC environment
    C:\BuildTools\VC\Auxiliary\Build\vcvars64.bat
    
    # 2. Launch MSYS2 UCRT64
    c:\msys64\ucrt64.exe
    
    # ... (clone nginx, download deps, build libModSecurity) ...
    
    # 8. Setup environment variables
    rm /usr/bin/link
    export PATH=/c/Strawberry/perl/bin:$PATH
    export LC_ALL=C
    export MODSECURITY_INC=objs/lib/ModSecurity/headers
    export MODSECURITY_LIB=objs/lib/ModSecurity/build/win32/build/Release
    
    # 9. Configure nginx
    auto/configure \
        --with-cc=cl \
        --with-debug \
        --prefix= \
        --conf-path=conf/nginx.conf \
        --pid-path=logs/nginx.pid \
        --http-log-path=logs/access.log \
        --error-log-path=logs/error.log \
        --sbin-path=nginx.exe \
        --http-client-body-temp-path=temp/client_body_temp \
        --http-proxy-temp-path=temp/proxy_temp \
        --http-fastcgi-temp-path=temp/fastcgi_temp \
        --http-scgi-temp-path=temp/scgi_temp \
        --http-uwsgi-temp-path=temp/uwsgi_temp \
        --with-cc-opt=-DFD_SETSIZE=1024 \
        --with-pcre=objs/lib/pcre2-10.39 \
        --with-zlib=objs/lib/zlib-1.3 \
        --with-openssl=objs/lib/openssl-3.0.13 \
        --with-openssl-opt=no-asm \
        --with-http_ssl_module \
        --with-http_v2_module \
        --with-http_auth_request_module \
        --add-module=objs/lib/ModSecurity-nginx
    
    # 10. Build
    nmake
  5. Configure ModSecurity directives in nginx

    master

    ModSecurity extends nginx configuration via several new directives. These can be used in http, server, or location contexts.

    modsecurity

    Enables or disables the ModSecurity module. This is an nginx flag and is independent of the SecRuleEngine state.

    • Syntax: modsecurity on | off
    • Default: off

    modsecurity_rules_file

    Specifies a local path to a ModSecurity configuration file.

    • Syntax: modsecurity_rules_file <path to rules file>
    • Default: no

    modsecurity_rules_remote

    Downloads a ModSecurity configuration file from a remote URL using an authentication key.

    • Syntax: modsecurity_rules_remote <key> <URL to rules>
    • Default: no

    modsecurity_rules

    Allows injecting ModSecurity rules directly into the nginx configuration string. This is useful for per-location customizations (e.g., SecRuleRemoveById).

    • Syntax: modsecurity_rules <modsecurity rule>
    • Default: no

    modsecurity_transaction_id

    Passes a custom transaction ID from nginx to the library instead of letting the library generate one. This is highly recommended for correlating nginx access logs with ModSecurity error logs using variables like $request_id.

    • Syntax: modsecurity_transaction_id string
    • Default: no

    modsecurity_use_error_log

    Controls whether ModSecurity error log functionality is enabled.

    • Syntax: modsecurity_use_error_log on | off
    • Default: on
    server {
        modsecurity on;
        modsecurity_rules_file /etc/my_modsecurity_rules.conf;
    
        location / {
            root /var/www/html;
        }
    
        location /ops {
            root /var/www/html/opts;
            modsecurity_rules '
              SecRuleEngine On
              SecDebugLog /tmp/modsec_debug.log
              SecDebugLogLevel 9
              SecRuleRemoveById 10
            ';
        }
    }
  6. Debug the ModSecurity-nginx connector

    master

    The connector respects the standard nginx debugging schema. To enable debug messages from the connector, include the --with-debug flag during the nginx configuration phase.

    Core dumps and crashes should be debugged using the same methods used for debugging nginx.

  7. Correlate nginx logs using modsecurity_transaction_id

    master

    To find correlations between nginx access logs and ModSecurity error logs, use modsecurity_transaction_id combined with a custom log_format that includes the nginx $request_id.

    Example configuration:

    log_format extended '$remote_addr - $remote_user [$time_local] '
                        "$request" $status $body_bytes_sent '"$http_referer" "$http_user_agent" $request_id';
    
    server {
        server_name host1;
        modsecurity on;
        modsecurity_transaction_id "host1-$request_id";
        access_log logs/host1-access.log extended;
        error_log logs/host1-error.log;
    }
    log_format extended '$remote_addr - $remote_user [$time_local] '
                        "$request" $status $body_bytes_sent '"$http_referer" "$http_user_agent" $request_id';
    
    server {
        server_name host1;
        modsecurity on;
        modsecurity_transaction_id "host1-$request_id";
        access_log logs/host1-access.log extended;
        error_log logs/host1-error.log;
        location / {
            ...
        }
    }
  8. Run ModSecurity-nginx tests on Windows

    master

    To validate the nginx binary with the ModSecurity-nginx module, follow these steps:

    1. Clone tests: In your nginx build directory, run:
      git clone -c advice.detachedHead=false --depth 1 https://github.com/nginx/nginx-tests.git test
    2. Prepare DLL: Copy libModSecurity.dll from the libModSecurity build directory to the directory containing nginx.exe.
    3. Prepare Test Files: Copy the ModSecurity-nginx tests into the test directory.
    4. Execute Tests: Set the TEST_NGINX_BINARY environment variable and run prove.

    Important Notes:

    • TEST_NGINX_BINARY must use backslashes (e.g., `..\