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