Source : https://tryhackme.com/room/bof1

The aim of this exercise is to modify the normal operation of the program so that it executes a function that it is not supposed to be able to execute.

After connecting to the machine via ssh, we find the program’s c code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void special()
{
printf("this is the special function");
printf("you did this, friend!\\n");
}
void normal()
{
printf("this is the normal function");
}
void other()
{
printf("why is this here?");
}
int main(int argc, char **argv)
{
volatile int (*new_ptr) () = normal;
char buffer[14];
gets(buffer);
new_ptr();
}

To ensure that memory addresses are consistent between normal execution and the debugger, we recommend that you disable certain environment variables in GDB :

1
set exec-wrapper env -u LINES -u COLUMNS

Now that GDB is ready, we can try to crash the program. According to the source code, the size of buffer[] is 14, so we know how many characters we can enter before the program crashes.

If you add a character, you get :

Don’t forget that in C, character strings end with the null byte \0 so in reality our string of 14 characters is 15, which causes overflow.

By testing 15 A, we can see that we can modify the value of the EIP register:

A corresponds to \x41 in hexadecimal, so we can see that from 15 A we can control what is written to memory. Let’s see how far we can go:

With 20 A, we can see that the memory space is completely filled, and with 21 A, the program redirects us to another instruction. We can deduce the number of octes available for the overflow by making 20 - 14 = 6 bytes

Next, to use the special() function, we retrieve the address at which it begins:

Thus, using this address (which we convert to little endian by reversing the byte order), we can inject this address into the EIP register: