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