分析PowerShell腳本區塊記錄 是做什麼的?
使用時機
- 調查需要分析PowerShell腳本區塊記錄的安全事件時
- 為此領域建立偵測規則或威脅狩獵查詢時
- SOC分析師需要此分析類型的結構化程序時
- 驗證相關攻擊技術的安全監控涵蓋範圍時
先決條件
- 熟悉安全營運概念與工具
- 可安全執行的測試或實驗室環境
- Python 3.8+ 並安裝必要依賴項
- 測試活動的適當授權
指令
- 安裝依賴項:
pip install python-evtx lxml - 收集PowerShell操作日誌:
Microsoft-Windows-PowerShell%4Operational.evtx - 使用python-evtx解析Event ID 4104項目,提取ScriptBlockText、ScriptBlockId以及MessageNumber/MessageTotal以重建多區塊腳本。
- 套用偵測啟發式規則:
- Base64編碼命令(
-EncodedCommand、FromBase64String) - 下載連結(
DownloadString、DownloadFile、Invoke-WebRequest、Net.WebClient) - AMSI繞過模式(
AmsiUtils、amsiInitFailed) - 混淆指標(高熵、tick-mark插入、字串串接)
- Base64編碼命令(
- 生成包含重建腳本、風險評分及MITRE ATT&CK對應的報告。
python scripts/agent.py --evtx-file /path/to/PowerShell-Operational.evtx --output ps_analysis.json
範例
偵測編碼命令執行
import base64
if "-encodedcommand" in script_text.lower():
encoded = script_text.split()[-1]
decoded = base64.b64decode(encoded).decode("utf-16-le")
重建多區塊腳本
跨多個4104事件分割的腳本共享相同的 ScriptBlockId。依 MessageNumber 排序區塊後串接,即可還原完整腳本。