关于 performing-malware-persistence-investigation
面向事件响应人员和威胁猎手的安全调查技能,用于检查恶意软件如何在 Windows 和 Linux 系统中维持驻留。它覆盖注册表、任务、WMI、文件及启动机制,并指导汇总调查报告。
主要功能
- 01Windows 注册表持久化检查
- 02计划任务与 WMI 检查
- 03文件系统和启动项检查
- 04Linux 持久化机制检查
- 05汇总持久化调查报告
适用场景
- 01调查恶意软件重启后驻留方式
- 02事件响应中定位持久化机制
- 03威胁狩猎未授权自启动项
- 04验证清除持久化后的系统状态
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ mukul975/ anthropic-cybersecurity-skills --skill performing-malware-persistence-investigation安装后在 Claude Code 中输入/performing-malware-persistence-investigation确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
LICENSEreferences/api-reference.mdscripts/agent.py详细介绍
执行恶意软件持久化调查
何时使用
- 在调查恶意软件如何在系统重启后在被入侵系统中维持存在时
- 在事件响应期间识别所有持久化机制以实现完整修复
- 用于威胁狩猎,以发现端点上的未授权自启动项
- 在分析恶意软件行为以了解其持久化策略时
- 用于验证事件修复后所有持久化均已移除
前提条件
- 具有管理员权限的取证镜像或实时系统访问
- 用于 Windows 持久化枚举的 Autoruns(Sysinternals)
- 用于离线注册表分析的 RegRipper
- 了解 Windows 和 Linux 持久化机制
- 用于扫描持久化位置的 YARA 规则
- 用于比较的已知良好自启动项基线
工作流
步骤 1:枚举 Windows 注册表持久化
# Extract registry hives from forensic image
mount -o ro,loop,offset=$((2048*512)) /cases/case-2024-001/images/evidence.dd /mnt/evidence
# Key registry persistence locations
python3 << 'PYEOF'
from Registry import Registry
import json
results = {'registry_persistence': []}
# SYSTEM hive analysis
system_reg = Registry.Registry("/cases/case-2024-001/registry/SYSTEM")
select = system_reg.open("Select")
current = select.value("Current").value()
cs = f"ControlSet{current:03d}"
# Services (very common persistence)
services = system_reg.open(f"{cs}\\Services")
for svc in services.subkeys():
try:
start_type = svc.value("Start").value()
image_path = ""
try:
image_path = svc.value("ImagePath").value()
except:
pass
# Start types: 0=Boot, 1=System, 2=Auto, 3=Manual, 4=Disabled
if start_type in (0, 1, 2) and image_path:
svc_type = svc.value("Type").value() if svc.values() else 0
results['registry_persistence'].append({
'location': f'HKLM\\SYSTEM\\{cs}\\Services\\{svc.name()}',
'type': 'Service',
'value': image_path,
'start_type': start_type,
'timestamp': str(svc.timestamp())
})
except Exception:
pass
# SOFTWARE hive analysis
sw_reg = Registry.Registry("/cases/case-2024-001/registry/SOFTWARE")
# Machine Run keys
run_keys = [
"Microsoft\\Windows\\CurrentVersion\\Run",
"Microsoft\\Windows\\CurrentVersion\\RunOnce",
"Microsoft\\Windows\\CurrentVersion\\RunServices",
"Microsoft\\Windows\\CurrentVersion\\RunServicesOnce",
"Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\Run",
"Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Run",
"Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\RunOnce",
]
for key_path in run_keys:
try:
key = sw_reg.open(key_path)
for value in key.values():
results['registry_persistence'].append({
'location': f'HKLM\\SOFTWARE\\{key_path}',
'type': 'Run Key',
'name': value.name(),
'value': str(value.value()),
'timestamp': str(key.timestamp())
})
except Exception:
pass
# NTUSER.DAT analysis
import glob
for ntuser in glob.glob("/cases/case-2024-001/registry/NTUSER*.DAT"):
try:
user_reg = Registry.Registry(ntuser)
user_run_keys = [
"Software\\Microsoft\\Windows\\CurrentVersion\\Run",
"Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce",
"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\\Startup",
]
for key_path in user_run_keys:
try:
key = user_reg.open(key_path)
for value in key.values():
results['registry_persistence'].append({
'location': f'HKCU\\{key_path}',
'type': 'User Run Key',
'name': value.name(),
'value': str(value.value()),
'timestamp': str(key.timestamp()),
'hive': ntuser
})
except Exception:
pass
except Exception:
pass
print(f"Total registry persistence entries: {len(results['registry_persistence'])}")
for entry in results['registry_persistence']:
print(f" [{entry['type']}] {entry.get('name', '')} -> {entry.get('value', '')[:100]}")
with open('/cases/case-2024-001/analysis/registry_persistence.json', 'w') as f:
json.dump(results, f, indent=2)
PYEOF
步骤 2:检查计划任务和 WMI 持久化
# Extract scheduled tasks from forensic image
mkdir -p /cases/case-2024-001/persistence/tasks/
cp -r /mnt/evidence/Windows/System32/Tasks/* /cases/case-2024-001/persistence/tasks/ 2>/dev/null
# Parse scheduled task XML files
python3 << 'PYEOF'
import os, xml.etree.ElementTree as ET
tasks_dir = '/cases/case-2024-001/persistence/tasks/'
suspicious_tasks = []
for root_dir, dirs, files in os.walk(tasks_dir):
for fname in files:
fpath = os.path.join(root_dir, fname)
try:
tree = ET.parse(fpath)
root = tree.getroot()
ns = {'t': 'http://schemas.microsoft.com/windows/2004/02/mit/task'}
actions = root.findall('.//t:Exec', ns)
for action in actions:
command = action.find('t:Command', ns)
args = action.find('t:Arguments', ns)
cmd_text = command.text if command is not None else ''
args_text = args.text if args is not None else ''
# Flag suspicious commands
suspicious_indicators = [
'powershell', 'cmd.exe', 'wscript', 'cscript', 'mshta',
'regsvr32', 'rundll32', 'certutil', 'bitsadmin',
'/c ', '-enc', '-e ', 'hidden', 'bypass', 'downloadstring',
'invoke-', 'iex', '/tmp/', 'appdata', 'programdata',
'temp\\', '.ps1', '.vbs', '.hta', 'base64'
]
is_suspicious = any(s in (cmd_text + ' ' + args_text).lower() for s in suspicious_indicators)
task_info = {
'name': fname,
'path': fpath.replace(tasks_dir, ''),
'command': cmd_text,
'arguments': args_text,
'suspicious': is_suspicious
}
if is_suspicious:
suspicious_tasks.append(task_info)
print(f"SUSPICIOUS TASK: {fname}")
print(f" Command: {cmd_text}")
print(f" Arguments: {args_text}")
print()
except Exception as e:
pass
print(f"\nTotal suspicious scheduled tasks: {len(suspicious_tasks)}")
PYEOF
# Check WMI event subscriptions (common APT persistence)
# WMI repository: C:\Windows\System32\wbem\Repository\
cp -r /mnt/evidence/Windows/System32/wbem/Repository/ /cases/case-2024-001/persistence/wmi/ 2>/dev/null
# Parse WMI persistence using PyWMIPersistenceFinder
python3 << 'PYEOF'
import os, re
# Search WMI OBJECTS.DATA for event subscriptions
wmi_db = '/cases/case-2024-001/persistence/wmi/OBJECTS.DATA'
if os.path.exists(wmi_db):
with open(wmi_db, 'rb') as f:
data = f.read()
# Search for EventFilter strings
filters = re.findall(b'__EventFilter.*?(?=\x00\x00)', data)
consumers = re.findall(b'CommandLineEventConsumer.*?(?=\x00\x00)', data)
bindings = re.findall(b'__FilterToConsumerBinding.*?(?=\x00\x00)', data)
print("=== WMI PERSISTENCE ===")
print(f"Event Filters: {len(filters)}")
print(f"Command Consumers: {len(consumers)}")
print(f"Filter-Consumer Bindings: {len(bindings)}")
for consumer in consumers:
decoded = consumer.decode('utf-8', errors='ignore')
print(f" Consumer: {decoded[:200]}")
else:
print("WMI repository not found")
PYEOF
步骤 3:检查文件系统和启动持久化
# Startup folders
echo "=== STARTUP FOLDER CONTENTS ===" > /cases/case-2024-001/analysis/startup_items.txt
ls -la "/mnt/evidence/ProgramData/Microsoft/Windows/Start Menu/Programs/Startup/" \
>> /cases/case-2024-001/analysis/startup_items.txt 2>/dev/null
for userdir in /mnt/evidence/Users/*/; do
username=$(basename "$userdir")
echo "--- User: $username ---" >> /cases/case-2024-001/analysis/startup_items.txt
ls -la "$userdir/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup/" \
>> /cases/case-2024-001/analysis/startup_items.txt 2>/dev/null
done
# Check DLL search order hijacking locations
echo "=== DLL HIJACKING CHECK ===" > /cases/case-2024-001/analysis/dll_hijack.txt
# Check for DLLs in application directories that should only be in System32
find /mnt/evidence/Program\ Files/ /mnt/evidence/Program\ Files\ \(x86\)/ \
-name "*.dll" -newer /mnt/evidence/Windows/System32/ntdll.dll 2>/dev/null \
>> /cases/case-2024-001/analysis/dll_hijack.txt
# Check for COM object hijacking
python3 << 'PYEOF'
from Registry import Registry
reg = Registry.Registry("/cases/case-2024-001/registry/SOFTWARE")
# Check for suspicious CLSID entries
try:
clsid = reg.open("Classes\\CLSID")
for key in clsid.subkeys():
try:
server = key.subkey("InprocServer32")
dll_path = server.value("(default)").value()
if any(s in dll_path.lower() for s in ['temp', 'appdata', 'programdata', 'downloads', 'tmp']):
print(f"SUSPICIOUS COM: {key.name()} -> {dll_path}")
except:
pass
except:
pass
PYEOF
# Check boot configuration for bootkits
# BCD (Boot Configuration Data)
ls -la /mnt/evidence/Boot/BCD 2>/dev/null
# Check for modified bootmgr or winload.exe
sha256sum /mnt/evidence/Windows/System32/winload.exe 2>/dev/null
步骤 4:检查 Linux 持久化机制
# If analyzing a Linux system
LINUX_ROOT="/mnt/evidence"
echo "=== LINUX PERSISTENCE CHECK ===" > /cases/case-2024-001/analysis/linux_persistence.txt
# Cron jobs
echo "--- Cron Jobs ---" >> /cases/case-2024-001/analysis/linux_persistence.txt
cat $LINUX_ROOT/etc/crontab >> /cases/case-2024-001/analysis/linux_persistence.txt 2>/dev/null
ls -la $LINUX_ROOT/etc/cron.d/ >> /cases/case-2024-001/analysis/linux_persistence.txt 2>/dev/null
cat $LINUX_ROOT/etc/cron.d/* >> /cases/case-2024-001/analysis/linux_persistence.txt 2>/dev/null
cat $LINUX_ROOT/var/spool/cron/crontabs/* >> /cases/case-2024-001/analysis/linux_persistence.txt 2>/dev/null
# Systemd services
echo "--- Custom Systemd Services ---" >> /cases/case-2024-001/analysis/linux_persistence.txt
find $LINUX_ROOT/etc/systemd/system/ -name "*.service" -not -type l \
>> /cases/case-2024-001/analysis/linux_persistence.txt 2>/dev/null
# SSH authorized keys
echo "--- SSH Authorized Keys ---" >> /cases/case-2024-001/analysis/linux_persistence.txt
find $LINUX_ROOT/home/ $LINUX_ROOT/root/ -name "authorized_keys" -exec cat {} \; \
>> /cases/case-2024-001/analysis/linux_persistence.txt 2>/dev/null
# Init scripts and rc.local
echo "--- RC Scripts ---" >> /cases/case-2024-001/analysis/linux_persistence.txt
cat $LINUX_ROOT/etc/rc.local >> /cases/case-2024-001/analysis/linux_persistence.txt 2>/dev/null
# Shell profile scripts
echo "--- Profile Scripts ---" >> /cases/case-2024-001/analysis/linux_persistence.txt
cat $LINUX_ROOT/etc/profile.d/*.sh >> /cases/case-2024-001/analysis/linux_persistence.txt 2>/dev/null
# LD_PRELOAD
echo "--- LD_PRELOAD ---" >> /cases/case-2024-001/analysis/linux_persistence.txt
cat $LINUX_ROOT/etc/ld.so.preload >> /cases/case-2024-001/analysis/linux_persistence.txt 2>/dev/null
grep -r "LD_PRELOAD" $LINUX_ROOT/etc/ >> /cases/case-2024-001/analysis/linux_persistence.txt 2>/dev/null
# Kernel modules
echo "--- Loaded Kernel Modules ---" >> /cases/case-2024-001/analysis/linux_persistence.txt
cat $LINUX_ROOT/etc/modules-load.d/*.conf >> /cases/case-2024-001/analysis/linux_persistence.txt 2>/dev/null
# PAM backdoors
echo "--- PAM Configuration ---" >> /cases/case-2024-001/analysis/linux_persistence.txt
find $LINUX_ROOT/etc/pam.d/ -exec grep -l "pam_exec\|pam_script" {} \; \
>> /cases/case-2024-001/analysis/linux_persistence.txt 2>/dev/null
步骤 5:编制持久化报告
# Generate comprehensive persistence report
python3 << 'PYEOF'
import json
with open('/cases/case-2024-001/analysis/registry_persistence.json') as f:
reg_data = json.load(f)
report = """
MALWARE PERSISTENCE INVESTIGATION REPORT
==========================================
PERSISTENCE MECHANISMS FOUND:
1. REGISTRY RUN KEYS:
"""
run_keys = [e for e in reg_data['registry_persistence'] if 'Run' in e.get('type', '')]
for entry in run_keys:
report += f" [{entry['timestamp']}] {entry.get('name', 'N/A')} -> {entry.get('value', '')[:100]}\n"
services = [e for e in reg_data['registry_persistence'] if e.get('type') == 'Service']
report += f"\n2. SERVICES ({len(services)} auto-start services):\n"
for entry in services[:20]:
report += f" {entry['location'].split('\\')[-1]}: {entry['value'][:100]}\n"
report += """
3. SCHEDULED TASKS: [See scheduled_tasks analysis]
4. WMI SUBSCRIPTIONS: [See WMI analysis]
5. STARTUP FOLDER: [See startup_items.txt]
6. COM HIJACKING: [See COM analysis]
SUSPICIOUS ENTRIES REQUIRING INVESTIGATION:
"""
# Flag suspicious entries
for entry in reg_data['registry_persistence']:
value = str(entry.get('value', '')).lower()
suspicious_indicators = ['powershell', 'cmd /c', 'wscript', 'certutil',
'programdata', 'appdata\\local\\temp', 'base64',
'.ps1', '.vbs', '.hta', '/tmp/', 'hidden']
if any(s in value for s in suspicious_indicators):
report += f" SUSPICIOUS: {entry.get('name', 'N/A')} -> {entry.get('value', '')[:100]}\n"
with open('/cases/case-2024-001/analysis/persistence_report.txt', 'w') as f:
f.write(report)
print(report)
PYEOF
关键概念
| 概念 | 描述 |
|---|---|
| Run 键 | 用户登录时执行程序的注册表键(HKLM 和 HKCU) |
| 计划任务 | 在触发器(时间、事件、登录)上执行的 Windows 任务计划程序条目 |
| WMI 事件订阅 | 触发操作的持久 WMI 查询(隐蔽持久化) |
| COM 劫持 | 重定向 COM 对象加载以执行恶意 DLL |
| DLL 搜索顺序劫持 | 将恶意 DLL 放置在优先于 System32 搜索的目录中 |
| 服务持久化 | 安装随系统自动启动的 Windows 服务 |
| 启动级持久化 | 修改启动配置或 MBR/VBR 以实现操作系统前执行 |
| 就地取材 | 使用合法系统工具(PowerShell、WMI、certutil)进行持久化 |
工具与系统
| 工具 | 用途 |
|---|---|
| Autoruns | Sysinternals 全面的自启动枚举工具 |
| RegRipper | 自动化注册表持久化痕迹提取 |
| KAPE | 自动化持久化痕迹收集与分析 |
| Velociraptor | 具有持久化狩猎痕迹的端点 Agent |
| OSQuery | 用于持久化枚举的基于 SQL 的系统查询 |
| PersistenceSniper | 用于 Windows 持久化检测的 PowerShell 工具 |
| RECmd | Eric Zimmerman 注册表命令行分析工具 |
| Volatility | 用于仅内存持久化的内存取证 |
常见场景
场景 1:初始入侵后的 APT 持久化 检查所有注册表 Run 键,枚举计划任务中的编码 PowerShell 命令,检查 WMI 事件订阅以发现事件触发执行,检查 COM 对象注册以发现被劫持的 CLSID,审查服务以发现最近安装的具有可疑映像路径的条目。
场景 2:勒索软件加密前持久化 识别勒索软件如何维持访问以进行重新加密或监控,检查会重新启动加密的计划任务,检查勒索软件操作者安装的服务,在宣布修复完成前验证不存在额外的后门持久化。
场景 3:无文件恶意软件持久化 专注于将有效载荷存储在注册表值中的基于注册表的持久化,检查从事件触发器执行 PowerShell 的 WMI 订阅,检查使用编码命令参数的计划任务,检查基于 mshta/rundll32 加载远程内容的持久化。
场景 4:修复后验证 运行 Autoruns 与已知良好基线的比较,验证所有已识别的持久化机制均已移除,检查可能被遗漏的额外持久化,确认服务、任务和注册表条目干净,监控再感染指标。
输出格式
Persistence Investigation Summary:
System: DESKTOP-ABC123 (Windows 10 Pro)
Analysis Date: 2024-01-20
Persistence Mechanisms Found:
Registry Run Keys (HKLM): 5 entries (1 SUSPICIOUS)
Registry Run Keys (HKCU): 3 entries (1 SUSPICIOUS)
Services (Auto-Start): 142 entries (2 SUSPICIOUS)
Scheduled Tasks: 67 entries (3 SUSPICIOUS)
WMI Subscriptions: 1 entry (SUSPICIOUS)
Startup Folder: 4 items (1 SUSPICIOUS)
COM Objects: 0 hijacked entries
DLL Hijacking: 0 detected
Suspicious Entries:
1. HKCU\Run\WindowsUpdate -> powershell -ep bypass -e <base64>
Timestamp: 2024-01-15 14:35:00
Action: Encoded PowerShell download cradle
2. Service: WinDefenderUpdate -> C:\ProgramData\svc\update.exe
Timestamp: 2024-01-15 14:40:00
Action: Unknown executable in ProgramData
3. Task: \Microsoft\Windows\Maintenance\SecurityUpdate
Command: cmd.exe /c powershell -w hidden -e <base64>
Trigger: On system startup
4. WMI: __EventFilter "ProcessStart" -> CommandLineEventConsumer
Action: Execute C:\Windows\Temp\svc.exe on WMI event
Remediation Required: 4 persistence mechanisms to remove
Report: /cases/case-2024-001/analysis/persistence_report.txt
评论
支持 Markdown