Monday, September 22, 2008

Hijack Return Address

The code segment in this post demonstrates by a simple example how to hijack a return address of a function. The hijacking of a return address is employed by untrusted users which provided data overwrites the program calls tack - stack buffer overflow - by inserting an executable code which execution upon return of the current function would let one to take control of the system.

This code demonstrates how to hicjack the return address of a function. In this example the "foo2" function is not called anywhere, but in function "foo" we change the returns address on the process stack to be the beginning of function "foo2". So when function "foo" returns "foo2" is called instead of returning to "main" function. This causes printing the string "In foo2" and then the return address is again modified to be the place where "foo" function had to return in "main".

The compiled executable is tested and works in x86 32bit architectures. The compiled executable is not tested in 64bit architectures and is not guaranteed to work.

To compile with gcc compiler type the following command (assuming that you copy and paste the code in file named hijack_return_address.c):
$ gcc -o hijack_return_address.exe hijack_return_address.c

#include
#include

long original_return_address = 0;

int foo();
int foo2();

int main()
{
printf("Hijack return address example.\n");

foo();
}

int foo()
{
/*
Get the address where the exection should continue after this
function returns
*/
asm("movl 4(%%ebp), %0" : "=r"(original_return_address));

printf("In foo original_return_address: %x\n", original_return_address);

/* Change the return address to go the beginning of foo2*/
asm("movl %0, 4(%%ebp)" : : "r"(foo2));

return 0;
}

int foo2()
{
printf("In foo2\n");

/* set the original address from main function as a return address */
asm("movl %0, 4(%%ebp)" : : "r"(original_return_address));

return 0;
}

No comments: