Category Archives: Malware Analysis

Malware Analysis – Dridex & Process Hollowing

[In this article we are going to do an analysis of one of the techniques used by the malware authors to hide its malicious intent when executed on Windows operating systems. The technique is not new but is very common across different malware families and is known as process hollowing. We will use OllyDbg to aid our analysis. ~LR]

Lately the threat actors behind Dridex malware have been very active. Across all the recent Dridex phishing campaigns the technique is the same. All the Microsoft Office documents contain embedded macros that download a malicious executable from one of many hard coded URLs. These hard coded URLs normally point to websites owned by legitimate people. The site is compromised in order to store the malicious file and also to hide any attribution related to the threat actors. The encoding and obfuscation techniques used in the macros are constantly changing in order to bypass security controls. The malicious executable also uses encoding, obfuscation and encryption techniques in order to evade antivirus signatures and even sandboxes. This makes AV detection hard. The variants change daily in order to evade the different security products.

When doing malware static analysis of recent samples, it normally does not produce any meaningful results. For example, running the strings command and displaying ASCII and UNICODE strings does not disclose much information about the binary real functionality. This means we might want to run the strings command after the malware has been unpacked. This will produce much more interesting results such as name of functions that interact with network, registry, I/O, etc.

In this case we will look at the following sample:

remnux@remnux:~$ file rudakop.ex_
 rudakop.ex_: PE32 executable for MS Windows (GUI) Intel 80386 32-bit
remnux@remnux:~$ md5sum rudakop.ex_
 6e5654da58c03df6808466f0197207ed  rudakop.ex_

The environment used to do this exercise is the one described in the dynamic malware analysis with RemnuxV5 article. The Virtual Machine that will be used runs Windows XP.  First we just run the malware and we can observe it creates a child process with the same name. This can be seen by running the sample and observing Process Explorer from Sysinternals or Process Hacker from Wen Jia Liu. The below picture illustrate this behavior.

dridex-processcreation

This behavior suggests that the malware creates a child process where it extracts an unpacked version of itself.

In this case we will try to unpack this malware sample in order to get more visibility into its functionality.  Bottom line, when the packed executable runs it will extract itself into memory and then runs the unpacked code. Before we step into the tools and techniques lets brief review the concept around process hollowing.

processhollowing

This technique, which is similar to the code injection technique, consists in starting a new instance of a legitimate process with the API CreateProcess() with the flag CREATE_SUSPENDED passed as argument. This will execute all the necessary steps in order to create the process and all its structure but will not execute the code.

The suspended state will permit the process address spaced of the legitimate process to be manipulated. More specifically the image base address and its contents.

The manipulations starts by carving out and clearing the virtual address region where the image base of the legitimate process resides. This is achieved using the API NtUnmapViewOfSection().

Then the contents of the malicious code and its image base will be allocated using VirtualAlloc(). During this step the protection attributes for the memory region will be marked as  writable and executable. And then the new image is copied over to the carved region using WriteProcessMemory()

Then the main thread, which is still in suspended state, is changed in order to point to the entry point of the new image base using the SetThreadContext() API.

Finally, the ResumeThread() is invoked and the malicious code starts executing.

This technique has been discussed at lengths and is very popular among malware authors. If you want to even go deeper in this concept you can read John Leitch article. Variants of this process exist but the concept is the same. Create a new legitimate process in suspended state, carve its contents, copy the malicious code into the new process and resume execution.

Now lets practice! In order to debug these steps we will use OllyDbg on a virtual machine running Windows XP.

OllyDbg is a powerful, mature and extremely popular debugger for x86 architecture. This amazing tool was created by Olesh Yuschuk. For this exercise we will use version 1.1. The goal is to extract the payload that is used during the process hollowing technique.

When loading this sample into OllyDbg we are presented with two messages. First an error stating “Bad or unknown format of 32bit executable”. OllyDbg can load the executable but it cannot find the entry point (OEP) which suggest the PE headers have been manipulated. Following that the message “compressed code?” is presented. This warning message is normally displayed when the executable is compressed or encrypted. This is a strong indicator that we are dealing with a packed executable. Here we click “No”.

codealert

When the sample is loaded we start by creating a breakpoint in CreateProcessW. This is a key step in the process hollowing technique. We do this by clicking in the disassembler window (top left) and then Ctrl+G. Then we write the function name we want to find. When clicking ok this will take us to the memory address of the function. Here we press F2 and a break point is set. The breakpoints can been seen and removed using the menu View – Breakpoints (Alt+B).

dridex-ollydbg-brkpoint

Then we start debugging our program by running it. We do this by pressing F9 or menu Debug – Run. Once the break point is reached we can see the moment before CreateProcessW function is invoked and the different arguments that will be loaded into the stack (bottom right).  One of the parameters is the CreationFlags where we can see the process is created in suspended mode.

dridex-createprocessw

For the sake of brevity we wont perform the breakpoint steps for the other function calls. But the methodology is to set breakpoints across the important function calls. Before we start debugging the program we can set a break point for the different function calls that were mentioned and review how this technique works. In this case we will move into the end of the process hollowing technique were we hit a breakpoint in WriteProcessMemory() . Once the breakpoint is reached we can see the moment before WriteProcessMemory() function is called and the different arguments. In the stack view (bottom right) we can see that one of the parameters is the Buffer. The data stored is this buffer is of particular interest to us because it contains the contents of the malicious code that is going to be written to the legitimate process. In this case might give us the unpacked binary.

dridex-writeprocessmem

Following this step the code is resumed and executed. During the debugging process if we have Process Hacker running in parallel we can see the new process being created. We can also edit its properties and view the memory regions being used and its suspended thread. Finally when the code is resumed we can see the parent process being terminated.

That’s it for today. In the next post we will carve this buffer out and perform further analysis on this sample in order to understand its intent and capabilities.

The threat actors behind malware have many incentives to protect their code. The world of packing , unpacking, debugging and anti-debugging is fascinating. The competition between malware authors and malware analysts is a fierce fight. The malware authors write armored malware in order to evade AV and Sandboxing detection. In addition they go great lengths ensuring the analysis will be difficult. For further reference you may want to look into the following books: Malware Analyst’s Cookbook and DVD: Tools and Techniques for Fighting Malicious Code, the Practical Malware Analysis and Malware Forensics: Investigating and Analyzing Malicious Code . More formal training is available from SANS with GREM course authored by Lenny Zeltser. Free resources are the Dr. FU’s Security blog on Malware analysis tutorials. The Binary Auditing site which contains free IDA Pro training material.  Finally, the malware analysis track  in the Open Security Training site is awesome. It contains several training videos and material for free!

 

References:

SANS FOR610: Reverse-Engineering Malware: Malware Analysis Tools and Techniques
Malware Analyst’s Cookbook and DVD: Tools and Techniques for Fighting Malicious Code
http://www.autosectools.com/Process-Hollowing.pdf John Leitch
https://www.trustwave.com/Resources/SpiderLabs-Blog/Analyzing-Malware-Hollow-Processes/
http://journeyintoir.blogspot.ch/2015/02/process-hollowing-meets-cuckoo-sandbox.html

Tagged , , , , ,

Malicious Office Document delivering Dyre

Phishing campaigns that distribute commodity malware are common and ongoing problem for end users and corporations. In this article would like give you an illustration about one email that was part of a phishing campaign that distributes a very successful banking trojan malware known as Dyre or Dyreza. This trojan is quite sophisticated. Among other things is capable of stealing all kinds of credentials from the victim’s computer. It can also redirect victim’s traffic to sites controlled by the threat actors using man-in-the-browser functionality. This allows interception and manipulation of traffic that is supposed to be delivered to legitimate sites. Dyre has remote access functionality that allows the threat actor to connect to websites trough the victim computer.

The distribution methods observed is the past are mainly done using phishing emails that include a malicious Microsoft Office document attached. It normally includes a Microsoft Word or Excel document with macros. The image below illustrates one of these samples where the sender falsely mimics a legitimate business transaction. This well-crafted email attempts to lure the recipient into opening the malicious attachment.

email-dyre

Noteworthy is that the threat actors behind the malware distribution operations go to great lengths ensuring the files are not detected as malicious  by the different security mechanism such as Anti-Spam, Anti-Virus and Sandboxes.  Is quite normal when  submitting this malicious Office documents to Virus Total to have less than 10% detection rate and being rated benign by Sandboxes.In this example as seen in the picture below, the user when opening the email attachment is presented with the information that the document is encrypted with RSA algorithm and the user needs to enable macros in order to see its content.

email-dyre2

The document is of course not encrypted and this is a social engineering technique to trick the users to run the malicious macro. Allowing macros to run causes the malware to be extracted and executed in the victim system.

So what makes this document different than the others recently seen? The difference is in the weaponization mechanism that was used. Traditionally, these malicious Office documents have encoded and obfuscated macros. These macros when executed will connect to a site and download the malicious executable. However, in this case the document contains an obfuscated macro but the executable is embedded within the document.  This reduces the steps needed for infection and might increase the infection rate.

What tools and techniques one could use to unravel what is inside the document?

For malicious document analysis, REMnux and the cheat sheet created by Lenny Zeltser are a fantastic companion. On REMnux v6 one of the new tools pre-installed is the python-oletools toolkit. This toolkit was created by Philippe Lagadec based on the work created by John William Davison on officeparser. The tool among other things can parse and extract VBA Macros from Microsoft Office documents. It supports a variety of Microsoft Office documents and it can be very handy for this type of malicious documents. We start with the usage of olemeta.py to view the document metadata. In this case we could see codepage 1252 which might indicate where the document was fabricated. Then we run oleid.py which gives us a very good overview about the capabilities inside the document. In this case we could observe that the document contain VBA macros and OLE embeded objects. These indicators definitely need a deeper look.

email-oletools

We start by looking at the VBA macro. The following picture illustrates the output given by olevba.py after analyzing the malicious Office document. It shows the actual macro and one could see that is obfuscated. In addition the tool gives its interpretation of the different functions used in the macro. Many of the functions used are considered suspicious.

 

email-olevba1

Based on this information we can see that the document contains a obfuscated VBA macro that presumably creates RTF files (300.rtf and 301.rtf) and extracts an executable called n1.exe.

To further dig into these artifacts we will use another great tool. Oledump created by Didier Stevens. This tool allows you to analyze OLE files. As stated in the manual page: “Many file formats are in fact OLE files, like Microsoft Office files, MSI files. Even the new Microsoft Office Open XML format uses OLE files for VBA macros”. Another powerful tool created by Didier that even supports decoders and plugins such as Yara rules. One of the Yara rules is based on the work made on OfficeMalscanner  by Frank Boldewin that can find shelcode, PE-files and other embedded streams inside Office documents.

To verify our suspicious we use oledump.py with a yara rule that detects the presence of PE files inside documents. The output confirms that an executable was found inside the document.

email-oledump1

We can now extract the executable. The stream that triggered the Yara rule is the stream 11. Once again using oledump.py we can extract the binary and redirected to a file for further analysis.

email-oledump2

With the executable extracted we can now start  using static and dynamic analysis techniques to determine the malware capabilities and extract IOCs that can be used to across our logs and network to find infected systems. This will be left for another blog post.

E-mail continues to be the weapon of choice for mass delivering malware. The tools and techniques used by attackers  continue to evolve and bypass all the security controls in place. From a defense perspective, the US-CERT put together excellent tips for detecting and preventing this type of malware and to avoid scams and phishing attempts applicable to home users and corporations.

 

MD5 of the files used in this exercise:
Evil.doc  : dd3cd493aa68f55d1df442873ad2b2e8
Evil.bin : 27079661fb498dcf18194f45a4171492

Tagged , , , ,

Memory Forensics with Volatility on REMnux v5 – Part 2

Before we continue our hands-on memory forensics exercise, will be good to refresh some concepts on how memory management works on Windows 32 bits operating systems running on x86 architecture. Windows operating systems have a complex and sophisticated memory management system. In particular the way the mapping works between physical and virtual addresses is a great piece of engineering.  On 32 bits x86 machines, virtual addresses are 32 bits long which means each process has 4GB of virtual addressable space. In a simplified manner the 4GB of addressable space is divided into two 2GB partitions. One for user mode processes – Low 2GB (0x00000000 through 0x7FFFFFFF) -and another for the Kernel mode – High 2GB (0x80000000 through 0xFFFFFFFF). This default configuration could be changed in the Windows boot configuration data store (BCD) to accommodate 3GB for user mode.  When a process is created and a region of virtual address space is allocated – trough VirtualAlloc API – the memory manager creates a VAD (Virtual Address Descriptor) for it. The VAD is essentially a data structure that contains the various elements of the process virtual addresses organized in a balanced tree. Elements such as the base address, access protection, the size of the region, name of mapped files and others are defined on each VAD entry.  The Microsoft Windows Internals book goes over in great detail about it.

Fortunately, Brendan Dolan-Gavitt, back in 2007 created a series of plugins for The Volatility Framework to query, walk and perform forensic examinations of the VAD tree. His original paper is available here.

That being said the next step in our quest to find the malicious code. We will use these great plugins to look at the memory ranges that are accessible by the suspicious process virtual address space. This will allows us to look for hidden and injected code. Worth to mention that a great book with excellent resources and exercises about this matter is the Malware Analyst Cookbook from Michael Ligh et. al. Another great resource that also goes into great detailed and was published last year is the Art of Memory Forensics also from Michael Ligh and the Volatility team.  Both books mention that among other things the VAD  might be useful to find malicious code hiding in another process. Essentially, by looking at the memory ranges that have an access protection marked as executable specially with the  PAGE_EXECUTE_READWRITE protection. This suggest that a particular memory range might be concealing executable code. This has been demonstrated by Michael Ligh and was translated into a Volatility plugin named Malfind. This plugin, among other things, detects code that might have been injected into a process address space by looking at its access protections.  For this particular case Malfind does not produce results for the explorer.exe (PID 1872). Might be due to the fact that permissions can be applied at a further granularity level than the VAD node level.

Our next hope is to start looking at the different VAD attributes and mapped files of the VAD tree for this suspicious process using the Vadinfo plugin. The Vadinfo plugin goes into great detail displaying info about the process memory and the output might be vast. For the sake of brevity only the first entry is displayed in the following picture.

memory-analysis-8

In this case the output of the Vadinfo plugin displays almost two hundred VAD nodes and its details. Because we are looking for specific IOCs that we found we want to further look into these memory regions. This is where the Vaddump plugin comes to great help. Vaddump is able to carve our each memory range specified on the VAD node and dump the data into a file.

memory-analysis-9

Then we can do some command line kung-fu to look into those files. We can determine what kind of files we have in the folder and also look for the indicators we found previously when performing dynamic  analysis.  In this case we could observe that the string “topic.php” appears in five different occasions using the default strings command. In addition it appears once when running strings with a different encoding criteria – and this exactly matches the found IOC.

memory-analysis-10

On a side note is interesting to see based on the file names the memory ranges that span the virtual address space from 0x00000000 to 0x7FFFFFFF. And you also could see that there is some groups of addresses more contiguous than others. This related on how the process memory layout looks like. The following image illustrates this layout on a x86 32bit Windows machine. This can be further visualized using VMMap tool from Mark Russinovich and available on the Sysinternals Suite.

memory-analysis-13

Back to our analysis, one first step is to look across dumped data from the Vaddump plugin see if there is any interesting executables files. We observed that the previous search found several Windows PE32 files. Running again our loop to look for Windows PE32 files we see that it contains 81 executables. However, we also know the majority of them are DLL’s. Lets scan trough the files to determine which ones are not DLL’s. This gives good results because only two files matched our search.

memory-analysis-14

Based on the two previous results we run again the Vadinfo plugin and looked deeper into those specific memory regions. The first memory region which starts at 0x01000000 contains normal attributes and a mapped file that matches the process name. The second memory regions which starts at 0x00090000 is  more interesting. Specially the node has the tag VadS. According to Michael Ligh and the Volatility Team this type of memory regions are strong candidates to have injected code.

memory-analysis-15

Next step? run strings into this memory region to see what comes up and don’t forget to run strings with a different encoding criteria.

As you could see below, on the left side, we have a small set of the strings found on the memory region. This information gives great insight into the malware capabilities, gives further hints that can be used to identify the malware on other systems and can further help our analysis. On the right side you have a subset of the strings found using a different encoding criteria. This goes together with previous strings and  gives you even further insight into what the malware does, its capabilities and the worst it can do.

memory-analysis-16

Security incident handlers might be satisfied with dynamic analysis performed on the malware because they can extract IOCs that might be used to identify the malware across the  defense systems and aid the  incident response actions. However, trough this exercise we gained intelligence about what the malware does by performing memory forensics. In addition, as malware evolves and avoids footprints in the hard drive the memory analysis will be needed to further understand the malware capabilities. This allows us to augment prevention controls and improve detection and response actions. Nonetheless, one might want to even go further  deep and not only determine what the malware does but also how.  That being said the next logical step would be to get the unpacked malware from memory and perform static analysis on the sample. Once again, Volatility Framework offers the capability of extracting PE files from memory. Then they can be loaded into a dissasembler and/or a debugger. To extract these files from memory there are a variety of plugins. We will use the dlldump plugin because it allows you to extract PE files from hidden or injected memory regions.

There are some caveats with the PE extraction plugins and there is a new sport around malware writers on how to manipulate PE files in memory or scramble the different sections so the malware analysts have a tougher time getting them. The Art of Memory Forensics and the The Rootkit Arsenal book goes into great detail into those aspects.

memory-analysis-17

With the malware sample unpacked and extracted from memory we can now go in and perform static analysis … this is left for another post.

That’s it – During the first part we defined the  steps needed to acquire the RAM data for a VMware virtual machine before and after infection.  Then, we started our quest of malware hunting in memory. We did this by benchmarking both memory captures against each other and by applying the intelligence gained during the dynamic analysis. On the second part we went deeper into the fascinating world of memory forensics. We manage to find the injected malware in memory that was hidden in a VAD entry of the explorer.exe process address space. We got great intel about the malware capabilities by looking at strings on memory regions and finally we extracted the hidden PE file. All this was performed  using the incredible Volatility Framework that does a superb job removing all the complex memory details from the investigation.

 

Malware sample used in this exercise:

remnux@remnux:~/Desktop$ pehash torrentlocker.exe
file:             torrentlocker.exe
md5:              4cbeb9cd18604fd16d1fa4c4350d8ab0
sha1:             eaa4b62ef92e9413477728325be004a5a43d4c83
ssdeep:           6144:NZ3RRJKEj8Emqh9ijN9MMd30zW73KQgpc837NBH:LhRzwEm7jEjz+/g2o7fH

 

References:

Ligh, M. H., Case, A., Levy, J., & Walters, A. (2014). Art of memory forensics: Detecting malware and threats in Windows, Linux, and Mac memory
Ligh, M. H. (2011). Malware analyst’s cookbook and DVD: Tools and techniques for fighting malicious code.
Russinovich, M. E., Solomon, D. A., & Ionescu, A. (2012). Windows internals: Part 1
Russinovich, M. E., Solomon, D. A., & Ionescu, A. (2012). Windows internals: Part 2
Blunden, B. (2009). The rootkit arsenal: Escape and evasion in the dark corners of the system.
Zeltser, Lenny (2013) SANS FOR610: Reverse-Engineering Malware: Malware Analysis Tools and Techniques

Tagged , , , , , , ,

Memory Forensics with Volatility on REMnux v5 – Part 1

As threats and technology continue to evolve and malware becomes more sophisticated, the acquisition of volatility data and its forensic analysis is a key step during incident response and digital forensics. This article is about acquiring RAM from a disposable virtual machine before and after malware infection. This data will then be analyzed using the powerful Volatility Framework. The steps described here go hand in hand with the steps described on previous blog posts here and here about dynamic malware analysis.

We will use the methodology stated in previous post. We will start the virtual machine in a known clean state by restoring it from a snapshot or starting a golden copy. Then we will suspend/pause the machine in order to create a checkpoint state file. This operation will create a VMSS file inside the directory where the virtual machine is stored. Then we will use a tool provided by VMware named Vmss2core to convert this VMSS file into a WinDbg file (memory.dmp).  From VMware website: Vmss2core is a tool to convert VMware checkpoint state files into formats that third party debugger tools understand. Last version is available here. It can handle both suspend (.vmss) and snapshot (.vmsn) checkpoint state files as well as both monolithic and non-monolithic (separate .vmem file) encapsulation of checkpoint state data. This tools will allow us to convert the VMware memory file into a format that is readable by the Volatility Framework.

Next, we restore the virtual machine to back where it was and we infect it with malware. After that, we suspend the machine again and repeat the previous steps. This allow us to have two memory dumps that we can compare against each other in order to facilitate the finding of malicious code.

memory-analysis-2To perform the analysis and the memory forensics we will use the powerful Volatility Framework. The Volatility Framework born based on the research that was done by AAron Walters and Nick Petroni on Volatools and FATkit. The first release of the Volatility Framework was released in 2007. In 2008 the volatility team won the DFRWS and added the features used in the challenge to Volatility 1.3.  Seven years have passed and this framework has gained a lot of popularity and attention from the security community. The outcome has been a very powerful, modular and feature rich framework that combines a number of tools to perform memory forensics. The framework is written in Python and allows plugins to be easily added in order to add features. Nowadays it is on version 2.4, it supports a variety of operating systems and is being actively maintained.

Below the  steps needed to acquire the RAM data for a VMware virtual machine:

  • Restore the VMware snapshot to a known clean state.
  • Pause the Virtual Machine
  • Execute vmss2core_win.exe
  • Rename the memory.dmp file to memory-before.dmp
  • Resume the virtual machine
  • Execute the malware
  • Pause the virtual machine
  • Execute vmss2core_win.exe
  • Rename the memory.dmp file to memory-after.dmp

The following picture ilustrates the usage of Vmss2core_win.exe.

memory-analysis-3

After performing this steps we can proceed to the analysis. First we move the memory dumps to REMnux. Then we start the Volatility Framework which comes pre-installed. We start our analysis by listing the process as a tree using the “pstree” module on both the clean and infected memory image. With this we can benchmark the infected machine and easily spot difference on infections performed by commodity malware.  In this case we can easily spot that on the infected machine there a process named explorer.exe (PID 1872) that references a parent process (PPID 1380) that is not listed. In addition we can observe the processes vssadmin.exe (PID 1168) and iexplorer.exe (PID 1224) which were spawned by explorer.exe.  Vsadmin.exe can manage volume shadow copies on the system. This strongly suggests that we are in presence of something suspicious.

memory-analysis-4

 

Next step is to do a deep dive. During the previous dynamic malware analysis articles series were we analyzed the same piece of malware we were able to extract indicators of compromise (IOC). These IOC’s were extracted  from our analysis performed at the network level and system level. We will use this information for our own advantage in order to reduce the effort needed to find Evil. We knew that after the infection the malware will attempt to contact the C&C using a HTTP POST request to the URL topic.php which was hosted in Russia.

Let’s use this pieces of information to search and identify the malicious code. To perform this we will look for ASCII and UNICODE strings that match those artifacts using src_strings utility that is part of The Sleuth Kit from Brian Carrier and is installed on REMnux.

memory-analysis-5

The  parameter “-t d” will tell the tool to print the location of the string in decimal. We save this findings in a text file. The results are  then used by Volatility. Next, we invoke Volatility and use the “strings” plugin that can map physical offsets to virtual addresses – this only works on raw memory images and not on crash dumps – . It works by traversing all the active processes  and is able to determine which ones accessed the specified strings.  In case of a match we will have a good hint on where the malicious code might reside. In this case the plugin is able to match the strings with the process ID 1872 on two different virtual addresses.  This corroborates the fact that on the previous step we saw this process without a parent process which was rather suspicions . Another clue that we might be in good direction.

memory-analysis-6

This can be easily confirmed by listing the process ID 1872 using the “pslist” module.   Given this fact we proceed with the extract of this process from memory to a file using the “procmemdump” plugin. Volatility Framework is so powerful that it can parse PE headers in memory and carve them out. With this plugin we can dump the process executable using its PID.  After extraction we can verify that the file commands correctly identifies the file as a PE32 executable. Then we can verify that the string we found previous is indeed part of this process.

memory-analysis-7

Well, looks like the string “topic.php” is not in the data we just extracted. However, as we could see in the previous analysis steps we determined that the actions performed by the malicious code were in the context of this process. Furthermore, during the basic static analysis performed (see previous post) on the malicious executable we saw that it references very few libraries but two of them were noteworthy. The LoadLibrary and GetProcAddress.  This suggest the malicious executable was either packed or encrypted. In addition those libraries suggest that  malicious code was injected into a process.  There are several techniques used by threat actors to inject malicious code into benign processes. I will expand on this techniques on a different blog post. As conclusion we might be looking at malicious code that was injected in the process explorer.exe (PID 1832) and is somehow concealed. This means we will need to look deeper into the obscure and fascinating world of memory forensics. Part two will follow!

 

Malware sample used in this exercise:

remnux@remnux:~/Desktop$ pehash torrentlocker.exe
file:             torrentlocker.exe
md5:              4cbeb9cd18604fd16d1fa4c4350d8ab0
sha1:             eaa4b62ef92e9413477728325be004a5a43d4c83
ssdeep:           6144:NZ3RRJKEj8Emqh9ijN9MMd30zW73KQgpc837NBH:LhRzwEm7jEjz+/g2o7fH

References:

Ligh, M. H. (2011). Malware analyst’s cookbook and DVD: Tools and techniques for fighting malicious code.
Zeltser, Lenny (2013) SANS FOR610: Reverse-Engineering Malware: Malware Analysis Tools and Techniques

Tagged , , , ,

Static Malware Analysis – Find Malicious Intent

Any tool that you execute that analyzes a binary without running, it performs some kind of static analysis. Basic static analysis consist on producing information about a particular binary without running the code. On Win32 PE files there are a few steps that one can perform in order to find information about the malicious intent of a file in a very short amount of time.

First step, profile the file. Essentially this can be done by calculating the cryptographic hash of the file. This will compute a fingerprint that uniquely identifies the file. This unique digest can be used easily across different online tools like Virus Total, Malwr or Metascan-online to confirm malicious intent. Also, a file similarity index should be calculated using a process called fuzzy hashing or Context Triggered Piecewise Hashing (CTPH) – the original paper about this technique was written by Jesse Kornblum here -.   This fuzzy hashing technique is helpful to identify malicious files from the same family.

Second step is to run the strings command against the malicious binary.  The strings command will display printable ASCII and UNICODE strings that are embedded within the file. This can disclose information about the binary functionality.

Third step is to use some tool to analyze the Win32 PE headers. Extracting information from the PE headers can reveal information about API calls that are imported and exported by the program. It can also disclose date and time of the compilation and other embedded data of interest. Common Windows PE files extensions are .exe, .dll, .sys, .drv,.cpl, .ocx. When you compile a binary you can perform static linking or dynamic linking. Static linking means all the helper functions needed to execute the binary are inside the binary. On the other hand, dynamic linking is when the executable runs and resolve pointers to the helper functions at run time. In other words the binary contain library dependencies and these dependencies can be looked at in order to infer functionality trough static analysis. These dependencies are included in the Import Address Table (IAT) section of the PE structure so the Windows loader (ntdll.dll) can know which dll’s and functions are needed for the binary to properly run.

Let’s see how we can perform these steps in REMnux v5 using the PE file analysis toolkit.  The toolbox was created by the Brazilian security researcher Fernando Mercês and others. Is a very feature rich and usefully set of tools to analysis windows binaries. The toolkit runs on Windows, Linux and Mac. Some of the tools include:

pev70

To perform the first step, start by hashing the malicious binary in order to uniquely identify it. Pehash is a small tool that will produce the hashing of the file using different hashing algorithms including CTPH using ssdeep.

remnux@remnux:~/Desktop$ pehash torrentlocker.exe
file:             torrentlocker.exe
md5:              4cbeb9cd18604fd16d1fa4c4350d8ab0
sha1:             eaa4b62ef92e9413477728325be004a5a43d4c83
ssdeep:           6144:NZ3RRJKEj8Emqh9ijN9MMd30zW73KQgpc837NBH:LhRzwEm7jEjz+/g2o7fH

Then we can run Pestr to search for strings in the entire file.

remnux@remnux:~/Desktop$ pestr torrentlocker.exe

Another example would be to run the command “strings -a torrentlocker.exe”. The -a suffix will force the strings commands to scan the entire file and not only the data section.

static-analysis-strings

From the output we can see the string MSVCRT.dll. This is meaningful because its the name of a Windows library i.e., the Microsoft Visual C Run-Time Library. We can conclude the program has been written with Visual C++. Another interesting string that corroborates this conclusion is the program database (PDB) file which holds debugging and project state information for Visual Studio projects. This could be used to attribution to some extent. Other information that we can see is the _controlfp or _oneexit strings which are names of Windows functions exported from the MSVCRT.dll. In this case the strings output doesn’t produce any more meaningful results because the malware is obfuscated or encrypted or packed. This means we might want to run the strings command after the malware has been unpacked – this will produce much more interesting results such as name of functions that interact with network, registry, I/O, etc.

The final step is to use Readpe tool to identify the dll and functions the binary needs to perform its function. The functions used can be shown in the form of both import by ordinal and import by name as you can see in the below picture. Normally the binaries contain a large number of imported functions. If the number is low we can conclude the binary is somehow packed, obfuscated or encrypted.

static-analysis-imports

In this case the malicious file does not show much dependencies but, for example, it invokes GetProcAddress and LoadLibrary windows functions from the Kernel32.dll library. These two functions are very popular among packed malware because they allow the binary to load and get access to other Windows functions. In addition it invokes Windows functions from the MFC42.dll using its ordinal number. This can slow down the analyst but you can use tools like Dependency Walker to find out what the ordinal number corresponds to.

For Microsoft Windows enthusiasts, the same steps can be performed in order to achieve the same results. The first step on Windows can be performed using the Microsoft File Checksum Integrity Verifier. The tool can be downloaded here and below a sample usage

static-analysis-fciv

The second step can be performed on a Windows machine using the strings.exe utility that comes with SysInternals Suite.

static-analysis-sysinternals

And finally, the third step. One of the tools to perform this step is the Microsoft DUMPBIN utility that comes with the 32-bit version of Microsoft Visual C++. It is a command line tool to dump the different properties of a Win32 PE file for early evaluation of the file intentions. Below shows the DUMPBIN output of running the /dependents followed by the /Imports section.

static-analysis-dumpbin

The result is the same as the Readpe utility. The previous output show all dependencies from the malicious file and its Import Address Table.

Another alternative is to run the powerful and feature rich PEStudio tool created by Marc Ochsenmeie. The tool is free for non-commercial use and can perform static analysis on 32-bit and 64 bit binaries. The tool is actively maintained and contains great functionality that is worth to look. For example it can lookup Virustotal and query the different Anti-Virus engines using the file MD5. Other great feature is the Indicators. The Indicators show anomalies of the application being analysed e.g., the file not being digitally signed,

static-analysis-pestudio

We have showed the three basic steps that are used to perform an initial assessment in order to find the program malicious intentions without running its code. In this case the malware is packed and obfuscated so we will need to dig deeper but I will leave that for another blog post.

Other tools and techniques exist and a great summary of the available tools for Windows is written by Lenny Zeltser here. Besides this, for the brave who want to go deeper, one of the best resources available to learn about Windows PE internals is the course “The Life of Binaries” created by Xeno Kovah and available on opensecuritytraining.info. Other material of interest is the Microsoft Windows PE and COFF specification – available here . The PE Reference diagram created by Ero Carrera Ventura and the Black Hat 09 presentation “Undocumented PECOFF” from Mario Vuksan and Tomislav Pericin are also great material. Microsoft also maintains the Windows API reference site that can be helpful when looking at the Import Address Table.

 

Tagged , , , , , , ,

Dynamic Malware Analysis with REMnux v5 – Part 2

procdotDuring part one we created the environment to perform dynamic malware analysis with REMnux toolkit. Then the malware was executed and  all the interactions with the network were observed and captured. Essentially,  the malware was executed in a disposable virtual machine and all the traffic – including SSL – was intercepted.

Now, to further acquire information that would help us answering the questions made during part 1, it would be relevant to observe what happens at the system level.

Below recipe involves running Process Monitor from Sysinternals. Process Monitor is an advanced monitoring tool for Windows that shows real-time file system, Registry and process/thread activity, In parallel we run a packet capture with Wireshark on the disposable machine or we run tcpdump on REMnux. These tools will be started before malware executed and stopped moments after the infection. Then we will import this data – pcap and procmon – into ProcDOT. ProcDOT is a free tool created by Christian Wojne from CERT.at. It runs on Windows or Linux and is installed on REMNux This tool has the capability to parse the Procmon data. Then correlates it with the pcap  and transforms the data into a picture. This enables malware visual analysis. This method can be of great help for a effective and efficient dynamic malware analysis. The steps using part 1 model are:

 

  • Restore the VMware snapshot.
  • Start Process Monitor (need to be installed beforehand) and configure Columns fields to be compatible with ProcDOT.
  • Start Wireshark or tcpdump on REMnux and start capturing traffic.
  • Copy the malware to the virtual machine and run the malware.
  • Stop the wireshark capture and export the traffic into PCAP.
  • Stop the Process Monitor capture and export the results into CSV.
  • Move the PCAP and CSV file to REMnux.
  • Power off the infected machine.
  • Execute ProcDOT and import the procmon and pcap data.
  • Select the process and render the analysis.
  • Run trough the animation to understand the timing aspects.

The picture below demonstrate the result (for the sake of size elements such of registry key and paths have been removed):

procdot-torrentlocker

 

This visualization technique is very helpful in order to determine in a very quick way what the malware does. The graph produced by ProcDOT is interactive and you can play an animation of it in order to determine in which sequence the events occurred. In this case several relevant events happened. You can easily observe that:

  • The executable torrentlocker.exe starts execution and invokes a new thread id 1924
  • The thread id 1924 creates a new suspicious file named 01000000
  • Thread id 1924 creates a new process named “explorer.exe” with pid 1928
  • This new process creates several actions including
  • A suspicious executable file is created under c:\windows named izigajev.exe
  • A new AutoStart registry key is created invoking the just created executable file
  • The file Administrator.wab is read and data written to it.
  • A new process name vssadmin.exe is invoked

By looking at this sequence of events we can conclude that the malware performs process injection by injecting its malicious code into a benign process. Creates a copy of itself and drops it into Windows folder. Maintains persistence by adding the dropped executable into the auto start registry key and creates several suspicious files.

A very simple, fast and effective method that can speed up the malware analysis. Using this visual analytic technique and the one described on part one you can gather indicators that could now be used to identify the malware in motion (network) or at rest (file system/registry) across your network. Further they could be used to augment existing security controls and find additional infected systems.

Tagged , , , ,

Dynamic Malware Analysis with REMnux v5 – Part 1

REMnux-logo1 [Part 1 illustrates a series of very useful tools and techniques used for dynamic analysis. Security incident handlers and malware analysts can apply this knowledge to analyze a malware sample in a quick fashion using the multi-purpose REMnux v5. This way you can extract IOCs that might be used to identify the malware across your defense systems and aid your incident response actions. ~Luis]

Malware analysis is a interesting topic nowadays. It requires a fairly broad of knowledge and practical experience across different subjects. My background is in systems and infrastructure which means I am more confident with the dynamic analysis methodology than the static analysis one. Some of the readers have similar background. However, if you are willing to roll your sleeves and spend time in order to learn and be proficient with the different tools and techniques static analysis can done – hopefully will write about basic static analysis in a near future. Additionally is intellectually challenging.

One of the goals of performing malware analysis is to determine the malware actions and get insight into its behavior and inner workings by analyzing its code. By doing this we can find answers to pertinent questions such as:

  • What are the malware capabilities?
  • What is the worst it can do?
  • Which indicators of compromise (IOC) could be used identify this malware in motion (network), at rest (file system) or in use (memory)?  – These IOCs can then be used across our defense systems and in our incident response actions.

The process consists of executing the malware specimen in a safe, secure, isolated and controlled environment.The dynamic analysis methodology allows you to determine the malware behavior and how it interacts with the network, file system, registry and others. In this post I go trough a technique to determine its behaviour at the network level. In this way we can start answering the previous questions.

How?

A simple and effective manner to execute malware analysis in an safe, isolated and controlled fashion would be to use a second hand laptop with enough RAM and fast I/O like a SSD drive. Then on top of it a virtualization software. My personal preferences goes VMware Workstation due to the wide range of operating systems supported, and affordable price. Essentially two virtual machines. One machine running the resourceful and multi-purpose REMnux v5.

For those who don’t know, REMnux is a fantastic toolkit based on Ubuntu created by Lenny Zeltser that provides an enormous amount of tools preinstalled to perform static and dynamic malware analysis. The tools installed have the ability to analyze Windows and Linux malware variants. You can download it from either as a Live CD or a preconfigured virtual appliance for Vmware or VirtualBox from here.

The second machine will be running Windows XP or 7 32 Bits. That will get you started. Then configure the environment and install the required tools on the disposable – relying heavily on VMware snapshots – Windows machine.

In the first technique, I want REMnux to act as gateway, dns server and proxy – including SSL – . This will allow us to intercept all network communications originating from the infected machine. The following picture illustrates the methodology for dynamic analysis.

malware-analysis-framework

The illustration should be self-explanatory. In this manner, any DNS request made by the infected machine will be redirected to the REMnux. If the malware is not using DNS but using hardcoded IP addresses, the requests will go through the default gateway which is pointing to the REMnux. The REMnux by its turn will have iptables configured to redirect all received traffic either on port TCP 80 or 443 to TCP port 8080. On this port – TCP 8080 – Burp Suite is listening as a transparent Proxy. In this way you will have visibility and control into all network communications initiated by the infected machine.

On REMnux the steps to perform this configuration are:

  1. Define the Network adapter settings on VMware Workstation to be in a custom virtual networkg., VMnet5.
  2. Define a static IP
  3. Start FakeDNS to answer any DNS requests.
  4. Start HTTP daemon to answer HTTP requests.
  5. Redirect HTTP and HTTPS traffic to port TCP 8080 by configuring redirect rules via iptables.
  6. Intercept HTTP requests using BURP Suite in Invisible mode on port 8080
  7. Optionally you run tcpdump to capture all the networking traffic (allows you to create IDS signatures).

Te necessary commands to perform steps 3 to 6 are:

remnux@remnux:~$ sudo fakedns 192.168.1.23
dom.query. 60 IN A 192.168.1.23

Open another shell:

remnux@remnux:~$ httpd start
Starting web server: thttpd.
remnux@remnux:~$ sudo sysctl -w net.ipv4.ip_forward=1
net.ipv4.ip_forward = 1
remnux@remnux:~$ sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
remnux@remnux:~$ sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 8080
remnux@remnux:~$ sudo iptables -t nat -L
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination        
REDIRECT   tcp  --  anywhere             anywhere            tcp dpt:https redir ports 
REDIRECT   tcp  --  anywhere             anywhere            tcp dpt:www redir ports 
REDIRECT   tcp  --  anywhere             anywhere            tcp dpt:www redir ports 
REDIRECT   tcp  --  anywhere             anywhere            tcp dpt:https redir ports 

remnux@remnux:~$ burpsuite
[1] 8912

malware-analysis-framework-burp

Then, on Windows the initial steps are:

  1. Define the Network adapter settings in the VMware to be in the same custom virtual network as the REMnux.
  2. Configure IP address in the same range as the REMnux
  3. Configure the DNS server to point to the REMnux
  4. Define the default GW as being the REMnux
  5. Test the network settings
  6. Create a VMware snapshot
  7. Move the malware sample to the machine
  8. Start necessary tools (if needed)
  9. Execute the malware sample

After having the machines ready you can move your malware sample to the disposable Windows machine and execute it. In this case I executed a malware variant of Torrentlocker. The result is shown in the following picture:

malware-analysis-framework-result1

  1. There is a query from the Windows machine to the DNS server asking the A record of the address allwayshappy.ru
  2. FakeDNS answers back with the IP of the REMnux
  3. Windows machines establishes a SSL connection to the IP REMnux on port 443 which is redirected trough iptables to port 8080
  4. The traffic is Intercept by Burp Suite and can be seen and manipulated in clear.
  5. The request can be forwarded to localhost on port 80 to fake an answer.

Following the first request, this malware performs a second request, potentially sending some more data. Unfortunately the request is encrypted – that would be a good challenge for static analysis!

malware-analysis-framework-burp2

As you could see in a quick manner you could determine that the malware tries to reach out to a C&C. This type of knowledge can then be used to find other compromised systems and start your incident response actions.

You might see this as a time-intensive process that does not scale – think a company that needs to analyse hundreds of samples per month, week or per day – solution is automation. Several automated malware analysis system have appeared over the last years such as CWSandbox, Norman Sandbox, Anubis, Cuckoo and others. Essentially these systems load the malicious binary into a virtual machine and execute it. During execution all the interactions with I/O, memory, registry and network are tracked and then a report is produced. This greatly reduces the costs of malware analysis. However, is good to understand how to do manual analysis because many times the malware samples only trigger on specific conditions or bypasses the sandboxes. In addition you start to be proficient on different tools and techniques!

 

References:
SANS FOR610: Reverse-Engineering Malware: Malware Analysis Tools and Techniques

Tagged , , , , , , , ,