I got a homework assignment asking me to invoke a function without explicitly calling it, using buffer overflow. The code is basically this:
#include <stdio.h>
#include <stdlib.h>
void g()
{
printf("now inside g()!\n");
}
void f()
{
printf("now inside f()!\n");
// can only modify this section
// cant call g(), maybe use g (pointer to function)
}
int main (int argc, char *argv[])
{
f();
return 0;
}
Though I'm not sure how to proceed. I thought about changing the return address for the program counter so that it'll proceed directly to the address of g(), but I'm not sure how to access it. Anyway, tips will be great.
That is compiler dependent, so no single answer can be given.
The following code will do what you want for gcc 4.4.1. Compile with optimizations disabled (important!)
Output:
While this solution doesn't use an overflow technique to overwrite the function's return address on the stack, it still causes
g()
to get called fromf()
on its way back tomain()
by only modifyingf()
and not callingg()
directly.Function epilogue-like inline assembly is added to
f()
to modify the value of the return address on the stack so thatf()
will return throughg()
.Understanding how this code works can lead to a better understanding of how a function's stack frame is setup for a particular architecture which forms the basis of buffer overflow techniques.
Since this is homework, I would like to echo codeaddict's suggestion of understanding how a buffer overflow actually works.
I learned the technique by reading the excellent (if a bit dated) article/tutorial on exploiting buffer overflow vulnerabilities Smashing The Stack For Fun And Profit.
Try this one:
or this one:
The basic idea is to alter the function's return address so that when the function returns is continues to execute at a new hacked address. As done by Nils in one of the answers, you can declare a piece of memory (usually array) and overflow it in such a way that the return address is overwritten as well.
I would suggest you to not blindly take any of the programs given here without actually understanding how they work. This article is very well written and you'll find it very useful:
A step-by-step on the buffer overflow vulnerablity