import asyncio, re
import aiohttp

LIST = "/root/recon/lists"
OUT = "/root/recon/ver2.tsv"
SEM = asyncio.Semaphore(40)

TITLE = re.compile(r"(?is)<title[^>]*>\s*(.*?)\s*</title>")
PLESK = re.compile(r"(?i)plesk[^0-9]{0,25}(\d+\.\d+(?:\.\d+)?)")
FGT_V = re.compile(r"[?&]v=(\d+\.\d+\.\d+)")
SONIC_V = re.compile(r"(?:SonicOS|firmware|version)[^0-9a-z]{0,25}(\d+\.\d+\.\d+\.\d+-\d+[a-z]*)", re.I)


def load(name):
    out = []
    try:
        for line in open(f"{LIST}/{name}.txt"):
            p = line.rstrip("\n").split("\t")
            if len(p) >= 3:
                out.append((p[0], int(p[1]), p[2]))
    except FileNotFoundError:
        pass
    return out


async def fetch(sess, url, method="GET", data=None):
    async with sess.request(method, url, data=data, allow_redirects=True, ssl=False) as r:
        raw = await r.content.read(40000)
        return r.status, dict(r.headers), raw.decode("utf-8", "replace")


async def v_plesk(sess, ip, port, sc):
    try:
        st, h, t = await fetch(sess, f"{sc}://{ip}:{port}/")
        m = TITLE.search(t)
        title = re.sub(r"\s+", " ", m.group(1)) if m else ""
        mv = PLESK.search(title) or PLESK.search(t)
        return (mv.group(1) if mv else ""), title[:60]
    except Exception:
        return "", ""


async def v_forti(sess, ip, port, sc):
    try:
        st, h, t = await fetch(sess, f"{sc}://{ip}:{port}/remote/login?lang=en")
        m = FGT_V.search(t)
        if m:
            return m.group(1), f"static-v {st}"
        m = TITLE.search(t)
        return "", (re.sub(r"\s+", " ", m.group(1)) if m else f"no-ver {st}")
    except Exception:
        return "", ""


async def v_sonic(sess, ip, port, sc):
    try:
        st, h, t = await fetch(sess, f"{sc}://{ip}:{port}/")
        m = SONIC_V.search(t)
        if m:
            return m.group(1), "page"
        st2, h2, t2 = await fetch(sess, f"{sc}://{ip}:{port}/cgi-bin/welcome")
        m = SONIC_V.search(t2) or re.search(r"(\d+\.\d+\.\d+\.\d+-\d+)", t2)
        if m:
            return m.group(1), "welcome"
        return "", (h.get("Server", "") + " " + str(st))[:60]
    except Exception:
        return "", ""


async def v_citrix(sess, ip, port, sc):
    try:
        st, h, t = await fetch(sess, f"{sc}://{ip}:{port}/")
        m = re.search(r"(?i)ns_gui|netscaler|citrix", t + str(h))
        return ("citrix" if m else ""), f"{st} {h.get('Server','')}"[:60]
    except Exception:
        return "", ""


async def v_simple(sess, ip, port, sc):
    try:
        st, h, t = await fetch(sess, f"{sc}://{ip}:{port}/")
        srv = h.get("Server", "")
        m = re.search(r"SimpleHelp/([A-Za-z0-9\-]+)", srv)
        return (m.group(1) if m else ""), srv[:60]
    except Exception:
        return "", ""


async def v_vault(sess, ip, port, sc):
    try:
        st, h, t = await fetch(sess, f"{sc}://{ip}:{port}/api/config")
        m = re.search(r'"version"\s*:\s*"([^"]+)"', t)
        return (m.group(1) if m else ""), "config"
    except Exception:
        return "", ""


async def v_next(sess, ip, port, sc):
    try:
        st, h, t = await fetch(sess, f"{sc}://{ip}:{port}/status.php")
        m = re.search(r'"version"\s*:\s*"([^"]+)"', t)
        if m:
            return m.group(1), "status"
        st, h, t = await fetch(sess, f"{sc}://{ip}:{port}/")
        m = re.search(r'version["\s:]+(\d+\.\d+\.\d+)', t)
        return (m.group(1) if m else ""), f"{st}"
    except Exception:
        return "", ""


JOBS = []
for name, fn in [("zimbra", v_plesk), ("fortinet", v_forti), ("sonicwall", v_sonic),
                 ("citrix", v_citrix), ("simplehelp", v_simple),
                 ("vaultwarden", v_vault), ("nextcloud", v_next), ("owncloud", v_next)]:
    for ip, port, sc in load(name):
        JOBS.append((name, ip, port, sc, fn))


async def main():
    conn = aiohttp.TCPConnector(limit=0, ssl=False)
    tout = aiohttp.ClientTimeout(total=15, connect=7, sock_read=10)
    hdr = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
    async with aiohttp.ClientSession(connector=conn, timeout=tout, headers=hdr) as sess:
        async def one(it):
            name, ip, port, sc, fn = it
            async with SEM:
                try:
                    v, ev = await fn(sess, ip, port, sc)
                except Exception:
                    v, ev = "", ""
                return name, ip, port, sc, v, ev
        res = await asyncio.gather(*[one(j) for j in JOBS])
    with open(OUT, "w") as f:
        for r in res:
            f.write("\t".join(map(str, r)) + "\n")
    got = sum(1 for r in res if r[4])
    print("probed", len(res), "got_version", got)

asyncio.run(main())
