
Analyzing Prefetch Files For Execution History
- 221 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Analyzing Prefetch Files for Execution History is an agent skill that helps interpret Windows Prefetch artifacts to infer recent program execution during security investigations.
About
Analyzing Prefetch Files for Execution History is an agent skill aimed at solo builders and indie operators who need lightweight digital forensics without a full DFIR team. Windows Prefetch stores metadata about recently launched executables; this skill guides structured interpretation of those artifacts so you can corroborate or refute what ran on a workstation or build VM. Use it during security reviews, suspected compromise triage, or compliance checks when Event Viewer and EDR data are incomplete. The skill is phase-specific to Ship → security: it does not replace secure coding in Build, but it closes the gap when you must reason about ground truth on a Windows endpoint. Pair it with broader hardening and logging skills; treat conclusions as corroborating evidence alongside other telemetry. Because published SKILL.md in the repo is minimal, treat operational steps as agent-procedural knowledge you validate against your toolchain and jurisdiction before production IR.
- Interprets Windows Prefetch (.pf) records to reconstruct program execution timelines
- Supports security investigations where process logs are missing or tampered
- Fits agent-assisted forensic workflows alongside other Anthropic cybersecurity skills
- Apache 2.0–licensed skill package suitable for audit and IR playbooks
- Outputs execution-history narrative suitable for post-incident reports
Analyzing Prefetch Files For Execution History by the numbers
- 221 all-time installs (skills.sh)
- +13 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #735 of 2,203 Security skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill analyzing-prefetch-files-for-execution-historyAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 221 |
|---|---|
| repo stars | ★ 27.3k |
| Security audit | 3 / 3 scanners passed |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Investigate which programs ran on a Windows host by interpreting Prefetch artifacts during incident response or malware triage.
Who is it for?
Best when you're doing Windows endpoint triage, malware homework, or audit support with agent assistance.
Skip if: Linux-only stacks, cloud-only forensics without Windows hosts, or teams that need certified chain-of-custody tooling instead of agent-guided analysis.
When should I use this skill?
You need to infer recent program execution on Windows using Prefetch artifacts during a security or IR review.
What you get
You produce a defensible execution-history narrative from Prefetch data that you can fold into a security report or next-step containment plan.
- Execution-history summary from Prefetch interpretation
- Notes for security report or follow-up containment
Files
Analyzing Prefetch Files for Execution History
When to Use
- When determining which programs were executed on a Windows system and when
- During malware investigations to confirm execution of suspicious binaries
- For establishing a timeline of application usage during an incident
- When correlating program execution with other forensic artifacts
- To identify anti-forensic tools or unauthorized software that was run
Prerequisites
- Access to Windows Prefetch directory (C:\Windows\Prefetch\) from forensic image
- PECmd (Eric Zimmerman), WinPrefetchView, or python-prefetch parser
- Understanding of Prefetch file format (versions 17, 23, 26, 30)
- Windows system with Prefetch enabled (default on client OS, disabled on servers)
- Knowledge of Prefetch naming conventions (APPNAME-HASH.pf)
Workflow
Step 1: Extract Prefetch Files from Forensic Image
# Mount the forensic image
mount -o ro,loop,offset=$((2048*512)) /cases/case-2024-001/images/evidence.dd /mnt/evidence
# Copy all prefetch files
mkdir -p /cases/case-2024-001/prefetch/
cp /mnt/evidence/Windows/Prefetch/*.pf /cases/case-2024-001/prefetch/
# Count and list prefetch files
ls -la /cases/case-2024-001/prefetch/ | wc -l
ls -la /cases/case-2024-001/prefetch/ | head -30
# Hash all prefetch files for integrity
sha256sum /cases/case-2024-001/prefetch/*.pf > /cases/case-2024-001/prefetch/pf_hashes.txt
# Note: Prefetch filename format is EXECUTABLE_NAME-XXXXXXXX.pf
# The hash (XXXXXXXX) is based on the executable path
# Same executable from different paths creates different prefetch filesStep 2: Parse Prefetch Files with PECmd
# Using Eric Zimmerman's PECmd (Windows or via Mono/Wine on Linux)
# Download from https://ericzimmerman.github.io/
# Parse a single prefetch file
PECmd.exe -f "C:\cases\prefetch\POWERSHELL.EXE-A]B2C3D4.pf"
# Parse all prefetch files and output to CSV
PECmd.exe -d "C:\cases\prefetch\" --csv "C:\cases\analysis\" --csvf prefetch_results.csv
# Parse with JSON output
PECmd.exe -d "C:\cases\prefetch\" --json "C:\cases\analysis\" --jsonf prefetch_results.json
# Output includes for each file:
# - Executable name and path
# - Run count
# - Last run time (up to 8 timestamps in Windows 10)
# - Files and directories referenced during execution
# - Volume information (serial number, creation date)
# - Prefetch file creation timeStep 3: Parse with Python for Linux-Based Analysis
pip install prefetch
python3 << 'PYEOF'
import os
import json
from datetime import datetime
# Parse prefetch files using python
import struct
def parse_prefetch(filepath):
"""Parse a Windows Prefetch file."""
with open(filepath, 'rb') as f:
data = f.read()
# Check for MAM compressed format (Windows 10)
if data[:4] == b'MAM\x04':
import lznt1 # or use DecompressBuffer
# Windows 10 prefetch files are compressed
print(f" [Compressed Win10 format - use PECmd for full parsing]")
return None
# Version 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" Invalid prefetch signature")
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,
}
# Extract last execution timestamps
if version == 23: # Vista/7 - 1 timestamp
ts = struct.unpack('<Q', data[128:136])[0]
result['last_run'] = filetime_to_datetime(ts)
elif version >= 26: # Win8+ - up to 8 timestamps
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):
"""Convert Windows FILETIME to datetime string."""
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
# Process all prefetch files
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" Executable: {result['executable']}")
print(f" Run Count: {result['run_count']}")
if 'last_run' in result:
print(f" Last Run: {result['last_run']}")
elif 'last_run_times' in result:
for i, ts in enumerate(result['last_run_times']):
print(f" Run Time {i+1}: {ts}")
results.append(result)
# Save results
with open('/cases/case-2024-001/analysis/prefetch_analysis.json', 'w') as f:
json.dump(results, f, indent=2)
PYEOFStep 4: Identify Suspicious Execution Evidence
# Search for known malicious tool names in prefetch
ls /cases/case-2024-001/prefetch/ | grep -iE \
'(MIMIKATZ|PSEXEC|WMIC|COBALT|BEACON|PWDUMP|PROCDUMP|LAZAGNE|RUBEUS|BLOODHOUND|SHARPHOUND|CERTUTIL|BITSADMIN)'
# Search for script interpreters (potential malicious execution)
ls /cases/case-2024-001/prefetch/ | grep -iE \
'(POWERSHELL|CMD\.EXE|WSCRIPT|CSCRIPT|MSHTA|REGSVR32|RUNDLL32|MSIEXEC)'
# Search for remote access tools
ls /cases/case-2024-001/prefetch/ | grep -iE \
'(TEAMVIEWER|ANYDESK|LOGMEIN|VNC|SPLASHTOP|SCREENCONNECT|AMMYY)'
# Search for data exfiltration tools
ls /cases/case-2024-001/prefetch/ | grep -iE \
'(RAR|7Z|ZIP|RCLONE|MEGA|DROPBOX|ONEDRIVE|GDRIVE|FTP|CURL|WGET)'
# Find recently created prefetch files (newest executables run)
ls -lt /cases/case-2024-001/prefetch/ | head -20
# Cross-reference with Shimcache and Amcache for confirmation
# Prefetch existence = program was executed at least onceStep 5: Build Execution Timeline
# Create timeline from prefetch data
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'
})
# Sort chronologically
timeline.sort(key=lambda x: x['timestamp'])
# Write timeline 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)
# Print suspicious time window
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']})")
PYEOFKey Concepts
| Concept | Description |
|---|---|
| Prefetch | Windows performance optimization that pre-loads application data and tracks execution |
| SCCA signature | Magic bytes identifying a valid Prefetch file |
| Path hash | CRC-based hash of the executable path forming part of the .pf filename |
| Run count | Number of times the executable has been launched (may wrap around) |
| Last run timestamps | Windows 8+ stores up to 8 most recent execution timestamps |
| Referenced files | List of files and directories accessed during the first 10 seconds of execution |
| Volume information | Drive serial number and creation date identifying the source volume |
| MAM compression | Windows 10 Prefetch files use MAM4 compression requiring decompression before parsing |
Tools & Systems
| Tool | Purpose |
|---|---|
| PECmd | Eric Zimmerman's Prefetch parser with CSV/JSON output |
| WinPrefetchView | NirSoft GUI tool for viewing Prefetch files |
| python-prefetch | Python library for parsing Prefetch files |
| Prefetch Hash Calculator | Tool to calculate expected hash from executable paths |
| KAPE | Automated artifact collection including Prefetch |
| Autopsy | Forensic platform with Prefetch analysis module |
| Plaso/log2timeline | Super-timeline tool that includes Prefetch parser |
| Velociraptor | Endpoint agent with Prefetch collection and analysis artifacts |
Common Scenarios
Scenario 1: Confirming Malware Execution Search Prefetch directory for the malware executable name, confirm execution via Prefetch existence, extract run count and last run time, identify referenced DLLs to understand malware behavior, correlate with registry autorun entries.
Scenario 2: Attacker Tool Usage Timeline Identify Prefetch files for PsExec, Mimikatz, BloodHound, and other attacker tools, build chronological timeline of tool execution, determine the sequence of the attack (reconnaissance, credential theft, lateral movement), match timestamps with network connection logs.
Scenario 3: Data Staging and Exfiltration Look for Prefetch entries of compression tools (7z, WinRAR, zip), identify execution of file transfer utilities (rclone, FTP clients), check for cloud storage client execution, timeline when data staging and transfer occurred.
Scenario 4: Anti-Forensics Detection Check for execution of known anti-forensic tools (CCleaner, Eraser, SDelete), identify if Prefetch directory was recently cleared (fewer files than expected for active system), note timestamps of anti-forensic tool execution relative to other evidence.
Output Format
Prefetch Analysis Summary:
System: Windows 10 Pro (Build 19041)
Prefetch Files: 234
Analysis Period: All available execution history
Execution Statistics:
Total unique executables: 234
First execution: 2023-06-15 (system install)
Latest execution: 2024-01-18 23:45 UTC
Suspicious Executions:
MIMIKATZ.EXE-5F2A3B1C.pf
Run Count: 3 | Last: 2024-01-16 02:30:15 UTC
PSEXEC.EXE-AD70946C.pf
Run Count: 7 | Last: 2024-01-16 02:45:30 UTC
RCLONE.EXE-1F3E5A2B.pf
Run Count: 2 | Last: 2024-01-17 03:15:00 UTC
POWERSHELL.EXE-022A1004.pf
Run Count: 145 | Last: 2024-01-18 14:00:00 UTC
Attack Timeline (from Prefetch):
2024-01-15 14:32 - POWERSHELL.EXE (initial access)
2024-01-16 02:30 - MIMIKATZ.EXE (credential theft)
2024-01-16 02:45 - PSEXEC.EXE (lateral movement)
2024-01-17 03:15 - RCLONE.EXE (data exfiltration)
Report: /cases/case-2024-001/analysis/execution_timeline.csv
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: Windows Prefetch Analysis Tools
Prefetch File Format
Location
C:\Windows\Prefetch\Filename Convention
EXECUTABLE_NAME-XXXXXXXX.pfEXECUTABLE_NAME- Uppercase name of the executed programXXXXXXXX- Hash of the executable path (8 hex characters).pf- Prefetch file extension
Version History
| Version | Windows OS | Notes |
|---|---|---|
| 17 | XP | Basic format |
| 23 | Vista, 7 | Added run count, timestamps |
| 26 | 8, 8.1 | Extended timestamps (8 entries) |
| 30 | 10, 11 | MAM compressed, 8 timestamps |
Header Structure (Uncompressed)
| Offset | Size | Field |
|---|---|---|
| 0 | 4 | Version |
| 4 | 4 | Signature (SCCA) |
| 12 | 4 | File size |
| 16 | 60 | Executable name (UTF-16LE) |
| 76 | 4 | Prefetch hash |
PECmd (Eric Zimmerman) - Full Parser
Syntax
PECmd.exe -f <prefetch_file> # Single file
PECmd.exe -d <prefetch_directory> # Entire directory
PECmd.exe -d <dir> --csv <output_dir> # Export to CSV
PECmd.exe -d <dir> --json <output_dir> # Export to JSON
PECmd.exe -f <file> -q # Quiet modeOutput Fields
| Field | Description |
|---|---|
SourceFilename | Original executable path |
RunCount | Number of times executed |
LastRun | Most recent execution timestamp |
PreviousRun0-7 | Up to 8 previous run timestamps (Win8+) |
FilesLoaded | DLLs and files accessed during execution |
Directories | Directories accessed |
VolumeSerialNumber | Volume where executable resided |
WinPrefetchView (NirSoft)
GUI Features
- Lists all prefetch files with execution details
- Shows run count, timestamps, referenced files
- Export to CSV, HTML, or text
- Sort by any column for analysis
Python Prefetch Parsing
Structure Parsing
import struct
with open("APP.EXE-HASH.pf", "rb") as f:
data = f.read()
version = struct.unpack_from("<I", data, 0)[0]
signature = data[4:8] # Should be b"SCCA"
exe_name = data[16:76].decode("utf-16-le").rstrip("\x00")
pf_hash = struct.unpack_from("<I", data, 76)[0]FILETIME Conversion
import datetime
def filetime_to_datetime(filetime):
epoch = datetime.datetime(1601, 1, 1)
delta = datetime.timedelta(microseconds=filetime // 10)
return epoch + deltaSuspicious Prefetch Indicators
Offensive Tools
| Tool | Prefetch Name |
|---|---|
| Mimikatz | MIMIKATZ.EXE-*.pf |
| PsExec | PSEXEC.EXE-*.pf, PSEXESVC.EXE-*.pf |
| BloodHound | SHARPHOUND.EXE-*.pf |
| Rubeus | RUBEUS.EXE-*.pf |
| LaZagne | LAZAGNE.EXE-*.pf |
LOLBins (Living Off the Land)
| Binary | Concern |
|---|---|
CERTUTIL.EXE | File download, Base64 decode |
MSHTA.EXE | Script execution via HTA |
REGSVR32.EXE | COM scriptlet execution |
BITSADMIN.EXE | File download |
MSBUILD.EXE | Code execution via project files |
Timeline Integration
Plaso / log2timeline
log2timeline.py timeline.plaso /path/to/prefetch/
psort.py -o l2tcsv timeline.plaso > prefetch_timeline.csv#!/usr/bin/env python3
"""Windows Prefetch file analysis agent for program execution history forensics."""
import struct
import os
import sys
import datetime
import json
import glob
def parse_prefetch_header(filepath):
"""Parse the Prefetch file header to extract execution metadata."""
with open(filepath, "rb") as f:
data = f.read()
# Check for compression (Windows 10 prefetch files are MAM compressed)
if data[:4] == b"MAM\x04":
# Windows 10 compressed format - need decompression
return {"error": "Compressed prefetch (Windows 10 MAM format) - use PECmd for full parsing",
"compressed": True, "raw_size": len(data)}
# Standard prefetch header (versions 17, 23, 26, 30)
if len(data) < 84:
return {"error": "File too small to be a valid prefetch file"}
version = struct.unpack_from("<I", data, 0)[0]
signature = data[4:8]
if signature != b"SCCA":
return {"error": f"Invalid signature: {signature.hex()} (expected 53434341)"}
file_size = struct.unpack_from("<I", data, 12)[0]
exe_name = data[16:76].decode("utf-16-le", errors="replace").rstrip("\x00")
hash_value = struct.unpack_from("<I", data, 76)[0]
result = {
"version": version,
"signature": signature.hex(),
"file_size": file_size,
"executable_name": exe_name,
"prefetch_hash": f"0x{hash_value:08X}",
}
# Version-specific parsing
if version == 17: # Windows XP
result["format"] = "Windows XP"
run_count = struct.unpack_from("<I", data, 144)[0]
last_run = parse_filetime(struct.unpack_from("<Q", data, 120)[0])
result["run_count"] = run_count
result["last_run_time"] = last_run
elif version == 23: # Windows Vista/7
result["format"] = "Windows Vista/7"
run_count = struct.unpack_from("<I", data, 152)[0]
last_run = parse_filetime(struct.unpack_from("<Q", data, 128)[0])
result["run_count"] = run_count
result["last_run_time"] = last_run
elif version == 26: # Windows 8/8.1
result["format"] = "Windows 8/8.1"
run_count = struct.unpack_from("<I", data, 208)[0]
last_run = parse_filetime(struct.unpack_from("<Q", data, 128)[0])
result["run_count"] = run_count
result["last_run_time"] = last_run
elif version == 30: # Windows 10/11
result["format"] = "Windows 10/11"
result["note"] = "Use PECmd.exe for full Windows 10 prefetch parsing"
else:
result["format"] = f"Unknown version {version}"
return result
def parse_filetime(filetime):
"""Convert Windows FILETIME (100ns intervals since 1601-01-01) to ISO string."""
if filetime == 0:
return "N/A"
try:
epoch = datetime.datetime(1601, 1, 1)
delta = datetime.timedelta(microseconds=filetime // 10)
dt = epoch + delta
return dt.isoformat() + "Z"
except (OverflowError, OSError):
return "Invalid timestamp"
def parse_prefetch_filename(filename):
"""Parse executable name and hash from prefetch filename format: APPNAME-HASH.pf."""
basename = os.path.basename(filename)
if not basename.upper().endswith(".PF"):
return None, None
name_part = basename[:-3] # Remove .pf
parts = name_part.rsplit("-", 1)
if len(parts) == 2:
return parts[0], parts[1]
return name_part, None
def scan_prefetch_directory(prefetch_dir):
"""Scan a directory of prefetch files and extract execution history."""
results = []
pf_files = glob.glob(os.path.join(prefetch_dir, "*.pf"))
pf_files.extend(glob.glob(os.path.join(prefetch_dir, "*.PF")))
for pf_file in sorted(set(pf_files)):
exe_name, pf_hash = parse_prefetch_filename(pf_file)
header = parse_prefetch_header(pf_file)
results.append({
"file": os.path.basename(pf_file),
"parsed_name": exe_name,
"parsed_hash": pf_hash,
"file_modified": datetime.datetime.fromtimestamp(
os.path.getmtime(pf_file)).isoformat(),
"header": header,
})
return results
SUSPICIOUS_EXECUTABLES = [
"MIMIKATZ", "PSEXEC", "WMIC", "PROCDUMP", "RUBEUS", "SEATBELT",
"BLOODHOUND", "SHARPHOUND", "LAZAGNE", "SECRETSDUMP", "NTDSUTIL",
"CERTUTIL", "BITSADMIN", "MSHTA", "REGSVR32", "RUNDLL32",
"CSCRIPT", "WSCRIPT", "POWERSHELL", "CMD", "MSBUILD",
"INSTALLUTIL", "REGASM", "REGSVCS", "XWIZARD",
"NETCAT", "NCAT", "NC", "NMAP", "MASSCAN",
"RAR", "7Z", "WINRAR", "RCLONE",
]
def detect_suspicious_execution(prefetch_results):
"""Flag suspicious or known-attacker-tool prefetch files."""
findings = []
for result in prefetch_results:
name = (result.get("parsed_name") or "").upper()
for sus in SUSPICIOUS_EXECUTABLES:
if sus in name:
findings.append({
"severity": "HIGH",
"executable": result.get("parsed_name"),
"file": result.get("file"),
"reason": f"Known offensive/dual-use tool: {sus}",
"run_count": result.get("header", {}).get("run_count"),
"last_run": result.get("header", {}).get("last_run_time"),
})
break
return findings
def build_execution_timeline(prefetch_results):
"""Build a chronological timeline of program execution."""
timeline = []
for result in prefetch_results:
header = result.get("header", {})
last_run = header.get("last_run_time")
if last_run and last_run not in ("N/A", "Invalid timestamp"):
timeline.append({
"timestamp": last_run,
"executable": result.get("parsed_name"),
"run_count": header.get("run_count"),
"prefetch_file": result.get("file"),
})
return sorted(timeline, key=lambda x: x["timestamp"])
def run_pecmd(prefetch_path, output_dir=None):
"""Run Eric Zimmerman's PECmd for comprehensive prefetch parsing."""
import subprocess
cmd = ["PECmd.exe", "-f", prefetch_path]
if output_dir:
cmd += ["--csv", output_dir]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
return result.stdout, result.returncode
if __name__ == "__main__":
print("=" * 60)
print("Windows Prefetch File Analysis Agent")
print("Execution history, timeline building, suspicious tool detection")
print("=" * 60)
target = sys.argv[1] if len(sys.argv) > 1 else None
if target and os.path.exists(target):
if os.path.isdir(target):
print(f"\n[*] Scanning prefetch directory: {target}")
results = scan_prefetch_directory(target)
print(f"[*] Found {len(results)} prefetch files")
print("\n--- Execution History ---")
for r in results[:20]:
header = r.get("header", {})
name = r.get("parsed_name", "?")
count = header.get("run_count", "?")
last = header.get("last_run_time", "?")
print(f" {name:30s} runs={count} last={last}")
print("\n--- Suspicious Executables ---")
suspicious = detect_suspicious_execution(results)
for s in suspicious:
print(f" [!] {s['executable']}: {s['reason']} "
f"(runs={s['run_count']}, last={s['last_run']})")
print("\n--- Execution Timeline ---")
timeline = build_execution_timeline(results)
for t in timeline[-20:]:
print(f" {t['timestamp']} | {t['executable']} (x{t['run_count']})")
else:
print(f"\n[*] Analyzing: {target}")
exe_name, pf_hash = parse_prefetch_filename(target)
print(f" Name: {exe_name}, Hash: {pf_hash}")
header = parse_prefetch_header(target)
print(f" {json.dumps(header, indent=2)}")
else:
print(f"\n[DEMO] Usage:")
print(f" python agent.py <prefetch_dir> # Analyze all .pf files")
print(f" python agent.py <file.pf> # Analyze single prefetch file")
Related skills
How it compares
Use for Windows artifact forensics rather than generic “scan my repo for secrets” security skills.
FAQ
Who is analyzing-prefetch-files-for-execution-history for?
Developers, security-curious founders, and small teams investigating Windows endpoints who want structured Prefetch interpretation via Claude Code, Cursor, or similar agents.
When should I use analyzing-prefetch-files-for-execution-history?
During Ship-phase security work: post-incident triage on a dev laptop, validating what ran on a build VM, or supplementing logs before you ship updates from a compromised-suspect machine.
Is analyzing-prefetch-files-for-execution-history safe to install?
Review the Security Audits panel on this Prism page and the upstream repo license; forensics skills may imply handling sensitive host data—run only on systems you own or are authorized to examine.