(Re)Investigating Powershell attacks

Matt Hastings (Tanium), Ryan Kazanciyan (Tanium)

BruCON 0x0A · Day 1

Overview

In this insightful talk, "Reinvestigating PowerShell Attacks," Matt Hastings and Ryan Kazanciyan from Tanium revisit their extensive research into PowerShell's role in offensive security and defensive strategies. The presentation, delivered at BruCON, serves as an updated retrospective on their previous talks from 2014 and 2015, highlighting the dramatic evolution of both offensive techniques leveraging PowerShell and the defensive capabilities built into the scripting language. The speakers, drawing from their backgrounds in incident response and forensics at Mandiant and PricewaterhouseCoopers, offer a unique perspective on how the security landscape around PowerShell has transformed over nearly a decade.

Watch on YouTube

Visual summary for (Re)Investigating Powershell attacks by Matt Hastings, Ryan Kazanciyan
Visual summary for (Re)Investigating Powershell attacks by Matt Hastings, Ryan Kazanciyan

Key moments

  1. 2:20 Initial PowerShell attack incident sparks research
  2. 10:50 PowerShell Script Block Logging: the auditing "holy grail"
  3. 14:50 PowerShell evasion techniques and attacker adaptations
  4. 25:00 Revisiting Desired State Configuration (DSC) for persistence
  5. 37:00 Event Tracing for Windows (ETW) for forensics
  6. 41:00 Empire attack demo and ETW forensic analysis
  7. 54:00 Analyzing .NET attacks with ETW (SharpSploit)
  8. 57:50 Q&A: ETW scalability for endpoint detection

(Re)Investigating Powershell attacks

Speakers: Matt Hastings, Product Manager (Tanium); Ryan Kazanciyan, Product Manager (Tanium)

Conference: BruCON

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

Overview

In this insightful talk, "Reinvestigating PowerShell Attacks," Matt Hastings and Ryan Kazanciyan from Tanium revisit their extensive research into PowerShell's role in offensive security and defensive strategies. The presentation, delivered at BruCON, serves as an updated retrospective on their previous talks from 2014 and 2015, highlighting the dramatic evolution of both offensive techniques leveraging PowerShell and the defensive capabilities built into the scripting language. The speakers, drawing from their backgrounds in incident response and forensics at Mandiant and PricewaterhouseCoopers, offer a unique perspective on how the security landscape around PowerShell has transformed over nearly a decade.

The core of the discussion revolves around the ongoing cat-and-mouse game between attackers and defenders, with PowerShell at its center. Initially, PowerShell was an under-audited, powerful tool ripe for abuse. However, significant advancements in logging and security features have made it one of the most auditable scripting languages available today. Despite these improvements, attackers continue to find new avenues for abuse, including the shift towards .NET-based attacks and the exploration of new PowerShell iterations like PowerShell Core (v6) and Desired State Configuration (DSC). Hastings and Kazanciyan provide a comprehensive technical deep dive into these changes, offering practical advice and demonstrating advanced forensic techniques using Event Tracing for Windows (ETW).

The talk underscores the critical importance of understanding legitimate PowerShell usage within an environment as a foundational step for effective detection. It also emphasizes the continuous need for defenders to adapt, moving beyond signature-based detection to more sophisticated behavioral analysis and leveraging powerful, often overlooked, built-in Windows telemetry sources like ETW. This presentation is essential for security professionals seeking to understand the current state of PowerShell security, the emerging threats, and the advanced defensive capabilities available to them.

Background

▶ Watch: Initial PowerShell attack incident sparks research (2:20)

The initial impetus for this research stemmed from a significant incident Matt Hastings and Ryan Kazanciyan investigated in 2013. Attackers had maintained persistent access to a victim environment for several years through compromised VPN credentials. After multiple rounds of detection and incomplete remediation, the adversaries shifted their tactics. They began interacting almost exclusively with compromised machines via PowerShell remoting and standard PowerShell scripts after logging into the VPN. This marked a pivotal moment for the investigators, as it was the first time they had encountered such extensive and exclusive use of PowerShell in a targeted breach, particularly PowerShell remoting.

At the time, forensic artifacts related to PowerShell activity were scarce. The lack of robust auditing mechanisms meant that investigators were often left with limited visibility into attacker actions. This challenge prompted the initial research, which aimed to uncover and document the forensic traces left by PowerShell attacks. Their 2014 presentation explored the artifacts generated by three primary methodologies: local PowerShell script execution, PowerShell remoting, and persistence via Windows Management Instrumentation (WMI) to execute malicious PowerShell commands. They examined evidence across various sources, including disk, event logs, memory, and network traffic.

Early findings, particularly concerning memory forensics, revealed significant limitations. While it was theoretically possible to reconstruct some strings of remoting activity from WSMHost and ServiceHost process memory, the ephemeral nature of these processes meant that the likelihood of successful recovery diminished rapidly once a session terminated. This scarcity of persistent evidence highlighted the urgent need for improved logging. Concurrently, preliminary offensive research into PowerShell, notably by individuals like Matt Graver, was already gaining traction, further emphasizing the growing threat and the gap in defensive capabilities. The state of PowerShell auditing in PowerShell 2.0, the most prevalent version at the time, was rudimentary, offering little more than session start and end times, making detailed incident reconstruction exceptionally challenging.

Key Findings

▶ Watch: PowerShell evasion techniques and attacker adaptations (14:50)

The talk presents several key findings and observations regarding the evolution of PowerShell attacks and defense:

  1. Dramatic Improvement in PowerShell Logging: Since 2014, PowerShell logging has advanced significantly. PowerShell v3 introduced module logging, providing visibility into commandlets run per session. PowerShell v4 (and later v5) introduced script block logging, a "holy grail" feature that logs blocks of code, even when obfuscated or encoded, by capturing them as they are decoded and executed through the pipeline. This level of transparency is unparalleled among common scripting languages, making PowerShell one of the most auditable.
  2. PowerShell's Strong Defensive Posture: When compared to other interpreted languages like VBScript or Python, PowerShell, with its modern logging features enabled, offers far superior security controls and auditing capabilities. This forces attackers to evolve their techniques or risk easy detection. Microsoft's efforts to enhance PowerShell's security have even influenced other languages, with Python 3.8 targeting similar runtime hooks for auditability.
  3. Rise of Evasion Techniques: The improved logging has driven the development of sophisticated evasion techniques. Tools like Dana Bohannon's Invoke-Obfuscation break apart command lines and code to bypass signature-based detection. Other methods include bypassing AMSI (Antimalware Scan Interface), disabling ETW (Event Tracing for Windows) logging providers, and PowerShell downgrade attacks (forcing systems to use older, less auditable versions like v2.0).
  4. Attackers Still Opt for Simplicity: Despite advanced evasion techniques, many attackers, including state-sponsored groups (e.g., APT32) and crypto-miners, continue to use simple, easily detectable PowerShell command lines. Statistics cited from Symantec indicate that only 4% of malicious code reviewed used obfuscation, suggesting attackers often prioritize ease of use and "living off the land" over stealth, especially if basic defenses are lacking.
  5. Shift Towards .NET Attacks: As PowerShell logging improves, sophisticated attackers are increasingly moving "below PowerShell" to .NET-based attacks. Tools like Ryan Cobb's Sharpsploit, written entirely in C#, bypass many PowerShell-specific logging mechanisms, presenting a new challenge for defenders.
  6. PowerShell Core (v6) Introduces New Auditing Nuances: PowerShell v6, built on .NET Core 6.0, is cross-platform and introduces new logging mechanisms, including a dedicated event log (PowerShellCore/Operational), a new ETW GUID, and JSON configuration files for audit settings. While event IDs are consistent with v5, the ability to disable auditing via unregister-manifest.ps1 and the presence of a persistent command history (history.txt) require new defensive considerations.
  7. Desired State Configuration (DSC) Remains Unpopular with Attackers: Despite the speakers' earlier research in 2015 identifying DSC as a potential persistence mechanism ("DSC-ompromise"), it has not seen significant adoption by attackers. Reasons include its complexity, difficulty in troubleshooting, version dependencies (requiring PowerShell 4.0+ on victims), and the existence of simpler, more covert persistence methods. The ongoing evolution of DSC Core further complicates its stability for exploitation.
  8. ETW as a Powerful Forensic and Detection Tool: Event Tracing for Windows (ETW), though long-standing, is an underutilized source of deep forensic telemetry. It offers kernel-level visibility into process creation, DLL loads, network connections, file system activity, and even .NET method calls, linking events back to specific processes and threads. ETW can provide comprehensive insights into attack chains, even when PowerShell logging is bypassed, offering a robust foundation for advanced behavioral detection.

Technical Deep Dive

▶ Watch: Event Tracing for Windows (ETW) for forensics (37:00)

The technical depth of the presentation covers the evolution of PowerShell logging, the intricacies of PowerShell v6, the underutilized Desired State Configuration (DSC), and the powerful capabilities of Event Tracing for Windows (ETW).

PowerShell Logging Evolution

PowerShell 2.0 (Pre-2014): In the early days, PowerShell 2.0 offered minimal direct logging. Only console session start and end times were reliably recorded. While AppLocker could audit script execution, and Transcription Logging could capture console input/output on a per-profile basis, these were often not widely deployed or easily bypassed. For remoting sessions, base64 encoded command blobs were sometimes logged, requiring manual decoding to understand the activity.

PowerShell 3.0 (2014): A significant leap forward, v3.0 introduced Module Logging. This allowed defenders to log commandlets executed for each PowerShell session, offering much greater visibility than before. However, it could generate substantial noise; for instance, running Invoke-Mimikatz could produce nearly 4,000 unique log events.

PowerShell 4.0 / 5.0 (Post-2014): The "holy grail" of PowerShell logging arrived with Script Block Logging, introduced in v4.0 but widely adopted with v5.0. This feature logs blocks of code as they are executed, crucially capturing obfuscated or encoded commands after they have been decoded by the PowerShell engine. This bypasses many common evasion techniques, providing the actual malicious code in the event log. It also uses a larger event log message format, reducing the number of fragmented events.

PowerShell v6 (Core)

PowerShell Core (v6.0) represents a fundamental shift. It is built on the .NET Core 6.0 runtime, making it open-source and cross-platform (Windows, Mac, Linux). It installs side-by-side with PowerShell v5 and has its own executable (pwsh.exe).

Key auditing changes in v6 include:

  • New Event Log: PowerShellCore/Operational.
  • New ETW GUID: A distinct GUID for its ETW provider.
  • JSON Configuration Files: Audit settings are now configured via .json files, offering granular control over script block logging, execution policy, and transcription.
  • register-manifest.ps1: A script used by administrators to register a configuration from a JSON file.
  • unregister command: This command can easily disable auditing settings. Crucially, it doesn't generate a discrete event log entry, but its execution is captured by transcription logging (which is enabled by default in v6).
  • Persistent Command History: A history.txt file (or ConsoleHost_history.txt) stores up to 4096 commands, similar to Bash history, offering another forensic artifact even if other logging is disabled.

Desired State Configuration (DSC)

Desired State Configuration (DSC) is an out-of-band management framework designed to enforce system configurations. It operates in two modes:

  • Push Mode: Uses WinRM (the same remoting service as PowerShell).
  • Pull Mode: Can use SMB, HTTP, or HTTPS. This mode was particularly interesting for attackers, as it allows a compromised machine to pull a malicious configuration from an internet-hosted server.

The speakers' 2015 research, "DSC-ompromise," demonstrated how DSC could be weaponized for persistence. Attackers could configure a system to automatically re-infect itself if a malicious file was deleted or a user account removed. Forensic artifacts for DSC activity include:

  • Network Activity: Distinctive URLs for pull mode configurations.
  • File System Activity: EDR tools would capture the creation of scheduled tasks, temporary and permanent MOF files (which store the configuration), and dropped payloads.
  • Event Logging: The default DSC operational log provides events indicating when a configuration is applied.

Despite its potential, DSC has not gained traction with attackers due to its complexity, version dependencies (PowerShell 4.0+ required on victims), and the availability of simpler, more covert persistence mechanisms.

DSC Core: Microsoft is transitioning to DSC Core, which aims to be cross-platform and open-source, mirroring PowerShell v6. It completely strips dependencies on WMI and the Windows Management Foundation, featuring a new cross-platform Local Configuration Manager (LCM). Resources for DSC Core can be implemented in C, C++, Python, or PowerShell Core, making it highly flexible but also a moving target for exploitation.

Event Tracing for Windows (ETW)

ETW is a powerful, long-standing (since Windows 2000) logging mechanism primarily designed for performance monitoring and application troubleshooting, but it serves as an excellent forensic tool.

  • Providers: ETW collects events from hundreds of providers, including kernel-level providers (for process/thread creation, DLL loads, execution), PowerShell, DNS client, network, and file system.
  • Sessions: Providers are grouped into sessions that can be configured to log specific event types or keywords to manage verbosity.
  • Event Processing: Events can be logged to ETL files (like the analytic log in Event Viewer) or processed asynchronously in memory for real-time analysis.
  • Event Linking: Crucially, ETW events are linked back to the specific process and thread that generated them, allowing for a comprehensive reconstruction of process activity.

While ETW can be impacted by PowerShell evasions that target PowerShell's internal logging, its kernel-level and broader system visibility means it can still capture activity "below" or "around" PowerShell, making it invaluable for detecting sophisticated attacks, including those leveraging .NET or process injection.

For .NET visibility, the dotnet-runtime ETW provider can log .NET method calls. This allows defenders to trace the execution of C# tools like Sharpsploit at a granular level, revealing functions like logon-passwords, SamDump, LsaSecrets, and WDigest as they are invoked, providing deep insight into attacker actions within the .NET runtime.

Demo / Proof of Concept

▶ Watch: Empire attack demo and ETW forensic analysis (41:00)

The talk included a compelling live demo showcasing an attack chain and its subsequent forensic analysis using ETW. The demonstration highlighted the comprehensive visibility offered by ETW, even against sophisticated techniques.

The scenario began with an attacker gaining initial access as a standard user (norm_no_admin) on a domain-joined machine. The attacker used Empire, a popular PowerShell post-exploitation framework, for the operation.

Attack Steps:

  1. Initial Execution & Credential Theft: The attacker executed a command using certutil to download and execute a PowerShell script from the internet: Get-GPPPassword.ps1. This script is designed to identify hard-coded configuration passwords in Group Policy Objects (GPOs), often exposing plaintext credentials.
  2. Privilege Escalation: After obtaining credentials, the attacker used runas to elevate privileges to an administrator.
  3. Empire Agent Deployment (VBScript): The attacker then opened Notepad, created a VBScript file (launcher.vbs), and used cscript to execute it. This VBScript launched a PowerShell command that downloaded and ran the Empire agent, establishing an initial beacon.
  4. Process Injection: The Empire agent then injected itself into a legitimate system process, spoolsv.exe (the Print Spooler service), and killed the original agent. This is a common technique to hide malicious activity within a trusted process.
  5. Post-Exploitation: From the injected spoolsv.exe process, the attacker executed several post-exploitation commands:
  • shell whoami /all: To verify user context.
  • mimikatz: To dump credentials from memory.
  • netstat: To view network connections.

ETW Forensic Analysis:

Throughout the attack, an ETW collection was continuously running on the victim machine. The analysis phase demonstrated how to parse and reconstruct the attack using a custom PowerShell module (running on PowerShell v6 on a Mac, highlighting its cross-platform nature).

  1. PowerShell Instance Identification: The analysis began by identifying all PowerShell instances run during the collection. This revealed the initial PowerShell process associated with Get-GPPPassword.ps1.
  2. Command and Script Block Reconstruction: For the Get-GPPPassword.ps1 instance, the module extracted all executed commands and reconstructed script blocks. This provided the full source code of the downloaded script, demonstrating how script block logging captures even internet-downloaded code.
  3. Child Process Tracking: ETW captured all child processes launched by the initial PowerShell instance, including whoami /all, certutil (showing its domain lookups and network connections), and runas for privilege escalation.
  4. VBScript Execution & Empire Launch: The analysis traced the execution from runas to a command shell, then to Notepad creating launcher.vbs, and finally to cscript executing the VBScript. This cscript process then spawned a second PowerShell instance, which was responsible for downloading and invoking the Empire agent. Again, the base64 encoded command and the full Invoke-Empire source code were reconstructed.
  5. Process Injection Visibility: The injection into spoolsv.exe (process ID 1924 in the demo) was clearly visible. While the initial process creation event for spoolsv wasn't captured (as it started before ETW collection), subsequent file I/O confirmed its identity. Crucially, ETW showed the loading of Automation.dll within spoolsv.exe. This is a significant indicator of compromise, as spoolsv should not typically load PowerShell-related DLLs.
  6. Injected Command Logging: Even though mimikatz was run from the injected spoolsv.exe process, ETW's kernel-level logging captured the PowerShell commands, including the full Invoke-Mimikatz script block. This demonstrated that ETW can log PowerShell activity even when executed from non-PowerShell processes via techniques like process injection.
  7. Thread-Level Granularity: The demo highlighted ETW's ability to provide granular detail down to individual threads, showing which thread within spoolsv was responsible for domain lookups or file system activity, invaluable for pinpointing injected code.
  8. Attack Visualization: The module generated a visual graph of the entire attack chain, starting from the initial PowerShell instance, showing all child processes, and connecting the different stages of the compromise.

Additional .NET Visibility Demo:

A brief follow-up demo showed the dotnet-runtime ETW provider capturing method calls from Sharpsploit executing mimikatz commands. This demonstrated how ETW could log specific .NET function calls like logon-passwords, SamDump, LsaSecrets, and WDigest, providing visibility into attacks that bypass PowerShell logging by directly leveraging the .NET framework.

The demo conclusively proved that while attackers evolve, comprehensive logging with ETW provides a powerful means to reconstruct complex attack scenarios, even those involving process injection and direct .NET execution.

Defensive Implications

▶ Watch: Q&A: ETW scalability for endpoint detection (57:50)

The detailed investigation into PowerShell attacks and the capabilities of ETW offers several critical defensive implications for security practitioners:

  1. Baseline Legitimate PowerShell Usage: This is the foundational step. Organizations must understand what "normal" PowerShell activity looks like in their environment. This includes enterprise tooling, group policy scripts, SCCM jobs, and administrative one-off scripts. Without a baseline, distinguishing malicious activity from benign noise is exceedingly difficult. This baselining should be done over time to capture periodic events.
  1. Enable Comprehensive PowerShell Logging:
  • Script Block Logging: Enable this universally (PowerShell v4/v5 and above). It is crucial for capturing decoded commands, even if obfuscated.
  • Module Logging: Enable for broader visibility into commandlets.
  • Transcription Logging: Enable this, especially for PowerShell v6, as it captures console input/output and can reveal attempts to disable auditing.
  • AppLocker Auditing: While not a blocking mechanism, auditing with AppLocker provides valuable insights into script and executable execution.
  1. Monitor PowerShell v6 (Core) Specifics:
  • Actively monitor the new PowerShellCore/Operational event log.
  • Be aware of the new ETW GUID for PowerShell Core.
  • Monitor for changes to PowerShell Core's JSON configuration files and registry keys that control auditing.
  • Crucially, monitor for the execution of unregister-manifest.ps1 or similar commands that disable auditing, which will be captured in transcription logs.
  • Regularly collect and analyze the persistent command history (history.txt or ConsoleHost_history.txt).
  1. Implement Robust ETW Collection and Analysis:
  • Recognize ETW as a primary source of deep system telemetry, extending beyond PowerShell.
  • Investigate and configure relevant ETW providers (kernel, PowerShell, DNS client, network, file system, dotnet-runtime) to collect forensically significant events.
  • Develop tooling or leverage existing EDR solutions that can collect, filter, and correlate ETW events to reconstruct attack chains.
  • Focus on linking events to processes and threads to gain granular visibility into activities like process injection.
  1. Detect Evasion Techniques:
  • PowerShell Downgrade Attacks: Implement controls to prevent the use of older, less secure PowerShell versions (e.g., v2.0).
  • AMSI Bypass: Monitor for known AMSI bypass techniques.
  • Logging Disablement: Actively look for attempts to disable PowerShell or ETW logging providers.
  • Obfuscation: While script block logging helps, behavioral analysis is still key to detecting highly obfuscated commands that might slip through.
  1. Monitor for Suspicious DLL Loads:
  • Alert on the loading of Automation.dll or other PowerShell-related DLLs by non-PowerShell processes (e.g., spoolsv.exe, explorer.exe). This is a strong indicator of process injection or reflective loading of PowerShell.
  1. Address .NET-Based Attacks:
  • As attackers shift to .NET, leverage the dotnet-runtime ETW provider for visibility into C# tools like Sharpsploit. Configure it to log method calls of interest, especially those related to credential dumping or reconnaissance.
  • Behavioral detection for .NET applications becomes crucial, as signature-based methods might fail against custom C# tools.
  1. Monitor Desired State Configuration (DSC) Activity:
  • While not widely adopted by attackers, DSC still poses a risk. Monitor network activity for suspicious pull requests to DSC configuration servers.
  • Monitor file system activity for MOF file creation, scheduled tasks related to DSC, and unexpected payloads.
  • Analyze the DSC operational logs for unauthorized configuration changes.
  1. Continuous Improvement: The security landscape is constantly evolving. Defenders must remain vigilant, continuously updating their understanding of new attack techniques and adapting their detection and prevention strategies accordingly. This includes staying abreast of research and collaborating within the security community.

By implementing these defensive measures, organizations can significantly improve their ability to detect, investigate, and respond to sophisticated PowerShell and related "living off the land" attacks.

Key Takeaways

  • PowerShell has evolved into the most auditable scripting language, offering unparalleled visibility when logging features like script block logging are fully enabled.
  • Attackers are adapting to enhanced PowerShell logging by employing obfuscation, downgrade attacks, and increasingly shifting to .NET-based attack frameworks like Sharpsploit.
  • Establishing a comprehensive baseline of legitimate PowerShell activity within an environment is a critical prerequisite for effective malicious PowerShell detection.
  • Event Tracing for Windows (ETW) is a powerful, often underutilized, kernel-level telemetry source that provides deep forensic visibility into process execution, DLL loads, network activity, and even .NET method calls, crucial for detecting sophisticated attacks that bypass standard PowerShell logging.
  • While Desired State Configuration (DSC) presented a potential persistence vector, its complexity and the availability of simpler alternatives have limited its adoption by attackers.
  • Defenders must move beyond signature-based detection and embrace behavioral analysis, leveraging robust logging and telemetry (like ETW) to identify anomalous activity, including suspicious DLL loads in trusted processes.

About the Speaker(s)

Ryan Kazanciyan and Matt Hastings are product managers at Tanium, where they focus on building software to help companies investigate, protect, and secure their environments. Both speakers share a similar career trajectory, having started their careers in consulting at PricewaterhouseCoopers. They then moved to Mandiant, where they specialized in Incident Response and forensics, gaining extensive experience in investigating complex cyberattacks. Their shared background in hands-on incident response heavily influenced their research into PowerShell attacks. They are based in Alexandria, Virginia, and have been presenting their research on PowerShell and related topics at conferences like BruCON since 2014. Their work reflects a deep understanding of both offensive techniques and defensive strategies, driven by real-world incident experience.

Reviews

→ Top-rated talks at BruCON 0x0A

All talks from BruCON 0x0A