]> code.octet-stream.net Git - hashgood/blob - src/verify.rs
6ad9ea9464a97870babac51567514250f8c15074
[hashgood] / src / verify.rs
1 use super::{
2 Algorithm, CandidateHash, CandidateHashes, Hash, MatchLevel, MessageLevel, Opt, Verification,
3 VerificationSource,
4 };
5 use clipboard::ClipboardContext;
6 use clipboard::ClipboardProvider;
7 use regex::Regex;
8 use std::fs::File;
9 use std::io;
10 use std::io::prelude::*;
11 use std::io::BufReader;
12 use std::path::PathBuf;
13
14 /// Calculate a list of candidate hashes based on the options specified.
15 /// If no hash options have been specified returns None.
16 /// It is assumed to be verified previously that at most one mode has been specified.
17 pub fn get_candidate_hashes(opt: &Opt) -> Result<Option<CandidateHashes>, String> {
18 if let Some(hash_string) = &opt.hash {
19 return Ok(Some(get_by_parameter(hash_string)?));
20 } else if opt.paste {
21 return Ok(Some(get_from_clipboard()?));
22 } else if let Some(hash_file) = &opt.hash_file {
23 return Ok(Some(get_from_file(hash_file)?));
24 }
25 Ok(None)
26 }
27
28 /// Generate a candidate hash from the provided command line parameter, or throw an error.
29 fn get_by_parameter(param: &str) -> Result<CandidateHashes, String> {
30 let bytes =
31 hex::decode(&param).map_err(|_| "Provided hash is invalid or truncated hex".to_owned())?;
32 let alg = Algorithm::from_len(bytes.len())?;
33 let candidate = CandidateHash {
34 filename: None,
35 bytes,
36 };
37 Ok(CandidateHashes {
38 alg,
39 hashes: vec![candidate],
40 source: VerificationSource::CommandArgument,
41 })
42 }
43
44 /// Generate a candidate hash from the system clipboard, or throw an error.
45 fn get_from_clipboard() -> Result<CandidateHashes, String> {
46 let mut ctx: ClipboardContext = match ClipboardProvider::new() {
47 Ok(ctx) => ctx,
48 Err(e) => return Err(format!("Error getting system clipboard: {}", e)),
49 };
50
51 let possible_hash = match ctx.get_contents() {
52 Ok(value) => value,
53 Err(e) => format!("Error reading from clipboard: {}", e),
54 };
55
56 let bytes = hex::decode(&possible_hash)
57 .map_err(|_| "Clipboard contains invalid or truncated hex".to_owned())?;
58 let alg = Algorithm::from_len(bytes.len())?;
59 let candidate = CandidateHash {
60 filename: None,
61 bytes,
62 };
63 Ok(CandidateHashes {
64 alg,
65 hashes: vec![candidate],
66 source: VerificationSource::Clipboard,
67 })
68 }
69
70 /// Generate a candidate hash from the digests file specified (could be "-" for STDIN), or throw an error.
71 fn get_from_file(path: &PathBuf) -> Result<CandidateHashes, String> {
72 // Get a reader for either standard input or the chosen path
73 let reader: Box<dyn Read> = if path.to_str() == Some("-") {
74 Box::new(std::io::stdin())
75 } else {
76 Box::new(File::open(path).map_err(|_| {
77 format!(
78 "Unable to open check file at path '{}'",
79 path.to_string_lossy()
80 )
81 })?)
82 };
83
84 // Read the first line, trimmed
85 let mut reader = BufReader::new(reader);
86 let mut line = String::new();
87 reader
88 .read_line(&mut line)
89 .map_err(|_| "Error reading from check file".to_owned())?;
90 let line = line.trim().to_owned();
91
92 // Does our first line look like a raw hash on its own? If so, use that
93 if let Some(candidate) = read_raw_candidate_from_file(&line, &path) {
94 return Ok(candidate);
95 }
96
97 // Maybe it's a digests file
98 // Reconstruct the full iterator by joining our already-read line with the others
99 let full_lines = vec![Ok(line)].into_iter().chain(reader.lines());
100
101 // Does the entire file look like a coreutils-style digests file? (SHA1SUMS, etc.)
102 if let Some(candidate) = read_coreutils_digests_from_file(full_lines, &path) {
103 return Ok(candidate);
104 }
105
106 // If neither of these techniques worked this is a fatal error
107 // The user requested we use this input but we couldn't
108 Err(format!(
109 "Provided check file '{}' was neither a hash nor a valid digests file",
110 path.to_string_lossy()
111 ))
112 }
113
114 fn read_raw_candidate_from_file(line: &str, path: &PathBuf) -> Option<CandidateHashes> {
115 // It is a little sad to use a dynamic regex in an otherwise nice Rust program
116 // These deserve to be replaced with a good old fashioned static parser
117 // But let's be honest: the impact is negligible
118 let re = Regex::new(r"^([[:xdigit:]]{32}|[[:xdigit:]]{40}|[[:xdigit:]]{64})$").unwrap();
119 if re.is_match(line) {
120 // These should both always succeed due to the matching
121 let bytes = match hex::decode(line) {
122 Ok(bytes) => bytes,
123 _ => return None,
124 };
125 let alg = match Algorithm::from_len(bytes.len()) {
126 Ok(alg) => alg,
127 _ => return None,
128 };
129 return Some(CandidateHashes {
130 alg,
131 source: VerificationSource::RawFile(path.clone()),
132 hashes: vec![CandidateHash {
133 bytes,
134 filename: None,
135 }],
136 });
137 }
138 None
139 }
140
141 fn read_coreutils_digests_from_file<I>(lines: I, path: &PathBuf) -> Option<CandidateHashes>
142 where
143 I: Iterator<Item = io::Result<String>>,
144 {
145 let re = Regex::new(
146 r"^(?P<hash>([[:xdigit:]]{32}|[[:xdigit:]]{40}|[[:xdigit:]]{64})) .(?P<filename>.+)$",
147 )
148 .unwrap();
149
150 let mut hashes = vec![];
151 let mut alg: Option<Algorithm> = None;
152 for l in lines {
153 if let Ok(l) = l {
154 let l = l.trim();
155 // Allow (ignore) blank lines
156 if l.is_empty() {
157 continue;
158 }
159 // If we can capture a valid line, use it
160 if let Some(captures) = re.captures(&l) {
161 let hash = &captures["hash"];
162 let filename = &captures["filename"];
163 // Decode the hex and algorithm for this line
164 let line_bytes = match hex::decode(hash) {
165 Ok(bytes) => bytes,
166 _ => return None,
167 };
168 let line_alg = match Algorithm::from_len(line_bytes.len()) {
169 Ok(alg) => alg,
170 _ => return None,
171 };
172 if alg.is_some() && alg != Some(line_alg) {
173 // Different algorithms in the same digest file are not supported
174 return None;
175 } else {
176 // If we are the first line, we define the overall algorithm
177 alg = Some(line_alg);
178 }
179 // So far so good - create an entry for this line
180 hashes.push(CandidateHash {
181 bytes: line_bytes,
182 filename: Some(filename.to_owned()),
183 });
184 } else {
185 // But if we have a line with content we cannot parse, this is an error
186 return None;
187 }
188 }
189 }
190
191 // It is a failure if we got zero hashes or we somehow don't know the algorithm
192 if hashes.is_empty() {
193 return None;
194 }
195 let alg = match alg {
196 Some(alg) => alg,
197 _ => return None,
198 };
199
200 // Otherwise all is well and we can return our results
201 Some(CandidateHashes {
202 alg,
203 source: VerificationSource::DigestsFile(path.clone()),
204 hashes,
205 })
206 }
207
208 /// Determine if the calculated hash matches any of the candidates.
209 ///
210 /// Ok result: the hash matches, and if the candidate has a filename, that matches too
211 /// Maybe result: the hash matches but the filename does not
212 /// Fail result: neither of the above
213 pub fn verify_hash<'a>(calculated: &Hash, candidates: &'a CandidateHashes) -> Verification<'a> {
214 let mut ok: Option<&CandidateHash> = None;
215 let mut maybe: Option<&CandidateHash> = None;
216 let mut messages = Vec::new();
217
218 for candidate in &candidates.hashes {
219 if candidate.bytes == calculated.bytes {
220 match candidate.filename {
221 None => ok = Some(candidate),
222 Some(ref candidate_filename) if candidate_filename == &calculated.filename => {
223 ok = Some(candidate)
224 }
225 Some(ref candidate_filename) => {
226 messages.push((
227 MessageLevel::Warning,
228 format!(
229 "The matched hash has filename '{}', which does not match the input.",
230 candidate_filename
231 ),
232 ));
233 maybe = Some(candidate);
234 }
235 }
236 }
237 }
238
239 // Warn that a "successful" MD5 result is not necessarily great
240 if candidates.alg == Algorithm::Md5 && (ok.is_some() || maybe.is_some()) {
241 messages.push((
242 MessageLevel::Note,
243 "MD5 can easily be forged. Use a stronger algorithm if possible.".to_owned(),
244 ))
245 }
246
247 // If we got a full match, great
248 if ok.is_some() {
249 return Verification {
250 match_level: MatchLevel::Ok,
251 comparison_hash: ok,
252 messages,
253 };
254 }
255
256 // Second priority, a "maybe" result
257 if maybe.is_some() {
258 return Verification {
259 match_level: MatchLevel::Maybe,
260 comparison_hash: maybe,
261 messages,
262 };
263 }
264
265 // Otherwise we failed
266 // If we only had one candidate hash, include it
267 let comparison = match candidates.hashes.len() {
268 1 => Some(&candidates.hashes[0]),
269 _ => None,
270 };
271 Verification {
272 match_level: MatchLevel::Fail,
273 comparison_hash: comparison,
274 messages,
275 }
276 }