Buffer overflow

From LQWiki
Jump to navigation Jump to search

A Buffer Overflow is something no one wants. It is a huge security issue, and is responsible for many of the vulnerabilities we all hear about every day.

Let's start with a basic C program, as follows:

#include <stdio.h>

int main(int argc, char *argv[]) 
  char myBuf[20];
  printf("CMD line arg: %s\n",argv[1]);
  printf("myBuf: %s\n",myBuf);
  return 0;

We compile this:

gcc -o buftest buftest.c

Then test it:

$ ./buftest aaaaaaaaaa
CMD line arg: aaaaaaaaaa
myBuf: aaaaaaaaaa

Yay. But, you ask, what happens when we put in more than 20 a's? Good question.

$ ./buftest aaaaaaaaaaaaaaaaaaaaaaaa
CMD line arg: aaaaaaaaaaaaaaaaaaaaaaaa
Segmentation Fault

That nice little message "Segmentation Fault" tells us that something bad happened. Woops.

Basically, variables are stored in the stack. Look at this:

| Start Addr | Variables | Return Addr |

So, when we say char myBuf[20], we are making the Variable section 20 bytes long. Yet, when we pass 24 a's to it, as in the example, it's overwriting the Return addres. So as the program runs, it looks at the return address to see where to go next. Alas, death awaits at the reading, for it returns "0x63636363", or aaaa. Thus, the OS tries to find the function at address "0x63636363", but it doesn't exist!

So you say, sure all this is fine and dandy, but is it really that bad is the program just crashes?


Lets say for a moment we open this our program in a Debugger: a program that lets us see those function addresses. Also, let's assume that we know how to make a Shell script: a string of assembly instructions that can do interesting things, like open a shell, run commands, etc.

As you saw before, our return address was changed to "0x63636363", because 63 is the ASCII code for a lowercase a. So, now that we've found where our shellcode lies in memory, we can change that return address to that address simply by inserting the right 4 charactors at the end of our "exploit string". After this happens, the OS jumps it's execution to the shellcode, and does whatever the shellcode writer, be her bad or good, wants.

So: CHECK YOUR BUFFERS! Always make sure that your variables are the size you're expecting, and limit them when neccesary by using functions like strncpy()