Wednesday, June 5, 2013

Smash the Stack IO Level 4 Writeup


It's been a while. I suppose finals, projects, etc. will do that. Anyway, I figured it was time to get back to posting content on here as much as possible - and I have some neat projects underway that I'm excited to share soon. For now, I'll continue the previous series covering the IO wargame on

Analyzing Level 4

In my previous post, I showed how a simple stack-based buffer overflow can allow us to manipulate the program in order to gain a shell, and extract the password for the level4 user. We can use that password to log in as level4.

We can see that we are given both the C source code and an executable binary to work with. Let's start by taking a look at the source:
As you can see, there isn't much to work with. However, that will make it easy for us, because it's clear which line we need to work with. We need to find some way to use the call to system("id"); code to give us a shell (or at least the password!).

So what happens when we call the "system()" command? Looking at the man page, we can see that this function calls /bin/sh -c command, where command is the argument to the function (in this case, "id"). Now, let's consider how /bin/sh knows where to find the given executable file. On the system, there exists an environment variable called PATH. We can see the following from the Wikipedia page:

When a command name is specified by the user or an exec call is made from a program, the system searches through $PATH, examining each directory from left to right in the list, looking for a filename that matches the command name. Once found, the program is executed as a child process of the command shell or program that issued the command. 

This means that when system() is called, the shell checks every directory on the PATH (from left to right) looking for a file by the given name. If it finds one, it executes it. The key thing to note is that we can change the PATH environment variable. This is done via the "export" command. Before we move on, really consider how it might be possible to change the PATH variable to force the system to execute a file it didn't intend to.

By using the knowledge that sh reads from left to right on the PATH, if we add a directory we control on the far left, and put in a file called "id", it will be executed when the system() command is called. Let's start by putting the following Python code in a file called "id" in the /tmp directory:
Next, we will manipulate our PATH variable to include the /tmp directory first so that our program is executed:
And now when we execute the program, we get a shell and the password to level5!

We can use this password to move on to Level 5. Pretty simple trick, but requires knowledge of how shells such as "sh" really work.


No comments:

Post a Comment