Babadook: Connection-less Powershell Persistent and Resilient “Backdoor”

At my previous company I used to prank the colleagues who left their stations unlocked. I call this my “internal awareness program”.

It was all fun and games at the beginning. I would leave post-its on their monitors with a friendly message “You could’ve been hacked” but it wasn’t giving the expected results. Some colleagues found it funny and started “collecting” my post-its. There was a guy in particular with 5 of them. It was evident harder measures had to be taken.

I’ve escalated the awareness program by replacing post-its to emailing the whole team with the message “I was reckless and left my computer unlocked”. Everybody would laugh about it but still wasn’t giving the needed outcome: People locking their desktops when away from the station.

Overcoming restrictions

I came to the conclusion that my colleagues would only learn the lesson if in fact they got hacked somehow, so I decided to make a backdoor so I’d be able to mess with their machines remotely.

Turns out that we were in a fairly constrained environment:

  • No direct connections between machines: VLAN isolation
  • User-only access, no admin privileges, cannot install anything
  • Corporate anti-virus in use, cannot use off-the-shelf solutions

So I started thinking what could I do with what I had in hands. As we were using Windows 7, one powerful tool came to my mind: POWERSHELL. Aw yiss!

I still needed to overcome some situations, no direct connections, inability to open sockets and so on.

As we were all members of the same team, we had access to the some shared folders and that was the vector that popped my mind. I would place a script on this shared folder and my backdoor would read this script and kinda eval() it. Simple and effective.

So by using the shared folder strategy and using powershell I’d solve the isolation problem AND the antivirus problem at once. I’ve added Clear-Content so the script would only run the code once.

I’ve skipped lunch for a day and rigged a quick and dirty POC. Tested on my machine, found a colleague that had left the machine unlocked and BAM, it was working.

After some days of fun, they started figuring out and killing my powershell process from the task manager. I needed to make the backdoor resilient.

Enter Babadook

The name came from an excellent scary movie (I trully recomend you to watch it!) I’d seen a while ago called The Babadook @ IMDB, which had the quote “If it’s in a word or in a look, you can’t get rid of the Babadook”.

That’s the motto I would follow to my backdoor. Make it unkillable as long as reasonably possible. Stealthiness wasn’t a big deal. Once I’d started playing the “Super Mario Theme Song” on their PC Speakers my presence would be spotted.

I kinda also wanted them to know and after some while after they came back to their stations and realized they had left it unlocked, they knew they had been pranked.

The Babadook

Multi-threading and the Watchdog routine

I quickly concluded that I’d needed to make my backdoor multi-threaded to have something watching my back while the main routine was waiting for commands. Powershell’s “Jobs” functionality would fit.

I’ve created a Watchdog function which were merely a while ($True) loop sending Stop-Process -processname taskmgr and ignoring errors (if the Task Manager wasn’t running).

I did the same for cmd.exe, wscript.exe and cscript.exe just to be safe.

This also effectively blocks running .bat and .vbs files since the interpreter has no chance to fully load before being killed by Babadook.

That worked for a while until IT released a GPO update blocking powershell remoting and thus blocking the use of powershell Jobs. *sadface*

So the quest for an alternative began and remembering how powershell and .NET integrate beautifully I was sure I could use some Somelongnamespace.Threading.Something .NET voodoo to accomplish that. Turned out the solution was way easier by using powershell’s Runspaces.

It worked as a charm! My watchdog was up again killing Task Manager immediatly as the window would (try) to appear. My colleagues were going crazy.

NOTE: Up to this moment I’ve been facing some issues with BeginInvoke which seems to fail to run ever once in a while, still debugging this issue. With Jobs I’ve never had this issue, instead I had issues where when the Job wasn’t properly stopped, it would run forever and required a reboot to die since the Watchdog wouldn’t let me open a powershell session.

There can be only one

In order to ensure that nobody would try to play smart and open a powershell window and try to use the Get-Process and Stop-Process to try to kill my backdoor, I’ve added the functionality to the watchdog to kill all powershell processes which were not his own. Upon start I’d save my process ID into a variable and use that to check the other powershell processes.

Also, no Powershell ISE here!

You can’t Run but I can hide!

At the same time my colleagues were desperately trying to kill Babadook, I was also doing the same to ensure I could cover the holes before they were able to get to it.

I’ve realized that someone could just invoke the taskill command directly from the “Run” dialog and that was bad (for me), so I needed a way to prevent that dialog from coming up. As this is a built-in dialog and not a process, I wasn’t able to take down on the classical way (with Stop-Process) so I’ve appealed to .NET extensions to grab some Windows API calls in order to enumerate the foreground window and if the title was what I wanted, kaboom!.

Hiding in plain sight

To add a sleight of fear, I’d thought it would be nice to hide my Babadook files since if my victim could find the command script on the shared folder, he could add some code there to kill Babadook and end my party, so a little code to get this sorted out was added to the Watchdog:

The last line adds an entry to the Registry turning on the option “Don’t display system and hidden files”. As this was on the While ($true) loop, even if the user turned that off, it would be turned back on immediately.

Take no shortcuts

With my anti-kill countermeasures in place, I was thinking on more ways to kill Babadook to improve the Watchdog, so it came to my mind that one could create a shortcut for taskill so I’ve made a little modification to my “Run Killer”:

That would take care of popping out the “Properties” dialog out of any file. Booya!

When everything else fails, reboot!

I’m sure there are some other ways to kill my process but that was enough for the moment (and I needed to get some lunch anyway). So people started realizing that a reboot was the only way to get rid of the Babadook.

I couldn’t leave this that way and needed a a persistence method. I first thought about the “Run” key on the registry but that might need admin privileges, so why not resort to our well known scheduled tasks?

Popped up a code to copy the Babadook script to the local machine with a random name and create the new task to run “At Logon”, “On Idle” and “Daily at 8AM”.

For more information on Task Scheduler options, check the MSDN Technet documentation.

That was working beautifully until I realized I needed some concurrency control. Of course my “There can be only one” code would kill the competitors but I needed something more elegant and Mutexes came to my mind. Added a code for that also:

And of course I needed to prevent them from opening the “Scheduled Tasks” dialog. Since a Stop-Process to the mmc process was giving me “Access Denied” (it runs in some kind of UAC), I needed to take the .NET approach. Modified my “IF” to consider that:

Recap

So far we got:

  • Connection-less command execution (full powershell language incl. .NET extensions + system()-like with Start-Process)
  • Watchdog / Userkit (userland “root”kit)
  • Persistence
  • Concurrency control

And that worked well enough for me :)

It’s not about the money

So if you read until here you might probably been wondering: “Did you really skipped those lunches just to mess up your colleagues?”

Well, kinda. It was a great learning and they surely got the message. No one now leaves their session unlocked. :)

When the news hit my team leader (how they called the Boss at the company) he saw this was a good way to show upper management and the other teams the dangers of an insider, how basic malware works and escalated the Babadook as a truly internal awareness program, so it turned out to be a great deal for everyone (except for a few really pissed off teammates).

Code

As always, you can get the Babadook source at my github.

GoldenEye 2.1 released with even more randomness

Recently I’ve discovered that GoldenEye got his first signature from a big vendor.

That’s funny since the main GoldenEye objective is to be signature-proof due its randomness. I’ve done a quick search on the internet and found the signature update link for their products, downloaded, located that one mentioned above.

It was a very crude signature, as expected:

Mostly are the only static texts GoldenEye had (since this update ;)). These are mostly leftovers from Barry’s HULK, which GoldenEye was spawned from.

Changelog

No worries, this new patch include the following changes:

  • Referer strings from search engines now only domain part hardcoded (rest is generated)
  • Referer generation function now generates even more random referers.
  • NO MORE HARDCODED USER AGENTS. I admit, hardcoded user agents were lame. There’s now a User-Agent Generator function that will generate RFC-2616 compliant user-agent strings.
  • External User-Agent List Support: As the generator function may generate UAs for inexistent browser version + plugin version combinations, you can now supply your own list of User-Agents (one per line – text file) via the -u flag.
  • Besides no-cache I’ve added the directive max-age=0 that does basically the same thing. GoldenEye will chose one of them during the strike request.
  • More random keepalive values: They’re 110-120 (legacy), now they’re random 1-1000
  • User-Agent lists: I’ve added a res directory for external resources. Multiple text files were placed there with user agents from different platforms.
  • Utilities! Now the getuas.py scrapes (requires BeautifulSoup) http://www.useragentstring.com/ URLs.

About the User-Agent generation algorithm

The user-agent string follows the following format: Mozilla/[version] ([system and browser information]) [platform] ([platform details]) [extensions]

I have a python dictionary with OS-specific values and Platform-specific (Webkit, Gecko, Internet Explorer) values. There are many options for each one. Mostly generated on the fly thanks to python’s dynamic lists generation.

Here’s an example of the property generation

Upon program start, it will generate N random values and populate the python list. As lists can be easily joined with the + operator, this makes dynamic list generation a charm. The same goes to OS-specific values

Any effort now to block our user-agents will block legitimate traffic also :)

About referer generation

In the previous GoldenEye versions, referers were crude and simple, like search engine search urls with some random parameter. Now referers are generated like request urls:

  • Random PATH (/Hiad727ja)
  • Random QueryString key and value names
  • Random QueryString key and value quantity
  • Random QueryString presence

As it was before, referer presence is also random.

I think that covers all the changes for this version.

Download, test (please, not on other people’s servers) and report!

Whitespace Esolang Covert Channel / Steganography

I’ve been always a fan of esoteric programming languages (esolangs). These programming languages are generally made just for fun, mostly in universities or for challenges. Wikipedia describes as the following:

An esoteric programming language (esolang, in short) is a programming language designed to test the boundaries of computer programming language design, as a proof of concept, or as a joke. The use of esoteric distinguishes these languages from programming languages that working developers use to write software.

You’ve probably seen some of the famous ones like brainfuck and shakespeare language. Some months ago I stumbled upon this funny one called “Whitespace“.

About Whitespace esolang

Whitespace is an esolang created by Edwin Brady and Chris Morris from the University of Durham in released in 2003. Their opcodes consists only of spaces, tabs and line-feeds. Interesting, huh?

Here’s a sample Hello, World! program in Whitespace (red = spaces, blue = tabs, black = VIM cursor):

Whitespace

This “feature” came into my mind as a very difficult pattern to detect through computational means since the language natively discards every other character permitting this language to be merged arbitrarily with any other text…. and even some code ;)

I’ve then remembered that HTML has cool workarounds with repeated spaces and tabs when it comes to parsing and rendering, so I could be able to inject Whitespace opcodes into HTML without breaking it and with minor rendering quirks.

So the weather was crappy, beer was over and I decided to make a covert shell with that.

Creating the covert shell

PHP is one of the most used languages in websites and power popular platforms like WordPress and MediaWiki. PHP has an output buffering system (ob_start, ob_get_contents etc) and a widely abused feature called auto_prepend_file. These would be enough to setup my covert shell.

I quickly spawned two files, one .htaccess to handle my shell injection via auto_prepend_file (very known and old trick) and one wcc.php to do the magic.

This would ensure my shell works on almost any php page on the target acessible through the browser.

First thing I had to do was ensure that the I’ve got the output buffer after all other possible output buffer handlers had processed it. There’s quite a time since I left web developing but I did remembered about register_shutdown_function that is used to, you know, register functions that will run before the script exits.

I could’ve stopped there, but I’ve wanted to prevent other register_shutdown_functions to win the race and alter the output after I did, so I did some research and saw that if you call register_shutdown_function from a register_shutdown_function, it will have high chances of being the last shutdown function (unless other register_shutdown_function did the same trick).

And further down…

That took care of ensuring that my wcc_merge_output function will run at the very end of any script.

Now it’s time to play with the output buffer and do the whitespace magic. I’ve placed ob_start on my wcc_init function that is prepended by .htaccess so as soon as script starts, output buffering is enabled.

If the magic cookie key is set, it will run the command with exec (for testing purposes, you can change to whichever method you want), gzdeflate-it and convert to whitespace language.

I won’t comment on the actual code responsible to converting from ASCII to Whitespace but FYI, it basically converts each char to binary, pushes each character to Whitespace Stack, then adds “print char from stack” N times, where N = len(string) and finally adds the “end program” sentence.

You can read more about the internals of Whitespace Language on the official page’s tutorial. If you’re interested, you can check the wcc_whitespace_print_string function source-code.

The wcc_init function ended up looking like this:

When the original script finishes its job and execution is passed to my shutdown function, wcc_merge_output will grab the contents of the output buffer, merge, display and exit.

The caveat

Of course, nothing comes easy. I decided to test the WCC on a real (little old) WordPress install so I pulled up an old VM that I had it installed.

My buffer was being ignored or duplicated, depending on the page. Turns out I did not account the race condition that other codes might introduce when handling output buffer and they were flushing the buffer before I could act, so I created a little trap to prevent others from messing with it.

As from the documentation for the callback parameter from ob_start:

The function will be called when the output buffer is flushed (sent) or cleaned (with ob_flush(), ob_clean() or similar function) or when the output buffer is flushed to the browser at the end of the request.

That did the trick.

The sanitization and tokenization process is quite simple.

For content, first I replace all tabs to spaces, place each line in an array with respective line number as index. Then I remove the linefeeds from the each line and break the line into tokens separated by spaces.

For whitespace, I just convert a string to an array of characters. Dead simple.

Merging content

This is quite simple also. For each whitespace token (character/opcode), I add one of the content parts (tokens) followed by the whitespace token.

If whitespace payload is less than content, when I finish adding whitespace tokens, I just add the remaining pieces glued toghether by spaces and keep their line feeds.

If whitespace payload is greater than content, I just add raw whitespace payload to the end of the HTML content. This brings up some issues on detection but it’s better than no output at all. Just choose a page with more content.

You can check it out the source-code of this routine.

Issuing requests to the shell

In this PoC I’ve used the classic Cookie command input trick.

So through a shell, you can do something like

Then parse with any Whitespace interpreter and inflate the payload again

inflate.php reads input from stdin and passes to gzinflate.

Result?

Visual Differences

For some content you might get some quirks, for others, not.

Here’s a screenshot from both pages sources. First with embedded Whitespace command output and the second is the original.

Whitespace HTML Source Comparison

Here’s a screenshot from both pages rendered HTML. First with embedded Whitespace command output and the second is the original. (Don’t mind the images, this theme has random header images)

Whitespace Rendered HTML Comparison

Size discrepancies

Since we’re mostly changing stuff than adding, our file size ends up very close to the original if you have enought HTML to fit your command output. Below is the comparison of the original HTML with one with the output from some commands.

I’ve ran id, ip a show, ps aux and ls -al. id was the only one that fit entirely in the HTML I’ve got (pretty short page). The others resulted in raw whitespace appended to the end of the original HTML.

LOL. In some cases it even “minifies” a little…

Final notes

  • I did not put any effort on encoding/encrypting the cookie or commands or whatever. This is only to test the covert response channel.
  • I also know that cookie based command passing is easily detectable. And are many other better ways to do that.
  • Of course there are better methods than exec to run code. This is also not the point of this research.

Source code & files

All files are available on my github repo. Feel free to download, play, fork, whatever.

New version of GoldenEye WebServer DoS tool released

After the hackers 2 hackers conference talk last year, some people contacted me about known Python performance issues regarding the use of threads related to the GIL.

Indeed the threading wasn’t performing well due the nature of GIL so I’ve rewritten the code to support Python’s multiprocessing module. It’s a tad faster but I haven’t tested it exhaustively so if you feel the inner-beta-tester in you, let me know!

The download is available as always at the github project page at https://github.com/jseidl/GoldenEye and you can read more about the tool at the project page at this blog.

Please test it (ON YOUR OWN RESOURCES!!) and let me know your thoughts!

Quick and dirty ngrep credential (username/password) sniffer

Some time ago I’ve posted a quick (and dirty too!) command-liner using tcpdump to sniff plaintext credentials over the wire.

Now I’ve acomplished the same thing with a shorter regex and ngrep tool.

Where -i is for case-insensitive and -q for more precise output. See man ngrep for additional information.

And the output is as follows:

Hope that helps!

Quick and dirty tcpdump credential (username/password) sniffer

I’ve been playing the last months with mobile pentesting within the Android platform. As I’ve been able to setup tcpdump-arm on my android phone, I began fooling around with it. I was trying to cross-compile Dug Song’s dsniff into armle architechture but it was only giving me headaches within the libnet/libnids dependencies and stuff.

So I wrote a quick one-liner to dump potential credentials (username/password) flowing in plaintext over the line:

And it works quite sufficiently:

Its not BY FAR efficient as dsniff, but can help out sometimes!

Downgrade HTTPS connections to HTTP using Ettercap filters

Ettercap is a great tool for MITM poisoning and sniffing. Everyone on Infosec should have played with it (or Cain) at least once.

Man-In-The-Middle

MITM attacks are pretty easy to perform on a local network but the tools tend to crash a LOT. Cain (Windows) is a little more stable than Ettercap but I prefer it over Cain because it doesn’t spoof SSL that I consider too loud depending on the attack. NOTE: Ettercap runs better on text mode.

Filters

Well, another nice feature of Ettercap are its filters. You can do lot of stuff while playing with them. The nicest toy I’ve found to play around so far is content rewriting (but I think custom packet injection can be even funnier). Irongeek has played with Ettercap Filters in the past to rewrite img tags.

Sniffing while MITM

Sniffing plaintext passwords are just easy. Either Cain and Ettercap are built to detect common strings containing passwords but SSL has made this kind of sniffing impossible and many sites are using it at least for the login processes.

So while we wait for the super-quantum-computers to break 256-bit AES encryption, we may consider avoiding SSL for the period we’re sniffing so I’ve thought that filters could be perfect for that.

What would define where the login form data will be sent? The form‘s action field. So if I can interfere in the HTTP response I can send the login data ANYWHERE.

I’ve decided to just downgrade the SSL because I always tend to make the least noise I can (because we don’t want to get caught by the forensics, do we?). I could redirect the request to a specially crafted site or so but it would be much more noticeable.

What if SSL is required on server-side

No problem, SSL on server-side can be a requirement but by the time the server complains, data was already sent over in plain-text. :)

Getting things done

You can get my filter on my github page.

Just run the attack with the filter (assuming router is 192.168.0.1 and victim is 192.168.0.100):

You should see the following output:

And your victim will no longer receive (nor send) any https string anymore.

Quick note about request / response filtering

Sometimes you may have to comment one leg (request / response) out of the filtering or you will get redirection loops (like while tampering Facebook connections). Also, if the request is already under https, you won’t be able to filter it. The beauty of this attack is disallowing your victim to escape your domain to a secure zone.

HTH!

MDK3 goes bruteforcing Wireless SSIDs

One good practice is to disable your SSID broadcast so you don’t show up on the victims list. Although this doesn’t make you completely invisible, it does aid reducing ease of location. (Networks can still be located by BSSIDs).

MDK3 was written by ASPj to bruteforce network SSIDs (even with wordlists).

Tape has done some testings around and described it all on his blog post. It has some videos too of the attack in progress on a 3-character-lenght SSID.

MDK3 version 6 is already available with the latest release of BackTrack 4 on /pentest/wireless/mdk3.

The Church of Wi-Fi has some SSID wordlists available at their website.

Good cracking!

Kentuckiana ISSA’s Metasploit Class videos available at Irongeek

These presentations from May 8th, 2010 performed on the Brown Hotel in Louisville, Kentucky. on exploiting with the Metasploit framework has an tremendous value. Its from this month, still fresh! Its 7 hours of presentations, it takes a while to finish (I took almost a week! phew!) but its totally worth it!

It starts with Adrian “Irongeek” Crenshaw introducing Metasploit exploiting a Windows box via msfweb and msfconsole. Pretty neat.

Pwrcycle shows a good SYN scanning configuration on nmap with best practices for stealth using Decoys and taking advantage of fragmentation over IPS/IDSs. He also describes database (sqlite) integration on MSF and importing nmap scan results (XML). Pwrcycle also talks a little about db_autopwn that automatically exploits the target based on their open ports (from nmap scan). Quite kiddie and stealthless (as pwncycle itself mentions on the video), but funny tough.

Another great topic handed by pwncycle is Pivoting, the technique of jumping through machines to escalate your privileges. You go from a restricted environment to a more-featured on, on the compromised machine network and account privileges.

One that is very very exciting is Elliott “Nullthreat” Cutright that introduces stack overflow on a live demo (that was really cool) of a step-by-step basic example using an outdated version of tftpd for Windows (plugged on a debugger) while spawning the calc.exe.

On a great overview on the Meterpreter, Metasploit’s meta-interpreter payload, Martin “PureHate” Bos shows the advanced features you can easily achieve without tons of Assembly hacking like file transfers, hash dumping, and forth. It also mentions the capability of restoring de MAC (access, more specifically) times from a file. Forensics experts, go crazy! He also talks about psexec and event log clearing. Excellent!

This video introduces lots of concepts on post-exploitation like process migration, trace cleanup and even injecting the encoded (shikata ga nai polymorphic encoding, to avoid detection from AVs) meterpreter into executables to create backdoors (the creation of a persistent meterpreter backdoor is also covered). Martin also briefly shows Metasploit Experss, that is a portable Metasploit version.

David “ReL1K” Kennedy opens his talk showing how language packs may influence the exploit since it changes memory locations and then proceeds to the opensource python-driven metasploit-integrated Social-Engineering Framework that exploits our weakest link in security: the human element.

Exploitation is done by spoofing (cloning) websites (that is excelent paired with Ettercap’s dns_spoof), spoofing Meterpreter Java Applet signature or by exploiting serious browser flaws like the Aurora Memory Corruption (used as example in video) within the Metasploit integration.

David also talks about using commom services’ ports to bypass egress filtering and exploiting SQL Server vulnerabilities with Metasploit and FastTrack.

Videos can be watched online at Adrian’s website. The videos can also be downloaded in a better quality (files ~ 500MB).

Awesome!