Analyzing usb device connection history

From killvxk/cybersecurity-skills-zh · View interactive version

Analyzing usb device connection history is an AI agent skill from the GitHub repository killvxk/cybersecurity-skills-zh. 从 Windows 注册表、事件日志和 setupapi 日志调查 USB 设备连接历史,以追踪可移动存储设备的使用情况和潜在的数据外泄行为。

How to use this skill

Skill file

分析 USB 设备连接历史

适用场景

前置条件

工作流程

步骤 1:提取 USB 相关制品

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

mkdir -p /cases/case-2024-001/usb/

# 注册表 hive
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 日志(首次连接时间戳)
cp /mnt/evidence/Windows/INF/setupapi.dev.log /cases/case-2024-001/usb/

# 事件日志
cp /mnt/evidence/Windows/System32/winevt/Logs/System.evtx /cases/case-2024-001/usb/

步骤 2:解析 USBSTOR 注册表键

python3 << 'PYEOF'
from Registry import Registry
import json

reg = Registry.Registry("/cases/case-2024-001/usb/SYSTEM")
select = reg.open("Select")
current = select.value("Current").value()
controlset = f"ControlSet{current:03d}"
usbstor_path = f"{controlset}\Enum\USBSTOR"
usbstor = reg.open(usbstor_path)

devices = []
for device_class in usbstor.subkeys():
    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'
    for instance in device_class.subkeys():
        serial = instance.name()
        last_write = instance.timestamp()
        device_info = {
            'vendor': vendor, 'product': product,
            'serial': serial, 'last_connected': str(last_write),
        }
        try:
            device_info['friendly_name'] = instance.value("FriendlyName").value()
        except:
            pass
        devices.append(device_info)
        print(f"设备:{vendor} {product} | 序列号:{serial} | 最后连接:{last_write}")

with open('/cases/case-2024-001/analysis/usb_devices.json', 'w') as f:
    json.dump(devices, f, indent=2)
print(f"\n发现 USB 存储设备总数:{len(devices)}")
PYEOF

步骤 3:提取驱动器盘符分配和用户关联

# 解析用户 MountPoints2(哪个用户访问了哪些设备)
python3 << 'PYEOF'
from Registry import Registry
import os, glob

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"用户 hive:{os.path.basename(ntuser)}")
        for key in mp2.subkeys():
            if '{' in key.name():
                print(f"  卷:{key.name()} | 最后访问时间:{key.timestamp()}")
    except Exception as e:
        print(f"  解析出错:{e}")
PYEOF

步骤 4:从 SetupAPI 提取首次连接时间戳

python3 << 'PYEOF'
import re

with open('/cases/case-2024-001/usb/setupapi.dev.log', '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(.*?)<<<'
usb_installs = []
for timestamp, section in re.findall(pattern, content, re.DOTALL):
    if 'USBSTOR' in section or 'USB\VID' in section:
        dev_match = re.search(r'(USBSTOR\[^\s]+|USB\VID_\w+&PID_\w+[^\s]*)', section)
        if dev_match:
            usb_installs.append({'first_install': timestamp, 'device_id': dev_match.group(1)})
            print(f"  {timestamp} | {dev_match.group(1)}")
print(f"\n发现 USB 安装记录总数:{len(usb_installs)}")
PYEOF

步骤 5:构建 USB 活动时间线

python3 << 'PYEOF'
import json, csv

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

timeline = []
for device in devices:
    timeline.append({
        'timestamp': device['last_connected'],
        'source': 'USBSTOR 注册表',
        'device': f"{device['vendor']} {device['product']}",
        'serial': device['serial'],
        'event': '最后连接时间',
        'detail': device.get('friendly_name', '')
    })

timeline.sort(key=lambda x: x['timestamp'])

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 时间线:{len(timeline)} 个事件已写入 usb_timeline.csv")
for entry in timeline:
    print(f"  {entry['timestamp']} | {entry['device']} | {entry['serial'][:20]}")
PYEOF

关键概念

| 概念 | 描述 |

|------|------|

| USBSTOR | 存储 USB 大容量存储设备识别信息和连接数据的注册表键 |

| VID/PID | 厂商 ID 和产品 ID,唯一标识 USB 设备的厂商和型号 |

| 设备序列号 | 各 USB 设备的唯一标识符(某些设备共享序列号) |

| MountedDevices | 将卷 GUID 和驱动器盘符映射到物理设备的注册表键 |

| MountPoints2 | 显示用户访问过哪些卷的每用户注册表键 |

| SetupAPI 日志 | 记录设备首次连接的 Windows 驱动程序安装日志 |

| DeviceContainers | SOFTWARE hive 中包含设备元数据和时间戳的注册表键 |

| EMDMgmt | 追踪支持 ReadyBoost 的设备(含序列号和时间戳)的注册表键 |

工具与系统

| 工具 | 用途 |

|------|------|

| USB Forensic Tracker | 专用的 USB 设备历史提取工具 |

| USBDeview | NirSoft 工具,列出连接到系统的所有 USB 设备 |

| RegRipper(usbstor 插件) | 从注册表 hive 自动提取 USB 制品 |

| Registry Explorer | 用于 USB 相关键的交互式注册表分析工具 |

| KAPE | 自动收集 USB 相关制品 |

| Plaso/log2timeline | 包含 USB 连接事件的时间线生成工具 |

| Velociraptor | 具有 USB 设备历史追踪制品的端点 Agent |

常见场景

场景 1:离职员工的数据外泄

提取 USBSTOR 条目以识别所有曾连接的 USB 设备,将设备序列号与 MountPoints2 相关联以确认用户访问,与文件访问日志和跳转列表最近文件进行交叉参照,在 USN 日志中检查大文件复制模式。

场景 2:安全系统中的未授权设备

对照已批准设备列表审计所有 USBSTOR 条目,通过 VID/PID 识别不符合企业批准硬件的未授权设备,确定未授权设备首次和最后连接的时间,检查是否有数据被传输。

场景 3:通过 USB 传播恶意软件

识别在恶意软件执行前连接的 USB 设备(Prefetch 时间戳),提取设备序列号和厂商信息,检查设备是否启用了自动运行,在 Prefetch 和 ShimCache 中查找从可移动驱动器盘符启动可执行文件的记录。

场景 4:跨多个系统追踪特定 USB 驱动器

在所有取证镜像的 USBSTOR 中搜索相同的设备序列号,构建驱动器连接过哪些系统及连接时间的映射,识别设备在组织内的时间顺序路径,与网络共享访问日志相关联。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.