bootintel-detectors 0.4.1

Client-side boot-log detectors for BootIntel — bootloader / kernel / SoC / exposure identification. Pure regex library, no I/O.
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! Client-side boot-log detectors for BootIntel.
//!
//! Mirrors the 9-detector streaming subset of the browser detector
//! library at bootintel.com/tools/fingerprint. Kept pure (no I/O, no
//! async, no serde) so this crate can be reused in other contexts —
//! a future WASM build for the browser tool, a plugin for third-party
//! firmware-analysis tooling, etc.
//!
//! Sync discipline: each detector below is a one-for-one port of a
//! browser detector entry. When adding, removing, or renaming a
//! detector, keep both sources aligned.
//!
//! Regex flavor: only features supported by both JavaScript regex
//! and Rust `regex` are used (no lookaround, no backreferences). If
//! a future detector needs lookaround, pull in `fancy-regex` for
//! just that detector — do not switch the whole library.

use regex::Regex;
use std::sync::LazyLock;

/// A single detector's output.
///
/// Matches the browser tool's `Finding` type field-for-field so JSON
/// output can be diffed against the browser tool's output byte-for-byte
/// on the same input.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding {
    pub label: String,
    pub value: String,
    pub detail: Option<String>,
    pub source: Option<String>,
    /// 1-based line number of `source` within the analyzed log.
    /// Populated by `analyze()`; `None` when the evidence could not be
    /// located (or when a `Finding` is constructed by hand, e.g. from
    /// an archived JSON envelope). Additive — existing consumers that
    /// don't know about it are unaffected.
    pub line_number: Option<usize>,
}

impl Finding {
    fn new(label: &str, value: impl Into<String>) -> Self {
        Self {
            label: label.to_string(),
            value: value.into(),
            detail: None,
            source: None,
            line_number: None,
        }
    }
    fn detail(mut self, d: impl Into<String>) -> Self {
        self.detail = Some(d.into());
        self
    }
    fn source(mut self, s: impl Into<String>) -> Self {
        self.source = Some(s.into());
        self
    }
}

/// Analyze a boot log against every detector; return findings in
/// detector-registration order. Detectors that don't match are
/// silently dropped.
///
/// # Line normalization
///
/// Several detectors are line-anchored (`(?m)^U-Boot`, `(?m)^GRUB`,
/// `(?m)^coreboot-`, `(?m)^procd:`). Real captures very often carry a
/// per-line prefix that defeats a bare `^`:
///
///   * `[12:34:56.789] ` — minicom / picocom / tio timestamping
///   * `[2026-09-23T10:00:00.000Z] ` — **our own** `--log-timestamps`
///   * `[    0.000000] ` — kernel printk timestamps
///   * `\x1b[32m` — ANSI colour from a colourising bootloader
///
/// Before `--log-timestamps` existed this was merely common; now the
/// tool's own capture mode breaks its own `scan`, which is why the
/// normalization lives here rather than being pushed onto callers.
///
/// So: split into lines, strip ANSI CSI sequences and any run of
/// leading bracketed timestamps, and run the detectors over the
/// normalized text. Evidence is then mapped back to the **original**
/// (unmodified) line, so `source` always shows the user what their
/// capture actually contained, prefix and all.
///
/// Ported from the legacy Node analyzer's `analyze()` so both
/// implementations agree on what a "line" is and what gets stripped.
pub fn analyze(log: &str) -> Vec<Finding> {
    let original = split_lines(log);
    let normalized: Vec<String> = original.iter().map(|l| normalize_line(l)).collect();
    let norm_log = normalized.join("\n");
    ALL_DETECTORS
        .iter()
        .filter_map(|d| (d.run)(&norm_log))
        .map(|f| attach_evidence(f, &original, &normalized))
        .collect()
}

/// Split on any of CRLF / LF / CR. `str::lines()` only handles LF and
/// CRLF; a bare-CR stream (some bootloaders emit CR-only line endings)
/// would otherwise arrive as one giant line and defeat every
/// line-anchored detector.
fn split_lines(log: &str) -> Vec<&str> {
    let mut out = Vec::new();
    let bytes = log.as_bytes();
    let mut start = 0usize;
    let mut i = 0usize;
    while i < bytes.len() {
        match bytes[i] {
            b'\n' => {
                out.push(&log[start..i]);
                i += 1;
                start = i;
            }
            b'\r' => {
                out.push(&log[start..i]);
                // CRLF counts as one terminator.
                i += if i + 1 < bytes.len() && bytes[i + 1] == b'\n' {
                    2
                } else {
                    1
                };
                start = i;
            }
            _ => i += 1,
        }
    }
    out.push(&log[start..]);
    out
}

/// ANSI CSI escape sequence: ESC `[` params intermediates final.
/// Same character classes as the Node analyzer's
/// `/\x1b\[[0-?]*[ -/]*[@-~]/g`.
static RE_ANSI_CSI: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\x1b\[[0-?]*[ -/]*[@-~]").unwrap());

/// One leading bracketed timestamp. Three accepted shapes, matching
/// the Node analyzer:
///   * `[12:34:56]` / `[12:34:56.789]`     — wall-clock terminal logger
///   * `[2026-09-23T10:00:00.000Z]`        — ISO-8601 (our --log-timestamps)
///   * `[    0.000000]`                    — kernel printk seconds
static RE_LEADING_TS: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"^\s*\[(?:\d{2}:\d{2}:\d{2}(?:\.\d+)?|\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?|\s*\d+\.\d+)\]\s*",
    )
    .unwrap()
});

/// Strip ANSI CSI sequences and leading bracketed timestamps from one
/// line. The timestamp strip loops: `bootintel analyze --log-timestamps`
/// over a Linux console produces *two* stacked prefixes
/// (`[2026-…Z] [    0.000000] Linux version …`), and the Node
/// analyzer's single-shot strip would leave the second one in place.
fn normalize_line(line: &str) -> String {
    let mut s = RE_ANSI_CSI.replace_all(line, "").into_owned();
    // Bounded loop — a pathological line of nothing but bracketed
    // timestamps must not spin forever.
    for _ in 0..8 {
        match RE_LEADING_TS.find(&s) {
            Some(m) if m.end() > 0 => {
                s = s[m.end()..].to_string();
            }
            _ => break,
        }
    }
    s
}

/// Point a finding's `source` at the original, unmodified line that
/// produced it, and record that line's 1-based number.
///
/// Detectors return the matched substring as `source`, taken from the
/// normalized text. Locating it is a plain substring search over the
/// normalized lines — far cheaper than the Node analyzer's re-run of
/// every detector against every line, and exact for the same reason
/// (the needle came out of that text verbatim).
fn attach_evidence(mut f: Finding, original: &[&str], normalized: &[String]) -> Finding {
    let Some(src) = f.source.clone() else {
        return f;
    };
    // A few regexes (`[^)]+`) can span a newline; anchor on the first
    // physical line of the match.
    let needle = src.split('\n').next().unwrap_or(&src);
    if needle.is_empty() {
        return f;
    }
    if let Some(i) = normalized.iter().position(|l| l.contains(needle)) {
        f.source = Some(original[i].to_string());
        f.line_number = Some(i + 1);
    }
    f
}

/// Return the labels of every registered detector, in order. Used by
/// the sync-check script + `bootintel version`.
pub fn detector_labels() -> Vec<&'static str> {
    ALL_DETECTORS.iter().map(|d| d.label).collect()
}

/// A canned MIPS OpenWrt boot log used by tests and by `--sample`
/// on the CLI. Byte-for-byte identical to the SAMPLE constant in the
/// browser detector library so browser + CLI output can be diffed
/// against each other.
pub const SAMPLE: &str = "U-Boot 2020.10 (Sep 17 2023 - 11:38:21 +0000)
Model: TP-Link Archer C7 v5
DRAM:  128 MiB
NAND:  ONFI device found
Hit any key to stop autoboot:  3
[    0.000000] Linux version 5.15.137 (builder@buildhost) (mips-openwrt-linux-musl-gcc (OpenWrt GCC 11.2.0 r19685-512e76967f), GNU ld (GNU Binutils) 2.37) #0 SMP Tue Nov 14 19:23:42 2023
[    0.000000] CPU0 revision is: 00019374 (MIPS 74Kc)
[    0.000000] Determined physical RAM map:
[    0.000000]  memory: 08000000 @ 00000000 (usable)
[    1.234567] mtd: device 0 (boot)
[    2.456789] eth0: PHY found at 0x00 (Atheros AR8327)
[    3.123456] procd: - early -
[    3.789012] procd: - init -
[    4.012345] hotplug2: Bootup detected
[    4.234567] dropbear[1234]: Not backgrounding
[    4.345678] uhttpd[1235]: Listening on 0.0.0.0:80 0.0.0.0:443
[    4.456789] dnsmasq[1236]: started, version 2.86 cachesize 150
[    5.012345] DHCP client bound to address 192.168.1.42";

/// Labels that mark a finding as a **critical exposure** — surfaced
/// in scan text output, batch rollups, HTML/SARIF/JUnit rendering,
/// `--gate-critical`, and the TUI's critical highlight. Kept as one
/// list here so scan + batch + output + tui + analyze all agree on
/// what "critical" means without drifting.
pub const CRITICAL_LABELS: &[&str] = &["Autoboot interruptable", "Telnet exposure"];

// ── Detector registry ────────────────────────────────────────────────
//
// Each entry mirrors a browser detector object. Preserve order + labels
// so JSON output stays comparable between browser + CLI.

struct Detector {
    label: &'static str,
    run: fn(&str) -> Option<Finding>,
}

static ALL_DETECTORS: &[Detector] = &[
    Detector {
        label: "Bootloader",
        run: run_bootloader,
    },
    Detector {
        label: "Kernel",
        run: run_kernel,
    },
    Detector {
        label: "CPU / Arch",
        run: run_cpu_arch,
    },
    Detector {
        label: "Init system",
        run: run_init_system,
    },
    Detector {
        label: "Device family",
        run: run_device_family,
    },
    Detector {
        label: "Network",
        run: run_network,
    },
    Detector {
        label: "Web admin",
        run: run_web_admin,
    },
    Detector {
        label: "Telnet exposure",
        run: run_telnet_exposure,
    },
    Detector {
        label: "Autoboot interruptable",
        run: run_autoboot_interruptable,
    },
];

// ── 1. Bootloader ────────────────────────────────────────────────────

// U-Boot line pattern. Multiline `(?m)` so `^` matches the start of
// any line, not just the whole log. Captures the version + build tag.
static RE_UBOOT: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?m)^U-Boot\s+(\S+(?:[-+][\w.+\-]+)?)\s+\(([^)]+)\)").unwrap());
static RE_COREBOOT: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?m)^coreboot-([\w.\-]+)").unwrap());
static RE_GRUB: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?m)^GRUB\s+(?:version\s+)?([\d.]+)").unwrap());
static RE_OPENSBI: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)OpenSBI\s+v?([\d.]+)").unwrap());
static RE_ESP_ROM: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)(rst:0x1\s+\(POWERON_RESET\)|esp_image:|chip is)").unwrap());

fn run_bootloader(log: &str) -> Option<Finding> {
    if let Some(m) = RE_UBOOT.captures(log) {
        let ver = m.get(1)?.as_str();
        let build = m.get(2)?.as_str();
        let source = m.get(0)?.as_str();
        return Some(
            Finding::new("Bootloader", format!("U-Boot {ver}"))
                .detail(build)
                .source(source),
        );
    }
    if let Some(m) = RE_COREBOOT.captures(log) {
        let ver = m.get(1)?.as_str();
        let source = m.get(0)?.as_str();
        return Some(Finding::new("Bootloader", format!("coreboot {ver}")).source(source));
    }
    if let Some(m) = RE_GRUB.captures(log) {
        let ver = m.get(1)?.as_str();
        let source = m.get(0)?.as_str();
        return Some(Finding::new("Bootloader", format!("GRUB {ver}")).source(source));
    }
    if let Some(m) = RE_OPENSBI.captures(log) {
        let ver = m.get(1)?.as_str();
        let source = m.get(0)?.as_str();
        return Some(Finding::new("Bootloader", format!("OpenSBI {ver}")).source(source));
    }
    if let Some(m) = RE_ESP_ROM.captures(log) {
        let source = m.get(0)?.as_str();
        return Some(
            Finding::new("Bootloader", "Espressif ROM bootloader")
                .detail("ESP8266/ESP32")
                .source(source),
        );
    }
    None
}

// ── 2. Kernel ────────────────────────────────────────────────────────

static RE_LINUX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"Linux version\s+(\S+)\s+\([^)]+\)\s+\(([^)]+)\)").unwrap());
static RE_DARWIN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"Darwin Kernel Version\s+([^:]+):").unwrap());
static RE_FREERTOS: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)FreeRTOS\s+(?:Kernel\s+)?V?([\d.]+)").unwrap());
static RE_ZEPHYR: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\*\*\*\s+Booting Zephyr OS build\s+([\w.\-]+)").unwrap());

fn run_kernel(log: &str) -> Option<Finding> {
    if let Some(m) = RE_LINUX.captures(log) {
        let ver = m.get(1)?.as_str();
        let toolchain = m.get(2)?.as_str();
        let source_full = m.get(0)?.as_str();
        // Match the TS slicing: detail truncated at 80, source at 200.
        let detail: String = toolchain.chars().take(80).collect();
        let source: String = source_full.chars().take(200).collect();
        return Some(
            Finding::new("Kernel", format!("Linux {ver}"))
                .detail(detail)
                .source(source),
        );
    }
    if let Some(m) = RE_DARWIN.captures(log) {
        let ver = m.get(1)?.as_str().trim();
        let source = m.get(0)?.as_str();
        return Some(Finding::new("Kernel", format!("Darwin {ver}")).source(source));
    }
    if let Some(m) = RE_FREERTOS.captures(log) {
        let ver = m.get(1)?.as_str();
        let source = m.get(0)?.as_str();
        return Some(Finding::new("Kernel", format!("FreeRTOS {ver}")).source(source));
    }
    if let Some(m) = RE_ZEPHYR.captures(log) {
        let ver = m.get(1)?.as_str();
        let source = m.get(0)?.as_str();
        return Some(Finding::new("Kernel", format!("Zephyr {ver}")).source(source));
    }
    None
}

// ── 3. CPU / Arch ────────────────────────────────────────────────────

static RE_MIPS: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)CPU\s*\d?\s+revision is:\s+\w+\s+\((MIPS\s+[\w\-]+)\)").unwrap()
});
static RE_ARM64: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)Booting Linux on physical CPU.*aarch64|Linux version.*aarch64").unwrap()
});
static RE_ARMV7: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)CPU:\s+ARMv7|Linux version.*\barmv7l\b").unwrap());
static RE_RISCV: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)Linux version.*riscv|hart\s+\d+:\s+running").unwrap());
static RE_X86: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)Linux version.*x86_64").unwrap());
static RE_XTENSA: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)(xtensa|esp32|esp8266)").unwrap());

fn run_cpu_arch(log: &str) -> Option<Finding> {
    if let Some(m) = RE_MIPS.captures(log) {
        return Some(Finding::new("CPU / Arch", m.get(1)?.as_str().to_string()));
    }
    if RE_ARM64.is_match(log) {
        return Some(Finding::new("CPU / Arch", "ARM64 (aarch64)"));
    }
    if RE_ARMV7.is_match(log) {
        return Some(Finding::new("CPU / Arch", "ARMv7 (32-bit)"));
    }
    if RE_RISCV.is_match(log) {
        return Some(Finding::new("CPU / Arch", "RISC-V"));
    }
    if RE_X86.is_match(log) {
        return Some(Finding::new("CPU / Arch", "x86_64"));
    }
    if RE_XTENSA.is_match(log) {
        return Some(Finding::new("CPU / Arch", "Xtensa (ESP)"));
    }
    None
}

// ── 4. Init system ───────────────────────────────────────────────────

static RE_PROCD_START: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?m)^procd:").unwrap());
static RE_PROCD_INIT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"procd:\s+-\s+init").unwrap());
static RE_SYSTEMD: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?m)systemd\[1\]:|Welcome to \w+ Linux").unwrap());
static RE_SYSV: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)INIT:\s+version\s+([\d.]+)").unwrap());
static RE_BUSYBOX_INIT: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"BusyBox v[\d.]+\s+\([^)]+\)\s+built-in shell").unwrap());
static RE_RUNIT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"runit:|runit-init").unwrap());

fn run_init_system(log: &str) -> Option<Finding> {
    if RE_PROCD_START.is_match(log) || RE_PROCD_INIT.is_match(log) {
        return Some(Finding::new("Init system", "procd").detail("OpenWrt-family"));
    }
    if RE_SYSTEMD.is_match(log) {
        return Some(Finding::new("Init system", "systemd"));
    }
    if let Some(m) = RE_SYSV.captures(log) {
        let ver = m.get(1)?.as_str();
        return Some(Finding::new("Init system", format!("SysV init {ver}")));
    }
    if RE_BUSYBOX_INIT.is_match(log) {
        return Some(Finding::new("Init system", "BusyBox init"));
    }
    if RE_RUNIT.is_match(log) {
        return Some(Finding::new("Init system", "runit"));
    }
    None
}

// ── 5. Device family ─────────────────────────────────────────────────

static RE_OPENWRT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)openwrt").unwrap());
static RE_OPENWRT_GCC: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)OpenWrt GCC[^)]*\d{4}-\w+").unwrap());
static RE_OPENWRT_R: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)OpenWrt\s+(r\d+[\-\w]+)").unwrap());
static RE_RPI: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)Raspberry\s*Pi|bcm27\d{2}|bcm28\d{2}").unwrap());
static RE_BUILDROOT: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)buildroot|br-\d{4}").unwrap());
static RE_YOCTO: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)yocto|poky-\w+").unwrap());
static RE_ESP_FAM: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)(esp32|esp8266|esp_image)").unwrap());
static RE_MEDIATEK: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)Mediatek|MT76\d{2}|MT79\d{2}").unwrap());
static RE_QUALCOMM: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)Qualcomm|IPQ\d{4}").unwrap());
static RE_ALLWINNER: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)(Allwinner|sunxi|H\d{1,3}\s+SoC)").unwrap());

fn run_device_family(log: &str) -> Option<Finding> {
    if RE_OPENWRT.is_match(log) {
        // Prefer the GCC-tag line, fall back to the release marker.
        let detail = RE_OPENWRT_GCC
            .find(log)
            .or_else(|| RE_OPENWRT_R.find(log))
            .map(|m| m.as_str().chars().take(80).collect::<String>());
        let mut f = Finding::new("Device family", "OpenWrt");
        if let Some(d) = detail {
            f = f.detail(d);
        }
        return Some(f);
    }
    if RE_RPI.is_match(log) {
        return Some(Finding::new("Device family", "Raspberry Pi family"));
    }
    if RE_BUILDROOT.is_match(log) {
        return Some(Finding::new("Device family", "Buildroot"));
    }
    if RE_YOCTO.is_match(log) {
        return Some(Finding::new("Device family", "Yocto / Poky"));
    }
    if RE_ESP_FAM.is_match(log) {
        return Some(Finding::new("Device family", "Espressif (ESP)"));
    }
    if RE_MEDIATEK.is_match(log) {
        return Some(Finding::new("Device family", "MediaTek SoC"));
    }
    if RE_QUALCOMM.is_match(log) {
        return Some(Finding::new("Device family", "Qualcomm IPQ"));
    }
    if RE_ALLWINNER.is_match(log) {
        return Some(Finding::new("Device family", "Allwinner sunxi"));
    }
    None
}

// ── 6. Network ───────────────────────────────────────────────────────

static RE_DHCP: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)DHCP\s+(?:client\s+)?bound to address\s+([\d.]+)").unwrap());
static RE_DNSMASQ: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)dnsmasq\[\d+\]:\s+started,\s+version\s+([\d.]+)").unwrap());
static RE_DROPBEAR: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)dropbear\[\d+\]").unwrap());

fn run_network(log: &str) -> Option<Finding> {
    if let Some(m) = RE_DHCP.captures(log) {
        let ip = m.get(1)?.as_str();
        let source = m.get(0)?.as_str();
        return Some(
            Finding::new("Network", "DHCP client active")
                .detail(format!("Lease: {ip}"))
                .source(source),
        );
    }
    if let Some(m) = RE_DNSMASQ.captures(log) {
        let ver = m.get(1)?.as_str();
        let source = m.get(0)?.as_str();
        return Some(Finding::new("Network", format!("dnsmasq {ver} active")).source(source));
    }
    if let Some(m) = RE_DROPBEAR.find(log) {
        return Some(Finding::new("Network", "Dropbear SSH started").source(m.as_str()));
    }
    None
}

// ── 7. Web admin ─────────────────────────────────────────────────────

static RE_UHTTPD: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)uhttpd\[\d+\]:\s+Listening on\s+([\d.:]+)").unwrap());
static RE_LIGHTTPD: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)lighttpd/([\d.]+)").unwrap());
static RE_NGINX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)nginx/([\d.]+)").unwrap());

fn run_web_admin(log: &str) -> Option<Finding> {
    if let Some(m) = RE_UHTTPD.captures(log) {
        let listen = m.get(1)?.as_str();
        let source = m.get(0)?.as_str();
        return Some(
            Finding::new("Web admin", "uhttpd active")
                .detail(format!("Listen: {listen}"))
                .source(source),
        );
    }
    if let Some(m) = RE_LIGHTTPD.captures(log) {
        let ver = m.get(1)?.as_str();
        let source = m.get(0)?.as_str();
        return Some(Finding::new("Web admin", format!("lighttpd {ver}")).source(source));
    }
    if let Some(m) = RE_NGINX.captures(log) {
        let ver = m.get(1)?.as_str();
        let source = m.get(0)?.as_str();
        return Some(Finding::new("Web admin", format!("nginx {ver}")).source(source));
    }
    None
}

// ── 8. Telnet exposure ───────────────────────────────────────────────

static RE_TELNET: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)telnetd?\[\d+\]?[^\n]*?(?:listening|started|on\s+\d)").unwrap()
});

fn run_telnet_exposure(log: &str) -> Option<Finding> {
    if let Some(m) = RE_TELNET.find(log) {
        return Some(
            Finding::new("Telnet exposure", "Telnet service started")
                .detail("Clear-text, review immediately")
                .source(m.as_str()),
        );
    }
    None
}

// ── 9. Autoboot interruptable ────────────────────────────────────────

static RE_AUTOBOOT_ANY: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"Hit any key to stop autoboot:\s*[1-9]").unwrap());
static RE_AUTOBOOT_CAP: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"Hit any key to stop autoboot:\s*\d+").unwrap());

fn run_autoboot_interruptable(log: &str) -> Option<Finding> {
    if RE_AUTOBOOT_ANY.is_match(log) {
        // Second regex is broader (matches 0 too) so we can capture the
        // actual matched source line — matches the TS behavior which
        // does the same two-step.
        if let Some(m) = RE_AUTOBOOT_CAP.find(log) {
            return Some(
                Finding::new("Autoboot interruptable", "Yes")
                    .detail("U-Boot will accept any key during the countdown")
                    .source(m.as_str()),
            );
        }
    }
    None
}