Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/uu/b2sum/src/b2sum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -22,7 +23,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
uu_app(),
args,
calculate_blake2b_length,
true,
ChecksumTool::B2sum,
)
}

Expand Down
13 changes: 6 additions & 7 deletions src/uu/checksum_common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -66,7 +66,7 @@ pub fn standalone_with_length_main(
cmd: Command,
args: impl uucore::Args,
validate_len: fn(&str) -> UResult<HashLength>,
allow_empty_filename: bool,
tool: ChecksumTool,
) -> UResult<()> {
let matches = uucore::clap_localization::handle_clap_result(cmd, args)?;
let algo = Some(algo);
Expand All @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -148,7 +147,7 @@ pub fn checksum_main(
length: Option<HashLength>,
matches: ArgMatches,
output_format: OutputFormat,
allow_empty_filename: bool,
tool: ChecksumTool,
) -> UResult<()> {
let check = matches.get_flag("check");

Expand Down Expand Up @@ -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,
Expand Down
9 changes: 8 additions & 1 deletion src/uu/cksum/src/cksum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 {
Expand Down
56 changes: 45 additions & 11 deletions src/uucore/src/lib/features/checksum/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Comment thread
ChihweiLHBird marked this conversation as resolved.
Resolved
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,
Expand Down Expand Up @@ -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<HashLength>) -> Option<Vec<u8>> {
fn get_raw_expected_digest(
checksum: &str,
len_hint: Option<HashLength>,
tool: ChecksumTool,
) -> Option<Vec<u8>> {
// 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).
Expand All @@ -569,6 +597,10 @@ fn get_raw_expected_digest(checksum: &str, len_hint: Option<HashLength>) -> 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.

Expand Down Expand Up @@ -816,6 +848,7 @@ fn process_algo_based_line(
line_info: &LineInfo,
cli_algo_kind: Option<AlgoKind>,
last_algo: &mut Option<String>,
tool: ChecksumTool,
) -> Result<(Vec<u8>, SizedAlgoKind), LineCheckError> {
let (algo_kind, algo_len) = identify_algo_name_and_length(line_info, cli_algo_kind, last_algo)?;

Expand All @@ -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)
Expand All @@ -847,11 +880,12 @@ fn process_non_algo_based_line(
line_info: &LineInfo,
cli_algo_kind: AlgoKind,
cli_algo_length: Option<HashLength>,
tool: ChecksumTool,
) -> Result<(Vec<u8>, 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
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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(),
Expand All @@ -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());
}
Expand Down
14 changes: 14 additions & 0 deletions tests/by-util/test_b2sum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!());
Expand Down
16 changes: 15 additions & 1 deletion tests/by-util/test_md5sum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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!());
Expand Down
16 changes: 16 additions & 0 deletions tests/by-util/test_sha384sum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
Loading