import asyncio, re, sys, time, collections
import aiohttp

TITLE = re.compile(r"(?is)<title[^>]*>\s*(.*?)\s*</title>")
SIG = {
    "papercut": r"(?i)papercut",
    "simplehelp": r"(?i)simplehelp",
    "zimbra": r"(?i)zimbra|sw-cp-server",
    "vaultwarden": r"(?i)vaultwarden|bitwarden",
    "vikunja": r"(?i)vikunja",
    "adito": r"(?i)adito",
    "trueconf": r"(?i)trueconf",
    "orthanc": r"(?i)orthanc",
    "dicom": r"(?i)dcm4che|dicom|pacs",
    "nextcloud": r"(?i)nextcloud",
    "owncloud": r"(?i)owncloud",
    "gitlab": r"(?i)gitlab",
    "zammad": r"(?i)zammad",
    "openemr": r"(?i)openemr",
    "whd": r"(?i)web help desk",
    "exchange": r"(?i)outlook web|/owa/|exchange",
    "citrix": r"(?i)netscaler|citrix gateway",
    "fortinet": r"(?i)fortinet|fortigate",
    "sonicwall": r"(?i)sonicwall",
    "ivanti": r"(?i)ivanti|dana-na",
    "f5": r"(?i)big-?ip|f5 networks",
    "sophos": r"(?i)sophos",
    "sangfor": r"(?i)sangfor",
    "hillstone": r"(?i)hillstone",
    "siteminder": r"(?i)siteminder",
    "veeam": r"(?i)veeam",
    "netapp": r"(?i)netapp|ontap",
    "synology": r"(?i)synology|diskstation",
    "qnap": r"(?i)qnap",
    "printer": r"(?i)hp laserjet|jetdirect|kyocera|ricoh|xerox",
    "camera": r"(?i)ipcam|webcam|hikvision|dahua|axis",
}
COMP = [(k, re.compile(v)) for k, v in SIG.items()]
stats = {"done": 0, "ans": 0, "hits": 0, "start": time.time()}
SEM = asyncio.Semaphore(900)

async def probe(sess, ip, port):
    for scheme in ("https", "http"):
        try:
            async with sess.get(f"{scheme}://{ip}:{port}/", allow_redirects=False, ssl=False) as r:
                raw = await r.content.read(16384)
                txt = raw.decode("utf-8", "replace")
                server = r.headers.get("Server", "")[:60]
                t = TITLE.search(txt)
                title = re.sub(r"\s+", " ", t.group(1)).strip()[:100] if t else ""
                return scheme, r.status, server, title, server + "\n" + txt
        except Exception:
            continue
    return None

async def worker(sess, ip, port, out, lock):
    try:
        res = await probe(sess, ip, port)
        if res:
            stats["ans"] += 1
            scheme, status, server, title, blob = res
            names = [n for n, p in COMP if p.search(blob)]
            if names:
                stats["hits"] += 1
            async with lock:
                out.write("\t".join([ip, str(port), scheme, str(status), server, title, ",".join(names)]) + "\n")
    except Exception:
        pass
    finally:
        stats["done"] += 1

async def statlog():
    with open("/root/recon/spec_probe.log", "a") as f:
        while True:
            el = time.time() - stats["start"]
            f.write(f"{time.strftime('%H:%M:%S')} done={stats['done']} hps={stats['done']/el:.0f} ans={stats['ans']} hits={stats['hits']}\n")
            f.flush()
            await asyncio.sleep(60)

async def main():
    infile, outfile = sys.argv[1], sys.argv[2]
    targets = []
    with open(infile, errors="replace") as f:
        for line in f:
            p = line.split()
            if len(p) >= 4 and p[0] == "open":
                targets.append((p[3], int(p[2])))
    conn = aiohttp.TCPConnector(limit=0, ssl=False)
    tout = aiohttp.ClientTimeout(total=8, connect=5, sock_read=5)
    hdr = {"User-Agent": "Mozilla/5.0"}
    lock = asyncio.Lock()
    stag = asyncio.create_task(statlog())
    with open(outfile, "a") as out:
        async with aiohttp.ClientSession(connector=conn, timeout=tout, headers=hdr) as sess:
            pend = set()
            async def task(t):
                async with SEM:
                    await worker(sess, t[0], t[1], out, lock)
            for t in targets:
                pend.add(asyncio.ensure_future(task(t)))
                if len(pend) >= 900:
                    _, pend = await asyncio.wait(pend, return_when=asyncio.FIRST_COMPLETED)
            if pend:
                await asyncio.wait(pend)
    stag.cancel()
    with open("/root/recon/spec_probe.log", "a") as f:
        f.write(f"COMPLETE done={stats['done']} ans={stats['ans']} hits={stats['hits']}\n")

asyncio.run(main())
