"""Check whether a Zabbix frontend signs session cookies with the seeded key.

Cookie format (7.4.x): base64(json({"sessionid": "...", "sign": "<hmac>"}))
sign = HMAC-SHA256(key, json_encode(data without sign))  (PHP json_encode)
"""
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"}


def parse_cookie(jar_value):
    """Return (data_dict, sign) or (None, None). Cookie value is URL-escaped (trailing %3D)."""
    try:
        val = urllib.parse.unquote(jar_value)
        raw = base64.b64decode(val + "=" * (-len(val) % 4))
        data = json.loads(raw)
    except Exception:
        return None, None
    if not isinstance(data, dict):
        return None, None
    sign = data.pop("sign", None)
    return data, sign


def php_json(d):
    """PHP json_encode with default flags for a flat dict of scalars."""
    return json.dumps(d, separators=(",", ":"), ensure_ascii=False).encode()


def check(value):
    data, sign = parse_cookie(value)
    if data is None or not sign:
        return None, None, None
    calc = hmac.new(KEY, php_json(data), hashlib.sha256).hexdigest()
    return data, sign, calc == sign


async def probe(sess, host, path):
    url = "https://%s%s" % (host, path)
    try:
        async with sess.get(url, ssl=False) as r:
            cookies = r.cookies
            val = None
            for c in cookies.values():
                if c.key == "zbx_session":
                    val = c.value
            if val is None:
                raw = r.headers.getall("Set-Cookie", [])
                for h in raw:
                    if h.startswith("zbx_session="):
                        val = h.split(";")[0].split("=", 1)[1]
            if not val:
                return "%s%s -> no-cookie (HTTP %d)" % (host, path, r.status)
            data, sign, ok = check(val)
            if data is None:
                return "%s%s -> undecodable cookie %s" % (host, path, val[:40])
            return "%s%s -> KEY_%s sessionid=%s data=%s" % (
                host, path, "MATCH" if ok else "differs",
                str(data.get("sessionid"))[:12], json.dumps(data)[:90])
    except Exception as e:
        return "%s%s -> err %s" % (host, path, type(e).__name__)


async def main(hosts, paths):
    to = aiohttp.ClientTimeout(total=12, connect=5, sock_read=10)
    sem = asyncio.Semaphore(20)
    async with aiohttp.ClientSession(timeout=to, headers=UA,
                                     connector=aiohttp.TCPConnector(limit=0, ssl=False)) as s:
        async def one(h, p):
            async with sem:
                return await probe(s, h, p)
        res = await asyncio.gather(*[one(h, p) for h in hosts for p in paths])
    for line in res:
        print(line)


if __name__ == "__main__":
    hs = [l.strip() for l in open(sys.argv[1]) if l.strip()]
    ps = sys.argv[2:] or ["/", "/zabbix/"]
    asyncio.run(main(hs, ps))
