diff --git a/src/uu/b2sum/src/b2sum.rs b/src/uu/b2sum/src/b2sum.rs index 4ba4dfa1d0b..385b4ffec6e 100644 --- a/src/uu/b2sum/src/b2sum.rs +++ b/src/uu/b2sum/src/b2sum.rs @@ -9,6 +9,7 @@ use clap::Command; use uu_checksum_common::{standalone_checksum_app_with_length, standalone_with_length_main}; +use uucore::checksum::validate::ChecksumTool; use uucore::checksum::{AlgoKind, BlakeLength, parse_blake_length}; use uucore::error::UResult; use uucore::translate; @@ -22,7 +23,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { uu_app(), args, calculate_blake2b_length, - true, + ChecksumTool::B2sum, ) } diff --git a/src/uu/checksum_common/src/lib.rs b/src/uu/checksum_common/src/lib.rs index 6e26d72240e..93d557eafe0 100644 --- a/src/uu/checksum_common/src/lib.rs +++ b/src/uu/checksum_common/src/lib.rs @@ -16,7 +16,7 @@ use clap::{Arg, ArgAction, ArgMatches, Command, ValueHint}; use uucore::checksum::compute::{ ChecksumComputeOptions, OutputFormat, perform_checksum_computation, }; -use uucore::checksum::validate::{self, ChecksumValidateOptions, ChecksumVerbose}; +use uucore::checksum::validate::{self, ChecksumTool, ChecksumValidateOptions, ChecksumVerbose}; use uucore::checksum::{AlgoKind, ChecksumError, HashLength, SizedAlgoKind}; use uucore::error::UResult; use uucore::line_ending::LineEnding; @@ -66,7 +66,7 @@ pub fn standalone_with_length_main( cmd: Command, args: impl uucore::Args, validate_len: fn(&str) -> UResult, - allow_empty_filename: bool, + tool: ChecksumTool, ) -> UResult<()> { let matches = uucore::clap_localization::handle_clap_result(cmd, args)?; let algo = Some(algo); @@ -82,7 +82,7 @@ pub fn standalone_with_length_main( let tag = matches.get_flag(options::TAG); let format = OutputFormat::from_standalone(text, tag); - checksum_main(algo, length, matches, format, allow_empty_filename) + checksum_main(algo, length, matches, format, tool) } /// Entrypoint for standalone checksums *NOT* accepting the `--length` argument @@ -94,8 +94,7 @@ pub fn standalone_main(algo: AlgoKind, cmd: Command, args: impl uucore::Args) -> let tag = matches.get_flag(options::TAG); let format = OutputFormat::from_standalone(text, tag); - // md5sum and sha*sum report an untagged line with no file name as improperly formatted. - checksum_main(algo, None, matches, format, false) + checksum_main(algo, None, matches, format, ChecksumTool::Other) } /// Base command processing for all the checksum executables. @@ -148,7 +147,7 @@ pub fn checksum_main( length: Option, matches: ArgMatches, output_format: OutputFormat, - allow_empty_filename: bool, + tool: ChecksumTool, ) -> UResult<()> { let check = matches.get_flag("check"); @@ -196,7 +195,7 @@ pub fn checksum_main( let verbose = ChecksumVerbose::new(status, quiet, warn); let opts = ChecksumValidateOptions { - allow_empty_filename, + tool, ignore_missing, strict, verbose, diff --git a/src/uu/cksum/src/cksum.rs b/src/uu/cksum/src/cksum.rs index 1a9806addc7..ae406bb297b 100644 --- a/src/uu/cksum/src/cksum.rs +++ b/src/uu/cksum/src/cksum.rs @@ -9,6 +9,7 @@ use clap::Command; use uu_checksum_common::{ChecksumCommand, checksum_main, default_checksum_app, options}; use uucore::checksum::compute::{DigestFormat, OutputFormat}; +use uucore::checksum::validate::ChecksumTool; use uucore::checksum::{ AlgoKind, BlakeLength, ChecksumError, HashLength, ReadingMode, Xxh3Length, parse_blake_length, sanitize_sha2_sha3_length_str, @@ -134,7 +135,13 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { print_cpu_debug_info(); } - checksum_main(algo_cli, length, matches, output_format, true) + checksum_main( + algo_cli, + length, + matches, + output_format, + ChecksumTool::Cksum, + ) } pub fn uu_app() -> Command { diff --git a/src/uucore/src/lib/features/checksum/validate.rs b/src/uucore/src/lib/features/checksum/validate.rs index 7b14575fe62..7a9fa9a1b27 100644 --- a/src/uucore/src/lib/features/checksum/validate.rs +++ b/src/uucore/src/lib/features/checksum/validate.rs @@ -66,12 +66,36 @@ impl ChecksumVerbose { } } +/// The utility that reads the checksum list. Some rules for a line depend on it. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub enum ChecksumTool { + Cksum, + B2sum, + /// md5sum and sha*sum + #[default] + Other, +} + +impl ChecksumTool { + /// An untagged line with no file name after the separator is a check of the file '' for + /// cksum and b2sum, and is improperly formatted for md5sum and sha*sum. + #[inline] + fn allows_empty_filename(self) -> bool { + matches!(self, Self::Cksum | Self::B2sum) + } + + /// cksum reads a digest in hexadecimal or in base64. md5sum, sha*sum and b2sum read + /// hexadecimal only. + #[inline] + fn allows_base64_digest(self) -> bool { + self == Self::Cksum + } +} + /// This struct regroups CLI flags. #[derive(Debug, Default, Clone, Copy)] pub struct ChecksumValidateOptions { - /// An untagged line with no file name after the separator is a check of the file '' for - /// cksum and b2sum, and is improperly formatted for md5sum and sha*sum. - pub allow_empty_filename: bool, + pub tool: ChecksumTool, pub ignore_missing: bool, pub strict: bool, pub verbose: ChecksumVerbose, @@ -551,7 +575,11 @@ impl LineInfo { } /// Extract the expected digest from the checksum string and decode it -fn get_raw_expected_digest(checksum: &str, len_hint: Option) -> Option> { +fn get_raw_expected_digest( + checksum: &str, + len_hint: Option, + tool: ChecksumTool, +) -> Option> { // If the length of the digest is not a multiple of 2, then it must be // improperly formatted (1 byte is 2 hex digits, and base64 strings should // always be a multiple of 4). @@ -569,6 +597,10 @@ fn get_raw_expected_digest(checksum: &str, len_hint: Option) -> Opti return Some(raw_ck); } + if !tool.allows_base64_digest() { + return None; + } + // If the checksum cannot be decoded as hexadecimal, interpret it as Base64 // instead. @@ -816,6 +848,7 @@ fn process_algo_based_line( line_info: &LineInfo, cli_algo_kind: Option, last_algo: &mut Option, + tool: ChecksumTool, ) -> Result<(Vec, SizedAlgoKind), LineCheckError> { let (algo_kind, algo_len) = identify_algo_name_and_length(line_info, cli_algo_kind, last_algo)?; @@ -833,7 +866,7 @@ fn process_algo_based_line( } .map(HashLength::from_bits); - let expected_checksum = get_raw_expected_digest(&line_info.checksum, len_hint) + let expected_checksum = get_raw_expected_digest(&line_info.checksum, len_hint, tool) .ok_or(LineCheckError::ImproperlyFormatted)?; let algo = SizedAlgoKind::from_unsized(algo_kind, algo_len) @@ -847,11 +880,12 @@ fn process_non_algo_based_line( line_info: &LineInfo, cli_algo_kind: AlgoKind, cli_algo_length: Option, + tool: ChecksumTool, ) -> Result<(Vec, SizedAlgoKind), LineCheckError> { use AlgoKind as ak; let expected_digest_sum = cli_algo_kind.expected_digest_bit_len(); - let expected_checksum = get_raw_expected_digest(&line_info.checksum, expected_digest_sum) + let expected_checksum = get_raw_expected_digest(&line_info.checksum, expected_digest_sum, tool) .ok_or(LineCheckError::ImproperlyFormatted)?; // When a specific algorithm name is input, use it and use the provided @@ -912,15 +946,15 @@ fn process_checksum_line( // The detected format is kept once the digest and the algorithm are valid. // A line rejected before that must not decide how the next ones are read. let mut line_format = *cached_line_format; - let line_info = LineInfo::parse(line, &mut line_format, opts.allow_empty_filename) + let line_info = LineInfo::parse(line, &mut line_format, opts.tool.allows_empty_filename()) .ok_or(LineCheckError::ImproperlyFormatted)?; let (expected_checksum, algo) = if line_info.format == LineFormat::AlgoBased { - process_algo_based_line(&line_info, cli_algo_name, last_algo)? + process_algo_based_line(&line_info, cli_algo_name, last_algo, opts.tool)? } else if let Some(cli_algo) = cli_algo_name { // If we match a non-algo based parser, we expect a cli argument // to give us the algorithm to use - process_non_algo_based_line(&line_info, cli_algo, cli_algo_length)? + process_non_algo_based_line(&line_info, cli_algo, cli_algo_length, opts.tool)? } else { // We have no clue of what algorithm to use return Err(LineCheckError::ImproperlyFormatted); @@ -1482,7 +1516,7 @@ mod tests { fn test_get_expected_digest() { let ck = "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=".to_owned(); - let result = get_raw_expected_digest(&ck, None); + let result = get_raw_expected_digest(&ck, None, ChecksumTool::Cksum); assert_eq!( result.unwrap(), @@ -1496,7 +1530,7 @@ mod tests { // The line misses a '=' at the end to be valid base64 let ck = "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU".to_owned(); - let result = get_raw_expected_digest(&ck, None); + let result = get_raw_expected_digest(&ck, None, ChecksumTool::Cksum); assert!(result.is_none()); } diff --git a/tests/by-util/test_b2sum.rs b/tests/by-util/test_b2sum.rs index 04fd1e52c36..83c3295fe12 100644 --- a/tests/by-util/test_b2sum.rs +++ b/tests/by-util/test_b2sum.rs @@ -77,6 +77,20 @@ fn test_check_status_reports_unusable_checksum_input() { .stderr_contains("'standard input': no properly formatted checksum lines found"); } +#[test] +fn test_check_tagged_base64_digest_is_improperly_formatted() { + let scene = TestScenario::new(util_name!()); + scene.fixtures.write("a", "a\n"); + + scene + .ucmd() + .arg("--check") + .pipe_in("BLAKE2b (a) = vt+7kNhYwtZ7fuj3Ujvj07VABO+eTwLyrXmh0Fv9/km4HjyS6/mbUEECtr8AP6NCWH9bMSTCBfVSBOjEtM59fA==\n") + .fails() + .no_stdout() + .stderr_is("b2sum: 'standard input': no properly formatted checksum lines found\n"); +} + #[test] fn test_invalid_b2sum_length_option_not_multiple_of_8() { let scene = TestScenario::new(util_name!()); diff --git a/tests/by-util/test_md5sum.rs b/tests/by-util/test_md5sum.rs index c3a7772738f..f01b728bf46 100644 --- a/tests/by-util/test_md5sum.rs +++ b/tests/by-util/test_md5sum.rs @@ -3,7 +3,7 @@ // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. -// spell-checker:ignore testf, ntestf +// spell-checker:ignore testf, ntestf, Qychcc use uutests::util::TestScenario; use uutests::{new_ucmd, util_name}; @@ -617,6 +617,20 @@ fn test_check_empty_file_name_does_not_set_format() { } } +#[test] +fn test_check_base64_digest_is_improperly_formatted() { + let scene = TestScenario::new(util_name!()); + scene.fixtures.write("a", "a\n"); + + scene + .ccmd("md5sum") + .arg("--check") + .pipe_in("YLcl8QychccNl4gN/oGRsw== a\n") + .fails() + .no_stdout() + .stderr_is("md5sum: 'standard input': no properly formatted checksum lines found\n"); +} + #[test] fn test_check_no_backslash_no_space() { let scene = TestScenario::new(util_name!()); diff --git a/tests/by-util/test_sha384sum.rs b/tests/by-util/test_sha384sum.rs index 8e1af024f8c..374e736e7ff 100644 --- a/tests/by-util/test_sha384sum.rs +++ b/tests/by-util/test_sha384sum.rs @@ -5,6 +5,22 @@ // spell-checker:ignore testf, ntestf +use uutests::at_and_ucmd; + use crate::common_checksum_tests::test_digest; test_digest! {sha384} + +// A SHA-256 digest has 64 hex digits. They are also valid base64 for 48 bytes, the size of a +// SHA-384 digest. +#[test] +fn test_check_sha256_digest_is_improperly_formatted() { + let (at, mut ucmd) = at_and_ucmd!(); + at.write("a", "a\n"); + + ucmd.arg("--check") + .pipe_in("87428fc522803d31065e7bce3cf03fe475096631e5e07bbd7a0fde60c4cf25c7 a\n") + .fails() + .no_stdout() + .stderr_is("sha384sum: 'standard input': no properly formatted checksum lines found\n"); +}