This post shows how to add a web application firewall (WAF) to NGINX on Ubuntu with ModSecurity and the OWASP Core Rule Set (CRS): it runs in log-only mode first, then blocks what the rules score as an attack, keeps a JSON audit log that rotates daily, and updates the rules weekly.
Lab context
- Web server (example)
- OS: Ubuntu 26.04 LTS
- NGINX: 1.28.3 (Ubuntu package)
- ModSecurity: libmodsecurity 3.0.14 + NGINX connector 1.0.3 (Ubuntu packages)
- OWASP CRS: 4.31.0
- Site: the default site on port 80 (
http://localhost/)
What you’ll build
- ModSecurity loaded in NGINX for every server block
- The OWASP CRS rules, signature-verified before use
- A JSON audit log of flagged requests only, rotated daily
- Log-only mode first, then blocking with
403 - A weekly CRS update that switches back if the new rules fail a test
Prerequisites
NGINX from Ubuntu’s packages, serving a site:
sudo apt update
sudo apt install -y nginxCheck:
curl -s -o /dev/null -w '%{http_code}\n' http://localhost/Expected:
2001. Install the ModSecurity module
Install it from Ubuntu’s packages:
sudo apt install -y libnginx-mod-http-modsecurityThe package enables the module in NGINX:
ls /etc/nginx/modules-enabled/Expected:
10-mod-http-ndk.conf 50-mod-http-modsecurity.confModSecurity comes in two parts:
- libmodsecurity: the engine. It reads the rules, scores each request and decides.
- NGINX connector (
libnginx-mod-http-modsecurity): the module that hands every request to the engine and answers403when the engine blocks. It also adds themodsecuritydirectives used in step 4.
2. Download and verify the OWASP CRS
The engine has no rules of its own. The CRS is the rule set it runs (SQL injection, XSS, command injection, scanners and more), released separately from the engine. Download the release and its signature from the project, then verify it with the project’s key:
CRS_VERSION=4.31.0
cd /tmp
curl -fsSLO https://github.com/coreruleset/coreruleset/releases/download/v$CRS_VERSION/coreruleset-$CRS_VERSION-minimal.tar.gz
curl -fsSLO https://github.com/coreruleset/coreruleset/releases/download/v$CRS_VERSION/coreruleset-$CRS_VERSION-minimal.tar.gz.asc
curl -fsSL https://coreruleset.org/security.asc | gpg --import
gpg --verify coreruleset-$CRS_VERSION-minimal.tar.gz.asc coreruleset-$CRS_VERSION-minimal.tar.gzExpected:
gpg: Good signature from "OWASP Core Rule Set <security@coreruleset.org>" [unknown]
Primary key fingerprint: 3600 6F0E 0BA1 6783 2158 8211 38EE ACA1 AB8A 6E72gpg also warns that the key isn’t certified by a key you trust. That’s normal for a key you’ve just imported.
Extract the release to a folder named after its version, create its setup file, and point /etc/nginx/waf/crs at it:
sudo mkdir -p /etc/nginx/waf
sudo tar -xzf coreruleset-$CRS_VERSION-minimal.tar.gz -C /etc/nginx/waf
sudo mv /etc/nginx/waf/coreruleset-$CRS_VERSION /etc/nginx/waf/crs-$CRS_VERSION
sudo cp /etc/nginx/waf/crs-$CRS_VERSION/crs-setup.conf.example /etc/nginx/waf/crs-$CRS_VERSION/crs-setup.conf
sudo ln -s /etc/nginx/waf/crs-$CRS_VERSION /etc/nginx/waf/crsThe link lets a later update (step 8) switch versions, and switch back, in one step.
3. Configure the ModSecurity engine
Create its working directory:
sudo install -d -o www-data -g www-data -m 750 /var/lib/nginx/modsecurityCreate /etc/nginx/waf/modsecurity.conf:
SecRuleEngine DetectionOnly
SecRequestBodyAccess On
SecRequestBodyLimit 13107200
SecRequestBodyNoFilesLimit 1048576
SecRequestBodyLimitAction ProcessPartial
SecRequestBodyJsonDepthLimit 512
SecArgumentsLimit 1000
SecRule REQUEST_HEADERS:Content-Type "^(?:application(?:/soap\+|/)|text/)xml" "id:200000,phase:1,t:none,t:lowercase,pass,nolog,ctl:requestBodyProcessor=XML"
SecRule REQUEST_HEADERS:Content-Type "^application/json" "id:200001,phase:1,t:none,t:lowercase,pass,nolog,ctl:requestBodyProcessor=JSON"
SecRule REQBODY_ERROR "!@eq 0" "id:200002,phase:2,t:none,log,deny,status:400,msg:'Failed to parse request body.',logdata:'%{reqbody_error_msg}',severity:2"
SecRule MULTIPART_STRICT_ERROR "!@eq 0" "id:200003,phase:2,t:none,log,deny,status:400,msg:'Multipart request body failed strict validation.'"
SecRule TX:/^MSC_/ "!@streq 0" "id:200005,phase:2,t:none,log,deny,msg:'ModSecurity internal error flagged: %{MATCHED_VAR_NAME}'"
SecResponseBodyAccess Off
SecTmpDir /var/lib/nginx/modsecurity
SecDataDir /var/lib/nginx/modsecurity
SecAuditEngine RelevantOnly
SecAuditLogRelevantStatus "^999$"
SecAuditLogParts AHZ
SecAuditLogType Serial
SecAuditLogFormat JSON
SecAuditLog /var/log/nginx/waf-audit.json
SecArgumentSeparator &
SecCookieFormat 0
SecUnicodeMapFile /etc/nginx/unicode.mapping 20127
SecStatusEngine OffSecRuleEngine DetectionOnlylogs matches but doesn’t block yet.- The audit log keeps only requests a rule matched (the status pattern
^999$never matches), and only parts A, H, Z: time, client, request line and matched rules. No headers or bodies: no cookies, no form data. ProcessPartialinspects the first 12.5 MB of a large request body and passes the rest.
Create /etc/nginx/waf/main.conf:
Include /etc/nginx/waf/modsecurity.conf
Include /etc/nginx/waf/crs/crs-setup.conf
Include /etc/nginx/waf/crs/rules/*.conf4. Turn it on in NGINX
Create /etc/nginx/conf.d/waf.conf:
modsecurity on;
modsecurity_rules_file /etc/nginx/waf/main.conf;Every server block inherits it from the http level. Test:
sudo nginx -tExpected:
… ModSecurity-nginx v1.0.3 (rules loaded inline/local/remote: 0/859/0)
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successfulReload:
sudo systemctl reload nginx5. Test in log-only mode
Send a script tag in the query string:
curl -s -o /dev/null -w '%{http_code}\n' 'http://localhost/?q=%3Cscript%3Ealert(1)%3C/script%3E'Expected:
200Check the audit log:
sudo tail -n 1 /var/log/nginx/waf-audit.json | grep -o '"ruleId":"[0-9]*"'Expected:
"ruleId":"941100"
"ruleId":"941110"
"ruleId":"941160"
"ruleId":"941390"
"ruleId":"949110"How CRS decides (anomaly scoring):
- Each matching rule adds to the request’s score: 5 for a critical match.
- Rule 949110 fires when the score reaches the threshold (5 by default). In blocking mode, that’s the
403. - A request no rule matches isn’t logged at all:
sudo wc -l /var/log/nginx/waf-audit.json
curl -s -o /dev/null -w '%{http_code}\n' http://localhost/
sudo wc -l /var/log/nginx/waf-audit.jsonExpected:
1 /var/log/nginx/waf-audit.json
200
1 /var/log/nginx/waf-audit.json6. Switch to blocking
Before you switch, read the audit log for legitimate requests: each one needs a rule exclusion first (not covered here).
Set the engine to On and reload:
sudo sed -i 's/^SecRuleEngine DetectionOnly/SecRuleEngine On/' /etc/nginx/waf/modsecurity.conf
sudo nginx -t && sudo systemctl reload nginxSend the same attack and a normal request:
curl -s -o /dev/null -w '%{http_code}\n' 'http://localhost/?q=%3Cscript%3Ealert(1)%3C/script%3E'
curl -s -o /dev/null -w '%{http_code}\n' http://localhost/Expected:
403
2007. Rotate the audit log
ModSecurity keeps the audit log open and doesn’t reopen it when logrotate signals NGINX, so we copy and truncate it in place. Create /etc/logrotate.d/nginx-waf-audit:
/var/log/nginx/waf-audit.json {
daily
rotate 14
missingok
notifempty
compress
delaycompress
copytruncate
}Force one rotation, then send another attack:
sudo logrotate -f /etc/logrotate.d/nginx-waf-audit
curl -s -o /dev/null -w '%{http_code}\n' 'http://localhost/?q=%3Cscript%3Ealert(1)%3C/script%3E'
sudo wc -l /var/log/nginx/waf-audit.json /var/log/nginx/waf-audit.json.1Expected:
403
1 /var/log/nginx/waf-audit.json
2 /var/log/nginx/waf-audit.json.1
3 totalThe new entry lands in the truncated waf-audit.json, and the earlier ones are in waf-audit.json.1.
8. Update the CRS weekly
Ubuntu updates the engine and the connector with the rest of the system. The CRS changes only when you install a new release, and a systemd timer checks for one every week.
Save the CRS signing key you imported in step 2:
gpg --export 36006F0E0BA167832158821138EEACA1AB8A6E72 | sudo tee /etc/nginx/waf/crs-signing-key.gpg > /dev/nullCreate /usr/local/sbin/crs-update:
#!/bin/bash
# Install the newest OWASP CRS 4.x release that's at least 7 days old.
# Stay on the current one if the signature, nginx -t or the test requests fail.
set -euo pipefail
WAF=/etc/nginx/waf
SITE=${SITE:-http://localhost/}
MIN_AGE_DAYS=${MIN_AGE_DAYS:-7}
current=$(readlink "$WAF/crs")
current=${current##*/crs-}
latest=$(curl -fsSL 'https://api.github.com/repos/coreruleset/coreruleset/releases?per_page=30' | python3 -c '
import calendar, json, re, sys, time
cur, min_age = tuple(map(int, sys.argv[1].split("."))), float(sys.argv[2]) * 86400
new = []
for r in json.load(sys.stdin):
m = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)", r["tag_name"])
age = time.time() - calendar.timegm(time.strptime(r["published_at"], "%Y-%m-%dT%H:%M:%SZ"))
if m and not r["prerelease"] and age > min_age:
v = tuple(map(int, m.groups()))
if v[0] == cur[0] and v > cur:
new.append(v)
print(".".join(map(str, max(new))) if new else "")' "$current" "$MIN_AGE_DAYS")
if [ -z "$latest" ]; then
echo "CRS $current is up to date"
exit 0
fi
echo "Updating CRS $current -> $latest"
cd "$(mktemp -d)"
url=https://github.com/coreruleset/coreruleset/releases/download/v$latest/coreruleset-$latest-minimal.tar.gz
curl -fsSLO "$url"
curl -fsSLO "$url.asc"
gpgv --keyring "$WAF/crs-signing-key.gpg" "coreruleset-$latest-minimal.tar.gz.asc" "coreruleset-$latest-minimal.tar.gz"
tar -xzf "coreruleset-$latest-minimal.tar.gz"
rm -rf "$WAF/crs-$latest"
mv "coreruleset-$latest" "$WAF/crs-$latest"
cp "$WAF/crs-$latest/crs-setup.conf.example" "$WAF/crs-$latest/crs-setup.conf"
ln -sfn "$WAF/crs-$latest" "$WAF/crs"
if nginx -t && systemctl reload nginx && sleep 2 \
&& [ "$(curl -s -o /dev/null -w '%{http_code}' "$SITE")" = 200 ] \
&& [ "$(curl -s -o /dev/null -w '%{http_code}' "$SITE?q=%3Cscript%3Ealert(1)%3C/script%3E")" = 403 ]; then
echo "CRS $latest is active"
find "$WAF" -maxdepth 1 -name 'crs-[0-9]*' ! -name "crs-$latest" ! -name "crs-$current" -exec rm -rf {} +
else
echo "CRS $latest failed the checks, back on $current"
ln -sfn "$WAF/crs-$current" "$WAF/crs"
nginx -t && systemctl reload nginx
exit 1
fiWhat it does:
- It installs only a newer 4.x release (a new major version may change the settings) that’s at least 7 days old.
- The signature must verify against the saved key, not one fetched at update time.
- After switching the link,
nginx -tmust pass, the site must still answer200, and the attack sample must get403. Otherwise it points the link back and reloads. - It keeps the current and the previous version.
Make it executable:
sudo chmod 755 /usr/local/sbin/crs-updateCreate /etc/systemd/system/crs-update.service:
[Unit]
Description=Update the OWASP CRS for ModSecurity
After=network-online.target nginx.service
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/crs-update
PrivateTmp=yesCreate /etc/systemd/system/crs-update.timer:
[Unit]
Description=Weekly OWASP CRS update
[Timer]
OnCalendar=weekly
RandomizedDelaySec=1h
Persistent=true
[Install]
WantedBy=timers.targetEnable the timer:
sudo systemctl daemon-reload
sudo systemctl enable --now crs-update.timerRun it once:
sudo /usr/local/sbin/crs-updateExpected, while no newer release is out:
CRS 4.31.0 is up to dateWith a newer release, it prints Updating CRS 4.31.0 -> <new version>, the gpgv and nginx -t lines, then CRS <new version> is active.
Check the next run:
systemctl list-timers crs-update.timerExpected (example):
NEXT LEFT LAST PASSED UNIT ACTIVATES
Mon 2026-11-30 00:51:09 UTC 1 day 11h - - crs-update.timer crs-update.serviceSummary
You now have ModSecurity and the OWASP CRS blocking attacks on every site this NGINX server hosts, with the rules updated weekly.
