mcpField
P
performing-static-malware-analysis-with-pe-studio

performing-static-malware-analysis-with-pe-studio

github.com/mukul975安全35.2k56 次安装8 周前更新
代码仓库

关于 performing-static-malware-analysis-with-pe-studio

一份使用 PEStudio 等工具对 Windows PE 文件进行静态恶意软件分析的技能指南,面向安全分析人员。它涵盖结构、导入项、字符串、资源与打包特征,可用于运行样本前的初步分流。

主要功能

  1. 01检查 PE 头部与节区
  2. 02按能力分类分析导入项
  3. 03提取普通及混淆字符串
  4. 04检查资源与嵌入数据
  5. 05识别打包和保护特征
  6. 06整理静态分析报告

适用场景

  1. 01分流可疑邮件附件
  2. 02提取文件中的网络指标
  3. 03判断样本是否经过打包
  4. 04为后续沙箱分析准备线索

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill performing-static-malware-analysis-with-pe-studio

安装后在 Claude Code 中输入/performing-static-malware-analysis-with-pe-studio确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

LICENSE
references/
api-reference.md
scripts/
agent.py

详细介绍

使用 PEStudio 执行静态恶意软件分析

何时使用

  • 已收集到可疑的 Windows 可执行文件,需要在沙箱执行前进行初步分类
  • 你需要在未运行样本的情况下,识别能够揭示恶意软件功能的导入、字符串和资源
  • 判断 PE 文件是否被加壳、混淆,或包含反分析技术
  • 提取嵌入在二进制文件中的入侵指标(哈希、URL、IP、注册表项)
  • 根据样本的导入表和节区特征对其能力进行分类

请勿使用于需要执行的动态行为分析;如需观察运行时行为,请使用沙箱(Cuckoo、ANY.RUN)。

前提条件

  • 在隔离的分析工作站上安装 PEStudio(免费版,来自 https://www.winitor.com/)
  • Python 3.8+ 以及 pefile 库,用于脚本化 PE 分析(pip install pefile)
  • CFF Explorer 或 PE-bear 作为补充 PE 分析工具
  • 可访问 VirusTotal API 进行哈希查询和社区情报检索
  • 与生产系统无网络连接的隔离分析 VM
  • FLOSS(FireEye Labs Obfuscated String Solver)用于提取混淆字符串

工作流

步骤 1:计算文件哈希并验证样本完整性

生成用于识别和情报查询的加密哈希:

# Generate MD5, SHA-1, and SHA-256 hashes
md5sum suspect.exe
sha1sum suspect.exe
sha256sum suspect.exe

# Check hash against VirusTotal
curl -s -X GET "https://www.virustotal.com/api/v3/files/$(sha256sum suspect.exe | cut -d' ' -f1)" \
  -H "x-apikey: $VT_API_KEY" | jq '.data.attributes.last_analysis_stats'

# Get file type with magic bytes verification
file suspect.exe
步骤 2:检查头部和节区表

在 PEStudio 中打开样本并检查结构属性:

PEStudio Analysis Points:
━━━━━━━━━━━━━━━━━━━━━━━━━
File Header:       Compilation timestamp, target architecture (x86/x64)
Optional Header:   Entry point address, image base, subsystem (GUI/console)
Section Table:     Section names, virtual/raw sizes, entropy values
                   High entropy (>7.0) in .text/.rsrc suggests packing
Signatures:        Authenticode signature presence and validity

使用 pefile 进行脚本化 PE 头部分析:

import pefile
import hashlib
import math

pe = pefile.PE("suspect.exe")

# Compilation timestamp
import datetime
timestamp = pe.FILE_HEADER.TimeDateStamp
compile_time = datetime.datetime.utcfromtimestamp(timestamp)
print(f"Compile Time: {compile_time} UTC")

# Section analysis with entropy calculation
for section in pe.sections:
    name = section.Name.decode().rstrip('\x00')
    entropy = section.get_entropy()
    raw_size = section.SizeOfRawData
    virtual_size = section.Misc_VirtualSize
    ratio = virtual_size / raw_size if raw_size > 0 else 0
    print(f"Section: {name:8s} Entropy: {entropy:.2f} Raw: {raw_size:>10} Virtual: {virtual_size:>10} Ratio: {ratio:.2f}")
    if entropy > 7.0:
        print(f"  [!] HIGH ENTROPY - likely packed or encrypted")
    if ratio > 10:
        print(f"  [!] HIGH V/R RATIO - unpacking stub likely present")
步骤 3:分析导入地址表(IAT)

识别表明恶意软件能力的可疑 API 导入:

# Extract and categorize imports
suspicious_imports = {
    "Process Injection": ["VirtualAllocEx", "WriteProcessMemory", "CreateRemoteThread", "NtCreateThreadEx"],
    "Keylogging": ["GetAsyncKeyState", "SetWindowsHookExA", "GetKeyState"],
    "Persistence": ["RegSetValueExA", "CreateServiceA", "SchTasksCreate"],
    "Evasion": ["IsDebuggerPresent", "CheckRemoteDebuggerPresent", "NtQueryInformationProcess"],
    "Network": ["InternetOpenA", "HttpSendRequestA", "URLDownloadToFileA", "WSAStartup"],
    "File Operations": ["CreateFileA", "WriteFile", "DeleteFileA", "MoveFileA"],
    "Crypto": ["CryptEncrypt", "CryptDecrypt", "CryptAcquireContextA"],
}

for entry in pe.DIRECTORY_ENTRY_IMPORT:
    dll_name = entry.dll.decode()
    for imp in entry.imports:
        if imp.name:
            func_name = imp.name.decode()
            for category, funcs in suspicious_imports.items():
                if func_name in funcs:
                    print(f"[!] {category}: {dll_name} -> {func_name}")
步骤 4:提取并分析字符串

使用 FLOSS 处理混淆字符串,并进行标准字符串提取:

# Standard strings extraction (ASCII and Unicode)
strings -a suspect.exe > strings_ascii.txt
strings -el suspect.exe > strings_unicode.txt

# FLOSS for decoded/deobfuscated strings
floss suspect.exe --output-json floss_output.json

# Search for network indicators in strings
grep -iE "(http|https|ftp)://" strings_ascii.txt
grep -iE "([0-9]{1,3}\.){3}[0-9]{1,3}" strings_ascii.txt
grep -iE "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" strings_ascii.txt

# Search for registry keys
grep -i "HKLM\\|HKCU\\|SOFTWARE\\|CurrentVersion\\Run" strings_ascii.txt

# Search for file paths and extensions
grep -iE "\.(exe|dll|bat|ps1|vbs|tmp)" strings_ascii.txt
步骤 5:检查资源和嵌入数据

检查 PE 资源节区中是否存在嵌入的载荷或配置:

# Extract resources from PE file
if hasattr(pe, 'DIRECTORY_ENTRY_RESOURCE'):
    for resource_type in pe.DIRECTORY_ENTRY_RESOURCE.entries:
        if hasattr(resource_type, 'directory'):
            for resource_id in resource_type.directory.entries:
                if hasattr(resource_id, 'directory'):
                    for resource_lang in resource_id.directory.entries:
                        data = pe.get_data(resource_lang.data.struct.OffsetToData,
                                          resource_lang.data.struct.Size)
                        entropy = calculate_entropy(data)
                        print(f"Resource Type: {resource_type.id} Size: {len(data)} Entropy: {entropy:.2f}")
                        if entropy > 7.0:
                            print(f"  [!] High entropy resource - possible embedded payload")
                        # Check for PE signature in resource (embedded executable)
                        if data[:2] == b'MZ':
                            print(f"  [!] Embedded PE detected in resource")
                            with open(f"extracted_resource_{resource_type.id}.bin", "wb") as f:
                                f.write(data)
步骤 6:检查加壳与保护

判断二进制文件是否被加壳或保护:

# Detect packer with Detect It Easy (DIE)
diec suspect.exe

# Check with PEiD signatures (command-line version)
python3 -c "
import pefile
pe = pefile.PE('suspect.exe')
# Check for common packer section names
packer_sections = {'.upx0': 'UPX', '.aspack': 'ASPack', '.adata': 'ASPack',
                   '.nsp0': 'NsPack', '.vmprotect': 'VMProtect', '.themida': 'Themida'}
for section in pe.sections:
    name = section.Name.decode().rstrip('\x00').lower()
    if name in packer_sections:
        print(f'[!] Packer detected: {packer_sections[name]} (section: {name})')

# Check import table size (very few imports suggest packing)
import_count = sum(len(entry.imports) for entry in pe.DIRECTORY_ENTRY_IMPORT)
if import_count < 10:
    print(f'[!] Only {import_count} imports - likely packed')
"
步骤 7:生成静态分析报告

将所有发现汇编成结构化的分类报告:

Document the following for each analyzed sample:
- File identification (hashes, file type, size, compile timestamp)
- Packing/protection status and identified packer
- Suspicious imports categorized by capability
- Network indicators extracted from strings (IPs, domains, URLs)
- Embedded resources and their characteristics
- Overall threat assessment and recommended next steps (sandbox execution, YARA rule creation)

关键概念

术语定义
PE(Portable Executable)Windows 可执行文件(.exe、.dll、.sys)的文件格式,包含定义操作系统如何加载二进制文件的头部、节区、导入和资源
导入地址表(IAT)列出可执行文件在运行时调用的外部 DLL 函数的 PE 结构;可揭示程序的能力和意图
节区熵PE 节区中随机性的统计度量;高于 7.0(满值 8.0)的值表示压缩、加密或加壳
FLOSSFireEye Labs Obfuscated String Solver;自动提取并解码标准 strings 遗漏的混淆字符串
加壳对 PE 文件代码节区进行压缩或加密以妨碍静态分析;需要运行时解包存根才能执行
PE 资源PE 文件内的数据节区,可包含图标、对话框、版本信息,或攻击者嵌入的载荷和配置数据
编译时间戳PE 头部中指示二进制文件编译时间的戳记;可能被伪造,但通常能揭示开发时间线

工具与系统

  • PEStudio:用于 PE 文件静态分析的免费 Windows 工具,在单一界面中提供指标、导入、字符串和资源检查
  • pefile(Python):用于以编程方式解析和分析 PE 文件结构的 Python 库,适用于自动化分析流水线
  • FLOSS:FireEye 工具,使用包括栈字符串解码在内的静态分析技术从恶意软件中提取混淆字符串
  • Detect It Easy(DIE):加壳器和编译器检测工具,可识别用于构建 PE 文件的保护器、编译器和链接器
  • CFF Explorer:高级 PE 编辑器和查看器,用于详细检查 PE 头部、节区、导入和资源目录

常见场景

场景:对可疑邮件附件进行初步分析

背景:SOC 收到关于钓鱼邮件中可疑可执行文件的告警。需要在占用沙箱资源之前对文件进行快速初步分析,以判断其是否恶意。

方法:

  1. 计算 SHA-256 哈希,并在 VirusTotal 上查询已有的检测结果和社区评论
  2. 在 PEStudio 中打开,检查 indicators 选项卡中标记为红色/黄色的项
  3. 核实编译时间戳(未来日期或 1970 年的日期表明时间戳被篡改)
  4. 检查导入表中是否有 VirtualAllocEx、CreateRemoteThread(注入)、URLDownloadToFileA(下载器)
  5. 提取字符串并搜索 C2 URL、IP 地址和文件路径
  6. 检查资源中是否嵌入 PE 文件或高熵数据块
  7. 评估加壳状态;如果已加壳,记录壳类型,并计划在深入分析前先脱壳

易犯错误:

  • 在没有佐证的情况下轻信 PE 编译时间戳(时间戳极易伪造)
  • 因为可疑导入很少就断定文件无害(加壳恶意软件会隐藏真实导入)
  • 只运行 ASCII 字符串提取,从而遗漏 Unicode 字符串
  • 未检查附加在最后一个 PE 节之后的 overlay 数据(配置数据的常见藏匿之处)

输出格式

STATIC MALWARE ANALYSIS REPORT
=================================
Sample:           suspect.exe
MD5:              d41d8cd98f00b204e9800998ecf8427e
SHA-256:          e3b0c44298fc1c149afbf4c8996fb924...
File Size:        245,760 bytes
File Type:        PE32 executable (GUI) Intel 80386
Compile Time:     2025-09-14 08:23:15 UTC

PACKING STATUS
Packer Detected:  None (native binary)
Section Entropy:  .text=6.42 .rdata=4.89 .data=3.21 .rsrc=7.81
Note:             .rsrc section entropy elevated - check resources

SUSPICIOUS IMPORTS
[INJECTION]       kernel32.dll -> VirtualAllocEx
[INJECTION]       kernel32.dll -> WriteProcessMemory
[INJECTION]       kernel32.dll -> CreateRemoteThread
[EVASION]         kernel32.dll -> IsDebuggerPresent
[NETWORK]         wininet.dll  -> InternetOpenA
[NETWORK]         wininet.dll  -> HttpSendRequestA
[PERSISTENCE]     advapi32.dll -> RegSetValueExA

EXTRACTED INDICATORS
URLs:             hxxps://update.malicious[.]com/gate.php
IPs:              185.220.101[.]42, 91.215.85[.]17
Registry Keys:    HKCU\Software\Microsoft\Windows\CurrentVersion\Run\svchost
File Paths:       C:\Users\Public\svchost.exe

EMBEDDED RESOURCES
Resource 101:     Size=98304 Entropy=7.89 [!] Embedded PE detected
Resource 102:     Size=4096  Entropy=2.14 (configuration XML)

ASSESSMENT
Threat Level:     HIGH
Classification:   Dropper with process injection capabilities
Recommended:      Execute in sandbox, extract embedded PE for separate analysis

评论

支持 Markdown