hashglass 0.1.0

Fast pentester-focused hash identifier — mode + cost + ready hashcat command. Handles secretsdump / containers / mixed dumps. Identification only.
Documentation
//! hashcat potfile support — skip already-cracked hashes.
//!
//! During a real engagement, hashcat writes solved hashes to a potfile as it
//! cracks them. On the next hashglass run over the same dump, we don't want to
//! re-suggest running hashcat on those — the pentester already has the
//! plaintext. This module reads that potfile and exposes a fast `contains()`
//! for the batch/split paths.
//!
//! Potfile format is `<hash>:<plaintext>` per line, one per line. Both fields
//! may contain `:`, so we split at the FIRST colon only. Some formats
//! (secretsdump NT hashes, most raw hashes) match exactly on the hash token;
//! others (structured `$…$` formats) require the hashcat wire format — those
//! we can only match if the user's dump uses the same encoding hashcat would.
//! We keep the match simple (exact string on the hash side) and document the
//! honest limitation.
//!
//! Cache is populated once per process. Lookups are O(1) via HashSet.

use std::collections::HashSet;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};

/// Default hashcat potfile locations, tried in order.
fn default_paths() -> Vec<PathBuf> {
    let mut v = Vec::new();
    // Linux/macOS: XDG data dir, then classic ~/.hashcat/hashcat.potfile
    if let Some(xdg) = std::env::var_os("XDG_DATA_HOME") {
        v.push(PathBuf::from(xdg).join("hashcat").join("hashcat.potfile"));
    }
    if let Some(home) = std::env::var_os("HOME") {
        v.push(PathBuf::from(&home).join(".local/share/hashcat/hashcat.potfile"));
        v.push(PathBuf::from(&home).join(".hashcat/hashcat.potfile"));
    }
    // Windows: %USERPROFILE%\hashcat.potfile lives next to hashcat.exe by default,
    // and %APPDATA%\hashcat\hashcat.potfile if the user relocated it.
    if let Some(userprofile) = std::env::var_os("USERPROFILE") {
        v.push(PathBuf::from(&userprofile).join("hashcat.potfile"));
    }
    if let Some(appdata) = std::env::var_os("APPDATA") {
        v.push(
            PathBuf::from(appdata)
                .join("hashcat")
                .join("hashcat.potfile"),
        );
    }
    v
}

/// Locate the hashcat potfile, or `None` if none of the default paths exist.
/// If the caller passed an explicit `--pot <path>`, it wins unconditionally.
pub fn resolve(explicit: Option<&Path>) -> Option<PathBuf> {
    if let Some(p) = explicit {
        return Some(p.to_path_buf());
    }
    default_paths().into_iter().find(|p| p.is_file())
}

/// Loaded potfile — the set of solved hash tokens for O(1) lookup.
///
/// We store the RAW hash column (everything before the first `:`) verbatim,
/// including any `$…$` prefixes, so `contains(nt_hash)` and
/// `contains("$1$sa$…")` both work depending on how hashcat wrote it.
pub struct Pot {
    solved: HashSet<String>,
    /// Path we loaded from — echoed to stderr for user transparency.
    pub source: PathBuf,
}

impl Pot {
    /// Load the potfile from disk. Silent-skip on any read/parse error for a
    /// single line — a corrupted line elsewhere doesn't invalidate the rest.
    pub fn load(path: PathBuf) -> std::io::Result<Self> {
        let file = std::fs::File::open(&path)?;
        let mut solved = HashSet::new();
        for line in BufReader::new(file).lines().map_while(Result::ok) {
            // Split at the FIRST colon. Cracked plaintext can contain ANY
            // character including `:`, so splitn(2) is critical.
            if let Some((hash, _plain)) = line.split_once(':') {
                let h = hash.trim();
                if !h.is_empty() {
                    solved.insert(h.to_string());
                }
            }
        }
        Ok(Pot {
            solved,
            source: path,
        })
    }

    /// Is this hash already cracked? O(1) lookup.
    pub fn contains(&self, hash: &str) -> bool {
        self.solved.contains(hash.trim())
    }

    /// How many solved hashes did we load. Used for a one-line status message.
    pub fn len(&self) -> usize {
        self.solved.len()
    }

    /// Convenience: is the pot empty?
    pub fn is_empty(&self) -> bool {
        self.solved.is_empty()
    }
}

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

    fn write_temp_pot(content: &str) -> PathBuf {
        let path = std::env::temp_dir().join(format!(
            "hashglass_pot_test_{}_{}.pot",
            std::process::id(),
            content.len(),
        ));
        let mut f = std::fs::File::create(&path).unwrap();
        f.write_all(content.as_bytes()).unwrap();
        path
    }

    #[test]
    fn loads_bare_hash_potfile() {
        let path = write_temp_pot(
            "31d6cfe0d16ae931b73c59d7e0c089c0:\n8846f7eaee8fb117ad06bdd830b7586c:password\n",
        );
        let pot = Pot::load(path.clone()).unwrap();
        assert_eq!(pot.len(), 2);
        assert!(pot.contains("31d6cfe0d16ae931b73c59d7e0c089c0"));
        assert!(pot.contains("8846f7eaee8fb117ad06bdd830b7586c"));
        assert!(!pot.contains("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn splits_at_first_colon_only() {
        // Cracked plaintext contains `:` — must NOT split there.
        let path = write_temp_pot("abc123:pass:with:colons\n");
        let pot = Pot::load(path.clone()).unwrap();
        assert!(pot.contains("abc123"));
        assert_eq!(pot.len(), 1);
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn skips_blank_and_malformed_lines() {
        let path = write_temp_pot("\ngood_hash:pw\nno_colon_here\n\n");
        let pot = Pot::load(path.clone()).unwrap();
        assert_eq!(pot.len(), 1);
        assert!(pot.contains("good_hash"));
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn explicit_path_wins_over_defaults() {
        let path = write_temp_pot("x:y\n");
        let resolved = resolve(Some(&path)).unwrap();
        assert_eq!(resolved, path);
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn missing_file_errors() {
        let missing = std::env::temp_dir().join("definitely_nonexistent_potfile_xyz.pot");
        assert!(Pot::load(missing).is_err());
    }
}