Monitor an NGINX WAF (ModSecurity + OWASP CRS) with Zabbix (Agent 2 Active Checks, Custom Template + Dashboard)

On this page12 sections

This post shows how to monitor the ModSecurity WAF on NGINX with Zabbix: a small Python script turns the audit log into statistics every minute, Zabbix agent 2 sends them as an active check, and an imported template adds per-site counts, two triggers and a dashboard.

This post is based on

Lab context

  • Web server (example)
    • Host: waf-zbx-web – 172.31.168.156, Ubuntu 26.04 LTS
    • WAF: NGINX 1.28.3 + ModSecurity 3.0.14 + OWASP CRS 4.31.0, blocking (as in the previous post)
    • Zabbix agent 2: 8.0.0
  • Zabbix
    • Zabbix server: 8.0.0, at 172.31.165.225

What you’ll build

  • The site (Host header) in every audit log entry
  • Statistics every minute: refused and flagged requests per site, top rules, attack types, sources
  • Zabbix agent 2 sending them with active checks (the agent connects out to the server)
  • A template with two triggers (WAF switched off, statistics not updated) and a dashboard

Prerequisites

  • The WAF from the previous post, with its audit log at /var/log/nginx/waf-audit.json
  • A Zabbix 8.0 server that the web server reaches on TCP 10051

1. Install Zabbix agent 2

On the web server:

wget -q https://repo.zabbix.com/zabbix/8.0/release/ubuntu/pool/main/z/zabbix-release/zabbix-release_latest_8.0+ubuntu26.04_all.deb
sudo dpkg -i zabbix-release_latest_8.0+ubuntu26.04_all.deb
sudo apt update
sudo apt install -y zabbix-agent2

Point it at the Zabbix server and set the host name you’ll use in Zabbix:

sudo sed -i -e 's/^Server=127.0.0.1$/Server=172.31.165.225/' \
  -e 's/^ServerActive=127.0.0.1$/ServerActive=172.31.165.225/' \
  -e 's/^Hostname=Zabbix server$/Hostname=waf-zbx-web/' /etc/zabbix/zabbix_agent2.conf
sudo grep -E '^(Server|ServerActive|Hostname)=' /etc/zabbix/zabbix_agent2.conf

Expected:

Server=172.31.165.225
ServerActive=172.31.165.225
Hostname=waf-zbx-web

Restart it:

sudo systemctl restart zabbix-agent2
systemctl is-active zabbix-agent2

Expected:

active

2. Name the site in the audit log

The audit log keeps no request headers and can’t tell which site a request is for. Create /etc/nginx/waf/site-label.conf:

# Add "site <Host>" to every request the audit log records (it has no request headers).
SecRule TX:BLOCKING_INBOUND_ANOMALY_SCORE|TX:BLOCKING_OUTBOUND_ANOMALY_SCORE "@gt 0" \
    "id:9500900,phase:5,pass,log,auditlog,t:none,msg:'site %{REQUEST_HEADERS.host}'"

It runs at the end of a request and only when a rule scored it: a clean request still isn’t logged.

Load it after the CRS rules:

echo 'Include /etc/nginx/waf/site-label.conf' | sudo tee -a /etc/nginx/waf/main.conf
sudo nginx -t && sudo systemctl reload nginx

Expected:

Include /etc/nginx/waf/site-label.conf
… ModSecurity-nginx v1.0.3 (rules loaded inline/local/remote: 0/860/0)
nginx: configuration file /etc/nginx/nginx.conf test is successful

Send the test attack and read the label:

curl -s -o /dev/null -w '%{http_code}\n' 'http://localhost/?q=%3Cscript%3Ealert(1)%3C/script%3E'
sudo tail -n 1 /var/log/nginx/waf-audit.json | grep -o '"message":"site [^"]*"'

Expected:

403
"message":"site localhost"

3. Build the statistics (systemd timer)

Create the directory:

sudo install -d /usr/local/lib/waf-stats

Create /usr/local/lib/waf-stats/waf_stats.py:

#!/usr/bin/python3
# WAF statistics for Zabbix: reads the new lines of the ModSecurity audit log, writes /var/lib/waf-stats/stats.json.
import grp
import json
import os
import re
import time
from collections import Counter

AUDIT = "/var/log/nginx/waf-audit.json"
SWITCH = "/etc/nginx/conf.d/waf.conf"
DIR = "/var/lib/waf-stats"
STATE, OUT = DIR + "/state.json", DIR + "/stats.json"
DAY = 86400
SKIP = {"949110", "959100", "980170", "980130", "9500900"}  # scoring and reporting rules


def load(path, default):
    try:
        with open(path, encoding="utf-8") as f:
            return json.load(f)
    except (OSError, ValueError):
        return default


def write(path, obj, mode, gid=0):
    with open(path + ".new", "w", encoding="utf-8") as f:
        json.dump(obj, f)
    os.chown(path + ".new", 0, gid)
    os.chmod(path + ".new", mode)
    os.replace(path + ".new", path)


def new_lines(st):
    try:
        s = os.stat(AUDIT)
    except FileNotFoundError:
        return []
    if "inode" not in st:  # first run: start at the end (older entries have no site label)
        st["inode"], st["offset"] = s.st_ino, s.st_size
    if st["inode"] != s.st_ino or s.st_size < st["offset"]:  # rotated
        st["inode"], st["offset"] = s.st_ino, 0
    with open(AUDIT, "rb") as f:
        f.seek(st["offset"])
        data = f.read(64 * 1024 * 1024)
    end = data.rfind(b"\n") + 1
    st["offset"] += end
    return data[:end].decode("utf-8", "replace").splitlines()


def event(line):
    t = json.loads(line)["transaction"]
    msgs = [m for m in t.get("messages") or [] if (m.get("details") or {}).get("ruleId")]
    ids = [m["details"]["ruleId"] for m in msgs]
    site = next((m["message"][5:].strip().lower().split(":")[0] for m in msgs
                 if m["details"]["ruleId"] == "9500900" and m.get("message", "").startswith("site ")), "") or "unknown"
    found = [m for m in msgs if m["details"]["ruleId"] not in SKIP]
    req = t.get("request") or {}
    return {
        "ts": int(time.mktime(time.strptime(t["time_stamp"], "%a %b %d %H:%M:%S %Y"))),
        "site": site,
        "ip": t.get("client_ip", ""),
        "refused": "949110" in ids and (t.get("response") or {}).get("http_code") == 403,
        "request": req.get("method", "") + " " + str(req.get("uri", "")).split("?", 1)[0][:80],
        "rules": [m["details"]["ruleId"] for m in found][:6],
        "names": {m["details"]["ruleId"]: m.get("message", "")[:90] for m in found},
        "types": sorted({g[7:] for m in found for g in m["details"].get("tags", []) if g.startswith("attack-")}),
    }


def main():
    now = int(time.time())
    st = load(STATE, {"totals": {}, "events": [], "names": {}})
    for line in new_lines(st):
        try:
            e = event(line)
        except (ValueError, KeyError, TypeError):
            continue
        tot = st["totals"].setdefault(e["site"], {"refused": 0, "flagged": 0})
        tot["refused" if e["refused"] else "flagged"] += 1
        st["names"].update(e.pop("names"))
        st["events"].append(e)
    st["events"] = events = [e for e in st["events"] if e["ts"] >= now - DAY][-50000:]
    st["names"] = dict(list(st["names"].items())[-2000:])
    write(STATE, st, 0o600)

    refused = [e for e in events if e["refused"]]
    per_site = Counter((e["site"], e["refused"]) for e in events)
    rules = Counter(r for e in events for r in e["rules"])
    types = Counter(t for e in events for t in e["types"])
    sources = Counter(e["ip"] for e in events)
    switch = open(SWITCH, encoding="utf-8").read() if os.path.exists(SWITCH) else ""
    stats = {
        "generated": now,
        "waf_on": int(bool(re.search(r"(?m)^\s*modsecurity\s+on\s*;", switch))),
        "refused_total": sum(v["refused"] for v in st["totals"].values()),
        "flagged_total": sum(v["flagged"] for v in st["totals"].values()),
        "refused_24h": len(refused),
        "flagged_24h": len(events) - len(refused),
        "sites": [{"site": s, "refused": v["refused"], "flagged": v["flagged"],
                   "refused_24h": per_site[(s, True)], "flagged_24h": per_site[(s, False)]}
                  for s, v in sorted(st["totals"].items())],
        "top_rules_24h": "\n".join(f"{n:>6}  {r}  {st['names'].get(r, '')}" for r, n in rules.most_common(15)) or "none",
        "attack_types_24h": "\n".join(f"{n:>6}  {t}" for t, n in types.most_common(12)) or "none",
        "top_sources_24h": "\n".join(f"{n:>6}  {ip}" for ip, n in sources.most_common(15)) or "none",
        "latest_refused": "\n".join(f"{time.strftime('%m-%d %H:%M:%S', time.localtime(e['ts']))}  {e['site']}  {e['ip']}  "
                                    f"{e['request']}  [{' '.join(e['rules'])}]" for e in reversed(refused[-15:])) or "none",
    }
    write(OUT, stats, 0o640, grp.getgrnam("zabbix").gr_gid)


if __name__ == "__main__":
    main()

What it does:

  • Reads only new audit log lines (its place is in state.json), starting at the end on the first run.
  • Refused: rule 949110 fired and the response is 403. Any other entry is flagged (let through).
  • Writes stats.json as root:zabbix 0640: the agent reads it, not the audit log.
  • Takes waf_on from /etc/nginx/conf.d/waf.conf (the file, not the running NGINX).

Make it executable:

sudo chmod 755 /usr/local/lib/waf-stats/waf_stats.py

Create /etc/systemd/system/waf-stats.service:

[Unit]
Description=WAF statistics for Zabbix
After=nginx.service

[Service]
Type=oneshot
ExecStart=/usr/local/lib/waf-stats/waf_stats.py
StateDirectory=waf-stats
StateDirectoryMode=0755
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateNetwork=yes
NoNewPrivileges=yes

Create /etc/systemd/system/waf-stats.timer:

[Unit]
Description=WAF statistics for Zabbix, every minute

[Timer]
OnBootSec=1min
OnUnitActiveSec=1min
AccuracySec=5s

[Install]
WantedBy=timers.target

Enable the timer:

sudo systemctl daemon-reload
sudo systemctl enable --now waf-stats.timer

Check:

sudo ls -l /var/lib/waf-stats/

Expected (example):

-rw------- 1 root root    74 Nov 28 15:12 state.json
-rw-r----- 1 root zabbix 233 Nov 28 15:12 stats.json

4. Import the template (Zabbix)

  • Download zabbix-nginx-waf-1.0.zip and extract nginx-waf-by-zabbix-agent-active.yaml (Zabbix 8.0 format)
  • Data collection → Templates → Import → choose the file → Import
  • Review the Added list → Import again. You should see Imported successfully.
The Added list of the template import

The template reads stats.json once a minute with one active item (vfs.file.contents). Dependent items split it, and discovery adds four items per site.

5. Create the host (Zabbix)

  • Data collection → Hosts → Create host
  • Host name: waf-zbx-web (the agent’s Hostname)
  • Templates: Nginx WAF by Zabbix agent active
  • Host groups: Linux servers
  • Interfaces: none (active checks only) → Add
The new host with the WAF template

6. Verify

After a minute or two, Monitoring → Hosts shows a green ZBX for the host. On the web server, send three attacks and one request by IP address:

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/?id=1%27%20OR%20%271%27=%271'
curl -s -o /dev/null -w '%{http_code}\n' 'http://localhost/?file=../../../../etc/passwd'
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1/

Expected:

403
403
403
200

The last one scores below the threshold (rule 920350, numeric Host header): it’s flagged and let through. A minute later:

sudo python3 -m json.tool /var/lib/waf-stats/stats.json | head -n 22

Expected (example):

{
    "generated": 1795878974,
    "waf_on": 1,
    "refused_total": 3,
    "flagged_total": 1,
    "refused_24h": 3,
    "flagged_24h": 1,
    "sites": [
        {
            "site": "127.0.0.1",
            "refused": 0,
            "flagged": 1,
            "refused_24h": 0,
            "flagged_24h": 1
        },
        {
            "site": "localhost",
            "refused": 3,
            "flagged": 0,
            "refused_24h": 3,
            "flagged_24h": 0
        }

Monitoring → Hosts → in the waf-zbx-web row, click Dashboards:

The top of the Nginx WAF: Overview dashboard
The rules, attack types and sources on the dashboard

A new site’s own line starts a minute after its first entry: its first requests show on the all sites line only.

7. Test the alert

Switch the WAF off:

sudo sed -i 's/^modsecurity on;/modsecurity off;/' /etc/nginx/conf.d/waf.conf
sudo nginx -t && sudo systemctl reload nginx

Within two minutes, Monitoring → Problems shows WAF is switched off:

The WAF is switched off problem

Switch it back on:

sudo sed -i 's/^modsecurity off;/modsecurity on;/' /etc/nginx/conf.d/waf.conf
sudo nginx -t && sudo systemctl reload nginx

The problem resolves at the next update. The other trigger, WAF statistics are not updated, fires when stats.json is 10 minutes old (e.g., the timer stopped).

Summary

You now have the WAF’s refused and flagged requests per site in Zabbix, and an alert when the WAF is switched off or its statistics stop.

Leave a Comment

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

Scroll to Top