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+) ")


def log(msg):
    with open(STAT, "a") as f:
        f.write("%s %s\n" % (time.strftime("%H:%M:%S"), msg))


def new_lines():
    """(offset, [(port, ip)]) for lines added since the last call. None if nothing new."""
    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 if out else None


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


async def one(sess, sem, port, ip):
    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, allow_redirects=False) as r:
                body = (await r.content.read(40000)).decode("utf-8", "replace")
                hdrs = dict(r.headers)
                score = marks(hdrs, body)
                if score < 3:
                    return
                ver = guest = saml = 0
                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:
                        j = json.loads(await vr.content.read(4000))
                        ver = str(j.get("result", ""))
                except Exception:
                    pass
                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")
                        guest = 1 if "guest" in g.lower() else 0
                        saml = 1 if ("saml" in g.lower() or "sso" in g.lower()) else 0
                except Exception:
                    pass
                rec = [ip, str(port), str(r.status), ver, str(score), str(guest), str(saml),
                       hdrs.get("Server", "")[:30].replace("\t", " ")]
                with open(HITS, "a") as f:
                    f.write("\t".join(rec) + "\n")
                log("HIT %s:%s ver=%s score=%d guest=%d saml=%d" % (ip, port, ver, score, guest, saml))
    except Exception:
        return


async def main():
    timeout = aiohttp.ClientTimeout(total=8, connect=4, sock_read=6)
    sem = asyncio.Semaphore(700)
    log("prober start")
    while True:
        batch = new_lines()
        if batch:
            log("batch %d" % len(batch))
            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 batch])
        else:
            running = os.popen("ps -eo args | grep -c '[m]asscan -p80,443,8080'").read().strip()
            if running == "0":
                log("masscan finished, exit")
                return
        await asyncio.sleep(300)


asyncio.run(main())
