hashglass 0.1.0

Fast pentester-focused hash identifier — mode + cost + ready hashcat command. Handles secretsdump / containers / mixed dumps. Identification only.
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
//! M3 — file / stdin batch identification.
//!
//! Reads line by line (streaming, so a million-line dump costs no extra
//! memory), identifies each line, prints a compact per-line result, and ends
//! with a grouped-by-mode summary.
//!
//! Line parsing folds in the one piece of *context* that carries its weight in
//! AD work: a pwdump / secretsdump line `user:rid:LM:NT:::` is recognized by
//! shape, and its NT/LM fields are **pinned** to modes 1000/3000 with full
//! confidence — instead of being fed to the bare-hex tier, where a 32-hex NT
//! hash would come back as an ambiguous MD5/NTLM/MD4 guess. The line shape
//! resolves what the token alone cannot.

use crate::hex::is_hex;
use crate::identify::{Candidate, Opts, identify_with};
use crate::output::AMBIGUOUS_BELOW;
use std::collections::{BTreeMap, HashMap};
use std::fs::{self, File};
use std::io::{BufRead, BufWriter, Write};
use std::path::Path;

/// One hash found on a line, with any context label and its candidates.
pub struct HashHit {
    /// The raw hash token.
    pub token: String,
    /// Context label, e.g. `NT: Administrator` for a pwdump field.
    pub label: Option<String>,
    /// Ranked candidates (empty = unrecognized).
    pub candidates: Vec<Candidate>,
}

/// Batch run configuration.
pub struct Cfg {
    /// Reveal rarer hex modes (`--all`).
    pub all: bool,
    /// Emit NDJSON instead of text.
    pub json: bool,
    /// Suppress per-line output, print only the final summary.
    pub summary_only: bool,
    /// Suppress the ambiguous bare-hex tier (`--strict`).
    pub strict: bool,
    /// Consider the opt-in salted `hash:salt` family (`--salted`).
    pub salted: bool,
    /// Loaded hashcat potfile — skip hashes already cracked in a prior
    /// hashcat run against the same dump. `None` = no potfile, everything
    /// gets identified.
    pub pot: Option<crate::potfile::Pot>,
}

impl Cfg {
    fn opts(&self) -> Opts {
        Opts {
            all: self.all,
            strict: self.strict,
            salted: self.salted,
        }
    }
}

/// Tallies accumulated across a batch run.
#[derive(Default)]
pub struct Summary {
    /// Content lines processed (blank / `#`-comment lines excluded).
    pub lines: usize,
    /// Hits with at least one candidate.
    pub hits: usize,
    /// Hits with no candidate.
    pub unrecognized: usize,
    /// Hits skipped because the hash is already in the loaded potfile.
    pub skipped_pot: usize,
    /// mode → (name, count) over each hit's top candidate.
    pub by_mode: BTreeMap<u32, (&'static str, usize)>,
}

const EMPTY_LM: &str = "aad3b435b51404eeaad3b435b51404ee";

/// Analyze one line into zero or more hits.
///
/// Returns empty for blank or `#`-comment lines. A recognized pwdump /
/// secretsdump line yields its NT (and non-empty LM) fields pinned to
/// NTLM/LM; every other line is identified as a single token.
pub fn analyze_line(line: &str, opts: Opts) -> Vec<HashHit> {
    // Slice 8 — surface cleaning first (BOM, CRLF, indent, wrapping quotes,
    // trailing comma). Anything downstream sees a normal-looking token.
    let t = crate::extract::clean(line);
    if t.is_empty()
        || t.starts_with('#')
        // impacket / secretsdump banner lines: `[*] Dumping…`, `[+] …`, `[-] …`
        || (t.starts_with('[') && t.len() >= 3 && matches!(t.as_bytes()[1], b'*' | b'+' | b'-') && t.as_bytes()[2] == b']')
    {
        return Vec::new();
    }

    // pwdump / secretsdump line — pin NT/LM, no ambiguity.
    if let Some(hits) = parse_pwdump(t) {
        return hits;
    }

    // Direct identify on the cleaned line — the common case.
    let direct = identify_with(t, opts);
    if !direct.is_empty() {
        return vec![HashHit {
            token: t.to_string(),
            label: None,
            candidates: direct,
        }];
    }

    // Label-stripped: `NT: <hex>`, `password = $2a$…`, `"nthash": "<hex>"`.
    if let Some(v) = crate::extract::strip_label(t) {
        let cs = identify_with(v, opts);
        if !cs.is_empty() {
            return vec![HashHit {
                token: v.to_string(),
                label: None,
                candidates: cs,
            }];
        }
    }

    // Embedded extract — hashes buried in JSON/CSV/hashcat-show output.
    // Multiple hits per line are legitimate here (a CSV row with two hashes).
    let mut hits = Vec::new();
    for cand in crate::extract::extract_candidates(t) {
        let cs = identify_with(&cand, opts);
        if !cs.is_empty() {
            hits.push(HashHit {
                token: cand,
                label: None,
                candidates: cs,
            });
        }
    }
    if !hits.is_empty() {
        return hits;
    }

    // Nothing matched. Return one HashHit with empty candidates so the batch
    // summary can still count it as "unrecognized".
    vec![HashHit {
        token: t.to_string(),
        label: None,
        candidates: Vec::new(),
    }]
}

/// Recognize `user:rid:LM:NT:::` by shape and pin NT/LM. `None` if the line
/// isn't that shape (numeric RID, two 32-hex fields).
fn parse_pwdump(line: &str) -> Option<Vec<HashHit>> {
    // Try a Kerberos-key line first — `user:aes256-cts-hmac-sha1-96:<hex>` etc.
    // These aren't pwdump-shaped (no RID), but they arrive in the same
    // secretsdump output and are the AD wedge nobody else parses.
    if let Some(hits) = parse_kerberos_key(line) {
        return Some(hits);
    }

    let f: Vec<&str> = line.split(':').collect();
    if f.len() < 4 {
        return None;
    }
    let (user_raw, rid, lm, nt) = (f[0], f[1], f[2], f[3]);
    if rid.is_empty() || !rid.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    if lm.len() != 32 || !is_hex(lm) || nt.len() != 32 || !is_hex(nt) {
        return None;
    }

    // Slice 9 — recognize the two variants secretsdump emits that the M3
    // parser ignored:
    //   `SERVER$:1001:aad3…:<nt>:::`      → machine account
    //   `user_history0:1001:aad3…:<nt>:::` → history entry (still crackable)
    // Extract them into cleaner labels; the mode itself stays NTLM/LM.
    let (user, tag) = if let Some(stem) = user_raw.strip_suffix('$') {
        (stem, Some("$MACHINE.ACC"))
    } else if let Some((stem, hist)) = split_history_suffix(user_raw) {
        (stem, Some(hist))
    } else {
        (user_raw, None)
    };

    let nt_label = match tag {
        Some(t) => format!("NT: {user} [{t}]"),
        None => format!("NT: {user}"),
    };
    let mut hits = vec![HashHit {
        token: nt.to_string(),
        label: Some(nt_label),
        candidates: vec![Candidate {
            mode: 1000,
            name: "NTLM",
            confidence: 0.99,
        }],
    }];
    if !lm.eq_ignore_ascii_case(EMPTY_LM) {
        let lm_label = match tag {
            Some(t) => format!("LM: {user} [{t}]"),
            None => format!("LM: {user}"),
        };
        hits.push(HashHit {
            token: lm.to_string(),
            label: Some(lm_label),
            candidates: vec![Candidate {
                mode: 3000,
                name: "LM",
                confidence: 0.99,
            }],
        });
    }
    Some(hits)
}

/// `bob_history0` → `("bob", "history 0")`. Returns `None` if the suffix isn't
/// recognized so callers can treat the user string as literal.
fn split_history_suffix(user: &str) -> Option<(&str, &'static str)> {
    let stem_end = user.rfind("_history")?;
    let tail = &user[stem_end + "_history".len()..];
    // secretsdump's history suffix is a single digit; if it isn't, this isn't
    // actually a history line — leave the raw name intact.
    if tail.len() == 1
        && tail
            .chars()
            .next()
            .map(|c| c.is_ascii_digit())
            .unwrap_or(false)
    {
        let label: &'static str = match tail {
            "0" => "history 0",
            "1" => "history 1",
            "2" => "history 2",
            "3" => "history 3",
            _ => "history",
        };
        Some((&user[..stem_end], label))
    } else {
        None
    }
}

/// Recognize a secretsdump Kerberos-key line:
///   `Administrator:aes256-cts-hmac-sha1-96:<hex64>`
///   `Administrator:aes128-cts-hmac-sha1-96:<hex32>`
///   `Administrator:des-cbc-md5:<hex16>`
/// Etype string → hashcat mode:
///   aes256… → 19700 (TGS-REP)  aes128… → 19600  des-cbc-md5 → 19600 fallback
///
/// This is the AD wedge: hashcat's --identify sees only the hex; nothing tells
/// it it's a Kerberos key. Line-shape context resolves it.
fn parse_kerberos_key(line: &str) -> Option<Vec<HashHit>> {
    let (user, rest) = line.split_once(':')?;
    let (etype, hex) = rest.split_once(':')?;
    if user.is_empty() || !is_hex(hex) {
        return None;
    }
    let (mode, name, note): (u32, &'static str, &'static str) = match etype {
        "aes256-cts-hmac-sha1-96" if hex.len() == 64 => {
            (19700, "Kerberos 5 TGS-REP aes256 (key)", "aes256 key")
        }
        "aes128-cts-hmac-sha1-96" if hex.len() == 32 => {
            (19600, "Kerberos 5 TGS-REP aes128 (key)", "aes128 key")
        }
        // des-cbc-md5 keys arrive alongside AES in AD dumps but have no
        // hashcat mode. Return an EMPTY hits vec so analyze_line short-
        // circuits (line is "recognized but nothing to crack") instead of
        // falling through to bare-hex where 16 hex hits MySQL323 as a
        // false positive.
        "des-cbc-md5" if hex.len() == 16 => return Some(Vec::new()),
        _ => return None,
    };
    Some(vec![HashHit {
        token: hex.to_string(),
        label: Some(format!("Krb {note}: {user}")),
        candidates: vec![Candidate {
            mode,
            name,
            confidence: 0.99,
        }],
    }])
}

/// Emit the raw token of every hit whose **top** candidate is `mode`, one per
/// line — nothing else on stdout, so it pipes straight into hashcat:
///   `hashglass --only 1000 dump.txt | hashcat -m 1000 - wordlist`
/// Returns how many tokens were emitted.
pub fn filter_only(
    reader: impl BufRead,
    mode: u32,
    opts: Opts,
    out: &mut impl Write,
) -> std::io::Result<usize> {
    let mut n = 0usize;
    for line in reader.lines() {
        let line = line?;
        for hit in analyze_line(&line, opts) {
            if hit.candidates.first().map(|c| c.mode) == Some(mode) {
                writeln!(out, "{}", hit.token)?;
                n += 1;
            }
        }
    }
    Ok(n)
}

/// What `split` wrote, for the follow-up summary + command list.
pub struct SplitReport {
    /// `dir` as given, for building the printed commands.
    pub dir: String,
    /// mode → (name, count) of tokens written to `<dir>/<mode>.txt`.
    pub by_mode: BTreeMap<u32, (&'static str, usize)>,
    /// Count written to `<dir>/unknown.txt`.
    pub unknown: usize,
    /// Count skipped because the hash was already in the potfile.
    pub skipped_pot: usize,
}

/// Create a file with owner-only permissions (0600 on Unix). NT hashes,
/// Kerberos AES keys, and secretsdump excerpts are sensitive credentials —
/// leaving them world-readable on a shared box (student lab, jump host,
/// engagement dropbox) is a real leak. Windows uses ACLs; the default is
/// already restricted to the owner + Administrators, so no explicit tightening
/// needed there.
fn create_owner_only(path: &Path) -> std::io::Result<File> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .mode(0o600)
            .open(path)
    }
    #[cfg(not(unix))]
    {
        File::create(path)
    }
}

/// Split a dump into one file per top-mode under `dir` (`<mode>.txt`, plus
/// `unknown.txt`), each holding raw tokens ready for hashcat. Streaming: file
/// handles are held open across the pass.
///
/// Output files are created with owner-only permissions (0600 on Unix) —
/// these files can contain live NTLM hashes and Kerberos AES keys from a
/// secretsdump; other users on the box must not read them.
///
/// If `pot` is provided, hashes already cracked in that potfile are skipped
/// entirely — not written to any output file. Reduces mid-engagement re-runs
/// to only the still-uncracked tail.
pub fn split(
    reader: impl BufRead,
    dir: &Path,
    opts: Opts,
    pot: Option<&crate::potfile::Pot>,
) -> std::io::Result<SplitReport> {
    fs::create_dir_all(dir)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        // Tighten the containing dir too — 0700 = owner-only rwx. Silent-fail
        // if the dir already exists with tighter perms (best-effort).
        let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
    }
    let mut writers: HashMap<u32, BufWriter<File>> = HashMap::new();
    let mut by_mode: BTreeMap<u32, (&'static str, usize)> = BTreeMap::new();
    let mut unknown_writer: Option<BufWriter<File>> = None;
    let mut unknown = 0usize;
    let mut skipped_pot = 0usize;

    for line in reader.lines() {
        let line = line?;
        for hit in analyze_line(&line, opts) {
            // Pot-skip: never write already-cracked hashes to the split
            // output. Saves disk, saves the reviewer's time, saves
            // re-suggesting a solved item.
            if let Some(pot) = pot
                && pot.contains(&hit.token)
            {
                skipped_pot += 1;
                continue;
            }
            match hit.candidates.first() {
                Some(top) => {
                    let writer = match writers.entry(top.mode) {
                        std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),
                        std::collections::hash_map::Entry::Vacant(e) => {
                            let f = create_owner_only(&dir.join(format!("{}.txt", top.mode)))?;
                            e.insert(BufWriter::new(f))
                        }
                    };
                    writeln!(writer, "{}", hit.token)?;
                    by_mode.entry(top.mode).or_insert((top.name, 0)).1 += 1;
                }
                None => {
                    if unknown_writer.is_none() {
                        unknown_writer =
                            Some(BufWriter::new(create_owner_only(&dir.join("unknown.txt"))?));
                    }
                    writeln!(unknown_writer.as_mut().unwrap(), "{}", hit.token)?;
                    unknown += 1;
                }
            }
        }
    }

    for (_, mut w) in writers {
        w.flush()?;
    }
    if let Some(mut w) = unknown_writer {
        w.flush()?;
    }
    Ok(SplitReport {
        dir: dir.to_string_lossy().into_owned(),
        by_mode,
        unknown,
        skipped_pot,
    })
}

/// Print the split summary with a ready-to-run hashcat command per mode.
pub fn render_split(rep: &SplitReport, out: &mut impl Write) -> std::io::Result<()> {
    writeln!(out, "wrote {} mode(s) to {}/", rep.by_mode.len(), rep.dir)?;
    let wl = crate::wordlist::substitute();
    let mut rows: Vec<(&u32, &(&'static str, usize))> = rep.by_mode.iter().collect();
    rows.sort_by(|a, b| b.1.1.cmp(&a.1.1).then(a.0.cmp(b.0)));
    for (mode, (name, count)) in rows {
        writeln!(
            out,
            "  -m {:<6} {:<20} {:>7}  ->  hashcat -m {} {}/{}.txt {}",
            mode,
            preview(name, 20),
            count,
            mode,
            rep.dir,
            mode,
            wl
        )?;
        // Cost line (slice 6). Silent when the mode has no data — never guess.
        let one = crate::cost::oneliner(*mode);
        if !one.is_empty() {
            writeln!(out, "         {one}")?;
        }
    }
    if rep.unknown > 0 {
        writeln!(
            out,
            "  {:<9} {:<20} {:>7}  ->  {}/unknown.txt  (try: hashcat --identify)",
            "unknown", "", rep.unknown, rep.dir
        )?;
    }
    if rep.skipped_pot > 0 {
        writeln!(
            out,
            "  (skipped {} hash(es) already in hashcat potfile)",
            rep.skipped_pot
        )?;
    }
    // Wordlist hint at the tail (silent when a wordlist was found).
    let h = crate::wordlist::hint();
    if !h.is_empty() {
        writeln!(out, "{h}")?;
    }
    Ok(())
}

/// Run a batch over `reader`, writing results to `out`. Returns the summary.
pub fn run(reader: impl BufRead, cfg: &Cfg, out: &mut impl Write) -> std::io::Result<Summary> {
    let mut sum = Summary::default();
    let mut line_no = 0usize;
    let opts = cfg.opts();

    for line in reader.lines() {
        let line = line?;
        line_no += 1;
        let hits = analyze_line(&line, opts);
        if hits.is_empty() {
            continue; // blank / comment
        }
        sum.lines += 1;

        for hit in &hits {
            // --pot filter: skip anything already cracked. Applies to
            // recognized hits only; unrecognized lines never had a hash
            // token to match against.
            if let Some(pot) = &cfg.pot
                && pot.contains(&hit.token)
            {
                sum.skipped_pot += 1;
                continue;
            }
            if hit.candidates.is_empty() {
                sum.unrecognized += 1;
            } else {
                sum.hits += 1;
                let top = &hit.candidates[0];
                sum.by_mode.entry(top.mode).or_insert((top.name, 0)).1 += 1;
            }
            if cfg.summary_only {
                continue;
            }
            if cfg.json {
                write_hit_json(out, line_no, hit)?;
            } else {
                write_hit_text(out, line_no, hit)?;
            }
        }
    }

    write_summary(out, cfg, &sum)?;
    Ok(sum)
}

fn write_hit_text(out: &mut impl Write, line_no: usize, hit: &HashHit) -> std::io::Result<()> {
    if hit.candidates.is_empty() {
        return writeln!(
            out,
            "  line {:<5} ??      unrecognized          {}",
            line_no,
            preview(&hit.token, 40)
        );
    }
    let top = &hit.candidates[0];
    let more = hit.candidates.len() - 1;
    let more_s = if more > 0 {
        format!(" +{more}")
    } else {
        String::new()
    };
    let ambig = if top.confidence < AMBIGUOUS_BELOW {
        " ?"
    } else {
        ""
    };
    let typ = preview(&format!("{}{}{}", top.name, more_s, ambig), 22);
    let tail = match &hit.label {
        Some(l) => format!("[{l}]"),
        None => preview(&hit.token, 40),
    };
    writeln!(
        out,
        "  line {:<5} -m {:<6} {:<22} {}",
        line_no, top.mode, typ, tail
    )
}

fn write_hit_json(out: &mut impl Write, line_no: usize, hit: &HashHit) -> std::io::Result<()> {
    let candidates: Vec<serde_json::Value> = hit
        .candidates
        .iter()
        .map(|c| {
            serde_json::json!({
                "mode": c.mode,
                "name": c.name,
                "hashcat": format!("-m {}", c.mode),
                "confidence": ((c.confidence as f64) * 100.0).round() / 100.0,
            })
        })
        .collect();
    let obj = serde_json::json!({
        "line": line_no,
        "token": hit.token,
        "label": hit.label,
        "candidates": candidates,
    });
    writeln!(out, "{}", serde_json::to_string(&obj).unwrap_or_default())
}

fn write_summary(out: &mut impl Write, cfg: &Cfg, sum: &Summary) -> std::io::Result<()> {
    if cfg.json {
        let by: serde_json::Map<String, serde_json::Value> = sum
            .by_mode
            .iter()
            .map(|(mode, (_, count))| (mode.to_string(), serde_json::json!(count)))
            .collect();
        let obj = serde_json::json!({
            "summary": {
                "lines": sum.lines,
                "hits": sum.hits,
                "unrecognized": sum.unrecognized,
                "skipped_pot": sum.skipped_pot,
                "by_mode": by,
            }
        });
        return writeln!(out, "{}", serde_json::to_string(&obj).unwrap_or_default());
    }

    writeln!(out)?;
    writeln!(
        out,
        "summary: {} line(s), {} hit(s) identified, {} unrecognized",
        sum.lines, sum.hits, sum.unrecognized
    )?;
    if sum.skipped_pot > 0 {
        writeln!(
            out,
            "  (skipped {} hash(es) already in hashcat potfile)",
            sum.skipped_pot
        )?;
    }
    let mut rows: Vec<(&u32, &(&'static str, usize))> = sum.by_mode.iter().collect();
    rows.sort_by(|a, b| b.1.1.cmp(&a.1.1).then(a.0.cmp(b.0)));
    for (mode, (name, count)) in rows {
        writeln!(out, "  -m {:<6} {:<22} {}", mode, preview(name, 22), count)?;
    }
    Ok(())
}

fn preview(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        s.to_string()
    } else {
        let head: String = s.chars().take(max.saturating_sub(1)).collect();
        format!("{head}…")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    #[test]
    fn blank_and_comment_lines_are_skipped() {
        assert!(analyze_line("", Opts::default()).is_empty());
        assert!(analyze_line("   ", Opts::default()).is_empty());
        assert!(analyze_line("# a comment", Opts::default()).is_empty());
    }

    #[test]
    fn secretsdump_line_pins_nt_and_suppresses_empty_lm() {
        // Administrator with empty password: empty LM sentinel + empty-pw NT.
        let hits = analyze_line(
            "Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::",
            Opts::default(),
        );
        assert_eq!(hits.len(), 1, "empty LM must be suppressed");
        assert_eq!(hits[0].candidates[0].mode, 1000);
        assert!(
            hits[0].candidates[0].confidence > 0.9,
            "context pins NT to NTLM"
        );
        assert_eq!(hits[0].label.as_deref(), Some("NT: Administrator"));
    }

    #[test]
    fn secretsdump_line_emits_lm_when_present() {
        let hits = analyze_line(
            "bob:1001:e52cac67419a9a224a3b108f3fa6cb6d:8846f7eaee8fb117ad06bdd830b7586c:::",
            Opts::default(),
        );
        assert_eq!(hits.len(), 2);
        assert_eq!(hits[0].candidates[0].mode, 1000); // NT first
        assert_eq!(hits[1].candidates[0].mode, 3000); // LM second
    }

    #[test]
    fn machine_account_line_tags_the_label() {
        let hits = analyze_line(
            "SERVER$:1001:aad3b435b51404eeaad3b435b51404ee:8846f7eaee8fb117ad06bdd830b7586c:::",
            Opts::default(),
        );
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].candidates[0].mode, 1000);
        let label = hits[0].label.as_deref().unwrap_or("");
        assert!(label.contains("SERVER"), "want stem, got {label:?}");
        assert!(label.contains("MACHINE"), "want machine tag, got {label:?}");
    }

    #[test]
    fn history_suffix_is_labelled() {
        let hits = analyze_line(
            "bob_history0:1101:aad3b435b51404eeaad3b435b51404ee:8846f7eaee8fb117ad06bdd830b7586c:::",
            Opts::default(),
        );
        assert_eq!(hits[0].candidates[0].mode, 1000);
        let label = hits[0].label.as_deref().unwrap_or("");
        assert!(label.contains("bob"));
        assert!(label.contains("history 0"));
    }

    #[test]
    fn kerberos_aes256_key_line_pins_to_19700() {
        let hits = analyze_line(
            "Administrator:aes256-cts-hmac-sha1-96:5c9d20d8c1c62c5476a1cee2ea8c8bd75d15edcf1d5c5a45b2b74d17b34ac47a",
            Opts::default(),
        );
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].candidates[0].mode, 19700);
        let label = hits[0].label.as_deref().unwrap_or("");
        assert!(label.contains("aes256"));
        assert!(label.contains("Administrator"));
    }

    #[test]
    fn kerberos_aes128_key_line_pins_to_19600() {
        let hits = analyze_line(
            "svc_web:aes128-cts-hmac-sha1-96:a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6",
            Opts::default(),
        );
        assert_eq!(hits[0].candidates[0].mode, 19600);
    }

    #[test]
    fn netntlmv2_line_is_not_mistaken_for_pwdump() {
        // Empty RID field -> not a pwdump line -> identified normally as 5600.
        let hits = analyze_line(
            "admin::N46iSNekpT:08ca45b7d7ea58ee:88dcbe4446168966a153a0064958dac6:5c7830315c7830310000000000000b45c67103d07d7b95acd12ffa11230e0000000052920b85f78d013c31cdb3b92f5d765c783030",
            Opts::default(),
        );
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].candidates[0].mode, 5600);
    }

    #[test]
    fn bare_hex_line_stays_ambiguous() {
        let hits = analyze_line("8743b52063cd84097a65d1633f5c74f5", Opts::default());
        assert_eq!(hits[0].candidates[0].mode, 0);
        assert!(hits[0].candidates[0].confidence < 0.6);
    }

    #[test]
    fn run_tallies_summary() {
        let dump = "\
# dump
Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
$1$28772684$iEwNOgGugqO9.bIz5sk8k/

garbage-not-a-hash-token
";
        let cfg = Cfg {
            all: false,
            json: false,
            summary_only: true,
            strict: false,
            salted: false,
            pot: None,
        };
        let mut out = Vec::new();
        let sum = run(Cursor::new(dump), &cfg, &mut out).unwrap();
        assert_eq!(sum.lines, 3); // comment + blank excluded
        assert_eq!(sum.hits, 2); // NTLM + md5crypt
        assert_eq!(sum.unrecognized, 1); // the garbage line
        assert_eq!(sum.by_mode.get(&1000).map(|v| v.1), Some(1));
        assert_eq!(sum.by_mode.get(&500).map(|v| v.1), Some(1));
    }

    #[test]
    fn filter_only_emits_just_matching_tokens() {
        let dump = "\
Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
$1$28772684$iEwNOgGugqO9.bIz5sk8k/
bob:1001:e52cac67419a9a224a3b108f3fa6cb6d:8846f7eaee8fb117ad06bdd830b7586c:::
";
        let mut out = Vec::new();
        let n = filter_only(Cursor::new(dump), 1000, Opts::default(), &mut out).unwrap();
        let text = String::from_utf8(out).unwrap();
        assert_eq!(n, 2, "two NT hashes");
        // Only raw NT tokens, nothing else — ready to pipe to hashcat -m 1000.
        assert_eq!(
            text,
            "31d6cfe0d16ae931b73c59d7e0c089c0\n8846f7eaee8fb117ad06bdd830b7586c\n"
        );
    }

    #[test]
    fn split_writes_one_file_per_mode() {
        let dir = std::env::temp_dir().join("hashglass_test_split_slice2");
        let _ = fs::remove_dir_all(&dir);
        let dump = "\
Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
svc:1104:aad3b435b51404eeaad3b435b51404ee:e19ccf75ee54e06b06a5907af13cef42:::
$2a$05$LhayLxezLhK1LhWvKxCyLOj0j1u.Kj0jZ0pEmm134uzrQlFvQJLF6
notahash
";
        let rep = split(Cursor::new(dump), &dir, Opts::default(), None).unwrap();
        assert_eq!(rep.by_mode.get(&1000).map(|v| v.1), Some(2)); // two NT
        assert_eq!(rep.by_mode.get(&3200).map(|v| v.1), Some(1)); // one bcrypt
        assert_eq!(rep.unknown, 1);
        let nt = fs::read_to_string(dir.join("1000.txt")).unwrap();
        assert_eq!(nt.lines().count(), 2);
        assert!(dir.join("unknown.txt").exists());
        // command list mentions the ready hashcat invocation
        let mut buf = Vec::new();
        render_split(&rep, &mut buf).unwrap();
        assert!(String::from_utf8(buf).unwrap().contains("hashcat -m 1000"));
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn run_ndjson_is_line_delimited_valid_json() {
        let cfg = Cfg {
            all: false,
            json: true,
            summary_only: false,
            strict: false,
            salted: false,
            pot: None,
        };
        let mut out = Vec::new();
        run(
            Cursor::new("$1$28772684$iEwNOgGugqO9.bIz5sk8k/\n"),
            &cfg,
            &mut out,
        )
        .unwrap();
        let text = String::from_utf8(out).unwrap();
        for line in text.lines() {
            serde_json::from_str::<serde_json::Value>(line).expect("each NDJSON line valid JSON");
        }
    }
}