Pulling Back the Curtains on EncodedCommand PowerShell Attacks

By

Category: Unit 42

Tags: ,

This post is also available in: 日本語 (Japanese)

A note to readers: The code samples included within this blog post may trigger alerts from your security software. Please note that this does not indicate an infection or an attack; rather, it is a notification that the code could be malicious if it were live.

PowerShell has continued to gain in popularity over the past few years as the framework continues to mature, so it’s no surprise we’re seeing it in more attacks. PowerShell offers attackers a wide range of capabilities natively on the system and with a quick look at the landscape of malicious PowerShell tools flooding out; you have a decent indicator of its growth.

Microsoft has done a fantastic job in later versions of PowerShell by giving multiple ways to log PowerShell activity (Transcription, ScriptBlock, etc) so there has been a shift to try and further obfuscate attacks at runtime.

Enter stage left - the PowerShell ‘-EncodedCommand’ parameter!

As shown above from the PowerShell Help output, it’s a command intended to take complex strings that may otherwise cause issues for the command-line and wrap them up for PowerShell to execute. By masking the “malicious” part of your command from prying eyes you can avoid strings that may tip-off the defense.

The purpose of this blog will be two-fold. First, in the “Analysis Overview”, I will be analyzing 4,100 recent samples identified within Palo Alto Networks AutoFocus that employ this EncodedCommand technique to see how PowerShell is being used and what techniques are being used in the wild for PowerShell attacks. Second, I will be using this blog to catalog the PowerShell code with examples of each decoded sample to aide in future identification or research.

Analysis Overview

To perform this analysis, I needed to first identify samples that were using this technique. Because PowerShell gives you a lot of flexibility when it comes to calling different parameters, identifying samples isn’t as straightforward as one might expect.

Below are three examples of different ways the EncodedCommand parameter can be called:

  1. Fully spelled out:
    powershell.exe –EncodedCommand ZQBjAGgAbwAgACIARABvAHIAbwB0AGgAeQAiAA==
  2. Truncated with alternate capitalization:
    powershell.exe –eNco ZQBjAGgAbwAgACIAVwBpAHoAYQByAGQAIgA=
  3. Using caret escape-character injection to break-up the string:
    powershell.exe –^e^C^ ZQBjAGgAbwAgACIAVwBpAHQAYwBoACIA

There are well over 100,000 variations possible by using combinations of these methods for the “EncodedCommand” parameter alone. Keeping that in mind, I came up with the below regex that gave decent coverage to the possible variants and could easily be applied to a huge corpus of dynamic analysis reports.

This allows for extraction of lines like the below at scale for further analysis.

Now, it’s no surprise but the majority of the encoded data is clearly generated from templates and public tools - attackers aren’t re-inventing the wheel every time they need to run shellcode or download another malicious file.  This is evidenced by the fact that the underlying code is almost identical with just slight adjustments to download locations and the like. To try and perform analysis on the data then, I needed to try and identify the code and attempt to determine what generated the code, or at minimum, attempt to cluster the code into like-buckets.

Profiling Approach

To illustrate some of the difficulties involved with this, back in 2012 Matthew Graeber published a blog post about a PowerShell script he put together that could load shellcode into memory and execute it. This script has been the cornerstone template for this technique, being used in most public tools that seek to use this functionality.

Following are two iterations of the technique from TrustedSec tools Social-Engineer Toolkit (SET) and Magic Unicorn. If you compare the two samples, you’ll see that SET uses “$c” whereas Magic Unicorn uses “$nLR” for the initial variable. Similarly, the “$size” variable in SET is “$g” in Magic Unicorn, the “$sc” variable is “$z”, and finally the “$x” variable is “$kuss”.

SET

Magic Unicorn

In Magic Unicorn, there is a line within the generating script that randomizes some variables. Below is an excerpt showing how this works.

This simply replaces some variables with a string of 3-4 random alphanumeric characters; however, not all variables get replaced so the combination of the random string with known anchors allows me to theorize how it was generated. Alternatively, I can also see when it looks like this particular piece of code was copied into another tool without the randomization part of the Magic Unicorn script as the variables don’t change or was further built upon by adding additional randomization.

It’s not an exact science and, when dealing with code that has been heavily re-used over many years by many different people, you’re bound to run into scenarios where the code just doesn’t lend itself well to profiling. I’ve attempted to classify it as accurately as possible but a word of caution - take the specific names with a grain of salt throughout this analysis as nothing is stopping someone simply copying and pasting the code into their own tool.

In total, I profiled 27 clusters of public tools or capabilities, which had unique identifiers to separate them apart from the rest. I’ll get into each of them later as I catalog each variant but, for now, the below table offers a breakdown of the variants, how many samples matched, and the overall percentage it accounted for in the sample set.

 

Variant Count % of Total
Downloader DFSP 1,373 33.49%
Shellcode Inject 1,147 27.98%
Unicorn 611 14.90%
PowerShell Empire 293 7.15%
SET 199 4.85%
Unknown 104 2.54%
Powerfun Reverse 100 2.44%
Downloader DFSP 2X 81 1.98%
Downloader DFSP DPL 24 0.59%
Downloader IEXDS 19 0.46%
PowerWorm 19 0.46%
Unicorn Modified 14 0.34%
Scheduled Task COM 11 0.27%
BITSTransfer 11 0.27%
VB Task 10 0.24%
TXT C2 10 0.24%
Downloader Proxy 9 0.22%
AMSI Bypass 8 0.20%
Veil Stream 7 0.17%
Meterpreter RHTTP 6 0.15%
DynAmite Launcher 6 0.15%
Downloader Kraken 5 0.12%
AppLocker Bypass 4 0.10%
PowerSploit GTS 3 0.07%
Powerfun Bind 2 0.05%
Remove AV 2 0.05%
DynAmite KL 1 0.02%

 

Over half of the samples analyzed utilized either a generic “DownloadFile-StartProcess” technique or a variant of the shellcode injection technique shown previously.

General Distribution / Stats

Across the 4,100 samples, there were 4 file formats seen.

File Format Count % of Total
"exe" 2,154 52.54%
"doc" 1,717 41.88%
"xls" 228 5.56%
"dll" 1 0.02%

 

EXE and DOC format account for the majority of extensions used across this sample set. Looking further at the DOC files, 77% of them, 1,326, matched the “Downloader DFSP” variant, which defines a generic downloader using the DownloadFile-StartProcess method as shown below.

Pivoting from there, 1,159 of the DOC files (87%) match known patterns for Cerber ransomware; the implication is that a tool is being used to generate the malicious Microsoft Word Documents that create the macro which launches PowerShell with this technique as the template.

The primary method of delivery across the DOC samples is SMTP/POP3, which aligns with the status quo of delivering ransomware by using malicious Microsoft Word Documents via e-mail campaigns.

fig1

Figure 1 Applications used to deliver malicious Powershell Word Documents

Looking at the target industries also shows a fairly even distribution throughout Higher Education, High Tech, Professional and Legal Services, and Healthcare.

fig2

Figure 2 Breakdown of Industries detecting malicious Powershell Word Documents

A quick look at the distribution over time also shows a number of large spikes that, again, aligns with the standard operating procedure of e-mail campaigns.

fig3

Figure 3 Number of malicious Powershell Word Documents captured in AutoFocus over the last 12 months

Looking at how the EXE samples were classified, nothing stands out as being dominant in terms of a group or malware family; however, interestingly enough there seems to be a preference for targeting companies in the High Tech industry.

fig4

Figure 4 Breakdown of Industries detecting malicious Executables using Powershell

The distribution over time is also fairly even in comparison to the DOC sample distribution over time.

fig5

Figure 5 Number of malicious Executables using Powershell captured in AutoFocus over the last 12 months

One possible explanation for this is a variation is distribution. For example, while DOC samples were primarily seen as attachments to e-mail, EXE samples were usually delivered through Web Browsing.

The last item I’ll touch on before diving into the commands themselves is the one DLL file that was detected using the EncodedCommand technique. This DLL contains no exports but when called with the DLLMain entry point will simply launch a PowerShell Empire stager which downloads an XOR’d script from a website and then uses PowerShell’s Invoke-Expression cmdlet to run the downloaded script. This sample was related to the Odinaff family that Symantec blogged about in October 2016.

Pre-Analysis Data / Stats

Before looking at the base64 encoded data, I looked at how each process was launched. This frequency analysis and inspection gives some insight into what additional parameters are being used alongside EncodedCommand.

EncodedCommand: (4,100 Samples – 100% Coverage)

Used to pass a base64 encoded string to PowerShell for execution.

Flag Count % of Total
"-enc" 3,407 83.29%
"-Enc" 412 10.05%
"-EncodedCommand" 229 5.59%
"-encodedcommand" 40 0.98%
"-encodedCommand" 7 0.17%
"-ec" 3 0.07%
"-en" 1 0.02%
"-ENC" 1 0.02%

 

WindowStyle Hidden: (2,083 Samples – 50.8% Coverage)

Used to prevent PowerShell from displaying a window when it executes code. The most used variant “-window hidden” is due to the PowerShell command that the previously mentioned Microsoft Word Documents distributing Cerber are using.

Flag Count % of Total
"-window hidden" 1,267 30.90%
"-W Hidden" 315 7.68%
"-w hidden" 159 3.88%
"-windowstyle hidden" 125 3.05%
"-win hidden" 67 1.63%
"-WindowStyle Hidden" 45 1.10%
"-win Hidden" 42 1.02%
"-wind hidden" 40 0.98%
"-WindowStyle hidden" 5 0.12%
"-WindowStyle hiddeN" 5 0.12%
"-windows hidden" 4 0.10%
"-Win Hidden" 3 0.07%
"-win hid" 2 0.05%
"-Window hidden" 2 0.05%
"-Wind Hidden" 1 0.02%
"-Win hidden" 1 0.02%

 

NonInteractive: (1,405 Samples – 42.4% Coverage)

Used to prevent creating an interactive prompt for the user. Used in combination with WindowStyle Hidden to hide signs of execution. For the “-noni” variation, 76% were the generic shellcode injection code and SET, whereas “-NonI” was PowerShell Empire.

Flag Count % of Total
"-noni" 1,042 25.41%
"-NonI" 331 8.07%
"-noninteractive" 27 0.66%
"-NonInteractive" 4 0.10%
"-nonI" 1 0.02%

 

NoProfile: (1,350 Samples – 32.9% Coverage)

Prevents PowerShell from loading profile scripts, which get executed on launch, so as to avoid potentially unwanted commands or settings. Similar to the breakdown for NonInteractive, “-nop” is primarily SET and the generic shellcode injection while “-NoP” is PowerShell Empire.

Flag Count % of Total
"-nop" 955 23.29%
"-NoP" 332 8.10%
"-noprofile" 57 1.39%
"-NoProfile" 5 0.12%
"-noP" 1 0.02%

 

ExecutionPolicy ByPass: (453 Samples – 11% Coverage)

Bypasses the default PowerShell script execution policy (Restricted) and will not block the execution of any scripts or create any prompts. It’s interesting to note that the code executed within EncodedCommand parameter does not apply to the execution policy.

Flag Count % of Total
"-ep bypass" 128 3.12%
"-exec bypass" 80 1.95%
"-executionpolicy bypass" 78 1.90%
"-Exec Bypass" 73 1.78%
"-ExecutionPolicy ByPass" 42 1.02%
"-ExecutionPolicy bypass" 26 0.63%
"-Exec ByPass" 9 0.22%
"-ExecutionPolicy Bypass" 5 0.12%
"-ExecuTionPolicy ByPasS" 4 0.10%
"-exe byPass" 2 0.05%
"-ep Bypass" 2 0.05%
"-ExecutionPolicy BypasS" 2 0.05%
"-Exe ByPass" 2 0.05%

 

Sta: (219 Samples - 5.3% Coverage)

Uses single-threaded apartment (now default as of PowerShell 3.0). This parameter was almost exclusively used in PowerShell Empire.

Flag Count % of Total
"-sta"  219  5.34%

 

NoExit: (23 Samples - 0.5% Coverage)

Prevents PowerShell from exiting after running the startup commands. This was exclusively used by the PowerWorm malware and was the only parameter used beside EncodedCommand.

Flag Count % of Total
"-noexit"  23  0.56%

 

ExecutionPolicy Hidden (5 Samples - 0.12% Coverage)

This actually isn’t a valid policy so PowerShell just ignores it. Every usage of it is related to a script I labeled “TXT C2”, which attempts to load a DNS TXT Record containing another PowerShell script, similar to PowerWorm. Most likely, the attacker meant to use ByPass here as they already have “-w hidden” later in their command.

Flag Count % of Total
"-ep hidden"  5  0.12%

 

NoLogo: (33 Samples - 0.8% Coverage)

Hides the copyright banner when PowerShell launches.

Flag Count % of Total
"-Nol" 10 0.24%
"-NoL" 10 0.24%
"-nologo" 9 0.22%
"-nol" 4 0.10%

 

ExecutionPolicy Unrestricted (1 Samples – 0.02% Coverage)

Similar to ByPass, but will warn the user before running unsigned scripts downloaded from the Internet. The underlying lone script that used this parameter tries to execute a script downloaded from the Internet, which should generate a warning.

Flag Count % of Total
"-ExecutionPolicy Unrestricted"  1  0.02%

 

Command (1 Samples – 0.02% Coverage)

Executes a command that follows the parameter as if they were typed at the PowerShell prompt. I only saw one instance of this and it was tied directly to a piece of malware that FireEye included in a blog about evading signature-based detections. The PowerShell code is included in the “Comments” field of a DOCM file and launched from a macro inside a Microsoft Word document. Below is the code in question that chains together multiple commands to perform an FTP transfer and subsequent NetCat connection.

Flag Count % of Total
"-c"  1  0.02%

 

Finally, I’ll end the parameter analysis by looking briefly at the top 10 combinations seen throughout this sample set.

Flag Combination Count % of Total
"-window hidden -enc" 1,242 30.29%
"-enc" 986 24.04%
"-nop -noni -enc" 736 17.95%
"-NoP -sta -NonI -W Hidden -Enc" 206 5.02%
"-EncodedCommand" 169 4.12%
"-ep bypass -noni -w hidden -enc" 102 2.48%
"-NoP -NonI -W Hidden -Enc" 60 1.46%
"-nop  -win hidden -noni -enc" 57 1.39%
"-executionpolicy bypass -windowstyle hidden -enc" 51 1.24%
"-nop -exec bypass -win Hidden -noni -enc" 41 1.00%

 

Even accounting for changes in case, the results only increase by a handful of samples in each category.

While doing the research to try and identify unique signatures for identification, I found multiple examples of the below, wherein the code author changes the parameters for a newer version of their tool.

fig6

Figure 6 Code Author Modified parameters between versions of a tool

This reduces the overall aggregate count for those families but I don’t believe it has much impact on the totals. In my review of the tools, authors are less focused on the dynamic ordering of the parameters or potentially dynamically adjusting parameter length to further obscure their attacks; instead they add in basic capitalization randomization and focus on the “meat” of their code. This can allow for some low-fidelity profiling based on just the way the PowerShell command is launched.

In addition, the top three combinations, which account for 72% of all combinations, are predominately straightforward and focused on just running code versus any clever attempts at further hiding their attacks from the user.

Post-Analysis Data / Stats

Next I’ll go over each of the identified variants and review their functionality. For each one that downloads a file or script, I’ll include the observed IP/Domain/URL at the end of this blog. Some of these may be malicious, some of them may be pentesters, and some of them may be people doing random testing of new techniques; unfortunately, it’s not usually possible to infer intention when doing bulk analysis but the data is provided for the reader to use as they see fit.

Downloaders

PowerShell code identified with the primary intention of downloading and running a secondary payload or executing PowerShell code obtained remotely.

Downloader DFSP (1,373 Samples - 33.49% Coverage)

This is a quintessential example of using PowerShell to download and run a file. It’s basically verbatim of the results you get when using Google to search for ways to download and run a file. As such, I’ve used the below template as a generic classification for the base64 encoded data that acts as a simple downloader for the true payload.

As was previously pointed out, almost all of the detections matching this category were linked back to the Microsoft Word documents launching this PowerShell command via a macro to download Cerber. One unique pattern observed in this sample was the usage of environment variables, in addition to their URI pattern.

Downloader for Cerber –

PowerShell Empire (293 Samples – 7.15% Coverage)

For this next one, the samples are using PowerShell Empire’s EncryptedScriptDropper to download a script remotely and decrypt it with an embedded XOR key.

In this example, the XOR key is “0192023a7bbd73250516f069df18b500” and the pulled down script, once decoded with that key, is the PowerShell Empire agent stager script that will POST system information to the C2 server and then download the encrypted Stage 1 Empire payload.

Downloader DFSP 2X (81 Samples - 1.98% Coverage)

This is the same as the previous downloader but it launches yet another instance of PowerShell to carry out the download. These were all linked to the Cerber downloader documents as well.

Downloader DFSP DPL (24 Samples - 0.59% Coverage)

Another downloader using the DownloadFile -> Start-Process technique that had two different variations within the sample set. A number of these samples matched behaviors related to Bartalex and may be indicative of changes to this well-known Office Macro generator.

Unabridged –

Abridged –

Downloader IEXDS (19 Samples – 0.46% Coverage)

This is another spin on a downloader that frequently pops-up when searching for methods to download and execute scripts for PowerShell. Effectively, the code simply downloads a PowerShell script remotely and executes it with Invoke-Expression. The resulting payloads can be quite different from one another and didn’t seem related.

The following two samples download an “Invoke-TwitterBot” script, which is “A Trojan bot controlled by a twitter account that was released at ShmooCon IX”.

BITSTransfer (11 Samples – 0.27% Coverage)

Another mechanism for downloading malware via PowerShell is through the BitsTransfer module. Background Intelligent Transfer Service (BITS) isn’t as frequently seen in downloading malware but offers similar functionality to other known transfer services, such as HTTP. Using this different method may allow attackers to avoid certain monitoring and take advantage of the fact that BITS will throttle transfers to not impact other bandwidth usage.

In my previous blog, I noted that a variant of the Cerber downloader was seen using BITS for a brief period of time and 10 out of these 11 samples were Microsoft Word documents leading to Cerber.

TXT C2 (10 Samples – 0.24% Coverage)

For this next one, the attacker uses PowerShell to make a DNS query for the TXT record of a domain. The TXT record contains another PowerShell script that is then passed to Invoke-Expression to execute.

Looking at the script which is returned shows that once this initial look-up occurs, it will set itself into a constant loop continuing to query for the TXT record of the domain and base64 decoding then executing the result.

This allows the attacker to establish a command and control channel when they are ready to interact with the compromised system.

John Lambert over at Microsoft recently tweeted about this variant and identified it as being used during penetration testing. Another example of the technique can be found in the Nishang framework for penetration testing.

Downloader Proxy (9 Samples – 0.22% Coverage)

This variant will explicitly use the configured proxy and credentials for the user running the PowerShell command. Of note for this one is the passing of the username as a value to the “u” parameter in the web request. This is a common “check-in” activity so the attacker knows whom they have infected; it can be used to further handle how subsequent interactions take place (e.g. block further connections if known sandbox username).

Meterpreter RHTTP (6 Samples – 0.15% Coverage)

This next technique simply pulls down the Invoke-Shellcode script used in tools such as PowerShell Empire and PowerSploit, and then calls the function to generate a reverse HTTPS Meterpreter shell.

All but one of the samples pulled code from GitHub, either directly through the official repository or through a forked version.

GitHub –

Non-GitHub –

Downloader Kraken (5 Samples – 0.12% Coverage)

I called this one “Kraken” simply because of the filename of the executable it downloads, (“Kraken.jpg”), but it uses a similar download technique as seen in Downloader DFSP. One difference is that instead of using the “$env” variable directly, it uses System.IO.Path to retrieve the path for the $TEMP directory.

AppLocker Bypass (4 Samples – 0.12% Coverage)

This next technique uses PowerShell to run the regsvr32 tool to bypass Microsoft Windows AppLocker. This technique was found by Casey Smith (@subTee) and abuses the fact that scripts are executed when unregistering a COM object via regsvr32.

Embedded Payloads

PowerShell code identified with the primary intention of launching embedded payloads, such as shellcode.

Shellcode Inject (1,147 Samples – 27.98% Coverage),

Unicorn (611 Samples – 14.90% Coverage),

SET (199 Samples – 4.85% Coverage),

Unicorn Modified (14 Samples – 0.34% Coverage)

As I already showed examples of SET and Magic Unicorn’s implementation of the Shellcode Injection technique, I’ve decided to just lump all of the variants together using this shellcode injection template. Below is a sample from the “Shellcode Inject” variant, which is a copy of Matt Graeber’s original post, and you’ll immediately see the similarities with the SET and Magic Unicorn code.

While the Cerber downloader accounted for a large sum of the EncodedCommand found in Microsoft Word documents, these four variants use the same technique accounting for almost the entirety launched from EXE files.

The gist of the code is that they import functions from DLL’s in the following order:

  • “kernel32.dll” VirtualAlloc
  • “kernel32.dll” CreateThread
  • “msvcrt.dll” memset

Then they load their shellcode into an array of bytes using the “0x” hex representation. Next, they call VirtualAlloc to allocate, at minimum, a 4,096 byte page of RWX memory, copy the byte-array to memory with memset, and finally transfer execution to the shellcode with CreateThread.

Out of the 1,971 samples, there were 1,211 unique shellcode payloads, indicating that over 50% of them were re-used in other attacks. Most of these tools utilize Metasploit to generate the shellcode and if they don’t accept specifying a payload, generally opted for reverse Meterpreter shells. For example, the below line is from the Magic Unicorn’s code showing how to specify the MSF payload.

The underlying code for the generation of the payload, including platform, architecture, and encoding:

Another interesting observation is that if you look at the shellcode length, the top 2 lengths were 294 and 312 bytes long, with 846 and 544 samples respectively; afterwards the sample counts fall off sharply.

Shellcode Length (Bytes) Count
294 846
312 544
337 145
303 131
285 46

 

What makes this interesting is the sheer volume of identical lengths signals to me that they are likely generating the same payload with the same tools and using something without much possible variation in length, such as a 4-byte IP compared to a variable length URL as the C2.

As this blog serves to catalog the differences between these variants, below are regex queries to identify the specific variant.

Shellcode Inject

Unicorn

SET

Unicorn Modified

Powerfun Reverse (100 Samples – 2.44% Coverage),

Powerfun Bind (2 Samples – 0.05% Coverage)

Another variation to code execution was found inside Powerfun, more specifically they use Metasploit’s “windows/powershell_reverse_tcp” and “powershell_bind_tcp” payloads to create interactive shells with the target system. The reverse payload is encoded with base64 and launched via a background process using System.Diagnostics.Process.

Reverse payload –

The bind payload sets up a TCP listener by listening with System.Net.Sockets.TCPClient and passing received PowerShell script to Invoke-Expression.

Bind payload –

PowerWorm (19 Samples – 0.46% Coverage)

PowerWorm is a malware family that TrendMicro blogged about in 2014 which has the capability of spreading by infecting other Microsoft Office DOC(X)/XLS(X) files. The PowerShell code is obfuscated with “junk” data placed between the legitimate commands.

Cleaned-up slightly –

The code will download Tor and Polipo by fetching download URL’s for the software from DNS TXT records and then eventually use the software to continuously check for new PowerShell commands that get passed to Invoke-Expression. Matt Graeber has done an excellent job of analyzing the full capabilities of this malware and provides de-obfuscated, commented, versions of the underlying PowerShell.

Veil Stream (7 Samples – 0.17% Coverage)

This is a similar technique as described in the “Powerfun Reverse” variant. The PowerShell code is injected into memory from a base64 string and executed with Invoke-Expression that eventually launches the actual shellcode payload. The layout of the code correlates to the Veil Framework implementation.

Persistence

PowerShell code identified with the primary intention of establishing persistence on the host.

Scheduled Task COM (11 Samples – 0.27% Coverage)

This variant seeks to create a persistence mechanism by creating a Scheduled Task that runs the malicious binary. The PE file this sample comes from drops a “minecraft.exe” and then launches this PowerShell command below - most likely, as it’s easier to pass this type of functionality off to PowerShell instead of trying to write the code into the original dropper.

The technique was seen primarily is samples associated to the Retefe banking trojan.

VB Task (10 Samples – 0.24% Coverage)

This grouping of PowerShell code originally comes from a PE that executes PowerShell with the EncodedCommand, which then creates a VBScript that is installed as a Scheduled Task. The VBSript simply launches another PowerShell script once it runs to achieve this.

DynAmite Launcher (6 Samples – 0.15% Coverage),

DynAmite KL (1 Sample – 0.02% Coverage)

DynAmite is a “Malware Creation Toolkit” which comes with your standard capabilities that one comes to expect with such a tool.

dynamitekl

It does give you the ability to mix and match the features you want and generates a PE wrapper that carries out the selected tasks, usually by simply executing PowerShell commands. The majority of code that I saw generated by this kit was taken from public tools but used swapped around variable names and locations.

The “DynAmite Launcher” variant covers the persistence aspect, which is established through creating Scheduled Tasks. Below are three different iterations of this, most likely from different versions and configurations.

For the “DynAmite KL” variant, it’s the keylogger portion of the kit but directly lifts code from an older version of the PowerSploit function Get-Keystrokes. Below are the meat of the script and a comparison of the two pieces, showing how DynAmite changes the location of the variables and types.

Get-Keystrokes –

Function DynAKey –

Other Techniques

AMSI Bypass (8 Samples – 0.20% Coverage)

Antimalware Scan Interface (AMSI) is a new feature Microsoft released in Windows 10 and is designed to facilitate communication between applications and AV products. Ideally, the application (PowerShell in this context) will take the script at runtime, after it’s deobfuscated or pulled in remotely from a website, and pass it through AMSI to your AV for scanning. If the AV software determines it’s malicious, it can now block the scripts execution.

#YAOMG (Yet Another of Matt Graebers)

Matt Graeber released a one-line tweet  that shows how you can bypass AMSI by simply changing “amsiInitFailed” to “True”, which makes it appear as if it failed to load and effectively skips this check.

The code shares a similar signature to PowerShell Empire’s XOR routine for their EncryptedScriptDropper and may be related or borrowed code.

PowerSploit GTS (3 Samples – 0.07% Coverage)

This is set of samples that simply use a module from another tool, in this case, the PowerSploit Get-TimedScreenshot. The code will take a screenshot using Drawing.Bitmap every 2 seconds.

For these types of attacks, the PowerShell code is just an augmentation to the overarching suite of tools being used in the attack, likely intended to save the attacker time in developing the desired functionality. In this case, Microsoft Excel documents contained macros that first launch a function to decode the PowerShell code and begin taking screenshots while a second function is called afterwards to decode a PE file that handles the rest of the attack.

fig7

Figure 7 Excel Macro decodes embedded Powershell script and PE file.

Remove AV (2 Samples – 0.05% Coverage)

This next variant uses PowerShell to forcefully uninstall both x86 and x64 versions of an installed AV application. It iterates over entries in the Uninstall registry path to find items with “*AVG*” and then quietly uninstalls each instance.

Notable One-Offs

After identifying as many variants as possible, I was left with around 100 “Unknown” samples, which were usually custom spins on the techniques described above. I’ll end this cataloging with a quick overview of some of the more notable samples.

Hidden Messages

This sample does some basic date checking through PowerShell and compares current datetime to an included datetime, if the current datetime is past the included one, it will not run. At the end of the code though, they leave a commented call-out to, possibly, their “hacking” group.

Another example of leaving hidden messages is in the sample below.

When you analyze the code it pulls down remotely from GitHub, which at the time of this writing kills PowerShell processes, it says “Hello SOC/IR team!  :-)”. It’s possible this is just a pentest or red-team exercise given the history of the file using “Test” a lot.

fig8

Figure 8 JavaScript file kills powershell and greets SOC/IR team.

Process Killing

This is another example of using PowerShell for specific purposes in an overarching attack. It will kill a number of processes typically associated with malware analysis.

Layers of Obfuscation

For this last example, it appears to be related to the samples shown in the “PowerSploit GTS” variants, as the originating macros are almost identical, but this sample did not use any of the other pieces.

This particular sample uses multiple layers of obfuscation to carry out its attack.

Layer 1 –

A Microsoft Excel document has a macro that pulls a base64 encoded data from a cell that is passes to PowerShell’s EncodedCommand parameter when it launches.

layer1

Layer 2 –

The decoded base64 is a long array of int values that get converted to their char value, and then executed as another PowerShell script.

Layer 3 –

The decoded data uses various techniques to obfuscate itself. The first technique is injecting backtick characters between other characters, which will be ignored at runtime. This is similar to the caret injection technique from the command-line, but works within the PowerShell code instead.

It also uses a technique commonly seen in other scripting languages by breaking up a string into a randomized list and then rebuilding the original string by calling specific values.

Cleaning up the code and building the strings shows that it downloads code remotely to pass to Invoke-Expression.

Conclusion

PowerShell is a robust scripting framework that offers a lot of capabilities, both for defense and offense. Hopefully this blog has served to highlight some of the current techniques being used in tools and attacks.

Across these samples, it seems clear that the majority of attacks are still relying on public tools, which isn’t surprising. As the PowerShell framework continues to be explored and matured, I suspect we will begin to see a lot more variation in attacks coming from this space. As it stands today, PowerShell seems to be mainly used as a tool to facilitate common functions attackers are used to within other frameworks, but will eventually start to take advantage of more native features once we move out of the “transference” phase to an “innovative” phase.

Observed C2 or Download Sites

Downloader DFSP

PowerShell Empire

Downloader DFSP 2X

Downloader DFSP DPL

Downloader IEXDS

BITSTransfer

TXT C2

Downloader Proxy

Downloader Kraken

PowerWorm

AMSI Bypass

Meterpreter RHTTP

Layers of Obfuscation

SHA1 Hashtag

Additional hashes to samples can be found here.