import asyncio, json, os, re, time

import aiohttp

LIST = "/root/recon/scan_zabbix.list"
STATE = "/root/recon/zabbix_probe.off"
HITS = "/root/recon/zabbix_hits.tsv"
STAT = "/root/recon/zabbix_probe.log"

UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0 Safari/537.36",
      "Accept": "text/html,application/xhtml+xml,*/*;q=0.8"}

LINE = re.compile(r"^open tcp (\d+) (\S+) ")
CONC = 5000
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:
                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


def score_of(headers, body):
    cookie = " ".join(v for k, v in headers.items() if k.lower() == "set-cookie")
    head = body[:20000]
    s = 0
    if "zbx_session" in cookie:
        s += 3
    if "Zabbix" in head:
        s += 2
    if "/assets/" in head or "zbx_" in head:
        s += 1
    if "zabbix" in headers.get("Server", "").lower():
        s += 1
    return s


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:
            async with sess.get(base + "/", ssl=False) as r:
                body = (await r.content.read(30000)).decode("utf-8", "replace")
                hdrs = dict(r.headers)
                st = r.status
            s = score_of(hdrs, body)
            if s < 3:
                return
            ver = ""
            try:
                async with sess.post(base + "/api_jsonrpc.php",
                                     json={"jsonrpc": "2.0", "method": "apiinfo.version",
                                           "params": {}, "id": 1},
                                     ssl=False, allow_redirects=False) as vr:
                    ver = str(json.loads(await vr.content.read(4000)).get("result", ""))
            except Exception:
                pass
            guest = saml = 0
            try:
                async with sess.get(base + "/index.php", ssl=False, allow_redirects=False) as gr:
                    g = (await gr.content.read(40000)).decode("utf-8", "replace").lower()
                    guest = 1 if "guest" in g else 0
                    saml = 1 if ("saml" in g or "sso" in g) else 0
            except Exception:
                pass
            with open(HITS, "a") as f:
                f.write("\t".join([ip, str(port), str(st), ver, str(s), str(guest), str(saml),
                                   hdrs.get("Server", "")[:30].replace("\t", " ")]) + "\n")
            log("HIT %s:%s ver=%s score=%d guest=%d saml=%d" % (ip, port, ver, s, guest, saml))
    except Exception:
        return
    finally:
        done += 1


async def main():
    timeout = aiohttp.ClientTimeout(total=3.5, connect=2, sock_read=3)
    sem = asyncio.Semaphore(CONC)
    log("prober3 start conc=%d chunk=50k" % CONC)
    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("chunk %d in %.0fs (%.0f/s) total=%d" % (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())
