Understanding Buffer Overflow Vulnerabilities in C Programming Part 2
Continuing from the example in the last post, let's try to understand how we can implement this and achieve privilege escalation.
You sit by yourself and try to guess the password in order to get into the debug mode. So you try a few shitty passwords, you try entering "password." Well, that's not working. Then maybe "youwontguessthisone." But you're also denied. You start thinking about what you can do, and then you remember reading the last post about buffer overflow. You decide to use this information to bypass the password check and go straight into the debug mode.
We will start by compiling the main.c file using the following command with gcc:
Notice a few things. First, we are using a couple of flags to help us remove protections that gcc has. Nevertheless, even though gcc has protections, it doesn't mean that our code is not vulnerable! We can see the warning after running gcc, which tells us that "the 'gets' function is dangerous and should not be used."
After this, we can run the code and attempt to overflow the buffer to trigger a segmentation fault:
Now let's check where the program crashed by using the following command:
The command sudo dmesg | tail -n 2 shows the last two lines of the kernel message buffer. It's useful for quickly checking recent system messages. The sudo part gives you administrative privileges, dmesg displays the kernel messages, and tail -n 2 filters and shows only the last two lines of that output.
We can see that we got a segfault at the address 41414141. To convert this to bytes, we can open Python3 and run the command:
We get A*4, so let's take 20 characters (which is what we defined in the buffer) and after this, we put as the password a quad-set of different characters to trigger a new segfault and repeat the whole process we just did.
We got quad F, meaning that 'AAAAAAAAAAAAAAAAAAAABBBBCCCCEEEE' comes after the last 'E', which is the place in the stack where we need to override and return to our debug function.
Let's find the address of the debug function.
The address is determined at compile time, so we need to inspect the compiled binary using the following command in the terminal:
objdump -d ./prog | less
After running this command, type "/debug" and you will see the name of the function along with the address on the left:
Next, let's create a Python file named exploit_main and write the following code inside:
Now all we have to do is write this command in the terminal and press enter twice:
(python3 exploit_main.py; cat) | ./prog
Well, our program has been hacked quite severely.
Deep Learning & Computer Vision Embedded Software Developer @ Mobileye | CS & Computational Neuroscience Student @ HUJI
1 年Wow, amazing ??
Software Team Lead
1 年????! ?????? ?
B.Sc. in electrical engineering and computer science student
1 年nice, thanks
Software developer at Wix.com
1 年Thanks Geva ??
Team Lead at Israel Defense Forces
1 年Cool thanks