Windows应急响应 - 35 恶意软件基础分析

Windows应急响应/35-恶意软件基础分析

本篇覆盖Windows平台恶意软件分析的基础方法与工具链

流程:hash查询 → VirusTotal → 静态分析 → 沙箱动态分析 → 报告

关联:14-钓鱼邮件与恶意文件执行30-YARA规则

一、PE文件格式基础

1.1 PE结构概览

PE (Portable Executable) 是Windows可执行文件的标准格式(.exe, .dll, .sys, .ocx)

结构层次:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
┌─────────────────────┐
DOS Header │ ← MZ 签名 (0x4D5A)
DOS Stub │ ← "This program cannot be run in DOS mode"
├─────────────────────┤
PE Signature │ ← "PE\0\0" (0x50450000)
├─────────────────────┤
COFF File Header │ ← Machine, NumberOfSections, TimeDateStamp
├─────────────────────┤
Optional Header │ ← AddressOfEntryPoint, ImageBase, Subsystem
Data Directories│ ← Import/Export/Resource/Debug/TLS 目录
├─────────────────────┤
Section Headers │ ← .text, .rdata, .data, .rsrc, .reloc
├─────────────────────┤
Section Bodies │ ← 实际代码和数据
└─────────────────────┘

1.2 关键字段(安全分析视角)

TimeDateStamp:编译时间,可伪造但仍有参考价值

AddressOfEntryPoint:程序入口点,异常入口点(如指向非.text节)是加壳特征

Subsystem:GUI (2) / CUI (3) / Driver (1)

Import Table:导入函数列表 → 分析程序功能的核心依据

Export Table:导出函数列表 → DLL功能分析

**Resource Section (.rsrc)**:可能嵌入额外PE、脚本、配置

TLS Callbacks:在EntryPoint之前执行 → 常用于反调试

1.3 常见可疑导入函数

类别 函数名 用途
进程注入 VirtualAllocEx, WriteProcessMemory, CreateRemoteThread 远程线程注入
进程注入 NtMapViewOfSection, NtUnmapViewOfSection Section映射注入
代码执行 WinExec, ShellExecute, CreateProcess 启动新进程
网络通信 InternetOpenUrl, HttpSendRequest, URLDownloadToFile HTTP通信
网络通信 WSAStartup, connect, send, recv Socket通信
文件操作 CreateFile, WriteFile, DeleteFile 文件释放/删除
注册表 RegSetValueEx, RegCreateKeyEx 持久化
权限提升 AdjustTokenPrivileges, OpenProcessToken 提权
信息收集 GetComputerName, GetUserName, GetSystemInfo 环境探测
加密相关 CryptEncrypt, CryptDecrypt, BCryptEncrypt 加密/勒索
反调试 IsDebuggerPresent, CheckRemoteDebuggerPresent 反分析

二、静态分析工具

2.1 PEStudio

首选静态分析工具,免费版功能足够

下载:https://www.winitor.com/

关键分析视图:

indicators:自动标记可疑特征(红/黄/绿)

imports:导入函数列表,可疑函数会高亮

strings:字符串提取,可疑字符串标记

sections:节区信息,异常熵值表示加密/压缩

resources:嵌入资源,可能包含payload

virustotal:集成VT查询结果

分析要点:

1
2
3
4
5
6
7
8
检查清单:
1. 编译时间(TimeDateStamp)是否合理
2. 熵值(Entropy)—— >7.0 高度可疑(加壳/加密)
3. 导入函数 —— 是否包含注入/网络/加密API
4. 字符串 —— IP地址、URL、命令、注册表路径
5. 资源 —— 是否嵌入了额外的PE或脚本
6. 签名 —— 是否有有效的数字签名
7. 节区名 —— 非标准名(.UPX0, .themida)表示加壳

2.2 Detect It Easy (DIE)

用于识别编译器、加壳器、加密器

下载:https://github.com/horsicq/Detect-It-Easy

能检测的壳/保护:

UPX, ASPack, Themida, VMProtect

.NET混淆器:ConfuserEx, .NET Reactor

Delphi, VB6, AutoIt编译

命令行用法:

1
2
3
4
5
6
7
8
9
# 命令行扫描
diec.exe --json C:\samples\malware.exe

# 批量扫描目录
Get-ChildItem C:\samples\*.exe | ForEach-Object {
Write-Host $_.Name -ForegroundColor Cyan
& diec.exe $_.FullName
Write-Host ""
}

2.3 CFF Explorer

PE头部编辑器,可查看和修改PE结构

适用场景:

详细查看 Import/Export Table

检查 TLS Callbacks

查看 .NET Metadata(对.NET PE)

修复损坏的PE头(高级分析)

下载:https://ntcore.com/explorer-suite/

2.4 Resource Hacker

查看和提取PE资源段内容

适用场景:

提取嵌入的图标、字符串、对话框

发现嵌入的PE文件(dropper常见)

查看版本信息

下载:http://www.angusj.com/resourcehacker/

2.5 strings 提取

Sysinternals Strings 或 FLOSS(FireEye Labs Obfuscated String Solver):

1
2
3
4
5
6
7
8
# Sysinternals strings
strings.exe -accepteula -n 8 C:\samples\malware.exe > C:\IR\strings_output.txt

# FLOSS —— 可解混淆字符串
floss.exe C:\samples\malware.exe > C:\IR\floss_output.txt

# 快速grep关键模式
Select-String -Path C:\IR\strings_output.txt -Pattern 'http|https|\.exe|\.dll|cmd\.exe|powershell|reg add|HKLM|HKCU|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'

FLOSS 优势:能解码 stack strings、tight loops、base64 编码的字符串

三、动态分析(沙箱)

3.1 Windows Sandbox

Windows 10/11 Pro+ 自带的一次性沙箱环境

启用方法:

1
2
# 启用 Windows Sandbox(需重启)
Enable-WindowsOptionalFeature -FeatureName "Containers-DisposableClientVM" -Online -NoRestart

特点:

每次启动都是全新环境,关闭后自动清除

可配置 .wsb 文件控制共享文件夹、网络等

配置文件示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- MalwareAnalysis.wsb -->
<Configuration>
<MappedFolders>
<MappedFolder>
<HostFolder>C:\Samples</HostFolder>
<SandboxFolder>C:\Users\WDAGUtilityAccount\Desktop\Samples</SandboxFolder>
<ReadOnly>true</ReadOnly>
</MappedFolder>
</MappedFolders>
<Networking>Disable</Networking>
<LogonCommand>
<Command>explorer.exe C:\Users\WDAGUtilityAccount\Desktop\Samples</Command>
</LogonCommand>
</Configuration>

注意:Sandbox没有持久化能力,关闭即丢失。适合快速验证,不适合长时间监控

3.2 在线沙箱服务

平台 URL 特点
ANY.RUN https://any.run 交互式沙箱,可操作样本,免费版可用
Joe Sandbox https://www.joesandbox.com 深度分析,检测evasion行为
Hybrid Analysis https://hybrid-analysis.com Falcon沙箱,免费,报告详尽
VirusTotal https://www.virustotal.com 多引擎扫描+沙箱行为报告
Triage https://tria.ge Hatching出品,快速分析

ANY.RUN 分析要点:

观察网络连接(C2通信、DNS请求)

观察进程树(子进程创建、注入行为)

观察文件系统变更(释放文件、修改配置)

观察注册表变更(持久化安装)

注意事项:

不要上传包含敏感信息的样本到公开沙箱

免费版报告通常是公开可见的

高级恶意软件可能检测沙箱环境并改变行为

3.3 本地动态分析环境

推荐使用 FLARE VM(FireEye/Mandiant维护的分析虚拟机)

搭建步骤:

1
2
3
4
5
6
7
8
9
10
11
12
# 在全新 Windows 10 VM 中安装 FLARE VM
# 1. 下载安装脚本
(New-Object net.webclient).DownloadFile(
'https://raw.githubusercontent.com/mandiant/flare-vm/main/install.ps1',
"$env:USERPROFILE\Desktop\install.ps1"
)

# 2. 解除执行策略限制
Set-ExecutionPolicy Unrestricted -Force

# 3. 运行安装(耗时较长,约1-2小时)
& "$env:USERPROFILE\Desktop\install.ps1"

包含工具:PEStudio, x64dbg, IDA Free, dnSpy, Process Monitor, Wireshark 等

动态分析监控工具组合:

Process Monitor (ProcMon) → 文件/注册表/网络/进程活动

Process Explorer → 进程树和DLL列表

Wireshark / FakeNet-NG → 网络流量捕获

Regshot → 注册表对比(运行前后快照)

API Monitor → API调用跟踪

四、YARA for Windows

4.1 YARA基础

YARA是恶意软件识别和分类的”模式匹配瑞士军刀”

Windows安装:

1
2
3
4
5
# 使用Chocolatey安装
choco install yara -y

# 或手动下载
# https://github.com/VirusTotal/yara/releases

基本用法:

1
2
3
4
5
6
7
8
# 单文件扫描
yara64.exe rules.yar C:\samples\malware.exe

# 递归扫描目录
yara64.exe -r rules.yar C:\samples\

# 输出匹配的字符串
yara64.exe -s rules.yar C:\samples\malware.exe

4.2 PE模块(pe module)

YARA内置的PE模块提供结构化的PE文件分析能力

常用条件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import "pe"
import "math"

rule Suspicious_PE_Characteristics {
condition:
pe.is_pe and
(
// 非标准节区数量
pe.number_of_sections < 2 or pe.number_of_sections > 10
or
// 异常入口点(不在第一个节区)
pe.entry_point < pe.sections[0].raw_data_offset
or
// 高熵值节区(加壳特征)
for any s in pe.sections : (
math.entropy(s.raw_data_offset, s.raw_data_size) > 7.5
)
)
}

pe.imports 检测可疑导入:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import "pe"

rule Process_Injection_Imports {
meta:
description = "检测常见进程注入API组合"
author = "IR Team"
severity = "high"
condition:
pe.is_pe and
pe.imports("kernel32.dll", "VirtualAllocEx") and
pe.imports("kernel32.dll", "WriteProcessMemory") and
(
pe.imports("kernel32.dll", "CreateRemoteThread") or
pe.imports("ntdll.dll", "NtCreateThreadEx")
)
}

pe.sections 检测加壳:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import "pe"

rule UPX_Packed {
meta:
description = "检测UPX加壳"
condition:
pe.is_pe and
for any s in pe.sections : (
s.name == "UPX0" or s.name == "UPX1"
)
}

rule Suspicious_Section_Names {
meta:
description = "非标准节区名称"
condition:
pe.is_pe and
for any s in pe.sections : (
s.name matches /^\.(themida|vmp|aspack|nsp|perplex)/ or
s.name matches /^[^.]/ // 不以.开头的节区名
)
}

4.3 Windows专用YARA规则

检测常见Windows恶意行为模式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import "pe"

rule Persistence_Registry_Strings {
meta:
description = "包含注册表持久化相关字符串"
mitre = "T1547.001"
strings:
$run1 = "CurrentVersion\\Run" ascii wide nocase
$run2 = "CurrentVersion\\RunOnce" ascii wide nocase
$ifeo = "Image File Execution Options" ascii wide nocase
$winlogon = "Winlogon" ascii wide nocase
$svc = "CurrentControlSet\\Services" ascii wide nocase
condition:
pe.is_pe and 2 of them
}

rule Credential_Theft_Indicators {
meta:
description = "可能的凭证窃取工具"
mitre = "T1003"
strings:
$s1 = "sekurlsa" ascii wide nocase
$s2 = "lsass" ascii wide nocase
$s3 = "mimikatz" ascii wide nocase
$s4 = "wdigest" ascii wide nocase
$s5 = "kerberos" ascii wide nocase
$s6 = "MiniDumpWriteDump" ascii
$s7 = "dbghelp.dll" ascii wide nocase
condition:
pe.is_pe and 3 of them
}

rule Ransomware_Indicators {
meta:
description = "勒索软件常见特征"
mitre = "T1486"
strings:
$enc1 = "CryptEncrypt" ascii
$enc2 = "BCryptEncrypt" ascii
$enc3 = "CryptGenKey" ascii
$note1 = "your files have been encrypted" ascii wide nocase
$note2 = "bitcoin" ascii wide nocase
$note3 = "ransom" ascii wide nocase
$ext1 = ".encrypted" ascii wide
$ext2 = ".locked" ascii wide
$vss = "vssadmin" ascii wide nocase
$shadow = "delete shadows" ascii wide nocase
condition:
pe.is_pe and
(1 of ($enc*)) and
(1 of ($note*) or 1 of ($ext*) or $vss or $shadow)
}

关联:30-YARA规则 —— YARA基础语法和ELF模块

五、.NET恶意软件分析

5.1 识别.NET程序

.NET程序特征:

导入表只有 mscoree.dll_CorExeMain / _CorDllMain

PE Optional Header 中有 CLR Runtime Header

DIE / PEStudio 会标识为 “.NET” 或 “C#”

PowerShell快速判断:

1
2
3
4
5
6
7
8
9
10
11
12
# 检查是否为.NET程序集
function Test-DotNetAssembly {
param([string]$Path)
try {
[System.Reflection.AssemblyName]::GetAssemblyName($Path) | Out-Null
return $true
} catch {
return $false
}
}

Test-DotNetAssembly "C:\samples\suspect.exe"

5.2 dnSpy / ILSpy 反编译

dnSpy(推荐,含调试功能):https://github.com/dnSpy/dnSpy

ILSpy(替代选择):https://github.com/icsharpcode/ILSpy

dnSpy分析流程:

  1. 打开样本 → 左侧树形结构浏览命名空间和类

  2. 找到 Main() 方法或 EntryPoint

  3. 追踪调用链:Main → 初始化 → 核心功能

  4. 关注:网络连接代码、加密/解密函数、文件操作、注册表操作

常见.NET恶意软件家族:

AsyncRAT / QuasarRAT → C# RAT,代码清晰

AgentTesla → .NET信息窃取器

RedLine Stealer → 凭证窃取

njRAT → VB.NET RAT

反混淆工具:

1
2
3
4
5
de4dot —— 通用.NET反混淆
https://github.com/de4dot/de4dot

用法:de4dot.exe malware_obfuscated.exe -o malware_cleaned.exe
支持:ConfuserEx, .NET Reactor, Eazfuscator, SmartAssembly 等

5.3 .NET分析YARA规则

利用PE模块的dotnet特性:

1
2
3
4
5
6
7
8
9
10
11
12
import "pe"
import "dotnet"

rule DotNet_Suspicious_Typo_Namespace {
meta:
description = "可疑的.NET命名空间(模仿合法软件)"
condition:
dotnet.is_dotnet and
for any ns in dotnet.assembly.name : (
ns matches /(Micr0soft|Wiind0ws|Syst3m|Gooogle)/i
)
}

六、PowerShell 去混淆(Deobfuscation)

6.1 常见混淆手法

混淆类型 示例
Base64编码 powershell -enc SQBFAFgA...
字符串拼接 "Inv"+"oke"+"-Exp"+"ression"
字符替换 -replace '###','e'
格式化字符串 "{2}{0}{1}" -f 'ke-','Expression','Invo'
Char数组 [char[]]@(73,69,88) -join ''
压缩+Base64 IEX(New-Object IO.StreamReader((New-Object IO.Compression.GzipStream(...))))
变量替代 ${e}="IEX"; &${e} ...

6.2 PSDecode

自动解码多层混淆的PowerShell脚本

安装与使用:

1
2
3
4
5
6
7
8
# 安装
Install-Module -Name PSDecode -Force

# 解码文件
PSDecode C:\samples\obfuscated.ps1

# 解码字符串
"powershell -enc SQBFAFgA..." | PSDecode

6.3 手动解码技巧

Base64解码

1
2
3
4
# 解码 -EncodedCommand 参数(Unicode Base64)
$encoded = "SQBFAFgAIAAoAE4AZQB3AC0ATwBiAGoA..."
$decoded = [System.Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($encoded))
Write-Host $decoded

分层解码:将IEX替换为Write-Output逐层剥离

1
2
3
4
# 原始:IEX(混淆代码)
# 替换IEX为输出,获取下一层
$code = '混淆的PowerShell代码'
$code -replace 'IEX|Invoke-Expression','Write-Output' | Invoke-Expression

ScriptBlock Logging:启用后自动记录解混淆后的代码

1
2
3
4
5
6
7
# 启用 ScriptBlock Logging(策略方式)
reg add "HKLM\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" /v EnableScriptBlockLogging /t REG_DWORD /d 1 /f

# 然后运行恶意脚本 → Event ID 4104 中记录解码后的明文
# 查看日志:
Get-WinEvent -LogName "Microsoft-Windows-PowerShell/Operational" -FilterXPath "*[System[EventID=4104]]" -MaxEvents 20 |
Select-Object TimeCreated, @{N='ScriptBlock';E={$_.Properties[2].Value}} | Format-List

七、加壳检测与脱壳

7.1 常见壳类型

类型 特征
UPX 压缩壳 节区名UPX0/UPX1,可自动脱壳
ASPack 压缩壳 节区名.aspack
Themida 保护壳 强反调试,虚拟化代码
VMProtect 保护壳 代码虚拟化,节区名.vmp
.NET Reactor .NET保护 混淆+加密
ConfuserEx .NET保护 开源.NET混淆器

7.2 UPX脱壳

UPX是最常见的开源压缩壳,可直接脱壳:

1
2
3
4
5
6
7
8
9
# 安装UPX
choco install upx -y

# 脱壳
upx -d C:\samples\packed.exe -o C:\samples\unpacked.exe

# 验证:比较文件大小和节区
Get-Item C:\samples\packed.exe, C:\samples\unpacked.exe |
Select-Object Name, Length | Format-Table

注意:部分恶意软件修改UPX头导致 upx -d 失败,需手动修复magic bytes

7.3 熵值分析

高熵值(>7.0)表示数据被加密或压缩 → 加壳特征

PowerShell计算文件熵值:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function Get-FileEntropy {
param([string]$Path)
$bytes = [System.IO.File]::ReadAllBytes($Path)
$freq = @{}
foreach ($b in $bytes) { $freq[$b]++ }
$entropy = 0.0
$len = $bytes.Length
foreach ($count in $freq.Values) {
$p = $count / $len
$entropy -= $p * [Math]::Log($p, 2)
}
return [Math]::Round($entropy, 4)
}

$e = Get-FileEntropy "C:\samples\suspect.exe"
Write-Host "Entropy: $e"
if ($e -gt 7.0) { Write-Host "[!] 高熵值 - 可能加壳/加密" -ForegroundColor Red }
elseif ($e -gt 6.0) { Write-Host "[~] 中等熵值 - 需进一步分析" -ForegroundColor Yellow }
else { Write-Host "[OK] 正常熵值" -ForegroundColor Green }

八、Triage分析工作流

8.1 标准流程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
┌─────────────┐
1. 获取样本 │ 收集样本,记录来源(邮件附件/下载/内存提取)
└──────┬──────┘

┌─────────────┐
2. 计算Hash │ MD5 / SHA256 → 保存为证据
└──────┬──────┘

┌─────────────┐
3. VT查询 │ VirusTotal查hash → 已知恶意?家族?
└──────┬──────┘

┌─────────────────┐
4. 静态分析 │ PEStudio → DIE → strings/FLOSS
└──────┬──────────┘

┌─────────────────┐
5. 沙箱分析 │ ANY.RUN / Joe Sandbox → 行为报告
└──────┬──────────┘

┌─────────────────┐
6. 深度分析(可选) │ dnSpy(.NET) / IDA / x64dbg
└──────┬──────────┘

┌─────────────────┐
7. 编写IOC/报告 │ YARA规则 + IOC列表 + 分析报告
└─────────────────┘

8.2 Hash计算与VT查询

PowerShell计算hash:

1
2
3
4
5
6
7
8
9
10
11
12
$file = "C:\samples\suspect.exe"
$md5 = (Get-FileHash $file -Algorithm MD5).Hash
$sha1 = (Get-FileHash $file -Algorithm SHA1).Hash
$sha256 = (Get-FileHash $file -Algorithm SHA256).Hash

Write-Host "MD5 : $md5"
Write-Host "SHA1 : $sha1"
Write-Host "SHA256 : $sha256"

# 复制SHA256到剪贴板(Windows)
$sha256 | Set-Clipboard
Write-Host "[+] SHA256已复制到剪贴板,可直接粘贴到VT搜索" -ForegroundColor Green

VT API查询(需API Key):

1
2
3
4
5
6
7
8
9
$apiKey = "YOUR_VT_API_KEY"
$hash = $sha256

$headers = @{ "x-apikey" = $apiKey }
$response = Invoke-RestMethod -Uri "https://www.virustotal.com/api/v3/files/$hash" -Headers $headers -Method Get

$stats = $response.data.attributes.last_analysis_stats
Write-Host "检测结果: $($stats.malicious)/$($stats.malicious + $stats.undetected) 引擎报毒"
Write-Host "类型标签: $($response.data.attributes.popular_threat_classification.suggested_threat_label)"

8.3 分析报告模板

标准报告应包含:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
=== 恶意软件分析报告 ===

1. 基本信息
- 文件名:
- 文件大小:
- MD5 / SHA256:
- 文件类型:PE32 / PE32+ / .NET / Script
- 编译时间:

2. 检测结果
- VT检出率:XX/XX
- 家族判定:
- DIE识别:编译器/加壳器

3. 静态分析发现
- 可疑导入函数:
- 可疑字符串(C2地址、URL等):
- 资源段嵌入物:

4. 动态行为(沙箱)
- 进程活动:
- 文件操作:
- 注册表修改:
- 网络连接:

5. IOC 指标
- 文件 Hash:
- C2 地址:
- 释放文件路径:
- 注册表修改项:

6. YARA规则
(附)

7. 结论与建议

关联参考:

14-钓鱼邮件与恶意文件执行 — 恶意文件初始入口

30-YARA规则 — YARA语法基础与ELF模块

36-自动化IR工具-KAPE与Velociraptor — 自动化取证采集


上一章 目录 下一章
34-内存取证-Volatility Windows应急响应 36-自动化IR工具-KAPE与Velociraptor