authoravatarclover caruso<git@paperclover.net>2026-12-01 17:02:48-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 17:13:06-08:00
loga791d487f17137e2647e72ee5a0841e504575f7c
treebc0f7653ca9793fb3cd40ef506ff738debb3f7c5
parent53b5fee5c10ef9042ab298c0666fcc4786fdab77
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

fix(engine): wave 29A media/readback/audio/av_decode hardening


4 files changed, 257 insertions(+), 71 deletions(-)

crates/engine/src/audio.rs+90-13
...@@ -4,7 +4,7 @@...@@ -4,7 +4,7 @@
4use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};4use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
5use cpal::{FromSample, Sample, SampleFormat, Stream};5use cpal::{FromSample, Sample, SampleFormat, Stream};
6use std::fs::File;6use std::fs::File;
7use std::io::{Cursor, ErrorKind};7use std::io::ErrorKind;
8use std::path::{Path, PathBuf};8use std::path::{Path, PathBuf};
9use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};9use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
10use std::sync::{Arc, Mutex};10use std::sync::{Arc, Mutex};
...@@ -62,6 +62,14 @@ fn decode_wav_stereo<const N: usize>(...@@ -62,6 +62,14 @@ fn decode_wav_stereo<const N: usize>(
62 }62 }
63}63}
6464
65fn alloc_wav_stereo_samples(total_frames: usize) -> Option<Vec<f32>> {
66 let sample_count = total_frames.checked_mul(2)?;
67 let mut stereo_samples = Vec::new();
68 stereo_samples.try_reserve_exact(sample_count).ok()?;
69 stereo_samples.resize(sample_count, 0.0_f32);
70 Some(stereo_samples)
71}
72
65/// Fast contiguous WAV loader for standard 1/2-channel PCM & IEEE-float RIFF/WAVE files.73/// Fast contiguous WAV loader for standard 1/2-channel PCM & IEEE-float RIFF/WAVE files.
66/// Returns `Ok(None)` for non-WAV, >2-channel, RF64, compressed, or unusual files so74/// Returns `Ok(None)` for non-WAV, >2-channel, RF64, compressed, or unusual files so
67/// callers fall back cleanly to `symphonia`.75/// callers fall back cleanly to `symphonia`.
...@@ -70,6 +78,13 @@ fn try_load_wav_fast(path: &Path, bytes: &[u8]) -> Result<Option<AudioTrack>, St...@@ -70,6 +78,13 @@ fn try_load_wav_fast(path: &Path, bytes: &[u8]) -> Result<Option<AudioTrack>, St
70 return Ok(None);78 return Ok(None);
71 }79 }
7280
81 let riff_size = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
82 let scan_end = if riff_size >= 4 {
83 bytes.len().min(8usize.saturating_add(riff_size as usize))
84 } else {
85 bytes.len()
86 };
87
73 const WAVE_FORMAT_PCM: u16 = 0x0001;88 const WAVE_FORMAT_PCM: u16 = 0x0001;
74 const WAVE_FORMAT_IEEE_FLOAT: u16 = 0x0003;89 const WAVE_FORMAT_IEEE_FLOAT: u16 = 0x0003;
75 const WAVE_FORMAT_EXTENSIBLE: u16 = 0xFFFE;90 const WAVE_FORMAT_EXTENSIBLE: u16 = 0xFFFE;
...@@ -86,7 +101,7 @@ fn try_load_wav_fast(path: &Path, bytes: &[u8]) -> Result<Option<AudioTrack>, St...@@ -86,7 +101,7 @@ fn try_load_wav_fast(path: &Path, bytes: &[u8]) -> Result<Option<AudioTrack>, St
86 let mut data_slice: Option<&[u8]> = None;101 let mut data_slice: Option<&[u8]> = None;
87 let mut pos = 12usize;102 let mut pos = 12usize;
88103
89 while pos + 8 <= bytes.len() {104 while scan_end.saturating_sub(pos) >= 8 {
90 let chunk_id = &bytes[pos..pos + 4];105 let chunk_id = &bytes[pos..pos + 4];
91 let chunk_size = u32::from_le_bytes([106 let chunk_size = u32::from_le_bytes([
92 bytes[pos + 4],107 bytes[pos + 4],
...@@ -98,7 +113,7 @@ fn try_load_wav_fast(path: &Path, bytes: &[u8]) -> Result<Option<AudioTrack>, St...@@ -98,7 +113,7 @@ fn try_load_wav_fast(path: &Path, bytes: &[u8]) -> Result<Option<AudioTrack>, St
98 let Some(payload_end) = payload_start.checked_add(chunk_size) else {113 let Some(payload_end) = payload_start.checked_add(chunk_size) else {
99 return Ok(None);114 return Ok(None);
100 };115 };
101 if payload_end > bytes.len() {116 if payload_end > scan_end {
102 return Ok(None);117 return Ok(None);
103 }118 }
104 let payload = &bytes[payload_start..payload_end];119 let payload = &bytes[payload_start..payload_end];
...@@ -183,7 +198,10 @@ fn try_load_wav_fast(path: &Path, bytes: &[u8]) -> Result<Option<AudioTrack>, St...@@ -183,7 +198,10 @@ fn try_load_wav_fast(path: &Path, bytes: &[u8]) -> Result<Option<AudioTrack>, St
183 data_slice = Some(payload);198 data_slice = Some(payload);
184 }199 }
185200
186 pos = payload_end + (chunk_size & 1);201 let Some(next_pos) = payload_end.checked_add(chunk_size & 1) else {
202 return Ok(None);
203 };
204 pos = next_pos;
187 }205 }
188206
189 let (Some((channels, sample_rate, block_align, sample_fmt)), Some(data)) = (fmt, data_slice)207 let (Some((channels, sample_rate, block_align, sample_fmt)), Some(data)) = (fmt, data_slice)
...@@ -195,7 +213,9 @@ fn try_load_wav_fast(path: &Path, bytes: &[u8]) -> Result<Option<AudioTrack>, St...@@ -195,7 +213,9 @@ fn try_load_wav_fast(path: &Path, bytes: &[u8]) -> Result<Option<AudioTrack>, St
195 let total_frames = data.len() / block_align;213 let total_frames = data.len() / block_align;
196 let usable_bytes = total_frames * block_align;214 let usable_bytes = total_frames * block_align;
197 let data = &data[..usable_bytes];215 let data = &data[..usable_bytes];
198 let mut stereo_samples = vec![0.0_f32; total_frames * 2];216 let Some(mut stereo_samples) = alloc_wav_stereo_samples(total_frames) else {
217 return Ok(None);
218 };
199219
200 match (channels, sample_fmt) {220 match (channels, sample_fmt) {
201 (1, WavSampleFormat::U8) => {221 (1, WavSampleFormat::U8) => {
...@@ -286,24 +306,29 @@ impl AudioTrack {...@@ -286,24 +306,29 @@ impl AudioTrack {
286 /// Decodes an audio file (`.wav`, `.mp3`, `.flac`, `.ogg`, `.m4a`, `.aac`) into306 /// Decodes an audio file (`.wav`, `.mp3`, `.flac`, `.ogg`, `.m4a`, `.aac`) into
287 /// interleaved stereo `f32` samples.307 /// interleaved stereo `f32` samples.
288 pub fn load(path: impl AsRef<Path>) -> Result<Self, String> {308 pub fn load(path: impl AsRef<Path>) -> Result<Self, String> {
309 const MAX_FAST_WAV_BYTES: u64 = 256 * 1024 * 1024;
289 let path_ref = path.as_ref();310 let path_ref = path.as_ref();
290 let is_wav = path_ref311 let is_wav = path_ref
291 .extension()312 .extension()
292 .and_then(|e| e.to_str())313 .and_then(|e| e.to_str())
293 .is_some_and(|ext| ext.eq_ignore_ascii_case("wav"));314 .is_some_and(|ext| ext.eq_ignore_ascii_case("wav"));
294315
295 let mss = if is_wav {316 if is_wav
317 && std::fs::metadata(path_ref)
318 .map(|m| m.len())
319 .is_ok_and(|len| len <= MAX_FAST_WAV_BYTES)
320 {
296 let bytes = std::fs::read(path_ref)321 let bytes = std::fs::read(path_ref)
297 .map_err(|e| format!("failed to open audio '{}': {e}", path_ref.display()))?;322 .map_err(|e| format!("failed to open audio '{}': {e}", path_ref.display()))?;
298 if let Some(track) = try_load_wav_fast(path_ref, &bytes)? {323 if let Some(track) = try_load_wav_fast(path_ref, &bytes)? {
299 return Ok(track);324 return Ok(track);
300 }325 }
301 MediaSourceStream::new(Box::new(Cursor::new(bytes)), Default::default())326 // Drop `bytes` before opening `File` so we stream instead of holding raw bytes in RAM.
302 } else {327 }
303 let file = File::open(path_ref)328
304 .map_err(|e| format!("failed to open audio '{}': {e}", path_ref.display()))?;329 let file = File::open(path_ref)
305 MediaSourceStream::new(Box::new(file), Default::default())330 .map_err(|e| format!("failed to open audio '{}': {e}", path_ref.display()))?;
306 };331 let mss = MediaSourceStream::new(Box::new(file), Default::default());
307 Self::load_via_symphonia(path_ref, mss)332 Self::load_via_symphonia(path_ref, mss)
308 }333 }
309334
...@@ -1243,7 +1268,7 @@ mod tests {...@@ -1243,7 +1268,7 @@ mod tests {
1243 let fast = try_load_wav_fast(&p, &bytes)1268 let fast = try_load_wav_fast(&p, &bytes)
1244 .unwrap_or_else(|e| panic!("{label}: {e}"))1269 .unwrap_or_else(|e| panic!("{label}: {e}"))
1245 .unwrap_or_else(|| panic!("{label}: expected fast path"));1270 .unwrap_or_else(|| panic!("{label}: expected fast path"));
1246 let mss = MediaSourceStream::new(Box::new(Cursor::new(bytes)), Default::default());1271 let mss = MediaSourceStream::new(Box::new(std::io::Cursor::new(bytes)), Default::default());
1247 let ref_track = AudioTrack::load_via_symphonia(&p, mss).expect("symphonia fallback");1272 let ref_track = AudioTrack::load_via_symphonia(&p, mss).expect("symphonia fallback");
1248 assert_eq!(fast.sample_rate, ref_track.sample_rate, "{label} sr");1273 assert_eq!(fast.sample_rate, ref_track.sample_rate, "{label} sr");
1249 assert_eq!(fast.channels, ref_track.channels, "{label} ch");1274 assert_eq!(fast.channels, ref_track.channels, "{label} ch");
...@@ -1255,4 +1280,56 @@ mod tests {...@@ -1255,4 +1280,56 @@ mod tests {
1255 assert_eq!(got_peaks, exp_peaks, "{label} peaks mismatch");1280 assert_eq!(got_peaks, exp_peaks, "{label} peaks mismatch");
1256 }1281 }
1257 }1282 }
1283
1284 #[test]
1285 fn wav_fast_ignores_trailing_garbage_past_riff_size_and_rejects_overflow() {
1286 // Build a valid minimal mono 16-bit PCM WAV with 4 frames, then append trailing garbage
1287 // past `8 + riff_size` (including a bogus second `data` chunk) and ensure it is ignored.
1288 let data_bytes: Vec<u8> = [0i16, 16384, -16384, 32767]
1289 .into_iter()
1290 .flat_map(|s| s.to_le_bytes())
1291 .collect();
1292 let riff_size = (36 + data_bytes.len()) as u32;
1293 let mut wav = Vec::new();
1294 wav.extend_from_slice(b"RIFF");
1295 wav.extend_from_slice(&riff_size.to_le_bytes());
1296 wav.extend_from_slice(b"WAVEfmt ");
1297 wav.extend_from_slice(&16u32.to_le_bytes());
1298 wav.extend_from_slice(&1u16.to_le_bytes()); // PCM
1299 wav.extend_from_slice(&1u16.to_le_bytes()); // mono
1300 wav.extend_from_slice(&48000u32.to_le_bytes());
1301 wav.extend_from_slice(&(48000u32 * 2).to_le_bytes());
1302 wav.extend_from_slice(&2u16.to_le_bytes());
1303 wav.extend_from_slice(&16u16.to_le_bytes());
1304 wav.extend_from_slice(b"data");
1305 wav.extend_from_slice(&(data_bytes.len() as u32).to_le_bytes());
1306 wav.extend_from_slice(&data_bytes);
1307
1308 let clean = try_load_wav_fast(Path::new("clean.wav"), &wav)
1309 .expect("clean ok")
1310 .expect("clean fast");
1311
1312 let mut with_trailing = wav.clone();
1313 with_trailing.extend_from_slice(b"data\xff\xff\xff\xffTRAILING_GARBAGE");
1314 let parsed = try_load_wav_fast(Path::new("trailing.wav"), &with_trailing)
1315 .expect("trailing ok")
1316 .expect("trailing fast should ignore bytes past riff_size");
1317 assert_eq!(parsed.samples, clean.samples);
1318 assert_eq!(parsed.sample_rate, 48000);
1319
1320 // Huge `data` chunk size in header must fall back cleanly (`Ok(None)`), never panic.
1321 let mut huge_chunk = wav.clone();
1322 let data_size_offset = 40;
1323 huge_chunk[data_size_offset..data_size_offset + 4]
1324 .copy_from_slice(&u32::MAX.to_le_bytes());
1325 assert!(
1326 try_load_wav_fast(Path::new("huge.wav"), &huge_chunk)
1327 .expect("huge chunk ok")
1328 .is_none()
1329 );
1330
1331 // `total_frames.checked_mul(2)` overflow and oversized reservation must return `None`.
1332 assert!(alloc_wav_stereo_samples(usize::MAX / 2 + 1).is_none());
1333 assert!(alloc_wav_stereo_samples(usize::MAX / 4).is_none());
1334 }
1258}1335}
crates/engine/src/av_decode.m+7-2
...@@ -30,6 +30,7 @@...@@ -30,6 +30,7 @@
30@property(nonatomic, assign) int64_t lastFrameIdx;30@property(nonatomic, assign) int64_t lastFrameIdx;
31@property(nonatomic, strong) NSMutableData *lastFrameRgba;31@property(nonatomic, strong) NSMutableData *lastFrameRgba;
32@property(nonatomic, assign) BOOL hasLastFrame;32@property(nonatomic, assign) BOOL hasLastFrame;
33@property(nonatomic, assign) BOOL lastFrameIsEof;
33@end34@end
3435
35@implementation AvVideoDecoderObj36@implementation AvVideoDecoderObj
...@@ -414,6 +415,7 @@ AvVideoDecoder *av_video_open(...@@ -414,6 +415,7 @@ AvVideoDecoder *av_video_open(
414 obj.lastFrameIdx = -1;415 obj.lastFrameIdx = -1;
415 obj.lastFrameRgba = nil;416 obj.lastFrameRgba = nil;
416 obj.hasLastFrame = NO;417 obj.hasLastFrame = NO;
418 obj.lastFrameIsEof = NO;
417419
418 // Verify AVAssetReader can actually open and decode this asset/codec.420 // Verify AVAssetReader can actually open and decode this asset/codec.
419 if (![obj openReaderAtSeconds:0.0]) {421 if (![obj openReaderAtSeconds:0.0]) {
...@@ -515,7 +517,7 @@ int av_video_decode_frame(...@@ -515,7 +517,7 @@ int av_video_decode_frame(
515 // If requesting a frame past EOF (including sequential advance stepping past EOF or517 // If requesting a frame past EOF (including sequential advance stepping past EOF or
516 // container duration overestimating the last video sample by > 4 frames), retry from518 // container duration overestimating the last video sample by > 4 frames), retry from
517 // endAnchor - 1.0 and, if that still misses, from the last known decoded frame timestamp.519 // endAnchor - 1.0 and, if that still misses, from the last known decoded frame timestamp.
518 if (!chosen && !obj.hasLastFrame && frame_idx > 0) {520 if (!chosen && !obj.lastFrameIsEof && frame_idx > 0) {
519 double endAnchor = obj.durSec > 0.0 ? fmin(targetPts, obj.trackStartSec + obj.durSec) : targetPts;521 double endAnchor = obj.durSec > 0.0 ? fmin(targetPts, obj.trackStartSec + obj.durSec) : targetPts;
520 double fallbackSec = fmax(0.0, endAnchor - 1.0);522 double fallbackSec = fmax(0.0, endAnchor - 1.0);
521 if ((canAdvance || fallbackSec < seekSec - 0.05) && [obj openReaderAtSeconds:fallbackSec]) {523 if ((canAdvance || fallbackSec < seekSec - 0.05) && [obj openReaderAtSeconds:fallbackSec]) {
...@@ -551,13 +553,16 @@ int av_video_decode_frame(...@@ -551,13 +553,16 @@ int av_video_decode_frame(
551 CFRelease(chosen);553 CFRelease(chosen);
552554
553 if (ok) {555 if (ok) {
554 if (hitEof || obj.nbFrames <= 0 || frame_idx >= obj.nbFrames - 4) {556 if (hitEof || (!obj.lastFrameIsEof && (obj.nbFrames <= 0 || frame_idx >= obj.nbFrames - 4))) {
555 if (!obj.lastFrameRgba || obj.lastFrameRgba.length < required) {557 if (!obj.lastFrameRgba || obj.lastFrameRgba.length < required) {
556 obj.lastFrameRgba = [NSMutableData dataWithLength:required];558 obj.lastFrameRgba = [NSMutableData dataWithLength:required];
557 }559 }
558 if (obj.lastFrameRgba.length >= required) {560 if (obj.lastFrameRgba.length >= required) {
559 memcpy(obj.lastFrameRgba.mutableBytes, out_rgba, required);561 memcpy(obj.lastFrameRgba.mutableBytes, out_rgba, required);
560 obj.hasLastFrame = YES;562 obj.hasLastFrame = YES;
563 if (hitEof) {
564 obj.lastFrameIsEof = YES;
565 }
561 }566 }
562 }567 }
563 obj.lastFrameIdx = frame_idx;568 obj.lastFrameIdx = frame_idx;
crates/engine/src/eval/dispatch.rs+20-4
...@@ -83,15 +83,31 @@ impl PendingReadback {...@@ -83,15 +83,31 @@ impl PendingReadback {
83 map_res?;83 map_res?;
84 let slice = self.buf.slice(..self.required_bytes);84 let slice = self.buf.slice(..self.required_bytes);
85 let data = slice.get_mapped_range()?;85 let data = slice.get_mapped_range()?;
86 let total_bytes = (self.width * self.height * 4) as usize;86 let total_bytes = (self.width as usize)
87 .checked_mul(self.height as usize)
88 .and_then(|n| n.checked_mul(4))
89 .ok_or("readback buffer size overflow")?;
87 dst.clear();90 dst.clear();
88 dst.reserve(total_bytes);91 dst.reserve(total_bytes);
89 if self.padded_bpr == self.unpadded_bpr {92 if self.padded_bpr == self.unpadded_bpr {
90 dst.extend_from_slice(&data[..total_bytes]);93 let src = data
94 .get(..total_bytes)
95 .ok_or("readback mapped buffer smaller than expected")?;
96 dst.extend_from_slice(src);
91 } else {97 } else {
98 let padded_bpr = self.padded_bpr as usize;
99 let unpadded_bpr = self.unpadded_bpr as usize;
92 for row in 0..self.height as usize {100 for row in 0..self.height as usize {
93 let start = row * self.padded_bpr as usize;101 let start = row
94 dst.extend_from_slice(&data[start..start + self.unpadded_bpr as usize]);102 .checked_mul(padded_bpr)
103 .ok_or("readback row offset overflow")?;
104 let end = start
105 .checked_add(unpadded_bpr)
106 .ok_or("readback row end overflow")?;
107 let src = data
108 .get(start..end)
109 .ok_or("readback mapped row out of bounds")?;
110 dst.extend_from_slice(src);
95 }111 }
96 }112 }
97 drop(data);113 drop(data);
crates/engine/src/media.rs+140-52
...@@ -134,9 +134,17 @@ fn u16_be_to_u8_rounded(hi: u8, lo: u8) -> u8 {...@@ -134,9 +134,17 @@ fn u16_be_to_u8_rounded(hi: u8, lo: u8) -> u8 {
134 ((u16::from_be_bytes([hi, lo]) as u32 + 128) / 257) as u8134 ((u16::from_be_bytes([hi, lo]) as u32 + 128) / 257) as u8
135}135}
136136
137const MAX_PNG_OUTPUT_BYTES: usize = 512 * 1024 * 1024;
138
139enum PngDecodeOutcome {
140 Decoded(([u32; 2], Vec<u8>, bool)),
141 Fallback,
142 Reject,
143}
144
137fn decode_png_rows<R: std::io::BufRead + std::io::Seek, F>(145fn decode_png_rows<R: std::io::BufRead + std::io::Seek, F>(
138 reader: &mut png::Reader<R>,146 reader: &mut png::Reader<R>,
139 w: u32,147 line_size: usize,
140 out_len: usize,148 out_len: usize,
141 row_out_bytes: usize,149 row_out_bytes: usize,
142 mut convert_row: F,150 mut convert_row: F,
...@@ -144,9 +152,12 @@ fn decode_png_rows<R: std::io::BufRead + std::io::Seek, F>(...@@ -144,9 +152,12 @@ fn decode_png_rows<R: std::io::BufRead + std::io::Seek, F>(
144where152where
145 F: FnMut(&[u8], &mut [u8]),153 F: FnMut(&[u8], &mut [u8]),
146{154{
147 let mut rgba = vec![0u8; out_len];155 let mut rgba = Vec::new();
148 let line_size = reader.output_line_size(w)?;156 rgba.try_reserve_exact(out_len).ok()?;
149 let mut row_buf = vec![0u8; line_size];157 rgba.resize(out_len, 0);
158 let mut row_buf = Vec::new();
159 row_buf.try_reserve_exact(line_size).ok()?;
160 row_buf.resize(line_size, 0);
150 for dst_row in rgba.chunks_exact_mut(row_out_bytes) {161 for dst_row in rgba.chunks_exact_mut(row_out_bytes) {
151 reader.read_row(&mut row_buf).ok()??;162 reader.read_row(&mut row_buf).ok()??;
152 convert_row(&row_buf, dst_row);163 convert_row(&row_buf, dst_row);
...@@ -155,79 +166,108 @@ where...@@ -155,79 +166,108 @@ where
155}166}
156167
157/// Fast direct PNG decoder matching `image::load_from_memory().into_rgba8()` bit-for-bit.168/// Fast direct PNG decoder matching `image::load_from_memory().into_rgba8()` bit-for-bit.
158/// Returns `None` for non-PNG, interlaced, animated, ICC-tagged, or unusual formats so the169/// Returns `Fallback` for non-PNG, interlaced, animated, ICC-tagged, or unusual formats so the
159/// caller falls back cleanly to `image::load_from_memory`.170/// caller falls back cleanly to `image::load_from_memory`, and `Reject` for corrupt or
160fn decode_png_bytes(bytes: &[u8]) -> Option<([u32; 2], Vec<u8>, bool)> {171/// oversized PNGs so callers fail immediately without double-decoding or OOM.
172fn decode_png_bytes(bytes: &[u8]) -> PngDecodeOutcome {
161 const PNG_SIGNATURE: [u8; 8] = [137, 80, 78, 71, 13, 10, 26, 10];173 const PNG_SIGNATURE: [u8; 8] = [137, 80, 78, 71, 13, 10, 26, 10];
162 if !bytes.starts_with(&PNG_SIGNATURE) {174 if !bytes.starts_with(&PNG_SIGNATURE) {
163 return None;175 return PngDecodeOutcome::Fallback;
164 }176 }
165177
166 let mut decoder = png::Decoder::new_with_limits(178 let mut decoder = png::Decoder::new_with_limits(
167 std::io::Cursor::new(bytes),179 std::io::Cursor::new(bytes),
168 png::Limits {180 png::Limits {
169 bytes: 512 * 1024 * 1024,181 bytes: MAX_PNG_OUTPUT_BYTES,
170 },182 },
171 );183 );
172 decoder.set_ignore_text_chunk(true);184 decoder.set_ignore_text_chunk(true);
173 decoder.set_transformations(png::Transformations::EXPAND);185 decoder.set_transformations(png::Transformations::EXPAND);
174186
175 let mut reader = decoder.read_info().ok()?;187 let Ok(mut reader) = decoder.read_info() else {
188 return PngDecodeOutcome::Reject;
189 };
176 let info = reader.info();190 let info = reader.info();
191 let (w, h) = info.size();
192 if w == 0 || h == 0 {
193 return PngDecodeOutcome::Reject;
194 }
195
196 let Some(pixel_count) = (w as usize).checked_mul(h as usize) else {
197 return PngDecodeOutcome::Reject;
198 };
199 let Some(out_len) = pixel_count.checked_mul(4) else {
200 return PngDecodeOutcome::Reject;
201 };
202 if out_len > MAX_PNG_OUTPUT_BYTES {
203 return PngDecodeOutcome::Reject;
204 }
205
177 if info.interlaced206 if info.interlaced
178 || info.icc_profile.is_some()207 || info.icc_profile.is_some()
179 || info.animation_control.is_some()208 || info.animation_control.is_some()
180 || info.frame_control.is_some()209 || info.frame_control.is_some()
181 {210 {
182 return None;211 return PngDecodeOutcome::Fallback;
183 }
184 let (w, h) = info.size();
185 if w == 0 || h == 0 {
186 return None;
187 }212 }
188213
189 let (color_type, bit_depth) = reader.output_color_type();214 let (color_type, bit_depth) = reader.output_color_type();
190 let pixel_count = (w as usize).checked_mul(h as usize)?;215 let Some(row_out_bytes) = (w as usize).checked_mul(4) else {
191 let out_len = pixel_count.checked_mul(4)?;216 return PngDecodeOutcome::Reject;
192 let row_out_bytes = (w as usize).checked_mul(4)?;217 };
218 let Some(line_size) = reader.output_line_size(w) else {
219 return PngDecodeOutcome::Reject;
220 };
193221
194 match (color_type, bit_depth) {222 match (color_type, bit_depth) {
195 (png::ColorType::Rgba, png::BitDepth::Eight) => {223 (png::ColorType::Rgba, png::BitDepth::Eight) => {
196 let mut rgba = vec![0u8; out_len];224 let mut rgba = Vec::new();
197 reader.next_frame(&mut rgba).ok()?;225 if rgba.try_reserve_exact(out_len).is_err() {
198 Some(([w, h], rgba, true))226 return PngDecodeOutcome::Reject;
227 }
228 rgba.resize(out_len, 0);
229 if reader.next_frame(&mut rgba).is_err() {
230 return PngDecodeOutcome::Reject;
231 }
232 PngDecodeOutcome::Decoded(([w, h], rgba, true))
199 }233 }
200 (png::ColorType::Rgb, png::BitDepth::Eight) => {234 (png::ColorType::Rgb, png::BitDepth::Eight) => {
201 let rgba = decode_png_rows(&mut reader, w, out_len, row_out_bytes, |src, dst| {235 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
202 let (src_chunks, _) = src.as_chunks::<3>();236 let (src_chunks, _) = src.as_chunks::<3>();
203 let (dst_chunks, _) = dst.as_chunks_mut::<4>();237 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
204 for (&[r, g, b], dst_px) in src_chunks.iter().zip(dst_chunks) {238 for (&[r, g, b], dst_px) in src_chunks.iter().zip(dst_chunks) {
205 *dst_px = [r, g, b, 255];239 *dst_px = [r, g, b, 255];
206 }240 }
207 })?;241 }) else {
208 Some(([w, h], rgba, false))242 return PngDecodeOutcome::Reject;
243 };
244 PngDecodeOutcome::Decoded(([w, h], rgba, false))
209 }245 }
210 (png::ColorType::Grayscale, png::BitDepth::Eight) => {246 (png::ColorType::Grayscale, png::BitDepth::Eight) => {
211 let rgba = decode_png_rows(&mut reader, w, out_len, row_out_bytes, |src, dst| {247 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
212 let (dst_chunks, _) = dst.as_chunks_mut::<4>();248 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
213 for (&g, dst_px) in src.iter().zip(dst_chunks) {249 for (&g, dst_px) in src.iter().zip(dst_chunks) {
214 *dst_px = [g, g, g, 255];250 *dst_px = [g, g, g, 255];
215 }251 }
216 })?;252 }) else {
217 Some(([w, h], rgba, false))253 return PngDecodeOutcome::Reject;
254 };
255 PngDecodeOutcome::Decoded(([w, h], rgba, false))
218 }256 }
219 (png::ColorType::GrayscaleAlpha, png::BitDepth::Eight) => {257 (png::ColorType::GrayscaleAlpha, png::BitDepth::Eight) => {
220 let rgba = decode_png_rows(&mut reader, w, out_len, row_out_bytes, |src, dst| {258 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
221 let (src_chunks, _) = src.as_chunks::<2>();259 let (src_chunks, _) = src.as_chunks::<2>();
222 let (dst_chunks, _) = dst.as_chunks_mut::<4>();260 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
223 for (&[g, a], dst_px) in src_chunks.iter().zip(dst_chunks) {261 for (&[g, a], dst_px) in src_chunks.iter().zip(dst_chunks) {
224 *dst_px = [g, g, g, a];262 *dst_px = [g, g, g, a];
225 }263 }
226 })?;264 }) else {
227 Some(([w, h], rgba, true))265 return PngDecodeOutcome::Reject;
266 };
267 PngDecodeOutcome::Decoded(([w, h], rgba, true))
228 }268 }
229 (png::ColorType::Rgba, png::BitDepth::Sixteen) => {269 (png::ColorType::Rgba, png::BitDepth::Sixteen) => {
230 let rgba = decode_png_rows(&mut reader, w, out_len, row_out_bytes, |src, dst| {270 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
231 let (src_chunks, _) = src.as_chunks::<8>();271 let (src_chunks, _) = src.as_chunks::<8>();
232 let (dst_chunks, _) = dst.as_chunks_mut::<4>();272 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
233 for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) {273 for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) {
...@@ -238,11 +278,13 @@ fn decode_png_bytes(bytes: &[u8]) -> Option<([u32; 2], Vec<u8>, bool)> {...@@ -238,11 +278,13 @@ fn decode_png_bytes(bytes: &[u8]) -> Option<([u32; 2], Vec<u8>, bool)> {
238 u16_be_to_u8_rounded(s[6], s[7]),278 u16_be_to_u8_rounded(s[6], s[7]),
239 ];279 ];
240 }280 }
241 })?;281 }) else {
242 Some(([w, h], rgba, true))282 return PngDecodeOutcome::Reject;
283 };
284 PngDecodeOutcome::Decoded(([w, h], rgba, true))
243 }285 }
244 (png::ColorType::Rgb, png::BitDepth::Sixteen) => {286 (png::ColorType::Rgb, png::BitDepth::Sixteen) => {
245 let rgba = decode_png_rows(&mut reader, w, out_len, row_out_bytes, |src, dst| {287 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
246 let (src_chunks, _) = src.as_chunks::<6>();288 let (src_chunks, _) = src.as_chunks::<6>();
247 let (dst_chunks, _) = dst.as_chunks_mut::<4>();289 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
248 for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) {290 for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) {
...@@ -253,38 +295,46 @@ fn decode_png_bytes(bytes: &[u8]) -> Option<([u32; 2], Vec<u8>, bool)> {...@@ -253,38 +295,46 @@ fn decode_png_bytes(bytes: &[u8]) -> Option<([u32; 2], Vec<u8>, bool)> {
253 255,295 255,
254 ];296 ];
255 }297 }
256 })?;298 }) else {
257 Some(([w, h], rgba, false))299 return PngDecodeOutcome::Reject;
300 };
301 PngDecodeOutcome::Decoded(([w, h], rgba, false))
258 }302 }
259 (png::ColorType::Grayscale, png::BitDepth::Sixteen) => {303 (png::ColorType::Grayscale, png::BitDepth::Sixteen) => {
260 let rgba = decode_png_rows(&mut reader, w, out_len, row_out_bytes, |src, dst| {304 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
261 let (src_chunks, _) = src.as_chunks::<2>();305 let (src_chunks, _) = src.as_chunks::<2>();
262 let (dst_chunks, _) = dst.as_chunks_mut::<4>();306 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
263 for (&[hi, lo], dst_px) in src_chunks.iter().zip(dst_chunks) {307 for (&[hi, lo], dst_px) in src_chunks.iter().zip(dst_chunks) {
264 let g = u16_be_to_u8_rounded(hi, lo);308 let g = u16_be_to_u8_rounded(hi, lo);
265 *dst_px = [g, g, g, 255];309 *dst_px = [g, g, g, 255];
266 }310 }
267 })?;311 }) else {
268 Some(([w, h], rgba, false))312 return PngDecodeOutcome::Reject;
313 };
314 PngDecodeOutcome::Decoded(([w, h], rgba, false))
269 }315 }
270 (png::ColorType::GrayscaleAlpha, png::BitDepth::Sixteen) => {316 (png::ColorType::GrayscaleAlpha, png::BitDepth::Sixteen) => {
271 let rgba = decode_png_rows(&mut reader, w, out_len, row_out_bytes, |src, dst| {317 let Some(rgba) = decode_png_rows(&mut reader, line_size, out_len, row_out_bytes, |src, dst| {
272 let (src_chunks, _) = src.as_chunks::<4>();318 let (src_chunks, _) = src.as_chunks::<4>();
273 let (dst_chunks, _) = dst.as_chunks_mut::<4>();319 let (dst_chunks, _) = dst.as_chunks_mut::<4>();
274 for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) {320 for (&s, dst_px) in src_chunks.iter().zip(dst_chunks) {
275 let g = u16_be_to_u8_rounded(s[0], s[1]);321 let g = u16_be_to_u8_rounded(s[0], s[1]);
276 *dst_px = [g, g, g, u16_be_to_u8_rounded(s[2], s[3])];322 *dst_px = [g, g, g, u16_be_to_u8_rounded(s[2], s[3])];
277 }323 }
278 })?;324 }) else {
279 Some(([w, h], rgba, true))325 return PngDecodeOutcome::Reject;
326 };
327 PngDecodeOutcome::Decoded(([w, h], rgba, true))
280 }328 }
281 _ => None,329 _ => PngDecodeOutcome::Fallback,
282 }330 }
283}331}
284332
285fn decode_raster_bytes(bytes: &[u8]) -> Option<([u32; 2], Vec<u8>, bool)> {333fn decode_raster_bytes(bytes: &[u8]) -> Option<([u32; 2], Vec<u8>, bool)> {
286 if let Some(decoded) = decode_png_bytes(bytes) {334 match decode_png_bytes(bytes) {
287 return Some(decoded);335 PngDecodeOutcome::Decoded(decoded) => return Some(decoded),
336 PngDecodeOutcome::Reject => return None,
337 PngDecodeOutcome::Fallback => {}
288 }338 }
289 let dyn_img = image::load_from_memory(bytes).ok()?;339 let dyn_img = image::load_from_memory(bytes).ok()?;
290 let has_alpha = dyn_img.color().has_alpha();340 let has_alpha = dyn_img.color().has_alpha();
...@@ -299,11 +349,7 @@ fn open_raster_rgba(path: &Path) -> Option<([u32; 2], Vec<u8>, bool)> {...@@ -299,11 +349,7 @@ fn open_raster_rgba(path: &Path) -> Option<([u32; 2], Vec<u8>, bool)> {
299 }349 }
300 // Read file contents in one contiguous pass to avoid tiny buffered syscalls over SMB/network shares.350 // Read file contents in one contiguous pass to avoid tiny buffered syscalls over SMB/network shares.
301 match std::fs::read(path) {351 match std::fs::read(path) {
302 Ok(bytes) => {352 Ok(bytes) => return decode_raster_bytes(&bytes),
303 if let Some(decoded) = decode_raster_bytes(&bytes) {
304 return Some(decoded);
305 }
306 }
307 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None,353 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None,
308 Err(_) => {}354 Err(_) => {}
309 }355 }
...@@ -3898,11 +3944,53 @@ mod tests {...@@ -3898,11 +3944,53 @@ mod tests {
3898 let expected_size = [dyn_img.width(), dyn_img.height()];3944 let expected_size = [dyn_img.width(), dyn_img.height()];
3899 let expected_rgba = dyn_img.into_rgba8().into_raw();3945 let expected_rgba = dyn_img.into_rgba8().into_raw();
39003946
3901 let (got_size, got_rgba, got_has_alpha) =3947 let (got_size, got_rgba, got_has_alpha) = match decode_png_bytes(&bytes) {
3902 decode_png_bytes(&bytes).unwrap_or_else(|| panic!("direct decode failed for {label}"));3948 PngDecodeOutcome::Decoded(v) => v,
3949 PngDecodeOutcome::Fallback | PngDecodeOutcome::Reject => {
3950 panic!("direct decode failed for {label}")
3951 }
3952 };
3903 assert_eq!(got_size, expected_size, "size mismatch for {label}");3953 assert_eq!(got_size, expected_size, "size mismatch for {label}");
3904 assert_eq!(got_has_alpha, expected_has_alpha, "alpha flag mismatch for {label}");3954 assert_eq!(got_has_alpha, expected_has_alpha, "alpha flag mismatch for {label}");
3905 assert_eq!(got_rgba, expected_rgba, "pixel mismatch for {label}");3955 assert_eq!(got_rgba, expected_rgba, "pixel mismatch for {label}");
3906 }3956 }
3907 }3957 }
3958
3959 #[test]
3960 fn reject_spoofed_oversized_png_ihdr_without_allocating() {
3961 fn png_crc32(data: &[u8]) -> u32 {
3962 let mut crc = 0xFFFF_FFFFu32;
3963 for &b in data {
3964 crc ^= b as u32;
3965 for _ in 0..8 {
3966 let mask = (crc & 1).wrapping_neg();
3967 crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
3968 }
3969 }
3970 !crc
3971 }
3972
3973 fn push_chunk(out: &mut Vec<u8>, chunk_type: &[u8; 4], payload: &[u8]) {
3974 out.extend_from_slice(&(payload.len() as u32).to_be_bytes());
3975 let crc_start = out.len();
3976 out.extend_from_slice(chunk_type);
3977 out.extend_from_slice(payload);
3978 let crc = png_crc32(&out[crc_start..]);
3979 out.extend_from_slice(&crc.to_be_bytes());
3980 }
3981
3982 let mut crafted = vec![137, 80, 78, 71, 13, 10, 26, 10];
3983 let mut ihdr = [0u8; 13];
3984 ihdr[0..4].copy_from_slice(&16u32.to_be_bytes());
3985 ihdr[4..8].copy_from_slice(&1_000_000_000u32.to_be_bytes());
3986 ihdr[8] = 8; // bit depth
3987 ihdr[9] = 6; // RGBA
3988 push_chunk(&mut crafted, b"IHDR", &ihdr);
3989 push_chunk(&mut crafted, b"IDAT", &[0x78, 0x9c, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00]);
3990 push_chunk(&mut crafted, b"IEND", &[]);
3991 assert_eq!(crafted.len(), 67);
3992
3993 assert!(matches!(decode_png_bytes(&crafted), PngDecodeOutcome::Reject));
3994 assert!(decode_raster_bytes(&crafted).is_none());
3995 }
3908}3996}