hashglass 0.1.0

Fast pentester-focused hash identifier — mode + cost + ready hashcat command. Handles secretsdump / containers / mixed dumps. Identification only.
Documentation
//! hashglass CLI.
//!
//! `hashglass "<hash>"`  → identify a hash string, print ranked hashcat modes.
//! `hashglass --json …`  → same, as JSON for pipelines.
//!
//! Exit codes: 0 = at least one candidate, 1 = analyzed but nothing matched,
//! 2 = usage error or a not-yet-implemented input mode.

use hashglass::identify::{Opts, identify_with};
use hashglass::{auto, batch, context, input, output, potfile};
use std::io::{BufRead, Cursor, Read, Seek, SeekFrom};
use std::path::PathBuf;
use std::process::ExitCode;

const USAGE: &str = "\
hashglass — identify which hashcat -m mode a hash matches

    hashglass \"<hash>\"       one hash → mode + ready hashcat command
    hashglass secret.kdbx    container → mode + extractor (keepass2john etc)
    hashglass dump.txt       messy dump → auto-split into dump.hashglass/,
                             prints a runnable hashcat line per group
    cat dump | hashglass -   same, from stdin (splits into ./stdin.hashglass/)

That's the whole tool. Flags below are only for scripting / edge cases.

ESCAPE HATCHES:
    --only <mode>   emit ONLY raw hashes of one mode (for piping to hashcat)
    --split <dir>   override the auto split directory
    --strict        never guess from bare hex (git-SHA / UUID → no match)
    --salted        also consider the ambiguous hash:salt family
    --pot [path]    read hashcat potfile, skip hashes already cracked. With no
                    path, auto-finds ~/.local/share/hashcat/hashcat.potfile etc.
    --all           for bare hex, also show rarer modes of that length
    --json          machine-readable output (NDJSON for dumps)
    -q, --summary   dump: print only the grouped summary
    -h, --help      show this help
    -V, --version   show version

EXIT CODES:  0 = something identified, 1 = nothing matched, 2 = usage / I/O.
";

fn main() -> ExitCode {
    let mut json = false;
    let mut all = false;
    let mut strict = false;
    let mut salted = false;
    let mut summary_only = false;
    let mut only: Option<u32> = None;
    let mut split: Option<String> = None;
    let mut positional: Option<String> = None;
    // Pot: None = flag not passed. Some(None) = auto-locate. Some(Some(p)) = explicit path.
    let mut pot_arg: Option<Option<PathBuf>> = None;

    let args: Vec<String> = std::env::args().skip(1).collect();
    let mut i = 0;
    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            "-h" | "--help" => {
                print!("{USAGE}");
                return ExitCode::SUCCESS;
            }
            "-V" | "--version" => {
                println!("hashglass {}", env!("CARGO_PKG_VERSION"));
                return ExitCode::SUCCESS;
            }
            "--json" => json = true,
            "--all" => all = true,
            "--strict" => strict = true,
            "--salted" => salted = true,
            "-q" | "--summary" => summary_only = true,
            "--only" => {
                i += 1;
                match args.get(i).and_then(|v| v.parse::<u32>().ok()) {
                    Some(m) => only = Some(m),
                    None => {
                        eprintln!("error: --only needs a hashcat mode number, e.g. --only 1000");
                        return ExitCode::from(2);
                    }
                }
            }
            "--split" => {
                i += 1;
                match args.get(i) {
                    Some(dir) => split = Some(dir.clone()),
                    None => {
                        eprintln!("error: --split needs an output directory, e.g. --split loot/");
                        return ExitCode::from(2);
                    }
                }
            }
            "--pot" => {
                // Peek the next arg: if it exists AND doesn't look like a flag,
                // treat as explicit path. Otherwise auto-locate.
                let next = args.get(i + 1);
                match next {
                    Some(p) if !p.starts_with('-') => {
                        pot_arg = Some(Some(PathBuf::from(p)));
                        i += 1;
                    }
                    _ => pot_arg = Some(None),
                }
            }
            // Reject unknown long flags, but never mistake a hash (which never
            // begins with "--") for one.
            _ if arg.starts_with("--") => {
                eprintln!("error: unknown flag: {arg}\n");
                eprint!("{USAGE}");
                return ExitCode::from(2);
            }
            _ => {
                if positional.is_some() {
                    eprintln!("error: expected a single hash or file argument (got extra: {arg})");
                    eprintln!("hint: quote the whole hash so the shell passes it as one argument.");
                    return ExitCode::from(2);
                }
                positional = Some(arg.clone());
            }
        }
        i += 1;
    }

    let Some(arg) = positional else {
        eprint!("{USAGE}");
        return ExitCode::from(2);
    };

    let resolved = input::resolve(&arg);
    let opts = Opts {
        all,
        strict,
        salted,
    };

    // Resolve the potfile once, up front. Silent-continue on failure — a
    // missing / unreadable potfile shouldn't crash the run.
    let pot = match pot_arg {
        Some(explicit) => match potfile::resolve(explicit.as_deref()) {
            Some(path) => match potfile::Pot::load(path.clone()) {
                Ok(p) => {
                    eprintln!(
                        "loaded potfile: {} ({} solved)",
                        p.source.display(),
                        p.len()
                    );
                    Some(p)
                }
                Err(e) => {
                    eprintln!("warning: could not load potfile {}: {e}", path.display());
                    None
                }
            },
            None => {
                eprintln!(
                    "warning: --pot given but no potfile found (default paths + no explicit)"
                );
                None
            }
        },
        None => None,
    };

    // Escape-hatch path: script-oriented flags (--only / --split) or the JSON /
    // summary switches keep the old exact behavior. Everything else — the flag-
    // less common case — goes through `auto`, which decides string-vs-file-vs-
    // dump-vs-container itself and prints a ready-to-run hashcat line.
    let scripty = only.is_some() || split.is_some() || json || summary_only;

    if scripty {
        let split_ref = split.as_deref();
        if only.is_some() || split_ref.is_some() {
            return match resolved {
                input::Input::Raw(s) => {
                    run_pipeline(Cursor::new(s), only, split_ref, opts, pot.as_ref())
                }
                input::Input::Stdin => {
                    run_pipeline(std::io::stdin().lock(), only, split_ref, opts, pot.as_ref())
                }
                input::Input::File(path) => match std::fs::File::open(&path) {
                    Ok(file) => run_pipeline(
                        std::io::BufReader::new(file),
                        only,
                        split_ref,
                        opts,
                        pot.as_ref(),
                    ),
                    Err(e) => {
                        eprintln!("error: cannot open {}: {e}", path.display());
                        ExitCode::from(2)
                    }
                },
            };
        }
        // --json / -q only: keep the old renderers.
        return match resolved {
            input::Input::Raw(hash) => run_raw_scripty(&hash, opts, json),
            input::Input::File(path) => run_file_scripty(path, opts, json, summary_only, pot),
            input::Input::Stdin => {
                let stdin = std::io::stdin();
                run_batch(stdin.lock(), opts, json, summary_only, pot)
            }
        };
    }

    // ── Zero-flag path: auto ────────────────────────────────────────────
    match resolved {
        input::Input::Raw(hash) => auto::run_hash(&hash, opts),
        input::Input::File(path) => auto::run_path(&path, opts),
        input::Input::Stdin => {
            // Auto-split stdin into ./stdin.hashglass/ so re-runs don't clobber.
            let dir = auto::default_split_dir(std::path::Path::new("stdin"));
            let stdin = std::io::stdin();
            match batch::split(stdin.lock(), &dir, opts, pot.as_ref()) {
                Ok(rep) if rep.by_mode.is_empty() && rep.unknown == 0 => {
                    eprintln!("no hashes found on stdin");
                    ExitCode::from(1)
                }
                Ok(rep) => {
                    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)
                }
            }
        }
    }
}

fn run_raw_scripty(hash: &str, opts: Opts, json: bool) -> ExitCode {
    let candidates = identify_with(hash, opts);
    let rendered = if json {
        output::render_json(hash, &candidates)
    } else {
        output::render_table(hash, &candidates)
    };
    print!("{rendered}");
    if !rendered.ends_with('\n') {
        println!();
    }
    if candidates.is_empty() {
        ExitCode::from(1)
    } else {
        ExitCode::SUCCESS
    }
}

fn run_file_scripty(
    path: PathBuf,
    opts: Opts,
    json: bool,
    summary_only: bool,
    pot: Option<potfile::Pot>,
) -> 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);
        }
    };
    let mut head = [0u8; 16];
    let n = file.read(&mut head).unwrap_or(0);
    if let Some(c) = context::recognize(&path, &head[..n]) {
        if json {
            println!("{}", context::render_json(&path, &c));
        } else {
            print!("{}", context::render(&path, &c));
        }
        ExitCode::SUCCESS
    } else {
        let _ = file.seek(SeekFrom::Start(0));
        run_batch(std::io::BufReader::new(file), opts, json, summary_only, pot)
    }
}

/// Pipeline mode: `--only` filters raw tokens to stdout; `--split` fans the
/// dump into per-mode files and prints the ready hashcat commands.
fn run_pipeline(
    reader: impl BufRead,
    only: Option<u32>,
    split: Option<&str>,
    opts: Opts,
    pot: Option<&potfile::Pot>,
) -> ExitCode {
    let broken = |e: &std::io::Error| {
        e.kind() == std::io::ErrorKind::BrokenPipe || e.raw_os_error() == Some(232)
    };
    if let Some(mode) = only {
        let stdout = std::io::stdout();
        let mut out = stdout.lock();
        return match batch::filter_only(reader, mode, opts, &mut out) {
            Ok(n) => {
                eprintln!("{n} hash(es) with top mode -m {mode}");
                if n > 0 {
                    ExitCode::SUCCESS
                } else {
                    ExitCode::from(1)
                }
            }
            Err(ref e) if broken(e) => ExitCode::SUCCESS,
            Err(e) => {
                eprintln!("error: {e}");
                ExitCode::from(2)
            }
        };
    }
    // --split
    let dir = split.expect("run_pipeline called with neither only nor split");
    match batch::split(reader, std::path::Path::new(dir), opts, pot) {
        Ok(rep) => {
            let stdout = std::io::stdout();
            let mut out = stdout.lock();
            let _ = batch::render_split(&rep, &mut out);
            if rep.by_mode.is_empty() && rep.unknown == 0 {
                ExitCode::from(1)
            } else {
                ExitCode::SUCCESS
            }
        }
        Err(e) => {
            eprintln!("error: {e}");
            ExitCode::from(2)
        }
    }
}

/// Stream a batch run to stdout and map the outcome to an exit code.
fn run_batch(
    reader: impl BufRead,
    opts: Opts,
    json: bool,
    summary_only: bool,
    pot: Option<potfile::Pot>,
) -> ExitCode {
    let cfg = batch::Cfg {
        all: opts.all,
        json,
        summary_only,
        strict: opts.strict,
        salted: opts.salted,
        pot,
    };
    let stdout = std::io::stdout();
    let mut out = stdout.lock();
    match batch::run(reader, &cfg, &mut out) {
        Ok(sum) if sum.hits > 0 => ExitCode::SUCCESS,
        Ok(_) => ExitCode::from(1),
        // A downstream reader closing early (head/less) is a clean stop, not an error.
        Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe || e.raw_os_error() == Some(232) => {
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("error: {e}");
            ExitCode::from(2)
        }
    }
}