deobfuscating-powershell-obfuscated-malware
Systematically deobfuscate multi-layer PowerShell malware using AST analysis, dynamic tracing, and tools like PSDecode and PowerDecode to reveal hidden payloads and C2 infrastructure.
What this skill does
# 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.
## When to Use
- When performing authorized security testing that involves deobfuscating powershell obfuscated malware
- When analyzing malware samples or attack artifacts in a controlled environment
- When conducting red team exercises or penetration testing engagements
- When building detection capabilities based on offensive technique understanding
## 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 (`I`nv`oke-Exp`ression`). 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.
## Workflow
### Step 1: Identify Obfuscation Layers
```python
#!/usr/bin/env python3
"""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 = []
# Check for Base64 encoded command
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")
# Check for FromBase64String
if re.search(r'\[Convert\]::FromBase64String', script_content, re.IGNORECASE):
techniques.append("Base64 FromBase64String")
# Check for string concatenation
concat_count = script_content.count("'+'") + script_content.count('"+"')
if concat_count > 3:
techniques.append(f"String Concatenation ({concat_count} joins)")
# Check for char array construction
if re.search(r'\[char\]\s*\d+', script_content, re.IGNORECASE):
techniques.append("Character Code Array")
# Check for Invoke-Expression variants
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(f"Invoke-Expression variant: {pattern}")
# Check for tick-mark obfuscation
tick_count = script_content.count('`')
if tick_count > 5:
techniques.append(f"Tick-mark Insertion ({tick_count} backticks)")
# Check for environment variable abuse
if re.search(r'\$env:', script_content, re.IGNORECASE):
env_refs = re.findall(r'\$env:\w+', script_content, re.IGNORECASE)
if len(env_refs) > 2:
techniques.append(f"Environment Variable Abuse ({len(env_refs)} refs)")
# Check for SecureString
if re.search(r'ConvertTo-SecureString', script_content, re.IGNORECASE):
techniques.append("SecureString Encryption")
# Check for compression
if re.search(r'IO\.Compression|DeflateStream|GZipStream',
script_content, re.IGNORECASE):
techniques.append("Compression (Deflate/GZip)")
# Check for XOR encoding
if re.search(r'-bxor\s+\d+', script_content, re.IGNORECASE):
techniques.append("XOR Encoding")
# Check for Replace chain
replace_count = len(re.findall(r'\.Replace\(', script_content))
if replace_count > 2:
techniques.append(f"Replace Chain ({replace_count} replacements)")
return techniques
def decode_base64_command(script_content):
"""Extract and decode Base64 encoded commands."""
b64_match = re.search(
r'-[Ee](?:nc(?:odedcommand)?)\s+([A-Za-z0-9+/=]{20,})',
script_content, re.IGNORECASE
)
if b64_match:
encoded = b64_match.group(1)
try:
decoded = base64.b64decode(encoded).decode('utf-16-le')
return decoded
except Exception:
return None
return None
def remove_tick_marks(script_content):
"""Remove PowerShell tick-mark obfuscation."""
# Remove backticks that are not escape sequences
escape_chars = {'`n', '`r', '`t', '`a', '`b', '`f', '`v', '`0', '``'}
result = []
i = 0
while i < len(script_content):
if script_content[i] == '`' and i + 1 < len(script_content):
pair = script_content[i:i+2]
if pair in escape_chars:
result.append(pair)
i += 2
else:
# Skip the backtick, keep the next char
result.append(script_content[i+1])
i += 2
else:
result.append(script_content[i])
i += 1
return ''.join(result)
def resolve_string_concat(script_content):
"""Resolve simple string concatenation patterns."""
# Pattern: 'str1' + 'str2'
pattern = re.compile(r"'([^']*)'\s*\+\s*'([^']*)'")
while pattern.search(script_content):
script_content = pattern.sub(lambda m: f"'{m.group(1)}{m.group(2)}'",
script_content)
# Pattern: "str1" + "str2"
pattern = re.compile(r'"([^"]*)"\s*\+\s*"([^"]*)"')
while pattern.search(script_content):
script_content = pattern.sub(lambda m: f'"{m.group(1)}{m.group(2)}"',
script_content)
return script_content
if __name__ == "__main__":
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} <powershell_script>")
sys.exit(1)
with open(sys.argv[1], 'r', errors='replace') as f:
content = f.read()
print("[+] Obfuscation Analysis")
print("=" * 60)
techniques = analyze_obfuscation(content)
for t in techniques:
print(f" - {t}")
# Attempt automatic deobfuscation
print("\n[+] Attempting Deobfuscation")
print("=" * 60)
# Layer 1: Remove tick marks
deobfuscated = remove_tick_marks(content)
# Layer 2: Resolve string concatenatiRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.