Analyzing PowerShell Script Block Logging
When to Use
- 当调查安全事件并需要分析 powershell script block logging 时
- 当为该领域构建检测规则或威胁狩猎查询时
- 当 SOC 分析师需要此类分析的结构化流程时
- 当验证相关攻击技术的安全监控覆盖范围时
Prerequisites
- 熟悉安全运营相关概念与工具
- 拥有可安全执行的测试或实验环境
- 已安装 Python 3.8+ 及所需依赖
- 获得对任何测试活动的相应授权
Instructions
- 安装依赖:
pip install python-evtx lxml
- 收集 PowerShell Operational 日志:
Microsoft-Windows-PowerShell%4Operational.evtx
- 使用 python-evtx 解析 Event ID 4104 条目,提取 ScriptBlockText、ScriptBlockId 以及 MessageNumber/MessageTotal,以便进行多段脚本重建。
- 应用检测启发式规则:
- Base64 编码命令(
-EncodedCommand、FromBase64String)
- 下载 cradle(
DownloadString、DownloadFile、Invoke-WebRequest、Net.WebClient)
- AMSI 绕过模式(
AmsiUtils、amsiInitFailed)
- 混淆指标(高熵、反引号插入、字符串拼接)
- 生成报告,包含重建后的脚本、风险评分以及 MITRE ATT&CK 映射。
python scripts/agent.py --evtx-file /path/to/PowerShell-Operational.evtx --output ps_analysis.json
Examples
Detect Encoded Command Execution
import base64
if "-encodedcommand" in script_text.lower():
encoded = script_text.split()[-1]
decoded = base64.b64decode(encoded).decode("utf-16-le")
Reconstruct Multi-Block Script
跨多个 4104 事件拆分的脚本共享同一个 ScriptBlockId。按 …