Hacking Series Part 14

Challenge: messy-malloc

Category: binary exploitation

We are given a binary and it’s source code called “auth” and “auth.c”. By looking at auth.c, you can tell that this program is essentially a simple authentication program. There are a few important features of the source code that show us how everything works, which are the functions login, logout, print_flag, as well as the user struct that looks like the following.

In order to get the flag, a user needs to have the correct access code. If you convert the access code used in the source code from hex to ASCII, the access code becomes ROOT_ACCESS_CODE.

If you look at login, you will see that when you enter a username, only the username part of the struct user is initialized. That means that the other two values (access_code and files) are still filled with random values from the previous memory allocation and are never zeroed out.

As a result, it would be possible to initialize an entire user struct with the correct access code in three steps. The first is to login with a crafted user struct containing ROOT_ACCESS_CODE in the middle with surrounding padding (since access_code is the second value in the struct). This can look something like the following.

Next, you use logout in order to free the allocated memory, which leaves an entire user struct in freed memory. Finally, you login again with the same length of the previous username so that malloc returns the same pointer to the recently freed memory (in this case, our crafted user struct). The username we provide when logging in a second time should not exceed the first set of padding characters, so it is safer to just login with a single character or two.

After that you can print the flag since the correct access code should be leaked to the access_code value of the struct. Using Python, I crafted the previous steps into an output and piped this to the service. The length of the username turned out to be 32 characters long, so in both login attempts, the length should be 32.

I immediately got the flag after that.

some chaos for you