hashglass 0.1.0

Fast pentester-focused hash identifier — mode + cost + ready hashcat command. Handles secretsdump / containers / mixed dumps. Identification only.
Documentation
//! M2 — the bare fixed-length hex tier.
//!
//! A string of only hex digits carries no structure, so several hashcat modes
//! share every length (32 hex = MD5 *or* NTLM *or* MD4 *or* …). This tier is
//! deliberately the *honest* one: it never returns a single confident answer
//! for an ambiguous length. It emits every plausible mode for that length,
//! ranked by real-world prevalence, with capped confidence so nothing here can
//! ever outrank a structured (M1) match.
//!
//! Prevalence order is a hand-tuned heuristic, not a measured distribution —
//! the point is only to surface the mode you most likely want first. hashcat
//! rejects a wrong `-m` on a length check instantly, so guessing top-down is
//! free.

use crate::identify::Candidate;

/// All modes that share one hex length, split into the common set (shown by
/// default) and the rarer tail (shown only with `--all`).
pub struct HexBucket {
    /// Length of the hex string in characters.
    pub chars: usize,
    /// Confidence for the top (rank 0) candidate; lower = more ambiguous
    /// length. Later ranks decay from here. Always well under the structured
    /// tier so a real M1 match always wins.
    pub base_confidence: f32,
    /// Prevalence-ordered common candidates: `(hashcat mode, name)`.
    pub common: &'static [(u32, &'static str)],
    /// Rarer candidates of the same length, revealed with `--all`.
    pub rare: &'static [(u32, &'static str)],
}

/// The length → modes table. Mode numbers are hashcat's.
pub static BUCKETS: &[HexBucket] = &[
    HexBucket {
        chars: 8,
        base_confidence: 0.30,
        common: &[(11500, "CRC32 (hashcat wants hash:salt)")],
        rare: &[],
    },
    HexBucket {
        chars: 16,
        base_confidence: 0.42,
        common: &[(200, "MySQL323"), (3000, "LM")],
        rare: &[],
    },
    HexBucket {
        chars: 32,
        base_confidence: 0.48,
        common: &[(0, "MD5"), (1000, "NTLM"), (900, "MD4")],
        rare: &[(2600, "md5(md5($pass))")],
    },
    HexBucket {
        chars: 40,
        base_confidence: 0.55,
        common: &[(100, "SHA-1"), (6000, "RIPEMD-160")],
        rare: &[(300, "MySQL4.1/MySQL5"), (4500, "sha1(sha1($pass))")],
    },
    HexBucket {
        chars: 56,
        base_confidence: 0.55,
        common: &[(1300, "SHA-224")],
        rare: &[(17300, "SHA3-224"), (17700, "Keccak-224")],
    },
    HexBucket {
        chars: 64,
        base_confidence: 0.50,
        common: &[
            (1400, "SHA-256"),
            (17400, "SHA3-256"),
            (17800, "Keccak-256"),
        ],
        rare: &[(6900, "GOST R 34.11-94"), (11700, "Streebog-256")],
    },
    HexBucket {
        chars: 96,
        base_confidence: 0.60,
        common: &[(10800, "SHA-384")],
        rare: &[(17500, "SHA3-384"), (17900, "Keccak-384")],
    },
    HexBucket {
        chars: 128,
        base_confidence: 0.48,
        common: &[(1700, "SHA-512"), (6100, "Whirlpool")],
        rare: &[
            (17600, "SHA3-512"),
            (18000, "Keccak-512"),
            (11800, "Streebog-512"),
        ],
    },
];

/// True if `s` is non-empty and every byte is an ASCII hex digit.
pub fn is_hex(s: &str) -> bool {
    !s.is_empty() && s.bytes().all(|b| b.is_ascii_hexdigit())
}

/// A real hash is effectively random (≈16 distinct nibbles over 32+ chars).
/// Hex of length ≥16 with fewer than 4 distinct characters — all-zeros,
/// `0f0f0f…`, `abababab…` — is a placeholder or pattern, not a hash. Rejecting
/// it costs nothing (no real hash is that degenerate) and stops obvious
/// non-hashes like an all-zero SID chunk being called MD5.
fn is_degenerate(s: &str) -> bool {
    if s.len() < 16 {
        return false; // don't over-filter short CRC32 / MySQL323
    }
    let mut seen = [false; 256];
    let mut distinct = 0u32;
    for b in s.bytes().map(|b| b.to_ascii_lowercase()) {
        if !std::mem::replace(&mut seen[b as usize], true) {
            distinct += 1;
        }
    }
    distinct < 4
}

/// Classify a bare-hex string into ranked candidates.
///
/// Returns empty if `s` is not pure hex, or its length matches no known
/// bucket. With `include_rare` false, only the common set for that length is
/// returned.
pub fn classify(s: &str, include_rare: bool) -> Vec<Candidate> {
    if !is_hex(s) || is_degenerate(s) {
        return Vec::new();
    }
    let Some(bucket) = BUCKETS.iter().find(|b| b.chars == s.len()) else {
        return Vec::new();
    };

    let mut out = Vec::new();
    let mut rank = 0usize;
    let mut push = |mode: u32, name: &'static str, rank: usize| {
        out.push(Candidate {
            mode,
            name,
            confidence: (bucket.base_confidence - rank as f32 * 0.08).max(0.05),
        });
    };
    for (mode, name) in bucket.common {
        push(*mode, name, rank);
        rank += 1;
    }
    if include_rare {
        for (mode, name) in bucket.rare {
            push(*mode, name, rank);
            rank += 1;
        }
    }
    out
}

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

    /// High-entropy hex of exactly `len` chars (16 distinct nibbles), so it
    /// looks like a real hash rather than a degenerate pattern.
    fn hexn(len: usize) -> String {
        "0123456789abcdef".chars().cycle().take(len).collect()
    }

    #[test]
    fn rejects_non_hex_and_unknown_lengths() {
        assert!(classify("nothex!!", false).is_empty());
        assert!(classify("", false).is_empty());
        assert!(classify(&hexn(31), false).is_empty()); // 31 = no bucket
    }

    #[test]
    fn degenerate_hex_is_rejected() {
        assert!(classify(&"0".repeat(32), true).is_empty()); // all zeros
        assert!(classify(&"f".repeat(40), true).is_empty()); // all f
        assert!(classify(&"0f".repeat(16), true).is_empty()); // 2 distinct, 32 chars
        assert!(!classify("8743b52063cd84097a65d1633f5c74f5", false).is_empty()); // real
    }

    #[test]
    fn md5_ranks_above_ntlm_above_md4() {
        let c = classify(&hexn(32), false);
        assert_eq!(
            c.iter().map(|x| x.mode).collect::<Vec<_>>(),
            vec![0, 1000, 900]
        );
        assert!(c[0].confidence > c[1].confidence);
        assert!(c[1].confidence > c[2].confidence);
    }

    #[test]
    fn nothing_here_reads_as_certain() {
        for len in [8, 16, 32, 40, 56, 64, 96, 128] {
            for c in classify(&hexn(len), true) {
                assert!(c.confidence < 0.85, "hex mode {} claimed certainty", c.mode);
            }
        }
    }

    #[test]
    fn rare_is_gated_by_include_rare() {
        let common = classify(&hexn(64), false);
        let all = classify(&hexn(64), true);
        assert!(all.len() > common.len());
        assert!(all.iter().any(|c| c.mode == 6900)); // GOST only with --all
        assert!(!common.iter().any(|c| c.mode == 6900));
    }

    #[test]
    fn uppercase_hex_is_accepted() {
        assert!(is_hex("8743B52063CD84097A65D1633F5C74F5"));
    }
}