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
//! Identification: run the compiled ruleset over one hash string and return
//! ranked candidates. No cracking, no I/O.

use crate::rules::{COMPILED, CompiledRule, SALTED_COMPILED};

/// A single ranked identification result.
#[derive(Debug, Clone, PartialEq)]
pub struct Candidate {
    /// hashcat `-m` mode number — paste straight into hashcat.
    pub mode: u32,
    /// Human-readable hash-type name.
    pub name: &'static str,
    /// Confidence in [0,1].
    pub confidence: f32,
}

/// Identification options.
#[derive(Clone, Copy, Default)]
pub struct Opts {
    /// Reveal rarer same-length hex modes.
    pub all: bool,
    /// Suppress the ambiguous bare-hex tier entirely — only structured/prefixed
    /// matches return. A bare 40-hex (a git SHA, say) becomes "no match"
    /// instead of a SHA-1 guess. This is the false-positive rail.
    pub strict: bool,
    /// Consider the opt-in `hash:salt` salted family (off by default because
    /// `<hex>:<anything>` collides with `checksum:filename` and friends).
    pub salted: bool,
}

fn push_matches(compiled: &[CompiledRule], s: &str, out: &mut Vec<Candidate>) {
    for c in compiled {
        if c.regex.is_match(s) {
            for &mode in c.rule.modes {
                out.push(Candidate {
                    mode,
                    name: c.rule.name,
                    confidence: c.rule.base_confidence,
                });
            }
        }
    }
}

/// Fast-path: cheap `starts_with` dispatch for the ~5 highest-frequency
/// structured prefixes. A hit means we skip the regex tier entirely — no
/// `LazyLock` first-touch cost (which compiles all ~40 regexes, ~60ms on cold
/// process). This is the whole point of slice-9: single-hash CLI usage
/// (`hashglass "$1$..."`) never pays the regex-compile tax.
///
/// Returns `Some(candidates)` if the prefix uniquely identified a mode.
/// Returns `None` if the input needs full regex evaluation.
///
/// Discipline: only include prefixes where a naive shape check (prefix + rough
/// length) is unambiguous. Anything ambiguous falls through to regex where the
/// stricter pattern applies. Correctness > speed.
fn fast_prefix(s: &str) -> Option<Vec<Candidate>> {
    // bcrypt — `$2a$/2b$/2y$/2x$NN$<53 base64-ish>`
    if let Some(rest) = s.strip_prefix("$2")
        && rest.len() >= 58
        && matches!(rest.as_bytes()[0], b'a' | b'b' | b'y' | b'x')
        && rest.as_bytes()[1] == b'$'
    {
        return Some(vec![Candidate {
            mode: 3200,
            name: "bcrypt (Blowfish, Unix) $2*$",
            confidence: 0.99,
        }]);
    }
    // md5crypt — `$1$<salt>$<hash>`, ends after two more `$`
    if let Some(rest) = s.strip_prefix("$1$")
        && rest.contains('$')
        && rest.len() >= 24
    {
        return Some(vec![Candidate {
            mode: 500,
            name: "md5crypt / MD5(Unix) / Cisco-IOS $1$",
            confidence: 0.99,
        }]);
    }
    // sha512crypt — `$6$[rounds=N$]<salt>$<86-char hash>`
    if let Some(rest) = s.strip_prefix("$6$")
        && rest.contains('$')
        && rest.len() >= 88
    {
        return Some(vec![Candidate {
            mode: 1800,
            name: "sha512crypt / SHA512(Unix) $6$",
            confidence: 0.99,
        }]);
    }
    // sha256crypt — `$5$[rounds=N$]<salt>$<43-char hash>`
    if let Some(rest) = s.strip_prefix("$5$")
        && rest.contains('$')
        && rest.len() >= 45
    {
        return Some(vec![Candidate {
            mode: 7400,
            name: "sha256crypt / SHA256(Unix) $5$",
            confidence: 0.99,
        }]);
    }
    // phpass — `$P$` or `$H$` followed by 31 chars total 34 length
    if (s.starts_with("$P$") || s.starts_with("$H$")) && s.len() == 34 {
        return Some(vec![Candidate {
            mode: 400,
            name: "phpass (WordPress / phpBB3 / Joomla)",
            confidence: 0.99,
        }]);
    }
    None
}

/// Identify a single hash string.
///
/// Runs the structured (M1) ruleset, then the bare-hex (M2) tier — the two are
/// mutually exclusive in practice, since every structured shape contains a
/// non-hex delimiter. Results are sorted by confidence (desc), then mode
/// number (asc) as a stable tiebreak; the capped hex confidences guarantee a
/// structured match always ranks first. `all` reveals the rarer hex modes for
/// a given length. An empty vec means neither tier recognized the input.
pub fn identify(input: &str, all: bool) -> Vec<Candidate> {
    identify_with(
        input,
        Opts {
            all,
            ..Opts::default()
        },
    )
}

/// Identify with explicit [`Opts`] (strict / salted control).
pub fn identify_with(input: &str, opts: Opts) -> Vec<Candidate> {
    let s = input.trim();

    // Fast-path (slice 9): if a common prefix matches unambiguously, skip the
    // regex tier entirely — no LazyLock first-touch cost. Only takes effect
    // when the user isn't asking for --salted (salted rules can co-fire on
    // some prefixed formats, so we need the full regex sweep in that case).
    if !opts.salted
        && let Some(mut cs) = fast_prefix(s)
    {
        // A structured match already outranks any bare-hex tier fallout — no
        // need to run hex::classify since these prefixes contain `$`.
        cs.sort_by(|a, b| {
            b.confidence
                .partial_cmp(&a.confidence)
                .unwrap_or(std::cmp::Ordering::Equal)
                .then(a.mode.cmp(&b.mode))
        });
        return cs;
    }

    let mut out: Vec<Candidate> = Vec::new();
    push_matches(&COMPILED, s, &mut out);
    if opts.salted {
        push_matches(&SALTED_COMPILED, s, &mut out);
    }
    // The bare-hex tier is the only ambiguous, false-positive-prone stage;
    // --strict drops it so a bare hex string is never claimed as a hash.
    if !opts.strict {
        out.extend(crate::hex::classify(s, opts.all));
    }

    out.sort_by(|a, b| {
        b.confidence
            .partial_cmp(&a.confidence)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then(a.mode.cmp(&b.mode))
    });
    out
}

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

    /// One example per mode. Structured/prefixed hashes are verbatim hashcat
    /// example-hash strings; the long Kerberos/Office/KeePass/DPAPI bodies are
    /// truncated to a structurally-valid representative (M5's auto-sync will
    /// pin the exact canonical strings). Each case asserts the correct mode is
    /// the top candidate.
    fn top_mode(hash: &str) -> u32 {
        let c = identify(hash, false);
        assert!(!c.is_empty(), "no candidate for: {hash}");
        c[0].mode
    }

    #[test]
    fn crypt_family() {
        assert_eq!(top_mode("$1$28772684$iEwNOgGugqO9.bIz5sk8k/"), 500);
        assert_eq!(top_mode("$apr1$71850310$gh9m4xcAn3MGxogwX/ztb."), 1600);
        assert_eq!(
            top_mode("$5$rounds=5000$GX7BopJZJxPc/KEK$le16UF8I2Anb.rOrn22AUPWvzUETDGefUmAV8AZkGcD"),
            7400
        );
        assert_eq!(
            top_mode(
                "$6$52450745$k5ka2p8bFuSmoVT1tzOyyuaREkkKBcCNqoDKzYiJL9RaE8yMnPgh2XzzF0NDrUhgrcLwg78xs1w5pJiypEdFX/"
            ),
            1800
        );
        assert_eq!(
            top_mode("$2a$05$LhayLxezLhK1LhWvKxCyLOj0j1u.Kj0jZ0pEmm134uzrQlFvQJLF6"),
            3200
        );
        assert_eq!(
            top_mode("$sha1$40000$jtNX3nZ2$hBNaIXkt4wBI2o5rsi8KejSjNqIq"),
            15100
        );
    }

    #[test]
    fn web_app_formats() {
        assert_eq!(top_mode("$P$984478476IagS59wHZvyQMArzfx58u."), 400);
        assert_eq!(top_mode("$H$984478476IagS59wHZvyQMArzfx58u."), 400);
        assert_eq!(
            top_mode("$S$C33783772bRXEnVExYFsyhWMzewYNI46xzUUKkHkJmuqBUp4tHUx"),
            7900
        );
        assert_eq!(
            top_mode(
                "pbkdf2_sha256$20000$H0dPx8NeajVu$GiC4k5kqbbR9qWBlsRgDywNqC2vd9kqfk7zdorEnNas="
            ),
            10000
        );
        assert_eq!(top_mode("{SHA}W6ph5Mm5Pz8GgiULbPgzG37mj9g="), 101);
        assert_eq!(top_mode("{SSHA}0MF7YJUwXd4hCyMOFmyM/HcZesM2FQ4l"), 111);
    }

    #[test]
    fn cisco() {
        assert_eq!(
            top_mode("$8$TnGX/fE4KGHOVU$pEhnEvxrEcqYKXGH3aFkYaC3B2MtqhkAKSl4WGWmc9E"),
            9200
        );
        assert_eq!(
            top_mode("$9$2MJBozw/9R3UsU$2lFhcKvpghcyw8deP25GOfyZaagyUOGBymkryvOdfo6"),
            9300
        );
    }

    #[test]
    fn kerberos() {
        assert_eq!(
            top_mode(
                "$krb5tgs$23$*user$realm$test/spn*$63386d22d359fe42230300d56852c9eb$891ad31d09ab89c6b3b8c5e5de6c06a7f49fd559d7a9a3c32576c8fdf6"
            ),
            13100
        );
        assert_eq!(
            top_mode("$krb5tgs$17$user$realm$ae8434177efd09be5bc2eff8$90b4ce5b"),
            19600
        );
        assert_eq!(
            top_mode("$krb5tgs$18$user$realm$8efd91bb01cc69dd07e46009$1090aa"),
            19700
        );
        assert_eq!(
            top_mode("$krb5asrep$23$user@domain.com:3e156ada591263b8aab0965f5aebd837$334ac"),
            18200
        );
        assert_eq!(top_mode("$krb5pa$23$user$realm$salt$6f9ef1af5"), 7500);
    }

    #[test]
    fn office_keepass_dpapi() {
        assert_eq!(
            top_mode("$office$*2007*20*128*16*411a51284e0d0200b131a8949aa8e07b*f1"),
            9400
        );
        assert_eq!(
            top_mode("$office$*2010*100000*128*16*77233201017277d426048818b9819cb8*b4"),
            9500
        );
        assert_eq!(
            top_mode("$office$*2013*100000*256*16*7dd611d7eb4c899f74816d1dec817b3b*948d"),
            9600
        );
        assert_eq!(
            top_mode("$keepass$*2*6000*0*4a3f8b6c2d*1c*7b1e*ac*ff"),
            13400
        );
        assert_eq!(
            top_mode("$DPAPImk$1*1*S-15-21-11*des3*sha1*100*abc*208*def"),
            15300
        );
        assert_eq!(
            top_mode("$DPAPImk$2*1*S-15-21-11*aes256*sha512*8000*abc*288*def"),
            15900
        );
    }

    #[test]
    fn archives() {
        assert_eq!(
            top_mode("$7z$0$19$0$salt$8$1122334455667788$123$60$deadbeef"),
            11600
        );
        assert_eq!(
            top_mode("$RAR3$*0*45109af8ab5f297a*adc9c4300c1c5be0"),
            12500
        );
        assert_eq!(
            top_mode("$rar5$16$74575567518807622265582327032280$15$d33c8"),
            13000
        );
        assert_eq!(
            top_mode("$zip2$*0*3*0*ab5f297a*1122*0*0*deadbeef*$/zip2$"),
            13600
        );
        // PDF prefix maps to a version family; assert it is present, not unique.
        let pdf = identify(
            "$pdf$2*3*128*-1028*1*16*da42ee15d4b3e08fe5b9ecea0e02ad0f*32* deadbeef",
            false,
        );
        assert!(pdf.iter().any(|c| c.mode == 10500));
    }

    #[test]
    fn jwt() {
        assert_eq!(
            top_mode(
                "eyJhbGciOiJIUzI1NiJ9.eyJpbmZvIjoibXkgc2VjcmV0In0.chURrO4W3up84rQFIQmOCFCUXKtoOJvY6qJ0LzjaQao"
            ),
            16500
        );
    }

    #[test]
    fn netntlm() {
        assert_eq!(
            top_mode(
                "u4-netntlm::kNS:338d08f8e26de93300000000000000000000000000000000:9526fb8c23a90751cdd619b6cea564742e1e4bf33006ba41:cb8086049ec4736c"
            ),
            5500
        );
        assert_eq!(
            top_mode(
                "admin::N46iSNekpT:08ca45b7d7ea58ee:88dcbe4446168966a153a0064958dac6:5c7830315c7830310000000000000b45c67103d07d7b95acd12ffa11230e0000000052920b85f78d013c31cdb3b92f5d765c783030"
            ),
            5600
        );
    }

    #[test]
    fn ad_cached_creds_and_wpa() {
        assert_eq!(
            top_mode("$DCC2$10240#tom#e4e938d12fe5974dc42a90120bd9c90f"),
            2100
        );
        assert_eq!(
            top_mode(
                "WPA*01*4d4fe7aac3a2cecab195321ceb99a7d0*fc690c158264*f4747f87f9f4*686173686361742d6573736964***"
            ),
            22000
        );
    }

    #[test]
    fn salted_family_is_opt_in_only() {
        let salt = Opts {
            salted: true,
            ..Opts::default()
        };
        // Default: NOT claimed — this is the fix for `d41d…:avatar.png`-style
        // `hex:filename` false positives.
        assert!(identify("01dfae6e5d4d90d9892622325959afbe:7050461", false).is_empty());
        assert!(identify("d41d8cd98f00b204e9800998ecf8427e:avatar.png", false).is_empty());
        // --salted: the ambiguous family appears, ranked but never certain.
        let c = identify_with("01dfae6e5d4d90d9892622325959afbe:7050461", salt);
        assert_eq!(c[0].mode, 10);
        assert!(c.iter().any(|x| x.mode == 20));
        assert!(c.iter().any(|x| x.mode == 1100));
        assert!(c[0].confidence < 0.85);
        assert_eq!(
            identify_with("2fc5a684737ce1bf7b3b239df432416e0dd07357:2014", salt)[0].mode,
            110
        );
        assert_eq!(
            identify_with(
                "c73d08de890479518ed60cf670d17faa26a4a71f995c1dcc978165399401a6c4:1234",
                salt
            )[0]
            .mode,
            1410
        );
    }

    #[test]
    fn strict_suppresses_the_bare_hex_tier() {
        let strict = Opts {
            strict: true,
            ..Opts::default()
        };
        // A bare 40-hex (git-SHA shape) is a SHA-1 guess by default...
        assert_eq!(
            identify("a1b2c3d4e5f6789012345678901234567890abcd", false)[0].mode,
            100
        );
        // ...but --strict returns nothing rather than guess.
        assert!(identify_with("a1b2c3d4e5f6789012345678901234567890abcd", strict).is_empty());
        // Structured hashes still identify under strict.
        assert_eq!(
            identify_with("$1$28772684$iEwNOgGugqO9.bIz5sk8k/", strict)[0].mode,
            500
        );
    }

    #[test]
    fn bare_hex_is_ranked_never_certain() {
        // 32 hex → MD5 first by prevalence, NTLM/MD4 alongside, none certain.
        let c = identify("8743b52063cd84097a65d1633f5c74f5", false);
        assert_eq!(c[0].mode, 0);
        assert!(c.iter().any(|x| x.mode == 1000));
        assert!(c.iter().any(|x| x.mode == 900));
        assert!(c[0].confidence < 0.6, "bare hex must not read as certain");
    }

    #[test]
    fn hex_lengths_pick_the_prevalent_mode() {
        // SHA-1 (40), SHA-256 (64, shown with its SHA3/Keccak twins), SHA-512 (128)
        assert_eq!(top_mode("aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d"), 100);
        let s256 = identify(
            "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
            false,
        );
        assert_eq!(s256[0].mode, 1400);
        assert!(s256.iter().any(|c| c.mode == 17400));
        assert_eq!(
            top_mode(
                "82a9dda829eb7f8ffe9fbe49e45d47d2dad9664fbb7adf72492e3c81ebd3e29134d9bc12212bf83c6840f10e8246b9db54a4859b7ccd0123d86e5872c1e5082f"
            ),
            1700
        );
    }

    #[test]
    fn all_flag_reveals_rare_modes() {
        let hash = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08";
        assert!(identify(hash, true).len() > identify(hash, false).len());
        assert!(identify(hash, true).iter().any(|c| c.mode == 6900)); // GOST, --all only
    }

    #[test]
    fn structured_match_excludes_the_hex_tier() {
        // A structured hash is never pure hex, so only its M1 candidate returns.
        let c = identify("$1$28772684$iEwNOgGugqO9.bIz5sk8k/", false);
        assert_eq!(c.len(), 1);
        assert_eq!(c[0].mode, 500);
    }

    #[test]
    fn whitespace_is_trimmed() {
        assert_eq!(top_mode("  $1$28772684$iEwNOgGugqO9.bIz5sk8k/\n"), 500);
    }
}