
Analyzing Usb Device Connection History
- 201 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Guide forensic review of USB device connection history to spot unauthorized removable media use during incident response or endpoint audits.
About
Analyzing USB Device Connection History is a security-oriented agent skill from the Anthropic cybersecurity skills line aimed at helping you interpret historical USB attachment evidence on endpoints. Solo builders and indie operators who ship desktop utilities, handle customer data on laptops, or run small-team IR drills install it when they need structured prompts for removable-media timelines rather than improvised shell grepping. Prism lists it under ship security because the payoff is catching policy violations, staging vectors, or post-incident scope before broader launch or operate phases. Public SKILL excerpts in the bundle emphasize licensing metadata; pair this skill with your OS-specific artifact locations and chain-of-custody practices. It is not a substitute for enterprise EDR, certified forensics labs, or legal discovery processes.
- Part of Anthropic cybersecurity skills collection for defensive analysis workflows
- Focuses on USB device connection history as an investigative surface
- Supports audit and incident-response style questions about prior attached devices
- Apache-2.0 licensed skill packaging for reuse in agent playbooks
- Fits endpoint forensics alongside broader security skill sets
Analyzing Usb Device Connection History by the numbers
- 201 all-time installs (skills.sh)
- +10 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #774 of 2,203 Security skills by installs in the Skillselion catalog
- Security screen: MEDIUM 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-usb-device-connection-historyAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 201 |
|---|---|
| repo stars | ★ 27.3k |
| Security audit | 2 / 3 scanners passed |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Guide forensic review of USB device connection history to spot unauthorized removable media use during incident response or endpoint audits.
Files
Analyzing USB Device Connection History
When to Use
- When investigating potential data exfiltration via removable storage devices
- During insider threat investigations to track USB device usage
- For compliance audits verifying removable media policy enforcement
- When correlating USB connections with file access and copy events
- For establishing a timeline of device connections during an incident
Prerequisites
- Forensic image or extracted registry hives and event logs
- Access to SYSTEM, SOFTWARE, and NTUSER.DAT registry hives
- SetupAPI logs (setupapi.dev.log)
- Windows Event Logs (System, Security, DriverFrameworks-UserMode)
- USBDeview, USB Forensic Tracker, or RegRipper
- Understanding of USB device identification (VID, PID, serial number)
Workflow
Step 1: Extract USB-Related Artifacts
# Mount forensic image and copy relevant artifacts
mount -o ro,loop,offset=$((2048*512)) /cases/case-2024-001/images/evidence.dd /mnt/evidence
mkdir -p /cases/case-2024-001/usb/
# Registry hives
cp /mnt/evidence/Windows/System32/config/SYSTEM /cases/case-2024-001/usb/
cp /mnt/evidence/Windows/System32/config/SOFTWARE /cases/case-2024-001/usb/
cp /mnt/evidence/Users/*/NTUSER.DAT /cases/case-2024-001/usb/
# SetupAPI logs (first connection timestamps)
cp /mnt/evidence/Windows/INF/setupapi.dev.log /cases/case-2024-001/usb/
# Event logs
cp /mnt/evidence/Windows/System32/winevt/Logs/System.evtx /cases/case-2024-001/usb/
cp "/mnt/evidence/Windows/System32/winevt/Logs/Microsoft-Windows-DriverFrameworks-UserMode%4Operational.evtx" \
/cases/case-2024-001/usb/ 2>/dev/null
cp "/mnt/evidence/Windows/System32/winevt/Logs/Microsoft-Windows-Partition%4Diagnostic.evtx" \
/cases/case-2024-001/usb/ 2>/dev/nullStep 2: Parse USBSTOR Registry Key
# Extract USBSTOR entries from SYSTEM hive
python3 << 'PYEOF'
from Registry import Registry
import json
reg = Registry.Registry("/cases/case-2024-001/usb/SYSTEM")
# Find current ControlSet
select = reg.open("Select")
current = select.value("Current").value()
controlset = f"ControlSet{current:03d}"
# Parse USBSTOR
usbstor_path = f"{controlset}\\Enum\\USBSTOR"
usbstor = reg.open(usbstor_path)
devices = []
print("=== USBSTOR DEVICES ===\n")
for device_class in usbstor.subkeys():
# Format: Disk&Ven_VENDOR&Prod_PRODUCT&Rev_REVISION
class_name = device_class.name()
parts = class_name.split('&')
vendor = parts[1].replace('Ven_', '') if len(parts) > 1 else 'Unknown'
product = parts[2].replace('Prod_', '') if len(parts) > 2 else 'Unknown'
revision = parts[3].replace('Rev_', '') if len(parts) > 3 else 'Unknown'
for instance in device_class.subkeys():
serial = instance.name()
last_write = instance.timestamp()
device_info = {
'vendor': vendor,
'product': product,
'revision': revision,
'serial': serial,
'last_connected': str(last_write),
}
# Get friendly name if available
try:
friendly = instance.value("FriendlyName").value()
device_info['friendly_name'] = friendly
except:
pass
# Get device parameters
try:
params = instance.subkey("Device Parameters")
try:
device_info['class_guid'] = params.value("ClassGUID").value()
except:
pass
except:
pass
devices.append(device_info)
print(f"Device: {vendor} {product}")
print(f" Serial: {serial}")
print(f" Last Connected: {last_write}")
print(f" Friendly Name: {device_info.get('friendly_name', 'N/A')}")
print()
# Save results
with open('/cases/case-2024-001/analysis/usb_devices.json', 'w') as f:
json.dump(devices, f, indent=2)
print(f"\nTotal USB storage devices found: {len(devices)}")
PYEOFStep 3: Extract Drive Letter Assignments and User Associations
# Parse MountedDevices from SYSTEM hive
python3 << 'PYEOF'
from Registry import Registry
import struct
reg = Registry.Registry("/cases/case-2024-001/usb/SYSTEM")
mounted = reg.open("MountedDevices")
print("=== MOUNTED DEVICES (Drive Letter Assignments) ===\n")
for value in mounted.values():
name = value.name()
data = value.value()
if name.startswith("\\DosDevices\\"):
drive_letter = name.replace("\\DosDevices\\", "")
if len(data) > 24:
# USB device - contains device path string
try:
device_path = data.decode('utf-16-le').strip('\x00')
if 'USBSTOR' in device_path or 'USB#' in device_path:
print(f" {drive_letter} -> {device_path}")
except:
pass
else:
# Fixed disk - contains disk signature + offset
disk_sig = struct.unpack('<I', data[0:4])[0]
offset = struct.unpack('<Q', data[4:12])[0]
print(f" {drive_letter} -> Disk Signature: 0x{disk_sig:08X}, Offset: {offset}")
PYEOF
# Parse user MountPoints2 (which user accessed which devices)
python3 << 'PYEOF'
from Registry import Registry
import os, glob
print("\n=== USER MOUNT POINTS (MountPoints2) ===\n")
for ntuser in glob.glob("/cases/case-2024-001/usb/NTUSER*.DAT"):
try:
reg = Registry.Registry(ntuser)
mp2 = reg.open("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\MountPoints2")
print(f"User hive: {os.path.basename(ntuser)}")
for key in mp2.subkeys():
guid = key.name()
last_write = key.timestamp()
if '{' in guid:
print(f" Volume: {guid} | Last accessed: {last_write}")
print()
except Exception as e:
print(f" Error parsing {ntuser}: {e}")
PYEOFStep 4: Extract First Connection Timestamps from SetupAPI
# Parse setupapi.dev.log for USB device first-install timestamps
python3 << 'PYEOF'
import re
print("=== SETUPAPI USB DEVICE INSTALLATIONS ===\n")
with open('/cases/case-2024-001/usb/setupapi.dev.log', 'r', errors='ignore') as f:
content = f.read()
# Find USB device installation sections
pattern = r'>>>\s+\[Device Install.*?\n.*?Section start (\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}).*?\n(.*?)<<<'
matches = re.findall(pattern, content, re.DOTALL)
usb_installs = []
for timestamp, section in matches:
if 'USBSTOR' in section or 'USB\\VID' in section:
# Extract device ID
dev_match = re.search(r'(USBSTOR\\[^\s]+|USB\\VID_\w+&PID_\w+[^\s]*)', section)
if dev_match:
device_id = dev_match.group(1)
usb_installs.append({
'first_install': timestamp,
'device_id': device_id
})
print(f" {timestamp} | {device_id}")
print(f"\nTotal USB installations found: {len(usb_installs)}")
PYEOF
# Parse Windows Event Logs for USB events
# Event IDs: 2003, 2010, 2100, 2102 (DriverFrameworks-UserMode)
# Event IDs: 6416 (Security - new external device recognized)
python3 << 'PYEOF'
import json
from evtx import PyEvtxParser
try:
parser = PyEvtxParser("/cases/case-2024-001/usb/System.evtx")
print("\n=== SYSTEM EVENT LOG USB EVENTS ===\n")
for record in parser.records_json():
data = json.loads(record['data'])
event_id = str(data['Event']['System']['EventID'])
# USB device connection events
if event_id in ('20001', '20003', '10000', '10100'):
timestamp = data['Event']['System']['TimeCreated']['#attributes']['SystemTime']
event_data = data['Event'].get('UserData', data['Event'].get('EventData', {}))
print(f" [{timestamp}] EventID {event_id}: {json.dumps(event_data, default=str)[:200]}")
except Exception as e:
print(f"Error: {e}")
PYEOFStep 5: Build USB Activity Timeline and Report
# Compile all USB evidence into a unified timeline
python3 << 'PYEOF'
import json, csv
timeline = []
# Load USBSTOR data
with open('/cases/case-2024-001/analysis/usb_devices.json') as f:
devices = json.load(f)
for device in devices:
timeline.append({
'timestamp': device['last_connected'],
'source': 'USBSTOR Registry',
'device': f"{device['vendor']} {device['product']}",
'serial': device['serial'],
'event': 'Last Connected',
'detail': device.get('friendly_name', '')
})
# Sort chronologically
timeline.sort(key=lambda x: x['timestamp'])
# Write timeline CSV
with open('/cases/case-2024-001/analysis/usb_timeline.csv', 'w', newline='') as f:
writer = csv.DictWriter(f, fieldnames=['timestamp', 'source', 'device', 'serial', 'event', 'detail'])
writer.writeheader()
writer.writerows(timeline)
print(f"USB Timeline: {len(timeline)} events written to usb_timeline.csv")
# Print summary
print("\n=== USB DEVICE SUMMARY ===")
for entry in timeline:
print(f" {entry['timestamp']} | {entry['device']} | {entry['serial'][:20]} | {entry['event']}")
PYEOFKey Concepts
| Concept | Description |
|---|---|
| USBSTOR | Registry key storing USB mass storage device identification and connection data |
| VID/PID | Vendor ID and Product ID uniquely identifying USB device manufacturer and model |
| Device serial number | Unique identifier for individual USB devices (some devices share serials) |
| MountedDevices | Registry key mapping volume GUIDs and drive letters to physical devices |
| MountPoints2 | Per-user registry key showing which volumes a user accessed |
| SetupAPI log | Windows driver installation log recording first-time device connections |
| DeviceContainers | Registry key in SOFTWARE hive with device metadata and timestamps |
| EMDMgmt | Registry key tracking ReadyBoost-compatible devices with serial numbers and timestamps |
Tools & Systems
| Tool | Purpose |
|---|---|
| USB Forensic Tracker | Specialized tool for USB device history extraction |
| USBDeview | NirSoft tool listing all USB devices connected to a system |
| RegRipper (usbstor plugin) | Automated USB artifact extraction from registry hives |
| Registry Explorer | Interactive registry analysis for USB-related keys |
| KAPE | Automated collection of USB-related artifacts |
| Plaso/log2timeline | Timeline creation including USB connection events |
| FTK Imager | Forensic imaging including removable media |
| Velociraptor | Endpoint agent with USB device history hunting artifacts |
Common Scenarios
Scenario 1: Data Exfiltration by Departing Employee Extract USBSTOR entries to identify all USB devices ever connected, correlate device serial numbers with MountPoints2 to confirm user access, cross-reference timestamps with file access logs and jump list recent files, check for large file copy patterns in USN journal.
Scenario 2: Unauthorized Device on Secure System Audit all USBSTOR entries against approved device list, identify unauthorized devices by VID/PID not matching corporate-approved hardware, determine when the unauthorized device was first and last connected, check if any data was transferred.
Scenario 3: Malware Delivery via USB Identify USB device connected just before malware execution (Prefetch timestamps), extract the device serial and vendor information, check if autorun was enabled for the device, look for executable launch from the removable drive letter in Prefetch and ShimCache.
Scenario 4: Tracking a Specific USB Drive Across Multiple Systems Search for the same device serial number in USBSTOR across all forensic images, build a map of which systems the drive was connected to and when, identify the chronological path of the device through the organization, correlate with network share access logs.
Output Format
USB Device History Analysis:
System: DESKTOP-ABC123 (Windows 10 Pro)
Total USB Storage Devices: 12
Analysis Sources: USBSTOR, MountedDevices, MountPoints2, SetupAPI, Event Logs
Device Inventory:
1. Kingston DataTraveler 3.0 (Serial: 0019E06B4521A2B0)
First Connected: 2024-01-10 09:15:32 (SetupAPI)
Last Connected: 2024-01-18 14:30:00 (USBSTOR)
Drive Letter: E:
User Access: suspect_user (MountPoints2)
2. WD My Passport (Serial: 575834314131363035)
First Connected: 2024-01-15 20:00:00
Last Connected: 2024-01-15 23:45:00
Drive Letter: F:
User Access: suspect_user
Suspicious Findings:
- Kingston drive connected 15 times during investigation period
- WD Passport connected only once, late evening (unusual hours)
- Unknown device (VID_1234&PID_5678) connected 2024-01-17, no matching approved device
Timeline: /cases/case-2024-001/analysis/usb_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: Analyzing USB Device Connection History
regipy (Python Registry Parser)
Open and Parse Registry Hive
from regipy.registry import RegistryHive
reg = RegistryHive("/path/to/SYSTEM")
key = reg.get_key("ControlSet001\\Enum\\USBSTOR")
for subkey in key.iter_subkeys():
print(subkey.name, subkey.header.last_modified)
for val in subkey.iter_values():
print(f" {val.name} = {val.value}")Key Registry Paths for USB Forensics
| Path | Hive | Description |
|---|---|---|
ControlSet00X\Enum\USBSTOR | SYSTEM | USB mass storage device identifiers |
MountedDevices | SYSTEM | Drive letter to device mapping |
ControlSet00X\Enum\USB | SYSTEM | All USB devices (not just storage) |
Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2 | NTUSER.DAT | Per-user volume access history |
Determine Active ControlSet
select_key = reg.get_key("Select")
current = select_key.get_value("Current")
controlset = f"ControlSet{current:03d}"python-evtx (Event Log Parsing)
from evtx import PyEvtxParser
import json
parser = PyEvtxParser("/path/to/System.evtx")
for record in parser.records_json():
data = json.loads(record["data"])
event_id = data["Event"]["System"]["EventID"]
if event_id in (20001, 20003): # USB plug events
print(record["timestamp"], event_id)SetupAPI Log Parsing
import re
with open("setupapi.dev.log", "r", errors="ignore") as f:
content = f.read()
pattern = r"Section start (\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2})"
for match in re.finditer(pattern, content):
print("First install:", match.group(1))USB Forensic Registry Keys
| Key | Data |
|---|---|
USBSTOR\Disk&Ven_X&Prod_Y&Rev_Z\Serial | Device class and serial |
FriendlyName value | Human-readable device name |
DeviceContainers (SOFTWARE) | Device metadata with timestamps |
EMDMgmt (SOFTWARE) | ReadyBoost device serial/volume info |
References
- regipy: https://pypi.org/project/regipy/
- python-evtx: https://pypi.org/project/evtx/
- SANS USB forensics: https://www.sans.org/blog/usb-device-tracking-artifacts/
#!/usr/bin/env python3
"""Agent for analyzing USB device connection history from Windows registry hives."""
import os
import json
import argparse
import csv
from regipy.registry import RegistryHive
def parse_usbstor(system_hive_path):
"""Parse USBSTOR registry key to enumerate USB storage devices."""
reg = RegistryHive(system_hive_path)
select_key = reg.get_key("Select")
current = select_key.get_value("Current")
controlset = f"ControlSet{current:03d}"
usbstor_path = f"{controlset}\\Enum\\USBSTOR"
devices = []
try:
usbstor_key = reg.get_key(usbstor_path)
except Exception:
return devices
for device_class in usbstor_key.iter_subkeys():
parts = device_class.name.split("&")
vendor = parts[1].replace("Ven_", "") if len(parts) > 1 else "Unknown"
product = parts[2].replace("Prod_", "") if len(parts) > 2 else "Unknown"
revision = parts[3].replace("Rev_", "") if len(parts) > 3 else "Unknown"
for instance in device_class.iter_subkeys():
serial = instance.name
device_info = {
"vendor": vendor,
"product": product,
"revision": revision,
"serial": serial,
"last_connected": str(instance.header.last_modified),
}
for val in instance.iter_values():
if val.name == "FriendlyName":
device_info["friendly_name"] = val.value
devices.append(device_info)
return devices
def parse_mounted_devices(system_hive_path):
"""Parse MountedDevices to map drive letters to USB devices."""
reg = RegistryHive(system_hive_path)
mounted_key = reg.get_key("MountedDevices")
mappings = []
for val in mounted_key.iter_values():
if val.name.startswith("\\DosDevices\\"):
drive_letter = val.name.replace("\\DosDevices\\", "")
data = val.value
if isinstance(data, bytes) and len(data) > 24:
try:
device_path = data.decode("utf-16-le").strip("\x00")
if "USBSTOR" in device_path or "USB#" in device_path:
mappings.append({
"drive_letter": drive_letter,
"device_path": device_path,
})
except (UnicodeDecodeError, ValueError):
pass
return mappings
def parse_mountpoints2(ntuser_path):
"""Parse MountPoints2 from NTUSER.DAT to find user-accessed volumes."""
reg = RegistryHive(ntuser_path)
mp2_path = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\MountPoints2"
mount_points = []
try:
mp2_key = reg.get_key(mp2_path)
except Exception:
return mount_points
for subkey in mp2_key.iter_subkeys():
if "{" in subkey.name:
mount_points.append({
"volume_guid": subkey.name,
"last_accessed": str(subkey.header.last_modified),
})
return mount_points
def parse_setupapi_log(log_path):
"""Parse setupapi.dev.log for USB first-install timestamps."""
import re
installs = []
with open(log_path, "r", errors="ignore") as f:
content = f.read()
pattern = r">>>\s+\[Device Install.*?\n.*?Section start (\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}).*?\n(.*?)<<<"
for match in re.finditer(pattern, content, re.DOTALL):
timestamp, section = match.group(1), match.group(2)
dev_match = re.search(r"(USBSTOR\\[^\s]+|USB\\VID_\w+&PID_\w+[^\s]*)", section)
if dev_match:
installs.append({
"first_install": timestamp,
"device_id": dev_match.group(1),
})
return installs
def build_timeline(devices, mappings, mount_points):
"""Build a unified USB activity timeline."""
timeline = []
for dev in devices:
timeline.append({
"timestamp": dev["last_connected"],
"source": "USBSTOR",
"device": f"{dev['vendor']} {dev['product']}",
"serial": dev["serial"],
"event": "Last Connected",
"detail": dev.get("friendly_name", ""),
})
for mp in mount_points:
timeline.append({
"timestamp": mp["last_accessed"],
"source": "MountPoints2",
"device": mp["volume_guid"],
"serial": "",
"event": "Volume Accessed",
"detail": "",
})
timeline.sort(key=lambda x: x["timestamp"])
return timeline
def export_timeline_csv(timeline, output_path):
"""Export timeline to CSV."""
if not timeline:
return
with open(output_path, "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=timeline[0].keys())
writer.writeheader()
writer.writerows(timeline)
def main():
parser = argparse.ArgumentParser(description="USB Device Connection History Agent")
parser.add_argument("--system-hive", required=True, help="Path to SYSTEM registry hive")
parser.add_argument("--ntuser", help="Path to NTUSER.DAT hive")
parser.add_argument("--setupapi-log", help="Path to setupapi.dev.log")
parser.add_argument("--output-dir", default="./usb_analysis")
parser.add_argument("--case-id", default="CASE-001")
args = parser.parse_args()
os.makedirs(args.output_dir, exist_ok=True)
devices = parse_usbstor(args.system_hive)
print(f"[+] USBSTOR devices: {len(devices)}")
for d in devices:
print(f" {d['vendor']} {d['product']} | Serial: {d['serial']}")
mappings = parse_mounted_devices(args.system_hive)
print(f"[+] USB drive mappings: {len(mappings)}")
mount_points = []
if args.ntuser:
mount_points = parse_mountpoints2(args.ntuser)
print(f"[+] MountPoints2 entries: {len(mount_points)}")
if args.setupapi_log:
installs = parse_setupapi_log(args.setupapi_log)
print(f"[+] SetupAPI installations: {len(installs)}")
timeline = build_timeline(devices, mappings, mount_points)
csv_path = os.path.join(args.output_dir, "usb_timeline.csv")
export_timeline_csv(timeline, csv_path)
print(f"[+] Timeline exported to {csv_path} ({len(timeline)} events)")
report = {
"case_id": args.case_id,
"total_devices": len(devices),
"devices": devices,
"drive_mappings": mappings,
"timeline_events": len(timeline),
}
print(json.dumps(report, indent=2, default=str))
if __name__ == "__main__":
main()
Related skills
FAQ
Is Analyzing Usb Device Connection History safe to install?
skills.sh reports 2 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.