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/zabbix_probe_%s.off" % TAG
HITS = "/root/recon/zabbix_hits_%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
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


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


def cookie_key_match(values):
    """True/False when a zbx_session cookie is decodable, None when it is not."""
    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


async def basics(sess, base):
    """Version, seeded-key match, SAML state, guest flag for one frontend base URL."""
    v1, v2 = await asyncio.gather(api_version(sess, base + "/api_jsonrpc.php"),
                                  api_version(sess, base + "/zabbix/api_jsonrpc.php"))
    if v1:
        ver, path = v1, "/"
    elif v2:
        ver, path = v2, "/zabbix/"
    else:
        return None
    key = None
    guest = saml = 0
    # UI may sit on another path than the API answered on; try both.
    for ui in {"/", "/zabbix/"}:
        site = base + ui.rstrip("/")
        try:
            async with sess.get(site + "/", ssl=False, allow_redirects=False) as r:
                hdrs = r.headers
                raw = [h.split("zbx_session=", 1)[1].split(";")[0]
                       for h in hdrs.getall("Set-Cookie", []) if "zbx_session=" in h]
                if key is None:
                    key = cookie_key_match(raw)
                body = (await r.content.read(60000)).decode("utf-8", "replace")
                low = body.lower()
                if not guest and ("enter=guest" in low or "sign in as guest" in low):
                    guest = 1
                if "index_sso.php" in low:
                    saml = 1
        except Exception:
            continue
        if key is not None or saml:
            break
    return ver, path, key, guest, saml


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 basics(sess, base)
            if not res:
                return
            ver, path, key, guest, saml = res
            with open(HITS, "a") as f:
                f.write("\t".join([ip, str(port), path, 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, path, ver, key, guest, saml))
    except Exception:
        return
    finally:
        done += 1


async def main():
    timeout = aiohttp.ClientTimeout(total=3.0, connect=1.5, sock_read=2.5)
    sem = asyncio.Semaphore(CONC)
    log("prober5[%s] start conc=%d ports=%s api+key+saml" % (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())
