[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6ERB5APTAJHNK6WJS6W844W":3,"skill-same:01M6ERB5APTAJHNK6WJS6W844W":87},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":48,"commitSha":49,"skillDirectory":50,"forksCount":51,"repositoryHtmlUrl":52,"repositoryHomepageUrl":6,"ownerHtmlUrl":53,"ownerBlogUrl":6,"ownerDescription":54,"updatedAt":55,"install":56,"resources":69},"01M6ERB5APTAJHNK6WJS6W844W","analyzing-usb-device-connection-history",null,"Investigate USB device connection history from Windows registry, event logs, and setupapi logs to track removable media usage and potential data exfiltration.","luokai0\u002Fai-agent-skills-by-luo-kai","luokai0","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F266954973?v=4","01M6E16VNT42JB8B3X3254QWJ7","luo kai","01M6E16VTFVP6S5XJF1V1MPV90",14,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F21-external-registries\u002F08-pinkpixel-collection\u002Fanalyzing-usb-device-connection-history\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"device","history","analyzing","analyzing usb device connection history","removable-media","event","investigate","Media","analysis","device-history","registry-analysis","cybersecurity","usb-forensics","data","data-exfiltration","exfiltration","forensics","logs","registry","windows","2026-11-10 10:12:30",false,"---\nname: analyzing-usb-device-connection-history\ndescription: Investigate USB device connection history from Windows registry, event logs, and setupapi logs to track removable media usage and potential data exfiltration.\ndomain: cybersecurity\nsubdomain: digital-forensics\ntags: [forensics, usb-forensics, removable-media, registry-analysis, data-exfiltration, device-history]\nversion: \"1.0\"\nauthor: mahipal\nlicense: Apache-2.0\n---\n\n# Analyzing USB Device Connection History\n\n## When to Use\n- When investigating potential data exfiltration via removable storage devices\n- During insider threat investigations to track USB device usage\n- For compliance audits verifying removable media policy enforcement\n- When correlating USB connections with file access and copy events\n- For establishing a timeline of device connections during an incident\n\n## Prerequisites\n- Forensic image or extracted registry hives and event logs\n- Access to SYSTEM, SOFTWARE, and NTUSER.DAT registry hives\n- SetupAPI logs (setupapi.dev.log)\n- Windows Event Logs (System, Security, DriverFrameworks-UserMode)\n- USBDeview, USB Forensic Tracker, or RegRipper\n- Understanding of USB device identification (VID, PID, serial number)\n\n## Workflow\n\n### Step 1: Extract USB-Related Artifacts\n\n```bash\n# Mount forensic image and copy relevant artifacts\nmount -o ro,loop,offset=$((2048*512)) \u002Fcases\u002Fcase-2024-001\u002Fimages\u002Fevidence.dd \u002Fmnt\u002Fevidence\n\nmkdir -p \u002Fcases\u002Fcase-2024-001\u002Fusb\u002F\n\n# Registry hives\ncp \u002Fmnt\u002Fevidence\u002FWindows\u002FSystem32\u002Fconfig\u002FSYSTEM \u002Fcases\u002Fcase-2024-001\u002Fusb\u002F\ncp \u002Fmnt\u002Fevidence\u002FWindows\u002FSystem32\u002Fconfig\u002FSOFTWARE \u002Fcases\u002Fcase-2024-001\u002Fusb\u002F\ncp \u002Fmnt\u002Fevidence\u002FUsers\u002F*\u002FNTUSER.DAT \u002Fcases\u002Fcase-2024-001\u002Fusb\u002F\n\n# SetupAPI logs (first connection timestamps)\ncp \u002Fmnt\u002Fevidence\u002FWindows\u002FINF\u002Fsetupapi.dev.log \u002Fcases\u002Fcase-2024-001\u002Fusb\u002F\n\n# Event logs\ncp \u002Fmnt\u002Fevidence\u002FWindows\u002FSystem32\u002Fwinevt\u002FLogs\u002FSystem.evtx \u002Fcases\u002Fcase-2024-001\u002Fusb\u002F\ncp \"\u002Fmnt\u002Fevidence\u002FWindows\u002FSystem32\u002Fwinevt\u002FLogs\u002FMicrosoft-Windows-DriverFrameworks-UserMode%4Operational.evtx\" \\\n   \u002Fcases\u002Fcase-2024-001\u002Fusb\u002F 2>\u002Fdev\u002Fnull\ncp \"\u002Fmnt\u002Fevidence\u002FWindows\u002FSystem32\u002Fwinevt\u002FLogs\u002FMicrosoft-Windows-Partition%4Diagnostic.evtx\" \\\n   \u002Fcases\u002Fcase-2024-001\u002Fusb\u002F 2>\u002Fdev\u002Fnull\n```\n\n### Step 2: Parse USBSTOR Registry Key\n\n```bash\n# Extract USBSTOR entries from SYSTEM hive\npython3 \u003C\u003C 'PYEOF'\nfrom Registry import Registry\nimport json\n\nreg = Registry.Registry(\"\u002Fcases\u002Fcase-2024-001\u002Fusb\u002FSYSTEM\")\n\n# Find current ControlSet\nselect = reg.open(\"Select\")\ncurrent = select.value(\"Current\").value()\ncontrolset = f\"ControlSet{current:03d}\"\n\n# Parse USBSTOR\nusbstor_path = f\"{controlset}\\\\Enum\\\\USBSTOR\"\nusbstor = reg.open(usbstor_path)\n\ndevices = []\nprint(\"=== USBSTOR DEVICES ===\\n\")\n\nfor device_class in usbstor.subkeys():\n    # Format: Disk&Ven_VENDOR&Prod_PRODUCT&Rev_REVISION\n    class_name = device_class.name()\n    parts = class_name.split('&')\n    vendor = parts[1].replace('Ven_', '') if len(parts) > 1 else 'Unknown'\n    product = parts[2].replace('Prod_', '') if len(parts) > 2 else 'Unknown'\n    revision = parts[3].replace('Rev_', '') if len(parts) > 3 else 'Unknown'\n\n    for instance in device_class.subkeys():\n        serial = instance.name()\n        last_write = instance.timestamp()\n\n        device_info = {\n            'vendor': vendor,\n            'product': product,\n            'revision': revision,\n            'serial': serial,\n            'last_connected': str(last_write),\n        }\n\n        # Get friendly name if available\n        try:\n            friendly = instance.value(\"FriendlyName\").value()\n            device_info['friendly_name'] = friendly\n        except:\n            pass\n\n        # Get device parameters\n        try:\n            params = instance.subkey(\"Device Parameters\")\n            try:\n                device_info['class_guid'] = params.value(\"ClassGUID\").value()\n            except:\n                pass\n        except:\n            pass\n\n        devices.append(device_info)\n        print(f\"Device: {vendor} {product}\")\n        print(f\"  Serial: {serial}\")\n        print(f\"  Last Connected: {last_write}\")\n        print(f\"  Friendly Name: {device_info.get('friendly_name', 'N\u002FA')}\")\n        print()\n\n# Save results\nwith open('\u002Fcases\u002Fcase-2024-001\u002Fanalysis\u002Fusb_devices.json', 'w') as f:\n    json.dump(devices, f, indent=2)\n\nprint(f\"\\nTotal USB storage devices found: {len(devices)}\")\nPYEOF\n```\n\n### Step 3: Extract Drive Letter Assignments and User Associations\n\n```bash\n# Parse MountedDevices from SYSTEM hive\npython3 \u003C\u003C 'PYEOF'\nfrom Registry import Registry\nimport struct\n\nreg = Registry.Registry(\"\u002Fcases\u002Fcase-2024-001\u002Fusb\u002FSYSTEM\")\n\nmounted = reg.open(\"MountedDevices\")\n\nprint(\"=== MOUNTED DEVICES (Drive Letter Assignments) ===\\n\")\nfor value in mounted.values():\n    name = value.name()\n    data = value.value()\n\n    if name.startswith(\"\\\\DosDevices\\\\\"):\n        drive_letter = name.replace(\"\\\\DosDevices\\\\\", \"\")\n        if len(data) > 24:\n            # USB device - contains device path string\n            try:\n                device_path = data.decode('utf-16-le').strip('\\x00')\n                if 'USBSTOR' in device_path or 'USB#' in device_path:\n                    print(f\"  {drive_letter} -> {device_path}\")\n            except:\n                pass\n        else:\n            # Fixed disk - contains disk signature + offset\n            disk_sig = struct.unpack('\u003CI', data[0:4])[0]\n            offset = struct.unpack('\u003CQ', data[4:12])[0]\n            print(f\"  {drive_letter} -> Disk Signature: 0x{disk_sig:08X}, Offset: {offset}\")\nPYEOF\n\n# Parse user MountPoints2 (which user accessed which devices)\npython3 \u003C\u003C 'PYEOF'\nfrom Registry import Registry\nimport os, glob\n\nprint(\"\\n=== USER MOUNT POINTS (MountPoints2) ===\\n\")\n\nfor ntuser in glob.glob(\"\u002Fcases\u002Fcase-2024-001\u002Fusb\u002FNTUSER*.DAT\"):\n    try:\n        reg = Registry.Registry(ntuser)\n        mp2 = reg.open(\"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\MountPoints2\")\n\n        print(f\"User hive: {os.path.basename(ntuser)}\")\n        for key in mp2.subkeys():\n            guid = key.name()\n            last_write = key.timestamp()\n            if '{' in guid:\n                print(f\"  Volume: {guid} | Last accessed: {last_write}\")\n        print()\n    except Exception as e:\n        print(f\"  Error parsing {ntuser}: {e}\")\nPYEOF\n```\n\n### Step 4: Extract First Connection Timestamps from SetupAPI\n\n```bash\n# Parse setupapi.dev.log for USB device first-install timestamps\npython3 \u003C\u003C 'PYEOF'\nimport re\n\nprint(\"=== SETUPAPI USB DEVICE INSTALLATIONS ===\\n\")\n\nwith open('\u002Fcases\u002Fcase-2024-001\u002Fusb\u002Fsetupapi.dev.log', 'r', errors='ignore') as f:\n    content = f.read()\n\n# Find USB device installation sections\npattern = r'>>>\\s+\\[Device Install.*?\\n.*?Section start (\\d{4}\u002F\\d{2}\u002F\\d{2} \\d{2}:\\d{2}:\\d{2}).*?\\n(.*?)\u003C\u003C\u003C'\nmatches = re.findall(pattern, content, re.DOTALL)\n\nusb_installs = []\nfor timestamp, section in matches:\n    if 'USBSTOR' in section or 'USB\\\\VID' in section:\n        # Extract device ID\n        dev_match = re.search(r'(USBSTOR\\\\[^\\s]+|USB\\\\VID_\\w+&PID_\\w+[^\\s]*)', section)\n        if dev_match:\n            device_id = dev_match.group(1)\n            usb_installs.append({\n                'first_install': timestamp,\n                'device_id': device_id\n            })\n            print(f\"  {timestamp} | {device_id}\")\n\nprint(f\"\\nTotal USB installations found: {len(usb_installs)}\")\nPYEOF\n\n# Parse Windows Event Logs for USB events\n# Event IDs: 2003, 2010, 2100, 2102 (DriverFrameworks-UserMode)\n# Event IDs: 6416 (Security - new external device recognized)\npython3 \u003C\u003C 'PYEOF'\nimport json\nfrom evtx import PyEvtxParser\n\ntry:\n    parser = PyEvtxParser(\"\u002Fcases\u002Fcase-2024-001\u002Fusb\u002FSystem.evtx\")\n\n    print(\"\\n=== SYSTEM EVENT LOG USB EVENTS ===\\n\")\n    for record in parser.records_json():\n        data = json.loads(record['data'])\n        event_id = str(data['Event']['System']['EventID'])\n\n        # USB device connection events\n        if event_id in ('20001', '20003', '10000', '10100'):\n            timestamp = data['Event']['System']['TimeCreated']['#attributes']['SystemTime']\n            event_data = data['Event'].get('UserData', data['Event'].get('EventData', {}))\n            print(f\"  [{timestamp}] EventID {event_id}: {json.dumps(event_data, default=str)[:200]}\")\nexcept Exception as e:\n    print(f\"Error: {e}\")\nPYEOF\n```\n\n### Step 5: Build USB Activity Timeline and Report\n\n```bash\n# Compile all USB evidence into a unified timeline\npython3 \u003C\u003C 'PYEOF'\nimport json, csv\n\ntimeline = []\n\n# Load USBSTOR data\nwith open('\u002Fcases\u002Fcase-2024-001\u002Fanalysis\u002Fusb_devices.json') as f:\n    devices = json.load(f)\n\nfor device in devices:\n    timeline.append({\n        'timestamp': device['last_connected'],\n        'source': 'USBSTOR Registry',\n        'device': f\"{device['vendor']} {device['product']}\",\n        'serial': device['serial'],\n        'event': 'Last Connected',\n        'detail': device.get('friendly_name', '')\n    })\n\n# Sort chronologically\ntimeline.sort(key=lambda x: x['timestamp'])\n\n# Write timeline CSV\nwith open('\u002Fcases\u002Fcase-2024-001\u002Fanalysis\u002Fusb_timeline.csv', 'w', newline='') as f:\n    writer = csv.DictWriter(f, fieldnames=['timestamp', 'source', 'device', 'serial', 'event', 'detail'])\n    writer.writeheader()\n    writer.writerows(timeline)\n\nprint(f\"USB Timeline: {len(timeline)} events written to usb_timeline.csv\")\n\n# Print summary\nprint(\"\\n=== USB DEVICE SUMMARY ===\")\nfor entry in timeline:\n    print(f\"  {entry['timestamp']} | {entry['device']} | {entry['serial'][:20]} | {entry['event']}\")\nPYEOF\n```\n\n## Key Concepts\n\n| Concept | Description |\n|---------|-------------|\n| USBSTOR | Registry key storing USB mass storage device identification and connection data |\n| VID\u002FPID | Vendor ID and Product ID uniquely identifying USB device manufacturer and model |\n| Device serial number | Unique identifier for individual USB devices (some devices share serials) |\n| MountedDevices | Registry key mapping volume GUIDs and drive letters to physical devices |\n| MountPoints2 | Per-user registry key showing which volumes a user accessed |\n| SetupAPI log | Windows driver installation log recording first-time device connections |\n| DeviceContainers | Registry key in SOFTWARE hive with device metadata and timestamps |\n| EMDMgmt | Registry key tracking ReadyBoost-compatible devices with serial numbers and timestamps |\n\n## Tools & Systems\n\n| Tool | Purpose |\n|------|---------|\n| USB Forensic Tracker | Specialized tool for USB device history extraction |\n| USBDeview | NirSoft tool listing all USB devices connected to a system |\n| RegRipper (usbstor plugin) | Automated USB artifact extraction from registry hives |\n| Registry Explorer | Interactive registry analysis for USB-related keys |\n| KAPE | Automated collection of USB-related artifacts |\n| Plaso\u002Flog2timeline | Timeline creation including USB connection events |\n| FTK Imager | Forensic imaging including removable media |\n| Velociraptor | Endpoint agent with USB device history hunting artifacts |\n\n## Common Scenarios\n\n**Scenario 1: Data Exfiltration by Departing Employee**\nExtract 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.\n\n**Scenario 2: Unauthorized Device on Secure System**\nAudit all USBSTOR entries against approved device list, identify unauthorized devices by VID\u002FPID not matching corporate-approved hardware, determine when the unauthorized device was first and last connected, check if any data was transferred.\n\n**Scenario 3: Malware Delivery via USB**\nIdentify 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.\n\n**Scenario 4: Tracking a Specific USB Drive Across Multiple Systems**\nSearch 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.\n\n## Output Format\n\n```\nUSB Device History Analysis:\n  System: DESKTOP-ABC123 (Windows 10 Pro)\n  Total USB Storage Devices: 12\n  Analysis Sources: USBSTOR, MountedDevices, MountPoints2, SetupAPI, Event Logs\n\n  Device Inventory:\n    1. Kingston DataTraveler 3.0 (Serial: 0019E06B4521A2B0)\n       First Connected:  2024-01-10 09:15:32 (SetupAPI)\n       Last Connected:   2024-01-18 14:30:00 (USBSTOR)\n       Drive Letter:     E:\n       User Access:      suspect_user (MountPoints2)\n\n    2. WD My Passport (Serial: 575834314131363035)\n       First Connected:  2024-01-15 20:00:00\n       Last Connected:   2024-01-15 23:45:00\n       Drive Letter:     F:\n       User Access:      suspect_user\n\n  Suspicious Findings:\n    - Kingston drive connected 15 times during investigation period\n    - WD Passport connected only once, late evening (unusual hours)\n    - Unknown device (VID_1234&PID_5678) connected 2024-01-17, no matching approved device\n\n  Timeline: \u002Fcases\u002Fcase-2024-001\u002Fanalysis\u002Fusb_timeline.csv\n```\n","# Analyzing USB Device Connection History\n\n## When to Use\n- When investigating potential data exfiltration via removable storage devices\n- During insider threat investigations to track USB device usage\n- For compliance audits verifying removable media policy enforcement\n- When correlating USB connections with file access and copy events\n- For establishing a timeline of device connections during an incident\n\n## Prerequisites\n- Forensic image or extracted registry hives and event logs\n- Access to SYSTEM, SOFTWARE, and NTUSER.DAT registry hives\n- SetupAPI logs (setupapi.dev.log)\n- Windows Event Logs (System, Security, DriverFrameworks-UserMode)\n- USBDeview, USB Forensic Tracker, or RegRipper\n- Understanding of USB device identification (VID, PID, serial number)\n\n## Workflow\n\n### Step 1: Extract USB-Related Artifacts\n\n```bash\n# Mount forensic image and copy relevant artifacts\nmount -o ro,loop,offset=$((2048*512)) \u002Fcases\u002Fcase-2024-001\u002Fimages\u002Fevidence.dd \u002Fmnt\u002Fevidence\n\nmkdir -p \u002Fcases\u002Fcase-2024-001\u002Fusb\u002F\n\n# Registry hives\ncp \u002Fmnt\u002Fevidence\u002FWindows\u002FSystem32\u002Fconfig\u002FSYSTEM \u002Fcases\u002Fcase-2024-001\u002Fusb\u002F\ncp \u002Fmnt\u002Fevidence\u002FWindows\u002FSystem32\u002Fconfig\u002FSOFTWARE \u002Fcases\u002Fcase-2024-001\u002Fusb\u002F\ncp \u002Fmnt\u002Fevidence\u002FUsers\u002F*\u002FNTUSER.DAT \u002Fcases\u002Fcase-2024-001\u002Fusb\u002F\n\n# SetupAPI logs (first connection timestamps)\ncp \u002Fmnt\u002Fevidence\u002FWindows\u002FINF\u002Fsetupapi.dev.log \u002Fcases\u002Fcase-2024-001\u002Fusb\u002F\n\n# Event logs\ncp \u002Fmnt\u002Fevidence\u002FWindows\u002FSystem32\u002Fwinevt\u002FLogs\u002FSystem.evtx \u002Fcases\u002Fcase-2024-001\u002Fusb\u002F\ncp \"\u002Fmnt\u002Fevidence\u002FWindows\u002FSystem32\u002Fwinevt\u002FLogs\u002FMicrosoft-Windows-DriverFrameworks-UserMode%4Operational.evtx\" \\\n   \u002Fcases\u002Fcase-2024-001\u002Fusb\u002F 2>\u002Fdev\u002Fnull\ncp \"\u002Fmnt\u002Fevidence\u002FWindows\u002FSystem32\u002Fwinevt\u002FLogs\u002FMicrosoft-Windows-Partition%4Diagnostic.evtx\" \\\n   \u002Fcases\u002Fcase-2024-001\u002Fusb\u002F 2>\u002Fdev\u002Fnull\n```\n\n### Step 2: Parse USBSTOR Registry Key\n\n```bash\n# Extract USBSTOR entries from SYSTEM hive\npython3 \u003C\u003C 'PYEOF'\nfrom Registry import Registry\nimport json\n\nreg = Registry.Registry(\"\u002Fcases\u002Fcase-2024-001\u002Fusb\u002FSYSTEM\")\n\n# Find current ControlSet\nselect = reg.open(\"Select\")\ncurrent = select.value(\"Current\").value()\ncontrolset = f\"ControlSet{current:03d}\"\n\n# Parse USBSTOR\nusbstor_path = f\"{controlset}\\\\Enum\\\\USBSTOR\"\nusbstor = reg.open(usbstor_path)\n\ndevices = []\nprint(\"=== USBSTOR DEVICES ===\\n\")\n\nfor device_class in usbstor.subkeys():\n    # Format: Disk&Ven_VENDOR&Prod_PRODUCT&Rev_REVISION\n    class_name = device_class.name()\n    parts = class_name.split('&')\n    vendor = parts[1].replace('Ven_', '') if len(parts) > 1 else 'Unknown'\n    product = parts[2].replace('Prod_', '') if len(parts) > 2 else 'Unknown'\n    revision = parts[3].replace('Rev_', '') if len(parts) > 3 else 'Unknown'\n\n    for instance in device_class.subkeys():\n        serial = instance.name()\n        last_write = instance.timestamp()\n\n        device_info = {\n            'vendor': vendor,\n            'product': product,\n            'revision': revision,\n            'serial': serial,\n            'last_connected': str(last_write),\n        }\n\n        # Get friendly name if available\n        try:\n            friendly = instance.value(\"FriendlyName\").value()\n            device_info['friendly_name'] = friendly\n        except:\n            pass\n\n        # Get device parameters\n        try:\n            params = instance.subkey(\"Device Parameters\")\n            try:\n                device_info['class_guid'] = params.value(\"ClassGUID\").value()\n            except:\n                pass\n        except:\n            pass\n\n        devices.append(device_info)\n        print(f\"Device: {vendor} {product}\")\n        print(f\"  Serial: {serial}\")\n        print(f\"  Last Connected: {last_write}\")\n        print(f\"  Friendly Name: {device_info.get('friendly_name', 'N\u002FA')}\")\n        print()\n\n# Save results\nwith open('\u002Fcases\u002Fcase-2024-001\u002Fanalysis\u002Fusb_devices.json', 'w') as f:\n    json.dump(devices, f, indent=2)\n\nprint(f\"\\nTotal USB storage devices found: {len(devices)}\")\nPYEOF\n```\n\n### Step 3: Extract Drive Letter Assignments and User Associations\n\n```bash\n# Parse MountedDevices from SYSTEM hive\npython3 \u003C\u003C 'PYEOF'\nfrom Registry import Registry\nimport struct\n\nreg = Registry.Registry(\"\u002Fcases\u002Fcase-2024-001\u002Fusb\u002FSYSTEM\")\n\nmounted = reg.open(\"MountedDevices\")\n\nprint(\"=== MOUNTED DEVICES (Drive Letter Assignments) ===\\n\")\nfor value in mounted.values():\n    name = value.name()\n    data = value.value()\n\n    if name.startswith(\"\\\\DosDevices\\\\\"):\n        drive_letter = name.replace(\"\\\\DosDevices\\\\\", \"\")\n        if len(data) > 24:\n            # USB device - contains device path string\n            try:\n                device_path = data.decode('utf-16-le').strip('\\x00')\n                if 'USBSTOR' in device_path or 'USB#' in device_path:\n                    print(f\"  {drive_letter} -> {device_path}\")\n            except:\n                pass\n        else:\n            # Fixed disk - contains disk signature + offset\n            disk_sig = struct.unpack('\u003CI', data[0:4])[0]\n            offset = struct.unpack('\u003CQ', data[4:12])[0]\n            print(f\"  {drive_letter} -> Disk Signature: 0x{disk_sig:08X}, Offset: {offset}\")\nPYEOF\n\n# Parse user MountPoints2 (which user accessed which devices)\npython3 \u003C\u003C 'PYEOF'\nfrom Registry import Registry\nimport os, glob\n\nprint(\"\\n=== USER MOUNT POINTS (MountPoints2) ===\\n\")\n\nfor ntuser in glob.glob(\"\u002Fcases\u002Fcase-2024-001\u002Fusb\u002FNTUSER*.DAT\"):\n    try:\n        reg = Registry.Registry(ntuser)\n        mp2 = reg.open(\"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Explorer\\\\MountPoints2\")\n\n        print(f\"User hive: {os.path.basename(ntuser)}\")\n        for key in mp2.subkeys():\n            guid = key.name()\n            last_write = key.timestamp()\n            if '{' in guid:\n                print(f\"  Volume: {guid} | Last accessed: {last_write}\")\n        print()\n    except Exception as e:\n        print(f\"  Error parsing {ntuser}: {e}\")\nPYEOF\n```\n\n### Step 4: Extract First Connection Timestamps from SetupAPI\n\n```bash\n# Parse setupapi.dev.log for USB device first-install timestamps\npython3 \u003C\u003C 'PYEOF'\nimport re\n\nprint(\"=== SETUPAPI USB DEVICE INSTALLATIONS ===\\n\")\n\nwith open('\u002Fcases\u002Fcase-2024-001\u002Fusb\u002Fsetupapi.dev.log', 'r', errors='ignore') as f:\n    content = f.read()\n\n# Find USB device installation sections\npattern = r'>>>\\s+\\[Device Install.*?\\n.*?Section start (\\d{4}\u002F\\d{2}\u002F\\d{2} \\d{2}:\\d{2}:\\d{2}).*?\\n(.*?)\u003C\u003C\u003C'\nmatches = re.findall(pattern, content, re.DOTALL)\n\nusb_installs = []\nfor timestamp, section in matches:\n    if 'USBSTOR' in section or 'USB\\\\VID' in section:\n        # Extract device ID\n        dev_match = re.search(r'(USBSTOR\\\\[^\\s]+|USB\\\\VID_\\w+&PID_\\w+[^\\s]*)', section)\n        if dev_match:\n            device_id = dev_match.group(1)\n            usb_installs.append({\n                'first_install': timestamp,\n                'device_id': device_id\n            })\n            print(f\"  {timestamp} | {device_id}\")\n\nprint(f\"\\nTotal USB installations found: {len(usb_installs)}\")\nPYEOF\n\n# Parse Windows Event Logs for USB events\n# Event IDs: 2003, 2010, 2100, 2102 (DriverFrameworks-UserMode)\n# Event IDs: 6416 (Security - new external device recognized)\npython3 \u003C\u003C 'PYEOF'\nimport json\nfrom evtx import PyEvtxParser\n\ntry:\n    parser = PyEvtxParser(\"\u002Fcases\u002Fcase-2024-001\u002Fusb\u002FSystem.evtx\")\n\n    print(\"\\n=== SYSTEM EVENT LOG USB EVENTS ===\\n\")\n    for record in parser.records_json():\n        data = json.loads(record['data'])\n        event_id = str(data['Event']['System']['EventID'])\n\n        # USB device connection events\n        if event_id in ('20001', '20003', '10000', '10100'):\n            timestamp = data['Event']['System']['TimeCreated']['#attributes']['SystemTime']\n            event_data = data['Event'].get('UserData', data['Event'].get('EventData', {}))\n            print(f\"  [{timestamp}] EventID {event_id}: {json.dumps(event_data, default=str)[:200]}\")\nexcept Exception as e:\n    print(f\"Error: {e}\")\nPYEOF\n```\n\n### Step 5: Build USB Activity Timeline and Report\n\n```bash\n# Compile all USB evidence into a unified timeline\npython3 \u003C\u003C 'PYEOF'\nimport json, csv\n\ntimeline = []\n\n# Load USBSTOR data\nwith open('\u002Fcases\u002Fcase-2024-001\u002Fanalysis\u002Fusb_devices.json') as f:\n    devices = json.load(f)\n\nfor device in devices:\n    timeline.append({\n        'timestamp': device['last_connected'],\n        'source': 'USBSTOR Registry',\n        'device': f\"{device['vendor']} {device['product']}\",\n        'serial': device['serial'],\n        'event': 'Last Connected',\n        'detail': device.get('friendly_name', '')\n    })\n\n# Sort chronologically\ntimeline.sort(key=lambda x: x['timestamp'])\n\n# Write timeline CSV\nwith open('\u002Fcases\u002Fcase-2024-001\u002Fanalysis\u002Fusb_timeline.csv', 'w', newline='') as f:\n    writer = csv.DictWriter(f, fieldnames=['timestamp', 'source', 'device', 'serial', 'event', 'detail'])\n    writer.writeheader()\n    writer.writerows(timeline)\n\nprint(f\"USB Timeline: {len(timeline)} events written to usb_timeline.csv\")\n\n# Print summary\nprint(\"\\n=== USB DEVICE SUMMARY ===\")\nfor entry in timeline:\n    print(f\"  {entry['timestamp']} | {entry['device']} | {entry['serial'][:20]} | {entry['event']}\")\nPYEOF\n```\n\n## Key Concepts\n\n| Concept | Description |\n|---------|-------------|\n| USBSTOR | Registry key storing USB mass storage device identification and connection data |\n| VID\u002FPID | Vendor ID and Product ID uniquely identifying USB device manufacturer and model |\n| Device serial number | Unique identifier for individual USB devices (some devices share serials) |\n| MountedDevices | Registry key mapping volume GUIDs and drive letters to physical devices |\n| MountPoints2 | Per-user registry key showing which volumes a user accessed |\n| SetupAPI log | Windows driver installation log recording first-time device connections |\n| DeviceContainers | Registry key in SOFTWARE hive with device metadata and timestamps |\n| EMDMgmt | Registry key tracking ReadyBoost-compatible devices with serial numbers and timestamps |\n\n## Tools & Systems\n\n| Tool | Purpose |\n|------|---------|\n| USB Forensic Tracker | Specialized tool for USB device history extraction |\n| USBDeview | NirSoft tool listing all USB devices connected to a system |\n| RegRipper (usbstor plugin) | Automated USB artifact extraction from registry hives |\n| Registry Explorer | Interactive registry analysis for USB-related keys |\n| KAPE | Automated collection of USB-related artifacts |\n| Plaso\u002Flog2timeline | Timeline creation including USB connection events |\n| FTK Imager | Forensic imaging including removable media |\n| Velociraptor | Endpoint agent with USB device history hunting artifacts |\n\n## Common Scenarios\n\n**Scenario 1: Data Exfiltration by Departing Employee**\nExtract 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.\n\n**Scenario 2: Unauthorized Device on Secure System**\nAudit all USBSTOR entries against approved device list, identify unauthorized devices by VID\u002FPID not matching corporate-approved hardware, determine when the unauthorized device was first and last connected, check if any data was transferred.\n\n**Scenario 3: Malware Delivery via USB**\nIdentify 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.\n\n**Scenario 4: Tracking a Specific USB Drive Across Multiple Systems**\nSearch 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.\n\n## Output Format\n\n```\nUSB Device History Analysis:\n  System: DESKTOP-ABC123 (Windows 10 Pro)\n  Total USB Storage Devices: 12\n  Analysis Sources: USBSTOR, MountedDevices, MountPoints2, SetupAPI, Event Logs\n\n  Device Inventory:\n    1. Kingston DataTraveler 3.0 (Serial: 0019E06B4521A2B0)\n       First Connected:  2024-01-10 09:15:32 (SetupAPI)\n       Last Connected:   2024-01-18 14:30:00 (USBSTOR)\n       Drive Letter:     E:\n       User Access:      suspect_user (MountPoints2)\n\n    2. WD My Passport (Serial: 575834314131363035)\n       First Connected:  2024-01-15 20:00:00\n       Last Connected:   2024-01-15 23:45:00\n       Drive Letter:     F:\n       User Access:      suspect_user\n\n  Suspicious Findings:\n    - Kingston drive connected 15 times during investigation period\n    - WD Passport connected only once, late evening (unusual hours)\n    - Unknown device (VID_1234&PID_5678) connected 2024-01-17, no matching approved device\n\n  Timeline: \u002Fcases\u002Fcase-2024-001\u002Fanalysis\u002Fusb_timeline.csv\n```\n",{"name":5,"tags":44,"author":45,"domain":30,"license":15,"version":46,"subdomain":47,"description":7},[35,31,23,29,33,28],"mahipal","1.0","digital-forensics","main","4d2fb89cdfb75f3f6fd3c6c5ec9ad90ea129eb3c","ai-agent-skills\u002F21-external-registries\u002F08-pinkpixel-collection\u002Fanalyzing-usb-device-connection-history",2,"https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai","https:\u002F\u002Fgithub.com\u002Fluokai0","a solo builder.","2026-05-06 04:29:04",{"source":8,"skillName":5,"commands":57,"prompt":67,"zipAvailable":68},[58,61,64],{"tool":59,"command":60},"npx","npx skills add luokai0\u002Fai-agent-skills-by-luo-kai --skill analyzing-usb-device-connection-history",{"tool":62,"command":63},"bunx","bunx skills add luokai0\u002Fai-agent-skills-by-luo-kai --skill analyzing-usb-device-connection-history",{"tool":65,"command":66},"pnpm","pnpm dlx skills add luokai0\u002Fai-agent-skills-by-luo-kai --skill analyzing-usb-device-connection-history","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F21-external-registries\u002F08-pinkpixel-collection\u002Fanalyzing-usb-device-connection-history\u002FSKILL.md",true,[70,75,81],{"path":71,"resourceType":71,"resourceTypeDesc":72,"sizeBytes":73,"sourceHtmlUrl":74},"LICENSE","许可证",11255,"https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F21-external-registries\u002F08-pinkpixel-collection\u002Fanalyzing-usb-device-connection-history\u002FLICENSE",{"path":76,"resourceType":77,"resourceTypeDesc":78,"sizeBytes":79,"sourceHtmlUrl":80},"references\u002Fapi-reference.md","REFERENCE","参考文档",2194,"https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F21-external-registries\u002F08-pinkpixel-collection\u002Fanalyzing-usb-device-connection-history\u002Freferences\u002Fapi-reference.md",{"path":82,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":85,"sourceHtmlUrl":86},"scripts\u002Fagent.py","SCRIPT","脚本",6587,"https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F21-external-registries\u002F08-pinkpixel-collection\u002Fanalyzing-usb-device-connection-history\u002Fscripts\u002Fagent.py",[88,116,133,163,196,233],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":92,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":39},"01M6F2SKTE208174C7S7JJCZC7","write-contracts","Generates secure Aptos Move V2 smart contracts with Object model, Digital Asset integration, security patterns, and storage type guidance. Includes comprehensive storage decision framework for optimal data structure selection. Triggers on: 'write contract', 'create NFT collection', 'build marketplace', 'implement minting', 'generate Move module', 'create token contract', 'build DAO', 'implement staking'. Ask storage questions when: 'store', 'track', 'registry', 'mapping', 'list', 'collection'.","MIT","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fwrite-contracts\u002FSKILL.md",[],[96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115],"write","contracts","write contracts","storage","secure","create","generate","collection","model","decision","ask","smart-contracts","selection","objects","structure","nft","token","aptos","critical","move",{"skillNo":117,"name":118,"nameZh":6,"description":119,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":92,"licenseFileUrl":6,"sourceHtmlUrl":120,"categories":121,"keywords":122,"publishedAt":39},"01M6F2RFXJ6T9MKW0A7N7GM45B","web-search","通用网络搜索技能，支持多引擎搜索（百度、必应、DuckDuckGo），无需API密钥即可获取实时信息","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fweb-search-ex-skill\u002FSKILL.md",[],[123,124,125,126,127,128,129,130,131,132],"web","search","web search","搜索","baidu","bing","duckduckgo","百度","多引擎","internet",{"skillNo":134,"name":135,"nameZh":6,"description":136,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":92,"licenseFileUrl":6,"sourceHtmlUrl":137,"categories":138,"keywords":144,"publishedAt":39},"01M6F2K968G1FZEZFPW2E6B222","solo-build","Execute implementation plan tasks with TDD workflow, auto-commit, and phase gates. Use when user says \"build it\", \"start building\", \"execute plan\", \"implement tasks\", \"ship it\", or references a track ID. Do NOT use for planning (use \u002Fplan) or scaffolding (use \u002Fscaffold).","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fsolo-build\u002FSKILL.md",[139],{"categoryNo":140,"categoryName":141,"taxonomyType":142,"taxonomyTypeDesc":143},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[145,146,147,148,149,150,151,152,124,153,154,155,96,156,157,158,159,160,161,162],"build","solo","solo build","MCP","workflow","commit","tasks","code","Bash","plan","read","auto","references","context7","query","scaffolding","ship it","project",{"skillNo":164,"name":165,"nameZh":6,"description":166,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":92,"licenseFileUrl":6,"sourceHtmlUrl":167,"categories":168,"keywords":175,"publishedAt":39},"01M6F2GKN39SGHSPWYB3662YC8","react-email","Use when building HTML email templates with React components, adding a visual email editor to an application using the React Email visual editor, rendering emails to HTML, or sending emails with Resend. Covers welcome emails, password resets, notifications, order confirmations, newsletters, transactional emails, and the embeddable email editor component.","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Freact-email-skills\u002FSKILL.md",[169,172],{"categoryNo":170,"categoryName":171,"taxonomyType":142,"taxonomyTypeDesc":143},"01JBSEEDCAT000000000000005","邮件与沟通",{"categoryNo":173,"categoryName":174,"taxonomyType":142,"taxonomyTypeDesc":143},"01JBSEEDCAT000000000000009","前端开发",[176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195],"react","email","react email","github","editor","components","react components","component","welcome","https","notifications","password","node","use","html","resend","visual","emails","rendering","with",{"skillNo":197,"name":198,"nameZh":6,"description":199,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":92,"licenseFileUrl":6,"sourceHtmlUrl":200,"categories":201,"keywords":214,"publishedAt":39},"01M6F2FBVGVDFSG8SSFJGXA40C","APITester Agent-Driven API Testing","Test API endpoints and document responses. Define tests in plain English, run them, get formatted results. Agent-driven Postman alternative.","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fopenclaw-api-tester\u002FSKILL.md",[202,205,208,209],{"categoryNo":203,"categoryName":204,"taxonomyType":142,"taxonomyTypeDesc":143},"01JBSEEDCAT000000000000008","测试与质量",{"categoryNo":206,"categoryName":207,"taxonomyType":142,"taxonomyTypeDesc":143},"01JBSEEDCAT000000000000010","后端与接口",{"categoryNo":140,"categoryName":141,"taxonomyType":142,"taxonomyTypeDesc":143},{"categoryNo":210,"categoryName":211,"taxonomyType":212,"taxonomyTypeDesc":213},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232],"testing","api","api testing","driven","APITester Agent Driven API Testing","test","run","postman","results","plain english","tester","endpoints","document","get","define","tests","english","api-tester",{"skillNo":234,"name":235,"nameZh":6,"description":236,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":92,"licenseFileUrl":6,"sourceHtmlUrl":237,"categories":238,"keywords":239,"publishedAt":39},"01M6F273Y3NGAPVJZ608BC0G9G","hubspot-implementation-plan","Generate a phased implementation plan from a HubSpot audit report. Creates prioritized, sequenced cleanup processes with effort estimates, dependencies, and automation feasibility. Use after running \u002Fhubspot-audit.","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fhubspot-implementation-plan\u002FSKILL.md",[],[154,240,241,242,243,244,245,102,246,247,248,249,250,189,251,252,195,253],"implementation","hubspot","hubspot implementation plan","automation","feasibility","cleanup","planning","report","audit","audit report","phased implementation","dependencies","processes","hubspot audit"]