mcpField
R
reverse-engineering-malware-with-ghidra

reverse-engineering-malware-with-ghidra

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

关于 reverse-engineering-malware-with-ghidra

面向安全分析师的 Ghidra 恶意软件逆向分析流程指南,适用于初步研判后需要深入代码分析的场景。内容涉及反编译、追踪 C2 逻辑、检查混淆并据此形成检测特征。

主要功能

  1. 01导入二进制文件并自动分析
  2. 02追踪函数与交叉引用
  3. 03分析反编译代码
  4. 04调查 C2 协议
  5. 05分析加密与混淆
  6. 06编写 YARA 检测规则

适用场景

  1. 01从代码层面检查可疑恶意软件行为
  2. 02提取嵌入的 C2 配置与密钥
  3. 03记录自定义 C2 协议
  4. 04依据代码特征制定检测规则

安装

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

$npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill reverse-engineering-malware-with-ghidra

安装后在 Claude Code 中输入/reverse-engineering-malware-with-ghidra确认已加载。

包含的文件

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

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

详细介绍

使用 Ghidra 逆向工程恶意软件

何时使用

  • 静态和动态分析已识别出需要更深入代码级理解的可疑功能
  • 你需要逆向工程 C2 通信协议、加密算法或自定义混淆
  • 理解恶意软件样本针对的确切漏洞利用机制或漏洞
  • 提取嵌入在已编译代码中的硬编码配置数据(C2 地址、加密密钥、活动 ID)
  • 基于独特的代码模式开发精确的 YARA 规则或检测签名

不要使用 对未知样本进行初步分类;先使用 PEStudio 进行静态分析,并使用 Cuckoo 进行行为分析。

先决条件

  • 已安装 Ghidra 11.x(从 https://ghidra-sre.org/ 下载)以及 JDK 17+
  • 与生产网络隔离的分析 VM(Windows 或 Linux 主机)
  • 熟悉 x86/x64 汇编语言和 Windows API 约定
  • Windows 系统 DLL 的 PDB 符号文件,以提高反编译准确性
  • Ghidra 脚本仓库(ghidra_scripts)用于自动化分析任务
  • 辅助参考:IDA Free 或 Binary Ninja,用于交叉验证分析结果

工作流

步骤 1:创建项目并导入二进制文件

设置 Ghidra 项目并导入恶意软件样本:

1. Launch Ghidra: ghidraRun (Linux) or ghidraRun.bat (Windows)
2. File -> New Project -> Non-Shared Project -> Select directory
3. File -> Import File -> Select malware binary
4. Ghidra auto-detects format (PE, ELF, Mach-O) and architecture
5. Accept default import options (or specify base address if known)
6. Double-click imported file to open in CodeBrowser
7. When prompted, run Auto Analysis with default analyzers enabled

用于自动化的无头分析:

# Run Ghidra headless analysis with decompiler
/opt/ghidra/support/analyzeHeadless /tmp/ghidra_project MalwareProject \
  -import suspect.exe \
  -postScript ExportDecompilation.py \
  -scriptPath /opt/ghidra/scripts/ \
  -deleteProject
步骤 2:识别关键函数和入口点

浏览二进制文件以定位关键代码段:

Navigation Strategy:
━━━━━━━━━━━━━━━━━━━
1. Start at entry point (OEP) - follow execution from _start/WinMain
2. Check Symbol Tree for imported functions (Window -> Symbol Tree)
3. Search for cross-references to suspicious APIs:
   - VirtualAlloc/VirtualAllocEx (memory allocation for injection)
   - CreateRemoteThread (remote thread injection)
   - CryptEncrypt/CryptDecrypt (encryption operations)
   - InternetOpen/HttpSendRequest (C2 communication)
   - RegSetValueEx (persistence via registry)
4. Use Search -> For Strings to find embedded URLs, IPs, and paths
5. Check the Functions window sorted by size (large functions often contain core logic)

用于高效导航的 Ghidra 键盘快捷键:

G         - Go to address
Ctrl+E    - Search for strings
X         - Show cross-references to current location
Ctrl+Shift+F - Search memory for byte patterns
L         - Rename label/function
;         - Add comment
T         - Retype variable
Ctrl+L    - Retype return value
步骤 3:分析反编译代码

使用 Ghidra 的反编译器理解函数逻辑:

// Example: Ghidra decompiler output for a decryption routine
// Analyst renames variables and adds types for clarity

void decrypt_config(BYTE *encrypted_data, int data_len, BYTE *key, int key_len) {
    // XOR decryption with rolling key
    for (int i = 0; i < data_len; i++) {
        encrypted_data[i] = encrypted_data[i] ^ key[i % key_len];
    }
    return;
}

// Analyst actions in Ghidra:
// 1. Right-click parameters -> Retype to correct types (BYTE*, int)
// 2. Right-click variables -> Rename to meaningful names
// 3. Add comments explaining the algorithm
// 4. Set function signature to propagate types to callers
步骤 4:追踪 C2 通信逻辑

跟踪网络通信代码路径:

Analysis Steps for C2 Protocol Reverse Engineering:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1. Find InternetOpenA/WinHttpOpen call -> trace to wrapper function
2. Follow data flow from encrypted config -> URL construction
3. Identify HTTP method (GET/POST), headers, and body format
4. Locate response parsing logic (JSON parsing, custom binary protocol)
5. Map the C2 command dispatcher (switch/case or jump table)
6. Document the command set (download, execute, exfiltrate, update, uninstall)

用于提取 C2 配置的 Ghidra 脚本:

# Ghidra Python script: extract_c2_config.py
# Run via Script Manager in Ghidra

from ghidra.program.model.data import StringDataType
from ghidra.program.model.symbol import SourceType

# Search for XOR decryption patterns
listing = currentProgram.getListing()
memory = currentProgram.getMemory()

# Find references to InternetOpenA
symbol_table = currentProgram.getSymbolTable()
for symbol in symbol_table.getExternalSymbols():
    if "InternetOpen" in symbol.getName():
        refs = getReferencesTo(symbol.getAddress())
        for ref in refs:
            print("C2 init at: {}".format(ref.getFromAddress()))
步骤 5:分析加密和混淆

识别并记录加密例程:

Common Malware Encryption Patterns:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
XOR Cipher:     Loop with XOR operation, often single-byte or rolling key
RC4:            Two loops (KSA + PRGA), 256-byte S-box initialization
AES:            Look for S-box constants (0x63, 0x7C, 0x77...) or calls to CryptEncrypt
Base64:         Lookup table with A-Za-z0-9+/= characters
Custom:         Combination of arithmetic operations (ADD, SUB, ROL, ROR with XOR)

Identification Tips:
- Search for constants: AES S-box, CRC32 table, MD5 init values
- Look for loop structures operating on byte arrays
- Check for Windows Crypto API usage (CryptAcquireContext -> CryptCreateHash -> CryptEncrypt)
- FindCrypt Ghidra plugin automatically identifies crypto constants
步骤 6:记录发现并创建检测签名

从逆向工程中生成可操作的情报:

# Generate YARA rule from unique code patterns found in Ghidra
cat << 'EOF' > malware_family_x.yar
rule MalwareFamilyX_Decryptor {
    meta:
        description = "Detects MalwareX decryption routine"
        author = "analyst"
        date = "2025-09-15"
    strings:
        // XOR decryption loop with hardcoded key
        $decrypt = { 8A 04 0E 32 04 0F 88 04 0E 41 3B CA 7C F3 }
        // C2 URL pattern after decryption
        $c2_pattern = "/gate.php?id=" ascii
    condition:
        uint16(0) == 0x5A4D and $decrypt and $c2_pattern
}
EOF

关键概念

术语定义
反汇编将机器码字节转换为人类可读的汇编语言指令;Ghidra 的 Listing 视图显示反汇编代码
反编译将汇编代码提升为伪 C 表示以便于分析;Ghidra 的 Decompile 窗口提供此视图
交叉引用(XREF)显示函数或数据地址从何处被调用或使用的引用;对于追踪代码执行流至关重要
控制流图(CFG)函数中所有可能执行路径的可视化表示;揭示分支逻辑和循环
原始入口点(OEP)解包后恶意软件代码的实际起始地址;打包器首先通过解包存根重定向执行
函数签名函数的返回类型、名称和参数类型;应用正确的签名可提高反编译器输出质量
Ghidra 脚本在 Ghidra 内执行的 Python 或 Java 自动化脚本,用于执行批量分析、模式搜索或数据提取

工具与系统

  • Ghidra:NSA 的开源软件逆向工程套件,具有反汇编器、反编译器和多架构脚本支持
  • IDA Pro/Free:行业标准的交互式反汇编器;IDA Free 提供基于云的 x86/x64 反编译
  • Binary Ninja:商业逆向工程平台,具有现代 UI 和广泛的插件开发 API
  • x64dbg:用于 Windows 的开源 x64/x32 调试器,与 Ghidra 一起用于恶意软件的动态调试
  • FindCrypt(Ghidra 插件):识别二进制代码中加密常量和算法的插件

常见场景

场景:逆向自定义 C2 协议

背景:行为分析显示,存在发往外部 IP 的非标准端口加密流量。由于该协议为专有协议,网络特征无法检测其变种。需要深入逆向工程以理解协议结构。

方法:

  1. 将脱壳后的样本导入 Ghidra,并运行完整的自动分析
  2. 定位 socket/WinHTTP API 调用,并反向追溯至调用函数
  3. 识别在发送数据之前调用的加密例程(从 send/HttpSendRequest 跟踪数据流)
  4. 逆向加密算法(XOR 密钥提取、RC4 密钥派生、AES 密钥定位)
  5. 通过分析响应解析函数来梳理命令结构(对命令 ID 使用 switch/case)
  6. 记录协议格式(头部结构、命令字节、加密方法)
  7. 为网络监控工具创建协议解码器脚本

陷阱:

  • 在开始手动分析之前未运行完整的自动分析(会遗漏函数边界和类型传播)
  • 忽略通过函数指针或 vtable 进行的间接调用(使用交叉引用查找保存函数地址的数据)
  • 将时间花在 Ghidra 的 Function ID(FID)或 FLIRT 签名本应识别出的库代码上
  • 未频繁保存 Ghidra 项目进度(分析状态可能会在崩溃时丢失)

输出格式

REVERSE ENGINEERING ANALYSIS REPORT
=====================================
Sample:           unpacked_payload.exe
SHA-256:          abc123def456...
Architecture:     x86 (32-bit PE)
Ghidra Project:   MalwareX_Analysis

FUNCTION MAP
0x00401000  main()              - Entry point, initializes config
0x00401200  decrypt_config()    - XOR decryption with 16-byte key
0x00401400  init_c2()           - WinHTTP initialization, URL construction
0x00401800  c2_beacon()         - HTTP POST beacon with system info
0x00401C00  cmd_dispatcher()    - Switch on 12 command codes
0x00402000  inject_process()    - Process hollowing into svchost.exe
0x00402400  persist_registry()  - HKCU Run key persistence
0x00402800  exfil_data()        - File collection and encrypted upload

C2 PROTOCOL
Method:           HTTPS POST to /gate.php
Encryption:       RC4 with derived key (MD5 of bot_id + campaign_key)
Bot ID Format:    MD5(hostname + username + volume_serial)
Beacon Interval:  60 seconds with 10% jitter
Command Set:
  0x01 - Download and execute file
  0x02 - Execute shell command
  0x03 - Upload file to C2
  0x04 - Update configuration
  0x05 - Uninstall and remove traces

ENCRYPTION DETAILS
Algorithm:        RC4
Key Derivation:   MD5(bot_id + "campaign_2025_q3")
Hardcoded Seed:   "campaign_2025_q3" at offset 0x00405A00

EXTRACTED IOCs
C2 URLs:          hxxps://update.malicious[.]com/gate.php
                  hxxps://backup.evil[.]net/gate.php (failover)
Campaign ID:      campaign_2025_q3
RC4 Key Material: [see encryption details above]

评论

支持 Markdown