"""Zabbix 7.4 CVE-2026-23933 prober v6.

Detection order per host:
  1. HEAD / and HEAD /zabbix/  -> Set-Cookie zbx_session (works even when API is closed)
  2. fallback: POST apiinfo.version on /api_jsonrpc.php and /zabbix/api_jsonrpc.php
For every detected frontend: GET the page (saml/guest markers) + HMAC check of the
cookie against the seeded session key.
"""
import asyncio
import base64
import hashlib
import hmac
import json
import os
import re
import sys
import time
import urllib.parse

import aiohttp

LIST = "/root/recon/scan_zabbix.list"
TAG = sys.argv[1] if len(sys.argv) > 1 else "all"
PORTS = set(int(x) for x in sys.argv[2].split(",")) if len(sys.argv) > 2 else None
STATE = "/root/recon/zabbix6_%s.off" % TAG
HITS = "/root/recon/zabbix6_%s.tsv" % TAG
STAT = "/root/recon/zabbix_probe.log"

KEY = b"0e1e3fb9846cbe4e079a22d38b2db33e"
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0 Safari/537.36",
      "Accept": "*/*"}
API = {"jsonrpc": "2.0", "method": "apiinfo.version", "params": {}, "id": 1}
LINE = re.compile(r"^open tcp (\d+) (\S+) ")
CONC = 4000
PATHS = ("/", "/zabbix/")
done = 0


def log(msg):
    with open(STAT, "a") as f:
        f.write("%s %s\n" % (time.strftime("%H:%M:%S"), msg))


def new_lines():
    if not os.path.exists(LIST):
        return None
    size = os.path.getsize(LIST)
    off = int(open(STATE).read().strip()) if os.path.exists(STATE) else 0
    if size < off:
        off = 0
    if size <= off:
        return None
    out, consumed = [], 0
    with open(LIST, "r", errors="replace") as f:
        f.seek(off)
        for line in f:
            if not line.endswith("\n"):
                break
            m = LINE.match(line)
            if m and (PORTS is None or int(m.group(1)) in PORTS):
                out.append((int(m.group(1)), m.group(2)))
            consumed += len(line.encode("utf-8", "replace"))
    open(STATE, "w").write(str(off + consumed))
    return out or None


def key_state(values):
    for val in values:
        try:
            val = urllib.parse.unquote(val)
            data = json.loads(base64.b64decode(val + "=" * (-len(val) % 4)))
            if not isinstance(data, dict):
                continue
            sign = data.pop("sign", None)
            if not sign:
                continue
            body = json.dumps(data, separators=(",", ":"), ensure_ascii=False).encode()
            return hmac.new(KEY, body, hashlib.sha256).hexdigest() == sign
        except Exception:
            continue
    return None


def zbx_cookies(headers):
    return [h.split("zbx_session=", 1)[1].split(";")[0]
            for h in headers.getall("Set-Cookie", []) if "zbx_session=" in h]


async def head(sess, url):
    async with sess.head(url, ssl=False, allow_redirects=False) as r:
        return r.status, r.headers, zbx_cookies(r.headers)


async def api_ver(sess, url):
    try:
        async with sess.post(url, json=API, ssl=False, allow_redirects=False) as r:
            if r.status != 200:
                return None
            j = json.loads(await r.content.read(600))
        v = j.get("result")
        return v if isinstance(v, str) and v[:1].isdigit() else None
    except Exception:
        return None


async def inspect(sess, base):
    cookies = {}
    for p in PATHS:
        try:
            st, hd, ck = await head(sess, base + p)
            if ck:
                cookies[p] = ck
        except Exception:
            pass
    ver = None
    if not cookies:
        return None
    ui = sorted(cookies, key=lambda p: (len(p), p))[0]
    v = await api_ver(sess, base + ui + "api_jsonrpc.php")
    ver = v or "?"
    key = key_state(cookies.get(ui, []))
    guest = saml = 0
    try:
        async with sess.get(base + ui, ssl=False, allow_redirects=False) as r:
            if r.status < 300:
                body = (await r.content.read(60000)).decode("utf-8", "replace")
                low = body.lower()
                guest = 1 if ("enter=guest" in low or "sign in as guest" in low) else 0
                saml = 1 if "index_sso.php" in low else 0
    except Exception:
        pass
    return ui, ver, key, guest, saml


def src_ok(r):
    return r.status >= 300


async def one(sess, sem, port, ip):
    global done
    scheme = "https" if port == 443 else "http"
    base = "%s://%s:%d" % (scheme, ip, port)
    try:
        async with sem:
            res = await inspect(sess, base)
            if not res:
                return
            ui, ver, key, guest, saml = res
            with open(HITS, "a") as f:
                f.write("\t".join([ip, str(port), ui, ver, {True: "KEYMATCH", False: "key",
                                                            None: "-"}[key],
                                   str(guest), str(saml)]) + "\n")
            log("HIT %s:%s%s ver=%s key=%s guest=%d saml=%d" % (ip, port, ui, ver, key, guest, saml))
    except Exception:
        return
    finally:
        done += 1


async def main():
    timeout = aiohttp.ClientTimeout(total=3.5, connect=1.5, sock_read=3.0)
    sem = asyncio.Semaphore(CONC)
    log("prober6[%s] start conc=%d ports=%s cookie-first" % (TAG, CONC, sorted(PORTS) if PORTS else "all"))
    while True:
        batch = new_lines()
        if batch:
            for i in range(0, len(batch), 50000):
                chunk = batch[i:i + 50000]
                t0 = time.time()
                async with aiohttp.ClientSession(timeout=timeout, headers=UA,
                                                 connector=aiohttp.TCPConnector(limit=0, ssl=False)) as s:
                    await asyncio.gather(*[one(s, sem, p, ip) for p, ip in chunk])
                dt = time.time() - t0
                log("[%s] chunk %d in %.0fs (%.0f/s) total=%d" % (TAG, len(chunk), dt,
                                                                  len(chunk) / max(dt, 1), done))
        else:
            running = os.popen("ps -eo args | grep -c '[m]asscan -p80,443,8080'").read().strip()
            if running == "0":
                log("masscan finished, exit total=%d" % done)
                return
        await asyncio.sleep(60)


asyncio.run(main())
