Skip to main content

peripheral_core/
lib.rs

1//! `peripheral-core` — external-device (peripheral) connection forensic reader.
2//!
3//! Parses Windows `setupapi.dev.log` device-installation logs into a uniform
4//! [`DeviceConnection`] stream: bus-classified, with each timestamp tagged
5//! authoritative-vs-inferred and the USB iSerial kept distinct from any volume
6//! serial. The input is attacker-controllable evidence — parsing is lenient
7//! (lossy UTF-8), bounds-checked, and never panics. No `unsafe`.
8//!
9//! Findings (DMA-capable device, mass-storage, HID/BadUSB, OS-generated serial)
10//! live in the sibling `peripheral-forensic` crate; this crate only decodes.
11//!
12//! ## v0.2 enrichment (not in this release)
13//!
14//! The richest source — the Windows registry `SYSTEM\CurrentControlSet\Enum\`
15//! keys (USBSTOR/USB), `MountedDevices`, and the device-property `0066`/`0067`
16//! Last-Arrival/Last-Removal `FILETIME`s — plus EVTX device events require the
17//! (unpublished) `winreg-core` and `winevt-forensic` crates. They are deferred
18//! to v0.2; v0.1 is scoped to the self-contained `setupapi.dev.log` source.
19
20#![forbid(unsafe_code)]
21
22pub mod linux_syslog;
23pub mod mounted_volumes;
24pub mod registry;
25pub mod setupapi;
26pub mod volume_info;
27
28/// The physical/logical bus a peripheral attached through.
29///
30/// The variant drives the DMA-capability and storage-class threat lenses
31/// downstream (see [`DeviceConnection::dma_capable`]).
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
33pub enum Bus {
34    /// USB (host-controller mediated; not directly DMA-capable as mass storage).
35    Usb,
36    /// Media Transfer Protocol (phones/cameras) — surfaced via `WpdBusEnumRoot`.
37    Mtp,
38    /// IEEE 1394 FireWire — bus-mastering DMA.
39    FireWire,
40    /// Thunderbolt — PCIe tunnelled, bus-mastering DMA.
41    Thunderbolt,
42    /// PCI Express — bus-mastering DMA.
43    Pcie,
44    /// External SATA — SATA/storage transport, explicitly NOT DMA.
45    Esata,
46    /// SD/MMC card.
47    SdMmc,
48    /// Bluetooth (typically HID/wireless).
49    Bluetooth,
50    /// ExpressCard — PCIe-backed, bus-mastering DMA.
51    ExpressCard,
52    /// SCSI / SAS storage transport.
53    ScsiSas,
54    /// NVMe storage.
55    Nvme,
56    /// Bus could not be determined from the enumerator.
57    Unknown,
58}
59
60impl Bus {
61    /// Classify a bus from a setupapi/instance-id **enumerator** prefix — the
62    /// leading token of a device instance id (`USBSTOR`, `USB`, `1394`, `PCI`,
63    /// `SCSI`, `SD`, `WpdBusEnumRoot`, …), matched case-insensitively.
64    ///
65    /// Returns [`Bus::Unknown`] for an unrecognized or empty enumerator; the
66    /// caller never gets a panic.
67    #[must_use]
68    pub fn from_enumerator(enumerator: &str) -> Self {
69        let e = enumerator.trim().to_ascii_uppercase();
70        match e.as_str() {
71            "USBSTOR" | "USB" => Self::Usb,
72            "1394" => Self::FireWire,
73            "THUNDERBOLT" => Self::Thunderbolt,
74            "PCI" | "PCIE" => Self::Pcie,
75            "SCSI" | "SAS" => Self::ScsiSas,
76            "NVME" => Self::Nvme,
77            "SD" | "MMC" | "SDBUS" => Self::SdMmc,
78            "ESATA" => Self::Esata,
79            "BTHENUM" | "BTHLE" | "BLUETOOTH" => Self::Bluetooth,
80            "EXPRESSCARD" => Self::ExpressCard,
81            "WPDBUSENUMROOT" | "MTP" => Self::Mtp,
82            _ => Self::Unknown,
83        }
84    }
85
86    /// Whether this bus can perform **bus-mastering DMA**, the property that
87    /// makes a device a direct-memory-access attack surface (MITRE T1200).
88    ///
89    /// DMA-capable: FireWire, Thunderbolt, PCIe, ExpressCard. Storage-class
90    /// transports (USB mass storage, eSATA, SD/MMC, SCSI/SAS, NVMe) and
91    /// HID/wireless transports (USB-HID, Bluetooth) are NOT DMA in this model.
92    ///
93    /// Caveat: SD-Express tunnels PCIe and *can* be DMA-capable; this v0.1
94    /// classifier treats bare `SD` as the legacy non-DMA SD/MMC bus, the common
95    /// case. Distinguishing SD-Express needs the device-capability bits that the
96    /// registry/EVTX v0.2 source carries.
97    #[must_use]
98    pub fn is_dma_capable(self) -> bool {
99        matches!(
100            self,
101            Self::FireWire | Self::Thunderbolt | Self::Pcie | Self::ExpressCard
102        )
103    }
104
105    /// Whether this bus is a removable mass-storage transport (the
106    /// data-exfiltration / autorun lens, MITRE T1052.001 / T1091).
107    #[must_use]
108    pub fn is_mass_storage(self) -> bool {
109        matches!(
110            self,
111            Self::Usb | Self::Esata | Self::SdMmc | Self::ScsiSas | Self::Nvme
112        )
113    }
114}
115
116/// How much trust a timestamp carries.
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
118pub enum Confidence {
119    /// Directly recorded by the source as the stated event
120    /// (e.g. the setupapi section-header install time → first-seen).
121    Authoritative,
122    /// Derived/undocumented — the value's meaning is inferred, not stated by the
123    /// source (e.g. the registry `0066`/`0067` Last-Arrival/Last-Removal
124    /// device-property `FILETIME`s, which are undocumented).
125    Inferred,
126}
127
128/// A timestamp tagged with its evidentiary confidence.
129///
130/// Pairing the value with its [`Confidence`] in the type makes the
131/// authoritative-vs-inferred distinction impossible to drop on the floor: a
132/// consumer cannot read `value` without also seeing how trustworthy it is.
133#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
134pub struct Stamp {
135    /// Unix epoch seconds.
136    pub value: i64,
137    /// How the value should be trusted.
138    pub confidence: Confidence,
139}
140
141impl Stamp {
142    /// An authoritative (source-stated) timestamp.
143    #[must_use]
144    pub fn authoritative(value: i64) -> Self {
145        Self {
146            value,
147            confidence: Confidence::Authoritative,
148        }
149    }
150
151    /// An inferred (derived/undocumented) timestamp.
152    #[must_use]
153    pub fn inferred(value: i64) -> Self {
154        Self {
155            value,
156            confidence: Confidence::Inferred,
157        }
158    }
159}
160
161/// A MITRE ATT&CK technique a connection is *consistent with* — never a verdict.
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
163pub struct MitreRef(pub &'static str);
164
165/// One external-device connection, normalized across sources.
166///
167/// The forensic cautions are baked into the type, not just the docs:
168/// - [`device_serial`](Self::device_serial) is the **USB iSerial** and is a
169///   distinct field from [`volume_serial`](Self::volume_serial) (a filesystem
170///   volume serial), so the two can never be conflated.
171/// - [`serial_is_os_generated`](Self::serial_is_os_generated) records that the
172///   device had no real iSerial (Windows synthesized one), weakening attribution.
173/// - Each timestamp is a [`Stamp`] carrying its authoritative-vs-inferred
174///   [`Confidence`].
175#[derive(Debug, Clone, PartialEq, Eq)]
176pub struct DeviceConnection {
177    // ── Identity ────────────────────────────────────────────────────────────
178    /// The classified bus.
179    pub bus: Bus,
180    /// Device setup-class GUID, when known.
181    pub device_class_guid: Option<String>,
182    /// USB vendor id (`VID_xxxx`).
183    pub vid: Option<u16>,
184    /// USB product id (`PID_xxxx`).
185    pub pid: Option<u16>,
186    /// The **USB iSerial** — the device-unique serial reported by the device.
187    /// DISTINCT from any [`volume_serial`](Self::volume_serial).
188    pub device_serial: Option<String>,
189    /// `true` when the instance-id serial was synthesized by Windows (the
190    /// serial's 2nd character is `&`) — the device exposed no real iSerial, so
191    /// attribution is weaker.
192    pub serial_is_os_generated: bool,
193    /// Human-readable friendly name, when present.
194    pub friendly_name: Option<String>,
195    /// The full device instance id (e.g.
196    /// `USB\VID_0781&PID_5583\1234567890AB`) — the primary key.
197    pub device_instance_id: String,
198
199    // ── Timestamps (each tagged authoritative-vs-inferred) ───────────────────
200    /// First-seen / first-install — authoritative when from the setupapi
201    /// section header.
202    pub first_install: Option<Stamp>,
203    /// Last install/driver event.
204    pub last_install: Option<Stamp>,
205    /// Last arrival (connect). INFERRED — derived from the undocumented registry
206    /// `0066` device property (v0.2).
207    pub last_arrival: Option<Stamp>,
208    /// Last removal (disconnect). INFERRED — derived from the undocumented
209    /// registry `0067` device property (v0.2).
210    pub last_removal: Option<Stamp>,
211
212    // ── Correlation join keys (volume_serial kept DISTINCT from device_serial) ─
213    /// `ParentIdPrefix` — joins the storage device to its volume.
214    pub parent_id_prefix: Option<String>,
215    /// Volume GUID (`\\?\Volume{...}`).
216    pub volume_guid: Option<String>,
217    /// Mounted drive letter.
218    pub drive_letter: Option<char>,
219    /// Filesystem **volume** serial (NTFS/FAT) — DISTINCT from the device's
220    /// USB [`device_serial`](Self::device_serial).
221    pub volume_serial: Option<u32>,
222    /// MBR disk signature.
223    pub disk_signature: Option<u32>,
224
225    // ── Threat lens ──────────────────────────────────────────────────────────
226    /// Whether the bus is bus-mastering DMA-capable (see [`Bus::is_dma_capable`]).
227    pub dma_capable: bool,
228    /// MITRE ATT&CK techniques this connection is *consistent with*.
229    pub mitre: Vec<MitreRef>,
230
231    // ── Provenance ───────────────────────────────────────────────────────────
232    /// Where this record came from (source file + 1-based line).
233    pub source: Provenance,
234}
235
236/// Where a [`DeviceConnection`] was decoded from.
237#[derive(Debug, Clone, PartialEq, Eq)]
238pub struct Provenance {
239    /// The source file (e.g. `setupapi.dev.log`, or the hive name `SYSTEM`).
240    pub file: String,
241    /// 1-based line number of the section header the record came from, for
242    /// line-oriented sources (`setupapi.dev.log`). `0` when the source is not
243    /// line-oriented (e.g. a registry hive — see [`key_path`](Self::key_path)).
244    pub line: usize,
245    /// The full registry key path the record was decoded from, for hive sources
246    /// (e.g. `ControlSet001\Enum\SCSI\Disk&Ven_…\5&22be343f&0&000000`). `None` for
247    /// line-oriented sources.
248    pub key_path: Option<String>,
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254
255    #[test]
256    fn usb_enumerators_classify_as_usb() {
257        assert_eq!(Bus::from_enumerator("USBSTOR"), Bus::Usb);
258        assert_eq!(Bus::from_enumerator("USB"), Bus::Usb);
259        assert_eq!(Bus::from_enumerator("usbstor"), Bus::Usb); // case-insensitive
260    }
261
262    #[test]
263    fn bus_specific_enumerators_classify() {
264        assert_eq!(Bus::from_enumerator("1394"), Bus::FireWire);
265        assert_eq!(Bus::from_enumerator("SCSI"), Bus::ScsiSas);
266        assert_eq!(Bus::from_enumerator("PCI"), Bus::Pcie);
267        assert_eq!(Bus::from_enumerator("SD"), Bus::SdMmc);
268        assert_eq!(Bus::from_enumerator("WpdBusEnumRoot"), Bus::Mtp);
269        assert_eq!(Bus::from_enumerator("THUNDERBOLT"), Bus::Thunderbolt);
270        assert_eq!(Bus::from_enumerator("ESATA"), Bus::Esata);
271        assert_eq!(Bus::from_enumerator("EXPRESSCARD"), Bus::ExpressCard);
272        assert_eq!(Bus::from_enumerator("BTHENUM"), Bus::Bluetooth);
273        assert_eq!(Bus::from_enumerator("NVME"), Bus::Nvme);
274    }
275
276    #[test]
277    fn unknown_enumerator_is_unknown_never_panics() {
278        assert_eq!(Bus::from_enumerator("HID"), Bus::Unknown);
279        assert_eq!(Bus::from_enumerator(""), Bus::Unknown);
280        assert_eq!(Bus::from_enumerator("   "), Bus::Unknown);
281    }
282
283    #[test]
284    fn dma_capable_is_exactly_firewire_thunderbolt_pcie_expresscard() {
285        for b in [Bus::FireWire, Bus::Thunderbolt, Bus::Pcie, Bus::ExpressCard] {
286            assert!(b.is_dma_capable(), "{b:?} must be DMA-capable");
287        }
288        // Storage-only transports are explicitly NOT DMA (eSATA is SATA/storage).
289        for b in [Bus::Usb, Bus::Esata, Bus::SdMmc, Bus::ScsiSas, Bus::Nvme] {
290            assert!(!b.is_dma_capable(), "{b:?} must NOT be DMA-capable");
291        }
292        // HID/wireless transports are not DMA either.
293        for b in [Bus::Bluetooth, Bus::Mtp, Bus::Unknown] {
294            assert!(!b.is_dma_capable(), "{b:?} must NOT be DMA-capable");
295        }
296    }
297
298    #[test]
299    fn mass_storage_classes() {
300        for b in [Bus::Usb, Bus::Esata, Bus::SdMmc, Bus::ScsiSas, Bus::Nvme] {
301            assert!(b.is_mass_storage(), "{b:?} should be mass storage");
302        }
303        for b in [Bus::FireWire, Bus::Thunderbolt, Bus::Bluetooth, Bus::Mtp] {
304            assert!(!b.is_mass_storage(), "{b:?} should not be mass storage");
305        }
306    }
307
308    #[test]
309    fn stamp_carries_confidence() {
310        assert_eq!(
311            Stamp::authoritative(10).confidence,
312            Confidence::Authoritative
313        );
314        assert_eq!(Stamp::inferred(10).confidence, Confidence::Inferred);
315    }
316}