Redirecting Code Execution
This section will demonstrate overwriting a function pointer to redirect code execution to another function.
Getting Started
We will be using the following code for the rest of this section:
#include <stdio.h>
#include <stdlib.h>
void win(void){
printf("You win!\n");
exit(0);
}
int main(int argc, char **argv){
struct {
char buffer[16];
void (*fp)(void);
} s;
s.fp = NULL;
printf("win: %p\n", win);
gets(s.buffer);
printf("fp: %p\n", s.fp);
if (s.fp == (void *)win)
s.fp();
exit(-1);
}Note: Compile with
gcc -o bof2 bof2.c
Overwriting Foo
If we try to send our previous 17 A’s, we’ll receive the same result as above; foo will be set to 0x41.
Stack:
Unfortunately, our objective is to access the win function. According to the code, this is possible if we set foo to the same value as win. Lucky for us, the binary gives us win’s address.
I highly recommend you attempt to reach the win function yourself before reading further.
Let’s see what happens if we send a few bytes more than before:
Stack:
It appears that foo’s address was set to 0x4847464544434241. If we convert this to ascii we get: HGFEDCBA.
Why is it backwards? A computer represents data according to its endianness. In most cases, you will be dealing with little-endian data (backwards). In networking, however, bytes are sent in “Network byte order” which is always big-endian (forwards).
In any event, this means we need to send our exploit to the server with the address of the win function in reverse. Using the echo command, we can use a pipe to send the data to our program’s standard input. If we look at the man page for echo, the -e flag says: -e, Enable interpretation of backslash escapes. The -e flag from echo allows us to send bytes if we escape them with a backslash. Recall that 0x41 is hexadecimal for 65 in decimal. Looking at the ascii table (man ascii), that corresponds to the letter “A”. If we run echo -e '\x41', we can print the letter A:
If we convert 0x565555554169 into a string representation, we just take two numbers at the end off at a time. 0x565555554169 becomes 0x69, 0x41, 0x55, 0x55, 0x55, 0x56. Using backslashes with the -e flag, we get \x69\x41\x55\x55\x55\x56.
If we combine everything, we can send our data off to the program and it should execute the win function.
Stack:
Congratulations, you’ve just redirected the program’s execution flow using a stack-based buffer overflow! Redirecting a program’s execution flow is commonly done in a technique called Return Oriented Programming, a more advanced stack-based buffer overflow. See the Return Oriented Programming section for more details.
Pwntools Exploit
Last updated