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