<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: analyzing-usb-artifacts
description: >-
  USB device forensic analysis including Windows USBSTOR registry enumeration,
  setupapi.dev.log parsing, drive letter mapping via MountedDevices, first/last
  connection timestamps, device serial number extraction, and Linux USB artifact
  analysis from kernel logs and udev rules.
domain: cybersecurity
subdomain: digital-forensics
tags:
  - usb-forensics
  - usbstor
  - setupapi
  - mounted-devices
  - device-tracking
  - data-exfiltration
version: "1.0"
author: defconxt
license: AGPL-3.0
compatibility: Designed for Claude Code, GitHub Copilot, OpenAI Codex, Cursor, Gemini CLI, and any agentskills.io-compatible agent.
metadata:
  mitre-attack: ["T1052.001", "T1091", "T1200"]
  nist-csf: ["RS.AN-3"]
  frameworks: ["NIST SP 800-86"]
---

# Analyzing USB Artifacts

## Overview

USB device artifacts provide evidence of external storage connections, which
is critical for data exfiltration, malware delivery, and insider threat
investigations. Windows preserves USB connection history across multiple
artifact sources including the Registry, setupapi logs, event logs, and
link files. Correlating these sources establishes first connect, last connect,
and last removal timestamps.

## Prerequisites

- RegRipper or `python-registry`
- Sleuth Kit for image-based extraction
- USBDeview (NirSoft) for live analysis
- Python 3.10+

```bash
pip install python-registry
```

## Key Concepts

### Windows USB Artifact Sources

| Source | Location | Evidence |
|--------|----------|----------|
| USBSTOR | `SYSTEM\CurrentControlSet\Enum\USBSTOR` | Device class, serial, first connect |
| USB | `SYSTEM\CurrentControlSet\Enum\USB` | VID/PID (Vendor/Product ID) |
| MountedDevices | `SYSTEM\MountedDevices` | Drive letter assignment |
| setupapi.dev.log | `C:\Windows\INF\setupapi.dev.log` | First install timestamp |
| Event Log | `Microsoft-Windows-DriverFrameworks-UserMode/Operational` | Connect/disconnect events |
| NTUSER.DAT MountPoints2 | `NTUSER.DAT\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2` | User who accessed device |
| Link files | `C:\Users\<user>\AppData\Roaming\Microsoft\Windows\Recent\` | Files opened from USB |

### USB Device Identification

```
USBSTOR key structure:
  USBSTOR\Disk&Ven_<vendor>&Prod_<product>&Rev_<revision>\<serial_number>

USB key structure:
  USB\VID_<vendor_id>&PID_<product_id>\<serial_number>

Example:
  USBSTOR\Disk&Ven_SanDisk&Prod_Ultra&Rev_1.00\4C530012345678
  USB\VID_0781&PID_5581\4C530012345678
```

### Timeline Correlation

```
First connection:  setupapi.dev.log "Device Install" timestamp
First user access: NTUSER.DAT MountPoints2 key last-write
Last connection:   SYSTEM\USBSTOR\<device> key last-write
Last removal:      Event Log EID 2100/2101 (DriverFrameworks)
```

## Workflow

### Step 1: Extract USBSTOR from Registry

```python
from Registry import Registry

def get_usb_devices(system_hive: str) -> list[dict]:
    reg = Registry.Registry(system_hive)
    devices = []
    for cs in ["ControlSet001", "ControlSet002"]:
        try:
            usbstor = reg.open(f"{cs}\\Enum\\USBSTOR")
        except Exception:
            continue
        for dev_class in usbstor.subkeys():
            vendor, product, rev = "", "", ""
            parts = dev_class.name().split("&")
            for p in parts:
                if p.startswith("Ven_"): vendor = p[4:]
                elif p.startswith("Prod_"): product = p[5:]
                elif p.startswith("Rev_"): rev = p[4:]
            for instance in dev_class.subkeys():
                friendly = ""
                for v in instance.values():
                    if v.name() == "FriendlyName":
                        friendly = str(v.value())
                devices.append({
                    "vendor": vendor, "product": product,
                    "revision": rev, "serial": instance.name(),
                    "friendly_name": friendly,
                    "last_write": instance.timestamp().isoformat(),
                })
    return devices
```

### Step 2: Parse setupapi.dev.log

```python
import re
from datetime import datetime

def parse_setupapi(log_path: str) -> list[dict]:
    installs = []
    with open(log_path, encoding="utf-8", errors="replace") as f:
        lines = f.readlines()
    for i, line in enumerate(lines):
        if "Device Install" in line and "USBSTOR" in line:
            timestamp = ""
            for j in range(max(0, i - 5), min(len(lines), i + 5)):
                match = re.search(r">>>  Section start (\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2})", lines[j])
                if match:
                    timestamp = match.group(1)
                    break
            device_match = re.search(r"USBSTOR\\([^\s]+)", line)
            installs.append({
                "device": device_match.group(1) if device_match else line.strip(),
                "first_install": timestamp,
            })
    return installs
```

### Step 3: Map Drive Letters

```python
def get_drive_mappings(system_hive: str) -> list[dict]:
    reg = Registry.Registry(system_hive)
    mappings = []
    try:
        mounted = reg.open("MountedDevices")
        for val in mounted.values():
            if val.name().startswith("\\DosDevices\\"):
                drive_letter = val.name().replace("\\DosDevices\\", "")
                raw = val.value()
                if isinstance(raw, bytes) and b"USBSTOR" in raw:
                    device_id = raw.decode("utf-16-le", errors="replace").strip("\x00")
                    mappings.append({"drive": drive_letter, "device": device_id})
    except Exception:
        pass
    return mappings
```

### Step 4: Linux USB Artifacts

```bash
# Kernel log USB events
dmesg | grep -i "usb"
journalctl -k | grep -i "usb mass storage"

# udev database
udevadm info --query=all --name=/dev/sdb

# USB device history (if logged)
grep -i "usb" /var/log/syslog /var/log/kern.log 2>/dev/null

# lsusb for current devices
lsusb -v 2>/dev/null | grep -E "idVendor|idProduct|iSerial|iManufacturer|iProduct"
```

## Detection

```yaml
title: Usb Artifacts Detection
id: 1e4cd756-57a0-4ce0-835a-4147c148923f
status: experimental
description: Detects suspicious activity related to analyzing usb artifacts techniques in digital forensics context
logsource:
  category: process_creation
  product: windows
detection:
  selection:
    CommandLine: "*analyzing*usb*"
  condition: selection
level: medium
tags:
  - attack.t1052.001
  - attack.t1091
  - attack.t1200
  - attack.collection
falsepositives:
  - Forensic investigation tools used by authorized incident response team
```

## Verification

- [ ] USBSTOR registry entries enumerated with serial numbers
- [ ] VID/PID mapped to vendor/product via USB ID database
- [ ] setupapi.dev.log parsed for first-install timestamps
- [ ] MountedDevices correlated for drive letter assignment
- [ ] MountPoints2 checked per user for access evidence
- [ ] Timeline constructed: first connect → last connect → last removal
- [ ] Evidence supports or refutes data exfiltration hypothesis

## References

- [SANS USB Device Tracking](https://www.sans.org/blog/usb-device-tracking-artifacts/)
- [USB ID Database](https://www.the-sz.com/products/usbid/)
- [MITRE T1052.001 — Exfiltration over USB](https://attack.mitre.org/techniques/T1052/001/)
- [NirSoft USBDeview](https://www.nirsoft.net/utils/usb_devices_view.html)
