Tag: malware

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).

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.