应急响应实战:从日志分析到威胁清除(附完整排查脚本与工具箱)
【提示】 本文所有技术内容仅用于授权测试、安全学习和合规的安全运维场景。未经授权对他人系统进行渗透测试或应急响应操作可能违反《网络安全法》《数据安全法》等相关法律法规。请在合法授权范围内使用本文所述技术。
一、应急响应概述与重要性
1.1 什么是应急响应
应急响应(Incident Response, IR)是指当安全事件发生时,组织为了识别、遏制、根除和恢复系统而采取的一系列结构化行动。它不仅仅是"被黑了去查日志",而是一套包含准备、检测、分析、遏制、根除、恢复和总结的完整方法论。
在当今威胁环境下,攻击者从初始访问到完成横向移动的平均时间已缩短至数小时甚至数十分钟。根据IBM的年度数据泄露报告,包含高效应急响应团队和广泛自动化部署的组织,平均数据泄露成本比低效组织低数百万美元。应急响应能力已经成为企业安全建设的核心能力之一。
1.2 为什么应急响应如此重要
| 维度 | 说明 |
|---|---|
| 减少损失 | 快速遏制可将数据泄露影响范围降低60%以上 |
| 合规要求 | 等保2.0、ISO27001、PCI DSS均要求具备应急响应能力 |
| 取证需求 | 规范的应急响应流程为后续法律诉讼提供证据链 |
| 业务连续性 | 快速恢复保障业务可用性,减少停机时间 |
| 信誉维护 | 及时响应降低品牌信誉损失和客户流失 |
【提示】 根据我国《网络安全法》第二十五条,网络运营者应当制定网络安全事件应急预案,及时处置系统漏洞、计算机病毒、网络攻击、网络侵入等安全风险。不制定应急预案的最高可处十万元以上一百万元以下罚款。
1.3 应急响应 vs 应急响应工程
DFIR(Digital Forensics and Incident Response)是数字取证与应急响应的合称。两者既有联系又有区别:
| 对比项 | IR(应急响应) | DFIR(数字取证与应急响应) |
|---|---|---|
| 目标 | 快速遏制和恢复 | 取证级证据保全与分析 |
| 时间要求 | 极速响应,争分夺秒 | 可接受较长时间深入分析 |
| 证据要求 | 满足内部决策即可 | 满足法律诉讼证据标准 |
| 操作限制 | 可修改系统状态 | 尽量不改变原始状态 |
| 输出 | 处置报告 | 司法级取证报告 |
二、应急响应方法论
2.1 NIST SP 800-61 框架
NIST SP 800-61《计算机安全事件处理指南》是业界最广泛参考的应急响应框架,将应急响应生命周期分为六个阶段:
阶段一:准备
在安全事件发生前做好人员和工具的准备工作。包括建立应急响应团队、制定应急预案、部署监控工具、进行培训演练等。准备阶段是整个应急响应的基础,决定了事件发生时的响应速度。
阶段二:检测与分析
通过安全设备告警、日志分析、用户报告等渠道发现可疑活动。此阶段需要快速判断是否为真实安全事件,评估事件的严重程度和影响范围。检测的准确性和速度直接决定后续处置的效果。
阶段三:遏制
采取措施限制攻击的扩散和深入。遏制分为短期遏制(如断网隔离受影响主机)和长期遏制(如清除后门)。遏制策略需要平衡业务连续性和安全控制的需求。
阶段四:根除
彻底清除攻击者在系统中留下的后门、恶意文件、异常账号等。根除阶段需要全面排查,避免遗漏导致攻击者再次进入。
阶段五:恢复
将系统恢复到正常运行状态。包括从干净备份恢复、重建系统、验证系统完整性等。恢复阶段需要持续监控,确保攻击者没有重新进入。
阶段六:总结
事件处置完成后进行复盘,编写事件报告,总结经验教训,改进安全策略和应急预案。总结阶段是持续改进应急响应能力的关键。
2.2 SANS PICERL 模型
SANS学院提出的PICERL模型将应急响应分为六个阶段,与NIST框架高度一致但更注重实践:
| 阶段 | 名称 | 核心任务 |
|---|---|---|
| P | Preparation 准备 | 团队建设、工具部署、预案演练 |
| I | Identification 识别 | 告警分析、事件确认、影响评估 |
| C | Containment 遏制 | 短期隔离、长期遏制策略制定 |
| E | Eradication 根除 | 清除恶意软件、后门、异常账号 |
| R | Recovery 恢复 | 系统恢复、业务验证、持续监控 |
| L | Lessons learned 总结 | 报告编写、流程改进、培训提升 |
2.3 应急响应流程图
以下是应急响应的标准流程(文字描述版):
安全事件发生
|
v
告警触发(SIEM/EDR/IDS/用户报告)
|
v
初步判断 --> 误报? --是--> 关闭工单,记录归档
|
否
|
v
事件分级(严重/高/中/低)
|
v
启动应急预案,通知IR团队
|
v
检测分析(日志/内存/流量取证)
|
v
遏制隔离(断网/封禁IP/停用账号)
|
v
根除威胁(清后门/杀进程/删文件)
|
v
系统恢复(重建/恢复备份/加固)
|
v
持续监控(72小时观察期)
|
v
总结复盘(报告编写/流程改进)
2.4 应急响应团队角色
一个完整的应急响应团队需要以下角色分工:
| 角色 | 职责 | 技能要求 |
|---|---|---|
| 事件指挥官 | 统筹协调,决策指挥 | 全局视野,决策能力 |
| 安全分析师 | 日志分析,威胁研判 | 日志分析,威胁情报 |
| 取证专家 | 取证保全,证据链管理 | 取证工具,法律知识 |
| 恶意代码分析师 | 恶意软件逆向分析 | 逆向工程,编程能力 |
| 系统管理员 | 系统操作,隔离恢复 | 系统运维,网络配置 |
| 沟通协调员 | 内外部沟通,上报通报 | 沟通能力,公关能力 |
| 法务顾问 | 法律合规,证据效力 | 法律法规,合规要求 |
2.5 应急响应工具箱清单
以下是一个标准的应急响应工具箱应包含的工具:
Windows工具:
| 工具 | 用途 |
|---|---|
| Autoruns | 自启动项分析 |
| Process Explorer | 进程分析 |
| TCPView | 网络连接分析 |
| Wireshark | 流量抓取分析 |
| Volatility | 内存取证 |
| Redline | 主机取证 |
| KAPE | 快速取证 |
| LogParser | 日志分析 |
| Sysinternals Suite | 系统工具集 |
| RegShot | 注册表快照对比 |
Linux工具:
| 工具 | 用途 |
|---|---|
| chkrootkit | Rootkit检测 |
| rkhunter | Rootkit检测 |
| lsof | 文件与进程关联 |
| netstat/ss | 网络连接分析 |
| strace | 系统调用追踪 |
| auditd | 审计日志 |
| tcpdump | 流量抓取 |
| LiME | 内存镜像 |
| The Sleuth Kit | 磁盘取证 |
| busybox | 应急工具箱 |
三、Windows应急响应
3.1 Windows日志体系详解
Windows日志体系是Windows应急响应的核心。主要的日志来源包括以下几类:
System日志: 记录系统组件的事件,如服务启动失败、驱动加载、系统错误等。事件来源标记为"System",对于排查恶意服务、驱动级Rootkit非常重要。
Security日志: 记录安全相关事件,包括登录认证、账号管理、权限使用、策略更改等。这是应急响应中最核心的日志来源,几乎所有入侵行为都会在此留下痕迹。
Application日志: 记录应用程序事件,某些恶意软件会以服务形式运行,可能在此日志中留下错误信息或行为记录。
Sysmon日志: Sysinternals出品的Sysmon(System Monitor)是应急响应利器,可记录进程创建、网络连接、文件创建、注册表修改等细粒度行为,是检测高级威胁的关键工具。
PowerShell日志: 包括模块日志记录(Module Logging,事件ID 4103)、脚本块日志记录(Script Block Logging,事件ID 4104)、转录日志(Transcription)等,对于检测无文件攻击至关重要。
WinRM日志: 记录远程管理操作,攻击者通过WinRM进行横向移动时会在此留下痕迹。
Task Scheduler日志: 记录计划任务操作,攻击者常用计划任务实现持久化。
3.2 关键事件ID速查表
以下是Windows应急响应中最关键的事件ID:
| 事件ID | 日志来源 | 含义 | 应急关注点 |
|---|---|---|---|
| 4624 | Security | 成功登录 | 关注登录类型(10远程/3本地)、来源IP |
| 4625 | Security | 登录失败 | 爆破特征,大量失败后成功 |
| 4648 | Security | 使用显式凭据登录 | 可能是横向移动 |
| 4663 | Security | 对象访问 | 敏感文件/注册表被访问 |
| 4672 | Security | 特权用户登录 | 管理员登录监控 |
| 4688 | Security | 进程创建 | 关注可疑进程链,需开启命令行审计 |
| 4698 | Security | 计划任务创建 | 持久化检测 |
| 4720 | Security | 用户账号创建 | 异常建号 |
| 4722 | Security | 用户账号启用 | 被禁用账号激活 |
| 4732 | Security | 成员加入安全组 | 提权行为 |
| 4738 | Security | 用户账号修改 | 账号属性变更 |
| 7045 | System | 服务安装 | 恶意服务创建 |
| 7036 | System | 服务状态变更 | 服务启停监控 |
| 1 | Sysmon | 进程创建 | 进程树分析 |
| 3 | Sysmon | 网络连接 | 异常外联 |
| 7 | Sysmon | 模块加载 | DLL注入检测 |
| 8 | Sysmon | 远程线程创建 | 进程注入 |
| 11 | Sysmon | 文件创建 | 恶意文件落地 |
| 13 | Sysmon | 注册表值设置 | 持久化检测 |
| 22 | Sysmon | DNS查询 | C2域名检测 |
| 255 | Sysmon | 错误 | Sysmon异常 |
| 4104 | PowerShell | 脚本块执行 | 无文件攻击检测 |
| 4103 | PowerShell | 模块执行 | 命令记录 |
| 400 | PowerShell | 引擎状态 | PowerShell启动 |
| 800 | PowerShell | 脚本块执行(管道) | 命令内容 |
3.3 日志分析方法
方法一:Event Viewer图形界面
通过eventvwr.msc打开事件查看器,可手动浏览各日志。适合初步查看和定向检索。支持筛选当前日志、创建自定义视图。
方法二:wevtutil命令行工具
rem 导出Security日志
wevtutil epl Security C:\ir\Security.evtx
rem 导出最近24小时System日志
wevtutil epl System C:\ir\System.evtx /q:"*[System[TimeCreated[timediff(@SystemTime) <= 86400000]]]"
rem 查询所有日志名称
wevtutil el > C:\ir\all_logs.txt
rem 查询指定日志的元数据
wevtutil gli Security
方法三:PowerShell Get-WinEvent
# 查询最近24小时的安全日志中所有登录事件(4624/4625)
$events = Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4624,4625; StartTime=(Get-Date).AddDays(-1)} -MaxEvents 1000
# 查询所有4688进程创建事件,提取进程命令行
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4688} -MaxEvents 500 |
Select-Object TimeCreated, @{Name='Process';Expression={$_.Properties[5].Value}}, @{Name='CommandLine';Expression={$_.Properties[8].Value}} |
Format-Table -AutoSize
# 查询Sysmon进程创建事件(事件ID 1)
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Sysmon/Operational'; Id=1} -MaxEvents 200 |
ForEach-Object {
$xml = [xml]$_.ToXml()
[PSCustomObject]@{
Time = $_.TimeCreated
Image = $xml.Event.EventData.Data | Where-Object {$_.Name -eq 'Image'} | Select-Object -ExpandProperty '#text'
CommandLine = $xml.Event.EventData.Data | Where-Object {$_.Name -eq 'CommandLine'} | Select-Object -ExpandProperty '#text'
Parent = $xml.Event.EventData.Data | Where-Object {$_.Name -eq 'ParentImage'} | Select-Object -ExpandProperty '#text'
}
} | Format-Table -AutoSize
# 统计登录失败IP排行(爆破检测)
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4625} -MaxEvents 10000 |
ForEach-Object {
$xml = [xml]$_.ToXml()
$ip = ($xml.Event.EventData.Data | Where-Object {$_.Name -eq 'IpAddress'}).'#text'
$ip
} | Group-Object | Sort-Object Count -Descending | Select-Object -First 20 Count, Name
# 查询所有服务安装事件(7045)- 恶意服务检测
Get-WinEvent -FilterHashtable @{LogName='System'; Id=7045} -MaxEvents 100 |
Select-Object TimeCreated, @{Name='ServiceName';Expression={$_.Properties[0].Value}}, @{Name='ImagePath';Expression={$_.Properties[1].Value}} |
Format-Table -AutoSize
方法四:LogParser(经典日志分析工具)
rem 统计登录失败次数最多的IP
LogParser.exe "SELECT EXTRACT_TOKEN(Strings,19,'|') AS SourceIP, COUNT(*) AS Attempts FROM Security WHERE EventID=4625 GROUP BY SourceIP ORDER BY Attempts DESC" -i:EVT -o:DATAGRID
rem 查找所有PowerShell执行事件
LogParser.exe "SELECT TimeGenerated, EXTRACT_TOKEN(Strings,3,'|') AS User, EXTRACT_TOKEN(Strings,10,'|') AS Command FROM Security WHERE EventID=4688 AND EXTRACT_TOKEN(Strings,5,'|') LIKE '%powershell%'" -i:EVT -o:DATAGRID
rem 统计各事件ID出现次数
LogParser.exe "SELECT EventID, COUNT(*) AS Count FROM Security GROUP BY EventID ORDER BY Count DESC" -i:EVT -o:CSV > event_stats.csv
rem 查找特定时间段的登录事件
LogParser.exe "SELECT TimeGenerated, EXTRACT_TOKEN(Strings,5,'|') AS LogonType, EXTRACT_TOKEN(Strings,12,'|') AS SourceIP FROM Security WHERE EventID=4624 AND TimeGenerated BETWEEN TIMESTAMP('2026-08-19 00:00:00','yyyy-MM-dd hh:mm:ss') AND TIMESTAMP('2026-08-19 23:59:59','yyyy-MM-dd hh:mm:ss')" -i:EVT -o:DATAGRID
3.4 PowerShell日志分析
现代攻击大量使用PowerShell实现无文件攻击,因此PowerShell日志分析至关重要。
首先需要开启PowerShell日志记录:
# 开启脚本块日志记录(事件ID 4104)
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name "EnableScriptBlockLogging" -Value 1
# 开启模块日志记录(事件ID 4103)
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging" -Name "EnableModuleLogging" -Value 1
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging" -Name "ModuleNames" -Value "*"
# 开启PowerShell转录日志
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription" -Name "EnableTranscripting" -Value 1
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription" -Name "OutputDirectory" -Value "C:\PSTranscripts"
分析PowerShell恶意执行特征的常见模式:
# 检测编码命令执行(Base64)
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'; Id=4104} |
Where-Object { $_.Message -match 'FromBase64String|EncodedCommand|-enc\s+-|-e\s+' } |
Select-Object TimeCreated, Message
# 检测下载执行(典型无文件攻击模式)
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'; Id=4104} |
Where-Object { $_.Message -match 'DownloadString|DownloadFile|Invoke-WebRequest|iex|Invoke-Expression|Net.WebClient|Start-BitsTransfer' } |
Select-Object TimeCreated, Message
# 检测混淆脚本
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'; Id=4104} |
Where-Object { $_.Message -match 'Join-Path|Char|FromBase64String|-replace|Format-String|Reverse' } |
Select-Object TimeCreated, Message
# 提取所有4104事件中的脚本内容并保存
$events = Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'; Id=4104} -MaxEvents 500
foreach ($event in $events) {
$scriptBlock = $event.Properties[0].Value
if ($scriptBlock -match 'http|exe|dll|base64|iex|download') {
Write-Output "[$($event.TimeCreated)] $scriptBlock"
Write-Output "----------------------------------------------"
}
}
3.5 常见入侵痕迹排查清单
| 排查项 | 检查方法 | 异常指标 |
|---|---|---|
| 异常账号 | net user / lusrmgr.msc / 事件ID 4720 | 新建账号、隐藏账号($结尾)、Guest启用 |
| 异常进程 | Task Manager / Process Explorer / tasklist | 无数字签名的进程、伪装系统进程名 |
| 异常网络连接 | netstat -ano / TCPView / Sysmon事件3 | 异常外联IP、非常用端口、C2端口 |
| 异常服务 | services.msc / sc query / 事件ID 7045 | 无描述服务、可疑路径服务 |
| 异常计划任务 | schtasks /query / 任务计划程序 | 未知任务、PowerShell/CMD计划任务 |
| 异常启动项 | Autoruns / msconfig | 注册表启动项、启动文件夹 |
| 异常文件 | 文件时间戳分析 / 数字签名验证 | 近期创建的可执行文件、无签名文件 |
| 异常注册表 | Autoruns / reg query | Run键、Image File Execution Options |
| 异常DLL | listdlls / Process Explorer | 注入到系统进程的未知DLL |
| 异常WMI | wmic / WMI事件订阅 | __EventFilter、__EventConsumer |
四、Linux应急响应
4.1 Linux日志体系
Linux系统日志体系是排查入侵行为的重要信息来源,主要日志文件如下:
| 日志文件 | 说明 | 内容 |
|---|---|---|
| /var/log/messages | 通用系统日志 | 服务启停、系统错误(CentOS/RHEL) |
| /var/log/syslog | 通用系统日志 | 服务启停、系统错误(Debian/Ubuntu) |
| /var/log/secure | 安全日志 | SSH登录、su/sudo、用户管理 |
| /var/log/auth.log | 认证日志 | SSH登录、su/sudo(Debian/Ubuntu) |
| /var/log/audit/audit.log | 审计日志 | 内核级审计,细粒度行为记录 |
| /var/log/wtmp | 登录记录 | 成功登录历史(二进制) |
| /var/log/btmp | 登录失败记录 | 失败登录历史(二进制) |
| /var/log/lastlog | 最后登录 | 每用户最后登录信息 |
| /var/log/cron | 定时任务日志 | crontab执行记录 |
| /var/log/maillog | 邮件日志 | 邮件服务相关 |
| /var/log/boot.log | 启动日志 | 系统启动过程 |
| /var/log/kern.log | 内核日志 | 内核消息 |
| /var/log/daemon.log | 守护进程日志 | 后台服务日志 |
| ~/.bash_history | 命令历史 | 用户执行过的命令 |
4.2 日志分析命令速查表
# SSH登录成功分析
grep "Accepted password" /var/log/secure # CentOS/RHEL
grep "Accepted password" /var/log/auth.log # Debian/Ubuntu
grep "Accepted.*$(date '+%b %d')" /var/log/secure # 今天的成功登录
# SSH登录失败分析(爆破检测)
grep "Failed password" /var/log/secure | head -20
grep "Failed password" /var/log/secure | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head -20 # 统计失败IP排行
grep "Invalid user" /var/log/secure # 非法用户名尝试
# 提取登录成功IP列表
grep "Accepted" /var/log/secure | awk '{print $11}' | sort -u
# last命令分析历史登录
last -20 # 最近20条登录记录
last -f /var/log/wtmp.1 # 查看轮转的历史wtmp
lastb -20 # 最近20条失败登录(需root)
# sudo使用记录分析
grep "sudo" /var/log/secure | grep "COMMAND" # 所有sudo命令
grep "user.*sudo" /var/log/secure # 特定用户sudo
# journalctl分析(systemd系统)
journalctl -u sshd --since "2026-08-19" --until "2026-08-19 23:59:59" # SSH日志
journalctl -u cron --since "1 hour ago" # 最近1小时cron日志
journalctl --since "2026-08-19" -p err # 当天错误级别日志
journalctl -f # 实时查看(类似tail -f)
journalctl -k # 内核日志
journalctl -u nginx -u mysql --since today # 多服务组合查询
# auditd审计日志分析
aureport --summary # 审计报告摘要
aureport --auth # 认证事件报告
aureport --failed # 失败事件报告
aureport -i -x # 可执行文件执行报告
ausearch -m USER_LOGIN --start today # 搜索今天的登录事件
ausearch -m ANOM_ABEND --start today # 搜索今天的异常终止
ausearch -k watch_rules 2>/dev/null # 搜索自定义审计规则命中
aureport -ts # 时间戳报告
# auditd自定义审计规则示例(添加到/etc/audit/rules.d/audit.rules)
# 监控passwd文件修改
-w /etc/passwd -p wa -k passwd_changes
# 监控sudoers文件修改
-w /etc/sudoers -p wa -k sudoers_changes
# 监控SSH配置修改
-w /etc/ssh/sshd_config -p wa -k ssh_config
# 监控crontab修改
-w /etc/crontab -p wa -k crontab_changes
# 监控二进制命令文件修改
-w /bin -p x -k bin_changes
-w /usr/bin -p x -k usr_bin_changes
# 监控内核模块加载
-w /sbin/insmod -p x -k module_insert
-w /sbin/rmmod -p x -k module_remove
# 重新加载审计规则
augenrules --load
4.3 进程分析
# 查看所有进程(完整命令行)
ps -auxwf # 树状显示所有进程
ps -ef --forest # 树状显示进程关系
ps aux | grep -v "grep" | grep -E "nc|bash -i|python|perl|ruby|/dev/tcp" # 查找反弹shell
# 查找隐藏进程(ps命令可能被Rootkit篡改)
# 方法一:比对ps和/proc目录
ls -d /proc/[0-9]* | awk -F/ '{print $3}' | sort -n > /tmp/proc_pids
ps -e -o pid --no-headers | sort -n > /tmp/ps_pids
diff /tmp/proc_pids /tmp/ps_pids # 差异即为隐藏进程
# 方法二:使用unhide工具
unhide proc # 检测隐藏进程
unhide brute # 暴力检测
# top命令实时监控
top -c -b -n 1 # 批处理模式显示一次(用于脚本)
top -c -b -n 1 | head -20 # 系统概况
# 查找CPU/内存占用最高的进程
ps aux --sort=-%cpu | head -10 # CPU前10
ps aux --sort=-%mem | head -10 # 内存前10
# 进程关联网络连接
netstat -tunlp # 查看监听端口和对应进程(旧版)
ss -tunlp # 查看监听端口和对应进程(推荐)
lsof -i:80 # 查看80端口占用
lsof -i -nP # 查看所有网络连接
lsof -p <PID> # 查看指定进程打开的文件
lsof -u root # 查看root用户进程
# 查找异常网络连接(反弹shell特征)
netstat -antp | grep ESTABLISHED | grep -v "127.0.0.1" # 外部已建立连接
ss -antp | grep -E "ESTAB|LISTEN" # 所有连接和监听
lsof -i -nP | grep -i estab # 已建立连接
# 查看进程的可执行文件路径
ls -la /proc/<PID>/exe # 获取进程对应二进制文件路径
ls -la /proc/<PID>/cwd # 获取进程工作目录
cat /proc/<PID>/cmdline # 获取进程命令行
cat /proc/<PID>/environ # 获取进程环境变量
cat /proc/<PID>/maps # 进程内存映射
strings /proc/<PID>/mem # 读取进程内存中的字符串
# strace追踪进程系统调用
strace -p <PID> -f -e trace=network # 追踪网络相关系统调用
strace -p <PID> -f -e trace=file # 追踪文件操作
strace -p <PID> -f -o /tmp/strace.log # 输出到文件
# 查看进程网络连接对应PID
for pid in $(ls /proc | grep -E '^[0-9]+$'); do
if ls -la /proc/$pid/fd 2>/dev/null | grep -q "socket"; then
echo "PID: $pid"
cat /proc/$pid/cmdline 2>/dev/null | tr '\0' ' '
echo ""
fi
done
4.4 文件分析
# 查找最近修改的文件(入侵后改动文件排查)
find / -mtime -1 -type f -exec ls -la {} \; 2>/dev/null # 最近1天修改
find / -mmin -60 -type f -exec ls -la {} \; 2>/dev/null # 最近60分钟修改
find / -ctime -1 -type f -exec ls -la {} \; 2>/dev/null # 最近1天属性改变
find / -atime -1 -type f -exec ls -la {} \; 2>/dev/null # 最近1天访问
find /tmp /var/tmp /dev/shm -type f -executable 2>/dev/null # 临时目录可执行文件
find / -name "*.py" -o -name "*.sh" -o -name "*.php" 2>/dev/null | xargs grep -l "import os" 2>/dev/null # 可疑脚本
# 查找SUID/SGID权限文件(提权后门排查)
find / -perm -4000 -type f -exec ls -la {} \; 2>/dev/null # SUID文件
find / -perm -2000 -type f -exec ls -la {} \; 2>/dev/null # SGID文件
# 查找隐藏文件
find / -name ".*" -type f -exec ls -la {} \; 2>/dev/null # 以.开头的隐藏文件
find / -name " " -type f 2>/dev/null # 文件名为空格
# 文件完整性校验(RPM包管理 - CentOS/RHEL)
rpm -Va > /tmp/rpm_verify.txt 2>&1 # 校验所有已安装包完整性
rpm -V openssh-server # 校验特定包
# 输出含义:S=大小变化 M=权限变化 5=MD5变化 L=符号链接变化 D=设备变化 U=用户变化 G=组变化 T=时间变化 P=能力变化
# 文件完整性校验(DPKG包管理 - Debian/Ubuntu)
dpkg -V > /tmp/dpkg_verify.txt 2>&1 # 校验所有已安装包完整性
dpkg -V openssh-server # 校验特定包
debsums -a # 需要安装debsums包
# MD5校验对比
find /bin /sbin /usr/bin /usr/sbin -type f -exec md5sum {} \; > /tmp/md5_before.txt # 生成校验值
# 对比已知良好值或基线文件
diff <(sort /tmp/md5_before.txt) <(sort /tmp/md5_baseline.txt)
# inotify实时监控文件变更(持续监控场景)
inotifywait -m -r /etc/ --timefmt '%Y-%m-%d %H:%M:%S' --format '%T %w%f %e' >> /tmp/file_changes.log 2>&1 &
# 查找异常大文件(可能为数据打包或数据库dump)
find / -type f -size +100M -exec ls -lh {} \; 2>/dev/null | sort -k5 -rn | head -20
# 查找被删除但被进程占用的文件(已删除但仍被打开)
lsof -nP | grep -i deleted | awk '{print $1, $2, $NF}' | sort -u
4.5 crontab与systemd分析
# 检查所有用户的crontab
for user in $(cut -d: -f1 /etc/passwd); do
crontab_content=$(crontab -l -u $user 2>/dev/null)
if [ -n "$crontab_content" ]; then
echo "=== User: $user ==="
echo "$crontab_content"
echo ""
fi
done
# 检查系统级crontab
cat /etc/crontab
ls -la /etc/cron.d/ /etc/cron.hourly/ /etc/cron.daily/ /etc/cron.weekly/ /etc/cron.monthly/
# 检查anacron
cat /etc/anacrontab
# 检查每个cron目录内容
for dir in /etc/cron.d /etc/cron.hourly /etc/cron.daily /etc/cron.weekly /etc/cron.monthly; do
echo "=== $dir ==="
ls -la $dir/
for file in $dir/*; do
if [ -f "$file" ]; then
echo "--- $file ---"
cat "$file"
echo ""
fi
done
done
# 检查systemd服务
systemctl list-timers --all # 所有定时器
systemctl list-unit-files --state=enabled --type=service # 所有启用的服务
systemctl list-units --type=service --state=running # 正在运行的服务
# 查找异常的systemd服务(关注/usr/local/bin等非标准路径)
find /etc/systemd /lib/systemd /usr/lib/systemd -name "*.service" -exec grep -l "ExecStart.*\(bash\|python\|nc\|ncat\|socat\|curl\|wget\)" {} \;
# 检查用户级systemd服务
find /home -path "*/.config/systemd/user/*" -name "*.service" 2>/dev/null
find /root/.config/systemd/user/ -name "*.service" 2>/dev/null
# 检查可疑服务文件
for svc in $(systemctl list-unit-files --type=service --state=enabled --no-legend | awk '{print $1}'); do
path=$(systemctl cat $svc 2>/dev/null | head -1 | awk -F'#' '{print $1}' | sed 's/# //')
if echo "$path" | grep -qE "/tmp/|/dev/shm/|/var/tmp/"; then
echo "[SUSPICIOUS] $svc -> $path"
fi
done
4.6 SSH日志分析
# 统计SSH暴力破解IP排行
grep "Failed password" /var/log/secure | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head -20
grep "Failed password" /var/log/auth.log | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head -20
# 查找暴力破解成功(大量失败后出现成功)
for ip in $(grep "Failed password" /var/log/secure | awk '{print $(NF-3)}' | sort -u); do
fail_count=$(grep "Failed password" /var/log/secure | grep "$ip" | wc -l)
success=$(grep "Accepted password" /var/log/secure | grep "$ip")
if [ -n "$success" ] && [ "$fail_count" -gt 10 ]; then
echo "[ALERT] Brute force success: $ip (failed $fail_count times)"
echo "$success"
fi
done
# 检查SSH密钥后门
find / -name "authorized_keys" -exec ls -la {} \; 2>/dev/null
find / -name "authorized_keys" -exec cat {} \; 2>/dev/null
# 检查每个用户的authorized_keys
for user_home in /home/* /root; do
if [ -f "$user_home/.ssh/authorized_keys" ]; then
echo "=== $user_home/.ssh/authorized_keys ==="
cat "$user_home/.ssh/authorized_keys"
fi
done
# 检查SSH配置是否被篡改
grep -E "PermitRootLogin|PasswordAuthentication|Port|AllowUsers|AllowGroups" /etc/ssh/sshd_config
# 检查known_hosts(可能泄露被攻击者访问过的主机)
find / -name "known_hosts" -exec cat {} \; 2>/dev/null
4.7 Rootkit检测
# rkhunter检测
yum install -y rkhunter # CentOS/RHEL
apt install -y rkhunter # Debian/Ubuntu
rkhunter --update # 更新数据库
rkhunter --check --sk # 执行检测,跳过按键确认
rkhunter --check --report-warnings-only # 仅报告警告项
rkhunter --propupd # 更新文件属性数据库(首次安装后执行)
# chkrootkit检测
yum install -y chkrootkit # CentOS/RHEL
apt install -y chkrootkit # Debian/Ubuntu
chkrootkit | grep -i "infected\|suspicious\|warning"
# 手动Rootkit检测方法
# 1. 检查内核模块
lsmod # 列出已加载内核模块
cat /proc/modules # 从/proc读取
# 对比lsmod和/proc/modules
diff <(lsmod | tail -n +2 | awk '{print $1}' | sort) <(cat /proc/modules | awk '{print $1}' | sort)
# 2. 检查异常内核模块
lsmod | grep -vE "^(Module|)" | awk '{print $1}' | while read mod; do
modinfo $mod 2>/dev/null | grep -q "filename" || echo "[SUSPICIOUS] Unknown module: $mod"
done
# 3. 检查LD_PRELOAD(用户态Rootkit)
echo $LD_PRELOAD
cat /etc/ld.so.preload 2>/dev/null
env | grep -i preload
# 4. 检查/etc/ld.so.preload文件
if [ -f /etc/ld.so.preload ]; then
echo "[CHECK] /etc/ld.so.preload exists:"
cat /etc/ld.so.preload
fi
# 5. 对比ps和/proc进程数(内核态Rootkit隐藏进程)
echo "ps count: $(ps -e --no-headers | wc -l)"
echo "/proc count: $(ls -d /proc/[0-9]* 2>/dev/null | wc -l)"
# 6. 检查异常的网络连接(隐藏端口)
# 对比netstat和/proc/net/tcp
cat /proc/net/tcp | awk '{print $2}' | grep -v "local_address" > /tmp/proc_net
ss -tlnp | awk '{print $4}' > /tmp/ss_out
diff /tmp/proc_net /tmp/ss_out
# 7. 使用unhide工具
unhide-linux26 brute # 暴力检测隐藏进程
unhide-linux26 proc # 进程检测
4.8 Linux应急排查清单
| 排查项 | 检查命令 | 异常指标 |
|---|---|---|
| 异常账号 | cat /etc/passwd / who / last | UID为0的非root账号、新创建账号 |
| 异常进程 | ps -auxwf / top / strace | 高CPU/内存、反弹shell特征 |
| 异常网络连接 | ss -tunlp / netstat -antp / lsof -i | 异常外联、隐藏端口 |
| 异常文件 | find / -mtime -1 -type f | 近期修改、SUID权限、临时目录可执行文件 |
| 异常crontab | crontab -l -u root / cat /etc/crontab | 未知定时任务、非标准路径脚本 |
| 异常服务 | systemctl list-units --type=service | 非标准路径服务、异常服务名 |
| 异常SSH | grep Accepted /var/log/secure | 爆破成功、异常IP登录 |
| Rootkit | rkhunter / chkrootkit / lsmod | 检测到Rootkit、异常内核模块 |
| 异常历史命令 | cat ~/.bash_history | 下载执行、提权、清痕迹命令 |
| 异常环境变量 | env / cat /etc/profile / ~/.bashrc | LD_PRELOAD劫持、异常PATH |
| 异常启动项 | /etc/rc.local / chkconfig --list | 非标准启动脚本 |
五、Web应用应急响应
5.1 Web中间件日志分析
Web中间件日志是分析Web攻击的第一手资料。不同中间件的日志格式有所不同。
Apache访问日志格式:
| 字段 | 说明 | 示例 |
|---|---|---|
| 远程IP | 客户端IP | 192.168.1.100 |
| 身份 | identd认证用户(通常为-) | - |
| 用户名 | HTTP认证用户 | - |
| 时间 | 请求时间戳 | [19/Aug/2026:10:00:01 +0800] |
| 请求行 | 方法+URI+协议 | GET /index.php?id=1 HTTP/1.1 |
| 状态码 | HTTP响应状态码 | 200 |
| 响应大小 | 响应体字节数 | 1234 |
| Referer | 来源页面 | https://google.com |
| User-Agent | 客户端标识 | Mozilla/5.0… |
Nginx访问日志格式(默认combined格式):
| 字段 | 说明 |
|---|---|
| $remote_addr | 客户端IP |
| $remote_user | 认证用户 |
| $time_local | 本地时间 |
| $request | 请求行 |
| $status | 状态码 |
| $body_bytes_sent | 响应大小 |
| $http_referer | 来源 |
| $http_user_agent | UA |
| $http_x_forwarded_for | XFF头(代理场景) |
Tomcat访问日志字段:
| 字段 | 说明 |
|---|---|
| %a | 远程IP |
| %t | 时间 |
| %r | 请求行 |
| %s | 状态码 |
| %b | 响应大小 |
| %{Referer}i | 来源 |
| %{User-Agent}i | UA |
| %D | 处理时间(毫秒) |
IIS日志字段(W3C格式):
| 字段 | 说明 |
|---|---|
| date time | 日期时间 |
| s-ip | 服务器IP |
| cs-method | 客户端方法 |
| cs-uri-stem | 请求URI |
| cs-uri-query | 查询字符串 |
| s-port | 服务器端口 |
| cs-username | 用户名 |
| c-ip | 客户端IP |
| cs(User-Agent) | UA |
| sc-status | 状态码 |
| sc-substatus | 子状态码 |
| time-taken | 处理时间 |
5.2 攻击特征识别
SQL注入特征:
# Apache日志中检测SQL注入
grep -E "union.*select|information_schema|benchmark\(|sleep\(|waitfor|order.*by|xp_cmdshell|load_file|into.*outfile" /var/log/httpd/access_log
grep -E "(\b(union|select|insert|update|delete|drop|create|alter)\b.*\b(from|into|table|database)\b)" /var/log/httpd/access_log
grep -E "'|\"|%27|%22|--|%20" /var/log/httpd/access_log | grep -iE "select|union|or.*1=1|and.*1=1"
# Nginx日志中检测SQL注入
grep -E "union.*select|information_schema|benchmark\(|sleep\(|waitfor|order.*by|xp_cmdshell|load_file|into.*outfile" /var/log/nginx/access.log
grep -E "%27|%22|'|" /var/log/nginx/access.log | grep -iE "select|union|or|and"
XSS攻击特征:
# 检测XSS攻击
grep -iE "alert\(|confirm\(|prompt\(|javascript:|onerror=|onload=|onmouseover=|<script|</script|document\.cookie|window\.location" /var/log/httpd/access_log
grep -iE "<img.*src.*=.*script|<svg.*onload|<iframe|<body.*onload" /var/log/httpd/access_log
grep -iE "%3Cscript|%3Cimg|%3Csvg|%3Ciframe|%3Cbody" /var/log/httpd/access_log
SSRF攻击特征:
# 检测SSRF攻击
grep -E "url=http|url=https|target=|host=|path=.*://|file://|gopher://|dict://|ftp://|ldap://" /var/log/httpd/access_log
grep -E "169\.254\.169\.254|metadata|127\.0\.0\.1|localhost|0\.0\.0\.0|0x7f000001|2130706433" /var/log/httpd/access_log # 云环境元数据地址检测
目录遍历攻击特征:
# 检测目录遍历
grep -E "\.\./|\.\.%2f|\.\.%5c|%2e%2e%2f|%2e%2e/|%2e%2e%5c|/etc/passwd|/etc/shadow|boot\.ini|win\.ini" /var/log/httpd/access_log
grep -E "/proc/self|/var/log|/home/.*\.ssh|/root/\.ssh" /var/log/httpd/access_log
文件上传攻击特征:
# 检测恶意文件上传
grep -iE "\.(php|php3|php4|php5|phtml|pht|jsp|jspx|asp|aspx|ashx|cer|asa|exe|sh|bat|cmd|war)$" /var/log/httpd/access_log | grep -i "POST"
grep -iE "upload|fileup|filename=|Content-Disposition" /var/log/httpd/access_log
# 检测双扩展名绕过
grep -iE "\.(php|jsp|asp)\.(jpg|png|gif|bmp|txt|pdf|doc)" /var/log/httpd/access_log
Webshell访问特征:
# Webshell特征检测
grep -iE "eval\(|base64_decode\(|gzinflate\(|assert\(|system\(|exec\(|passthru\(|shell_exec\(|popen\(|proc_open\(|preg_replace.*/e" /var/log/httpd/access_log
# 常见Webshell文件名
grep -iE "shell\.php|cmd\.php|c99\.php|r57\.php|b374k|wso|eval\.php|1\.php|test\.php|x\.php|1t\.php|admin\.php" /var/log/httpd/access_log
# 检测Webshell访问模式(频繁POST到单一文件)
awk '{print $1, $7}' /var/log/nginx/access.log | grep "POST" | awk '{print $2}' | sort | uniq -c | sort -rn | head -20
5.3 日志分析工具
GoAccess(实时日志分析):
# 安装GoAccess
yum install -y goaccess # CentOS/RHEL
apt install -y goaccess # Debian/Ubuntu
# 实时分析Apache日志
goaccess /var/log/httpd/access_log --log-format=COMBINED -a
# 实时分析Nginx日志
goaccess /var/log/nginx/access.log --log-format=COMBINED -a
# 生成HTML报告
goaccess /var/log/nginx/access.log --log-format=COMBINED -o /var/www/html/report.html --real-time-html
ELK Stack(Elasticsearch + Logstash + Kibana):
ELK是最流行的日志分析平台,适用于大规模日志收集、存储、分析和可视化。Logstash负责日志收集和解析,Elasticsearch负责存储和搜索,Kibana负责可视化展示。
Logstash配置示例(解析Nginx日志):
input {
file {
path => "/var/log/nginx/access.log"
start_position => "beginning"
}
}
filter {
grok {
match => { "message" => "%{COMBINEDAPACHELOG}" }
}
date {
match => [ "timestamp" , "dd/MMM/yyyy:HH:mm:ss Z" ]
}
geoip {
source => "clientip"
}
}
output {
elasticsearch {
hosts => ["localhost:9200"]
index => "nginx-logs-%{+YYYY.MM.dd}"
}
}
Splunk(企业级SIEM):
Splunk是商业SIEM平台,支持强大的搜索语言(SPL):
# 检测SQL注入尝试
index=web sourcetype=access_combined (sql_injection OR "union select" OR "information_schema" OR "benchmark(" OR "sleep(")
# 检测Webshell访问
index=web sourcetype=access_combined (eval( OR base64_decode( OR system( OR exec() AND method=POST
# 统计访问量异常的IP
index=web sourcetype=access_combined | stats count by clientip | sort -count | head 20
# 检测目录遍历
index=web sourcetype=access_combined (.. OR %2e%2e OR /etc/passwd OR /etc/shadow)
Grafana Loki(轻量级日志系统):
Loki是Grafana出品的轻量级日志系统,适合容器化环境,使用LogQL查询语言:
# 检测SQL注入
{job="nginx"} |= "union select" or |= "information_schema" or |= "benchmark("
# 统计IP访问量
sum by (remote_addr) (count_over_time({job="nginx"}[1h]))
# 检测404错误扫描
{job="nginx"} |= " 404 " | logfmt | line_format "{{.remote_addr}}"
5.4 Webshell查杀
# 使用find查找可疑PHP文件(按内容特征)
find /var/www -name "*.php" -exec grep -l "eval\|base64_decode\|gzinflate\|assert\|system\|exec\|passthru\|shell_exec" {} \;
# 查找最近修改的PHP文件
find /var/www -name "*.php" -mtime -7 -exec ls -la {} \;
# 查找PHP文件中的危险函数组合
find /var/www -name "*.php" -exec grep -lE "eval\s*\(|base64_decode\s*\(|gzinflate\s*\(|assert\s*\(|system\s*\(|exec\s*\(|passthru\s*\(|shell_exec\s*\(|popen\s*\(|proc_open\s*\(|preg_replace\s*\(.*\/e" {} \;
# 检测PHP一句话木马
find /var/www -name "*.php" -exec grep -lE "\$_(POST|GET|REQUEST|COOKIE)\[.*\]\s*\)" {} \;
# 检测PHP文件中嵌入的编码内容(常见于混淆Webshell)
find /var/www -name "*.php" -exec grep -lE "base64_decode\s*\(\s*[\"']\s*[A-Za-z0-9+/=]{50,}" {} \;
# 检测非常规位置的可执行文件
find /var/www -name "*.php" -path "*/upload*" 2>/dev/null
find /var/www -name "*.php" -path "*/tmp*" 2>/dev/null
find /var/www -name "*.php" -path "*/images*" 2>/dev/null
find /var/www \( -name "*.phtml" -o -name "*.pht" -o -name "*.php3" -o -name "*.php4" -o -name "*.php5" -o -name "*.php7" -o -name "*.shtml" \) 2>/dev/null
# 检测PHP文件中的十六进制编码
find /var/www -name "*.php" -exec grep -lE "0x[0-9a-fA-F]{20,}|\\\\x[0-9a-fA-F]{2}" {} \;
# 使用河马Webshell查杀工具(推荐)
wget https://www.shellpub.com/static/hm-linux.tgz
tar -xzf hm-linux.tgz
cd hm-linux
chmod +x hm
./hm scan /var/www/ # 扫描Web目录
./hm deepscan /var/www/ # 深度扫描
# 使用ScanWebShell工具
# (下载后直接使用,支持Windows/Linux)
python scan_webshell.py /var/www/
# D盾Webshell查杀(Windows环境)
# 用于Windows服务器IIS环境的Webshell检测
5.5 Web应急排查清单
| 排查项 | 检查方法 | 异常指标 |
|---|---|---|
| 访问日志 | grep分析access_log | SQL注入/XSS/Webshell特征 |
| 错误日志 | cat error_log | 异常错误、模块崩溃 |
| Webshell | find + grep河马工具 | 评估函数、一句话木马 |
| 异常文件 | find -mtime -7 | 近期上传的脚本文件 |
| 文件权限 | ls -la | Web目录可写权限异常 |
| 配置文件 | cat httpd.conf/nginx.conf | 被篡改的配置项 |
| Session文件 | find session目录 | Session目录中的PHP文件 |
| 上传目录 | ls -la upload/ | 上传目录中的可执行文件 |
| 临时目录 | ls /tmp/ | 临时目录可执行文件 |
| 数据库 | 查询异常表 | Webshell写入的数据表 |
六、内存取证
6.1 内存取证原理
内存取证是指获取和分析系统物理内存的过程。由于恶意代码(特别是无文件攻击和Rootkit)可能在内存中运行而不在磁盘留下痕迹,内存取证成为现代应急响应不可或缺的技术。
内存取证的关键价值在于:即使攻击者删除了磁盘上的恶意文件,只要进程仍在运行或内存未被覆盖,就可以从内存中提取完整的恶意代码样本、加密密钥、网络连接信息、命令历史等关键证据。
6.2 物理内存获取方法
Windows内存获取:
| 工具 | 说明 |
|---|---|
| winpmem | 开源内存获取工具,支持Windows 7及以上 |
| livekd | Windbg附加工具,支持实时内存分析 |
| Magnet RAM Capture | 商业工具,支持多种Windows版本 |
| FTK Imager | 支持内存镜像获取 |
| DumpIt | 轻量级一键获取工具 |
rem 使用winpmem获取内存镜像
winpmem.exe memdump.raw
rem 使用DumpIt获取
DumpIt.exe
rem 使用FTK Imager获取(GUI操作)
rem File -> Capture Memory -> 输出文件路径
Linux内存获取(使用LiME):
# 编译LiME内核模块
git clone https://github.com/504ensicsLabs/LiME.git
cd LiME/src
make
# 加载LiME模块并获取内存镜像(raw格式)
insmod lime.ko "path=/tmp/memory.raw format=raw"
# 获取内存镜像(lime格式,包含元数据)
insmod lime.ko "path=/tmp/memory.lime format=lime"
# 通过网络传输内存镜像(避免本地写文件)
insmod lime.ko "path=tcp:192.168.1.100:4444 format=raw"
# 在分析端使用 nc -l 4444 > memory.raw 接收
# 使用AVML(微软出品的轻量级工具)
wget https://github.com/microsoft/avml/releases/download/v0.1.0/avml
chmod +x avml
./avml memory.raw
6.3 Volatility框架使用
Volatility是最强大的内存取证分析框架,支持Windows、Linux和macOS内存镜像分析。以下是Volatility 3(Python3版本)的使用方法。
基础分析命令:
# 安装Volatility 3
pip3 install volatility3
# 获取镜像信息(推荐首先执行)
vol.py -f memory.raw windows.info
# 列出所有进程
vol.py -f memory.raw windows.pslist # 使用双链表列举
vol.py -f memory.raw windows.psscan # 使用池标签扫描(可发现隐藏进程)
vol.py -f memory.raw windows.pstree # 树状显示进程关系
# 进程详细信息
vol.py -f memory.raw windows.pstree --pid <PID>
# 获取进程命令行
vol.py -f memory.raw windows.cmdline --pid <PID>
# 列出进程打开的句柄
vol.py -f memory.raw windows.handles --pid <PID>
# 列出网络连接
vol.py -f memory.raw windows.netscan # 扫描网络连接
vol.py -f memory.raw windows.netstat # 使用网络栈列举
# 文件扫描
vol.py -f memory.raw windows.filescan # 扫描文件对象
vol.py -f memory.raw windows.filescan --filter "*.exe"
vol.py -f memory.raw windows.filescan --filter "*.dll"
vol.py -f memory.raw windows.filescan --filter "*.ps1"
# 提取文件
vol.py -f memory.raw windows.dumpfiles --pid <PID> # 提取进程加载的文件
vol.py -f memory.raw windows.dumpfiles --virtaddr <OFFSET> # 按偏移提取
# DLL列表
vol.py -f memory.raw windows.dlllist --pid <PID>
# 注册表分析
vol.py -f memory.raw windows.registry.hivelist # 列出注册表蜂巢
vol.py -f memory.raw windows.registry.printkey --key "Software\Microsoft\Windows\CurrentVersion\Run" # 读取Run键
vol.py -f memory.raw windows.registry.hivedump --hive <OFFSET> # 导出注册表蜂巢
# 服务分析
vol.py -f memory.raw windows.svcscan # 扫描服务
vol.py -f memory.raw windows.svcscan --filter "name=*"
# 计划任务
vol.py -f memory.raw windows.tasksched
# 恶意代码检测
vol.py -f memory.raw windows.malfind # 查找注入代码
vol.py -f memory.raw windows.malfind --pid <PID>
# 内核模块扫描
vol.py -f memory.raw windows.modscan # 扫描内核模块
vol.py -f memory.raw windows.moddump --driver <BASE> # 提取驱动
# 提取进程内存
vol.py -f memory.raw windows.memmap --pid <PID> --dump
# 命令行环境变量
vol.py -f memory.raw windows.envars --pid <PID>
# 检测进程注入
vol.py -f memory.raw windows.malfind
Volatility 2命令(兼容老版本镜像):
# 获取镜像信息(推荐首先执行,判断操作系统版本)
volatility --profile=Win10_19041_x64_17763 -f memory.raw imageinfo
# 使用kdbgscan自动识别profile
volatility -f memory.raw kdbgscan
# 列出进程
volatility --profile=Win10_19041_x64_17763 -f memory.raw pslist
volatility --profile=Win10_19041_x64_17763 -f memory.raw psscan # 可发现隐藏进程
volatility --profile=Win10_19041_x64_17763 -f memory.raw pstree
# 命令行参数
volatility --profile=Win10_19041_x64_17763 -f memory.raw cmdline
volatility --profile=Win10_19041_x64_17763 -f memory.raw cmdline -p <PID>
# 网络连接
volatility --profile=Win10_19041_x64_17763 -f memory.raw netscan
volatility --profile=Win10_19041_x64_17763 -f memory.raw connections # XP/2003
volatility --profile=Win10_19041_x64_17763 -f memory.raw connscan
# 文件扫描和提取
volatility --profile=Win10_19041_x64_17763 -f memory.raw filescan | grep -iE "\.exe|\.dll|\.ps1|\.bat"
volatility --profile=Win10_19041_x64_17763 -f memory.raw dumpfiles -n --dump-dir=./output
volatility --profile=Win10_19041_x64_17763 -f memory.raw dumpfiles -r <regex> --dump-dir=./output
volatility --profile=Win10_19041_x64_17763 -f memory.raw dumpfiles -p <PID> --dump-dir=./output
# 提取进程(dmp格式)
volatility --profile=Win10_19041_x64_17763 -f memory.raw procdump -p <PID> --dump-dir=./output
volatility --profile=Win10_19041_x64_17763 -f memory.raw memdump -p <PID> --dump-dir=./output
# DLL列表
volatility --profile=Win10_19041_x64_17763 -f memory.raw dlllist -p <PID>
# 句柄
volatility --profile=Win10_19041_x64_17763 -f memory.raw handles -p <PID>
# 注册表
volatility --profile=Win10_19041_x64_17763 -f memory.raw hivelist
volatility --profile=Win10_19041_x64_17763 -f memory.raw printkey -K "Software\Microsoft\Windows\CurrentVersion\Run"
volatility --profile=Win10_19041_x64_17763 -f memory.raw hivedump -o <OFFSET> --dump-dir=./output
# 服务
volatility --profile=Win10_19041_x64_17763 -f memory.raw svcscan
# 恶意代码检测
volatility --profile=Win10_19041_x64_17763 -f memory.raw malfind
volatility --profile=Win10_19041_x64_17763 -f memory.raw malfind -p <PID>
volatility --profile=Win10_19041_x64_17763 -f memory.raw ldrmodules # 检测隐藏DLL
volatility --profile=Win10_19041_x64_17763 -f memory.raw moddump --dump-dir=./output --base=<BASE> # 提取内核模块
# 剪贴板内容
volatility --profile=Win10_19041_x64_17763 -f memory.raw clipboard
volatility --profile=Win10_19041_x64_17763 -f memory.raw Clipboard
# 提取凭据
volatility --profile=Win10_19041_x64_17763 -f memory.raw hashdump # SAM哈希
volatility --profile=Win10_19041_x64_17763 -f memory.raw lsadump # LSA密钥
volatility --profile=Win10_19041_x64_17763 -f memory.raw cachedump # 域缓存凭据
volatility --profile=Win10_19041_x64_17763 -f memory.raw Mimikatz # Mimikatz方法
# Shellcode检测
volatility --profile=Win10_19041_x64_17763 -f memory.raw yarascan -y rules.yar
6.4 完整内存分析流程
以下是一个完整的内存分析流程脚本:
#!/bin/bash
# Memory Forensics Analysis Script
# Usage: ./mem_analysis.sh <memory_image> <profile>
IMAGE=$1
PROFILE=$2
OUTPUT_DIR="./mem_analysis_output"
mkdir -p $OUTPUT_DIR
echo "[*] Starting Memory Forensics Analysis"
echo "[*] Image: $IMAGE"
echo "[*] Profile: $PROFILE"
echo ""
# Step 1: Image Info
echo "[1/10] Getting image info..."
volatility --profile=$PROFILE -f $IMAGE imageinfo > $OUTPUT_DIR/01_imageinfo.txt 2>&1
# Step 2: Process List
echo "[2/10] Listing processes..."
volatility --profile=$PROFILE -f $IMAGE pslist > $OUTPUT_DIR/02_pslist.txt 2>&1
volatility --profile=$PROFILE -f $IMAGE psscan > $OUTPUT_DIR/02_psscan.txt 2>&1
volatility --profile=$PROFILE -f $IMAGE pstree > $OUTPUT_DIR/02_pstree.txt 2>&1
# Step 3: Hidden Process Detection
echo "[3/10] Detecting hidden processes..."
echo "--- pslist PIDs ---" > $OUTPUT_DIR/03_hidden_procs.txt
volatility --profile=$PROFILE -f $IMAGE pslist --output-file=$OUTPUT_DIR/pslist_pids.txt
awk 'NR>1{print $3}' $OUTPUT_DIR/pslist_pids.txt | sort -n > $OUTPUT_DIR/pslist_sorted.txt
echo "--- psscan PIDs ---" >> $OUTPUT_DIR/03_hidden_procs.txt
volatility --profile=$PROFILE -f $IMAGE psscan --output-file=$OUTPUT_DIR/psscan_pids.txt
awk 'NR>1{print $3}' $OUTPUT_DIR/psscan_pids.txt | sort -n > $OUTPUT_DIR/psscan_sorted.txt
echo "--- Hidden PIDs (in psscan but not in pslist) ---" >> $OUTPUT_DIR/03_hidden_procs.txt
comm -13 $OUTPUT_DIR/pslist_sorted.txt $OUTPUT_DIR/psscan_sorted.txt >> $OUTPUT_DIR/03_hidden_procs.txt
# Step 4: Command Lines
echo "[4/10] Getting command lines..."
volatility --profile=$PROFILE -f $IMAGE cmdline > $OUTPUT_DIR/04_cmdline.txt 2>&1
# Step 5: Network Connections
echo "[5/10] Scanning network connections..."
volatility --profile=$PROFILE -f $IMAGE netscan > $OUTPUT_DIR/05_netscan.txt 2>&1
volatility --profile=$PROFILE -f $IMAGE connections > $OUTPUT_DIR/05_connections.txt 2>&1
volatility --profile=$PROFILE -f $IMAGE connscan > $OUTPUT_DIR/05_connscan.txt 2>&1
# Step 6: Malware Detection
echo "[6/10] Detecting injected code..."
volatility --profile=$PROFILE -f $IMAGE malfind > $OUTPUT_DIR/06_malfind.txt 2>&1
volatility --profile=$PROFILE -f $IMAGE ldrmodules > $OUTPUT_DIR/06_ldrmodules.txt 2>&1
# Step 7: File Scan
echo "[7/10] Scanning files..."
volatility --profile=$PROFILE -f $IMAGE filescan > $OUTPUT_DIR/07_filescan.txt 2>&1
echo "Suspicious files:" > $OUTPUT_DIR/07_suspicious_files.txt
grep -iE "\.exe|\.dll|\.ps1|\.bat|\.vbs|\.js|\.jar" $OUTPUT_DIR/07_filescan.txt >> $OUTPUT_DIR/07_suspicious_files.txt
# Step 8: Registry Analysis
echo "[8/10] Analyzing registry..."
volatility --profile=$PROFILE -f $IMAGE hivelist > $OUTPUT_DIR/08_hivelist.txt 2>&1
volatility --profile=$PROFILE -f $IMAGE printkey -K "Software\Microsoft\Windows\CurrentVersion\Run" > $OUTPUT_DIR/08_run_key.txt 2>&1
volatility --profile=$PROFILE -f $IMAGE printkey -K "Software\Microsoft\Windows\CurrentVersion\RunOnce" > $OUTPUT_DIR/08_runonce_key.txt 2>&1
# Step 9: Services
echo "[9/10] Scanning services..."
volatility --profile=$PROFILE -f $IMAGE svcscan > $OUTPUT_DIR/09_svcscan.txt 2>&1
# Step 10: Credential Extraction
echo "[10/10] Extracting credentials..."
volatility --profile=$PROFILE -f $IMAGE hashdump > $OUTPUT_DIR/10_hashdump.txt 2>&1
volatility --profile=$PROFILE -f $IMAGE lsadump > $OUTPUT_DIR/10_lsadump.txt 2>&1
volatility --profile=$PROFILE -f $IMAGE cachedump > $OUTPUT_DIR/10_cachedump.txt 2>&1
echo ""
echo "[*] Analysis complete. Results saved to $OUTPUT_DIR/"
echo "[*] Review priority:"
echo " 1. $OUTPUT_DIR/03_hidden_procs.txt (hidden processes)"
echo " 2. $OUTPUT_DIR/06_malfind.txt (injected code)"
echo " 3. $OUTPUT_DIR/05_netscan.txt (network connections)"
echo " 4. $OUTPUT_DIR/04_cmdline.txt (suspicious commands)"
echo " 5. $OUTPUT_DIR/10_hashdump.txt (credentials)"
6.5 常见恶意代码内存特征
| 恶意行为 | 内存特征 | 检测方法 |
|---|---|---|
| 进程注入 | 进程内存中有可执行且可写页面 | malfind, ldrmodules |
| 空闲进程注入 | 在空闲进程内存中发现额外代码段 | malfind -p PID(explorer.exe) |
| Hollow进程 | 进程路径与内存中执行代码不一致 | procdump + 文件对比 |
| 无文件攻击 | PowerShell进程内存中有可执行代码 | malfind -p PID(powershell) |
| Rootkit | SSDT钩子、IRP修改 | ssdt, moddump |
| 反弹Shell | 异常网络连接、Socket在非常规进程 | netscan + cmdline |
| 凭据窃取 | lsass进程中有注入代码 | malfind -p PID(lsass) |
七、恶意软件分析
7.1 静态分析
静态分析是在不运行恶意软件的情况下分析其特征的技术。
基础分析:
# file命令 - 识别文件类型
file malware.exe
file suspicious.dll
file unknown_file
# strings命令 - 提取可读字符串
strings -n 8 malware.exe > strings_output.txt # 最少8字符的字符串
strings -el malware.exe > unicode_strings.txt # Unicode字符串(小端)
strings -a malware.exe > all_strings.txt # 所有节区
strings -n 6 malware.exe | grep -iE "http|ftp|\.exe|\.dll|cmd|powershell" # 过滤URL和命令
# md5sum / sha256sum - 计算文件哈希(用于IOC匹配)
md5sum malware.exe
sha256sum malware.exe
# ssdeep - 模糊哈希(用于相似恶意软件聚类)
ssdeep.exe malware.exe
PE文件分析(Windows可执行文件):
# 使用pestudio或PEview查看PE结构(GUI工具)
# 使用pefile(Python库)分析PE文件
python3 -c "
import pefile
pe = pefile.PE('malware.exe')
print('Compile Time:', pe.FILE_HEADER.TimeDateStamp)
print('Entry Point:', hex(pe.OPTIONAL_HEADER.AddressOfEntryPoint))
print('Image Base:', hex(pe.OPTIONAL_HEADER.ImageBase))
print('Sections:')
for section in pe.sections:
print(f' {section.Name.decode().strip(chr(0))}: VAddr={hex(section.VirtualAddress)} Size={hex(section.SizeOfRawData)} Entropy={section.get_entropy():.2f}')
print('Imports:')
for entry in pe.DIRECTORY_ENTRY_IMPORT:
print(f' {entry.dll.decode()}:')
for imp in entry.imports:
if imp.name:
print(f' {imp.name.decode()}')
"
# 重点关注高熵值节区(>7.0可能表示加壳/加密)
python3 -c "
import pefile
pe = pefile.PE('malware.exe')
for section in pe.sections:
entropy = section.get_entropy()
name = section.Name.decode().strip(chr(0))
flag = ' [PACKED?]' if entropy > 7.0 else ''
print(f'{name}: Entropy={entropy:.2f} Size={hex(section.SizeOfRawData)}{flag}')
"
# 检查导入表中的危险函数
python3 -c "
import pefile
pe = pefile.PE('malware.exe')
dangerous = ['CreateProcess', 'ShellExecute', 'WinExec', 'CreateRemoteThread', 'WriteProcessMemory', 'VirtualAllocEx', 'LoadLibrary', 'GetProcAddress', 'URLDownloadToFile', 'InternetOpenUrl', 'socket', 'connect', 'send', 'recv', 'CreateService', 'RegCreateKey', 'RegSetValue']
if hasattr(pe, 'DIRECTORY_ENTRY_IMPORT'):
for entry in pe.DIRECTORY_ENTRY_IMPORT:
for imp in entry.imports:
if imp.name:
name = imp.name.decode()
if any(d in name for d in dangerous):
print(f'[DANGER] {entry.dll.decode()} -> {name}')
"
# 检查资源段(可能隐藏payload)
python3 -c "
import pefile
pe = pefile.PE('malware.exe')
if hasattr(pe, 'DIRECTORY_ENTRY_RESOURCE'):
for res_type in pe.DIRECTORY_ENTRY_RESOURCE.entries:
for res_id in res_type.directory.entries:
for res_lang in res_id.directory.entries:
data = pe.get_data(res_lang.data.struct.OffsetToData, res_lang.data.struct.Size)
entropy = sum(float(data.count(byte)) / len(data) * (-math.log2(float(data.count(byte)) / len(data) + 1e-10)) for byte in range(256) if data.count(byte) > 0) if data else 0
print(f'Resource Type={res_type.id} ID={res_id.id} Size={len(data)} Entropy={entropy:.2f}')
"
7.2 动态分析
动态分析是在受控环境中运行恶意软件以观察其行为的技术。
Process Monitor(进程监控):
设置过滤器监控恶意软件的行为:
- Process Name equals malware.exe
- Operation is RegCreateKey or RegSetValue(注册表操作)
- Operation is CreateFile or WriteFile(文件操作)
- Operation is TCP Connect或UDP Send(网络操作)
Process Explorer(进程树分析):
使用Process Explorer查看恶意软件创建的子进程、加载的DLL、网络连接等。
Wireshark(网络流量抓取):
在沙箱环境中抓取恶意软件的网络流量,分析C2通信、数据外泄等行为。
API Monitor(API调用追踪):
使用API Monitor可以追踪恶意软件调用的所有Windows API,了解其行为细节。
7.3 沙箱分析
VirusTotal(在线多引擎扫描与行为分析):
VirusTotal不仅提供多引擎病毒扫描,还提供沙箱行为分析报告,包括文件行为、网络通信、注册表修改等信息。可通过API实现自动化分析。
# VirusTotal API v3 查询文件报告
curl -s --request GET \
--url "https://www.virustotal.com/api/v3/files/<sha256_hash>" \
--header "x-apikey: <YOUR_API_KEY>" | jq '.'
# 上传文件分析(小于32MB)
curl -s --request POST \
--url "https://www.virustotal.com/api/v3/files" \
--header "x-apikey: <YOUR_API_KEY>" \
--form "file=@malware.exe" | jq '.'
# 查询域名报告
curl -s --request GET \
--url "https://www.virustotal.com/api/v3/domains/<domain>" \
--header "x-apikey: <YOUR_API_KEY>" | jq '.'
AnyRun(交互式沙箱):
AnyRun提供交互式恶意软件分析沙箱,可以在分析过程中与恶意软件交互,适合需要人工交互的恶意软件(如勒索软件、银行木马)。
Hybrid Analysis(自动化沙箱):
Hybrid Analysis提供自动化沙箱分析,支持Windows和Android环境,生成详细的行为分析报告。
# Hybrid Analysis API查询
curl -s --request POST \
--url "https://www.hybrid-analysis.com/api/v2/quick-scan" \
--header "api-key: <YOUR_API_KEY>" \
--header "Content-Type: application/x-www-form-urlencoded" \
--data "scan_type=file&file=@malware.exe"
7.4 常见恶意软件行为表
| 恶意软件类型 | 典型行为 | 网络特征 | 文件特征 |
|---|---|---|---|
| 挖矿木马 | 创建隐藏进程、CPU高占用 | 连接矿池(3333/5555/14444等端口) | xmrig等矿工程序 |
| 勒索软件 | 批量加密文件、修改桌面壁纸 | 连接C2获取密钥、上传加密文件信息 | 勒索信文件(.txt/.html) |
| 远控木马 | 键盘记录、屏幕截取、文件窃取 | 定期心跳包连接C2 | 注入系统进程 |
| 蠕虫病毒 | 内网扫描、利用漏洞传播 | 大量扫描流量(445/3389等) | 自复制传播 |
| 间谍软件 | 数据收集、键盘记录 | 定期外传数据 | 隐藏在临时目录 |
| 后门 | 持久化驻留、等待指令 | 监听端口等待连接 | 伪装系统服务 |
| Webshell | 命令执行、文件管理 | 通过HTTP协议通信 | 位于Web目录 |
| 僵尸网络 | DDoS攻击、垃圾邮件 | 连接C2服务器 | 加入僵尸网络 |
7.5 YARA规则编写
YARA是恶意软件分类和识别的标准工具,通过规则匹配识别恶意文件。
// 基本YARA规则结构
rule BasicRule {
meta:
description = "Basic example rule"
author = "IR Team"
date = "2026-08-19"
strings:
$text_string = "malware" // 文本字符串
$hex_string = { 4D 5A } // 十六进制(PE文件头)
$regex_string = /https?:\/\/[a-z0-9\.]+/i // 正则表达式
condition:
$text_string or $hex_string
}
// 检测Meterpreter反弹Shell
rule Meterpreter_Reverse_Shell {
meta:
description = "Detect Meterpreter reverse shell payloads"
author = "IR Team"
severity = "high"
strings:
$mz = "MZ" at 0 // PE头
$meterpreter = "meterpreter" // Meterpreter标识
$reverse = "Reverse"
$stager = "stager"
$reflective = "ReflectiveLoader"
$load_dll = "LoadLibrary" // 导入函数
condition:
$mz at 0 and ($meterpreter or $reflective) and $reverse
}
// 检测Webshell(PHP)
rule PHP_Webshell_Generic {
meta:
description = "Generic PHP webshell detection"
author = "IR Team"
strings:
$eval = "eval(" nocase
$assert = "assert(" nocase
$system = "system(" nocase
$exec = "exec(" nocase
$passthru = "passthru(" nocase
$shell_exec = "shell_exec(" nocase
$base64 = "base64_decode(" nocase
$post = "$_POST" nocase
$get = "$_GET" nocase
$request = "$_REQUEST" nocase
condition:
filesize < 100KB and
2 of ($eval, $assert, $system, $exec, $passthru, $shell_exec, $base64) and
1 of ($post, $get, $request)
}
// 检测挖矿木马
rule CryptoMiner_Generic {
meta:
description = "Detect cryptocurrency miners"
author = "IR Team"
strings:
$pool1 = "stratum+tcp" nocase // 矿池协议
$pool2 = "stratum+ssl" nocase
$xmrig = "xmrig" // 常见矿工
$cpuminer = "cpuminer"
$donate = "donate" nocase // 捐赠等级
$algo1 = "cryptonight" nocase // 挖矿算法
$algo2 = "randomx" nocase
$algo3 = "ethash" nocase
condition:
1 of ($pool1, $pool2) and
1 of ($xmrig, $cpuminer) or
2 of ($algo1, $algo2, $algo3)
}
// 检测勒索软件特征
rule Ransomware_Generic {
meta:
description = "Detect ransomware behavior strings"
author = "IR Team"
strings:
$encrypt1 = "AES" nocase // 加密算法
$encrypt2 = "RSA" nocase
$encrypt3 = "vssadmin delete" nocase // 删除卷影副本
$encrypt4 = "wbadmin delete" nocase // 删除备份
$encrypt5 = "bcdeedit" nocase // 修改启动配置
$ransom1 = "YOUR FILES ARE ENCRYPTED" nocase // 勒索信文本
$ransom2 = "How to decrypt" nocase
$ransom3 = "Bitcoin" nocase // 比特币地址
$ransom4 = "pay" nocase
$ext1 = ".locked" // 加密后扩展名
$ext2 = ".encrypted"
$ext3 = ".crypted"
condition:
1 of ($encrypt3, $encrypt4, $encrypt5) or
1 of ($ransom1, $ransom2) or
1 of ($ext1, $ext2, $ext3) and 1 of ($encrypt1, $encrypt2)
}
使用YARA进行扫描:
# 安装YARA
yum install -y yara # CentOS/RHEL
apt install -y yara # Debian/Ubuntu
# 扫描单个文件
yara -r rules.yar malware.exe
# 递归扫描目录
yara -r rules.yar /var/www/
# 输出到文件
yara -r rules.yar /tmp/ > yara_results.txt
# 显示匹配的字符串
yara -s rules.yar malware.exe
# 扫描进程内存
yara -r rules.yar -p <PID>
# 使用多个规则文件
yara -r rules1.yar rules2.yar rules3.yar /var/www/
7.6 完整恶意软件分析流程
#!/bin/bash
# Malware Analysis Workflow Script
# Usage: ./malware_analysis.sh <sample_file>
SAMPLE=$1
OUTPUT_DIR="./malware_analysis_$(date +%Y%m%d_%H%M%S)"
mkdir -p $OUTPUT_DIR
echo "[*] Malware Analysis Workflow"
echo "[*] Sample: $SAMPLE"
echo "[*] Output: $OUTPUT_DIR"
echo ""
# Phase 1: Basic Info
echo "[Phase 1] Basic Information"
file $SAMPLE > $OUTPUT_DIR/01_filetype.txt 2>&1
md5sum $SAMPLE >> $OUTPUT_DIR/01_hashes.txt 2>&1
sha1sum $SAMPLE >> $OUTPUT_DIR/01_hashes.txt 2>&1
sha256sum $SAMPLE >> $OUTPUT_DIR/01_hashes.txt 2>&1
stat $SAMPLE >> $OUTPUT_DIR/01_filestat.txt 2>&1
echo "Done."
echo ""
# Phase 2: String Extraction
echo "[Phase 2] String Extraction"
strings -n 8 $SAMPLE > $OUTPUT_DIR/02_strings_ascii.txt 2>&1
strings -el -n 8 $SAMPLE > $OUTPUT_DIR/02_strings_unicode.txt 2>&1
grep -iE "http|ftp|\.exe|\.dll|cmd|powershell|reg|temp|appdata" $OUTPUT_DIR/02_strings_ascii.txt > $OUTPUT_DIR/02_suspicious_strings.txt 2>&1
echo "Done."
echo ""
# Phase 3: PE Analysis
echo "[Phase 3] PE File Analysis"
python3 -c "
import pefile, sys
try:
pe = pefile.PE('$SAMPLE')
print('Compile Time:', pe.FILE_HEADER.TimeDateStamp)
print('Entry Point:', hex(pe.OPTIONAL_HEADER.AddressOfEntryPoint))
print('Image Base:', hex(pe.OPTIONAL_HEADER.ImageBase))
print()
print('Sections:')
for section in pe.sections:
entropy = section.get_entropy()
flag = ' [PACKED]' if entropy > 7.0 else ''
print(f' {section.Name.decode().strip(chr(0)):10s} VAddr={hex(section.VirtualAddress):12s} Size={hex(section.SizeOfRawData):12s} Entropy={entropy:.2f}{flag}')
print()
if hasattr(pe, 'DIRECTORY_ENTRY_IMPORT'):
print('Imported DLLs:')
for entry in pe.DIRECTORY_ENTRY_IMPORT:
print(f' {entry.dll.decode()}')
print()
dangerous = ['CreateProcess', 'ShellExecute', 'WinExec', 'CreateRemoteThread', 'WriteProcessMemory', 'VirtualAllocEx', 'LoadLibrary', 'GetProcAddress', 'URLDownloadToFile', 'InternetOpen', 'socket', 'connect', 'send', 'recv', 'CreateService', 'RegCreateKey', 'RegSetValue', 'CreateFile', 'WriteFile']
print('Dangerous Imports:')
for entry in pe.DIRECTORY_ENTRY_IMPORT:
for imp in entry.imports:
if imp.name:
name = imp.name.decode()
if any(d in name for d in dangerous):
print(f' [!] {entry.dll.decode()} -> {name}')
except Exception as e:
print(f'Error: {e}')
" > $OUTPUT_DIR/03_pe_analysis.txt 2>&1
echo "Done."
echo ""
# Phase 4: YARA Scan
echo "[Phase 4] YARA Rule Scanning"
if [ -f rules.yar ]; then
yara -s rules.yar $SAMPLE > $OUTPUT_DIR/04_yara_results.txt 2>&1
else
echo "No rules.yar found, skipping YARA scan" > $OUTPUT_DIR/04_yara_results.txt
fi
echo "Done."
echo ""
# Phase 5: Hash Lookup
echo "[Phase 5] Hash Lookup (VirusTotal)"
SHA256=$(sha256sum $SAMPLE | awk '{print $1}')
echo "SHA256: $SHA256"
echo "Manual check: https://www.virustotal.com/gui/file/$SHA256" > $OUTPUT_DIR/05_virustotal.txt
echo "Done."
echo ""
echo "[*] Static Analysis Complete"
echo "[*] Review priority:"
echo " 1. $OUTPUT_DIR/03_pe_analysis.txt (PE structure)"
echo " 2. $OUTPUT_DIR/02_suspicious_strings.txt (suspicious strings)"
echo " 3. $OUTPUT_DIR/04_yara_results.txt (YARA matches)"
echo " 4. $OUTPUT_DIR/05_virustotal.txt (VirusTotal link)"
echo ""
echo "[*] Next: Dynamic analysis in sandbox environment"
八、网络流量分析
8.1 流量抓取方法
# tcpdump - 命令行抓包工具
# 抓取所有流量到文件
tcpdump -i eth0 -w /tmp/capture.pcap
# 抓取指定接口、端口
tcpdump -i eth0 port 80 -w /tmp/web.pcap
tcpdump -i eth0 port 443 -w /tmp/https.pcap
# 抓取指定主机流量
tcpdump -i eth0 host 192.168.1.100 -w /tmp/host.pcap
# 抓取指定网段
tcpdump -i eth0 net 192.168.1.0/24 -w /tmp/subnet.pcap
# 实时查看抓包内容
tcpdump -i eth0 -nn -X
# 过滤特定协议
tcpdump -i eth0 tcp port 22 -w /tmp/ssh.pcap # SSH流量
tcpdump -i eth0 tcp port 3389 -w /tmp/rdp.pcap # RDP流量
tcpdump -i eth0 tcp port 445 -w /tmp/smb.pcap # SMB流量
tcpdump -i eth0 icmp -w /tmp/icmp.pcap # ICMP流量
tcpdump -i eth0 udp port 53 -w /tmp/dns.pcap # DNS流量
# 组合过滤
tcpdump -i eth0 'host 192.168.1.100 and (port 80 or port 443)' -w /tmp/host_web.pcap
# 抓取大数据量时不截断
tcpdump -i eth0 -s 0 -w /tmp/full_capture.pcap # -s 0 不限制包大小
# 读取pcap文件
tcpdump -r /tmp/capture.pcap -nn
tcpdump -r /tmp/capture.pcap -nn -X # 十六进制和ASCII
Wireshark - 图形化抓包与分析工具:
Wireshark是最广泛使用的网络协议分析工具,支持深度协议解析和强大的过滤语言。
# Linux下安装Wireshark
yum install -y wireshark # CentOS/RHEL
apt install -y wireshark # Debian/Ubuntu
# 命令行模式(tshark)
tshark -i eth0 -w /tmp/capture.pcap
tshark -r /tmp/capture.pcap -Y "http.request" -T fields -e http.host -e http.request.uri
tshark -r /tmp/capture.pcap -Y "dns.qry.name" -T fields -e dns.qry.name | sort -u
Zeek(Bro)- 网络流量分析框架:
Zeek(原Bro)是强大的网络流量分析框架,可生成详细的连接日志、HTTP日志、DNS日志、SSL日志等。
# 离线分析pcap文件
zeek -r capture.pcap local
# 生成的日志文件
# conn.log - 所有连接
# http.log - HTTP请求
# dns.log - DNS查询
# ssl.log - SSL/TLS连接
# files.log - 传输的文件
# weird.log - 异常事件
Suricata - 入侵检测/防御系统:
# 离线分析pcap文件
suricata -r capture.pcap -c /etc/suricata/suricata.yaml
# 查看告警
cat fast.log
cat eve.json | jq 'select(.event_type=="alert")'
8.2 网络协议分析
| 协议 | 端口 | 关注点 |
|---|---|---|
| HTTP | 80 | Web攻击载荷 |
| HTTPS | 443 | C2通信(需解密) |
| DNS | 53 | DNS隧道、C2域名 |
| SSH | 22 | 横向移动 |
| RDP | 3389 | 远程控制 |
| SMB | 445 | 文件共享、漏洞利用 |
| FTP | 21 | 数据外泄 |
| SMTP | 25 | 邮件外发 |
| ICMP | - | 隧道通信、Ping扫描 |
| Kerberos | 88 | 域认证、票据窃取 |
| LDAP | 389 | 目录查询 |
8.3 常见攻击流量特征表
| 攻击类型 | 流量特征 | 检测方法 |
|---|---|---|
| C2通信 | 定期心跳包、固定间隔连接 | 连接频率分析、JA3指纹 |
| DDoS | 大量SYN包、UDP泛洪 | 流量基线对比、包速率异常 |
| 爆破 | 大量同源认证请求 | 失败计数、频率分析 |
| 端口扫描 | 大量SYN到不同端口 | 单IP多端口连接统计 |
| 数据外泄 | 大量出站流量、DNS隧道 | 出站流量基线、DNS查询长度 |
| 蠕虫传播 | 内网横向扫描 | 445/3389/22端口扫描统计 |
| Web攻击 | HTTP请求中含攻击载荷 | URL参数正则匹配 |
| DNS隧道 | 长域名、高频DNS查询 | DNS查询长度、频率分析 |
| 域横向 | Kerberos异常票据请求 | 票据请求模式分析 |
8.4 Wireshark过滤技巧
显示过滤器(Display Filter):
# HTTP相关
http.request.method == "POST" # 所有POST请求
http.request.uri contains "union" # SQL注入特征
http.request.uri contains "eval" # Webshell特征
http.request.uri matches "(?i)(union|select|from)" # 正则匹配
http.host contains "malware" # 恶意域名
http.user_agent contains "curl" # 异常UA
http.response.code == 500 # 服务器错误
http.request.uri contains ".." # 目录遍历
# DNS相关
dns.qry.name contains "malware" # 恶意域名查询
dns.qry.name matches ".*\\d{10,}.*" # 超长子域名(DNS隧道)
dns.flags.response == 1 # DNS响应
# TCP相关
tcp.flags.syn == 1 and tcp.flags.ack == 0 # SYN包(扫描)
tcp.flags.reset == 1 # RST包
tcp.stream eq 5 # 追踪TCP流5
# IP相关
ip.src == 192.168.1.100 # 源IP过滤
ip.dst == 10.0.0.5 # 目标IP过滤
ip.src == 192.168.1.100 and ip.dst == 10.0.0.5 # 双向过滤
# 端口相关
tcp.port == 4444 # 指定端口
tcp.port == 4444 or tcp.port == 1337 # C2端口
tcp.dstport == 3389 # RDP流量
udp.port == 53 # DNS流量
# 组合过滤
ip.src == 192.168.1.100 and tcp.port == 4444 # 特定IP+端口
http.request.method == "POST" and http.host contains "evil" # POST+恶意域名
# 统计分析
Statistics > Conversations # 查看所有会话
Statistics > Endpoints # 查看所有端点
Statistics > Protocol Hierarchy # 协议分布
Statistics > IPv4 Statistics # IP统计
# 追踪流
Right-click > Follow > TCP Stream # 追踪TCP流
Right-click > Follow > HTTP Stream # 追踪HTTP流
# 提取文件
File > Export Objects > HTTP # 导出HTTP传输文件
File > Export Objects > SMB # 导出SMB传输文件
过滤表达式按钮:
Wireshark支持创建过滤表达式按钮,方便快速应用常用过滤器。点击过滤器栏右侧的"+"号即可添加。
8.5 入侵检测规则编写
Snort规则语法:
# Snort规则基本格式
# [Action] [Protocol] [Source IP] [Source Port] -> [Dest IP] [Dest Port] [Options]
# 检测SQL注入
alert tcp any any -> $HOME_NET 80 (msg:"SQL Injection Attempt - UNION SELECT"; content:"union"; nocase; content:"select"; nocase; distance:0; within:50; sid:1000001; rev:1;)
# 检测目录遍历
alert tcp any any -> $HOME_NET 80 (msg:"Directory Traversal Attempt"; content:"../"; nocase; sid:1000002; rev:1;)
# 检测Webshell访问
alert tcp any any -> $HOME_NET 80 (msg:"Webshell Access - eval"; content:"eval"; nocase; content:"POST"; http_method; sid:1000003; rev:1;)
# 检测Nmap扫描
alert tcp any any -> $HOME_NET any (msg:"Nmap Scan Detected"; flags:A; ack:0; sid:1000004; rev:1;)
# 检测反弹Shell(常用端口)
alert tcp $HOME_NET any -> any 4444 (msg:"Possible Reverse Shell - Port 4444"; sid:1000005; rev:1;)
alert tcp $HOME_NET any -> any 1337 (msg:"Possible Reverse Shell - Port 1337"; sid:1000006; rev:1;)
# 检测DNS隧道
alert udp any any -> $HOME_NET 53 (msg:"DNS Tunneling - Long Query"; content:"|00|"; byte_test:1,>,20,0,relative; sid:1000007; rev:1;)
Suricata规则示例:
# 检测Metasploit Meterpreter
alert http any any -> any any (msg:"Meterpreter Reverse Shell"; content:"GET"; http_method; content:"/"; http_uri; pcre:"/\/[A-Za-z0-9]{4,}\b/"; sid:2000001; rev:1;)
# 检测Cobalt Strike
alert http any any -> any any (msg:"Cobalt Strike Beacon"; content:"Cookie|3a|"; http_header; pcre:"/Cookie:\s*[A-Za-z0-9+/=]{20,}/"; sid:2000002; rev:1;)
# 检测Empire框架
alert http any any -> any any (msg:"Empire C2 Beacon"; content:"POST"; http_method; content:"execution"; http_client_body; sid:2000003; rev:1;)
# 检测Mimikatz
alert http any any -> any any (msg:"Mimikatz Usage"; content:"sekurlsa"; nocase; sid:2000004; rev:1;)
# 检测异常User-Agent
alert http any any -> any any (msg:"Suspicious User-Agent"; content:"Mozilla/5.0|20 7c 20|"; sid:2000005; rev:1;)
8.6 网络IOC提取
# 从pcap中提取所有IP
tshark -r capture.pcap -T fields -e ip.src -e ip.dst | tr '\t' '\n' | sort -u > iocs_ips.txt
# 从pcap中提取所有域名
tshark -r capture.pcap -Y "dns.qry.name" -T fields -e dns.qry.name | sort -u > iocs_domains.txt
# 从pcap中提取所有URL
tshark -r capture.pcap -Y "http.request" -T fields -e http.host -e http.request.uri | sed 's/\t/ /' | sort -u > iocs_urls.txt
# 从pcap中提取所有文件哈希
tshark -r capture.pcap -Y "http.request.method==POST" -T fields -e http.file_data | sort -u > iocs_postdata.txt
# 提取HTTP传输的文件
tshark -r capture.pcap --export-objects http,/tmp/extracted_files/
# 提取SMB传输的文件
tshark -r capture.pcap --export-objects smb,/tmp/extracted_files/
# 提取所有User-Agent
tshark -r capture.pcap -Y "http.user_agent" -T fields -e http.user_agent | sort | uniq -c | sort -rn > iocs_useragents.txt
# 提取JA3指纹(TLS客户端指纹)
tshark -r capture.pcap -Y "tls.handshake.type==1" -T fields -e ip.src -e ip.dst -e tls.handshake.ja3 | sort -u > iocs_ja3.txt
# 统计各IP连接数
tshark -r capture.pcap -T fields -e ip.src | sort | uniq -c | sort -rn | head -20 > conn_stats.txt
# 提取所有DNS查询
tshark -r capture.pcap -Y "dns.flags.response==0" -T fields -e ip.src -e dns.qry.name | sort -u > dns_queries.txt
8.7 完整流量分析流程
#!/bin/bash
# Network Traffic Analysis Script
# Usage: ./traffic_analysis.sh <pcap_file>
PCAP=$1
OUTPUT_DIR="./traffic_analysis_$(date +%Y%m%d_%H%M%S)"
mkdir -p $OUTPUT_DIR
echo "[*] Network Traffic Analysis"
echo "[*] PCAP: $PCAP"
echo "[*] Output: $OUTPUT_DIR"
echo ""
# Phase 1: Overview
echo "[1/7] Traffic Overview..."
tshark -r $PCAP -q -z io,phs > $OUTPUT_DIR/01_protocol_hierarchy.txt 2>&1
tshark -r $PCAP -q -z conv,ip > $OUTPUT_DIR/01_ip_conversations.txt 2>&1
tshark -r $PCAP -q -z endpoints,ip > $OUTPUT_DIR/01_ip_endpoints.txt 2>&1
# Phase 2: HTTP Analysis
echo "[2/7] HTTP Analysis..."
tshark -r $PCAP -Y "http.request" -T fields -e frame.time -e ip.src -e ip.dst -e http.host -e http.request.method -e http.request.uri > $OUTPUT_DIR/02_http_requests.txt 2>&1
grep -iE "union|select|eval|exec|system|cmd|shell|base64|\.\.|%27|%22" $OUTPUT_DIR/02_http_requests.txt > $OUTPUT_DIR/02_http_suspicious.txt 2>&1
tshark -r $PCAP -Y "http.user_agent" -T fields -e ip.src -e http.user_agent | sort -u > $OUTPUT_DIR/02_user_agents.txt 2>&1
# Phase 3: DNS Analysis
echo "[3/7] DNS Analysis..."
tshark -r $PCAP -Y "dns.flags.response==0" -T fields -e ip.src -e dns.qry.name | sort -u > $OUTPUT_DIR/03_dns_queries.txt 2>&1
awk '{print length($2), $0}' $OUTPUT_DIR/03_dns_queries.txt | sort -rn | head -20 > $OUTPUT_DIR/03_long_dns_queries.txt 2>&1
# Phase 4: Connection Analysis
echo "[4/7] Connection Analysis..."
tshark -r $PCAP -q -z conv,tcp > $OUTPUT_DIR/04_tcp_conversations.txt 2>&1
tshark -r $PCAP -T fields -e ip.src -e ip.dst -e tcp.dstport | sort | uniq -c | sort -rn | head -50 > $OUTPUT_DIR/04_top_connections.txt 2>&1
# Phase 5: File Extraction
echo "[5/7] File Extraction..."
mkdir -p $OUTPUT_DIR/extracted_files_http
tshark -r $PCAP --export-objects http,$OUTPUT_DIR/extracted_files_http/ 2>&1
mkdir -p $OUTPUT_DIR/extracted_files_smb
tshark -r $PCAP --export-objects smb,$OUTPUT_DIR/extracted_files_smb/ 2>&1
# Phase 6: IOC Extraction
echo "[6/7] IOC Extraction..."
tshark -r $PCAP -T fields -e ip.src -e ip.dst | tr '\t' '\n' | sort -u > $OUTPUT_DIR/06_ioc_ips.txt 2>&1
tshark -r $PCAP -Y "dns.qry.name" -T fields -e dns.qry.name | sort -u > $OUTPUT_DIR/06_ioc_domains.txt 2>&1
tshark -r $PCAP -Y "http.request" -T fields -e http.host -e http.request.uri | sed 's/\t//' | sort -u > $OUTPUT_DIR/06_ioc_urls.txt 2>&1
# Phase 7: Suricata Alert Scan
echo "[7/7] Suricata Alert Scan..."
if command -v suricata &> /dev/null; then
suricata -r $PCAP -c /etc/suricata/suricata.yaml -l $OUTPUT_DIR/ 2>&1
cat $OUTPUT_DIR/fast.log 2>/dev/null > $OUTPUT_DIR/07_alerts.txt
cat $OUTPUT_DIR/eve.json 2>/dev/null | jq 'select(.event_type=="alert")' > $OUTPUT_DIR/07_alerts_json.txt 2>/dev/null
else
echo "Suricata not installed, skipping" > $OUTPUT_DIR/07_alerts.txt
fi
echo ""
echo "[*] Analysis complete. Results in $OUTPUT_DIR/"
echo "[*] Review priority:"
echo " 1. $OUTPUT_DIR/02_http_suspicious.txt (attack signatures)"
echo " 2. $OUTPUT_DIR/07_alerts.txt (IDS alerts)"
echo " 3. $OUTPUT_DIR/06_ioc_ips.txt (IOC IPs)"
echo " 4. $OUTPUT_DIR/03_long_dns_queries.txt (DNS tunneling)"
echo " 5. $OUTPUT_DIR/extracted_files_http/ (extracted files)"
九、入侵痕迹排查实战
9.1 入驻判断方法
入侵排查需要系统性地检查以下八个维度:
| 维度 | 检查目标 | 工具/命令 |
|---|---|---|
| 账号 | 异常新建账号、隐藏账号、权限提升 | net user / getent passwd |
| 进程 | 恶意进程、反弹shell、挖矿进程 | tasklist / ps / Process Explorer |
| 网络 | 异常外联、C2连接、监听端口 | netstat / ss / TCPView |
| 文件 | 恶意文件落地、Webshell、后门 | find / Autoruns |
| 服务 | 恶意服务、持久化服务 | services.msc / systemctl |
| 计划任务 | 持久化计划任务 | schtasks / crontab |
| 注册表/启动 | 自启动项、注册表后门 | Autoruns / reg query |
| 日志 | 入侵痕迹、日志清除 | 事件查看器 / journalctl |
9.2 持久化后门排查表
Windows持久化机制排查:
| 后门类型 | 检查位置 | 检查命令 |
|---|---|---|
| 注册表Run键 | HKLM…\Run, HKCU…\Run | reg query “HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run” |
| 启动文件夹 | %APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup | dir /b startup目录 |
| 服务 | services.msc | sc query / Get-Service |
| 计划任务 | schtasks | schtasks /query /fo LIST /v |
| WMI事件订阅 | __EventFilter, __EventConsumer | wmic path __EVENTFILTER get / wmic path __EventConsumer get |
| COM劫持 | HKCU\Software\Classes\CLSID | Autoruns检查 |
| DLL劫持 | 应用程序目录DLL | 检查应用目录可疑DLL |
| 映像劫持 | Image File Execution Options | reg query “HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options” |
| Winlogon | Notify, Shell, Userinit | reg query “HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon” |
| LSASS加载 | LSA Providers | reg query “HKLM\SYSTEM\CurrentControlSet\Control\Lsa” |
| AppInit_DLLs | AppInit_DLLs注册表值 | reg query “HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows” |
| BITS任务 | BITS传输任务 | bitsadmin /list |
| 快捷方式 | .lnk文件 | 检查快捷方式目标路径 |
Linux持久化机制排查:
| 后门类型 | 检查位置 | 检查命令 |
|---|---|---|
| crontab | /var/spool/cron/, /etc/cron.* | crontab -l, cat /etc/crontab |
| systemd服务 | /etc/systemd/system/ | systemctl list-unit-files |
| rc.local | /etc/rc.local, /etc/rc.d/ | cat /etc/rc.local |
| 启动脚本 | /etc/init.d/, /etc/profile | ls /etc/init.d/, cat /etc/profile |
| SSH密钥 | authorized_keys | cat ~/.ssh/authorized_keys |
| LD_PRELOAD | /etc/ld.so.preload,环境变量 | cat /etc/ld.so.preload, echo $LD_PRELOAD |
| PAM后门 | /etc/pam.d/ | 检查PAM模块配置 |
| 内核模块 | lsmod | lsmod, cat /proc/modules |
| SUID后门 | SUID权限文件 | find / -perm -4000 |
| 软连接后门 | /tmp/下的软连接 | ls -la /tmp/ |
| 账号后门 | UID=0账号 | awk -F: ‘$3==0 {print $1}’ /etc/passwd |
9.3 隐藏文件与ADS流检测
Windows隐藏文件和ADS(Alternate Data Streams):
# 查找隐藏文件
Get-ChildItem -Path C:\ -Recurse -Force -ErrorAction SilentlyContinue | Where-Object {$_.Attributes -match "Hidden"} | Select-Object FullName, Length, Attributes
# 查找ADS(NTFS交换数据流)
Get-ChildItem -Path C:\Users -Recurse -Force -ErrorAction SilentlyContinue | ForEach-Object { Get-Item -Path $_.FullName -Stream * -ErrorAction SilentlyContinue | Where-Object { $_.Stream -ne ':$DATA' -and $_.Stream -ne 'Zone.Identifier' } | Select-Object FileName, Stream, Length }
# 使用streams命令行工具查找ADS
streams.exe -s C:\Users\
# 使用PowerShell查找ADS(更全面)
Get-ChildItem -Path C:\ -Recurse -Force -ErrorAction SilentlyContinue | ForEach-Object {
try {
$streams = Get-Item -Path $_.FullName -Stream * -ErrorAction Stop
foreach ($stream in $streams) {
if ($stream.Stream -ne ':$DATA' -and $stream.Stream -ne 'Zone.Identifier' -and $stream.Length -gt 0) {
Write-Output "$($_.FullName):$($stream.Stream) - $($stream.Length) bytes"
}
}
} catch {}
}
# 查找异常的ADS内容(可能隐藏可执行代码)
Get-ChildItem -Path C:\Users -Recurse -Force -ErrorAction SilentlyContinue | ForEach-Object {
try {
$streams = Get-Item -Path $_.FullName -Stream * -ErrorAction Stop
foreach ($stream in $streams) {
if ($stream.Stream -ne ':$DATA' -and $stream.Length -gt 1024) {
$content = Get-Content -Path "$($_.FullName):$($stream.Stream)" -Encoding Byte -TotalCount 2 -ErrorAction SilentlyContinue
if ($content[0] -eq 0x4D -and $content[1] -eq 0x5A) {
Write-Output "[EXE in ADS] $($_.FullName):$($stream.Stream)"
}
}
}
} catch {}
}
Linux隐藏文件:
# 查找隐藏文件(以.开头)
find / -name ".*" -type f 2>/dev/null
# 查找特定隐藏文件
find / -name ".. *" -type f 2>/dev/null # 以..开头的隐藏文件
find / -name " " -type f 2>/dev/null # 文件名为空格
find / -name "..." -type f 2>/dev/null # 三个点文件
# 查找特殊权限的隐藏文件
find / -name ".*" -type f -perm /+x 2>/dev/null # 可执行的隐藏文件
9.4 完整排查脚本
Windows完整排查脚本:
# Windows Incident Response Investigation Script
# Author: IR Team
# Usage: Run as Administrator
$OutputDir = "C:\IR_$(Get-Date -Format 'yyyyMMdd_HHmmss')"
New-Item -ItemType Directory -Path $OutputDir | Out-Null
Write-Host "[*] Starting Windows IR Investigation"
Write-Host "[*] Output directory: $OutputDir"
Write-Host ""
# 1. Account Analysis
Write-Host "[1/12] Analyzing accounts..."
net user > $OutputDir\01_net_user.txt 2>&1
net localgroup administrators > $OutputDir\01_local_admins.txt 2>&1
wmic useraccount get Name, SID, Disabled, AccountType > $OutputDir\01_useraccount_wmic.txt 2>&1
# 查找隐藏账号($结尾)
Get-WmiObject Win32_UserAccount | Where-Object { $_.Name -like "*`$" } | Select-Object Name, SID, Disabled > $OutputDir\01_hidden_accounts.txt 2>&1
# 查找UID=0的非标准账号
Get-WmiObject Win32_UserAccount | Where-Object { $_.SID -like "S-1-5-21-*-500" -and $_.Name -ne "Administrator" } > $OutputDir\01_suspicious_admin.txt 2>&1
# 2. Process Analysis
Write-Host "[2/12] Analyzing processes..."
tasklist /v /fo csv > $OutputDir\02_tasklist.csv 2>&1
Get-Process | Select-Object Id, Name, Path, Company, Description | Export-Csv -Path $OutputDir\02_getprocess.csv -NoTypeInformation
# 查找无数字签名的进程
Get-Process | Where-Object { $_.Path -and -not (Get-AuthenticodeSignature $_.Path).Status -eq "Valid" } | Select-Object Id, Name, Path > $OutputDir\02_unsigned_processes.txt 2>&1
# 查找可疑进程名
Get-Process | Where-Object { $_.Name -match "(svchost|explorer|lsass|csrss|winlogon)" -and $_.Path -notmatch "(system32|SysWOW64)" } | Select-Object Id, Name, Path > $OutputDir\02_impersonating_processes.txt 2>&1
# 3. Network Analysis
Write-Host "[3/12] Analyzing network connections..."
netstat -ano > $OutputDir\03_netstat.txt 2>&1
# 获取网络连接对应进程
$connections = Get-NetTCPConnection -State Established | Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, OwningProcess
$connections | ForEach-Object { $proc = Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue; [PSCustomObject]@{ LocalAddress=$_.LocalAddress; LocalPort=$_.LocalPort; RemoteAddress=$_.RemoteAddress; RemotePort=$_.RemotePort; PID=$_.OwningProcess; ProcessName=$proc.Name; ProcessPath=$proc.Path } } | Export-Csv -Path $OutputDir\03_network_connections.csv -NoTypeInformation
# 查找异常外联
Get-NetTCPConnection -State Established | Where-Object { $_.RemoteAddress -notmatch "^(127\.|10\.|172\.(1[6-9]|2[0-9]|3[01])\.|192\.168\.|169\.254\.)" } | Select-Object RemoteAddress, RemotePort, OwningProcess > $OutputDir\03_external_connections.txt 2>&1
# 4. Service Analysis
Write-Host "[4/12] Analyzing services..."
Get-Service | Select-Object Name, DisplayName, Status, StartType | Export-Csv -Path $OutputDir\04_services.csv -NoTypeInformation
Get-WmiObject Win32_Service | Where-Object { $_.PathName -match "temp|tmp|appdata|public|downloads" } | Select-Object Name, DisplayName, PathName > $OutputDir\04_suspicious_services.txt 2>&1
sc query type= service state= all > $OutputDir\04_sc_query.txt 2>&1
# 5. Scheduled Tasks
Write-Host "[5/12] Analyzing scheduled tasks..."
schtasks /query /fo LIST /v > $OutputDir\05_schtasks.txt 2>&1
# 查找可疑计划任务
Get-ScheduledTask | Where-Object { $_.Actions.Execute -match "(powershell|cmd|wscript|cscript|mshta|regsvr32)" } | Select-Object TaskName, TaskPath, State, @{N='Execute';E={$_.Actions.Execute}} | Export-Csv -Path $OutputDir\05_suspicious_tasks.csv -NoTypeInformation
# 6. Startup Items
Write-Host "[6/12] Analyzing startup items..."
reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" > $OutputDir\06_run_hklm.txt 2>&1
reg query "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" > $OutputDir\06_run_hkcu.txt 2>&1
reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce" >> $OutputDir\06_run_hklm.txt 2>&1
reg query "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce" >> $OutputDir\06_run_hkcu.txt 2>&1
Get-CimInstance Win32_StartupCommand | Select-Object Name, Command, Location, User | Export-Csv -Path $OutputDir\06_startup_commands.csv -NoTypeInformation
# 7. Registry IFEO
Write-Host "[7/12] Analyzing Image File Execution Options..."
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options" /s > $OutputDir\07_ifeo.txt 2>&1
# 8. WMI Analysis
Write-Host "[8/12] Analyzing WMI subscriptions..."
Get-WmiObject -Namespace root\Subscription -Class __EventFilter > $OutputDir\08_wmi_filters.txt 2>&1
Get-WmiObject -Namespace root\Subscription -Class __EventConsumer > $OutputDir\08_wmi_consumers.txt 2>&1
Get-WmiObject -Namespace root\Subscription -Class __FilterToConsumerBinding > $OutputDir\08_wmi_bindings.txt 2>&1
# 9. Recent File Analysis
Write-Host "[9/12] Analyzing recent files..."
Get-ChildItem -Path C:\ -Recurse -File -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-7) -and $_.Extension -match "(\.exe|\.dll|\.ps1|\.bat|\.vbs|\.js)" } | Select-Object FullName, LastWriteTime, Length | Export-Csv -Path $OutputDir\09_recent_files.csv -NoTypeInformation
# 10. PowerShell History
Write-Host "[10/12] Analyzing PowerShell history..."
$PSReadLinePath = (Get-PSReadLineOption).HistorySavePath
if (Test-Path $PSReadLinePath) {
Get-Content $PSReadLinePath | Select-String -Pattern "http|iex|download|invoke|exec|base64|enc" | Out-File $OutputDir\10_powershell_suspicious.txt
Copy-Item $PSReadLinePath $OutputDir\10_powershell_history.txt
}
# 11. Event Log Analysis
Write-Host "[11/12] Analyzing event logs..."
# 检查日志清除
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=1102} -MaxEvents 10 -ErrorAction SilentlyContinue | Select-Object TimeCreated, Message > $OutputDir\11_log_cleared.txt 2>&1
# 检查登录成功
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4624} -MaxEvents 100 -ErrorAction SilentlyContinue | ForEach-Object { $xml = [xml]$_.ToXml(); $ip = ($xml.Event.EventData.Data | Where-Object {$_.Name -eq 'IpAddress'}).'#text'; $logonType = ($xml.Event.EventData.Data | Where-Object {$_.Name -eq 'LogonType'}).'#text'; [PSCustomObject]@{Time=$_.TimeCreated; LogonType=$logonType; IP=$ip} } | Where-Object { $_.LogonType -eq 10 -or $_.LogonType -eq 3 } | Select-Object -First 50 > $OutputDir\11_remote_logins.txt 2>&1
# 检查进程创建
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4688} -MaxEvents 100 -ErrorAction SilentlyContinue | ForEach-Object { $xml = [xml]$_.ToXml(); [PSCustomObject]@{Time=$_.TimeCreated; Process=($xml.Event.EventData.Data | Where-Object {$_.Name -eq 'NewProcessName'}).'#text'; CommandLine=($xml.Event.EventData.Data | Where-Object {$_.Name -eq 'CommandLine'}).'#text'} } | Export-Csv -Path $OutputDir\11_process_creation.csv -NoTypeInformation
# 12. Summary
Write-Host "[12/12] Generating summary..."
Write-Host ""
Write-Host "[*] Investigation complete!"
Write-Host "[*] Results saved to: $OutputDir"
Write-Host "[*] Review priority:"
Write-Host " 1. 01_hidden_accounts.txt (hidden accounts)"
Write-Host " 2. 02_unsigned_processes.txt (unsigned processes)"
Write-Host " 3. 03_external_connections.txt (external connections)"
Write-Host " 4. 04_suspicious_services.txt (suspicious services)"
Write-Host " 5. 05_suspicious_tasks.csv (suspicious tasks)"
Write-Host " 6. 08_wmi_consumers.txt (WMI persistence)"
Write-Host " 7. 11_log_cleared.txt (log clearing)"
Linux完整排查脚本:
#!/bin/bash
# Linux Incident Response Investigation Script
# Author: IR Team
# Usage: sudo ./linux_ir.sh
if [ "$(id -u)" -ne 0 ]; then
echo "Please run as root"
exit 1
fi
OUTPUT_DIR="/tmp/ir_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$OUTPUT_DIR"
echo "[*] Starting Linux IR Investigation"
echo "[*] Output directory: $OUTPUT_DIR"
echo ""
# 1. Account Analysis
echo "[1/14] Analyzing accounts..."
cat /etc/passwd > "$OUTPUT_DIR/01_passwd.txt" 2>&1
cat /etc/shadow > "$OUTPUT_DIR/01_shadow.txt" 2>&1
cat /etc/group > "$OUTPUT_DIR/01_group.txt" 2>&1
# UID=0账号
awk -F: '$3==0 {print $1}' /etc/passwd > "$OUTPUT_DIR/01_uid0_accounts.txt" 2>&1
# 空密码账号
awk -F: '($2=="!" || $2=="*" || $2=="") {print $1}' /etc/shadow > "$OUTPUT_DIR/01_empty_password.txt" 2>&1
# 可登录账号
grep -v "nologin\|/false" /etc/passwd > "$OUTPUT_DIR/01_loginable_accounts.txt" 2>&1
# 最近创建账号
lastlog > "$OUTPUT_DIR/01_lastlog.txt" 2>&1
# 2. Process Analysis
echo "[2/14] Analyzing processes..."
ps -auxwf > "$OUTPUT_DIR/02_ps.txt" 2>&1
top -b -n 1 > "$OUTPUT_DIR/02_top.txt" 2>&1
# 查找反弹shell
ps -auxwf | grep -E "nc |ncat |socat |bash -i|/dev/tcp|python.*import|perl.*socket|ruby.*socket" | grep -v grep > "$OUTPUT_DIR/02_reverse_shell.txt" 2>&1
# 隐藏进程检测
ls -d /proc/[0-9]* 2>/dev/null | awk -F/ '{print $3}' | sort -n > /tmp/proc_pids
ps -e --no-headers -o pid | sort -n > /tmp/ps_pids
echo "Hidden processes:" > "$OUTPUT_DIR/02_hidden_procs.txt"
comm -13 /tmp/ps_pids /tmp/proc_pids >> "$OUTPUT_DIR/02_hidden_procs.txt"
# 3. Network Analysis
echo "[3/14] Analyzing network..."
ss -tunlp > "$OUTPUT_DIR/03_ss.txt" 2>&1
netstat -antp > "$OUTPUT_DIR/03_netstat.txt" 2>&1
lsof -i -nP > "$OUTPUT_DIR/03_lsof.txt" 2>&1
# 异常外联
ss -ant | grep ESTAB | grep -v "127.0.0.1" | grep -vE "10\.|172\.(1[6-9]|2[0-9]|3[01])\.|192\.168\." > "$OUTPUT_DIR/03_external_connections.txt" 2>&1
# 4. File Analysis
echo "[4/14] Analyzing files..."
find / -mtime -1 -type f -exec ls -la {} \; 2>/dev/null > "$OUTPUT_DIR/04_recent_files.txt" &
# SUID文件
find / -perm -4000 -type f -exec ls -la {} \; 2>/dev/null > "$OUTPUT_DIR/04_suid_files.txt" &
# 临时目录可执行文件
find /tmp /var/tmp /dev/shm -type f -executable 2>/dev/null > "$OUTPUT_DIR/04_tmp_executables.txt" &
# 隐藏文件
find / -name ".*" -type f 2>/dev/null > "$OUTPUT_DIR/04_hidden_files.txt" &
wait
# 5. Package Integrity
echo "[5/14] Checking package integrity..."
if command -v rpm &> /dev/null; then
rpm -Va > "$OUTPUT_DIR/05_rpm_verify.txt" 2>&1
elif command -v dpkg &> /dev/null; then
dpkg -V > "$OUTPUT_DIR/05_dpkg_verify.txt" 2>&1
fi
# 6. Crontab Analysis
echo "[6/14] Analyzing crontab..."
for user in $(cut -d: -f1 /etc/passwd); do
content=$(crontab -l -u "$user" 2>/dev/null)
if [ -n "$content" ]; then
echo "=== $user ===" >> "$OUTPUT_DIR/06_crontab.txt"
echo "$content" >> "$OUTPUT_DIR/06_crontab.txt"
fi
done
cat /etc/crontab >> "$OUTPUT_DIR/06_crontab.txt" 2>&1
ls -la /etc/cron.d/ >> "$OUTPUT_DIR/06_crontab.txt" 2>&1
for dir in hourly daily weekly monthly; do
echo "=== /etc/cron.$dir ===" >> "$OUTPUT_DIR/06_crontab.txt"
ls -la /etc/cron.$dir/ >> "$OUTPUT_DIR/06_crontab.txt" 2>&1
done
# 7. Systemd Analysis
echo "[7/14] Analyzing systemd..."
systemctl list-unit-files --state=enabled --type=service > "$OUTPUT_DIR/07_systemd_enabled.txt" 2>&1
systemctl list-units --type=service --state=running > "$OUTPUT_DIR/07_systemd_running.txt" 2>&1
systemctl list-timers --all > "$OUTPUT_DIR/07_systemd_timers.txt" 2>&1
# 查找可疑服务
find /etc/systemd /lib/systemd /usr/lib/systemd -name "*.service" -exec grep -l "ExecStart.*\(bash\|python\|nc\|ncat\|socat\|curl\|wget\)" {} \; 2>/dev/null > "$OUTPUT_DIR/07_suspicious_services.txt"
# 8. SSH Analysis
echo "[8/14] Analyzing SSH..."
grep "Accepted" /var/log/secure /var/log/auth.log 2>/dev/null | tail -50 > "$OUTPUT_DIR/08_ssh_success.txt" 2>&1
grep "Failed password" /var/log/secure /var/log/auth.log 2>/dev/null | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head -20 > "$OUTPUT_DIR/08_ssh_brute_force.txt" 2>&1
# SSH密钥检查
find / -name "authorized_keys" -exec ls -la {} \; 2>/dev/null > "$OUTPUT_DIR/08_authorized_keys.txt" 2>&1
find / -name "authorized_keys" -exec sh -c 'echo "=== {} ==="; cat {}' \; 2>/dev/null >> "$OUTPUT_DIR/08_authorized_keys.txt" 2>&1
# SSH配置
grep -E "PermitRootLogin|PasswordAuthentication|Port|AllowUsers" /etc/ssh/sshd_config > "$OUTPUT_DIR/08_ssh_config.txt" 2>&1
# 9. History Analysis
echo "[9/14] Analyzing command history..."
for user_home in /root /home/*; do
if [ -f "$user_home/.bash_history" ]; then
echo "=== $user_home/.bash_history ===" >> "$OUTPUT_DIR/09_bash_history.txt"
cat "$user_home/.bash_history" >> "$OUTPUT_DIR/09_bash_history.txt"
fi
done
# 可疑命令
grep -E "wget|curl|nc |ncat|bash -i|python.*import|perl.*socket|chmod.*777|useradd|passwd|sudo|su -|export.*PATH|base64" "$OUTPUT_DIR/09_bash_history.txt" > "$OUTPUT_DIR/09_suspicious_commands.txt" 2>&1
# 10. Environment Analysis
echo "[10/14] Analyzing environment..."
env > "$OUTPUT_DIR/10_env.txt" 2>&1
echo "LD_PRELOAD: $LD_PRELOAD" >> "$OUTPUT_DIR/10_env.txt" 2>&1
cat /etc/ld.so.preload 2>/dev/null >> "$OUTPUT_DIR/10_env.txt" 2>&1
cat /etc/profile >> "$OUTPUT_DIR/10_profile.txt" 2>&1
for user_home in /root /home/*; do
echo "=== $user_home/.bashrc ===" >> "$OUTPUT_DIR/10_bashrc.txt"
cat "$user_home/.bashrc" 2>/dev/null >> "$OUTPUT_DIR/10_bashrc.txt"
echo "=== $user_home/.profile ===" >> "$OUTPUT_DIR/10_bashrc.txt"
cat "$user_home/.profile" 2>/dev/null >> "$OUTPUT_DIR/10_bashrc.txt"
done
# 11. Kernel Module Analysis
echo "[11/14] Analyzing kernel modules..."
lsmod > "$OUTPUT_DIR/11_lsmod.txt" 2>&1
cat /proc/modules > "$OUTPUT_DIR/11_proc_modules.txt" 2>&1
# 对比lsmod和/proc/modules
diff <(lsmod | tail -n +2 | awk '{print $1}' | sort) <(cat /proc/modules | awk '{print $1}' | sort) > "$OUTPUT_DIR/11_module_diff.txt" 2>&1
# 12. Rootkit Scan
echo "[12/14] Scanning for rootkits..."
if command -v rkhunter &> /dev/null; then
rkhunter --check --sk --report-warnings-only > "$OUTPUT_DIR/12_rkhunter.txt" 2>&1
fi
if command -v chkrootkit &> /dev/null; then
chkrootkit > "$OUTPUT_DIR/12_chkrootkit.txt" 2>&1
fi
# 13. Log Analysis
echo "[13/14] Analyzing logs..."
# 检查日志是否被清除
ls -la /var/log/ > "$OUTPUT_DIR/13_log_files.txt" 2>&1
# 检查secure/auth日志是否被清空
if [ -f /var/log/secure ]; then
echo "secure log size: $(wc -c < /var/log/secure)" >> "$OUTPUT_DIR/13_log_check.txt"
fi
if [ -f /var/log/auth.log ]; then
echo "auth.log size: $(wc -c < /var/log/auth.log)" >> "$OUTPUT_DIR/13_log_check.txt"
fi
# journalctl
journalctl --since "3 days ago" -p err > "$OUTPUT_DIR/13_journal_errors.txt" 2>&1
# 14. Startup Analysis
echo "[14/14] Analyzing startup..."
cat /etc/rc.local 2>/dev/null > "$OUTPUT_DIR/14_rc_local.txt" 2>&1
ls -la /etc/init.d/ > "$OUTPUT_DIR/14_initd.txt" 2>&1
chkconfig --list 2>/dev/null > "$OUTPUT_DIR/14_chkconfig.txt" 2>&1
echo ""
echo "[*] Investigation complete!"
echo "[*] Results saved to: $OUTPUT_DIR"
echo "[*] Review priority:"
echo " 1. 01_uid0_accounts.txt (UID=0 accounts)"
echo " 2. 02_reverse_shell.txt (reverse shells)"
echo " 3. 03_external_connections.txt (external connections)"
echo " 4. 04_suid_files.txt (SUID files)"
echo " 5. 06_crontab.txt (scheduled tasks)"
echo " 6. 07_suspicious_services.txt (suspicious services)"
echo " 7. 08_authorized_keys.txt (SSH backdoor keys)"
echo " 8. 09_suspicious_commands.txt (suspicious commands)"
echo " 9. 11_module_diff.txt (hidden kernel modules)"
echo " 10. 12_rkhunter.txt (rootkit scan)"
9.5 排查优先级表
| 优先级 | 排查项 | 理由 |
|---|---|---|
| P0 紧急 | 网络异常外联 | 确认C2连接,阻断数据外泄 |
| P0 紧急 | 异常进程 | 确认恶意进程运行状态 |
| P1 高 | 账号异常 | 排查后门账号 |
| P1 高 | 持久化机制 | 消除驻留后门 |
| P2 中 | 文件分析 | 确认恶意文件范围 |
| P2 中 | 日志分析 | 还原攻击路径 |
| P3 低 | 内核模块 | 检查Rootkit |
| P3 低 | 配置审查 | 发现配置篡改 |
十、威胁清除与系统恢复
10.1 隔离方案
网络隔离:
# Windows网络隔离
# 方法一:禁用网卡
netsh interface set interface "以太网" disable
# 方法二:阻断所有出站(保留本地)
netsh advfirewall set allprofiles firewall policy blockinbound,blockoutbound
# 方法三:添加阻断规则
netsh advfirewall firewall add rule name="Block All Outbound" dir=out action=block enable=yes
# Linux网络隔离
# 方法一:关闭网卡
ip link set eth0 down
# 方法二:iptables阻断所有出站(保留管理SSH)
iptables -A OUTPUT -d 127.0.0.1 -j ACCEPT
iptables -A OUTPUT -p tcp --sport 22 -j ACCEPT
iptables -A OUTPUT -j DROP
# 方法三:修改路由
ip route del default
主机隔离:
# Windows断开网络但保留本地管理
# 保留RDP管理,阻断其他
netsh advfirewall firewall add rule name="Allow RDP" dir=in protocol=TCP localport=3389 action=allow
netsh advfirewall firewall add rule name="Block All Inbound" dir=in action=block
netsh advfirewall firewall add rule name="Block All Outbound" dir=out action=block
10.2 恶意进程清除
# Windows
# 终止指定进程
taskkill /F /PID <PID>
taskkill /F /IM malware.exe
# 终止进程树
taskkill /F /T /PID <PID>
# 查找并终止指定路径的进程
Get-Process | Where-Object { $_.Path -match "malware" } | Stop-Process -Force
# 终止子进程后终止父进程
$proc = Get-Process -Name "malware"
$children = Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq $proc.Id }
$children | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }
Stop-Process -Id $proc.Id -Force
# Linux
# 终止进程
kill -9 <PID>
killall -9 malware_name
# 终止进程及其子进程
pkill -9 -P <PPID>
# 通过进程名终止
pkill -9 -f "malware"
pkill -9 -f "/tmp/malware"
# 终止指定用户所有进程
pkill -9 -u malicious_user
10.3 后门清除
文件后门清除:
# Windows删除恶意文件
Remove-Item -Path "C:\temp\malware.exe" -Force
Remove-Item -Path "C:\Users\Public\backdoor.dll" -Force
# 删除隐藏文件
Remove-Item -Path "C:\temp\malware.exe" -Force -Hidden
# 删除ADS流
Remove-Item -Path "C:\temp\file.txt:malware_stream"
# Linux删除恶意文件
rm -f /tmp/malware
rm -f /var/tmp/backdoor
rm -f /dev/shm/.hidden_file
# 安全删除(覆盖后删除)
shred -u -z /tmp/malware
服务后门清除:
# Windows
# 删除服务
sc stop "MalwareService"
sc delete "MalwareService"
# PowerShell方式
Remove-Service -Name "MalwareService"
# Linux
# 停止并禁用服务
systemctl stop malware.service
systemctl disable malware.service
# 删除服务文件
rm -f /etc/systemd/system/malware.service
rm -f /lib/systemd/system/malware.service
systemctl daemon-reload
注册表后门清除:
# 清除Run键后门
Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" -Name "MalwareEntry"
Remove-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" -Name "MalwareEntry"
# 清除IFEO后门
Remove-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\target.exe" -Recurse
# 清除Winlogon后门
Remove-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name "Userinit" # 注意恢复默认值
# 清除AppInit_DLLs
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows" -Name "AppInit_DLLs" -Value ""
计划任务后门清除:
# Windows
schtasks /delete /TN "MalwareTask" /F
Get-ScheduledTask -TaskName "MalwareTask" | Unregister-ScheduledTask
# Linux
crontab -l -u root | grep -v "malware" | crontab -u root -
rm -f /etc/cron.d/malware
rm -f /var/spool/cron/malware_user
10.4 账号清理
# Windows
# 禁用恶意账号
net user "malicious_user" /active:no
# 删除恶意账号
net user "malicious_user" /delete
# 从管理员组移除
net localgroup administrators "malicious_user" /delete
# 重置管理员密码
net user administrator "NewStrongPassword123!"
# Linux
# 锁定账号
usermod -L malicious_user
# 删除账号
userdel -r malicious_user
# 从sudo组移除
gpasswd -d malicious_user sudo
# 恢复root密码
passwd root
10.5 系统重建策略
| 策略 | 适用场景 | 优点 | 缺点 |
|---|---|---|---|
| 清理修复 | 后门明确、范围可控 | 恢复快、成本低 | 可能有残留后门 |
| 系统重建 | 后门多、Rootkit感染 | 彻底清除 | 恢复慢、成本高 |
| 镜像恢复 | 有干净备份镜像 | 快速恢复 | 需有备份基础 |
| 临时修复 | 紧急恢复业务 | 极速恢复 | 仅为过渡方案 |
10.6 恢复验证清单
| 验证项 | 验证方法 | 通过标准 |
|---|---|---|
| 网络连接 | netstat/ss检查 | 无异常外联 |
| 进程列表 | ps/tasklist | 无恶意进程 |
| 账号状态 | net user / getent passwd | 无异常账号 |
| 服务列表 | sc query / systemctl | 无可疑服务 |
| 计划任务 | schtasks / crontab -l | 无可疑任务 |
| 启动项 | Autoruns / rc.local | 无可疑启动项 |
| 文件完整性 | rpm -Va / SFC | 系统文件完好 |
| 日志监控 | 事件查看器 / journalctl | 72小时无异常 |
| 后门检测 | rkhunter / malfind | 无后门残留 |
| 漏洞修复 | 补丁检查 | 已修复入口漏洞 |
十一、事件溯源与时间线分析
11.1 时间线构建方法
事件溯源的核心是构建完整的时间线,将分散在多系统多源头的日志关联起来,还原攻击者的完整活动轨迹。时间线分析的基本步骤如下:
步骤一:确定时间基准。 确保所有分析设备的时钟同步(NTP),否则时间关联将失效。检查系统时区设置,统一时间格式。
步骤二:收集多源日志。 从安全设备(IDS/IPS/WAF/EDR)、系统日志(Windows/Linux)、应用日志(Web/数据库)、网络流量(pcap)等多个来源收集日志。
步骤三:统一时间格式。 将不同来源的时间戳统一为ISO 8601格式(YYYY-MM-DDTHH:MM:SS.sssZ),消除时区差异。
步骤四:关联分析。 按时间排序所有事件,识别因果关系,构建攻击链条。
步骤五:标注关键节点。 标记攻击的初始访问、执行、持久化、提权、防御绕过、凭据访问、发现、横向移动、收集、外泄等阶段。
11.2 日志关联分析
# 使用log2timeline构建统一时间线(plaso框架)
# 安装plaso
pip3 install plaso
# 从Windows evtx日志生成时间线
log2timeline.py timeline.windows /path/to/Security.evtx --parsers winevtx
# 从多个日志源生成统一时间线
log2timeline.py timeline.case1 /path/to/logs/ --parsers winevtx,syslog,apache_access,bash_history
# 使用psort分析时间线
psort.py -o timeline_output.csv -w csv timeline.case1 "source host eq '192.168.1.100'"
# 按时间范围过滤
psort.py -o filtered_timeline.csv -w csv timeline.case1 "date > '2026-08-19 00:00:00' and date < '2026-08-19 23:59:59'"
# 按分析器过滤(只看特定事件类型)
psort.py -o events.csv -w csv timeline.case1 "parser contains 'winevtx'"
# 使用Timesketch进行可视化时间线分析(Web界面)
# Timesketch是Google开源的时间线分析工具
pip3 install timesketch
# 导入plaso文件到Timesketch
# psort.py -o timesketch timeline.case1 "timesketch_server"
手动关联分析示例:
#!/usr/bin/env python3
"""
Timeline correlation analysis script
Reads multiple log sources and creates a unified timeline
"""
import re
import sys
from datetime import datetime
events = []
# Parse Windows Security log (CSV export from LogParser)
def parse_windows_log(file_path):
with open(file_path, 'r') as f:
for line in f:
parts = line.strip().split(',')
if len(parts) >= 3:
timestamp_str = parts[0]
event_id = parts[1]
details = parts[2]
try:
dt = datetime.strptime(timestamp_str, '%Y-%m-%d %H:%M:%S')
events.append({
'time': dt,
'source': 'Windows',
'event_id': event_id,
'details': details
})
except ValueError:
pass
# Parse Apache access log
def parse_apache_log(file_path):
pattern = r'^(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+) (\S+)" (\d+) (\d+)'
with open(file_path, 'r') as f:
for line in f:
match = re.match(pattern, line)
if match:
ip = match.group(1)
timestamp_str = match.group(2)
method = match.group(3)
uri = match.group(4)
status = match.group(6)
try:
dt = datetime.strptime(timestamp_str, '%d/%b/%Y:%H:%M:%S')
events.append({
'time': dt,
'source': 'Apache',
'event_id': f'{method} {uri} {status}',
'details': f'IP={ip} {method} {uri} Status={status}'
})
except ValueError:
pass
# Parse Linux syslog
def parse_syslog(file_path):
pattern = r'^(\w{3}\s+\d+\s+\d+:\d+:\d+)\s+\S+\s+(.*)'
with open(file_path, 'r') as f:
for line in f:
match = re.match(pattern, line)
if match:
timestamp_str = f'2026 {match.group(1)}'
message = match.group(2)
try:
dt = datetime.strptime(timestamp_str, '%Y %b %d %H:%M:%S')
events.append({
'time': dt,
'source': 'Syslog',
'event_id': '',
'details': message
})
except ValueError:
pass
# Build and output timeline
def output_timeline(output_file):
events.sort(key=lambda x: x['time'])
with open(output_file, 'w') as f:
f.write('Time,Source,EventID,Details\n')
for event in events:
f.write(f"{event['time'].isoformat()},{event['source']},{event['event_id']},{event['details']}\n")
print(f"[+] Timeline written to {output_file}")
print(f"[+] Total events: {len(events)}")
if __name__ == '__main__':
output = sys.argv[1] if len(sys.argv) > 1 else 'timeline.csv'
# Parse log files (adjust paths as needed)
parse_windows_log('windows_events.csv')
parse_apache_log('access.log')
parse_syslog('/var/log/syslog')
output_timeline(output)
11.3 IOC提取与关联
IOC(Indicators of Compromise,入侵指标)是识别攻击者活动的特征数据,包括以下类型:
| IOC类型 | 示例 | 提取来源 |
|---|---|---|
| IP地址 | 192.168.1.100 | 日志、流量、内存 |
| 域名 | evil.malware.com | DNS日志、流量、配置 |
| 文件哈希 | SHA256: a1b2c3… | 文件系统、内存 |
| URL | http://evil.com/payload.exe | Web日志、流量 |
| 邮箱 | attacker@evil.com | 邮件日志、配置 |
| 证书指纹 | TLS证书SHA256 | 流量、配置 |
| 注册表键 | HKLM…\Run\Malware | 内存、注册表 |
| Mutex | Global\MutexName | 进程分析、内存 |
IOC自动化提取与匹配:
# 使用find命令批量提取文件哈希
find / -type f -name "*.exe" -exec sha256sum {} \; 2>/dev/null > file_hashes.txt
find / -type f -name "*.dll" -exec sha256sum {} \; 2>/dev/null >> file_hashes.txt
# 提取日志中的IP地址
grep -oE '([0-9]{1,3}\.){3}[0-9]{1,3}' /var/log/syslog | sort -u > ioc_ips.txt
# 提取日志中的URL
grep -oE 'https?://[a-zA-Z0-9./?=_-]+' /var/log/syslog | sort -u > ioc_urls.txt
# 从DNS日志提取域名
grep "A " /var/log/named/*.log 2>/dev/null | awk '{print $NF}' | sort -u > ioc_domains.txt
# 使用OpenCTI进行IOC管理和关联(开源威胁情报平台)
# 支持IOC导入、关联分析、可视化
pip3 install opencti
# VirusTotal批量查询IP信誉
for ip in $(cat ioc_ips.txt); do
result=$(curl -s "https://www.virustotal.com/api/v3/ip_addresses/$ip" \
-H "x-apikey: YOUR_API_KEY" | jq -r '.data.attributes.last_analysis_stats')
echo "$ip: $result"
done
# 查询域名信誉(使用多个威胁情报源)
for domain in $(cat ioc_domains.txt); do
echo "=== $domain ==="
# VirusTotal
curl -s "https://www.virustotal.com/api/v3/domains/$domain" \
-H "x-apikey: YOUR_API_KEY" | jq -r '.data.attributes.last_analysis_stats.malicious' 2>/dev/null
# AlienVault OTX
curl -s "https://otx.alienvault.com/api/v1/indicators/domain/$domain/general" | jq -r '.pulse_info.count' 2>/dev/null
echo ""
done
11.4 攻击路径还原
攻击路径还原是溯源分析的核心目标,需要将时间线上的事件按照攻击者行为进行分组和关联。参考MITRE ATT&CK框架的战术和技术分类:
| 战术阶段 | 典型行为 | 对应日志/痕迹 |
|---|---|---|
| 初始访问 | 钓鱼邮件、漏洞利用 | 邮件日志、Web日志、IDS告警 |
| 执行 | 运行恶意代码 | 进程创建日志、Sysmon事件1 |
| 持久化 | 创建后门 | 注册表Run键、计划任务、服务创建 |
| 提权 | 利用漏洞提权 | 日志中特权提升事件 |
| 防御绕过 | 禁用杀软、清除日志 | 日志清除事件、安全软件状态变更 |
| 凭据访问 | Mimikatz、密码转储 | lsass进程访问、凭据相关事件 |
| 发现 | 内网扫描、信息收集 | 网络扫描流量、AD查询日志 |
| 横向移动 | 横向登录、文件传输 | 4624登录事件、SMB流量 |
| 收集 | 数据打包、压缩 | 文件操作日志、大文件创建 |
| 外泄 | 数据外传 | 异常出站流量、DNS隧道 |
11.5 影响范围评估
# 评估受影响主机范围
# 1. 查找与恶意IP通信的所有主机
for ip in $(cat ioc_ips.txt); do
echo "=== Hosts communicating with $ip ==="
grep "$ip" /var/log/firewall.log 2>/dev/null | awk '{print $1}' | sort -u
grep "$ip" /var/log/iptables.log 2>/dev/null | awk '{print $1}' | sort -u
done
# 2. 查找所有访问恶意域名的DNS查询
for domain in $(cat ioc_domains.txt); do
echo "=== Hosts querying $domain ==="
grep "$domain" /var/log/named/*.log 2>/dev/null | awk '{print $1}' | sort -u
done
# 3. 查找所有运行恶意文件的主机
for hash in $(cat ioc_hashes.txt); do
echo "=== Hosts with file hash $hash ==="
# 在SIEM中搜索该哈希
# 在EDR中搜索该哈希
done
# 4. 生成受影响主机清单
cat > impact_assessment.md << 'EOF'
# Impact Assessment Report
## Confirmed Compromised Hosts
| Host IP | Hostname | Evidence | First Seen | Last Seen |
|---|---|---|---|---|
| 192.168.1.100 | WEB01 | C2 connection, Webshell | 2026-08-19 10:00 | 2026-08-19 14:00 |
## Potentially Affected Hosts
| Host IP | Hostname | Evidence | Risk Level |
|---|---|---|---|
| 192.168.1.101 | DB01 | Lateral movement from WEB01 | High |
## Unaffected Hosts
| Host IP | Hostname | Notes |
|---|---|---|
| 192.168.1.200 | MAIL01 | No indicators found |
EOF
11.6 溯源报告编写
完整的溯源报告应包含以下结构:
| 章节 | 内容 |
|---|---|
| 事件概述 | 事件摘要、影响范围、严重程度 |
| 检测过程 | 如何发现的、告警详情 |
| 攻击时间线 | 完整时间线表格 |
| 攻击路径 | MITRE ATT&CK映射 |
| 影响评估 | 受影响系统、数据泄露评估 |
| IOC列表 | IP/域名/哈希/URL |
| 处置措施 | 已采取的遏制和根除措施 |
| 改进建议 | 安全加固、流程改进建议 |
| 附录 | 原始日志、取证文件清单 |
十二、应急响应工具箱
12.1 Windows工具集
| 工具 | 类别 | 用途 | 获取方式 |
|---|---|---|---|
| Autoruns | 持久化 | 自启动项分析 | Sysinternals官网 |
| Process Explorer | 进程分析 | 进程树、DLL、句柄分析 | Sysinternals官网 |
| Process Monitor | 行为监控 | 文件/注册表/网络操作监控 | Sysinternals官网 |
| TCPView | 网络分析 | 实时网络连接监控 | Sysinternals官网 |
| WinDbg | 调试 | 内核级调试与内存分析 | Windows SDK |
| RegShot | 注册表 | 注册表快照对比 | GitHub |
| Redline | 取证 | 主机快速取证分析 | FireEye/Mandiant |
| KAPE | 取证 | 快速证据收集 | GitHub |
| Volatility | 内存取证 | 内存镜像分析 | GitHub |
| LogParser | 日志分析 | Windows日志查询分析 | 微软 |
| FTK Imager | 磁盘取证 | 磁盘镜像和内存获取 | Exterro |
| DumpIt | 内存获取 | 一键内存镜像获取 | GitHub |
| WinDbg Preview | 调试 | 高级内核调试 | Windows Store |
| PEview | PE分析 | PE文件结构查看 | GitHub |
| pestudio | PE分析 | PE文件静态分析 | Valhalla |
KAPE快速取证工具使用:
# 下载和安装KAPE
# 从GitHub下载: https://github.com/EricZimmerman/Kape
# 解压后使用
# 使用KAPE收集证据(_kape CLI)
.\_kape.cli --tsource C:\ --tdest E:\collection --target KapeTriage --module sync
# 使用特定模块收集
.\_kape.cli --msource E:\collection --mdest E:\analysis --module !EZParser
# 收集特定证据类型
.\_kape.cli --tsource C:\ --tdest E:\collection --target RegistryHives --target EventLogs
# 运行分析模块
.\_kape.cli --msource E:\collection --mdest E:\analysis --module WindowsEventsParser --module LECmd
12.2 Linux工具集
| 工具 | 类别 | 用途 | 获取方式 |
|---|---|---|---|
| SIFT | 取证套件 | 完整的取证工具集 | SANS |
| REMnux | 恶意代码分析 | 恶意软件分析系统 | GitHub |
| LiME | 内存获取 | Linux内存镜像 | GitHub |
| Volatility | 内存取证 | 内存镜像分析 | pip3 |
| The Sleuth Kit | 磁盘取证 | 磁盘镜像分析 | apt |
| chkrootkit | Rootkit检测 | Linux Rootkit扫描 | apt |
| rkhunter | Rootkit检测 | Linux Rootkit扫描 | apt |
| auditd | 审计 | 系统审计日志 | 系统自带 |
| inotify-tools | 文件监控 | 文件变更实时监控 | apt |
| busybox | 应急工具 | 嵌入式工具集 | apt |
SIFT工作站常用命令:
# SIFT工作站的预配置工具
# 镜像挂载
ewfmount image.E01 /mnt/ewf
mount -o ro,loop,showfiles /mnt/ewf/ewf1 /mnt/disk
# 使用The Sleuth Kit分析
fls -r /mnt/disk # 列出所有文件
fls -rd /mnt/disk # 列出已删除文件
icat /mnt/disk <inode> # 按inode提取文件
istat /mnt/disk <inode> # 显示inode信息
ils /mnt/disk # 列出已删除inode
mmls /mnt/disk # 显示分区表
fsstat /mnt/disk # 显示文件系统信息
# 使用log2timeline
log2timeline.py timeline /mnt/disk --parsers linux_syslog,linux_bash,webserver
psort.py -o timeline.csv -w csv timeline
# 使用Volatility分析Linux内存
vol.py -f memory.raw linux.pslist
vol.py -f memory.raw linux.bash
vol.py -f memory.raw linux.check_syscall
vol.py -f memory.raw linux.check_modules
vol.py -f memory.raw linux.tainted_modules
vol.py -f memory.raw linux.proc.maps
12.3 便携工具包制作
# 制作Windows便携应急响应工具包
# 目录结构:
# IR_Toolkit/
# ├── Windows/
# │ ├── Sysinternals/
# │ ├── Volatility/
# │ ├── KAPE/
# │ ├── LogParser/
# │ ├── scripts/
# │ └── IR_Launcher.bat
# ├── Linux/
# │ ├── scripts/
# │ └── IR_Launcher.sh
# └── IOC/
# ├── ioc_ips.txt
# ├── ioc_domains.txt
# └── yara_rules.yar
# Windows启动脚本 IR_Launcher.bat
cat > IR_Launcher.bat << 'BATCH'
@echo off
echo ============================================
echo Incident Response Toolkit Launcher
echo ============================================
echo.
echo [1] Full IR Investigation (Collect All)
echo [2] Process Analysis Only
echo [3] Network Analysis Only
echo [4] Persistence Analysis Only
echo [5] Memory Acquisition
echo [6] Log Analysis
echo [7] Exit
echo.
set /p choice="Select option: "
if "%choice%"=="1" goto full
if "%choice%"=="2" goto process
if "%choice%"=="3" goto network
if "%choice%"=="4" goto persist
if "%choice%"=="5" goto memory
if "%choice%"=="6" goto logs
if "%choice%"=="7" exit
:full
echo Running full investigation...
powershell -ExecutionPolicy Bypass -File scripts\windows_ir.ps1
goto end
:process
echo Process analysis...
autoruns.exe -a -m -s processes.txt
procdump.exe -accepteula -ma -i
tasklist /v /fo csv > processes.csv
goto end
:network
echo Network analysis...
netstat -ano > netstat.txt
TCPView.exe /accepteula
goto end
:persist
echo Persistence analysis...
autoruns.exe -a -m -s persistence.txt
schtasks /query /fo LIST /v > schtasks.txt
reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" > run_hklm.txt
reg query "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" > run_hkcu.txt
goto end
:memory
echo Memory acquisition...
DumpIt.exe
goto end
:logs
echo Log analysis...
wevtutil epl Security Security.evtx
wevtutil epl System System.evtx
wevtutil epl Application Application.evtx
goto end
:end
echo.
echo Investigation complete. Review output files.
pause
BATCH
# Linux启动脚本 IR_Launcher.sh
cat > IR_Launcher.sh << 'BASH'
#!/bin/bash
echo "============================================"
echo " Incident Response Toolkit Launcher"
echo "============================================"
echo
echo "[1] Full IR Investigation (Collect All)"
echo "[2] Process Analysis Only"
echo "[3] Network Analysis Only"
echo "[4] Persistence Analysis Only"
echo "[5] Memory Acquisition (LiME)"
echo "[6] Log Analysis"
echo "[7] Exit"
echo
read -p "Select option: " choice
case $choice in
1)
echo "Running full investigation..."
bash scripts/linux_ir.sh
;;
2)
echo "Process analysis..."
ps -auxwf > processes.txt
lsof -i -nP > network_lsof.txt
;;
3)
echo "Network analysis..."
ss -tunlp > ss.txt
netstat -antp > netstat.txt
;;
4)
echo "Persistence analysis..."
for user in $(cut -d: -f1 /etc/passwd); do
crontab -l -u $user 2>/dev/null >> crontab_all.txt
done
systemctl list-unit-files --state=enabled --type=service > systemd_enabled.txt
;;
5)
echo "Memory acquisition..."
insmod lime.ko "path=/tmp/memory.raw format=raw"
;;
6)
echo "Log analysis..."
grep "Accepted" /var/log/secure /var/log/auth.log 2>/dev/null > ssh_logins.txt
grep "Failed password" /var/log/secure /var/log/auth.log 2>/dev/null > ssh_brute.txt
;;
7)
exit 0
;;
esac
echo
echo "Investigation complete. Review output files."
BASH
chmod +x IR_Launcher.sh
12.4 自动化应急脚本
自动化IOC扫描脚本:
#!/bin/bash
# IOC Scanner - Scan system for known indicators of compromise
# Usage: ./ioc_scanner.sh <ioc_file>
IOC_FILE=$1
OUTPUT_DIR="./ioc_scan_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$OUTPUT_DIR"
echo "[*] IOC Scanner"
echo "[*] IOC file: $IOC_FILE"
echo "[*] Output: $OUTPUT_DIR"
echo ""
# Function to scan for IP IOCs
scan_ips() {
echo "[*] Scanning for malicious IPs..."
grep -E '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' "$IOC_FILE" | while read ip; do
echo "Checking IP: $ip"
# Check network connections
connections=$(ss -antp 2>/dev/null | grep "$ip")
if [ -n "$connections" ]; then
echo "[ALERT] Active connection to malicious IP: $ip" | tee -a "$OUTPUT_DIR/ip_alerts.txt"
echo "$connections" | tee -a "$OUTPUT_DIR/ip_alerts.txt"
fi
# Check logs
log_hits=$(grep "$ip" /var/log/secure /var/log/auth.log /var/log/messages /var/log/syslog 2>/dev/null)
if [ -n "$log_hits" ]; then
echo "[FOUND] IP $ip found in logs" | tee -a "$OUTPUT_DIR/ip_log_hits.txt"
echo "$log_hits" | head -10 | tee -a "$OUTPUT_DIR/ip_log_hits.txt"
fi
done
}
# Function to scan for file hash IOCs
scan_hashes() {
echo "[*] Scanning for malicious file hashes..."
grep -E '^[a-f0-9]{64}$' "$IOC_FILE" | while read hash; do
echo "Checking hash: $hash"
# Scan all executable files
find / -type f -executable -exec sha256sum {} \; 2>/dev/null | grep "$hash" | while read match; do
echo "[ALERT] Malicious file found: $match" | tee -a "$OUTPUT_DIR/hash_alerts.txt"
done
done
}
# Function to scan for domain IOCs
scan_domains() {
echo "[*] Scanning for malicious domains..."
grep -E '^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.[a-zA-Z]{2,}$' "$IOC_FILE" | while read domain; do
echo "Checking domain: $domain"
# Check DNS logs
dns_hits=$(grep "$domain" /var/log/named/*.log /var/log/dnsmasq.log 2>/dev/null)
if [ -n "$dns_hits" ]; then
echo "[ALERT] DNS query to malicious domain: $domain" | tee -a "$OUTPUT_DIR/domain_alerts.txt"
echo "$dns_hits" | head -10 | tee -a "$OUTPUT_DIR/domain_alerts.txt"
fi
# Check /etc/hosts
hosts_hit=$(grep "$domain" /etc/hosts 2>/dev/null)
if [ -n "$hosts_hit" ]; then
echo "[ALERT] Malicious domain in /etc/hosts: $domain" | tee -a "$OUTPUT_DIR/domain_alerts.txt"
fi
done
}
# Function to scan for filename IOCs
scan_filenames() {
echo "[*] Scanning for malicious filenames..."
grep -E '^\S+\.\S+$' "$IOC_FILE" | grep -vE '^[0-9]+\.' | while read filename; do
echo "Checking filename: $filename"
find / -name "$filename" 2>/dev/null | while read filepath; do
echo "[ALERT] Malicious file found: $filepath" | tee -a "$OUTPUT_DIR/file_alerts.txt"
done
done
}
# Run all scans
scan_ips
scan_hashes
scan_domains
scan_filenames
echo ""
echo "[*] Scan complete. Results in $OUTPUT_DIR/"
echo "[*] Summary:"
for f in "$OUTPUT_DIR"/*.txt; do
if [ -f "$f" ]; then
count=$(wc -l < "$f")
echo " $(basename $f): $count alerts"
fi
done
12.5 工具对比表
| 工具 | 平台 | 类别 | 开源/商业 | 推荐场景 |
|---|---|---|---|---|
| Autoruns | Windows | 持久化 | 免费 | 自启动项排查 |
| KAPE | Windows | 取证 | 免费 | 快速证据收集 |
| Volatility | 跨平台 | 内存取证 | 开源 | 内存分析 |
| Redline | Windows | 取证 | 免费 | 主机取证 |
| Wireshark | 跨平台 | 流量分析 | 开源 | 网络流量分析 |
| tcpdump | Linux | 流量抓取 | 开源 | 命令行抓包 |
| Zeek | 跨平台 | 流量分析 | 开源 | 大规模流量监控 |
| Suricata | 跨平台 | IDS/IPS | 开源 | 入侵检测 |
| YARA | 跨平台 | 恶意代码 | 开源 | 恶意文件识别 |
| Plaso | 跨平台 | 时间线 | 开源 | 日志时间线 |
| SIFT | Linux | 取证套件 | 免费 | 综合取证 |
| REMnux | Linux | 恶意代码 | 免费 | 恶意软件分析 |
| Splunk | 跨平台 | SIEM | 商业 | 企业级日志分析 |
| ELK Stack | 跨平台 | 日志平台 | 开源 | 日志收集分析 |
| The Sleuth Kit | 跨平台 | 磁盘取证 | 开源 | 磁盘镜像分析 |
十三、自动化应急响应
13.1 SOAR概念与实践
SOAR(Security Orchestration, Automation and Response,安全编排自动化与响应)是将安全工具集成、流程自动化和事件响应编排为一体的平台。SOAR的核心能力包括:
| 能力 | 说明 |
|---|---|
| 编排 | 集成多种安全工具(SIEM、EDR、防火墙等) |
| 自动化 | 自动执行调查和响应流程 |
| 响应 | 预定义响应动作和剧本 |
| 案例 | 统一管理安全事件 |
| 威胁情报 | 集成和管理威胁情报 |
| 报告 | 自动生成事件报告 |
常见的SOAR平台包括:
| 平台 | 厂商 | 特点 |
|---|---|---|
| Splunk SOAR | Splunk | 与Splunk深度集成 |
| Cortex XSOAR | Palo Alto | 开源社区版本可用 |
| IBM Resilient | IBM | 企业级IR编排 |
| SWIMLANE | Swimlane | 可视化流程设计 |
| Shuffle | 开源 | 开源SOAR平台 |
13.2 自动取证脚本
#!/usr/bin/env python3
"""
Automated Evidence Collection Script
Collects forensic evidence from a compromised system
"""
import os
import sys
import subprocess
import platform
import hashlib
import json
from datetime import datetime
from pathlib import Path
class EvidenceCollector:
def __init__(self, output_dir="./evidence"):
self.output_dir = output_dir
self.timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
self.case_dir = os.path.join(output_dir, f"case_{self.timestamp}")
self.manifest = {
"case_id": f"CASE-{self.timestamp}",
"collection_time": datetime.now().isoformat(),
"system": platform.platform(),
"hostname": platform.node(),
"evidence_items": []
}
os.makedirs(self.case_dir, exist_ok=True)
def run_command(self, command, output_file, description=""):
"""Execute a command and save output"""
print(f"[*] Collecting: {description}...")
try:
result = subprocess.run(
command, shell=True, capture_output=True, text=True, timeout=300
)
output_path = os.path.join(self.case_dir, output_file)
with open(output_path, 'w', encoding='utf-8', errors='replace') as f:
f.write(result.stdout)
if result.stderr:
f.write(f"\n--- STDERR ---\n{result.stderr}")
file_hash = self._hash_file(output_path)
self.manifest["evidence_items"].append({
"description": description,
"command": command,
"output_file": output_file,
"hash_sha256": file_hash,
"size_bytes": os.path.getsize(output_path)
})
print(f" [+] Saved to {output_file} (sha256: {file_hash[:16]}...)")
except subprocess.TimeoutExpired:
print(f" [!] Timeout for: {command}")
except Exception as e:
print(f" [!] Error: {e}")
def _hash_file(self, filepath):
h = hashlib.sha256()
with open(filepath, 'rb') as f:
while True:
chunk = f.read(8192)
if not chunk:
break
h.update(chunk)
return h.hexdigest()
def collect_windows(self):
"""Collect Windows evidence"""
print("=" * 60)
print("Windows Evidence Collection")
print("=" * 60)
# System info
self.run_command("systeminfo", "01_systeminfo.txt", "System Information")
# Account analysis
self.run_command("net user", "02_net_user.txt", "User Accounts")
self.run_command("net localgroup administrators", "02_local_admins.txt", "Local Administrators")
self.run_command('wmic useraccount get Name,SID,Disabled,AccountType', "02_useraccount.txt", "User Account Details")
# Process analysis
self.run_command("tasklist /v /fo csv", "03_tasklist.csv", "Process List")
self.run_command("wmic process get ProcessId,Name,ExecutablePath,CommandLine /format:csv", "03_process_details.csv", "Process Details")
# Network analysis
self.run_command("netstat -ano", "04_netstat.txt", "Network Connections")
self.run_command("netstat -anob", "04_netstat_with_pid.txt", "Network Connections with PID")
self.run_command("arp -a", "04_arp.txt", "ARP Table")
self.run_command("ipconfig /all", "04_ipconfig.txt", "IP Configuration")
# Service analysis
self.run_command("sc query type= service state= all", "05_services.txt", "Services")
self.run_command('wmic service get Name,DisplayName,State,StartMode,PathName /format:csv', "05_service_details.csv", "Service Details")
# Scheduled tasks
self.run_command("schtasks /query /fo LIST /v", "06_schtasks.txt", "Scheduled Tasks")
# Registry persistence
self.run_command('reg query "HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"', "06_run_hklm.txt", "HKLM Run Key")
self.run_command('reg query "HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"', "06_run_hkcu.txt", "HKCU Run Key")
# Recent files
self.run_command('powershell "Get-ChildItem C:\\ -Recurse -File -ErrorAction SilentlyContinue | Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays(-7)} | Select-Object FullName,LastWriteTime,Length | Format-Table -AutoSize"', "07_recent_files.txt", "Recent Files")
# Event logs
self.run_command("wevtutil epl Security security.evtx", "08_security.evtx", "Security Event Log")
self.run_command("wevtutil epl System system.evtx", "08_system.evtx", "System Event Log")
# PowerShell history
self.run_command('powershell "Get-Content (Get-PSReadLineOption).HistorySavePath -ErrorAction SilentlyContinue"', "09_powershell_history.txt", "PowerShell History")
self.save_manifest()
def collect_linux(self):
"""Collect Linux evidence"""
print("=" * 60)
print("Linux Evidence Collection")
print("=" * 60)
# System info
self.run_command("uname -a", "01_uname.txt", "System Info")
self.run_command("uptime", "01_uptime.txt", "Uptime")
self.run_command("date", "01_date.txt", "Current Date")
# Account analysis
self.run_command("cat /etc/passwd", "02_passwd.txt", "User Accounts")
self.run_command("cat /etc/shadow 2>/dev/null", "02_shadow.txt", "Shadow File")
self.run_command("cat /etc/group", "02_group.txt", "Groups")
self.run_command("awk -F: '$3==0 {print $1}' /etc/passwd", "02_uid0.txt", "UID=0 Accounts")
self.run_command("last -50", "02_last.txt", "Login History")
# Process analysis
self.run_command("ps -auxwf", "03_ps.txt", "Process List")
self.run_command("ps -ef --forest", "03_ps_tree.txt", "Process Tree")
self.run_command("lsof -i -nP 2>/dev/null", "03_lsof_network.txt", "Network File Handles")
# Network analysis
self.run_command("ss -tunlp", "04_ss.txt", "Network Connections")
self.run_command("netstat -antp 2>/dev/null", "04_netstat.txt", "Network Connections (netstat)")
self.run_command("ip addr", "04_ip_addr.txt", "IP Addresses")
self.run_command("ip route", "04_routes.txt", "Routing Table")
# File analysis
self.run_command("find / -mtime -1 -type f 2>/dev/null | head -500", "05_recent_files.txt", "Recent Files (24h)")
self.run_command("find / -perm -4000 -type f -exec ls -la {} \\; 2>/dev/null", "05_suid_files.txt", "SUID Files")
self.run_command("find /tmp /var/tmp /dev/shm -type f 2>/dev/null", "05_temp_files.txt", "Temp Directory Files")
# Package integrity
self.run_command("rpm -Va 2>/dev/null || dpkg -V 2>/dev/null", "06_package_verify.txt", "Package Integrity")
# Crontab
for user_cmd in ["crontab -l -u root 2>/dev/null", "cat /etc/crontab 2>/dev/null", "ls -la /etc/cron.d/ 2>/dev/null", "ls -la /etc/cron.hourly/ 2>/dev/null", "ls -la /etc/cron.daily/ 2>/dev/null"]:
self.run_command(user_cmd, "07_crontab.txt", f"Crontab: {user_cmd}")
# Systemd
self.run_command("systemctl list-unit-files --state=enabled --type=service", "08_systemd_enabled.txt", "Enabled Services")
self.run_command("systemctl list-timers --all", "08_systemd_timers.txt", "Systemd Timers")
# SSH
self.run_command('find / -name "authorized_keys" -exec sh -c \'echo "=== {} ==="; cat {}\' \\; 2>/dev/null', "09_ssh_keys.txt", "SSH Authorized Keys")
self.run_command("grep 'Accepted\\|Failed' /var/log/secure /var/log/auth.log 2>/dev/null | tail -100", "09_ssh_logins.txt", "SSH Login Log")
# Kernel modules
self.run_command("lsmod", "10_lsmod.txt", "Kernel Modules")
self.run_command("cat /proc/modules", "10_proc_modules.txt", "Proc Modules")
# Rootkit scan
self.run_command("rkhunter --check --sk --report-warnings-only 2>/dev/null || echo 'rkhunter not installed'", "11_rkhunter.txt", "Rootkit Scan")
self.run_command("chkrootkit 2>/dev/null || echo 'chkrootkit not installed'", "11_chkrootkit.txt", "Chkrootkit Scan")
self.save_manifest()
def save_manifest(self):
"""Save the evidence manifest"""
manifest_path = os.path.join(self.case_dir, "manifest.json")
with open(manifest_path, 'w') as f:
json.dump(self.manifest, f, indent=2)
print(f"\n[*] Manifest saved to {manifest_path}")
print(f"[*] Evidence collected in {self.case_dir}/")
print(f"[*] Total items: {len(self.manifest['evidence_items'])}")
if __name__ == "__main__":
collector = EvidenceCollector()
if platform.system() == "Windows":
collector.collect_windows()
elif platform.system() == "Linux":
collector.collect_linux()
else:
print(f"Unsupported platform: {platform.system()}")
sys.exit(1)
13.3 IOC自动化匹配
#!/usr/bin/env python3
"""
IOC Automation Matching Engine
Matches system artifacts against known IOCs
"""
import os
import re
import hashlib
import json
import socket
from datetime import datetime
class IOCMatcher:
def __init__(self, ioc_file="iocs.json"):
self.iocs = self._load_iocs(ioc_file)
self.matches = []
def _load_iocs(self, ioc_file):
"""Load IOCs from JSON file"""
default_iocs = {
"ips": [],
"domains": [],
"hashes": [],
"urls": [],
"filenames": [],
"registry_keys": [],
"mutexes": []
}
if os.path.exists(ioc_file):
with open(ioc_file, 'r') as f:
return json.load(f)
return default_iocs
def check_ip(self, ip):
"""Check if IP is in IOC list"""
if ip in self.iocs.get("ips", []):
self.matches.append({
"type": "ip",
"value": ip,
"severity": "high"
})
return True
return False
def check_domain(self, domain):
"""Check if domain is in IOC list"""
if domain in self.iocs.get("domains", []):
self.matches.append({
"type": "domain",
"value": domain,
"severity": "high"
})
return True
return False
def check_hash(self, filepath):
"""Check file hash against IOC list"""
sha256 = self._hash_file(filepath)
if sha256 in self.iocs.get("hashes", []):
self.matches.append({
"type": "hash",
"value": sha256,
"filepath": filepath,
"severity": "critical"
})
return True
return False
def _hash_file(self, filepath):
h = hashlib.sha256()
try:
with open(filepath, 'rb') as f:
while True:
chunk = f.read(8192)
if not chunk:
break
h.update(chunk)
return h.hexdigest()
except:
return ""
def check_filename(self, filename):
"""Check filename against IOC list"""
if filename in self.iocs.get("filenames", []):
self.matches.append({
"type": "filename",
"value": filename,
"severity": "medium"
})
return True
return False
def check_network_connections(self):
"""Check active network connections"""
print("[*] Checking network connections...")
# This would use psutil or netstat output
# Simplified example
import subprocess
result = subprocess.run(["netstat", "-an"], capture_output=True, text=True)
ip_pattern = r'(\d+\.\d+\.\d+\.\d+)'
ips = set(re.findall(ip_pattern, result.stdout))
for ip in ips:
if ip != "0.0.0.0" and ip != "127.0.0.1":
self.check_ip(ip)
def check_files(self, directory="/"):
"""Scan files in directory for IOC matches"""
print(f"[*] Scanning files in {directory}...")
for root, dirs, files in os.walk(directory):
for filename in files:
filepath = os.path.join(root, filename)
# Check filename
self.check_filename(filename)
# Check hash for executables
if filename.endswith(('.exe', '.dll', '.so', '.bin')):
self.check_hash(filepath)
def scan_dns_cache(self):
"""Check DNS cache for malicious domains"""
print("[*] Checking DNS cache...")
import subprocess
try:
result = subprocess.run(
["powershell", "-Command", "Get-DnsClientCache | Select-Object -ExpandProperty Entry"],
capture_output=True, text=True
)
for domain in result.stdout.strip().split('\n'):
domain = domain.strip()
if domain:
self.check_domain(domain)
except:
pass
def generate_report(self):
"""Generate IOC match report"""
report = {
"scan_time": datetime.now().isoformat(),
"total_iocs": sum(len(v) for v in self.iocs.values()),
"matches_found": len(self.matches),
"matches": self.matches
}
print(f"\n[*] IOC Scan Report")
print(f" Total IOCs: {report['total_iocs']}")
print(f" Matches found: {report['matches_found']}")
for match in self.matches:
severity = match.get('severity', 'unknown')
print(f" [{severity.upper()}] {match['type']}: {match['value']}")
return report
if __name__ == "__main__":
matcher = IOCMatcher("iocs.json")
matcher.check_network_connections()
matcher.scan_dns_cache()
report = matcher.generate_report()
with open("ioc_report.json", 'w') as f:
json.dump(report, f, indent=2)
print(f"\n[*] Report saved to ioc_report.json")
13.4 自动化威胁狩猎
Sigma规则(通用检测规则格式):
Sigma是一种通用的日志检测规则格式,可以转换为不同SIEM平台的查询语法。
# Sigma Rule: Detect Suspicious PowerShell Execution
title: Suspicious PowerShell Execution with Encoded Command
id: 4d5120e6-3e9e-4f3e-9c3f-9e2c3e2c9e2c
status: experimental
description: Detects PowerShell execution with Base64 encoded commands
author: IR Team
date: 2026/08/19
tags:
- attack.execution
- attack.t1059.001
logsource:
product: windows
service: powershell
detection:
selection:
EventID: 4104
ScriptBlockText|contains:
- "FromBase64String"
- "-EncodedCommand"
- "-enc "
condition: selection
falsepositives:
- Legitimate administrative scripts
level: high
---
# Sigma Rule: Detect Mimikatz
title: Mimikatz Use Detected
id: 5e5120e6-3e9e-4f3e-9c3f-9e2c3e2c9e2d
status: experimental
description: Detects potential Mimikatz credential dumping
author: IR Team
date: 2026/08/19
tags:
- attack.credential_access
- attack.t1003
logsource:
product: windows
service: security
detection:
selection_process:
EventID: 4688
NewProcessName|contains:
- "mimikatz"
- "sekurlsa"
- "lsadump"
selection_access:
EventID: 4663
ObjectType: "Process"
ObjectName|contains: "lsass.exe"
condition: selection_process or selection_access
level: critical
---
# Sigma Rule: Detect Webshell Access
title: Webshell Access Pattern
id: 6e5120e6-3e9e-4f3e-9c3f-9e2c3e2c9e2e
status: experimental
description: Detects webshell access patterns in web server logs
author: IR Team
date: 2026/08/19
tags:
- attack.persistence
- attack.t1505.003
logsource:
product: linux
service: webserver
detection:
selection:
cs-method: POST
cs-uri-query|contains:
- "eval("
- "system("
- "exec("
- "base64_decode("
- "shell_exec("
filter_legitimate:
cs-uri-query|contains:
- "login"
- "contact"
- "search"
condition: selection and not filter_legitimate
falsepositives:
- Legitimate web applications with eval-like functions
level: high
使用sigmac工具将Sigma规则转换为SIEM查询:
# 安装sigmac
pip3 install sigma
# 转换为Splunk查询
sigmac -t splunk -c config/splunk.yml rules/powersshell_encoded.yml
# 转换为Elasticsearch查询
sigmac -t es-qs rules/mimikatz.yml
# 转换为Kibana查询DSL
sigmac -t kibana rules/webshell_access.yml
# 转换为SQL查询(用于日志数据库)
sigmac -t sql rules/mimikatz.yml
# 批量转换所有规则
sigmac -t splunk -c config/splunk.yml -r rules/ -o splunk_queries.conf
威胁狩猎查询示例(Splunk SPL):
# 查找异常进程创建(无签名验证)
index=windows sourcetype=WinEventLog:Security EventID=4688
| lookup signed_processes.exe_name AS NewProcessName OUTPUT signature_status
| where signature_status != "Valid" AND signature_status != "OS"
# 查找横向移动(同一账号在多台主机登录)
index=windows sourcetype=WinEventLog:Security EventID=4624 LogonType=10 OR LogonType=3
| stats dc(Computer) as host_count by user
| where host_count > 3
| sort -host_count
# 查找异常服务创建
index=windows sourcetype=WinEventLog:System EventID=7045
| search NOT (ServiceName IN ("*", "W3SVC", " MSSQLSERVER", "SQLServer"))
| table _time, Computer, ServiceName, ServiceType, BinaryPath
# 查找PowerShell异常执行
index=windows sourcetype=WinEventLog:PowerShell* (ScriptBlockText=*FromBase64String* OR ScriptBlockText=*DownloadString* OR ScriptBlockText=*Invoke-Expression* OR ScriptBlockText=*iex*)
| stats count by Computer, user
| sort -count
# 查找DNS隧道特征
index=dns | stats count, max(length(query)) as max_len by src_ip
| where max_len > 50 OR count > 1000
| sort -max_len
# 查找数据外泄特征
index=firewall action=allow direction=outbound
| stats sum(bytes_out) as total_bytes by dest_ip
| where total_bytes > 100000000
| sort -total_bytes
13.5 EDR联动
现代应急响应越来越依赖EDR(Endpoint Detection and Response)平台。EDR提供持续的主机监控、行为分析和自动响应能力。
| EDR功能 | 应急响应价值 |
|---|---|
| 进程监控 | 实时记录进程创建和命令行 |
| 文件监控 | 跟踪文件创建、修改和删除 |
| 网络监控 | 记录所有网络连接 |
| 注册表监控 | 监控关键注册表修改 |
| 行为分析 | 基于行为的威胁检测 |
| 远程响应 | 远程隔离、终止进程 |
| 威胁狩猎 | 主动搜索已知和未知威胁 |
| 威胁情报集成 | 自动匹配IOC |
13.6 SIEM告警调查流程
当SIEM产生告警时,标准调查流程如下:
告警产生
|
v
初步分诊 --> 严重度评估 --> 分配优先级
|
v
上下文收集 --> 关联事件 --> 扩展搜索
|
v
初步判断 --> 误报? --是--> 关闭告警,记录原因
|
否
|
v
深度分析 --> 取证收集 --> 溯源分析
|
v
制定响应 --> 遏制策略 --> 执行隔离
|
v
根除威胁 --> 恢复系统 --> 验证确认
|
v
编写报告 --> 改进检测规则 --> 完善剧本
13.7 完整自动化响应脚本
#!/usr/bin/env python3
"""
Automated Incident Response Playbook
Executes automated response actions based on alert type
"""
import json
import subprocess
import platform
from datetime import datetime
class IncidentResponder:
def __init__(self):
self.system = platform.system()
self.actions_log = []
def log_action(self, action, result, details=""):
entry = {
"timestamp": datetime.now().isoformat(),
"action": action,
"result": result,
"details": details
}
self.actions_log.append(entry)
print(f"[{entry['timestamp']}] {action}: {result}")
def isolate_network(self):
"""Isolate the host from network"""
print("\n[!] ISOLATING HOST FROM NETWORK")
if self.system == "Windows":
# Block all inbound and outbound
subprocess.run(['netsh', 'advfirewall', 'set', 'allprofiles', 'firewall', 'policy', 'blockinbound,blockoutbound'])
self.log_action("Network Isolation", "Success", "Blocked all firewall traffic")
elif self.system == "Linux":
# Block outbound except SSH management
subprocess.run(['iptables', '-A', 'OUTPUT', '-d', '127.0.0.1', '-j', 'ACCEPT'])
subprocess.run(['iptables', '-A', 'OUTPUT', '-p', 'tcp', '--sport', '22', '-j', 'ACCEPT'])
subprocess.run(['iptables', '-A', 'OUTPUT', '-j', 'DROP'])
self.log_action("Network Isolation", "Success", "iptables rules applied")
def kill_process(self, pid=None, name=None):
"""Terminate malicious process"""
print(f"\n[!] TERMINATING MALICIOUS PROCESS")
if self.system == "Windows":
if pid:
subprocess.run(['taskkill', '/F', '/PID', str(pid)])
elif name:
subprocess.run(['taskkill', '/F', '/IM', name])
self.log_action("Process Kill", "Success", f"Killed PID={pid} Name={name}")
elif self.system == "Linux":
if pid:
subprocess.run(['kill', '-9', str(pid)])
elif name:
subprocess.run(['pkill', '-9', '-f', name])
self.log_action("Process Kill", "Success", f"Killed PID={pid} Name={name}")
def disable_account(self, username):
"""Disable a compromised account"""
print(f"\n[!] DISABLING ACCOUNT: {username}")
if self.system == "Windows":
subprocess.run(['net', 'user', username, '/active:no'])
self.log_action("Account Disable", "Success", f"Disabled {username}")
elif self.system == "Linux":
subprocess.run(['usermod', '-L', username])
self.log_action("Account Disable", "Success", f"Locked {username}")
def block_ip(self, ip):
"""Block a malicious IP"""
print(f"\n[!] BLOCKING IP: {ip}")
if self.system == "Windows":
subprocess.run(['netsh', 'advfirewall', 'firewall', 'add', 'rule',
f'name=Block_{ip}', 'dir=in', 'action=block',
f'remoteip={ip}'])
self.log_action("IP Block", "Success", f"Blocked {ip}")
elif self.system == "Linux":
subprocess.run(['iptables', '-I', 'INPUT', '-s', ip, '-j', 'DROP'])
self.log_action("IP Block", "Success", f"Blocked {ip}")
def collect_evidence(self):
"""Quick evidence collection"""
print("\n[*] COLLECTING EVIDENCE")
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
evidence_dir = f"./evidence_{timestamp}"
os.makedirs(evidence_dir, exist_ok=True)
if self.system == "Windows":
subprocess.run(['tasklist', '/v', '/fo', 'csv'],
stdout=open(f"{evidence_dir}/processes.csv", 'w'))
subprocess.run(['netstat', '-ano'],
stdout=open(f"{evidence_dir}/netstat.txt", 'w'))
elif self.system == "Linux":
subprocess.run(['ps', '-auxwf'],
stdout=open(f"{evidence_dir}/ps.txt", 'w'))
subprocess.run(['ss', '-tunlp'],
stdout=open(f"{evidence_dir}/ss.txt", 'w'))
self.log_action("Evidence Collection", "Success", f"Saved to {evidence_dir}")
return evidence_dir
def handle_phishing_alert(self, alert_data):
"""Playbook for phishing alert"""
print("\n" + "=" * 60)
print("PLAYBOOK: Phishing Alert Response")
print("=" * 60)
# Step 1: Collect evidence
self.collect_evidence()
# Step 2: Block malicious IP/domain
if 'malicious_ip' in alert_data:
self.block_ip(alert_data['malicious_ip'])
# Step 3: Kill malicious process if running
if 'malicious_pid' in alert_data:
self.kill_process(pid=alert_data['malicious_pid'])
# Step 4: Disable compromised account
if 'compromised_user' in alert_data:
self.disable_account(alert_data['compromised_user'])
# Step 5: Isolate if necessary
if alert_data.get('severity') == 'critical':
self.isolate_network()
self.generate_report(alert_data)
def handle_webshell_alert(self, alert_data):
"""Playbook for webshell alert"""
print("\n" + "=" * 60)
print("PLAYBOOK: Webshell Alert Response")
print("=" * 60)
# Step 1: Collect evidence
self.collect_evidence()
# Step 2: Identify webshell process
if 'process_pid' in alert_data:
self.kill_process(pid=alert_data['process_pid'])
# Step 3: Delete webshell file
if 'webshell_path' in alert_data:
try:
os.remove(alert_data['webshell_path'])
self.log_action("File Deletion", "Success", f"Deleted {alert_data['webshell_path']}")
except Exception as e:
self.log_action("File Deletion", "Failed", str(e))
# Step 4: Block attacker IP
if 'attacker_ip' in alert_data:
self.block_ip(alert_data['attacker_ip'])
# Step 5: Isolate host
if alert_data.get('severity') == 'critical':
self.isolate_network()
self.generate_report(alert_data)
def handle_lateral_movement(self, alert_data):
"""Playbook for lateral movement alert"""
print("\n" + "=" * 60)
print("PLAYBOOK: Lateral Movement Response")
print("=" * 60)
# Step 1: Collect evidence
self.collect_evidence()
# Step 2: Block lateral movement IP
if 'source_ip' in alert_data:
self.block_ip(alert_data['source_ip'])
# Step 3: Disable compromised account
if 'compromised_user' in alert_data:
self.disable_account(alert_data['compromised_user'])
# Step 4: Kill malicious process
if 'process_pid' in alert_data:
self.kill_process(pid=alert_data['process_pid'])
# Step 5: Isolate affected host
self.isolate_network()
self.generate_report(alert_data)
def generate_report(self, alert_data):
"""Generate incident response report"""
report = {
"incident_time": datetime.now().isoformat(),
"alert_type": alert_data.get('alert_type', 'unknown'),
"severity": alert_data.get('severity', 'unknown'),
"actions_taken": self.actions_log,
"status": "contained",
"recommendations": [
"Conduct full forensic analysis",
"Review all related systems for compromise",
"Update detection rules",
"Review and update security policies"
]
}
report_file = f"ir_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
with open(report_file, 'w') as f:
json.dump(report, f, indent=2)
print(f"\n[*] Report saved to {report_file}")
print(f"[*] Total actions taken: {len(self.actions_log)}")
print(f"[*] Status: CONTAINED")
print(f"[*] Recommendations:")
for rec in report['recommendations']:
print(f" - {rec}")
if __name__ == "__main__":
responder = IncidentResponder()
# Example: Handle phishing alert
alert = {
"alert_type": "phishing",
"severity": "critical",
"malicious_ip": "203.0.113.50",
"malicious_pid": 1234,
"compromised_user": "jdoe"
}
responder.handle_phishing_alert(alert)
十四、总结与参考资源
14.1 应急响应检查清单
| 阶段 | 检查项 | 状态 |
|---|---|---|
| 准备 | 应急响应预案已制定 | 待确认 |
| 准备 | IR团队角色已分配 | 待确认 |
| 准备 | 工具箱已准备和测试 | 待确认 |
| 准备 | 联系人清单已更新 | 待确认 |
| 检测 | 日志监控已部署 | 待确认 |
| 检测 | SIEM告警规则已配置 | 待确认 |
| 检测 | EDR已部署 | 待确认 |
| 遏制 | 网络隔离方案已就绪 | 待确认 |
| 遏制 | 账号禁用流程已明确 | 待确认 |
| 根除 | 后门清除流程已明确 | 待确认 |
| 根除 | 恶意文件清除方法已明确 | 待确认 |
| 恢复 | 系统重建方案已制定 | 待确认 |
| 恢复 | 备份恢复流程已明确 | 待确认 |
| 恢复 | 验证清单已制定 | 待确认 |
| 总结 | 报告模板已准备 | 待确认 |
| 总结 | 复盘会议流程已明确 | 待确认 |
14.2 日志分析速查表
| 场景 | Windows命令 | Linux命令 |
|---|---|---|
| 查看登录成功 | Get-WinEvent -FilterHashtable @{LogName=‘Security’;Id=4624} | grep Accepted /var/log/secure |
| 查看登录失败 | Get-WinEvent -FilterHashtable @{LogName=‘Security’;Id=4625} | grep “Failed password” /var/log/secure |
| 查看进程创建 | Get-WinEvent -FilterHashtable @{LogName=‘Security’;Id=4688} | ps -auxwf |
| 查看服务创建 | Get-WinEvent -FilterHashtable @{LogName=‘System’;Id=7045} | systemctl list-units |
| 查看计划任务 | schtasks /query /fo LIST /v | crontab -l / ls /etc/cron.* |
| 查看网络连接 | netstat -ano | ss -tunlp |
| 查看文件修改 | Get-ChildItem -Filter * -Recurse | find / -mtime -1 |
| 查看日志清除 | Get-WinEvent -FilterHashtable @{LogName=‘Security’;Id=1102} | 检查日志文件大小 |
| 查看账号变更 | Get-WinEvent -FilterHashtable @{LogName=‘Security’;Id=4720} | cat /etc/passwd / last |
| 查看特权使用 | Get-WinEvent -FilterHashtable @{LogName=‘Security’;Id=4672} | grep sudo /var/log/secure |
14.3 工具速查表
| 任务 | Windows工具 | Linux工具 | 跨平台工具 |
|---|---|---|---|
| 进程分析 | Process Explorer | ps/top/strace | Volatility |
| 网络分析 | TCPView | ss/netstat/lsof | Wireshark/tcpdump |
| 文件分析 | find/Autoruns | find/md5sum/rpm -V | YARA |
| 日志分析 | LogParser/Get-WinEvent | grep/awk/journalctl | Splunk/ELK |
| 内存取证 | winpmem/DumpIt | LiME | Volatility |
| 持久化排查 | Autoruns | crontab/systemctl | - |
| Rootkit检测 | - | rkhunter/chkrootkit | Volatility malfind |
| 恶意代码分析 | PEview/pestudio | strings/file | YARA/VirusTotal |
| 流量分析 | Wireshark | tcpdump/Zeek | Wireshark/Suricata |
| 时间线分析 | KAPE/Redline | log2timeline | Plaso/Log2Timeline |
| 自动化 | PowerShell | bash/python | Python/SOAR |
14.4 参考资源列表
| 资源名称 | 说明 | 链接 |
|---|---|---|
| NIST SP 800-61 | 计算机安全事件处理指南 | csrc.nist.gov |
| MITRE ATT&CK | 攻击者战术和技术知识库 | attack.mitre.org |
| SANS PICERL | 应急响应方法论 | sans.org |
| Volatility Framework | 内存取证框架 | volatilityfoundation.org |
| Sysinternals Suite | Windows系统工具集 | docs.microsoft.com/sysinternals |
| KAPE | 快速取证工具 | github.com/EricZimmerman/Kape |
| Plaso/log2timeline | 时间线分析工具 | github.com/log2timeline |
| YARA | 恶意代码识别规则 | github.com/VirusTotal/yara |
| Sigma Project | 通用检测规则 | github.com/SigmaHQ/sigma |
| VirusTotal | 恶意文件多引擎扫描 | virustotal.com |
| AbuseIPDB | 恶意IP数据库 | abuseipdb.com |
| AlienVault OTX | 开源威胁情报 | otx.alienvault.com |
| TheHive | 开源事件响应平台 | thehive-project.org |
| Cortex | 自动化分析引擎 | thehive-project.org |
| MISP | 开源威胁情报平台 | misp-project.org |
| CyberChef | 数据编码转换工具 | gchq.github.io/CyberChef |
14.5 合规声明
【提示】 本文所有技术内容仅用于授权测试、安全学习和合规的安全运维场景。请在合法授权范围内使用本文所述技术。未经授权对他人系统进行渗透测试或应急响应操作可能违反以下法律法规:
- 《中华人民共和国网络安全法》
- 《中华人民共和国数据安全法》
- 《中华人民共和国个人信息保护法》
- 《中华人民共和国刑法》相关条款(第285条非法侵入计算机信息系统罪、第286条破坏计算机信息系统罪)
在进行任何安全测试和应急响应操作前,请确保:
- 已获得系统所有者的明确书面授权
- 操作范围在授权协议约定范围内
- 不影响业务系统的正常运行
- 妥善保护获取的敏感数据和证据
- 遵守相关法律法规和行业规范
本文作者不对任何因不当使用本文所述技术而造成的后果承担责任。
更多推荐




所有评论(0)