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;
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);
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
}
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()
);
}
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);
}
};
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));
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_hit(&hit);
let h = wordlist::hint();
if !h.is_empty() {
eprintln!("{h}");
}
return ExitCode::SUCCESS;
}
return run_hash(&line, opts);
}
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)
}
}
}
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)
}
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"));
}
}