WEBINAR
GigaOm Radar Report for PTaaS: How to Make a Smarter Investment in Pentesting
WEBINAR
GigaOm Radar Report for PTaaS: How to Make a Smarter Investment in Pentesting

Exploiting Buffer Overflow Vulnerabilities: A Step-by-Step Guide (Part 2)

Buffer overflow vulnerability happens when data written to a buffer exceeds its size, which may overwrite important data or execute malicious code. Attackers can exploit these vulnerabilities to gain unauthorized access, execute malicious code, or steal sensitive data. This blog will provide an overview of buffer overflow exploitation, including its causes, consequences, and the methods attackers use to exploit it. It's important to understand the basics before diving into exploitation and steps of buffer overflow.

Welcome to part 2 of the buffer overflow series. In this blog, we will see the exploitation of buffer overflow vulnerability in detailed steps. Check out part one to learn the basics of overflow vulnerabilities.

Introduction

The buffer overflow vulnerability occurs whenever data written to a buffer exceeds its size. The extra data can overflow into adjacent memory locations, potentially overwriting important data or executing malicious code.

Buffer overflows have been a major security concern for decades and are a common target for attackers. An attacker can use these attacks to gain unauthorized access to a system, execute malicious code, or steal sensitive data.

This blog will provide an overview of buffer overflow exploitation, including its causes and consequences. Furthermore, we will discuss the methods attackers use to exploit buffer overflows.

Understanding the basics is necessary before diving into exploitation and steps of buffer overflow.

The Basics

To exploit buffer overflows at the machine level, we use assembly language. For attackers to execute malicious code, it is essential to understand how to control a program's execution flow.

To exploit buffer overflows, you need to understand a few basic concepts in assembly language:

Registers: Registers are fast, small storage locations in a processor for storing data that is being processed. Using buffer overflows, attackers can overwrite the contents of certain registers, allowing them to control the flow of execution.

EAX: The EAX register is a general-purpose register that holds the result of arithmetic operations and stores the address of the processed data. In buffer overflow exploitation, the EAX register stores the address of a pointer to the input buffer that contains the attacker's malicious code.

EDX: The EDX register is another general-purpose register often used with the EAX register. The EDX register stores the address of the fixed-size buffer that is being overflowed.

EBP: The EBP register is used as a base pointer to locate data on the stack. In buffer overflow exploitation, the EBP register can locate the return address stored on the stack, which the attacker will overwrite with the address of their malicious code.

ESP: The ESP register is used as a stack pointer to keep track of the top of the stack. In buffer overflow exploitation, the ESP register can locate the buffer that is being overflowed and identify the adjacent memory locations that will be overwritten.

EIP: The EIP register holds the address of the next instruction to be executed by the program. In buffer overflow exploitation, the attacker will attempt to overwrite the contents of the EIP register with the address of their malicious code.

Stack: In a program, the stack is a region of memory used to store data for function calls and return addresses. A buffer overflow can allow an attacker to hijack the flow of execution by overwriting data on the stack, including the return address.

When you call a function, a new frame pushes onto the top of the stack. This frame contains information about the function call, including the call's return address, any arguments passed to the function, and any local variables declared within the function.

Instructions: Assembly language instructions can move data, perform arithmetic operations, and jump to different program parts. An attacker can inject malicious code into a program using buffer overflows, which the processor can execute.

Several instructions can be involved in a buffer overflow vulnerability:

  1. mov: This instruction copies a value from one memory location to another. A buffer overflow can occur if the destination buffer is not large enough to hold the data being copied.

  2. cpy: Similar to mov, this instruction copies data from one memory location to another. Again, a buffer overflow can occur if the destination buffer is not large enough.

  3. strcpy: This is a commonly used function in C that copies a null-terminated string from one buffer to another. A buffer overflow can occur if the destination buffer is not large enough.

  4. memcpy: This is a C function that copies a specified number of bytes from one memory location to another. A buffer overflow can occur if the destination buffer is not large enough to hold the data being copied.

  5. strncpy: This is a C function that copies a specified number of characters from one buffer to another. If the destination buffer is not large enough, the function will write null characters to the destination buffer to ensure that the string is null-terminated, but this can lead to a buffer overflow if the null characters overwrite adjacent memory locations.

  6. sprintf: This is a C function that writes formatted output to a string buffer. A buffer overflow can occur if the destination buffer is not large enough.

  7. vsprintf: This is a C function that writes formatted output to a string buffer, using a variable number of arguments. A buffer overflow can occur if the destination buffer is not large enough.

Potential Risks of Buffer Overflow

Buffer overflows can result in a wide range of security risks, including:

  1. Arbitrary Code Execution: One of the most severe consequences of a buffer overflow is the ability of an attacker to execute arbitrary code with the permissions of the affected process. This can lead to a complete compromise of the system, including theft of sensitive information.

  2. Denial of Service (DoS): A buffer overflow can cause a program to crash or hang, leading to a denial of service attack. This can result in temporary or permanent disruption of service and can also cause a chain reaction that spreads to other systems and services, potentially resulting in widespread outages.

  3. Information Leakage: A buffer overflow can allow an attacker to access sensitive information, such as passwords, encryption keys, or confidential data, stored in the affected process's memory.

  4. Elevation of Privilege: A buffer overflow can allow an attacker to gain elevated privileges on the affected system, potentially bypassing security controls and accessing sensitive systems and data.

General Exploitation Steps

  1. Discovery: Identifying the vulnerability is the first step in exploiting a buffer overflow. An attacker can do this through manual code review, automated vulnerability scanning, or other means.

  2. Craft the payload: Once the vulnerability has been identified, the attacker must craft a payload that will overwrite the buffer and redirect the program's execution flow to the attacker's code. An attacker must carefully construct this payload to bypass any security features such as ASLR or DEP.

  3. Injection: The payload is then injected into the buffer, usually through a network-based attack vector such as a network packet or a web request.

  4. Triggering: The attacker must then trigger the buffer overflow condition, causing the program to write the payload to the buffer and overwrite the adjacent memory locations.

  5. Execution: Once the payload has been injected and the buffer overflow has been triggered, the attacker's code is executed, allowing them to take control of the program and execute their desired actions.

Practical Examples

Now, We will be exploiting Windows based buffer-overflow. Here are a few prerequisites for the same.

 

Windows-Based Buffer Overflow Example

We will be covering the following 6 steps in detail for buffer overflow:

  1. Fuzzing
  2. Finding Offset
  3. Finding Bad Characters
  4. Finding Vulnerable Modules
  5. Shellcode generation
  6. Exploitation

 

Fuzzing

In buffer overflow exploitation, fuzzing discovers vulnerabilities in software. The basic idea behind fuzzing is to send many malformed or unexpected inputs to a software program to identify input validation flaws that could lead to security vulnerabilities, such as buffer overflows.

Making Fuzzer
  1. Generation of test inputs: The attacker then generates many malformed or unexpected inputs, known as "fuzz inputs." These inputs stress the software and expose any input validation flaws.
  2. Injection of test inputs: The fuzz inputs are sent to the software program through a network-based attack vector or by running the software with the fuzz inputs as input data.
  3. Monitoring: The software's behavior is monitored during the fuzzing process to identify any crashes or unexpected results. Any crashes or unexpected results are analyzed to determine if a security vulnerability, such as a buffer overflow, caused them.

Screenshot 2023-04-17 at 11.52.38 AM

A) Checking for vulnerability

Open Python interceptor and run the following command to generate inputs.

'V’*1000

B) Copy the generated input and paste it into Input Field.

Screenshot 2023-04-17 at 11.53.49 AM

C)Click on OK, and the application will crash.

Screenshot 2023-04-17 at 11.54.13 AM

What is an offset?

In computer science, offsets are the positions of values within data structures, such as arrays, strings, or memory buffers. Offsets indicate how far a value is from the beginning of a data structure.

Regarding memory buffers, the offset refers to the position within the buffer where a particular value or piece of data is stored. For example, in a buffer of 100 bytes, an offset of 50 would indicate that a specific value is 50 bytes from the start of the buffer.

The offset may determine the location of an error within a buffer and access and manipulate data within buffers. Additionally, offsets can determine the location of malicious code if a buffer overflow occurs, allowing an attacker to control the flow of the program's execution.

Here we aim to control EIP as it stores the next instruction to execute; we will use an immunity debugger.

The immunity debugger will allow us to view the contents of registers at the time of the crash.

A) Attach a vulnerable file to Immunity Debugger by going to File>Open Vulnerable Application(32bit)

Screenshot 2023-04-17 at 11.54.38 AM

B) At First application will be opened in paused mode, so click on the Play button at the top. It will load the application into the immunity debugger and start.

Screenshot 2023-04-17 at 11.57.58 AM

We will again give large input to our vulnerable application and observe it in the immunity debugger.

Screenshot 2023-04-17 at 11.58.06 AM

As we can see, ESP and EIP registers are overwritten, and our vulnerable application crashed with an error access violation.

Now, we have to understand how much input we should give to our program to control our EIP register. For that, we can use the Metasploit framework.

For that, we need two ruby scripts given below.

1)Pattern Create

It will create a payload, and after inputting in a vulnerable application attached to the immunity debugger, it will give us an offset value.

2)Pattern Offset

This script will match the value of the offset and will confirm the location.

A) Run pattern create

Screenshot 2023-04-17 at 11.59.20 AM

B) We give this generated input to vulnerable applications and observe it in the immunity debugger.

Screenshot 2023-04-17 at 11.59.53 AM

C)Observe the application and catch EIP register value.

Screenshot 2023-04-17 at 12.00.00 PM

      EIP value: 6A41376A

D)Run pattern offset script and give EIP value.

Screenshot 2023-04-17 at 12.00.09 PM

E) Now we have to recheck our finding

Screenshot 2023-04-17 at 12.00.15 PM

F) Entering input in vulnerable applications.

Screenshot 2023-04-17 at 1.31.29 PM

G) Observing the application's EIP value.

Screenshot 2023-04-17 at 1.31.35 PM

Value:43434342

It is nothing but 3 C's in Hexadecimal format. It means we have control over EIP register values.

 

What are bad characters?

In buffer overflows, "bad characters" are certain characters in input data that cause problems when present in the data used to overflow a buffer. These characters can cause the program's execution to deviate from the intended path and disrupt the execution of the payload to be injected into the vulnerable buffer.

When exploiting a buffer overflow vulnerability, carefully crafting the payload data is often necessary to avoid bad characters and ensure the payload executes correctly. This requires understanding the target system and the data used to exploit the vulnerability.

Here are some examples of characters that are commonly considered bad characters in buffer overflow exploitation:

Null bytes (ASCII value 0): These characters are often used to terminate strings in C and other programming languages and can cause problems when used in buffer overflow payloads.

Newline characters (ASCII value 10): These characters are often used as line separators in text files and can cause problems when used in buffer overflow payloads.

Carriage return characters (ASCII value 13): These characters are often used to separate lines in text files and can cause problems when used in buffer overflow payloads.

Non-printable characters (ASCII values 0-31): These characters can cause problems with output formatting or string manipulation.

Binary data: Some payloads may contain binary data, and characters within this binary data may be interpreted as bad characters.

Bad characters

  • 00 for NULL
  • 0A for Line Feed n
  • 0D for Carriage Return r
  • FF for Form Feed f

 

Finding Vulnerable Modules 

It's a crucial step. After finding EIP value, we have to find a vulnerable DLL file that gets loaded when our R GUI application starts. Some DLL files don't have protection from buffer overflow attacks. We will find such DLL files using a tool named Mona.

1) Download Mona tool and copy Mona.py into \Immunity Debugger\PyCommands directory.

Screenshot 2023-04-17 at 1.33.00 PM

2)Now, let's fire up the immunity debugger with our vulnerable application again!

3)Input the following command to the command line in Immunity Debugger:

Command:

!mona modules

It will list all the dll files currently in use and their safety flags.

Screenshot 2023-04-17 at 1.33.31 PM

4)Then we will choose R.dll file, which is used by our vulnerable application and doesn't have any protection.

Finding OP code for JMP ESP

Now we will find the address pushed on the stack when R.dll is called in the application. For that, we have to run the following command:

!mona find -s "\xff\xe4" -m R.dll

Screenshot 2023-04-17 at 1.33.53 PM

In our case address is:

0x6e595ddb

 

Building exploit to execute a command on a windows machine

We can build exploit code that will execute the command on windows machines when we put input in vulnerable applications.

So for that, let's quickly fire up kali console and type:

msfvenom -a x86 — platform Windows -p windows/exec cmd=notepad.exe -e x86/alpha_upper -b ‘\x00’ -f c

 

What is MSFvenom?

MSFvenom is a payload generator tool that is part of the Metasploit framework. The Metasploit framework is an open-source toolkit for developing and executing exploitation code.

MSFvenom creates and encodes payloads that attackers can integrate into exploit modules within the Metasploit framework. These payloads can be used to execute arbitrary code on a target system and for various purposes, such as establishing a reverse shell, creating a bind shell, or running a meterpreter session.

It supports a wide range of platforms and architectures and allows for creation of payloads designed to evade anti-virus software. The tool integrates with the Metasploit framework, providing a powerful and flexible platform for penetration testing and security research.

Screenshot 2023-04-17 at 1.35.24 PM

MSFvenom is a critical tool within the Metasploit framework, allowing the ability to generate custom payloads to exploit vulnerabilities in target systems.

Command: msfvenom -a x86 — platform Windows -p windows/exec cmd=notepad.exe -e x86/alpha_upper -b ‘\x00’ -f c

Screenshot 2023-04-17 at 1.35.30 PM

We must merge our exploitation script and a few NOP sled characters to work it properly.

 

What is NOP sled characters?

A NOP (No Operation) sled is a sequence of NOP instructions in machine code that does nothing when executed. In a buffer overflow attack, a NOP sled is a filler between the injected malicious payload and the return address the attacker wants to overwrite in the vulnerable program's stack.

The purpose of a NOP sled is to provide a predictable and controllable path for the program's execution to reach the injected malicious payload. When a buffer overflow occurs, the excess data written to the buffer can overwrite adjacent data on the stack, including the return address. The attacker can use a NOP sled to increase the chances that the overwritten return address will point to the start of the NOP sled, leading to the execution of the malicious payload.

Here are some examples of NOP sleds for different architectures:

x86 (32-bit): The x86 architecture uses the 0x90 instruction to represent a NOP. A NOP sled for x86 can be represented as a sequence of 0x90 instructions.

\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90

x86-64 (64-bit): The x86-64 architecture also uses the 0x90 instruction to represent a NOP. A NOP sled for x86-64 can be represented as a sequence of 0x90 instructions.

\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90

ARM (32-bit): The ARM architecture uses the 0x01 instruction to represent a NOP. A NOP sled for ARM can be represented as a sequence of 0x01 instructions.

\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01

 

Final Code Looks Like This

Screenshot 2023-04-17 at 1.36.41 PM

Run this exploit in kali Linux and it will generate malicious input which can execute command if application is vulnerable to buffer overflow.

Screenshot 2023-04-17 at 1.36.48 PM

Generate shellcode

Screenshot 2023-04-17 at 1.36.54 PM

Now input shellcode in vulnerable application and observe the result.

Screenshot 2023-04-17 at 1.38.12 PM

 

Reverse shell using buffer overflow

Prerequisites for Demonstration

  • Vulnerable application: dostackbufferoverflowgood.exe
  • Testing/Analysis Machine: Microsoft Windows 10 
  • Attacker Machine: Kali Linux 
  • Debugger used: Immunity Debugger

Steps

A) Open the application and run Nmap scan on windows IP address

Screenshot 2023-04-17 at 1.46.00 PM

B) To application via Netcat to understand functionality. 

   Screenshot 2023-04-17 at 1.46.06 PM

C)Making Fuzzer.

Screenshot 2023-04-17 at 1.46.47 PM

D)Running Fuzzer and observing crash.

Screenshot 2023-04-17 at 1.46.53 PM

E) Observing crash and ESP register value in immunity debugger.

Screenshot 2023-04-17 at 1.47.23 PM

F) Creating payload for offset value.

Screenshot 2023-04-17 at 1.47.31 PM

G) Script for finding offset value.

Screenshot 2023-04-17 at 1.47.37 PM

H) Observing offset value in immunity debugger.

Screenshot 2023-04-17 at 1.48.22 PM

I)Generating bad characters by script.

Screenshot 2023-04-17 at 1.48.29 PM

J) Observing bad characters in registers.

Screenshot 2023-04-17 at 1.49.24 PM

K) Finding JMP ESP via Mona in Immunity Debugger.

Screenshot 2023-04-17 at 1.49.29 PM

L) Got JMP ESP address.

Screenshot 2023-04-17 at 1.49.35 PM

M) Generating Reverse Shell Payload via MSFvenom.

Screenshot 2023-04-17 at 1.50.15 PM

N) Start Netcat on 4444 port and run the exploit with combining crashing value+ JMP ESP + NOPs + Shellcode.

Screenshot 2023-04-17 at 1.50.21 PM

O) Observing Netcat connection!

Screenshot 2023-04-17 at 1.50.27 PM

 

Is Buffer Overflow still a concern?

Buffer overflows continue to be a problem in the modern era. One recent example is the remote code execution vulnerability (CVE-2022-0601) discovered in Microsoft Windows CryptoAPI (Crypt32.dll) in January 2022. This vulnerability was due to a buffer overflow in how the Windows CryptoAPI handled Elliptic Curve Cryptography (ECC) certificates. An attacker could exploit this vulnerability by crafting a malicious certificate and convincing a user to install it on their system, allowing the attacker to execute arbitrary code with the user's permissions.

Another example is the heap buffer overflow vulnerability (CVE-2022-0796) in the OpenSSL library in March 2022. This vulnerability affected multiple platforms, including Linux, Windows, and macOS, and could allow an attacker to execute arbitrary code with the permissions of the user who is running the vulnerable software.

Conclusion

Buffer overflow exploitation is a serious threat to the security of software systems, and it's essential for developers to be aware of the dangers of buffer overflows and to take the necessary precautions to protect against these types of attacks. This can include using secure coding practices, canary values to detect buffer overflows, and various mitigation techniques such as stack protection and address space layout randomization (ASLR). By being proactive about security, developers can help protect their software systems against buffer overflow exploitation and other security threats.

 

Buffer Overflow Labs

https://github.com/CyberSecurityUP/Buffer-Overflow-Labs 

https://mega.nz/folder/UuZmnbzR#9uZEkqKLsxFZPG0WzDZK5Q 

https://github.com/stephenbradshaw/vulnserver 

 

References

https://anubissec.github.io/Vulnserver-Exploiting-TRUN-Vanilla-EIP-Overwrite/# 

https://bufferoverflows.net/exploiting-vanilla-buffer-overflow-in-vulnserver-trun-command/ 

https://www.purpl3f0xsecur1ty.tech/2019/02/28/Vulnserver.html 

https://medium.com/purple-team/buffer-overflow-c36dd9f2be6f 

https://www.hackingarticles.in/a-beginners-guide-to-buffer-overflow/ 

https://steflan-security.com/complete-guide-to-stack-buffer-overflow-oscp/ 

https://www.google.com/amp/s/boschko.ca/braindead-buffer-overflow-guide-to-pass-the-oscp-blindfolded/amp/ 

https://github.com/3isenHeiM/OSCP-BoF 

https://github.com/CyberSecurityUP/Buffer-Overflow-Labs 

https://github.com/johnjhacking/Buffer-Overflow-Guide 

 

Back to Blog
About Ninad Mathpati
Ninad Mathpati is a Cybersecurity Enthusiast and Hacker with an ethical mindset. He has been working as an Application Security Engineer for 4+ years with core interest in Web, Mobile Application Security, Network Security, API Security, Source Code Analysis, and Thick Client Pentesting. More By Ninad Mathpati
Overflow Vulnerabilities
Overflow vulnerabilities occur when a program or system accepts more data than it can handle, leading to memory corruption and potentially allowing attackers to execute malicious code. Core Pentester Ninad Mathpati writes about these types of vulnerabilities and how to prevent them.
Blog
Apr 3, 2023
A Pentester’s Guide to Command Injection
Get expert insights with a command injection tutorial with insights from pentesting experts at Cobalt, a Pentest as a Service (PtaaS) provider.
Blog
Dec 11, 2020
A Pentester’s Guide to File Inclusion
Read the Pentester’s Guide to File Inclusion for key insights into this common vulnerability.
Blog
Feb 19, 2021