What is Buffer Overflow ?
In computer every application runs on a defined memory boundary and if part of the application exceeds the boundary then program crashes or in technical word “segmentation fault occurs”. Let’s see an example to understand it much better. Below is a smallest buggy code written in C programming language .
First try to understand the code below.
If you don’t understand most of C ( just like me ) it’s ok. Just follow along for now.
- int main( int argc, char **argv)
everything in C starts from main. Here char **argv means that this program will accept arguments from command line. For this program command line argument is Welcome
foo is a function which takes value passed in char**argv as an argument or some people say parameter. The value of char **argv is Welcome.
- Now the program execution jumps to foo.
What is happening in the above code ? The argument Welcome is passed to foo as a parameter . After that we declare c is a array which creates a memory space which can hold 12 characters only.
Strcpy(a,b) is a inbuld function which comes with C program library . As you might have guessed by now, it just copies string from a variable b to another variable a.
Strcpy(c,bar) is just copying the value stored in bar ( welcome ) to our c variable .
Well after copying the variable the execution return back to last statement of main which is } and exits . Below is the diagram created by me (it’s one of my masterpiece actually…. )
Now why the above code is vulnerable?
Every application is written using a one or more programming language. Every programming language is not foolproof. However, C is one the oldest and buggy programming language because it contains some functions which lacks some security checks.
Strcpy() function is a C built-in function which lacks bound checking. Bound checking means you can write more values in c i.e., you can execute the above program like below with more than 12 characters.
But how a hacker can use this for his benefit. See the below diagram.
From the above diagram you should have got the point why the code is vulnerable. Thanks to my awesome drawing skills. If not (however that’s impossible) ,let’s say application 1 is written using vulnerable code like C and application 2 is written using a modern high level programming language. Hacker exploited the strcpy() vulnerability and written beyond the allocated memory boundary (in our case it is 12 ) and put the memory address of another application example notepad.exe
Note: Next section is about stacks and registers. If you try to understand buffer overflow exploitation works and follow along for all the coming sections , please pay your full attention. I will also add a demo video how exploitation works at the end of next section