Author: d4rksystem

Chantay’s Resume: Investigating a CV-Themed ZLoader Malware Campaign

Chantay’s Resume: Investigating a CV-Themed ZLoader Malware Campaign

One beautiful and sunny evening, I happened to be poking around VirusTotal – because that’s what I do with sunny evenings – and I happened to come across an interesting CV-themed document. It was an Excel document entitled “Chantay’s Resume.xlsm”. This caught my eye mostly because resume’s should almost never be in Excel format. Unless you are applying for an accountant role, perhaps – I’m not sure what those people do.

I decided to poke around at this file a bit:

excel-suspicious-resume-document

Upon opening this document in Excel, I received a helpful message from the job applicant. Good thing Chantay provided instructions for his resume file, otherwise I wouldn’t be able to see his prior work experience and educational credentials somewhere embedded in this CV.

I pressed the Enable Macros button at the top, as Chantay nicely instructed, and I received this popup error message:

dll-download-error-message

It looks as if Chantay’s resume attempts to download a DLL file from the Internet and then executes it . However, my malware analysis virtual machine is not connected to the Internet, so this process failed. Capturing this download request in a web proxy, such as Fiddler, proved this to be correct:

malicious-dll-download

A connection attempt was made to “hxxp://205.185.125[.]104/7kWZLZ”. This URL is likely hosting Chantay’s malicious DLL.

I also captured this activity in ProcMon (ProcessMonitor). Let’s inspect this activity:

malicious-dll-download-procmon

It seems that Excel is attempting to download this DLL from 205.185.125.104, write the file (WriteFile) to a directory in my C: drive, and then load the file using rundll32.exe (ProcessCreate). This is a fairly common method of downloading and executing a payload from the Internet.

How is Excel doing all this, you may ask? I have no idea. There appears to be no VBA macro code in this document, nor p-code, or any other sneaky ways of obfuscating code in Office documents. But let’s dig a bit deeper.

The objects within this Excel document, like many Office documents, can be extracted simply by using a Zip utility such as 7zip. I used 7zip to extract all the embedded objects and one item specifically stood out:

hidden-xlm-code-excel-1


sheet1.xml” is 481kb, which is a substantial size given that this Excel document appears to only have one page of text and not much else. Inspecting this file a bit more revealed some code, which is likely hidden in the Excel spreadsheet itself:

hidden-xlm-code-excel

What we know now is that there is hidden code in this document somewhere, we are just not sure where. Olevba, my go-to tool for Microsoft Office document analysis, displays the following:

excel-document-olevba-analysis

So we know that this is an OpenXML formatted document and it contains no typical VBA macros. Let’s open Excel back up and see if we can find the hidden code.

If we navigate to the “Formulas” menu in Excel, there is an option for “Name Manager”. The Name Manager holds information relating to MS Excel formulas. I suspect this document is utilizing formulas for code execution, since this is what we observed when inspecting the XML files above. Name Manger will allow us to see the values of these formulas.

The Name Manager definitely contains some interesting strings worth investigating:

excel-malicious-xlm-code-analysis2

We can see a file path to a DLL, several Windows API functions (CreateDirectoryA, Download File, …), and a URL. Finally, there is an Auto_Open function. This function will execute when Excel is opened on the victim machine and after macros are enabled. We can jump to this location in the Excel workbook by double-clicking this Auto_Open entry in the list.

excel-malicious-xlm-code-analysis1

These functions are obfuscated – Excel needs to “calculate” these values before they can be seen in cleartext. When this Excel document is opened by a victim, the formulas will be calculated and the malicious code will execute.

Luckily for us, the built-in Excel debugger can be utilized to inspect this code. We can do this by right-clicking an interesting cell, selecting “Run”, and then “Step Into”, which will allow us to step into the formula and inspect its output:

dll-file-download-excel-xlm-code-debugging

After stepping though some of the code, we can see interesting strings such as a file being downloaded and saved to the C: drive as a DLL file.

To save time, and because I’m such as nice guy, I de-obfuscated the code for you, using the methods I outlined earlier. This Excel document:

  1. Loads kernel32.dll and invokes CreateDirectoryA to create a new directory under the C: drive in format C:<random>\<random>.
  2. Loads URLMON.dll and invokes DownloadToFileA to download the payload DLL file from hxxp://205.185.125[.]104/kWZLZ.
  3. Starts rundll32.exe to execute the downloaded DLL.

Let’s grab this DLL from the web server and look into it a bit further.

campaign-not-found-error-message

Bullocks. We are presented with a “default campaign not found” message, and the payloads appear to be no longer hosted here. Unfortunately, we won’t be able to grab this payload in this manner.

I turned instead to my friend VirusTotal. A brief search on VirusTotal shows that there are (or were, at one point) several DLL files hosted on this IP address:

ip-address-hosting-zloader-malware

In addition, there appears to be many other “resume” files that point to this same IP, including “Ying Rume.xlsm”, “Rose Carron CV.doc”, “Federico CV.xls”, among others:

malicious-resume-documents


Circling back to the DLL files, let’s inspect a few of these. Many of these DLL’S have interesting properties. Let’s choose one that looks interesting:

dll-version-info

This DLL is called “Google ipdate”, a very legitimate-sounding DLL file, likely straight from Google.

Let’s take a look at the static properties of this DLL file:

inspecting-static-dll-properties

A few interesting things about this sample are that it is coded in Borland Delphi, which is a bit strange for a DLL file. Also, as we already saw previously, we have the classic “Google Inc.” and “Google ipdate” meta data.

The original DLL being dropped and executed by the resume Excel document was executed with the parameter of “DllRegisterServer”. I know this because I saw this in the ProcMon output. So, to execute this DLL file in, say, x64dbg, we can run it with the command:

rundll32.exe <dll_file.dll>,DllRegisterServer
 running-zloader-dll-in-debugger

After about 1 minute of execution time, msiexec.exe is spawned.

msiexec-process-created

If we attach to the new MSI process in x64dbg and dump its process memory, we can better understand what malware family this sample resides in. Strings are a good place to start with this. We are able to see here some interesting URL strings in memory:

zloader-ip-c2s-in-strings

Leveraging Fiddler (or any other web proxy), I was able to confirm that this malware sample is attempting to contact the URLs I saw in memory.

zloader-contacting-c2-ip-addresses

These are likely C2 addresses. After a bit of research on the format of these URLs, there appears to be one malware family that is notorious for using a URI of “post.php”. Dum dum dum… Zloader.

ZLoader is a form of Downloader malware that establishes a connection with one or multiple C2’s, and then attempts to drop additional modules, implants, and other malware. So, it seems that at least one of the DLL’s being delivered in this campaign is ZLoader. Below, we can see part of this infrastructure, mapped out in VirusTotal:

complete-zloader-maldoc-investigation-virustotal

Summary

Well, there you have it. To summarize, Chantay’s nice resume utilizes hidden XLM macros in order to download and execute a DLL payload. The DLL payload, in my case, was a ZLoader variant. Very tricky, Chantay. Hope you at least got that job you were applying for.

Key takeaways: Be careful with resume files sent directly to you, and even more careful if they are in a non-standard format. Resume’s should almost always be in .doc, .docx, .rtf, or possible .pdf… But almost never in .xls/.xlsx fromat 🙂

As always, thanks for reading! If you enjoyed this post, follow me on Twitter (@d4rksystem).

Malware Samples Used

Resume document

b87f733efc95172621e267293ea60c41758ddcd9e005028df22af7e0a199cca8

DLL File

d36366666b407fe5527b96696377ee7ba9b609c8ef4561fa76af218ddd764dec

Analysis of A Lokibot InfoStealer

Analysis of A Lokibot InfoStealer

Lokibot is a family of “infostealers” designed to steal sensitive data such as credentials, cryptocurrency wallets, and other juicy things. Once a victim system is infected, this data is typically sent to a Command & Control server via HTTP POST.

I decided to dig deeper into this infostealer out of curiosity, as well as its prevalence in the cybercrime communities.

Here is the sha256 hash of the sample I used during this analysis:

49B9A126A7E543B1279C0863795D21CABD5EAA7D4A4E8B6DC1DF717BEDE1559A

A quick static file analysis of the sample does not reveal much. Below, we can see some of the properties and headers of the file, such as that it is an executable. We can also see that the sample is likely written and compiled in Delphi. The import table is also lacking, leading me to believe that the sample is packed and will later unpack itself in memory.

Lokibot sample properties – packed

Let’s run the sample in our sandbox and see how it behaves.

Behavioral Analysis

When starting the Lokibot executable in a virtual machine, the sample basically copies itself to the users “AppData\Roaming” directory as “ever.exe”. It then executes the “ever.exe” executable, unpacks itself into a new instance of “ever.exe“, and kills the original “ever.exe” process.

Below, we can see the unpacked sample running as “ever.exe”.

Lokibot sample running on Windows 7.

Capturing traffic in Wireshark, we can see some interesting behavior:

Wireshark traffic.

The sample seems to make an HTTP POST to the domain “smallthingstress.sytes.net”. Inside the POST data is my Windows hostname, username, and a string at the end. At the beginning, there is a reference to “ckav.ru”. This is actually referencing a domain, “fuckav.ru”, which we will see again later in this sample’s code.

Unfortunately, I was unable to do more analysis of the complete C&C traffic flow because the domain appears to be offline now. Good thing for the victims, bad thing for us malware analysts 🙁

Unpacking Lokibot

The goal of this analysis is to understand the detailed functionalities of the malware. One of the ways in which to do this is to let the sample unpack itself in memory, and then extract it from memory as an executable and finally rebuilding the PE headers and IAT (Import Address Table). This way, we will be able to open up the sample in IDA or another disassembler and view its functionalities to start analyzing it.

For unpacking, I decided to use a tool called “hollows_hunter“. I wrote in detail about hollows_hunter here if you are interested.

In summary, hollows_hunter is a tool that scans all processes in your virtual Windows environment and attempts to locate malicious activity such as hooking, code injection, shellcode, etc. Once the malicious activity is recognized, hollows_hunter automatically dumps the associated executables, and attempts to rebuild the PE file and IAT. It worked really well in past samples I have ran it on, and it is a good idea to run this tool before attempting manual unpacking to save some time.

HollowsHunter in action.

I ran the Lokibot sample and started hollows_hunter, which can be seen in the above screenshot. Luckily, hollows_hunter was able to dump the malicious process. To my surprise, it also rebuilt the PE and (some of) the IAT successfully, allowing me to inspect interesting imports and strings.

Static Analysis of Unpacked Lokibot

After dumping the unpacked executable, we can now see several interesting strings and functionalities:

Suspicious strings…

For example, there are strings that reference SQL statements, the URL we saw earlier (“smallthingstress.sytes.net”), the “fuckav.ru” domain reference, and some strings referencing various browsers.

Based on the above findings, we can be mostly sure that this sample is designed to enumerate and extract system information such as browser and SQL data. Let’s import the sample into IDA for a deeper analysis.

To start revering this sample, I chose a few of the interesting strings and imports in the strings list. Some of the items that caught my attention were the browser-related strings, and the connection-related imports (socket, connect, send, etc.)

Below, we can see a list of the functionalities of this sample. This Lokibot sample is attempting to read data from the following applications:

Lokibot – interesting functionalities.

Lokibot queries the filesystem and registry in order to enumerate system information, credentials, cookies, and other juicy data. Below, we can see some of the function code that is responsible for stealing Safari browser and keychain data:

Lokibot – stealing Safari data.

And here we can see the code responsible for enumerating SSH-related Putty data:

Finally, after gathering the juicy data, Lokibot sends this data to a remote web server (in my case: “smallthingstress.sytes.net”), which is what we saw in the Wireshark data earlier. We can see that in the below code, where the C2 URL and socket information is referenced:

That concludes this brief analysis of Lokibot. There are a lot of areas of code that I did not go deeply into during the static analyses, so I’m sure that this sample has additional functionalities that I overlooked. However, in malware analysis, its easy to get stuck in a rabbit hole of code. Sometimes it is best to simply understand the main functionalities of the code in order to quickly build detentions for them and respond to them in the future, rather than get lost in kilobytes worth of code that may or may not prove to be interesting.

As always, thanks for reading! If you enjoyed this post, follow me on Twitter (@d4rksystem).

Random Code Generation in PowerShell-Based Malware “sLoad”

Random Code Generation in PowerShell-Based Malware “sLoad”

Every once in a while, malware will surprise me with a new technique, or a new method of implementing an older technique. It’s kind of like malware analysis Christmas. Unpacking a gift (the malware) and getting a new toy. Nevermind.

Anyway, I was looking into a new “sLoad” sample the other day. “sLoad” is a Powershell-based Trojan downloader that implements a number of interesting techniques, but one special technique that I wanted to highlight with this post. I will not be covering the entire sLoad infection chain in detail here. If you want more information on sLoad, Microsoft put together a great analysis:

https://www.microsoft.com/security/blog/2020/01/21/sload-launches-version-2-0-starslord/ 

Buried in this sLoad PowerShell script, there is a call to a function “Get-Command -type Cmdlet”, as well as a call to “Get-Random -count 18”. “Get-Command” is typically called by system admins or developers who wish to get a list of various PowerShell functions that can be used for a certain task. In this case, the sLoad code is essentially generating a random subset (18, to be exact) of PowerShell cmdlets, and storing the resultant list in a variable ($r, in this case).

Generating list of random cmdlets!

We can see the $r variable populated with these 18 random PowerShell cmdlets:

Random PowerShell cmdlets.
Random PowerShell cmdlets.

To prove to you (and to me) that I’m not crazy, I ran this code again for your viewing pleasure and received the following new list of 18 random cmdlets:

More random PowerShell cmdlets.
More random PowerShell cmdlets.

Further on in the code, this list of random cmdlets is then separated with try/catch statements, and other code:

sLoad random code generation.
sLoad random code generation.

Finally, this end result is written to another PowerShell file and dropped to disk. The resulting script looks like the following:

sLoad final dropped script with random cmdlets.
sLoad final dropped script with random cmdlets.

We can see our random cmdlets that don’t actually serve a purpose here, and they will fail to run. Their main purpose is to obfuscate the code a bit, confusing the analyst, and burying the actual malicious functions in a small sea of garbage. In addition, these extra cmdlets likely confuse some endpoint defenses as well (such as EDR and AV).

The interesting thing is that I have not seen any additional information on the Internet for this technique, including in the Microsoft blog post.

As previously mentioned, I won’t go into detail on the malicous functiioanlity, but to quickly summarize, this script is loading a previously-dropped encrypted file (system.ini), which is then decrypted. I may write a follow up post on this decryption functionality as this is interesting as well.

Anyway, I simply wanted to highlight the random code-generation capabilities of this interesting sLoad variant. Please contact me (@d4rksystem) if you see something incorrect in this post or have additional comments!

As always, thanks for reading! If you enjoyed this post, follow me on Twitter (@d4rksystem).

Reversing Ryuk: A Technical Analysis of Ryuk Ransomware

Reversing Ryuk: A Technical Analysis of Ryuk Ransomware

Ryuk has been in operation since mid-2018 and is still one of the key ransomware variants operating in 2020. The threat actors behind Ryuk have been known to target a wide range of industries, and they typically demand substantial ransom amounts.

Lately, given the ongoing COVID-19 situation, the actors behind Ryuk have been taking advantage of this and targeting the most vulnerable – hospitals and the health care industry. In light of this (and because I am personally interested in how Ryuk functions), here is a technical analysis of Ryuk’s key functionalities.

Note: The Ryuk sample I used for this analysis is:

feafc5f8e77a3982a47158384e20dffee4753c20

Carbon Copies

The first thing Ryuk does upon execution is the creation of two “hidden” executable files that are placed on the desktop or one of the user’s temporary directories, depending on where the Ryuk sample was executed from.

Ryuk hidden executables.
Ryuk hidden executables.

These executables are actually copies of the primary Ryuk executable, and seem to be used for a few different purposes – most notably persistence and spawning additional instances of itself for more threads and faster encryption of the filesystem.

Ryuk child processes.
Ryuk child processes (executables) running.

Ryuk is extremely fast in its encryption process. This is possible due to the way Ryuk behaves in regards to threads. The two executables and associated processes that were created, along with the process injection techniques I will outline below, all serve as hosts for multi-threaded encryption. More on this later.

Process Injection

After the creation of its child processes, Ryuk will attempt to inject itself into additional processes running on the victim’s system.

Ryuk utilizes the Windows functions CreateToolHelp32Snapshot, Process32First, and Process32Next in order to enumerate processes running on the victim’s system and search for a feasible target process for injection:

Ryuk enumerating system processes.
Ryuk enumerating system processes.

Ryuk is only able to inject code into processes that are running at the same (or lower) privilege level as the Ryuk sample itself. So if Ryuk is running as Administrator or System (hopefully not the case!) it will be able to inject into System-level processes.

An important note is that Ryuk will not inject into csrss.exe, explorer.exe, or lsass.exe. This safeguard is likely used to prevent system instability, but this is just an educated guess. (Please let me know if you have additional information about this.)

Ryuk process-injection safeguards.
Ryuk process-injection safeguards.

After enumeration and selection of a target process, Ryuk utilizes a typical process injection technique:

First, the OpenProcess and GetModuleHandleA functions are called in order to get a handle to the target process.

Ryuk getting a handle to the target process.
Ryuk getting a handle to the target process.

VirtualAllocEx is then called in order to allocate memory within the address space of the target process, followed by WriteProcessMemory, which is called in order to write code into this new memory space. Finally, CreateRemoteThread is called to create a new thread in the context of the victim process, which will subsequently execute the injected code.

Ryuk writing memory and creating a thread.
Ryuk writing memory and creating a thread.

This injection process can also be seen in an excerpt from API Monitor:

Ryuk process injection - API Monitor.
Ryuk process injection – API Monitor.

The injected code is actually just another copy of the original Ryuk process. (See my post on unpacking Ryuk if you are interested in learning one method of leveraging this process injection technique in order to unpack Ryuk.)

When I ran Ryuk in my Windows VM, code was injected into dwm.exe, taskhost.exe, and even the VirtualBox Tray process (VBoxTray.exe). Interestingly, two of these processes crashed a few minutes after injection, so it appears that Ryuk can cause some incidental system instability.

Ryuk code injection crashes VBoxTray.exe.
Ryuk code injection crashes VBoxTray.exe.

Command Execution

Ryuk leverages Windows command line tools for most of its supporting functionalities. Some of these commands can be seen in the below code:

Ryuk executing various command-line commands.
Ryuk executing various command-line commands.

During my analysis, the following command were run by Ryuk:

net.exe stop "audioendpointbuilder" /y

This command kills the “audio endpoint builder” Windows service, which causes audio to malfunction on the victim system. I am still unsure why Ryuk executes this command, and I have no good suggestions.. Other than perhaps to infuriate the end user.

net.exe stop "samss" /y

Stops the Security Accounts Manager. This technique may be used to prevent security alerts being triggered and sent to a SIEM.

cmd.exe /c "WMIC.exe shadowcopy delete" 

This command clears the Windows Volume Shadow Copies so that they cannot be used to recover files.

cmd.exe /c "vssadmin.exe Delete Shadows /all /quiet"

This command is used as another method of removing shadow copies of files.

cmd.exe /c "bcdedit /set {default} recoveryenabled No & bcdedit /set {default}"
cmd.exe /c "bootstatuspolicy ignoreallfailures"

These commands are used to disable Windows error recovery and associated boot options so it is more difficult to recover the system.

icacls "C:*" /grant Everyone:F /T /C /Q
icacls "D:*" /grant Everyone:F /T /C /Q
icacls "Z:*" /grant Everyone:F /T /C /Q

These commands attempt to assign the group Everyone full permissions to the C, D,and Z drives. This is used before the encryption process begins, to ensure Ryuk has permissions to modify files.

cmd.exe " /C REG ADD "HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "EV" /t REG_SZ /d "<path_to_Ryuk>"

This command is used to add Registry persistence. Essentially, this will ensure the Ryuk sample will run again upon system bootup. Ryuk will only encrypt files once, however. Speaking of that… on to encryption!

Encryption – A Multi-Threaded Operation

The file encryption process runs once the above command line commands have been executed. As previously mentioned, Ryuk encrypts the filesystem using multiple threads, spread amongst the primary Ryuk executable, the secondary executables, and the processes Ryuk was able to inject into. Ryuk creates a new thread for each file being encrypted:

Ryuk encryption threads.
Ryuk encryption threads.

Ryuk utilizes the functions FindFirstFileW and FindNextFileW in order to iterate through the files on the victim system. Once a file has been found, Ryuk will call CreateThread in order to start a new encryption thread.

It is notable how quickly Ryuk is able to enumerate the files on the victim system and encrypt them. In my initial tests (running on a virtual machine with 50+ GB hard drive) files were encrypted within a matter of 120 seconds or so, including files on network-attached drives.

Ryuk will also create a “readme” file (RyukReadme.htm) in every directory that contains encrypted files. This readme file instructs the victim to contact the email address mentioned for further instructions on how to pay the ransom:

Ryuk readme file.
Ryuk readme file.

I originally wanted to go a bit more in depth into how Ryuk encrypted files and the encryption algorithms used. However, after a bit of research and code review, I realized that Ryuk is not doing anything incredibly new or note-worthy in terms of the encryption process. According to this research, Ryuk is utilizing RSA-4096 and AES-256 encryption algorithms, which are extremely strong and, at this point in time, “unbreakable”. I put unbreakable in quotes because, technically, no encryption algorithms are completely unbreakable and all will eventually be broken 😉

Network Enumeration

Ryuk performs some rudimentary network enumeration in order to discover other network drives and adjacent systems to encrypt. In my tests, and according to the Ryuk code in the sample I analyzed, Ryuk is able to enumerate the network in a few different ways.

First, Ryuk obtains the ARP table from the victim machine (using the GetIpNetTable function) and attempts to ping those connected systems to see if they are online:

Ryuk pinging connected systems.
Ryuk pinging connected systems.

If these systems are “alive”, Ryuk will attempt to connect to and mount SMB shares on these systems:

Ryuk attempting to connect to SMB network shares.
Ryuk attempting to connect to SMB network shares.

Ryuk will then attempt to encrypt any file system it is able to, given the victim system has the correct permissions and network capabilities to mount these devices.

In addition, Ryuk grabs the network adapter IP addresses (using the GetAdapterAddresses function) from the victim system:and attempts to send WOL (Wake-On-LAN) packets to these systems in order to wake them up. Ryuk will only send WOL packets to addresses that start with 10, 172, or 192.

Ryuk Wake-on-LAN attempts.
Ryuk Wake-on-LAN attempts.

Defending Against Ryuk

Ryuk MITRE ATT&CK matrix.
Ryuk MITRE ATT&CK matrix.
  • Since Ryuk (and other modern ransomware) is incredibly efficient and will encrypt an entire filesystem and attached network drives very quickly (likely within minutes), it is best to detect Ryuk as early in the Kill Chain as possible, ideally in the Delivery phases and before Installation.
  • Ryuk is typically delivered via other malware and droppers, such as Trickbot, Dridex, and Cobalt Strike Beacons. Developing detections and mitigating controls against these malware variants in order to detect an infection before the deployment of Ryuk is optimal.
  • In the event that Ryuk is deployed and encryption occurs, a sound business continuity and backup plan will be very helpful. Ensure offline backups are kept available.
  • Consider very carefully before paying the ransom for the purchase of the Ryuk decryptor software. This decryptor software has been well-researched by several threat intelligence vendors, and is said to be very poorly programmed and tends to crash during the decryption process, or worse, permanently destroys encrypted files.

As always, thanks for reading! If you enjoyed this post, follow me on Twitter (@d4rksystem).

Unpacking Ryuk

Unpacking Ryuk

In an earlier post, I wrote a technical analysis of the Ryuk ransomware and its behaviors. This post is a follow-up to that, for whoever is interested in learning one method of unpacking a Ryuk sample.

As explained in my previous post, Ryuk will typically try to inject itself into several processes running on the victim system. It does this be leveraging a common injection technique using OpenProcess, VirtualAllocEx, WriteProcessMemory, and finally, CreateRemoteThread .

Ryuk can be extracted from memory by running it in a debugger (x64dbg is my choice for this) and setting a breakpoint on CreateRemoteThread (this can be done with the command setBPX CreateRemoteThread in x64dbg).

Breakpoint hit on CreateRemoteThread.
Breakpoint hit on CreateRemoteThread.

Once the breakpoint is hit and program execution is paused, we can expect to see a handle to a process (the process in which Ryuk wishes to inject code into) by inspecting the call stack window. In my case, the handle is 0x148, located in rcx:

Call stack for CreateRemoteThread.
Call stack for CreateRemoteThread.

Next, we need to cross-reference this handle with its process name in order to find out the target process. We could use x64dbg for this, but I will use ProcessHacker because I feel it is a bit easier to use in this case. To do this, simply launch ProcessHacker, right-click the running Ryuk process, select Properties, and then the Handles tab.

We can see below that the handle (0x148) is associated with the taskhost.exe process. It looks like Ryuk injected code into taskhost.exe and is now attempting to run this code. Note: This process may be different for you! Ryuk often injects into dwm.exe, virtual machine processes, and others.

Handle to taskhost.exe in Ryuk process.
Handle to taskhost.exe in Ryuk process.

Now we must inspect this taskhost.exe process and try to find the location where Ryuk injected code. We can do this with ProcessHacker or any number of memory inspection tools. I have chosen instead to attach the process again to x64dbg and inspect the memory there. This is just a matter of personal preference, however.

What we are looking for in the taskhost.exe process address space is a suspicious memory region where Ryuk’s code has likely been injected. This can be accomplished using the Memory tab in x64dbg (or the Memory tab in ProcessHacker, if you choose to do it with this tool). In x64dbg, underneath the taskhost.exe memory region, we can see a memory region has been created with ERW (Execute-Read-Write) permissions, which is suspicious. The memory region has a significant size (163 kb), which is definitely enough space to store an executable:

Injected executable in taskhost.exe.
Injected executable in taskhost.exe.

This is likely our injected code. We can dump this memory region from x64dbg (or from ProcessHacker) by right-clicking the memory region and selecting the Dump or Save option.

Now you should be able to inspect this file in a PE viewer, or a disassembler (such as IDA), and should be able to see readable strings:

Ryuk strings - before unpacking executable.
Ryuk strings – before unpacking executable.
Ryuk strings - after unpacking executable.
Ryuk strings – after unpacking executable.

After dumping the memory region, if we try to start analyzing this file in a disassembler (such as IDA), we would see that this file is not a valid PE file, or is otherwise corrupted. To fix this, you can the use PE_Unmapper tool. This tool will “unmap” the executable from memory and fix up our dumped executable, including rebuilding the Import Address Table. Note: Other tools may work for this as well, including Scylla or OllyDump, but I found that PE_Unmapper worked the best for my case.

With PE_Unmapper, we can unmap this dumped executable using the following command syntax:

pe_unmapper.exe [mem_dump_input] [mem_address_base] [output_file]

In my case, the command would be:

pe_unmapper.exe ryuk_dump.mem 0x13F630000 ryuk_fixed.exe

You should now have imports listed in a PE viewer tool or in a disassembler. One important thing to note is that Ryuk dynamically builds a second imports table using the GetProcAddress function. This means that there are actually more imports than what is listed in the Imports section of any PE viewer tool. Because of this, you will likely experience issues analyzing this file in a disassembler.

These functions seem to be labeled as cs:qword_<address>. To fix this issue, you will have to manually rename these functions, like so:

Ryuk imports table - before fixing.
Ryuk imports table – before fixing.
Ryuk imports table - after fixing.
Ryuk imports table – after fixing.

You could probably script this part as well, if you felt motivated enough. If you do, please share it with me 😉

Here is the sha256 hash of the sample I used in my analysis:

feafc5f8e77a3982a47158384e20dffee4753c20

This sample can be found on VirusTotal. If you don’t have access to VirusTotal, just Google the hash and you may be able to find it elsewhere online. Otherwise, any new-ish Ryuk sample will likely work for this analysis.

Well, that’s about it. As always, thanks for reading! If you enjoyed this post, follow me on Twitter (@d4rksystem).

Extracting Malware from Memory with Hollows_Hunter

Extracting Malware from Memory with Hollows_Hunter

Sometimes I come across a tool that makes me stop and think what I have been doing all my life life without it. This is how I feel about hollows_hunter. Hollows_hunter is essentially a tool for automatic extraction of evil objects and malicious code from memory. The tool is able to hunt for things such as process injection and replacement, process hollowing, DLL injection, malicious shellcode, and has a host of other uses. Hollows_hunter is based on pe-sieve, written by the same author, hasherezade.

Once a malicious object is found in memory (for example, malicious code in a running process), the tool will auto-magically extract the process from memory, and attempt to rebuild the headers and Import Address Table (IAT). In many cases, the tool is able to completely fix up the dumped file and rebuild the IAT so I could load it into IDA for further analysis. This is great because some of the malware samples I attempt to unpack and extract end up as warped shells of their once-glorious selves, un-analyzable in IDA. Hollows_hunter has saved me a lot of time recently, and seems to not get as much attention as it deserves. This drove me to write a quick tutorial post for it.

Let’s dive into hollows_hunter to see why it is so useful. Hollows_hunter gives a wealth of options that we can enable to help us better extract the data we are looking for:

hollows_hunter command line parameters.

For the following post, I’ll be using the sample with the SHA256 hash:

f8d281ee13bd7bde9b236a21966e7868836c452f1b2b10ad7c6dd1c395fbf149

You can find this file on VirusTotal or elsewhere online, in case you want to follow along.

First, I’m going to run the sample in a Windows 7 VM sandbox. Immediately after executing the sample, I run hollows_hunter:

Running hollows_hunter.

The command line options I used above are “hooks”, “shellc”, “data”, and “imp”.

  • “hooks” essentially tells hollows_hunter to look for malicious hooks and patches in memory.
  • shellc” instructs the tool to look for shellcode (this sometimes produces false-positives, so handle with care.)
  • data” tells hollows_hunter to inspect non-executable memory segments. This is sometimes important because malware may write data to non-executable areas of memory. This data may be useful strings, or it may be code that the malware will later try to execute.
  • Finally, “imp 1” instructs hollows_hunter to attempt an automated rebuild of the Import Address Table (IAT). This is super helpful, as we will see in a minute.

I ran hollows_hunter as Administrator so that it can scan system processes. I could have also ran the sample with the parameter “loop”. This parameter instructs hollows_hunter to continually run on repeat, constantly looking for malicious activity.

After running hollows_hunter, we can see that it scanned all running processes, found some malicious activity in memory, and dumped those memory regions:

hollows_hunter summary.

PID 2892 and 2944 are, in my case, false positives. I know that because hollows_hunter seems to always detect malicious activity in svchost.exe and wmpnetwk.exe when running as an Administration. Powershell.exe (PID 2520) is the PowerShell process I am running hollows_hunter in, so this is also a false positive.

EDIT: After messing around with the latest version of HollowsHunter (HollowsHunter Portable 0.2.4), I have confirmed that the issues with most of these false positives have been fixed . Obviously, there will always be false positives with any tool, but @hasherezade did a great job at identifying the common FP’s.

We can see that the malware sample has spawned two strange processes (WhatsAppWeb.exe, PID 2480/2088), and hollows_hunter was able to dump those processes from memory.

If we navigate to the hollows_hunter directory that we ran the tool from, we can see new directories that match the name of the PID that was dumped. In my case, the directories I am interested in are “process_2480” and “process_2088”. Let’s see what hollows_hunter dumped for us in the “process_2480” directory:

hollows_hunter dumped process.

Here we can see the dumped executable from memory, the list of imports that the sample is likely utilizing, and a report of the findings in JSON format. Now let’s inspect the “WhatsAppWeb.exe” here. I will open this file in IDA, my disassembler of choice.

Interesting strings in "WhatsAppWeb.exe".

Looking at the strings, we can immediately see some of the capabilities of this malware sample. This sample seems to be utilizing keylogging functionalities, and possibly attempting to disable anti-virus software.

"WhatsAppWeb.exe" imports.

If we look at the Imports section, we can see all of the imports are listed here. This means that the IAT was successfully rebuilt! Rebuilding the IAT is always a huge pain in my %@$, so hollows_hunter really helped here!

Because the sample has been unpacked, the IAT and PE structure have been rebuilt, and the strings appear readable, this malware should be easy to analyze further in IDA. Whoot.

Analyzing "WhatsAppWeb.exe" in IDA.

Well, that’s all for now. I hope you learned a bit about the usefulness of hollows_hunter. Thanks to hasherezade for putting in the work to create such a useful tool!

If you enjoyed this post, follow me on Twitter (@d4rksystem) 🙂

Javascript Deobfuscation with Process Hacker

Javascript Deobfuscation with Process Hacker

I truly dislike Javascript-based malware. Deobfuscation of Javascript is, to me, annoying at best – and rage-inducing at worst. I love unpacking and analyzing PE executables, DLL’s, and the like, but I tend to avoid Javascript analysis when possible. However, in the world of malware, sometimes you must face your annoying, rage-inducing enemy in the face.

I have found that sometimes the fastest and simplest way to deobfuscate complex Javascript code is to simply run it in a Windows virtual machine using a JavaScript interpreter (such as the built-in wscript.exe), then dumping the memory of that process and directly extracting the deobfuscated code. I say “sometimes” because this techniques does not always work. I will explain why later.

Ok, let’s see how this could be done in practice.

I have downloaded a sample of WSHRAT, a Remote Access Trojan (RAT) written in Javascript. WSHRAT contains many interesting functionalities including keylogging, credentials stealing, and others. If you are interested in following along, here is the sample I used for this analysis.

https://www.virustotal.com/gui/file/f3f60c60e8f112bb0e2f04edb515a6984f9f148fcfd0871859c97fcd3c7a06b7/detection

Sorry – you must have a VirusTotal account capable of downloading the sample. But if you are resourceful, I’m sure you can find the sample elsewhere 😉

If we open the WSHRAT sample in a text editor, we can see that it contains a long obfuscated string in function “bgftrewas”. This string is actually obfuscated and encoded using several techniques. If you have time, you may be able to deobfuscated it manually.. But if you don’t have time, like me, you just want instant gratification 🙂 Let’s run the malware with the native Windows “wscript” Javascript interpreter and inspect the process memory!

WSHRAT Javascript code.
Obfuscated function.

Before we get started, it is important to note that this technique does not work for all Javascript code. In this particular case, WSHRAT is a “standalone” .js file and will run natively in Windows. Some Javascript code requires the context of a browser, PDF file, or other external contexts. You may be able to use this technique for even these, however your mileage may vary..

Double-clicking the .js file in Windows 7 will launch the file in wscript.exe. Other versions of Windows may use a different interpreter, but it shouldn’t be much different than what I describe here.

Next, open a tool such as Process Hacker or Process Explorer. Any tool that allows the viewing of processes and dumping the memory of said processes will work. Process Hacker is my go-to tool so I will demonstrate that in this blog post. If you inspect the running processes with Process Hacker, you will see two instances of wscript.exe running. This is the Javascript malware.

Choose the wscript process utilizing the most memory, right click on it, and select “Properties”. Then select the “Memory” tab – this will display the memory allocated to the wscript process. Finally, selecting “Strings” will display all strings in the current allocated memory. Select a string length of about 1000 bytes. This will allow us to quickly view the most interesting strings in the memory.

Now we can see a nice list of strings and code in the current memory of the wscript process.

Most of these strings are not helpful. The trick is to find the deobfuscated code in memory. Hint: Look for interesting functions and variables that were once obfuscated but are now readable. The strings in the image above hint that this may be the deobfuscated code. We can see in this image that the memory address of these strings is at offset 0x4cc3710 (it may be different on your machine if you are following along!). We could dump the code directly from the Strings window, but there is a better way to do it.

If we close the Strings windows and go back to the Memory window, we can located the entire memory region in which the deobfuscated Javascript code may reside. In my case, this memory region is 0x4ca0000, which contains the memory region we identified above (0x4cc3710). Right-click on the memory region we want to dump, and select “Save”. Then save this memory dump to a file.

After we dump the memory to a file, open the file in a text editor. There will be some unreadable content, but we will eventually find the deobfuscated Javascript code in the file! Sometimes the code may be spread across multiple memory regions, so you may need to dump multiple memory regions in order to find the entire deobfuscated malicious code. In the case of WSHRAT, however, most of the important code is in the memory segment we dumped earlier.

I hope you can use these techniques in the future when analyzing Javascript. Happy deobfuscation 🙂 If you enjoyed this post, follow me on Twitter (@d4rksystem)!

Malware Analysis in 5-Minutes: Deobfuscating PowerShell Scripts

Malware Analysis in 5-Minutes: Deobfuscating PowerShell Scripts

I often run into obfuscated PowerShell while analyzing malicious documents and executables. Malware authors have many reasons for obfuscating their PowerShell activities, but mostly they do it to tick me off for the lulz.

There are a few good ways (and many bad ways) to tear apart PowerShell scripts and discover what they are doing under the hood, but today we’ll be focusing on a quick and easy one – because quick and easy is always best. Right? Yes. Ok, let’s get started.

For this demonstration, I’ll be using a Windows 7 VM and PowerShell ISE, which is installed on most Windows 7 builds.

Below, we have a PowerShell script that I extracted from a Microsoft Word document.

PowerShell script.
PowerShell script.

The PowerShell script was embedded in the MS Word document and would be executed if a user opens the document and clicks the “Enable Macros” button. Most users wouldn’t have an issue with this, and would happily click this button to make this annoying security popup go away. I understand, dear user. Security is hard.

Now, there are a few ways we can approach this script:

  1. We can stare at it for 15 minutes while crying into our Scotch. I tried this, and the script was still obfuscated.
  2. We can deobfuscate it by hand, working through the math on a nice sheet of paper. Your mathematics professor would be proud.
  3. We can take this code into the PowerShell ISE built into Windows, run it, and dump the variables. I will be focusing on Option 3 for the remainder of this blog post.

As I mention previously, the goal here is to deobfuscate this PowerShell script in the easiest, quickest way possible. The most effective way to do this it to simply run the PowerShell script in the PowerShell ISE, and then dump all variables from memory. This will allow us to quickly see what the script is doing with minimal effort. As a warning, if you are doing this at home (or, God forbid, at work), this will infect your system, so ensure you are using a VM or a system you don’t care too much about.

Below, you will see that I copied and pasted the PowerShell script into the Powershell ISE in Windows 7, and also removed the “powershell.exe” and beginning parameters from the script. All we need is the script code itself. Ok, let’s run the script, and then dump variables from memory.

PowerShell ISE
PowerShell ISE.

After running, to dump variables, simply use the command Get-Variable in the console after the script has finished running.

Get-Variable command output.
Get-Variable command output.

Most of the variables that are displayed here are of little interest to us. Let’s focus on the variables that were actually referenced in the script. These variables likely contain the deobfuscated PowerShell code, and can be seen below:

Interesting variables...
Interesting variables…

Variable “hyvbx” contains a “;”. Wow. Profound. We can skip this one because obviously it’s not that important.

Variable “gazuk” seems like it contains something a lot more interesting. Let’s dump the complete contents of that variable using the command Write-Output $variable_name;.

Variable output.
Variable output.

Now, that’s better. Here we clearly have the deobfuscated PowerShell commands!

If we analyze this further, we can see that the script is looking to see if our analysis environment is running virtualization software such as Vmware, VirtualBox, or KVM. It is also checking to see what country we are located in. If the system passes these checks, the script will execute, and will attempt to download a javascript file and executable from various web servers and run them. I won’t go into additional detail on this specific malware or what it is downloading, as that is not in the scope of this post.

Deobfuscated PowerShell!
Deobfuscated PowerShell!

Congratulations on successfully deobfusctating a PowerShell script the easy way! Keep in mind that this will not always work, and you may need to create breakpoints in the Powershell ISE in order to step though the code. This technique, however, works in many cases.

If you enjoyed this post, follow me on Twitter (@d4rksystem) 🙂

Thanks for reading.

Hunting for SAP

Hunting for SAP

SAP systems, especially Internet-facing ones, are often an overlooked attack surface for many organizations. SAP systems can contain several misconfigurations such as:

  • Outdated software
  • Sensitive information set to “Public”
  • Weak and/or default login credentials
  • Other good stuff

When analyzing the attack surface of your organization, or during a penetration test, it is important to look for these SAP systems. Generally, a web-facing SAP system will run on port 80, 443, 8080, or other common web ports. Internal SAP systems may use ports 3200-3399, 3600, 8000, 8100, or 50013-59914. To find these systems, simply run an Nmap scan such as the below. (DISCLAIMER: Only run the suggested tools on systems you have permission to scan!)

Example: “nmap -sV -p 80,443,3200-3299,3600,8000,8080,8100,50013-59914 “.

Be on the lookout for services that have “SAP” or “Netweaver” in the name.

Once some potential SAP systems have been identified, boot up Metasploit and look for the “sap_icm_urlscan” module. This module is very useful for “scanning” an SAP web server for directories that potentially should not be publicly accessible.

The above outputs show several SAP directories discovered. Some of these directories look pretty juicy (admin, soap_management, etc.)!

Now, open up a browser and take a look at a few of those directories. You may find some information that should not be Internet accessible. A few examples of what should not be on the Internet:

Some of the information that can be gathered from the above pages is:

  • System monitoring and status
  • Internal network hostnames and IP addresses
  • Detailed SAP software version information
  • SAP system logs
  • Host operating system versions and information

Attackers can use this information to launch other attacks on the SAP system, or potentially use this information to exploit a flaw in a connected system.

Well, that’s it for now. Hopefully this has motivated you to look into your Internet-facing SAP infrastructure. Good luck!

 

Subdomain Attack Surface Discovery – Part 2

Subdomain Attack Surface Discovery – Part 2

Welcome to Part 2 of Subdomain Attack Surface Discovery! If you haven’t read Part 1, I would do that first… Otherwise confusion may follow. Assuming you are continuing after Part 1, let’s get back to our list of subdomains.

But first, a much-needed disclaimer.

DISCLAIMER: The tools and techniques in this post should only be run against hosts that you have permission to scan!

Ok, back to business.

In order to start taking a deeper look at the Internet attack surface to see what’s out there, we need to perform some light enumeration of the targets. My chosen tool for this is Nmap. Some have suggested the use of masscan for this instead of Nmap. I like masscan for extremely large quantities of hosts, but Nmap tends to work for me just fine for a “normal” number of hosts.

Generally, I only scan for the top 20 ports (nmap Top 20) to keep the scan quick and not to attract unwanted attention, but you can tailor this to fit your recon style.

Command: “nmap -vvv -sS –open –top-ports 20 –max-retries 2 -iL import_filename.txt -oA export_filename”

Let’s quickly dissect this nmap command. The “-vvv” puts Nmap in “very verbose” mode, meaning that there will be a lot of output and feedback. The “-sS” tells Nmap to run a more stealthy SYN scan. “–open” tells Nmap to only show open ports. “–top-ports 20” tells Nmap to only scan for the most common 20 ports – these are generally all we need for this initial reconnaissance. The “–max-retries 2” tells Nmap to stop probing a target port if a certain number of “retries” occurs. In a nutshell, this will speed up the scan. “-iL import_filename.tx” is the list of IP addresses and hostnames that you want to scan. From Part 1, this is the list of subdomains we discovered. Finally, “-oA export_filename” is the export file name. This will send the output of Nmap to 3 different file formats that can later be used.

Here is some of the information returned from the Nmap scan:

Here we see some standard web ports such as 80 and 443. These ports are hosting web services. Sometimes you will find more peculiar ports open, such as the below output:

Hosts such as this should be looked at more closely to ensure the open ports have a good reason for being open (e.g., providing services to the end-user).

Next, I run my favorite recon tool – Eyewitness. Eyewitness was written in Python and it simply takes screenshots of websites, and RDP and VNC login screens, and is a GREAT tool for quickly figuring out which hosts and subdomains look interesting and warrant further “review”. Let’s run an Eyewitness “scan”.

Since Eyewitness will navigate to all the subdomains and attempt to screenshot them, this tool can take quite a while to complete. Usually I will start an Eyewitness enumeration and go do something else for a few hours (or the day).

Command: “python EyeWitness.py –all-protocols -x nmap_file –timeout 15 -d output_file”

The Nmap input file should be the output of our Nmap scan from above. The output file name can be named anything.

Eyewitness reports output in HTML format, so you can open the result files in a web browser. After open the results in Firefox, I can see that various types of web pages were discovered. What we want to look for here are login portals, misconfigured web pages or applications, weird errors, or obvious potential issues such directory indexing and SQL errors.

Let’s take a look at our results. This is the type of stuff to look for:

Login portals, such as these:

Error Messages / Strange Output, such as these:

Misconfigured Web Pages, such as the below:

Or, Information about the backend infrastructure, such as the below:

These are only examples – Anything that looks out of the ordinary or peculiar should be inspected further. Usually this combination of tools and techniques can help you get a quick overview of the Internet attack surface of your organization, and can also be used in bughunting.

Please leave comments if anything is incorrect or if you have a better idea for the execution of these techniques!

I am currently working on a Python script that automates this tool chain and will write about it in the another post.. I know there are many tools and scripts out there that do similar recon, but I always find it safer to rely on a tool chain instead of a single tool that does it all – you never know when the developer stops supporting the “do-it-all” tool. With a tool chain, you can also include new tools and scripts (or take them out) in the chain any time you need!