deobfuscating-powershell-obfuscated-malware
使用 AST 分析、动态追踪以及 PSDecode 和 PowerDecode 等工具,系统地对多层 PowerShell 恶意软件进行去混淆,以揭示隐藏的载荷和 C2 基础设施。
Best use case
deobfuscating-powershell-obfuscated-malware is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
使用 AST 分析、动态追踪以及 PSDecode 和 PowerDecode 等工具,系统地对多层 PowerShell 恶意软件进行去混淆,以揭示隐藏的载荷和 C2 基础设施。
Teams using deobfuscating-powershell-obfuscated-malware should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/deobfuscating-powershell-obfuscated-malware/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How deobfuscating-powershell-obfuscated-malware Compares
| Feature / Agent | deobfuscating-powershell-obfuscated-malware | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
使用 AST 分析、动态追踪以及 PSDecode 和 PowerDecode 等工具,系统地对多层 PowerShell 恶意软件进行去混淆,以揭示隐藏的载荷和 C2 基础设施。
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# 对混淆 PowerShell 恶意软件进行去混淆
## 概述
PowerShell 因其与 Windows 的深度集成和强大的脚本功能而被恶意软件作者大量滥用。混淆技术包括:字符串拼接、Base64 编码、字符替换、Invoke-Expression 分层、SecureString 滥用、环境变量操控和反引号插入。现代恶意软件使用多层混淆,需要迭代式去混淆。PSDecode、PowerDecode 和 PowerPeeler 等工具可以自动化大部分这一过程,而手动 AST(抽象语法树)分析则可以处理自定义混淆。PowerPeeler 通过对表达式相关 AST 节点进行指令级动态分析,实现了 95% 的去混淆正确率。
## 前置条件
- Python 3.9+,包含 `base64`、`re`、`subprocess` 模块
- PowerShell 5.1+ 或 PowerShell 7+(用于 AST 访问)
- PSDecode(`Install-Module PSDecode`)
- PowerDecode(https://github.com/Malandrone/PowerDecode)
- 用于安全脚本执行的隔离虚拟机或沙箱
- CyberChef,用于手动编码转换
- 理解 PowerShell AST 和 Invoke-Expression 模式
## 核心概念
### 常见混淆技术
PowerShell 恶意软件采用分层混淆来规避静态检测。字符串拼接将命令拆分到多个变量中(`$a='In'+'voke'`)。Base64 编码将整个脚本包装在 `-EncodedCommand` 参数中。字符代码数组使用 `[char]` 转换(`[char[]](73,69,88)|%{$r+=$_}`)。环境变量滥用从 `$env:` 路径中读取子字符串。反引号插入在 PowerShell 会忽略的字符之间添加反引号(``I`nv`oke-Exp`ression``)。SecureString 转换使用 ConvertTo-SecureString 配合嵌入的密钥加密字符串。
### 基于 AST 的去混淆
PowerShell 的抽象语法树暴露了脚本的解析结构,与表面层面的混淆无关。通过遍历 AST 并评估表达式节点,分析人员可以解析拼接的字符串、解码编码值并重建原始命令。PowerPeeler 在指令级别使用这种方法,监控执行过程以将 AST 节点与其评估结果相关联。
### 动态执行追踪
通过将 `Invoke-Expression`(IEX)替换为 `Write-Output`,分析人员可以安全地捕获通常会被执行的去混淆脚本内容。这种技术通过迭代替换 IEX 调用跨越多层工作,直到最终载荷被揭示。
## 操作步骤
### 步骤 1:识别混淆层
```python
#!/usr/bin/env python3
"""识别并分类 PowerShell 混淆技术。"""
import re
import base64
import sys
def analyze_obfuscation(script_content):
"""识别 PowerShell 脚本中使用的混淆技术。"""
techniques = []
# 检查 Base64 编码命令
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")
# 检查 FromBase64String
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"字符串拼接({concat_count} 次连接)")
# 检查字符数组构造
if re.search(r'\[char\]\s*\d+', script_content, re.IGNORECASE):
techniques.append("字符代码数组")
# 检查 Invoke-Expression 变体
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 变体:{pattern}")
# 检查反引号混淆
tick_count = script_content.count('`')
if tick_count > 5:
techniques.append(f"反引号插入({tick_count} 个反引号)")
# 检查环境变量滥用
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"环境变量滥用({len(env_refs)} 处引用)")
# 检查 SecureString
if re.search(r'ConvertTo-SecureString', script_content, re.IGNORECASE):
techniques.append("SecureString 加密")
# 检查压缩
if re.search(r'IO\.Compression|DeflateStream|GZipStream',
script_content, re.IGNORECASE):
techniques.append("压缩(Deflate/GZip)")
# 检查 XOR 编码
if re.search(r'-bxor\s+\d+', script_content, re.IGNORECASE):
techniques.append("XOR 编码")
# 检查 Replace 链
replace_count = len(re.findall(r'\.Replace\(', script_content))
if replace_count > 2:
techniques.append(f"Replace 链({replace_count} 次替换)")
return techniques
def decode_base64_command(script_content):
"""提取并解码 Base64 编码的命令。"""
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):
"""移除 PowerShell 反引号混淆。"""
# 移除非转义序列的反引号
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:
# 跳过反引号,保留下一个字符
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):
"""解析简单的字符串拼接模式。"""
# 模式:'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)
# 模式:"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"用法:{sys.argv[0]} <powershell_script>")
sys.exit(1)
with open(sys.argv[1], 'r', errors='replace') as f:
content = f.read()
print("[+] 混淆分析")
print("=" * 60)
techniques = analyze_obfuscation(content)
for t in techniques:
print(f" - {t}")
# 尝试自动去混淆
print("\n[+] 正在尝试去混淆")
print("=" * 60)
# 第 1 层:移除反引号
deobfuscated = remove_tick_marks(content)
# 第 2 层:解析字符串拼接
deobfuscated = resolve_string_concat(deobfuscated)
# 第 3 层:解码 Base64
b64_decoded = decode_base64_command(deobfuscated)
if b64_decoded:
print("[+] Base64 解码内容:")
print(b64_decoded[:2000])
deobfuscated = b64_decoded
print(f"\n[+] 去混淆后脚本长度:{len(deobfuscated)} 个字符")
output_file = sys.argv[1] + ".deobfuscated.ps1"
with open(output_file, 'w') as f:
f.write(deobfuscated)
print(f"[+] 已保存到 {output_file}")
```
### 步骤 2:多层 IEX 替换
```python
import subprocess
import tempfile
import os
def iex_replacement_deobfuscate(script_content, max_layers=10):
"""迭代地将 IEX 替换为 Write-Output 以解包各层。"""
# IEX 替换模式
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):
# 应用 IEX 替换
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" [+] 在第 {layer_num} 层未发现更多 IEX 层")
break
# 写入临时文件并在受限的 PowerShell 中执行
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=True, text=True, timeout=30
)
output = result.stdout.strip()
if output and output != current:
print(f" [+] 第 {layer_num + 1} 层:解包了 "
f"{len(output)} 个字符")
layers.append({
"layer": layer_num + 1,
"technique": "IEX 替换",
"content_length": len(output),
})
current = output
else:
break
except subprocess.TimeoutExpired:
print(f" [!] 第 {layer_num + 1} 层:执行超时")
break
finally:
os.unlink(tmp_path)
return current, layers
```
### 步骤 3:从去混淆后的脚本中提取 IoC
```python
def extract_iocs_from_script(deobfuscated_content):
"""从去混淆后的 PowerShell 中提取攻陷指标。"""
iocs = {
"urls": [],
"ips": [],
"domains": [],
"file_paths": [],
"registry_keys": [],
"commands": [],
"base64_blobs": [],
}
# URL
url_pattern = re.compile(
r'https?://[^\s\'"<>)\]]+', re.IGNORECASE
)
iocs["urls"] = list(set(url_pattern.findall(deobfuscated_content)))
# IP 地址
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', 'DownloadFile', 'DownloadData',
'Start-Process', 'Invoke-WebRequest',
'New-Object IO.MemoryStream',
'Reflection.Assembly',
'Add-MpPreference -ExclusionPath',
'Set-MpPreference -DisableRealtimeMonitoring',
'New-ScheduledTask', 'Register-ScheduledTask',
]
for cmd in suspicious_cmds:
if cmd.lower() in deobfuscated_content.lower():
iocs["commands"].append(cmd)
return iocs
```
## 验证标准
- 所有混淆层已被正确识别和分类
- Base64 编码的命令已解码为可读的 PowerShell
- 反引号和字符串拼接混淆已解析
- IEX 替换揭示了下一阶段的载荷
- 从最终去混淆阶段提取了 URL、IP 和文件路径
- 去混淆后的脚本与沙箱中观察到的恶意软件行为相符
## 参考资料
- [PSDecode - PowerShell 去混淆](https://github.com/R3MRUM/PSDecode)
- [PowerDecode - 多层去混淆](https://github.com/Malandrone/PowerDecode)
- [PowerPeeler - 指令级去混淆](https://arxiv.org/html/2406.04027v2)
- [SentinelOne - 解构 PowerShell 混淆](https://www.sentinelone.com/blog/deconstructing-powershell-obfuscation-in-malspam-campaigns/)
- [MITRE ATT&CK T1059.001 - PowerShell](https://attack.mitre.org/techniques/T1059/001/)Related Skills
reverse-engineering-rust-malware
使用 IDA Pro 和 Ghidra 对 Rust 编译的恶意软件进行逆向工程,掌握处理非空终止字符串、提取 crate 依赖项和 Rust 特有控制流分析的专项技术。
reverse-engineering-malware-with-ghidra
使用 NSA 的 Ghidra 反汇编器和反编译器对恶意软件二进制文件进行逆向工程,在汇编和伪 C 代码层面理解其内部逻辑、密码学例程、C2 协议和规避技术。适用于恶意软件逆向工程、反汇编分析、反编译、二进制分析或理解恶意软件内部机制等请求。
reverse-engineering-dotnet-malware-with-dnspy
使用 dnSpy 反编译器和调试器对 .NET 恶意软件进行逆向工程,分析 C#/VB.NET 源代码,识别混淆技术,提取配置信息,理解包括信息窃取器、远程访问木马(RAT)和加载器在内的恶意功能。适用于 .NET 恶意软件分析、C# 恶意软件反编译、托管代码逆向工程或 .NET 混淆分析等请求。
reverse-engineering-android-malware-with-jadx
使用 JADX 反编译器对恶意 Android APK 文件进行逆向工程,分析 Java/Kotlin 源代码,识别包括数据窃取、C2 通信、权限提升和覆盖攻击在内的恶意功能。检查 Manifest 权限、Receiver、Service 及原生库。适用于 Android 恶意软件分析、APK 逆向工程、移动端恶意软件调查或 Android 威胁分析等请求。
performing-static-malware-analysis-with-pe-studio
使用 PEStudio 对 Windows PE(可移植可执行文件)恶意软件样本进行静态分析, 检查文件头、导入表、字符串、资源和指标,无需执行二进制文件。 识别可疑特征,包括加壳、反分析技术和恶意导入。适用于静态恶意软件分析、 PE 文件检查、Windows 可执行文件分析或执行前恶意软件分级等请求场景。
performing-malware-triage-with-yara
使用 YARA 规则对文件模式、字符串、字节序列和结构特征进行匹配,快速分级和分类恶意软件样本, 识别已知恶意软件家族及可疑指标。涵盖规则编写、扫描和与分析流程的集成。适用于 YARA 规则创建、 恶意软件分类、模式匹配、样本分级或基于签名的检测等请求场景。
performing-malware-persistence-investigation
系统性地调查 Windows 和 Linux 系统上的所有持久化机制,以识别恶意软件如何在重启后存活并维持访问。
performing-malware-ioc-extraction
恶意软件 IOC(失陷指标)提取是指通过分析恶意软件,识别可操作的失陷指标,包括文件哈希、网络指标(C2 域名、IP 地址、URL)、注册表修改、互斥体名称、嵌入字符串和行为产物。
performing-malware-hash-enrichment-with-virustotal
使用 VirusTotal API 富化恶意软件文件哈希,获取检测率、行为分析、YARA 匹配和上下文威胁情报,用于事件分类和 IOC 验证。
performing-firmware-malware-analysis
分析固件镜像中嵌入的恶意软件、后门和未授权修改,目标包括路由器、IoT 设备、UEFI/BIOS 和嵌入式系统。涵盖固件提取、文件系统分析、二进制逆向工程和 Bootkit 检测。适用于固件安全 分析、IoT 恶意软件调查、UEFI Rootkit 检测或嵌入式设备入侵评估等请求场景。
performing-automated-malware-analysis-with-cape
部署和操作 CAPEv2 沙箱,进行自动化恶意软件分析,具备行为监控、载荷提取、配置解析和反规避能力。
hunting-for-anomalous-powershell-execution
通过分析脚本块日志(事件 4104)、模块日志(事件 4103)和进程创建事件,狩猎恶意 PowerShell 活动。 分析员解析 Windows 事件日志 EVTX 文件,检测混淆命令、AMSI 绕过尝试、编码 payload、 凭据转储关键词和可疑下载器(download cradles)。适用于涉及 PowerShell 威胁狩猎、脚本块分析、 编码命令检测或 AMSI 绕过识别的场景。