Communitygithub.com

预取文件执行历史分析

使用 PECmd、WinPrefetchView 或 python-prefetch 等工具解析 Windows 预取文件(版本 17、23、26、30),以确定程序执行历史,包括运行次数、执行时间戳以及引用的文件/DLL。用于在调查期间构建 Windows 系统上的程序执行时间线、确认可疑二进制文件是否运行,或关联执行证据与其他取证构件。

预取文件执行历史分析 是什么?

该技能专注于分析 Windows 预取(Prefetch)文件,以揭示系统上程序的执行历史。预取是 Windows 的一项性能优化功能,会记录应用程序的加载信息和运行轨迹,生成以 `.pf` 为扩展名的文件,通常位于 `C:\Windows\Prefetch\`。通过解析这些文件,可以获取每个可执行文件的运行次数、最近运行时间(Windows 8+ 支持最多 8 个时间戳)、引用的文件和 DLL 列表、卷信息等关键数据。该技能支持三种主流解析工具:Eric Zimmerman 的 PECmd(功能最全面,支持 CSV/JSON 输出)、NirSoft 的 WinPrefetchView(图形界面)以及 python-prefetch 库(适用于 Linux/Mac 分析环境)。使用场景包括:确认恶意软件是否在系统上运行、构建攻击者工具使用时间线、检测数据压缩/传输工具用于数据外泄、识别反取证工具的痕迹。工作流程包括:从取证镜像提取预取文件、使用 PECmd 或 Python 解析文件、识别可疑执行、构建执行时间线。该技能适用于 Windows 10/11、Windows 7/8、Windows Server 等主流系统(服务器默认禁用预取,需手动确认)。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/mukul975/Anthropic-Cybersecurity-Skills/tree/main/skills/analyzing-prefetch-files-for-execution-history

在你喜欢的 AI 中提问

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

文档

预取文件执行历史分析 是做什么的?

何时使用

  • 当需要确定 Windows 系统上执行了哪些程序及执行时间时
  • 在恶意软件调查中,确认可疑二进制文件是否运行
  • 构建事件期间应用程序使用的时间线
  • 将程序执行与其他取证构件进行关联
  • 识别运行过的反取证工具或未经授权的软件

前置条件

  • 从取证镜像中访问 Windows 预取目录(C:\Windows\Prefetch\)
  • PECmd(Eric Zimmerman)、WinPrefetchView 或 python-prefetch 解析器
  • 了解预取文件格式(版本 17、23、26、30)
  • 启用了预取的 Windows 系统(客户端操作系统默认启用,服务器禁用)
  • 了解预取命名约定(APPNAME-HASH.pf)

工作流程

步骤 1:从取证镜像中提取预取文件

# 挂载取证镜像
mount -o ro,loop,offset=$((2048*512)) /cases/case-2024-001/images/evidence.dd /mnt/evidence

# 复制所有预取文件
mkdir -p /cases/case-2024-001/prefetch/
cp /mnt/evidence/Windows/Prefetch/*.pf /cases/case-2024-001/prefetch/

# 统计和列出预取文件
ls -la /cases/case-2024-001/prefetch/ | wc -l
ls -la /cases/case-2024-001/prefetch/ | head -30

# 为所有预取文件计算哈希以确保完整性
sha256sum /cases/case-2024-001/prefetch/*.pf > /cases/case-2024-001/prefetch/pf_hashes.txt

# 注意:预取文件名格式为 EXECUTABLE_NAME-XXXXXXXX.pf
# 哈希值(XXXXXXXX)基于可执行文件路径计算
# 不同路径下的同一可执行文件会产生不同的预取文件

步骤 2:使用 PECmd 解析预取文件

# 使用 Eric Zimmerman 的 PECmd(Windows 上,或 Linux 上通过 Mono/Wine)
# 从 https://ericzimmerman.github.io/ 下载

# 解析单个预取文件
PECmd.exe -f "C:\cases\prefetch\POWERSHELL.EXE-A]B2C3D4.pf"

# 解析所有预取文件并输出为 CSV
PECmd.exe -d "C:\cases\prefetch\" --csv "C:\cases\analysis\" --csvf prefetch_results.csv

# 解析并以 JSON 格式输出
PECmd.exe -d "C:\cases\prefetch\" --json "C:\cases\analysis\" --jsonf prefetch_results.json

# 每个文件的输出包括:
# - 可执行文件名称和路径
# - 运行次数
# - 最后运行时间(Windows 10 中最多 8 个时间戳)
# - 执行期间引用的文件和目录
# - 卷信息(序列号、创建日期)
# - 预取文件创建时间

步骤 3:在 Linux 环境下使用 Python 解析

pip install prefetch

python3 << 'PYEOF'
import os
import json
from datetime import datetime

# 使用 python 解析预取文件
import struct

def parse_prefetch(filepath):
    """解析 Windows 预取文件。"""
    with open(filepath, 'rb') as f:
        data = f.read()

    # 检查 MAM 压缩格式(Windows 10)
    if data[:4] == b'MAM\x04':
        import lznt1  # 或使用 DecompressBuffer
        # Windows 10 预取文件是压缩的
        print(f"  [已压缩的 Win10 格式 - 请使用 PECmd 进行完整解析]")
        return None

    # 版本 17 (XP)、23 (Vista/7)、26 (8.1)、30 (10)
    version = struct.unpack('<I', data[0:4])[0]
    signature = data[4:8]

    if signature != b'SCCA':
        print(f"  无效的预取签名")
        return None

    file_size = struct.unpack('<I', data[8:12])[0]
    exec_name = data[16:76].decode('utf-16-le').strip('\x00')
    run_count = struct.unpack('<I', data[208:212])[0] if version >= 23 else struct.unpack('<I', data[144:148])[0]

    result = {
        'version': version,
        'executable': exec_name,
        'file_size': file_size,
        'run_count': run_count,
    }

    # 提取最后执行时间戳
    if version == 23:  # Vista/7 - 1 个时间戳
        ts = struct.unpack('<Q', data[128:136])[0]
        result['last_run'] = filetime_to_datetime(ts)
    elif version >= 26:  # Win8+ - 最多 8 个时间戳
        timestamps = []
        for i in range(8):
            ts = struct.unpack('<Q', data[128+i*8:136+i*8])[0]
            if ts > 0:
                timestamps.append(filetime_to_datetime(ts))
        result['last_run_times'] = timestamps

    return result

def filetime_to_datetime(ft):
    """将 Windows FILETIME 转换为日期时间字符串。"""
    if ft == 0:
        return None
    timestamp = (ft - 116444736000000000) / 10000000
    try:
        return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S UTC')
    except (OSError, ValueError):
        return None

# 处理所有预取文件
prefetch_dir = '/cases/case-2024-001/prefetch/'
results = []

for filename in sorted(os.listdir(prefetch_dir)):
    if filename.lower().endswith('.pf'):
        filepath = os.path.join(prefetch_dir, filename)
        print(f"\n=== {filename} ===")
        result = parse_prefetch(filepath)
        if result:
            print(f"  可执行文件: {result['executable']}")
            print(f"  运行次数:  {result['run_count']}")
            if 'last_run' in result:
                print(f"  最后运行:   {result['last_run']}")
            elif 'last_run_times' in result:
                for i, ts in enumerate(result['last_run_times']):
                    print(f"  运行时间 {i+1}: {ts}")
            results.append(result)

# 保存结果
with open('/cases/case-2024-001/analysis/prefetch_analysis.json', 'w') as f:
    json.dump(results, f, indent=2)
PYEOF

步骤 4:识别可疑执行证据

# 搜索预取文件中已知的恶意工具名称
ls /cases/case-2024-001/prefetch/ | grep -iE \
   '(MIMIKATZ|PSEXEC|WMIC|COBALT|BEACON|PWDUMP|PROCDUMP|LAZAGNE|RUBEUS|BLOODHOUND|SHARPHOUND|CERTUTIL|BITSADMIN)'

# 搜索脚本解释器(潜在恶意执行)
ls /cases/case-2024-001/prefetch/ | grep -iE \
   '(POWERSHELL|CMD\.EXE|WSCRIPT|CSCRIPT|MSHTA|REGSVR32|RUNDLL32|MSIEXEC)'

# 搜索远程访问工具
ls /cases/case-2024-001/prefetch/ | grep -iE \
   '(TEAMVIEWER|ANYDESK|LOGMEIN|VNC|SPLASHTOP|SCREENCONNECT|AMMYY)'

# 搜索数据外泄工具
ls /cases/case-2024-001/prefetch/ | grep -iE \
   '(RAR|7Z|ZIP|RCLONE|MEGA|DROPBOX|ONEDRIVE|GDRIVE|FTP|CURL|WGET)'

# 查找最近创建的预取文件(最新运行的可执行文件)
ls -lt /cases/case-2024-001/prefetch/ | head -20

# 与 Shimcache 和 Amcache 交叉验证
# 预取文件存在 = 程序至少运行了一次

步骤 5:构建执行时间线

# 从预取数据创建时间线
python3 << 'PYEOF'
import json
import csv

with open('/cases/case-2024-001/analysis/prefetch_analysis.json') as f:
    data = json.load(f)

timeline = []
for entry in data:
    if 'last_run_times' in entry:
        for ts in entry['last_run_times']:
            if ts:
                timeline.append({
                    'timestamp': ts,
                    'executable': entry['executable'],
                    'run_count': entry['run_count'],
                    'source': 'Prefetch'
                })
    elif 'last_run' in entry and entry['last_run']:
        timeline.append({
            'timestamp': entry['last_run'],
            'executable': entry['executable'],
            'run_count': entry['run_count'],
            'source': 'Prefetch'
        })

# 按时间顺序排序
timeline.sort(key=lambda x: x['timestamp'])

# 写入时间线 CSV 文件
with open('/cases/case-2024-001/analysis/execution_timeline.csv', 'w', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=['timestamp', 'executable', 'run_count', 'source'])
    writer.writeheader()
    writer.writerows(timeline)

# 打印可疑时间窗口内的记录
for entry in timeline:
    if '2024-01-15' in entry['timestamp'] or '2024-01-16' in entry['timestamp']:
        print(f"  {entry['timestamp']} | {entry['executable']} (x{entry['run_count']})")
PYEOF

关键概念

概念描述
预取Windows 性能优化,预加载应用程序数据并跟踪执行
SCCA 签名标识有效预取文件的魔法字节
路径哈希基于可执行文件路径的 CRC 哈希,构成 .pf 文件名的一部分
运行次数可执行文件启动的次数(可能溢出)
最后运行时间戳Windows 8+ 存储最多 8 个最近的执行时间戳
引用的文件执行前 10 秒内访问的文件和目录列表
卷信息标识源卷的驱动器序列号和创建日期
MAM 压缩Windows 10 预取文件使用 MAM4 压缩,需要解压后才能解析

工具与系统

工具用途
PECmdEric Zimmerman 的预取解析器,支持 CSV/JSON 输出
WinPrefetchViewNirSoft 图形界面工具,用于查看预取文件
python-prefetch用于解析预取文件的 Python 库
预取哈希计算器根据可执行文件路径计算预期哈希的工具
KAPE自动化构件收集工具,支持预取文件收集
Autopsy取证平台,包含预取分析模块
Plaso/log2timeline超级时间线工具,包含预取解析器
Velociraptor端点代理,支持预取收集和分析构件

常见场景

场景 1:确认恶意软件执行 在预取目录中搜索恶意软件可执行文件名,通过预取文件是否存在来确认执行情况,提取运行次数和最后运行时间,识别引用的 DLL 以了解恶意软件行为,与注册表自动启动项进行关联。

场景 2:攻击者工具使用时间线 识别 PsExec、Mimikatz、BloodHound 及其他攻击者工具的预取文件,构建工具执行的时间顺序时间线,确定攻击顺序(侦查、凭据窃取、横向移动),将时间戳与网络连接日志匹配。

场景 3:数据准备与外泄 查找压缩工具(7z、WinRAR、zip)的预取条目,识别文件传输实用程序(rclone、FTP 客户端)的执行情况,检查云存储客户端的执行,时间线记录数据准备和传输的时刻。

场景 4:反取证检测 检查已知的反取证工具执行情况(CCleaner、Eraser、SDelete),确认预取目录是否被最近清除(活跃系统上文件数量少于预期),记录反取证工具执行的时间戳并与其他证据进行比对。

输出格式

预取分析摘要:
  系统:Windows 10 Pro(版本 19041)
  预取文件数:234
  分析周期:所有可用的执行历史

  执行统计:
    唯一可执行文件总数:234
    首次执行:2023-06-15(系统安装)
    最近执行:2024-01-18 23:45 UTC

  可疑执行:
    MIMIKATZ.EXE-5F2A3B1C.pf
      运行次数:3 | 最后运行:2024-01-16 02:30:15 UTC
    PSEXEC.EXE-AD70946C.pf
      运行次数:7 | 最后运行:2024-01-16 02:45:30 UTC
    RCLONE.EXE-1F3E5A2B.pf
      运行次数:2 | 最后运行:2024-01-17 03:15:00 UTC
    POWERSHELL.EXE-022A1004.pf
      运行次数:145 | 最后运行:2024-01-18 14:00:00 UTC

  攻击时间线(来自预取):
    2024-01-15 14:32 - POWERSHELL.EXE(初始访问)
    2024-01-16 02:30 - MIMIKATZ.EXE(凭据窃取)
    2024-01-16 02:45 - PSEXEC.EXE(横向移动)
    2024-01-17 03:15 - RCLONE.EXE(数据外泄)

  报告:/cases/case-2024-001/analysis/execution_timeline.csv

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,

相关技能