| name | deobfuscating-powershell-obfuscated-malware |
| description | Systematically deobfuscate multi-layer PowerShell malware using AST analysis, dynamic tracing, and tools like PSDecode and PowerDecode to reveal hidden payloads and C2 infrastructure. |
| domain | cybersecurity |
| subdomain | malware-analysis |
| tags | ["powershell","deobfuscation","malware-analysis","scripting","obfuscation","ast-analysis","incident-response"] |
| version | 1.0 |
| author | mahipal |
| license | Apache-2.0 |
Deobfuscating PowerShell Obfuscated Malware
Overview
PowerShell is heavily abused by malware authors due to its deep Windows integration and powerful scripting capabilities. Obfuscation techniques include string concatenation, Base64 encoding, character substitution, Invoke-Expression layering, SecureString abuse, environment variable manipulation, and tick-mark insertion. Modern malware uses multiple obfuscation layers requiring iterative deobfuscation. Tools like PSDecode, PowerDecode, and PowerPeeler automate much of this process, while manual AST (Abstract Syntax Tree) analysis handles custom obfuscation. PowerPeeler achieves a 95% deobfuscation correctness rate using instruction-level dynamic analysis of expression-related AST nodes.
Prerequisites
- Python 3.9+ with
base64, re, subprocess modules
- PowerShell 5.1+ or PowerShell 7+ (for AST access)
- PSDecode (
Install-Module PSDecode)
- PowerDecode (https://github.com/Malandrone/PowerDecode)
- Isolated VM or sandbox for safe script execution
- CyberChef for manual encoding transformations
- Understanding of PowerShell AST and Invoke-Expression patterns
Key Concepts
Common Obfuscation Techniques
PowerShell malware employs layered obfuscation to evade static detection. String concatenation splits commands across variables ($a='In'+'voke'). Base64 encoding wraps entire scripts in -EncodedCommand parameters. Character code arrays use [char] casting ([char[]](73,69,88)|%{$r+=$_}). Environment variable abuse reads substrings from $env: paths. Tick-mark insertion adds backticks between characters that PowerShell ignores (Invoke-Expression`). SecureString conversion encrypts strings using ConvertTo-SecureString with embedded keys.
AST-Based Deobfuscation
PowerShell's Abstract Syntax Tree exposes the parsed structure of scripts regardless of surface-level obfuscation. By walking the AST and evaluating expression nodes, analysts can resolve concatenated strings, decode encoded values, and reconstruct the original commands. PowerPeeler uses this approach at the instruction level, monitoring the execution process to correlate AST nodes with their evaluated results.
Dynamic Execution Tracing
By replacing Invoke-Expression (IEX) with Write-Output, analysts can safely capture the deobfuscated script content that would normally be executed. This technique works across multiple layers by iteratively replacing IEX calls until the final payload is revealed.
Practical Steps
Step 1: Identify Obfuscation Layers
"""Identify and classify PowerShell obfuscation techniques."""
import re
import base64
import sys
def analyze_obfuscation(script_content):
"""Identify obfuscation techniques used in PowerShell script."""
techniques = []
b64_pattern = re.compile(
r'-[Ee](?:nc(?:odedcommand)?)\s+([A-Za-z0-9+/=]{20,})',
re.IGNORECASE
)
if b64_pattern.search(script_content):
techniques.append("Base64 EncodedCommand")
if re.search(r'\[Convert\]::FromBase64String', script_content, re.IGNORECASE):
techniques.append("Base64 FromBase64String")
concat_count = script_content.count("'+'") + script_content.count('"+"')
if concat_count > 3:
techniques.append(f"String Concatenation ({concat_count} joins)")
if re.search(r'\[char\]\s*\d+', script_content, re.IGNORECASE):
techniques.append("Character Code Array")
iex_patterns = [
r'Invoke-Expression',
r'\bIEX\b',
r'\.\s*\(\s*\$',
r'&\s*\(\s*\$',
r'\|\s*IEX',
r'\|\s*Invoke-Expression',
]
for pattern in iex_patterns:
if re.search(pattern, script_content, re.IGNORECASE):
techniques.append()
tick_count = script_content.count()
tick_count > :
techniques.append()
re.search(, script_content, re.IGNORECASE):
env_refs = re.findall(, script_content, re.IGNORECASE)
(env_refs) > :
techniques.append()
re.search(, script_content, re.IGNORECASE):
techniques.append()
re.search(,
script_content, re.IGNORECASE):
techniques.append()
re.search(, script_content, re.IGNORECASE):
techniques.append()
replace_count = (re.findall(, script_content))
replace_count > :
techniques.append()
techniques
():
b64_match = re.search(
,
script_content, re.IGNORECASE
)
b64_match:
encoded = b64_match.group()
:
decoded = base64.b64decode(encoded).decode()
decoded
Exception:
():
escape_chars = {, , , , , , , , }
result = []
i =
i < (script_content):
script_content[i] == i + < (script_content):
pair = script_content[i:i+]
pair escape_chars:
result.append(pair)
i +=
:
result.append(script_content[i+])
i +=
:
result.append(script_content[i])
i +=
.join(result)
():
pattern = re.()
pattern.search(script_content):
script_content = pattern.sub( m: ,
script_content)
pattern = re.()
pattern.search(script_content):
script_content = pattern.sub( m: ,
script_content)
script_content
__name__ == :
(sys.argv) < :
()
sys.exit()
(sys.argv[], , errors=) f:
content = f.read()
()
( * )
techniques = analyze_obfuscation(content)
t techniques:
()
()
( * )
deobfuscated = remove_tick_marks(content)
deobfuscated = resolve_string_concat(deobfuscated)
b64_decoded = decode_base64_command(deobfuscated)
b64_decoded:
()
(b64_decoded[:])
deobfuscated = b64_decoded
()
output_file = sys.argv[] +
(output_file, ) f:
f.write(deobfuscated)
()
Step 2: Multi-Layer IEX Replacement
import subprocess
import tempfile
import os
def iex_replacement_deobfuscate(script_content, max_layers=10):
"""Iteratively replace IEX with Write-Output to unwrap layers."""
replacements = [
(r'\bInvoke-Expression\b', 'Write-Output'),
(r'\bIEX\b', 'Write-Output'),
(r'\|\s*IEX\b', '| Write-Output'),
]
current = script_content
layers = []
for layer_num in range(max_layers):
modified = current
for pattern, replacement in replacements:
modified = re.sub(pattern, replacement, modified, flags=re.IGNORECASE)
if modified == current and layer_num > 0:
print(f" [+] No more IEX layers found at layer {layer_num}")
break
with tempfile.NamedTemporaryFile(mode='w', suffix='.ps1',
delete=False) as tmp:
tmp.write(modified)
tmp_path = tmp.name
try:
result = subprocess.run(
['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass',
'-File', tmp_path],
capture_output=, text=, timeout=
)
output = result.stdout.strip()
output output != current:
(
)
layers.append({
: layer_num + ,
: ,
: (output),
})
current = output
:
subprocess.TimeoutExpired:
()
:
os.unlink(tmp_path)
current, layers
Step 3: Extract IOCs from Deobfuscated Script
def extract_iocs_from_script(deobfuscated_content):
"""Extract indicators of compromise from deobfuscated PowerShell."""
iocs = {
"urls": [],
"ips": [],
"domains": [],
"file_paths": [],
"registry_keys": [],
"commands": [],
"base64_blobs": [],
}
url_pattern = re.compile(
r'https?://[^\s\'"<>)\]]+', re.IGNORECASE
)
iocs["urls"] = list(set(url_pattern.findall(deobfuscated_content)))
ip_pattern = re.compile(
r'\b(?:\d{1,3}\.){3}\d{1,3}\b'
)
iocs["ips"] = list(set(ip_pattern.findall(deobfuscated_content)))
path_pattern = re.compile(
r'[A-Za-z]:\\[^\s\'"<>|]+|'
r'\\\\[^\s\'"<>|]+|'
r'%(?:APPDATA|TEMP|USERPROFILE|PROGRAMFILES)%[^\s\'"<>|]*',
re.IGNORECASE
)
iocs["file_paths"] = list(set(path_pattern.findall(deobfuscated_content)))
reg_pattern = re.compile(
r'(?:HKLM|HKCU|HKCR|HKU|HKCC)(?:\\[^\s\'"<>|]+)+',
re.IGNORECASE
)
iocs["registry_keys"] = list(set(reg_pattern.findall(deobfuscated_content)))
suspicious_cmds = [
'New-Object Net.WebClient',
'DownloadString', , ,
, ,
,
,
,
,
, ,
]
cmd suspicious_cmds:
cmd.lower() deobfuscated_content.lower():
iocs[].append(cmd)
iocs
Validation Criteria
- All obfuscation layers identified and classified correctly
- Base64 encoded commands decoded to readable PowerShell
- Tick-mark and string concatenation obfuscation resolved
- IEX replacement reveals next-stage payloads
- URLs, IPs, and file paths extracted from final deobfuscated stage
- Deobfuscated script matches observed malware behavior in sandbox
References