From ad9850f18fadac54048f680d1da7f50f379cd124 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 11:05:37 -0500 Subject: [PATCH] fix(audio): validate FLAC stream precision and complete consumption --- crates/audio/src/flac_decode.rs | 49 +++++++++++++++++++++++++++++-- crates/audio/tests/flac_decode.rs | 37 +++++++++++++++++++++++ 2 files changed, 84 insertions(+), 2 deletions(-) diff --git a/crates/audio/src/flac_decode.rs b/crates/audio/src/flac_decode.rs index dfb6f5fc1..bb56e65c5 100644 --- a/crates/audio/src/flac_decode.rs +++ b/crates/audio/src/flac_decode.rs @@ -225,6 +225,11 @@ impl Decoder { /// Decode the frame at the start of `data`. pub fn decode_frame(&self, data: &[u8]) -> Result { + // StreamInfo has public fields: container callers can construct it without + // parse(), so validate before it can control shifts and sample reads. + if self.info.is_some_and(|i| !(4..=32).contains(&i.bits_per_sample) || !(1..=8).contains(&i.channels) || i.sample_rate == 0) { + return Err(DecodeError::Invalid("invalid decoder STREAMINFO")); + } let mut r = Bits::new(data); if r.bits(15)? != 0x7FFC { return Err(DecodeError::Invalid("missing frame sync code")); @@ -315,8 +320,7 @@ impl Decoder { } let mut chans = Vec::with_capacity(channels); for c in out { - let v: Result> = - c.into_iter().map(|s| i32::try_from(s).map_err(|_| DecodeError::Invalid("sample outside the bit depth"))).collect(); + let v: Result> = c.into_iter().map(|s| checked_sample(s, bits)).collect(); chans.push(v?); } Ok(Frame { sample_rate, bits_per_sample: bits as u8, variable_block_size: variable, number, block_size, channels: chans, size }) @@ -542,6 +546,11 @@ pub fn decode_with_limit(bytes: &[u8], max_values: u64) -> Result { if frame.channels.len() != channels.len() { return Err(DecodeError::Invalid("the channel count changes inside the stream")); } + // One file has one sample rate and depth. Otherwise callers would play + // samples under incompatible STREAMINFO metadata. + if frame.sample_rate != info.sample_rate || frame.bits_per_sample != info.bits_per_sample { + return Err(DecodeError::Invalid("frame format differs from STREAMINFO")); + } total += frame.block_size as u64; if total.saturating_mul(channels.len() as u64) > max_values { return Err(DecodeError::TooLarge); @@ -551,8 +560,44 @@ pub fn decode_with_limit(bytes: &[u8], max_values: u64) -> Result { } pos += frame.size; } + // Unknown total_samples must not turn a corrupt/truncated next frame into + // a successfully decoded shorter recording. + if pos != bytes.len() { + return Err(DecodeError::Invalid("trailing data or missing frame sync")); + } if info.total_samples != 0 && total != info.total_samples { return Err(DecodeError::Truncated); } Ok(Decoded { info, channels }) } + +// Validate the advertised precision, not just the storage type. Malformed +// predictors may produce an i32 that is still invalid for 4–24-bit audio. +fn checked_sample(sample: i64, bits: u32) -> Result { + if !(4..=32).contains(&bits) { + return Err(DecodeError::Invalid("invalid sample bit depth")); + } + let bound = 1i64 << (bits - 1); + if !(-bound..bound).contains(&sample) { + return Err(DecodeError::Invalid("sample outside the bit depth")); + } + i32::try_from(sample).map_err(|_| DecodeError::Invalid("sample outside the bit depth")) +} + +#[cfg(test)] +mod sample_bounds_tests { + use super::checked_sample; + + #[test] + fn samples_must_fit_declared_precision() { + for bits in 4..=32 { + let bound = 1i64 << (bits - 1); + assert_eq!(checked_sample(-bound, bits).map(i64::from), Ok(-bound)); + assert_eq!(checked_sample(bound - 1, bits).map(i64::from), Ok(bound - 1)); + assert!(checked_sample(-bound - 1, bits).is_err()); + assert!(checked_sample(bound, bits).is_err()); + } + assert!(checked_sample(0, 0).is_err()); + assert!(checked_sample(0, 255).is_err()); + } +} diff --git a/crates/audio/tests/flac_decode.rs b/crates/audio/tests/flac_decode.rs index c35267b08..a1895789b 100644 --- a/crates/audio/tests/flac_decode.rs +++ b/crates/audio/tests/flac_decode.rs @@ -172,3 +172,40 @@ fn ffmpeg_decodes_our_files_to_our_samples() { assert!(interleave(&got.channels) == want, "{channels}ch {bits}-bit: samples differ from ffmpeg's decode"); } } + +#[test] +fn rejects_unknown_length_corruption_and_streaminfo_format_mismatch() { + let src = signal(1, 100, 16, 7); + let original = encode(&src, 44_100, 16, 4096, 5); + let at = STREAMINFO_OFFSET as usize; + // STREAMINFO is not CRC-covered. Clear only the 36-bit total sample count. + let mut unknown = original.clone(); + unknown[at + 13] &= 0xf0; + unknown[at + 14..at + 18].fill(0); + assert_eq!(decode(&unknown).unwrap().channels, src); + for tail in [vec![0xff], vec![0x00, 0x00]] { + let mut broken = unknown.clone(); + broken.extend(tail); + assert!(decode(&broken).is_err()); + } + // The encoder spells these in frame headers, independent of STREAMINFO. + let mut wrong_rate = original.clone(); + let mut packed = u64::from_be_bytes(wrong_rate[at + 10..at + 18].try_into().unwrap()); + packed = (packed & ((1u64 << 44) - 1)) | (48_000u64 << 44); + wrong_rate[at + 10..at + 18].copy_from_slice(&packed.to_be_bytes()); + assert!(decode(&wrong_rate).is_err()); + let mut wrong_depth = original; + wrong_depth[at + 12] = (wrong_depth[at + 12] & !1) | 1; + wrong_depth[at + 13] = (wrong_depth[at + 13] & 0x0f) | 0x70; + assert!(decode(&wrong_depth).is_err()); +} + +#[test] +fn caller_constructed_streaminfo_is_validated_before_decoding() { + let file = encode(&signal(1, 100, 16, 9), 44_100, 16, 4096, 5); + let info = StreamInfo::parse(&file[STREAMINFO_OFFSET as usize..]).unwrap(); + for bits in [0, 1, 3, 33, 64, 255] { + let invalid = StreamInfo { bits_per_sample: bits, ..info }; + assert!(matches!(Decoder::new(invalid).decode_frame(&[]), Err(DecodeError::Invalid(_)))); + } +}