Introduction

This section will demonstrate the basic concepts behind a stack-based buffer overflow by overwriting an integer on the stack.

Live Overflow - Using a buffer overflow to overwrite a stack variable

Conceptual Overview

This is a very old exploit which can be found in Phrack 49’s Smashing the Stack for Fun and Profit by Aleph One (1996). Many compilers implement multiple protections that will stop you from running this exploit, so initially we will be passing two special arguments (-fno-stack-protector and -no-pie) to remove some of these protections and lessen the complexity of the attack. In the later sections, we will work around many of the mitigations that compilers currently implement.

Getting Started

We will be using the following code for the rest of this section:

Note: Compile with gcc -o bof1 bof1.c

Overwriting a Value

Can you spot the vulnerability? The function gets is an extremely unsafe function to receive user input as it does not check how many characters it will, or should, receive. For this reason, it is an inherently dangerous function.

From the gets man page under “Bugs”:

Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.

As the man page says, gets will continue to store characters past the end of the buffer. What does that look like in our scenario?

Our struct looks like this in memory:

In this case, the numbers on the bottom represent the index for each element. From here on out, the numbers on the bottom will represent values in memory.

If we were to write “AB” to the buffer, it would look like this:

What if we wrote “AAAAAAAAAAAAAAAA” (16 A’s)?

This isn’t devastating as we didn’t corrupt any memory, but the buffer no longer contains a valid C string. Recall that C strings must be null-terminated. If foo was not set to 0, a call to printf would have trouble knowing where to stop and it would continue printing until it hit a NULL character.

What would happen if we wrote “AAAAAAAAAAAAAAAAA” (17 A’s)? It is at this point that I implore you to compile the program yourself and try it out. Are you surprised by what you found?

By writing 17 As, we completely filled our buffer and wrote one byte passed the end of the buffer. This is a buffer overflow! Because of how we allocated the memory for this structure, this is a stack-based buffer overflow.

Note: 41 is hexadecimal for the letter A. See man ascii.

Pwntools Exploit

Last updated