hashglass 0.1.0

Fast pentester-focused hash identifier — mode + cost + ready hashcat command. Handles secretsdump / containers / mixed dumps. Identification only.
Documentation
//! M4 — container recognition.
//!
//! The other context signals landed already: the pwdump/secretsdump line
//! shape (M3) is the high-value one, and a formatted Kerberos/structured hash
//! is unambiguous on its own — so a `krbtgt`-nearby keyword boost would change
//! nothing and is deliberately not implemented (it would only add false
//! confidence). What remains genuinely useful is the plan's "header bytes"
//! idea: point hashglass at an *encrypted container* (`secret.kdbx`, a locked
//! `.7z`) and have it name the hashcat mode plus the `*2john` extractor you
//! need to pull the crackable hash out first.
//!
//! Detection is magic-byte-first (authoritative), falling back to extension
//! only for formats that have no reliable header (VeraCrypt is deniable by
//! design). A text dump of hashes has no container magic, so it falls straight
//! through to batch identification.

use std::path::Path;

/// A recognized encrypted container and how to crack it.
pub struct Container {
    /// Human-readable container type.
    pub kind: &'static str,
    /// Candidate hashcat mode(s); exact one depends on cipher/version.
    pub modes: &'static [u32],
    /// The `*2john` (or `*2hashcat`) tool that extracts the crackable hash.
    pub extractor: &'static str,
    /// Optional caveat (empty string = none).
    pub note: &'static str,
}

fn starts_with(head: &[u8], sig: &[u8]) -> bool {
    head.len() >= sig.len() && &head[..sig.len()] == sig
}

fn ext_of(path: &Path) -> Option<String> {
    path.extension()
        .and_then(|e| e.to_str())
        .map(|e| e.to_ascii_lowercase())
}

/// Recognize an encrypted container from its first bytes (and, for header-less
/// formats, its extension). `None` means "not a known container" — treat the
/// file as a text dump.
pub fn recognize(path: &Path, head: &[u8]) -> Option<Container> {
    // KeePass 2.x (KDBX): signature 0x9AA2D903, little-endian on disk.
    if starts_with(head, &[0x03, 0xD9, 0xA2, 0x9A]) {
        return Some(Container {
            kind: "KeePass 2.x (KDBX)",
            modes: &[13400],
            extractor: "keepass2john",
            note: "",
        });
    }
    // 7-Zip
    if starts_with(head, &[0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C]) {
        return Some(Container {
            kind: "7-Zip archive",
            modes: &[11600],
            extractor: "7z2john",
            note: "",
        });
    }
    // RAR: "Rar!\x1a\x07" then 0x01,0x00 = RAR5, 0x00 = RAR3/4
    if starts_with(head, &[0x52, 0x61, 0x72, 0x21, 0x1A, 0x07]) {
        if head.get(6) == Some(&0x01) {
            return Some(Container {
                kind: "RAR5 archive",
                modes: &[13000],
                extractor: "rar2john",
                note: "",
            });
        }
        return Some(Container {
            kind: "RAR3 archive",
            modes: &[12500],
            extractor: "rar2john",
            note: "",
        });
    }
    // PDF
    if starts_with(head, b"%PDF") {
        return Some(Container {
            kind: "PDF document",
            modes: &[10400, 10500, 10600, 10700],
            extractor: "pdf2john",
            note: "exact mode depends on the PDF version/revision",
        });
    }
    // ZIP local-file header — OOXML Office docs are ZIPs; split by extension.
    if starts_with(head, &[0x50, 0x4B, 0x03, 0x04]) {
        match ext_of(path).as_deref() {
            Some("docx" | "xlsx" | "pptx") => {
                return Some(Container {
                    kind: "MS Office (OOXML)",
                    modes: &[9400, 9500, 9600],
                    extractor: "office2john",
                    note: "9400/9500/9600 = 2007/2010/2013",
                });
            }
            _ => {
                return Some(Container {
                    kind: "ZIP archive",
                    modes: &[13600],
                    extractor: "zip2john",
                    note: "or a PKZIP 17200-series mode; zip2john picks it",
                });
            }
        }
    }
    // OLE2 compound file — legacy Office (.doc/.xls/.ppt ≤2003)
    if starts_with(head, &[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]) {
        return Some(Container {
            kind: "MS Office (legacy OLE, ≤2003)",
            modes: &[9700, 9800],
            extractor: "office2john",
            note: "9700=Office2003 MD5+RC4, 9800=SHA1+RC4",
        });
    }
    // libpcap — big-endian A1B2C3D4 or little-endian D4C3B2A1. Nanosecond
    // variant is A1B23CD4 / 4CD3B2A1 (same first byte + endianness split).
    if starts_with(head, &[0xD4, 0xC3, 0xB2, 0xA1])
        || starts_with(head, &[0xA1, 0xB2, 0xC3, 0xD4])
        || starts_with(head, &[0x4D, 0x3C, 0xB2, 0xA1])
        || starts_with(head, &[0xA1, 0xB2, 0x3C, 0x4D])
    {
        return Some(Container {
            kind: "libpcap capture",
            modes: &[22000],
            extractor: "hcxpcapngtool",
            note: "hcxpcapngtool -o hashes.hc22000 <file>  →  hashcat -m 22000 hashes.hc22000",
        });
    }
    // pcapng — magic block type 0x0A0D0D0A ("\n\r\r\n").
    if starts_with(head, &[0x0A, 0x0D, 0x0D, 0x0A]) {
        return Some(Container {
            kind: "pcapng capture",
            modes: &[22000],
            extractor: "hcxpcapngtool",
            note: "hcxpcapngtool -o hashes.hc22000 <file>  →  hashcat -m 22000 hashes.hc22000",
        });
    }
    // NTDS.dit — ESE database. The first 4 bytes are the checksum, and the
    // literal signature 0xEF CD AB 89 sits at offset 4 (Microsoft's "JET"
    // magic). Any AD engagement's highest-value artifact — nothing else in
    // this list even comes close.
    if head.len() >= 8 && head[4..8] == [0xEF, 0xCD, 0xAB, 0x89] {
        return Some(Container {
            kind: "NTDS.dit (ESE database)",
            modes: &[1000, 3000],
            extractor: "impacket-secretsdump",
            note: "impacket-secretsdump -ntds <file> -system SYSTEM LOCAL  →  hashglass on the output",
        });
    }

    // Header-less formats: extension-only, clearly flagged.
    match ext_of(path).as_deref() {
        Some("vc" | "tc" | "hc") => Some(Container {
            kind: "VeraCrypt/TrueCrypt volume",
            modes: &[13721, 13711, 6211],
            extractor: "veracrypt2hashcat",
            note: "extension-only guess — these formats have no header magic by design",
        }),
        // NTDS.dit sometimes appears without a valid ESE header (partial dump,
        // hive shard) — surface the extension so a senior sees the hint even
        // then.
        Some("dit") => Some(Container {
            kind: "NTDS.dit (ESE database, extension-only)",
            modes: &[1000, 3000],
            extractor: "impacket-secretsdump",
            note: "impacket-secretsdump -ntds <file> -system SYSTEM LOCAL  →  hashglass on the output",
        }),
        _ => None,
    }
}

/// Render container guidance as text.
pub fn render(path: &Path, c: &Container) -> String {
    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("file");
    let modes = c
        .modes
        .iter()
        .map(|m| format!("-m {m}"))
        .collect::<Vec<_>>()
        .join(" / ");
    let mut s = format!("{name} → {}\n", c.kind);
    s.push_str(&format!("  hashcat {modes}\n"));
    s.push_str(&format!(
        "  extract the crackable hash first:  {} {name}\n",
        c.extractor
    ));
    if !c.note.is_empty() {
        s.push_str(&format!("  note: {}\n", c.note));
    }
    s
}

/// Render container guidance as JSON.
pub fn render_json(path: &Path, c: &Container) -> String {
    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("file");
    let v = serde_json::json!({
        "file": name,
        "container": c.kind,
        "modes": c.modes,
        "extractor": c.extractor,
        "note": if c.note.is_empty() { serde_json::Value::Null } else { serde_json::json!(c.note) },
    });
    serde_json::to_string_pretty(&v).unwrap_or_else(|_| "{}".to_string())
}

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

    #[test]
    fn kdbx_magic_is_keepass() {
        let c = recognize(Path::new("secret.kdbx"), &[0x03, 0xD9, 0xA2, 0x9A, 0x00]).unwrap();
        assert_eq!(c.modes, &[13400]);
        assert_eq!(c.extractor, "keepass2john");
    }

    #[test]
    fn rar5_vs_rar3_by_version_byte() {
        let r5 = recognize(
            Path::new("a.rar"),
            &[0x52, 0x61, 0x72, 0x21, 0x1A, 0x07, 0x01, 0x00],
        )
        .unwrap();
        assert_eq!(r5.modes, &[13000]);
        let r3 = recognize(
            Path::new("a.rar"),
            &[0x52, 0x61, 0x72, 0x21, 0x1A, 0x07, 0x00],
        )
        .unwrap();
        assert_eq!(r3.modes, &[12500]);
    }

    #[test]
    fn pk_magic_splits_office_from_zip() {
        let pk = [0x50u8, 0x4B, 0x03, 0x04];
        assert_eq!(
            recognize(Path::new("book.xlsx"), &pk).unwrap().kind,
            "MS Office (OOXML)"
        );
        assert_eq!(
            recognize(Path::new("files.zip"), &pk).unwrap().kind,
            "ZIP archive"
        );
    }

    #[test]
    fn text_dump_is_not_a_container() {
        // ASCII hash-dump content has no container magic.
        assert!(recognize(Path::new("dump.txt"), b"Administrator:500:aad3").is_none());
    }

    #[test]
    fn pcap_little_and_big_endian_both_recognized() {
        // LE (D4C3B2A1) is what tcpdump on Linux writes.
        let le = recognize(
            Path::new("wifi.pcap"),
            &[0xD4, 0xC3, 0xB2, 0xA1, 0x02, 0x00],
        )
        .unwrap();
        assert_eq!(le.modes, &[22000]);
        assert_eq!(le.extractor, "hcxpcapngtool");
        // BE (A1B2C3D4) is rarer but valid.
        let be = recognize(
            Path::new("wifi.pcap"),
            &[0xA1, 0xB2, 0xC3, 0xD4, 0x00, 0x02],
        )
        .unwrap();
        assert_eq!(be.modes, &[22000]);
    }

    #[test]
    fn pcapng_magic_block_type_recognized() {
        let c = recognize(
            Path::new("cap.pcapng"),
            &[0x0A, 0x0D, 0x0D, 0x0A, 0x1C, 0x00, 0x00, 0x00],
        )
        .unwrap();
        assert_eq!(c.kind, "pcapng capture");
        assert_eq!(c.modes, &[22000]);
    }

    #[test]
    fn ntds_dit_by_ese_magic_at_offset_4() {
        // Real NTDS.dit: 4 bytes of checksum, then 0xEF CD AB 89.
        let mut head = vec![0xAA, 0xBB, 0xCC, 0xDD, 0xEF, 0xCD, 0xAB, 0x89];
        head.extend([0x00; 8]);
        let c = recognize(Path::new("NTDS.dit"), &head).unwrap();
        assert!(c.kind.starts_with("NTDS.dit"));
        assert_eq!(c.extractor, "impacket-secretsdump");
        assert!(c.note.contains("SYSTEM"));
    }

    #[test]
    fn ntds_dit_extension_fallback_when_magic_absent() {
        // A dumped/partial NTDS without the ESE header — still surface the hint
        // via extension.
        let c = recognize(Path::new("ntds_partial.dit"), &[0x00; 4]).unwrap();
        assert!(c.kind.contains("extension-only"));
        assert_eq!(c.extractor, "impacket-secretsdump");
    }

    #[test]
    fn veracrypt_is_extension_only_with_caveat() {
        let c = recognize(Path::new("vol.vc"), &[0x00, 0x11, 0x22]).unwrap();
        assert!(c.note.contains("extension-only"));
    }
}