Stack Based Buffer Overflow Tutorial - By Paid Hackers

stack based buffer overflow
Stack Based Buffer Overflow Tutorial

Hello, and welcome to my guide on exploiting stack based buffer overflows. This is a basic tutorial, and is geared toward beginning exploit writers and those in the technology field who do not understand what buffer overflows are and how they can be exploited. I will attempt to make this as simple as possible and explain as much as possible throughout the tutorial. This tutorial was created on a machine running Kali Linux, and because it is aimed toward beginner-level exploitation, the exploit is local. Let's start.

Wait, what is a buffer?

0x01- Buffers


A buffer is simply a space in memory that holds data. For instance, let's say we have a simple C program. This program takes one argument. And in the code, we have an alloted buffer of 10 bytes for the argument that we supply. Since a character is 1 byte, logically we have space for 10 characters. Well, if there is nothing written in code to check the size of our input, then technically we would be able to supply as many characters as we want for our buffer.

This is where a buffer overflow would occur. We could supply 20 characters which would be placed into our 10 byte buffer. The result of this would be the overwriting of memory addresses. Then, when the function that is used for our input is finished executing, the program will try to return to where it left off in runtime.But because the extra data we supplied overwrote addresses in memory it wasn't supposed to, the program now has a segmentation fault. A segmentation fault is named as such because there was a "fault", or an error, in a segment of memory.

 

0x02- Memory Segments

 

1 --> Text Segment

Also known as the code segment, this memory segment contains the actual code to be executed. It is usually marked read-only, so the instructions of the program cannot be modified.

2 --> Data Segment

This memory segment contains global variables that are initialized by the programmer.

3 --> BSS Segment

Also known as the Uninitialized Data Segment, this segment contains uninitialized global variables. Variables in this segment are initialized to a null or 0 value before execution of the program.

4 --> Heap Segment

The most dynamic memory segment. The heap grows downward, toward higher memory addresses when more memory is requested as the program executes.

5 --> Stack Segment

The main focus of this tutorial, the stack segment is a collection of stack frames that are placed on the stack as functions are executed. The stack also contains the arguments and variables local to a function. This will be explained further as we go along.


Now that we have defined the memory segments, let's talk about the main focus of this tutorial, the stack.

0x03- The Stack Segment


Since the stack segment is where a function's local variables and arguments are placed during the execution of a function, we are able to exploit vulnerabilities like stack overflows. Earlier I mentioned something called a stack frame. A stack frame is a representation of a function call. As functions are called, more stack frames are added to the stack, and the stack grows upward, toward lower memory addresses. It also grows toward the heap, and if you are confused about what it would look like graphically, take a look-



 

This is a graphic representation of all memory segments, but take note at which way the stack segment grows and also where the higher and lower memory addresses reside. This is the way the stack grows when data is placed into it, such as stack frames. And alternatively, when functions return to their caller, the stack grows back down toward higher addresses as the number of stack frames decrease. The way this happens is through the procedure prologue and the procedure epilogue. This is how the program sets up a new stack frame for each function and it's data. Here is an example of a procedure prologue in x86 Assembly Language-


#Procedure Prologue

 pushl   %ebp
        movl    %esp, %ebp
        subl    $N,%esp
 
  
 
 
 Here, we see 3 instructions. First, the old frame pointer gets pushed onto the stack (this is called the saved frame pointer). Then, the value of the stack pointer gets placed into the frame pointer so that a new stack frame can be placed on top of the old stack frame in the stack. Lastly, take away however much data we need from the stack to make room for the current function's local variables and data. This will make the stack grow up towards lower memory, and the value of the stack pointer will be less then what it was by however many bytes were taken away.

#Procedure Epilogue

movl    %ebp, %esp
        popl    %ebp
        ret 

Here is the epilogue. First the stack pointer is replaced with the frame pointer, and the stack pointer is returned to the value it was at before the prologue. Then the base pointer is popped of the stack, so it is returned to it's value before the prologue. Then the program is returned to the calling function by taking the previous frame's return address off the stack and jumping execution of the program to that address.

Ah yes, the return address. You see, the program needs somewhere to return after a function is executed. After the epilogue occurs and the program execution is about to return to the caller function, the value of the instruction pointer is executed by the processor. You see, the instruction pointer is what the processor executes next. So whatever address the instruction pointer holds, which would be our return address, is where execution of the program is going to jump to. This is the crucial part of our exploitation, because controlling where the processor is going to execute an instruction means we can control execution flow of the program and ultimately determine where we want execution of the program to go.

0x04- Exploitation

First, let's turn off ASLR. Address Layout Stack Randomization is a security protection that comes by default in most modern operating systems. It ensures that the memory address of certain registers and instructions is random at startup. There are, of course, ways to bypass this, but that's for a later tutorial. For the time being, turn it off-

echo 0 > /proc/sys/kernel/randomize_va_space

So now that we have all of the explanation out of the way, let's take what we know and apply it to our exploitation. We are going to compile a vulnerable C program and exploit it, gaining a shell on the system. Let's take a look at the source code of our program-


#include
#include
int main(int argc, char** argv)
{
char buffer[500];
strcpy(buffer, argv[1]);
return 0;
}




This is our vulnerable source code. It's not hard to read, if you know how to write code in C. We have the header files at the top, the main function with a pointer to use for an argument.  We then have a buffer that has been alloted 500 bytes. Then we see the strcpy function place the argument we supply into the buffer. Create an empty file and place the code inside it, and then name it vuln.c. Then, compile the program-


Here we are using a couple parameters inside of GCC, such as -fno-stack-protector. This is to disable canaries being inserted into our program. A canary is a random integer placed in the code, and if it is overwritten, then stack smashing, which is what we are essentially doing, is detected. We also use -z execstack to make sure the stack is executable.

Now then, let's run the program with an argument and see what happens-


As you can see, we added 20 "A" characters as an argument. We already know that the program will be fine, because we have a 500 byte buffer. Let's place the program in the GNU Debugger, and then let's use an interactive scripting language to pipe however many characters we want through the program as an argument with a nice little one-liner. I got it, Python. ;)

In the following example, we start GDB in quiet mode with our program, and then supply 550 "A" characters to the program-


From our output above, we see that after supplying the characters to the program we received a segmentation fault. After looking at the registers with the info reg command, we can see that both the frame pointer (EBP) and the return address/instruction pointer (EIP) have been overwritten with 4 bytes worth of x41 each. In case you weren't aware, \x41 is the hexadecimal representation of the character "A". It seems as though overflowing the buffer was successful and we've written past it into other parts of the stack.

Here is what we need to do. We need to craft our exploit concept in such a way that we can overflow the program, gain control of the instruction pointer, and supply the instruction pointer with an address of our choosing in memory. Our exploit would basically look something like this-

[Useless Data That Does Nothing] + [NOPS] + [Shellcode] + [Return Address]


Well what is this stuff? I'll tell you. You see, just because we overwrote the instruction pointer doesn't mean we have control of it yet. We want to be able to overwrite it perfectly, byte for byte. This means we have to know how much data to feed into our vulnerable buffer right before we overwrite the instruction pointer, because we will be supplying an address of our choosing. This is called searching for the offset. We could manually do it, but in real life, we would have no idea how many bytes the buffer is alloted. So, we will just use a really easy and awesome method made possible by the awesome hackers at Rapid 7. We are going to use The Metasploit Framework to generate a pattern of characters, the same amount that we supplied to the buffer the first time (550). Then, we will search for an offset based on what pattern we overwrite the instruction pointer with. Since I am using Kali Linux, the scripts to do this are located in /opt/metasploit/apps/pro/msf3/tools. Then let's create our pattern, feed it into our program the same way we did the first time, and find our offset. Here we go-



Here we created our pattern of 550 characters.



Then we fed our characters into our program in GDB, and we overwrite the instruction pointer with 0x31724130. We now feed this memory address into pattern_offset to find our offset-


And now we know that our offset is 512 bytes. This means that we have to feed 512 bytes into our program right before the 4 byte address of the instruction pointer is overwritten. So this means that 516 bytes of data will overwrite our instruction pointer. We can prove this by feeding 512 "A" characters into our vulnerable buffer and then supplying 4 "B" characters. Our instruction pointer should be overwritten with 42424242, and yes, \x42 is hexadecimal for the "B" character.


This confirms our offset, and now we have the first part of our buffer crafted. Now we have control of the instruction pointer, because we know how many bytes of data to supply before we overwrite the instruction pointer with an address of our choosing. First we will supply the buffer with "A" characters, followed by some NOPS, followed by our shellcode, and lastly a return address.

Now we need a valid return address. This is an address that is specific to our NOPS. Here is why. We supply our "A" characters for garbage to take up space, then we supply our NOPS and shellcode, with a return address at the end of our input. Our return address will point in our set of NOPS, and the processor will "slide" through the NOPS until it reaches our shellcode, which will be on the stack after our NOPS.

But how do we find our return address? Well, by looking at the function that is being called to copy our argument input into the vulnerable buffer. And even if we hadn't seen the source code for our program, we would still know that the highly know vulnerable function strcpy() is being called in our program by looking at the disassembled code in GDB. What we need to do is set a breakpoint in 2 places- the first at the address where the function is called, and then another breakpoint after the function call.

How is this important for the return address? Because of the procedure prologue. Remember how the return address gets pushed to the stack during the prologue? This is so the program can return execution back to the caller function to go on with the rest of the program. When we overwrote our buffer, the return address was overwritten with our "A" characters, and then popped off of the stack and EIP tried to execute it. Once we run the program with our breakpoints in place, we will be able to see our input being pushed onto the stack. We will be able to find an address in the stack to use just by looking through the stack until we find our set of NOPS, and choosing an address that falls somewhere in the middle of them.  So let's open our program in GDB, set our breakpoints at the proper places, run the program, and find a good return address.

First, we will open our program and disassemble it-



Then we will set break points at the call instruction for strcpy(), and at the instruction immediately after it-


Then we will run our program with a buffer that is crafted to simulate our exploit. We will use the characters A, B, "\x90" (NOP), and C to show what data would actually be where in our real exploit.

* The "A" characters will simulate the first set of NOPS.

* The "\x90" characters will simulate our set of NOPS. This is where we want to look for a return address, because our shellcode comes after this.

* The "B" characters will simulate our shellcode.
*The "C" characters will simulate our return address.

So, the command we use in GDB to run our program as such is-

run `python -c 'print "A" * 234 + "\x90" * 234 + "B" * 44 + "CCCC"'`

We determined this buffer by some simple math. We have 516 bytes to overwrite the instruction pointer. We subtract 4 from it, because our return address will be 4 bytes. Then we subtract 44 bytes, because that will be the size of the shellcode we use. Then we take the remaining space (468 bytes) and divide it by two, and we have 234 bytes. We will distribute 234 bytes to each "A" and "\x90".

Here we ran the program and hit our first breakpoint. We use x/16xw $esp to look at the top of the stack, and then look at the $esp address (esp is the register used as the stack pointer).




Here we can see the top of the stack, and we can also see that our input hasn't been pushed to the stack yet, because the strcpy() function isn't done executing. Let's step to the next address right after the function call and look at the top of the stack again-



Looking at the top of the stack, we can see that our "A" characters have been pushed to the stack, because strcpy() has executed and placed our input in the buffer. Now we continue past this address, and take a look at what happens when the function is finished executing and the popped return address attempts to be executed-



And as expected, the return address in EIP is corrupted, and our memory address (43434343, the equivalent of "CCCC"), is trying to be executed. Obviously it won't because it is not a valid address, but we know that we can overwrite it, and we can also now look at the stack and analyze what addresses we can use for a return address. Let's take a look by using x\64xw $esp - 100. This will let us look at memory with the x command. We specify that we want to view a unit size of 64 addresses (4 bytes each), and we want to look at them as hexadecimal instructions. We also specify the stack pointer ($esp), and we want to look 100 bytes beyond the stack pointer, where our data would still be stored in the buffer at the time of the crash. Let's run the command we mentioned-


Here we can see an address that points into our NOPS, 0xbffff690. Our simulated shellcode comes afterwards, as seen by the "42" instructions. Now we have a return address.

Now we just need our shellcode. I used the Shellcode Generator written by certaindeath, but you can also use msfpayload in the Metasploit Framework.  You can find the source code here. I'll use it to create a /bin/sh shell-


We now have what we need to create our exploit. 234 "A" characters, 234 NOPS, Shellcode, and our return address. It should look like this-

`python -c 'print "A" * 234 + "\x90" * 234 + "\x31\xc0\x83\xec\x01\x88\x04\x24\x68\x6e\x2f\x73\x68\x66\x68\x62\x69\x83\xec\x01\xc6\x04\x24\x2f\x89\xe6\x50\x56\xb0\x0b\x89\xf3\x89\xe1\x31\xd2\xcd\x80\xb0\x01\x31\xdb\xcd\x80" + "\x90\xf6\xff\xbf"'`

Is that our return address at the end?

Well yeah, but the reason it looks weird to you is because it's in Little Endian order. The stack is a FILO (First In, Last Out) data type, meaning the first thing to get pushed onto the stack is the last thing to be popped off. This means that we have to push each byte of our return address onto the stack backwards, and it will be read in memory as bffff690. Now let's run our exploit-


Pwned. We run our exploit, step through both of our breakpoints, and end up with a shell. We also could have used 468 NOPS instead of splitting them betweens NOPS and "A" characters. Either way, the instruction pointer is going to hit our shellcode.

Let's run it outside of the debugger in the command line as a regular argument-


And here you can see our exploit is successful. Running the command whoami in our shell let's us know we have root privileges. :)
                                       Sincerely Paid hackers
Stack Based Buffer Overflow Tutorial - By Paid Hackers  Stack Based Buffer Overflow Tutorial  - By Paid Hackers Reviewed by amit on 01:37 Rating: 5

No comments:

Powered by Blogger.