Skip to content

Commit bc58548

Browse files
fix(cksum): handle memory exhaustion gracefully for shake algorithms
1 parent 9a72a67 commit bc58548

1 file changed

Lines changed: 10 additions & 6 deletions

File tree

src/uu/cksum/src/cksum.rs

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ fn maybe_sanitize_length(
5252
match (algo_cli, input_length) {
5353
// No provided length is not a problem so far.
5454
(_, None) => Ok(None),
55-
55+
5656
// For SHA2 and SHA3, if a length is provided, ensure it is correct.
5757
(Some(algo @ (AlgoKind::Sha2 | AlgoKind::Sha3)), Some(s_len)) => {
5858
sanitize_sha2_sha3_length_str(algo, s_len).map(Some)
@@ -65,11 +65,16 @@ fn maybe_sanitize_length(
6565
(Some(AlgoKind::Shake128 | AlgoKind::Shake256), Some(len)) => match len.parse::<usize>() {
6666
Ok(0) => Ok(None),
6767
Ok(l) => {
68-
if l > u32::MAX as usize {
69-
Err(ChecksumError::InvalidLength(len.into()).into())
70-
} else {
71-
Ok(Some(HashLength::from_bits(l)))
68+
let bytes_needed = (l + 7) / 8;
69+
70+
let mut test_buffer: Vec<u8> = Vec::new();
71+
let safety_cushion = bytes_needed.saturating_add(65536);
72+
73+
if test_buffer.try_reserve(safety_cushion).is_err() {
74+
return Err(uucore::error::USimpleError::new(1, "memory exhausted"));
7275
}
76+
77+
Ok(Some(HashLength::from_bits(l)))
7378
}
7479
Err(_) => Err(ChecksumError::InvalidLength(len.into()).into()),
7580
},
@@ -121,7 +126,6 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
121126
if matches.get_flag(options::DEBUG) {
122127
print_cpu_debug_info();
123128
}
124-
125129
checksum_main(algo_cli, length, matches, output_format)
126130
}
127131

0 commit comments

Comments
 (0)