ThisCalculator

Everyday

Add a WAF in Front of Your Node.js API

Updated · Standard formula, shown below

This guide walks you through placing a web application firewall (WAF) in front of your Node.js API to filter and monitor HTTP traffic before it reaches your application. You’ll learn how to set up a reverse proxy with a WAF layer, configure rules, and test that legitimate requests pass while malicious ones are blocked. You’ll need a server running your Node.js API, root or sudo access, and a domain name pointing to that server (recommended for TLS).

What You’ll Need

  • A Linux server (Ubuntu 22.04 or similar) with your Node.js API already running and listening on a local port (e.g., 3000).
  • Root or sudo access to install packages and edit configuration files.
  • A domain name (like api.example.com) with an A record pointing to your server’s public IP, if you want HTTPS.
  • Basic familiarity with the command line and editing files with nano or vim.

Step-by-Step

  1. Install Nginx and the ModSecurity WAF engine. On Ubuntu, run: sudo apt update && sudo apt install nginx libmodsecurity3-dev. This installs the Nginx web server and the ModSecurity library, which provides the core WAF functionality.
  2. Build the Nginx ModSecurity connector. The connector is a dynamic module that lets Nginx use ModSecurity. Clone the repository and compile it: git clone --depth 1 https://github.com/SpiderLabs/ModSecurity-nginx.git, then cd ModSecurity-nginx. You’ll need the Nginx source: sudo apt install dpkg-dev, then apt-get source nginx (enable source repos in /etc/apt/sources.list if needed). Compile with: sudo ./configure --with-compat --add-dynamic-module=../ModSecurity-nginx (after extracting the Nginx source and running ./configure there). Then sudo make modules. Copy the resulting objs/ngx_http_modsecurity_module.so to /usr/share/nginx/modules/.
  3. Enable the module in Nginx. Create a file /etc/nginx/modules-enabled/60-modsecurity.conf containing: load_module modules/ngx_http_modsecurity_module.so;. Test with sudo nginx -t.
  4. Download the OWASP Core Rule Set (CRS). This is a set of rules that detect common attacks like SQL injection and XSS. Run: sudo git clone https://github.com/coreruleset/coreruleset /etc/nginx/modsecurity/coreruleset. Then copy the example config: sudo cp /etc/nginx/modsecurity/coreruleset/crs-setup.conf.example /etc/nginx/modsecurity/coreruleset/crs-setup.conf.
  5. Create a ModSecurity configuration file. Create /etc/nginx/modsecurity/modsecurity.conf with the following minimum content: SecRuleEngine On (or DetectionOnly to test first), SecRequestBodyAccess On, SecResponseBodyAccess Off, SecAuditEngine RelevantOnly, SecAuditLog /var/log/modsec_audit.log, and Include /etc/nginx/modsecurity/coreruleset/crs-setup.conf and Include /etc/nginx/modsecurity/coreruleset/rules/*.conf.
  6. Configure Nginx to proxy to your Node.js API and enable ModSecurity. Edit your site configuration (e.g., /etc/nginx/sites-available/api) to look like this:
    server {
        listen 80;
        server_name api.example.com;
    
        modsecurity on;
        modsecurity_rules_file /etc/nginx/modsecurity/modsecurity.conf;
    
        location / {
            proxy_pass http://localhost:3000;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }

    Then enable the site: sudo ln -s /etc/nginx/sites-available/api /etc/nginx/sites-enabled/ and remove the default if needed.

  7. Test and restart Nginx. Run sudo nginx -t to check for syntax errors, then sudo systemctl restart nginx.
  8. Test with a benign request. Send a GET request to your API: curl http://api.example.com/health. You should get your normal response. Check the ModSecurity audit log (sudo tail -f /var/log/modsec_audit.log) to see that requests are being logged.
  9. Test with a malicious request. Try a simple SQL injection payload: curl "http://api.example.com/items?id=1 OR 1=1". If ModSecurity is in On mode, you should get a 403 Forbidden response. If you used DetectionOnly, the request will pass but be logged.
  10. Set up HTTPS (recommended). Use Certbot to obtain a free SSL certificate: sudo apt install certbot python3-certbot-nginx, then sudo certbot --nginx -d api.example.com. This will automatically update your Nginx config to listen on 443 and redirect HTTP.

Common Mistakes

  • Forgetting to load the module: If you skip step 3, Nginx will fail to start with an “unknown directive modsecurity” error.
  • Using the wrong path for the rules: The Include directives in modsecurity.conf must point to the actual location of the CRS files. Double-check that the files exist.
  • Blocking all traffic: If you set SecRuleEngine On before testing, you might block legitimate requests due to false positives. Always start in DetectionOnly mode and monitor logs.
  • Not setting proxy headers: Without proxy_set_header X-Real-IP, your Node.js app will see the proxy’s IP instead of the client’s IP, which can break logging or rate limiting.
  • Placing ModSecurity in the wrong server block: The modsecurity directives must be inside the server block, not in http (unless you want it globally).

Tips

  • Start in DetectionOnly mode: This logs violations without blocking, letting you tune rules before enforcing them.
  • Use the OWASP CRS with recommended config: The CRS includes a crs-setup.conf with many options; review the comments to adjust sensitivity (e.g., SecDefaultAction).
  • Whitelist legitimate endpoints: If your API has public endpoints that trigger false positives (like a search endpoint with special characters), add exclusion rules in a separate file included after the CRS.
  • Monitor logs regularly: Set up log rotation for /var/log/modsec_audit.log to avoid disk filling.
  • Keep CRS updated: Periodically pull the latest CRS to get new rules for emerging threats.

Troubleshooting

  • Nginx fails to start after adding the module: Run sudo nginx -t to see the exact error. If it says “unknown directive modsecurity”, the module isn’t loaded. Check that the .so file exists and the load_module path is correct.
  • All requests get 403 even benign ones: This usually means a rule is too strict. Switch to DetectionOnly and check the audit log to see which rule triggered. You can then add a SecRuleRemoveById directive for that rule ID in a custom file.
  • Requests are not being logged: Ensure SecAuditEngine is set to RelevantOnly or On, and that the audit log file is writable by the Nginx user (www-data).
  • HTTPS not working after Certbot: If you get a certificate error, make sure your domain resolves to the server and that port 443 is open in your firewall. Run sudo certbot renew --dry-run to test.
  • Node.js API unreachable after configuring proxy: Verify your Node.js app is still listening on the correct port (e.g., netstat -tulpn | grep 3000). Also check that proxy_pass uses the exact address and port.

Frequently Asked Questions

Do I need a WAF if I already validate input in my Node.js code?

Yes, defense in depth. A WAF catches attacks that your code might miss, such as protocol violations or known exploit patterns, and it can also protect against zero-day attacks before you patch your code.

Will a WAF slow down my API?

There is some overhead because every request is inspected, but with a well-configured Nginx and ModSecurity, the impact is usually minimal (a few milliseconds). You can mitigate by using caching or offloading WAF to a CDN.

Can I use a cloud WAF instead of self-hosting?

Yes, services like AWS WAF, Cloudflare, or Akamai offer managed WAFs that are easier to set up and scale. This guide is for self-hosting with Nginx, which gives you full control and no per-request costs.

How do I update the OWASP CRS?

Simply pull the latest from GitHub: sudo git -C /etc/nginx/modsecurity/coreruleset pull, then restart Nginx. Always test in DetectionOnly mode first.

What if my API uses WebSockets? Will ModSecurity block them?

ModSecurity can inspect WebSocket handshakes but not the data frames. You may need to exclude WebSocket upgrade requests from body inspection. Add a rule to skip SecRuleEngine for @rx ^/socket if needed.

Can I run ModSecurity with Node.js directly without Nginx?

There is no official ModSecurity connector for Node.js. The common approach is to use a reverse proxy like Nginx or HAProxy, which is what this guide does. Alternatively, use a Node.js middleware like node-modsecurity (community project) but it’s less maintained.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.