In this post we’re going to be looking at level 9 of the Natas wargame provided by Over The Wire.
What’s Going On?
Upon logging in we’re presented with another text entry and submit button, a long with a link to the source of the php page. Viewing the HTML source quickly shows no hints or ideas, so let’s click on the view source code link. Once we are viewing the PHP source code, we can see what this page does. It takes a user input and passes it as part of a command to the PHP function passthru(). Passthru() takes a string representing a shell command, and executes it, returning the output back towards us. In this instance, passthru() gets fed a string starting with the grep command. This is all good in the normal execution, we can even grep through the dictionary.txt file by submitting the web form with values in it. However, what can we do with this to break out?
Exploit
The first thing to notice is that the user supplied input is not sanitized. Next, it’s placed into the middle of a command, making it slightly more involved than passthru(userInput), but not by much. Since the string passed to passthru is sent directly to the shell, we can break up shell commands with the semi-color delimiter. To test this, let’s make a crafted string. This string will finish the grep command, perform a command we desire, then do something with the appended “dictionary.txt. To test this, let’s try to make our command print the current directory. Let’s make use of the following string for that:
“skldfjklsjfklsjf” dictionary.txt; pwd; ls -la
Putting the above string into the search box and clicking submit will net us a page with the current directory (/var/www/natas/natas9), and an ls -la print out of dictionary.txt. Now lets switch up the pwd command with something more valuable. If we remember back a couple levels, we had to read a password from a file at /etc/natas_webpass/natas8. Well, let’s see if there is a similar file for the next level. Let’s get the directory listing from /etc/natas_webpass:
“skldfjklsjfklsjf” dictionary.txt; ls -la /etc/natas_webpass/; ls -la
Upon searching, we get back the listing of the natas_webpass directory. Low and behold, there is a natas10 file which is group readable for natas9! So, let’s try to read that file:
“lksdfklsdfdklsf” dictionary.txt; more /etc/natas_webpass/natas10; ls -la
Once executed, we should now see the password for level10.
So What?
One should be VERY careful when using functions such as passthru(), exec(), system(), etc. Even if they are designed to take a string (“a command”), sometimes multiple commands can be put together in a way which is both logically legal and against the initial intentions of the original command. These functions are very dangerous as the commands are passed to the shell, and if they are user supplied, that means users can alter and possibly control what is passed to the shell.