2 Algorithm
, CandidateHash
, CandidateHashes
, Hash
, MatchLevel
, MessageLevel
, Opt
, Verification
,
5 #[cfg(feature = "paste")]
6 use clipboard
::{ClipboardContext
, ClipboardProvider
};
10 use std
::io
::prelude
::*;
11 use std
::io
::BufReader
;
12 use std
::path
::PathBuf
;
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
)?
));
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
> {
31 hex
::decode(¶m
).map_err(|_
| "Provided hash is invalid or truncated hex".to_owned())?
;
32 let alg
= Algorithm
::from_len(bytes
.len())?
;
33 let candidate
= CandidateHash
{
39 hashes
: vec
![candidate
],
40 source
: VerificationSource
::CommandArgument
,
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")]
48 let mut ctx
: ClipboardContext
= match ClipboardProvider
::new() {
50 Err(e
) => return Err(format
!("Error getting system clipboard: {}", e
)),
53 let possible_hash
= match ctx
.get_contents() {
55 Err(e
) => format
!("Error reading from clipboard: {}", e
),
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
{
65 return Ok(CandidateHashes
{
67 hashes
: vec
![candidate
],
68 source
: VerificationSource
::Clipboard
,
71 #[cfg(not(feature = "paste"))]
73 return Err("Paste not implemented".to_owned());
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())
83 Box
::new(File
::open(path
).map_err(|_
| {
85 "Unable to open check file at path '{}'",
86 path
.to_string_lossy()
91 // Read the first line, trimmed
92 let mut reader
= BufReader
::new(reader
);
93 let mut line
= String
::new();
96 .map_err(|_
| "Error reading from check file".to_owned())?
;
97 let line
= line
.trim().to_owned();
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
);
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());
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
);
113 // If neither of these techniques worked this is a fatal error
114 // The user requested we use this input but we couldn't
116 "Provided check file '{}' was neither a hash nor a valid digests file",
117 path
.to_string_lossy()
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
) {
132 let alg
= match Algorithm
::from_len(bytes
.len()) {
136 return Some(CandidateHashes
{
138 source
: VerificationSource
::RawFile(path
.clone()),
139 hashes
: vec
![CandidateHash
{
148 fn read_coreutils_digests_from_file
<I
>(lines
: I
, path
: &PathBuf
) -> Option
<CandidateHashes
>
150 I
: Iterator
<Item
= io
::Result
<String
>>,
153 r
"^(?P<hash>([[:xdigit:]]{32}|[[:xdigit:]]{40}|[[:xdigit:]]{64})) .(?P<filename>.+)$",
157 let mut hashes
= vec
![];
158 let mut alg
: Option
<Algorithm
> = None
;
162 // Allow (ignore) blank lines
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
) {
175 let line_alg
= match Algorithm
::from_len(line_bytes
.len()) {
179 if alg
.is
_some
() && alg
!= Some(line_alg
) {
180 // Different algorithms in the same digest file are not supported
183 // If we are the first line, we define the overall algorithm
184 alg
= Some(line_alg
);
186 // So far so good - create an entry for this line
187 hashes
.push(CandidateHash
{
189 filename
: Some(filename
.to_owned()),
192 // But if we have a line with content we cannot parse, this is an error
198 // It is a failure if we got zero hashes or we somehow don't know the algorithm
199 if hashes
.is
_empty
() {
202 let alg
= match alg
{
207 // Otherwise all is well and we can return our results
208 Some(CandidateHashes
{
210 source
: VerificationSource
::DigestsFile(path
.clone()),
215 /// Determine if the calculated hash matches any of the candidates.
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();
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
=> {
232 Some(ref candidate_filename
) => {
234 MessageLevel
::Warning
,
236 "The matched hash has filename '{}', which does not match the input.",
240 maybe
= Some(candidate
);
246 // Warn that a "successful" MD5 result is not necessarily great
247 if candidates
.alg
== Algorithm
::Md5
&& (ok
.is
_some
() || maybe
.is
_some
()) {
250 "MD5 can easily be forged. Use a stronger algorithm if possible.".to_owned(),
254 // If we got a full match, great
256 return Verification
{
257 match_level
: MatchLevel
::Ok
,
263 // Second priority, a "maybe" result
265 return Verification
{
266 match_level
: MatchLevel
::Maybe
,
267 comparison_hash
: maybe
,
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]),
279 match_level
: MatchLevel
::Fail
,
280 comparison_hash
: comparison
,
290 fn test_read_raw_inputs() {
291 let example_path
: PathBuf
= "some_file".into
();
292 let valid_md5
= "d229da563da18fe5d58cd95a6467d584";
293 let valid_sha1
= "b314c7ebb7d599944981908b7f3ed33a30e78f3a";
294 let valid_sha1_2
= valid_sha1
.to_uppercase();
295 let valid_sha256
= "1eb85fc97224598dad1852b5d6483bbcf0aa8608790dcc657a5a2a761ae9c8c6";
299 let invalid3
= "d229da563da18fe5d58cd95a6467d58";
300 let invalid4
= "1eb85fc97224598dad1852b5d6483bbcf0aa8608790dcc657a5a2a761ae9c8c67";
301 let invalid5
= "1eb85fc97224598dad1852b5d 483bbcf0aa8608790dcc657a5a2a761ae9c8c6";
304 read_raw_candidate_from_file(valid_md5
, &example_path
),
305 Some(CandidateHashes
{
311 read_raw_candidate_from_file(valid_sha1
, &example_path
),
312 Some(CandidateHashes
{
313 alg
: Algorithm
::Sha1
,
318 read_raw_candidate_from_file(&valid_sha1_2
, &example_path
),
319 Some(CandidateHashes
{
320 alg
: Algorithm
::Sha1
,
325 read_raw_candidate_from_file(valid_sha256
, &example_path
),
326 Some(CandidateHashes
{
327 alg
: Algorithm
::Sha256
,
332 for i
in &[invalid1
, invalid2
, invalid3
, invalid4
, invalid5
] {
333 assert
!(read_raw_candidate_from_file(*i
, &example_path
).is
_none
());