hashglass 0.1.0

Fast pentester-focused hash identifier — mode + cost + ready hashcat command. Handles secretsdump / containers / mixed dumps. Identification only.
Documentation
//! Auto mode — the zero-flag pentester path.
//!
//! What you actually want when you type `hashglass <thing>`:
//!   `<hash>`         → identify + one-line ready command
//!   `<container>`    → mode + extractor, exactly as before (M4)
//!   `secretsdump`    → auto-split by mode + a runnable hashcat line per group
//!   `mixed dump`     → same auto-split, no flag needed
//!   single-hash file → identify the one hash, don't spam split output
//!
//! Flags become the escape hatch (`--only`, `--split <dir>`, `--strict`,
//! `--salted`, `--json`), not the interface. The default just works.

use crate::batch;
use crate::cost;
use crate::identify::{Opts, identify_with};
use crate::wordlist;
use std::io::{BufRead, BufReader, Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

/// One shot on a raw hash string: print the mode(s) + a ready hashcat line.
pub fn run_hash(hash: &str, opts: Opts) -> ExitCode {
    let cs = identify_with(hash, opts);
    if cs.is_empty() {
        let with_salt = identify_with(
            hash,
            Opts {
                salted: true,
                ..opts
            },
        );
        if !with_salt.is_empty() {
            eprintln!("looks like hash:salt — rerun with --salted to consider it.");
        } else {
            eprintln!("no known hash type matched.");
        }
        return ExitCode::from(1);
    }
    let top = &cs[0];
    println!("{} (-m {})", top.name, top.mode);

    // Cost annotation — the whole point of slice 6. Silent if we don't have
    // data for this mode; fake numbers are worse than no numbers.
    let oneliner = cost::oneliner(top.mode);
    if !oneliner.is_empty() {
        println!("  {oneliner}");
    }
    if let Some(a) = cost::advice(top.mode) {
        println!("  {a}");
    }

    if cs.len() > 1 {
        let alts: Vec<String> = cs
            .iter()
            .skip(1)
            .take(3)
            .map(|c| c.mode.to_string())
            .collect();
        println!("  alt: -m {}", alts.join(" / -m "));
    }
    println!(
        "\n  hashcat -m {} <(echo '{}') {}",
        top.mode,
        hash,
        wordlist::substitute()
    );
    let h = wordlist::hint();
    if !h.is_empty() {
        eprintln!("{h}");
    }
    ExitCode::SUCCESS
}

/// Print a single [`crate::batch::HashHit`] with the same "advisor" layout as
/// `run_hash` — mode line + cost + advice + ready command. Used when the
/// hit came from `analyze_line` (pwdump-pinned NT, JSON-extracted hex, …) so
/// we don't re-identify the bare token and lose context.
fn print_hit(hit: &crate::batch::HashHit) {
    let top = &hit.candidates[0];
    match &hit.label {
        Some(l) => println!("{} (-m {}) [{}]", top.name, top.mode, l),
        None => println!("{} (-m {})", top.name, top.mode),
    }
    let one = cost::oneliner(top.mode);
    if !one.is_empty() {
        println!("  {one}");
    }
    if let Some(a) = cost::advice(top.mode) {
        println!("  {a}");
    }
    if hit.candidates.len() > 1 {
        let alts: Vec<String> = hit
            .candidates
            .iter()
            .skip(1)
            .take(3)
            .map(|c| c.mode.to_string())
            .collect();
        println!("  alt: -m {}", alts.join(" / -m "));
    }
    println!(
        "\n  hashcat -m {} <(echo '{}') {}",
        top.mode,
        hit.token,
        wordlist::substitute()
    );
}

/// Auto-dispatch a filesystem path: container → extractor guidance;
/// single-hash file → identify one; multi-line dump → auto-split.
pub fn run_path(path: &Path, opts: Opts) -> ExitCode {
    let mut file = match std::fs::File::open(path) {
        Ok(f) => f,
        Err(e) => {
            eprintln!("error: cannot open {}: {e}", path.display());
            return ExitCode::from(2);
        }
    };

    // 1. Container recognition (magic bytes) — reuses M4's context module.
    let mut head = [0u8; 16];
    let n = file.read(&mut head).unwrap_or(0);
    if let Some(c) = crate::context::recognize(path, &head[..n]) {
        print!("{}", crate::context::render(path, &c));
        return ExitCode::SUCCESS;
    }
    let _ = file.seek(SeekFrom::Start(0));

    // 2. Peek line count without allocating the whole file. A single
    //    content-line file goes through `analyze_line` — same cleaning +
    //    label-strip + embedded-extract pipeline as batch mode. Skipping this
    //    (calling `run_hash` on the raw line) is exactly the bug that made
    //    CRLF and `hash:password` `--show` output silently fail.
    let mut reader = BufReader::new(file);
    let (line_count, first) = peek_lines(&mut reader);
    if line_count == 1
        && let Some(line) = first
    {
        let hits = crate::batch::analyze_line(&line, opts);
        if let Some(hit) = hits.into_iter().find(|h| !h.candidates.is_empty()) {
            // Print the hit directly — preserves pwdump/context pinning we
            // just resolved. Dispatching back through run_hash would re-do
            // identify on just the token and lose that context.
            print_hit(&hit);
            let h = wordlist::hint();
            if !h.is_empty() {
                eprintln!("{h}");
            }
            return ExitCode::SUCCESS;
        }
        return run_hash(&line, opts);
    }

    // 3. Multi-line dump → auto-split to `<name>.hashglass/` next to the file
    //    so re-runs are idempotent-in-place (no cwd surprises), then print
    //    the same ready commands the old `--split` used to.
    let dir = default_split_dir(path);
    let _ = reader.seek(SeekFrom::Start(0));
    match batch::split(reader, &dir, opts, None) {
        Ok(rep) => {
            if rep.by_mode.is_empty() && rep.unknown == 0 {
                eprintln!("no hashes found in {}", path.display());
                return ExitCode::from(1);
            }
            let stdout = std::io::stdout();
            let mut out = stdout.lock();
            let _ = batch::render_split(&rep, &mut out);
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("error: {e}");
            ExitCode::from(2)
        }
    }
}

/// Peek up to 2 non-blank, non-comment lines so we can distinguish a single-hash
/// file from a dump without reading the whole thing.
fn peek_lines(reader: &mut impl BufRead) -> (usize, Option<String>) {
    let mut count = 0usize;
    let mut first: Option<String> = None;
    for line in reader.lines().map_while(Result::ok) {
        let t = line.trim();
        if t.is_empty() || t.starts_with('#') {
            continue;
        }
        count += 1;
        if first.is_none() {
            first = Some(t.to_string());
        }
        if count >= 2 {
            break;
        }
    }
    (count, first)
}

/// `dump.txt` → `dump.hashglass/`, alongside the source. Deliberately NOT
/// `./split/` — a pentester runs on many dumps in the same cwd and the last
/// one silently clobbering the previous is exactly the footgun from the
/// critique.
pub fn default_split_dir(path: &Path) -> PathBuf {
    let stem = path
        .file_stem()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_else(|| "hashglass".into());
    let parent = path.parent().unwrap_or_else(|| Path::new("."));
    parent.join(format!("{stem}.hashglass"))
}

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

    #[test]
    fn default_split_dir_lives_next_to_source() {
        let d = default_split_dir(Path::new("/tmp/loot/dump.txt"));
        assert_eq!(d, PathBuf::from("/tmp/loot/dump.hashglass"));
    }

    #[test]
    fn peek_skips_blank_and_comment() {
        let mut r = std::io::Cursor::new("# header\n\nfirst-hash\nsecond\n");
        let (n, first) = peek_lines(&mut r);
        assert_eq!(n, 2);
        assert_eq!(first.as_deref(), Some("first-hash"));
    }

    #[test]
    fn peek_reports_one_for_single_content_line() {
        let mut r = std::io::Cursor::new("only-one\n");
        let (n, first) = peek_lines(&mut r);
        assert_eq!(n, 1);
        assert_eq!(first.as_deref(), Some("only-one"));
    }
}