import asyncio, socket, ssl, re, random
import aiohttp
from cryptography import x509
from cryptography.x509.oid import NameOID

def load():
    vers = {}
    for line in open("/root/recon/ver2.tsv"):
        p = line.rstrip("\n").split("\t")
        if len(p) >= 5 and p[0] == "zimbra":
            vers[(p[1], p[2])] = p[4]
    out = []
    for line in open("/root/recon/lists/zimbra.txt"):
        p = line.rstrip("\n").split("\t")
        if len(p) >= 3:
            out.append((p[0], int(p[1]), p[2], vers.get((p[0], p[1]), "")))
    return out


def rdns(ip):
    try:
        h = socket.gethostbyaddr(ip)
        return h[0]
    except Exception:
        return ""


def cert_names(ip, port=443, t=5):
    try:
        pem = ssl.get_server_certificate((ip, port), timeout=t)
        c = x509.load_pem_x509_certificate(pem.encode())
        names = []
        try:
            san = c.extensions.get_extension_for_class(x509.SubjectAlternativeName)
            names += [n for n in san.value.get_values_for_type(x509.DNSName)]
        except Exception:
            pass
        try:
            cn = c.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
            names += [a.value for a in cn]
        except Exception:
            pass
        return sorted(set(n for n in names if n and len(n) < 200))
    except Exception:
        return []


async def get(sess, url, host=None):
    h = {"Host": host} if host else {}
    try:
        async with sess.get(url, headers=h, ssl=False, allow_redirects=False) as r:
            t = await r.content.read(4000)
            return r.status, t.decode("utf-8", "replace")
    except Exception as e:
        return 0, type(e).__name__


async def main():
    data = load()
    old = [d for d in data if d[3].startswith(("17.", "18.0.30", "18.0.31", "18.0.35", "18.0.39"))]
    new = [d for d in data if d[3].startswith(("18.0.81", "18.0.82"))]
    print("old", len(old), "new", len(new))
    loop = asyncio.get_running_loop()
    tout = aiohttp.ClientTimeout(total=12, connect=6, sock_read=8)
    lines = []
    async with aiohttp.ClientSession(timeout=tout, headers={"User-Agent": "Mozilla/5.0"}) as sess:
        # --- old cluster detail ---
        for ip, port, sc, v in old:
            host = await loop.run_in_executor(None, rdns, ip)
            names = await loop.run_in_executor(None, cert_names, ip, 443)
            st80, body80 = await get(sess, f"http://{ip}/plesk-stat/webstat/")
            sts, bodys = await get(sess, f"https://{ip}/plesk-stat/webstat/")
            g = "GOACCESS" if ("GoAccess" in body80 or "GoAccess" in bodys) else ""
            print(f"{ip:16s} {v:8s} rdns={host[:40]:40s} san={names[:3]} 80={st80} 443s={sts} {g}")
            lines.append("\t".join([ip, str(port), sc, v, host, ",".join(names[:5]), str(st80), str(sts), g]))

        # --- sample of new versions: SAN then stats by domain ---
        sample = random.sample(new, min(40, len(new)))
        dom_hits = 0
        for ip, port, sc, v in sample:
            names = await loop.run_in_executor(None, cert_names, ip, 443)
            if not names:
                continue
            d = names[0].lstrip("*.")
            st, body = await get(sess, "http://" + d + "/plesk-stat/webstat/", host=d)
            st2, body2 = await get(sess, "https://" + d + "/plesk-stat/webstat/", host=d)
            ok = st == 200 and ("GoAccess" in body or "Web Statistics" in body)
            ok2 = st2 == 200 and ("GoAccess" in body2 or "Web Statistics" in body2)
            if ok or ok2:
                dom_hits += 1
            print(f"NEW {ip:16s} {v} dom={d[:45]:45s} http={st} https={st2} stats={'YES' if (ok or ok2) else ''}")
            lines.append("\t".join([ip, str(port), sc, v, d, str(st), str(st2), "STATS" if (ok or ok2) else ""]))
        print("new-sample with stats:", dom_hits, "/", len(sample))
    open("/root/recon/plesk_stats.tsv", "w").write("\n".join(lines))

asyncio.run(main())
