Investigating PowerShell Attacks

Matt Hastings, Ryan Kazanciyan (Technical Director · Mandiant)

BruCON 0x06 · Day 1

Overview

This article delves into the intricacies of forensically investigating attacks that leverage PowerShell, Microsoft's powerful command-line shell and scripting language. Presented by Ryan Kazanciyan, a Technical Director at Mandiant, and Matt Hastings, this BruCON talk underscores PowerShell's pivotal role in post-exploitation scenarios, from lateral movement and data exfiltration to maintaining persistence within compromised environments. The speakers highlight the growing trend of both targeted attackers and mass malware campaigns adopting PowerShell due to its versatility and ability to operate "off the land," often without writing artifacts to disk.

Watch on YouTube

Visual summary for Investigating PowerShell Attacks by Matt Hastings, Ryan Kazanciyan
Visual summary for Investigating PowerShell Attacks by Matt Hastings, Ryan Kazanciyan

Key moments

  1. 0:00 Introduction to PowerShell attack analysis
  2. 2:10 PowerShell's power and use by attackers
  3. 9:10 Recovering commands from WinRM service memory
  4. 26:00 Achieving detailed command history with module logging
  5. 34:50 Challenges in finding WMI persistence on disk
  6. 43:00 Using Sysmon to capture full command lines
  7. 45:00 Key recommendations for better PowerShell auditing

Investigating PowerShell Attacks

Speakers: Matt Hastings; Ryan Kazanciyan (Technical Director, Mandiant)

Conference: BruCON

YouTube: https://www.youtube.com/watch?v=J7mFCUp3FWA

Overview

This article delves into the intricacies of forensically investigating attacks that leverage PowerShell, Microsoft's powerful command-line shell and scripting language. Presented by Ryan Kazanciyan, a Technical Director at Mandiant, and Matt Hastings, this BruCON talk underscores PowerShell's pivotal role in post-exploitation scenarios, from lateral movement and data exfiltration to maintaining persistence within compromised environments. The speakers highlight the growing trend of both targeted attackers and mass malware campaigns adopting PowerShell due to its versatility and ability to operate "off the land," often without writing artifacts to disk.

The motivation for this research stemmed from real-world incident response engagements, including a notable case where a Fortune 100 organization remained compromised for over three years. During this extensive breach, attackers heavily relied on PowerShell remoting and scripts, logging in via an insecure VPN mechanism and conducting command and control (C2) operations. This posed significant forensic challenges, particularly in large environments with tens of thousands of systems, prompting Mandiant to investigate the specific artifacts left behind by various PowerShell attack techniques. The talk serves as a critical guide for defenders and forensic investigators grappling with the stealth and power of PowerShell-based threats.

The core objective of the Mandiant team's research was to systematically catalog the forensic evidence generated by different PowerShell interaction methods. They focused on three primary scenarios: local script execution, PowerShell remoting using the WinRM protocol, and persistent PowerShell installations. For each scenario, they examined potential evidence sources across the registry, disk, event logs, memory, and network, providing a comprehensive framework for incident responders. The findings presented are highly relevant for any organization seeking to enhance its detection and response capabilities against sophisticated adversaries who increasingly weaponize native operating system tools.

Background

▶ Watch: Introduction to PowerShell attack analysis (0:00)

PowerShell, far from being a mere command shell, is an incredibly potent scripting language that offers deep integration with the .NET Framework and the Windows API. This extensive capability, including the ability to reflectively load DLLs and interact with virtually any component of the Windows operating system, makes it an attractive tool for both legitimate system administrators and malicious actors. Its flexibility allows attackers to perform a wide array of post-exploitation activities, circumventing traditional security controls that might target executable files.

The speakers noted a significant shift in the threat landscape, with PowerShell becoming a cornerstone of advanced persistent threat (APT) operations. Tools like PowerSploit, a widely known open-source collection of PowerShell modules for offensive security, exemplify this trend. PowerSploit offers functionalities spanning reconnaissance, code injection, DLL injection, and even includes a Mimikatz module that reflectively loads the credential dumping tool into memory on a remote system without ever touching disk. Beyond targeted attacks, mass malware campaigns have also embraced PowerShell; examples include a 2006 proof-of-concept PowerShell worm, and more recent ransomware and file infectors observed by Trend Labs that utilized PowerShell for propagation and malicious operations.

Mandiant's research assumed a post-exploitation context, meaning the attacker already possesses administrator access (local or domain) to the victim environment. This assumption is crucial because, at this stage, attackers are less concerned with initial compromise and more focused on lateral movement, data exfiltration, and persistence. The talk also dismissed common PowerShell execution controls, such as script signing requirements or default WinRM disablement, as trivial to bypass for an attacker with administrative privileges. The research primarily focused on PowerShell version 2.0, as it was the lowest common denominator and the most prevalent version in corporate environments (default on Windows 7 SP1 and Windows Server 2008 R2). Subsequent versions like PowerShell 3.0 and 4.0, while offering enhanced logging, required optional updates and were less commonly deployed in the enterprise at the time of the talk.

Key Findings

▶ Watch: Recovering commands from WinRM service memory (9:10)

The Mandiant team's investigation yielded critical insights into the forensic artifacts left by PowerShell attacks across various evidence sources:

Memory Analysis:

While challenging due to the ephemeral nature of some PowerShell processes, memory forensics proved viable. The primary finding was that fragments of PowerShell commands and responses, even those executed remotely, could persist for hours in the memory of the svchost.exe process hosting the WinRM service. Although the wsmprovhost.exe process (where PowerShell code often executes directly during remoting) has a short lifespan, the WinRM service's svchost.exe held remnants of the SOAP (Simple Object Access Protocol) messages used for encapsulation. Notably, base64-encoded commands were found in their decoded, cleartext form within memory, providing valuable context to investigators. Kernel memory and page files were less reliable sources due offering unpredictable data retention.

Event Logs:

Event logs emerged as a critical source, with PowerShell 3.0 and above offering significantly improved auditing capabilities.

  • PowerShell Operational Log (EIDs 400, 403): These events mark the start and stop of PowerShell engine states, providing bookends for activity and indicating whether the session was local (ConsoleHost) or remote (ServerRemoteHost).
  • PowerShell 3.0+ Operational Log (EID 4100): Captures verbose error messages, including failed script executions or connection attempts to remote systems, potentially revealing attacker targets.
  • WinRM Operational Log (EID 169, 84, 134): Records user accounts and authentication types for remote sessions, offering an alternative to rolled security logs for identifying compromised credentials.
  • Analytic/Debug Logs (EID 7930, 7937): While disabled by default and extremely noisy, these logs can capture specific commandlets or script launches. However, they lack command arguments and require manual decoding of hex-encoded data for remote sessions, making them impractical for routine use.
  • Module Logging (PowerShell 3.0+, EID 4103): This was identified as the most significant improvement. When enabled, it logs every command issued to PowerShell, including full syntax, piped commands, and crucially, the output of those commands. This means sensitive data like cleartext passwords from Mimikatz could be found directly in the event logs, albeit generating a high volume of events (e.g., over 1200 events for a single Invoke-Mimikatz execution).

Persistence Mechanisms:

WMI (Windows Management Instrumentation) was highlighted as a powerful and stealthy mechanism for PowerShell persistence, particularly due to its inclusion in frameworks like PowerSploit. Attackers can create WMI event filters (queries that trigger on specific system events, like uptime or time of day), consumers (actions to perform, such as launching powershell.exe), and bindings to link them. Malicious code can be stored in PowerShell profiles or directly embedded as command-line arguments within the consumer definition (up to approximately 800 characters), making it difficult to detect on disk.

  • Disk Forensics: WMI objects are stored in undocumented files (objects.data, index.btr) within system32\wbem\repository, making offline analysis challenging. However, strings searches on objects.data can sometimes reveal WQL queries and command-line arguments in clear Unicode.
  • Registry: Limited evidence, but the presence of the Win32ClockProvider registry key can be a strong indicator of a time-based WMI filter, often used by PowerSploit.

Other Defensive Aids:

  • PowerShell Profiles: Can be legitimately used to enable transcript logging (recording command history to a file) or custom functions that capture input/output. However, they can be bypassed with the -NoProfile flag.
  • AppLocker: In audit mode, AppLocker can log script execution, including the user and script path, offering valuable visibility.
  • Sysmon: A highly recommended tool that logs process creation with full command-line arguments (including PowerShell scripts), file creation time changes, and network connections, filling crucial visibility gaps.
  • Execution Policy: While not a security boundary, monitoring for anomalous changes to the PowerShell execution policy can indicate attacker activity.
  • Network Traffic: WinRM operates over ports 5985 (HTTP) and 5986 (HTTPS). While command content is encrypted even over HTTP, HTTP headers can reveal PowerShell versions, which can be baselined for anomalous activity.

Technical Deep Dive

▶ Watch: Achieving detailed command history with module logging (26:00)

The Mandiant research provided granular detail on the technical artifacts left by PowerShell attacks, offering investigators specific targets for forensic analysis.

Memory Analysis

The speakers meticulously dissected the process hierarchy involved in PowerShell remoting via WinRM. When a client uses Invoke-Command to execute a binary (e.g., evil.exe) on a remote system, the following sequence occurs:

  1. svchost.exe (running the DCOM Launch service, which starts at boot) spawns a child process.
  2. An instance of wsmprovhost.exe (Web Services Management Provider Host) is created.
  3. wsmprovhost.exe then spawns the target binary (e.g., evil.exe) as its child.

However, a critical distinction arises when Invoke-Command is used to execute native commandlets or local scripts that run commandlets. In this scenario, wsmprovhost.exe is spawned, and the PowerShell code executes directly within the context of that process, without spawning a separate powershell.exe instance on the remote system. This "in-process" execution makes detection harder as it doesn't leave a distinct powershell.exe entry in process lists or prefetch files (for the PowerShell executable itself).

Forensically, the shell history maintained during a PowerShell session within wsmprovhost.exe is valuable but highly ephemeral, disappearing the moment the session ends. This makes live capture during an attack nearly impossible. The key breakthrough in memory forensics was the discovery that the svchost.exe process hosting the WinRM service (distinct from the DCOM Launch service) retains fragments of the SOAP messages used to encapsulate PowerShell objects during remoting. These remnants, including recently executed commands and their responses, can persist for "many hours or even until the system is rebooted" (00:10:30). The speaker demonstrated recovery of simple commands like echo "test string ps session" and complex Invoke-Mimikatz syntax from WinRM service memory even five hours after execution. Even base64-encoded commands (e.g., powershell.exe -EncodedCommand ...) are decoded into cleartext within this memory space, providing direct insight into attacker intent.

To efficiently search this potentially large memory region, investigators should target specific WS-Management and Microsoft PowerShell Remoting Protocol syntax. Keywords such as rsp:Command and rsp:CommandLine were identified as excellent starting points, as they are often found near the actual executed commands in memory. While challenging, this method allows for the recovery of critical evidence even in diskless execution scenarios.

Event Log Analysis

The speakers provided a detailed breakdown of forensically significant event logs:

  • Microsoft-Windows-PowerShell/Operational.evtx:
  • EID 400 (Engine state is changed from None to Available): Marks the start of a PowerShell session.
  • EID 403 (Engine state is changed from Available to Stopped): Marks the end of a PowerShell session.
  • The HostName field distinguishes local (ConsoleHost) from remote (ServerRemoteHost) sessions (00:18:15).
  • PowerShell 3.0+ (EID 4100): Logs verbose errors, revealing failed commands, script names, and connection targets (e.g., Cannot be loaded because running scripts is disabled on this system).
  • Microsoft-Windows-WinRM/Operational.evtx:
  • EID 169: Captures the connecting user (matt h), authentication service (NTLM), and connection details for WinRM sessions (00:21:00).
  • EID 84 and 134: Provide additional bookends for WinRM activity.
  • Microsoft-Windows-PowerShell/Analytic.evtx and Microsoft-Windows-WinRM/Analytic.evtx:
  • These logs (disabled by default) generate an enormous volume of events. For example, EID 7937 in the PowerShell Analytic log captures commandlets or script launches, but crucially, it does not include arguments (00:19:30).
  • WinRM Analytic logs capture every piece of data sent and received, including initial protocol negotiations. This data is hex-encoded and requires individual decoding and reassembly to reconstruct commands and responses. For example, listing files in C:\ would generate a separate event for each file as a unique object (00:23:40). This makes them impractical for routine forensic analysis due to volume and decoding complexity.
  • Module Logging (PowerShell 3.0+):
  • Enabled via GPO or Set-AuthenticodeSignature, this feature (EID 4103) is a game-changer. It logs the full command text, including piped commands, and their output.
  • The speakers demonstrated how a complex command like Get-ChildItem -Path C:\temp -Recurse -Filter *.txt | Select-String -Pattern "password" would be fully logged, including the results (00:27:00).
  • Critically, when Invoke-Mimikatz was executed, the module log captured over 1200 events, ultimately containing the cleartext Mimikatz output, including dumped credentials (00:28:00). This capability provides unparalleled visibility into attacker actions.

WMI Persistence

WMI persistence leverages Windows' eventing subsystem:

  1. Event Filters: Define conditions (written in WQL, Windows Query Language) that trigger an action. Examples include SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_LocalTime' AND TargetInstance.Second = 0 (for clock-based triggers) or queries based on system uptime (00:31:00). PowerSploit often uses these.
  2. Event Consumers: Specify the action to be taken when a filter is triggered. For persistence, this is often powershell.exe with arguments.
  3. Bindings: Connect a filter to a consumer.

Attackers can store their malicious PowerShell code in two primary ways:

  1. PowerShell Profiles: Code is placed in a .ps1 file within a user-specific or system-wide profile directory (e.g., C:\Users\<user>\Documents\WindowsPowerShell\profile.ps1). When powershell.exe launches (without the -NoProfile flag), this code automatically executes (00:32:00).
  2. Consumer Command-Line Arguments: The PowerShell command, often compressed and encoded, is directly embedded into the command-line argument of the WMI consumer. This avoids writing a separate script file to disk and bypasses file-based detection (00:33:00). This is limited by the Windows command line length (approx. 800 characters).

Forensic Recovery of WMI Persistence:

  • Live System: The Get-WmiObject PowerShell cmdlet can enumerate all WMI event filters, consumers, and bindings. This is the most straightforward way to detect WMI persistence on a running system. Sysinternals Autoruns (version 12 and later) also enumerates WMI objects, providing MD5 hashes and digital signatures of consumer binaries (00:38:00).
  • Dead System (Disk Image): This is significantly harder. WMI objects are stored in undocumented, complex binary files like objects.data and index.btr within C:\Windows\System32\wbem\Repository. There is "no good way to examine this on a system and determine what WMI filters are installed" (00:35:00). However, running strings on objects.data can sometimes reveal clear Unicode strings for WQL queries and consumer command lines.
  • Registry: A specific registry key, HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WMI\Win32ClockProvider, was identified as an artifact created by WMI event filters using a specific time-of-day trigger (often seen with PowerSploit). This key is not present in default Windows installations, making it a strong indicator of compromise (00:37:00).

Demo / Proof of Concept

▶ Watch: Using Sysmon to capture full command lines (43:00)

While the talk did not feature a live, interactive demonstration of an attack or a step-by-step forensic analysis during the presentation, the speakers presented their findings and evidence based on extensive testing and real-world incident response experience. The examples shown, such as the recovery of Invoke-Mimikatz syntax from svchost.exe memory or the detailed output in PowerShell module logs, served as concrete proof of concept for their investigative techniques. They detailed the artifacts that would be found, illustrating the efficacy of their methods rather than performing a live exploit and subsequent capture.

Defensive Implications

▶ Watch: Key recommendations for better PowerShell auditing (45:00)

The detailed insights into PowerShell attack forensics provide a clear roadmap for enhancing defensive postures:

  1. Upgrade to PowerShell 3.0+ and Enable Module Logging: This is the single most impactful recommendation. Module logging (EID 4103) in PowerShell 3.0+ (and further improved in PowerShell 5.0 beta, which groups events) provides granular command-level auditing, capturing inputs, piped commands, and outputs, including sensitive data like cleartext passwords from Mimikatz. This significantly improves visibility into attacker actions.
  1. Baseline Legitimate PowerShell Activity: Organizations must understand what "normal" PowerShell usage looks like in their environment. This includes identifying typical users, source IP ranges (e.g., admin subnets, VPN pools), standard script paths, and expected PowerShell versions. This baseline is crucial for detecting anomalies.
  1. Monitor for Anomalous PowerShell Activity:
  • Unexpected Remoting: Alert on PowerShell remoting (WinRM over ports 5985/5986) originating from unusual subnets, non-administrative user accounts, or targeting systems not typically managed via PowerShell.
  • Unusual Script Names/Paths: Look for scripts with suspicious names (e.g., evil.ps1) or executed from non-standard locations (e.g., C:\Users\Public).
  • Execution Policy Changes: While easily bypassed, an attacker might modify the registry setting for the execution policy out of convenience. Such a change, especially if unique in the environment, is a strong indicator of compromise.
  • PowerShell Version Mismatches: Monitor WinRM HTTP headers for PowerShell version information. An attacker might be using a different version than what's standard for the internal network, triggering alerts.
  1. Deploy and Configure Sysmon: Sysinternals Sysmon is an invaluable tool. Configure it to log process creation events with full command-line arguments (including PowerShell scripts and their parameters), file creation time changes (useful for detecting time-stomping), and network connections. This provides crucial visibility into PowerShell execution and communication.
  1. Leverage AppLocker in Audit Mode: Even if application whitelisting isn't fully enforced, AppLocker in audit mode can log all script executions, including the user and the full script path, providing vital intelligence without blocking legitimate operations.
  1. Regularly Inspect PowerShell Profiles: Periodically examine user-specific and system-wide PowerShell profile files (.ps1) for malicious code, especially those that might be hidden with excessive padding. Consider enforcing script signing for profiles if possible.
  1. Actively Hunt for WMI Persistence:
  • On live systems, use Get-WmiObject or Sysinternals Autoruns (v12+) to enumerate WMI event filters and consumers. Baseline these objects to identify any anomalous or newly created entries.
  • Examine the registry for the Win32ClockProvider key, a strong indicator of specific WMI persistence techniques.
  • Be aware of the difficulty of WMI forensics on dead systems and rely on live analysis where possible.
  1. Strengthen Core Security Controls: The speakers emphasized that PowerShell attacks are primarily post-exploitation. Therefore, fundamental security controls remain paramount: prevent initial compromise, enforce strong authentication, implement network segmentation, and maintain host-based firewalls to limit lateral movement and C2 channels. Limiting administrative privileges is always the best first line of defense.

Key Takeaways

  • PowerShell is a primary post-exploitation tool: Its deep integration with Windows and versatile capabilities make it a favored weapon for targeted attackers and mass malware, enabling lateral movement, data exfiltration, and persistence.
  • Memory forensics can reveal hidden activity: Even in "diskless" PowerShell remoting scenarios, fragments of commands (including decoded encoded commands) can be recovered for hours from the svchost.exe process hosting the WinRM service.
  • PowerShell 3.0+ with Module Logging is essential for auditing: This feature (EID 4103) provides unprecedented visibility by logging full command syntax, piped commands, and their output, including sensitive data like Mimikatz dumps. Upgrading to PowerShell 5.0 (and newer) further refines this logging.
  • WMI event filters and consumers are stealthy persistence mechanisms: Attackers can use WMI to automatically launch PowerShell, often embedding malicious code directly into consumer command-line arguments or profiles, making detection challenging, especially on dead disk images.
  • Baseling and anomaly detection are critical: Understanding normal PowerShell activity within an environment is key to identifying unusual remoting, script execution, or configuration changes that indicate compromise.
  • Sysmon and AppLocker provide invaluable visibility: These tools, when properly configured, can log crucial details like full command lines for process creation and script execution attempts, significantly enhancing detection capabilities.

About the Speaker(s)

Ryan Kazanciyan is a Technical Director with Mandiant, a leading cybersecurity firm specializing in incident response. His work primarily focuses on large, complex breaches and targeted attacks, often involving adversaries who maintain persistence in victim environments for extended periods. His expertise lies in incident response, forensics, and understanding the evolving tactics, techniques, and procedures (TTPs) of sophisticated attackers.

Matt Hastings is also associated with Mandiant, and based on the context of the talk, he is involved in incident response and forensic investigations, contributing to the detailed research on uncovering and analyzing advanced attack methodologies, particularly those leveraging native operating system tools like PowerShell.

Reviews

  • Heather Calloway (CISO) — MUST SEE ★★★★★

→ Top-rated talks at BruCON 0x06

All talks from BruCON 0x06