usb-forensic 0.1.0

USB device-history correlation engine — reconstructs USB connection history from every Windows artifact and scores cross-source timestamp consistency. Pipeline-native, reproducible, panic-free.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! `usb4n6` — run the USB-history correlation pipeline over evidence sources and emit a
//! JSONL timeline plus graded findings.
//!
//! Thin shell (Humble Object): every decision — parsing, correlation, grading,
//! serialization — lives in the tested `usb_forensic` / `peripheral_core` / `lnk_core`
//! libraries; this binary only reads input, detects its type, wires the sources, and
//! writes output.
//!
//! ```text
//! usb4n6 [--table|--timeline|--files|--export-mbr|--report|--docx|--pdf] [--tz-offset=<secs>] [--year=<YYYY>] <file>...
//!     # files: setupapi.dev.log, a SYSTEM hive, .lnk, *.automaticDestinations-ms,
//!     #        a Partition/Diagnostic .evtx, a raw or E01 USB device image, a macOS com.apple.iPod.plist, or a Linux syslog/dmesg (auto-detected)
//! usb4n6 --version
//! ```
//! stdout: JSONL (default), a results grid (`--table`), the aggregate super-timeline as
//! JSONL (`--timeline`), a Markdown court report (`--report`), or a native `.docx`/`.pdf`
//! report. `--tz-offset=<secs>` normalizes
//! host-local (setupapi/Linux) timestamps to UTC. `--year=<YYYY>` supplies the
//! reference year for year-less Linux syslog timestamps (required when a syslog is
//! given). stderr: a summary and graded findings.

use peripheral_core::emdmgmt::{parse_emdmgmt, EmdVolume};
use peripheral_core::linux_syslog::parse_linux_syslog;
use peripheral_core::mounted_volumes::{parse_mounted_volumes, MountedVolume};
use peripheral_core::mountpoints2::{parse_mountpoints2, UserMount};
use peripheral_core::registry::parse_registry;
use peripheral_core::setupapi::parse_setupapi;
use peripheral_core::volume_info::{parse_volume_info_cache, VolumeLabel};
use std::process::ExitCode;
use usb_forensic::{
    analyse_device_image, audit, kernel_pnp_events, parse_boot_sectors, parse_ipod_plist,
    parse_system_profiler, parse_unified_log, to_jsonl, AppleDevice, AppleIPodSource, DeviceImage,
    DeviceImageSource, EmdMgmtSource, HistorySource, JumpListArtifact, JumpListSource,
    KernelPnpEvent, KernelPnpSource, LnkArtifact, LnkSource, MacUnifiedLogSource, MacUsbDevice,
    MacUsbSource, MountPoints2Source, PartitionDiagSource, PeripheralSource, SourceKind,
    UsbEnumeration, VolumeCacheSource,
};
use winevt_extract::{partition_diag, PartitionDiagEvent};

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    if args.iter().any(|a| a == "-V" || a == "--version") {
        println!("usb4n6 {}", env!("CARGO_PKG_VERSION"));
        return ExitCode::SUCCESS;
    }
    let mode = if args.iter().any(|a| a == "--pdf") {
        Output::Pdf
    } else if args.iter().any(|a| a == "--docx") {
        Output::Docx
    } else if args.iter().any(|a| a == "--report") {
        Output::Report
    } else if args.iter().any(|a| a == "--table") {
        Output::Table
    } else if args.iter().any(|a| a == "--timeline") {
        Output::Timeline
    } else if args.iter().any(|a| a == "--files") {
        Output::Files
    } else if args.iter().any(|a| a == "--export-mbr") {
        Output::ExportMbr
    } else {
        Output::Jsonl
    };
    // Optional host UTC offset (seconds) to normalize local-clock (setupapi/Linux) times.
    let tz_offset = args.iter().find_map(|a| {
        a.strip_prefix("--tz-offset=")
            .and_then(|v| v.parse::<i64>().ok())
    });
    // Reference year for year-less Linux syslog timestamps (required for a syslog).
    let year = args.iter().find_map(|a| {
        a.strip_prefix("--year=")
            .and_then(|v| v.parse::<i64>().ok())
    });
    let paths: Vec<&String> = args.iter().filter(|a| !a.starts_with('-')).collect();
    if paths.is_empty() {
        eprintln!(
            "usage: usb4n6 [--table|--timeline|--files|--export-mbr|--report|--docx|--pdf] [--tz-offset=<secs>] \
             [--year=<YYYY>] <file>...  \
             (setupapi.dev.log/SYSTEM hive/.lnk/jumplist/.evtx/Linux syslog; -V)"
        );
        return ExitCode::FAILURE;
    }
    run(&paths, mode, tz_offset, year)
}

/// How to render the correlated histories on stdout.
#[derive(Clone, Copy)]
enum Output {
    /// One JSON object per device (machine, round-trippable) — the default.
    Jsonl,
    /// A human-readable results grid.
    Table,
    /// The aggregate super-timeline: every timestamped event across all devices,
    /// chronological, as JSONL (one event per line).
    Timeline,
    /// The opened/accessed-files report: files touched on each device.
    Files,
    /// Export each input device image's raw MBR sector as an annotated hex dump.
    ExportMbr,
    /// A court-oriented Markdown forensic report.
    Report,
    /// The forensic report as a native Word `.docx` (binary; redirect to a file).
    Docx,
    /// The forensic report as a native `.pdf` (binary; redirect to a file).
    Pdf,
}

/// A `.lnk` Shell Link begins with `HeaderSize` = 0x4C little-endian.
fn is_shell_link(bytes: &[u8]) -> bool {
    bytes.get(..4) == Some(&[0x4C, 0x00, 0x00, 0x00])
}

/// An `*.automaticDestinations-ms` jump list is an OLE/CFB compound file.
fn is_compound_file(bytes: &[u8]) -> bool {
    bytes.get(..8) == Some(&[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1])
}

/// A Windows registry hive begins with the `regf` base-block signature.
fn is_registry_hive(bytes: &[u8]) -> bool {
    bytes.get(..4) == Some(b"regf")
}

/// A Windows Event Log (`.evtx`) begins with the `ElfFile\0` file-header signature.
fn is_evtx(bytes: &[u8]) -> bool {
    bytes.get(..8) == Some(b"ElfFile\0")
}

/// Parse a `.evtx` and extract USB Kernel-PnP configuration events. Iterates the raw records
/// as JSON (the `evtx` reader) and defers the field decoding to `kernel_pnp_events`. Returns
/// empty on an unreadable file or a log with no USB Kernel-PnP events.
fn parse_kernel_pnp(path: &str) -> Vec<KernelPnpEvent> {
    let Ok(mut parser) = evtx::EvtxParser::from_path(path) else {
        return Vec::new();
    };
    kernel_pnp_events(
        parser
            .records_json_value()
            .filter_map(Result::ok)
            .map(|r| r.data),
    )
}

/// A raw disk image with an MBR ends its first sector with the `0x55AA` boot signature.
fn is_disk_image(bytes: &[u8]) -> bool {
    bytes.get(0x1FE..0x200) == Some(&[0x55, 0xAA])
}

/// An `EnCase` E01 forensic image begins with the `EVF` + `09 0d 0a ff 00` signature.
fn is_e01(bytes: &[u8]) -> bool {
    bytes.get(..8) == Some(b"EVF\x09\x0d\x0a\xff\x00")
}

/// Open an `EnCase` E01 image and decode its boot sectors (built-in image mounting — no
/// external mounter). The E01 reader is seekable, so it is handed straight to
/// `analyse_device_image`, which seeks to each partition on demand. `None` on an invalid
/// image.
fn parse_e01_device_image(path: &str) -> Option<DeviceImage> {
    let mut reader = ewf::EwfReader::open(path).ok()?;
    let size = reader.total_size();
    analyse_device_image(&mut reader, size)
}

/// A property list — a binary `bplist00` or an XML plist (the `com.apple.iPod.plist` form).
fn is_plist(bytes: &[u8]) -> bool {
    bytes.get(..8) == Some(b"bplist00")
        || String::from_utf8_lossy(bytes.get(..512).unwrap_or(bytes)).contains("<plist")
}

/// A `system_profiler -json SPUSBDataType` capture (JSON carrying the `SPUSBDataType` key).
fn is_system_profiler_usb(bytes: &[u8]) -> bool {
    String::from_utf8_lossy(bytes.get(..512).unwrap_or(bytes)).contains("SPUSBDataType")
}

/// A `log show --style json` capture — a JSON array whose entries are unified-log records
/// (each carries `"eventType" : "logEvent"`, which sits at the head of the first record).
fn is_unified_log(bytes: &[u8]) -> bool {
    let head = String::from_utf8_lossy(bytes.get(..512).unwrap_or(bytes));
    head.trim_start().starts_with('[') && head.contains("logEvent")
}

/// A Linux kernel log carries the `New USB device found` enumeration marker that the
/// syslog reader keys on; setupapi text does not.
fn looks_like_linux_syslog(text: &str) -> bool {
    text.contains("New USB device found")
}

/// Write a binary artifact to stdout; returns `false` (and reports) on I/O error.
fn write_binary(bytes: &[u8], label: &str) -> bool {
    use std::io::Write as _;
    match std::io::stdout().write_all(bytes) {
        Ok(()) => true,
        Err(err) => {
            eprintln!("usb4n6: cannot write {label}: {err}");
            false
        }
    }
}

/// Device connections and artifacts gathered from the input files, grouped by origin
/// so each batch is stamped with the right [`SourceKind`] (which drives container /
/// clock-locality reasoning downstream).
#[derive(Default)]
struct Ingested {
    setupapi: Vec<peripheral_core::DeviceConnection>,
    registry: Vec<peripheral_core::DeviceConnection>,
    linux: Vec<peripheral_core::DeviceConnection>,
    lnk: Vec<LnkArtifact>,
    jumplists: Vec<JumpListArtifact>,
    partition_diag: Vec<PartitionDiagEvent>,
    kernel_pnp: Vec<KernelPnpEvent>,
    volume_labels: Vec<VolumeLabel>,
    emd_volumes: Vec<EmdVolume>,
    device_images: Vec<(DeviceImage, String)>,
    apple_devices: Vec<(Vec<AppleDevice>, String)>,
    mac_usb: Vec<(Vec<MacUsbDevice>, String)>,
    mac_log: Vec<(Vec<UsbEnumeration>, String)>,
    mounted_volumes: Vec<MountedVolume>,
    user_mounts: Vec<UserMount>,
}

impl Ingested {
    /// Total source records read, across every origin.
    fn record_count(&self) -> usize {
        self.setupapi.len()
            + self.registry.len()
            + self.linux.len()
            + self.lnk.len()
            + self.jumplists.len()
            + self.partition_diag.len()
            + self.kernel_pnp.len()
            + self.volume_labels.len()
            + self.user_mounts.len()
            + self.emd_volumes.len()
            + self.device_images.len()
            + self
                .apple_devices
                .iter()
                .map(|(d, _)| d.len())
                .sum::<usize>()
            + self.mac_usb.iter().map(|(d, _)| d.len()).sum::<usize>()
            + self.mac_log.iter().map(|(d, _)| d.len()).sum::<usize>()
    }
}

/// Read and classify every input file by content, routing it to the matching reader.
/// Returns `None` (after reporting) on a fatal error: an unreadable file, or a Linux
/// syslog with no `--year` (its year-less timestamps would otherwise be silently wrong).
fn ingest(paths: &[&String], year: Option<i64>) -> Option<Ingested> {
    let mut g = Ingested::default();
    for path in paths {
        let bytes = match std::fs::read(path.as_str()) {
            Ok(bytes) => bytes,
            Err(err) => {
                eprintln!("usb4n6: cannot read {path}: {err}");
                return None;
            }
        };
        if is_compound_file(&bytes) {
            match lnk_core::parse_automatic_destinations(&bytes, Some(path)) {
                Some(list) => g.jumplists.push(JumpListArtifact {
                    source_path: (*path).clone(),
                    list,
                }),
                None => eprintln!("usb4n6: {path}: not a valid jump list, skipping"),
            }
        } else if is_shell_link(&bytes) {
            match lnk_core::parse_shell_link(&bytes) {
                Some(link) => g.lnk.push(LnkArtifact {
                    source_path: (*path).clone(),
                    link,
                }),
                None => eprintln!("usb4n6: {path}: not a valid Shell Link, skipping"),
            }
        } else if is_registry_hive(&bytes) {
            match winreg_core::hive::Hive::from_bytes(bytes) {
                Ok(hive) => {
                    // Any registry hive is probed by every hive reader; each returns empty
                    // on a hive that lacks its key. SYSTEM → device Enum + MountedDevices
                    // MBR volumes; SOFTWARE → VolumeInfoCache labels; NTUSER → MountPoints2.
                    g.registry.extend(parse_registry(&hive, path));
                    g.volume_labels.extend(parse_volume_info_cache(&hive, path));
                    g.mounted_volumes.extend(parse_mounted_volumes(&hive, path));
                    g.user_mounts.extend(parse_mountpoints2(&hive, path));
                    g.emd_volumes.extend(parse_emdmgmt(&hive, path));
                }
                Err(err) => eprintln!("usb4n6: {path}: not a valid registry hive: {err}"),
            }
        } else if is_unified_log(&bytes) {
            let evs = parse_unified_log(&bytes);
            if evs.is_empty() {
                eprintln!("usb4n6: {path}: unified log has no USB enumeration events, skipping");
            } else {
                g.mac_log.push((evs, (*path).clone()));
            }
        } else if is_system_profiler_usb(&bytes) {
            let devs = parse_system_profiler(&bytes);
            if devs.is_empty() {
                eprintln!("usb4n6: {path}: system_profiler capture has no USB devices, skipping");
            } else {
                g.mac_usb.push((devs, (*path).clone()));
            }
        } else if is_plist(&bytes) {
            let devs = parse_ipod_plist(&bytes);
            if devs.is_empty() {
                eprintln!("usb4n6: {path}: plist has no Apple-device history, skipping");
            } else {
                g.apple_devices.push((devs, (*path).clone()));
            }
        } else if is_e01(&bytes) {
            match parse_e01_device_image(path) {
                Some(img) => g.device_images.push((img, (*path).clone())),
                None => eprintln!("usb4n6: {path}: E01 has no readable MBR, skipping"),
            }
        } else if is_disk_image(&bytes) {
            match parse_boot_sectors(&bytes) {
                Some(img) => g.device_images.push((img, (*path).clone())),
                None => eprintln!("usb4n6: {path}: MBR present but unreadable, skipping"),
            }
        } else if is_evtx(&bytes) {
            // The evtx reader parses the file by path (not the bytes we sniffed). Each
            // extractor scans for its own provider and returns empty for a log that is not
            // its own, so both run on any .evtx: Partition/Diagnostic and Kernel-PnP.
            match partition_diag(std::path::Path::new(path.as_str())) {
                Ok(events) => g.partition_diag.extend(events),
                Err(err) => eprintln!("usb4n6: {path}: cannot parse event log: {err}"),
            }
            g.kernel_pnp.extend(parse_kernel_pnp(path));
        } else {
            let text = String::from_utf8_lossy(&bytes);
            if looks_like_linux_syslog(&text) {
                let Some(y) = year else {
                    eprintln!(
                        "usb4n6: {path}: Linux syslog timestamps are year-less — \
                         pass --year=<YYYY>"
                    );
                    return None;
                };
                g.linux.extend(parse_linux_syslog(&text, path, y));
            } else {
                g.setupapi.extend(parse_setupapi(&text, path));
            }
        }
    }
    Some(g)
}

fn run(paths: &[&String], mode: Output, tz_offset: Option<i64>, year: Option<i64>) -> ExitCode {
    let Some(g) = ingest(paths, year) else {
        return ExitCode::FAILURE;
    };

    let setupapi = PeripheralSource::new(&g.setupapi, SourceKind::SetupApi);
    let registry = PeripheralSource::new(&g.registry, SourceKind::Usbstor);
    let linux = PeripheralSource::new(&g.linux, SourceKind::LinuxKernelLog);
    let lnk = LnkSource::new(&g.lnk);
    let jumplist = JumpListSource::new(&g.jumplists);
    let partdiag = PartitionDiagSource::new(&g.partition_diag);
    let kernelpnp = KernelPnpSource::new(&g.kernel_pnp);
    let volcache = VolumeCacheSource::new(&g.volume_labels);
    let usermounts = MountPoints2Source::new(&g.user_mounts);
    let emd = EmdMgmtSource::new(&g.emd_volumes);
    let sources: [&dyn HistorySource; 10] = [
        &setupapi,
        &registry,
        &linux,
        &lnk,
        &jumplist,
        &partdiag,
        &kernelpnp,
        &volcache,
        &usermounts,
        &emd,
    ];

    // Gather every claim, optionally normalize local clocks to UTC, then reconcile:
    // (1) volume-serial → device (file-to-device), and (2) the MountedDevices MBR bridge
    // unifying drive-letter and volume-GUID facts onto one canonical volume. Then correlate.
    let mut claims: Vec<_> = sources.iter().flat_map(|s| s.claims()).collect();
    for (img, loc) in &g.device_images {
        claims.extend(DeviceImageSource::new(img, loc.clone()).claims());
    }
    for (devs, loc) in &g.apple_devices {
        claims.extend(AppleIPodSource::new(devs, loc.clone()).claims());
    }
    for (devs, loc) in &g.mac_usb {
        claims.extend(MacUsbSource::new(devs, loc.clone()).claims());
    }
    for (evs, loc) in &g.mac_log {
        claims.extend(MacUnifiedLogSource::new(evs, loc.clone()).claims());
    }
    if let Some(offset) = tz_offset {
        usb_forensic::normalize_local_clocks(&mut claims, offset);
    }
    let claims = usb_forensic::reconcile_volume_serials(&claims);
    let claims = usb_forensic::canonicalize_mounted_volumes(&claims, &g.mounted_volumes);
    let histories = usb_forensic::correlate(&claims);

    let findings = audit(&histories);

    let rendered = match mode {
        Output::Jsonl => match to_jsonl(&histories) {
            Ok(jsonl) => jsonl,
            Err(err) => {
                eprintln!("usb4n6: serialization failed: {err}");
                return ExitCode::FAILURE;
            }
        },
        Output::Table => usb_forensic::render_table(&histories),
        Output::Files => usb_forensic::render_accessed_files(&histories),
        Output::ExportMbr => g
            .device_images
            .iter()
            .map(|(img, loc)| usb_forensic::export_mbr_hex(img, loc))
            .collect(),
        Output::Timeline => {
            let events = usb_forensic::super_timeline(&histories);
            match usb_forensic::timeline_to_jsonl(&events) {
                Ok(jsonl) => jsonl,
                Err(err) => {
                    eprintln!("usb4n6: serialization failed: {err}");
                    return ExitCode::FAILURE;
                }
            }
        }
        Output::Report => usb_forensic::render_report(&histories, &findings),
        Output::Docx => {
            if !write_binary(&usb_forensic::render_docx(&histories, &findings), "docx") {
                return ExitCode::FAILURE;
            }
            String::new()
        }
        Output::Pdf => {
            if !write_binary(&usb_forensic::render_pdf(&histories, &findings), "pdf") {
                return ExitCode::FAILURE;
            }
            String::new()
        }
    };
    print!("{rendered}");

    eprintln!(
        "usb4n6: {} device(s) from {} source record(s), {} finding(s)",
        histories.len(),
        g.record_count(),
        findings.len()
    );
    for finding in &findings {
        eprintln!(
            "  [{:?}] {}{}",
            finding.severity, finding.code, finding.note
        );
    }
    ExitCode::SUCCESS
}