wip(image): TIFF budget fixes pre-merge checkpoint
Browse files at this commit6e80b0d3db68411688aee03769150f505f08a00eParent: b4d23d92 changed files +142 -7
- crates/ec-image/src/lib.rs +54 -1
- crates/ec-image/src/tiff.rs +88 -6
crates/ec-image/src/lib.rsmodified+54 -1
| @@ -133,13 +133,23 @@ pub struct Limits { | |||
| 133 | pub max_pixels: u64, | 133 | pub max_pixels: u64, |
| 134 | /// Largest single decompressed buffer accepted, in bytes. | 134 | /// Largest single decompressed buffer accepted, in bytes. |
| 135 | pub max_alloc: usize, | 135 | pub max_alloc: usize, |
| 136 | + /// Largest total bytes accepted across every frame of one decode call. | ||
| 137 | + /// | ||
| 138 | + /// A single frame can pass [`Limits::check_bytes`] on its own and still | ||
| 139 | + /// be a bomb once a segment count multiplies it — a stripped or tiled | ||
| 140 | + /// TIFF decompresses many segments per call, so a file whose segments | ||
| 141 | + /// each look small on their own can still retain gigabytes nothing ever | ||
| 142 | + /// checked one buffer at a time. [`AllocBudget`] enforces this across a | ||
| 143 | + /// decode call. | ||
| 144 | + pub max_total_alloc: usize, | ||
| 136 | } | 145 | } |
| 137 | 146 | ||
| 138 | impl Default for Limits { | 147 | impl Default for Limits { |
| 139 | fn default() -> Self { | 148 | fn default() -> Self { |
| 140 | Limits { | 149 | Limits { |
| 141 | max_pixels: 1 << 28, | 150 | max_pixels: 1 << 28, |
| 142 | - max_alloc: 1 << 32, | 151 | + max_alloc: 1 << 30, |
| 152 | + max_total_alloc: 1 << 32, | ||
| 143 | } | 153 | } |
| 144 | } | 154 | } |
| 145 | } | 155 | } |
| @@ -159,6 +169,49 @@ impl Limits { | |||
| 159 | } | 169 | } |
| 160 | Ok(()) | 170 | Ok(()) |
| 161 | } | 171 | } |
| 172 | + | ||
| 173 | + /// Check a byte count computed from header-declared fields (a strip's | ||
| 174 | + /// `width * height * bpp`, a palette size, a chunk length) before it | ||
| 175 | + /// sizes a single allocation. `what` names the buffer for the error. | ||
| 176 | + pub fn check_bytes(&self, what: &str, bytes: Option<usize>) -> Result<usize> { | ||
| 177 | + let bytes = | ||
| 178 | + bytes.ok_or_else(|| Error::corrupt(format!("{what}: size overflows usize")))?; | ||
| 179 | + if bytes > self.max_alloc { | ||
| 180 | + return Err(Error::unsupported( | ||
| 181 | + what.to_string(), | ||
| 182 | + format!("{bytes} bytes past the {} allocation limit", self.max_alloc), | ||
| 183 | + )); | ||
| 184 | + } | ||
| 185 | + Ok(bytes) | ||
| 186 | + } | ||
| 187 | +} | ||
| 188 | + | ||
| 189 | +/// Accumulates bytes spent across every segment of one decode call and | ||
| 190 | +/// refuses once the running total crosses [`Limits::max_total_alloc`] — the | ||
| 191 | +/// guard for `segment_count x segment_size`, which [`Limits::check_bytes`] | ||
| 192 | +/// alone never sees since it only ever looks at one buffer at a time. | ||
| 193 | +#[derive(Debug, Default)] | ||
| 194 | +pub struct AllocBudget(usize); | ||
| 195 | + | ||
| 196 | +impl AllocBudget { | ||
| 197 | + /// Spend `bytes` from the budget, refusing once the running total passes | ||
| 198 | + /// `limits.max_total_alloc`. | ||
| 199 | + pub fn spend(&mut self, limits: &Limits, what: &str, bytes: usize) -> Result<()> { | ||
| 200 | + self.0 = self | ||
| 201 | + .0 | ||
| 202 | + .checked_add(bytes) | ||
| 203 | + .ok_or_else(|| Error::corrupt(format!("{what}: total size overflows usize")))?; | ||
| 204 | + if self.0 > limits.max_total_alloc { | ||
| 205 | + return Err(Error::unsupported( | ||
| 206 | + what.to_string(), | ||
| 207 | + format!( | ||
| 208 | + "{} total decoded bytes past the {} limit", | ||
| 209 | + self.0, limits.max_total_alloc | ||
| 210 | + ), | ||
| 211 | + )); | ||
| 212 | + } | ||
| 213 | + Ok(()) | ||
| 214 | + } | ||
| 162 | } | 215 | } |
| 163 | 216 | ||
| 164 | /// What a file said about its own pixels, parsed but not applied. | 217 | /// What a file said about its own pixels, parsed but not applied. |
crates/ec-image/src/tiff.rsmodified+88 -6
| @@ -16,7 +16,7 @@ | |||
| 16 | //! a different format that happens to share a signature byte. The incumbent | 16 | //! a different format that happens to share a signature byte. The incumbent |
| 17 | //! `image` crate refuses all three as well. | 17 | //! `image` crate refuses all three as well. |
| 18 | 18 | ||
| 19 | -use crate::{Image, ImageFormat, Info, Limits, Metadata, Pixels}; | 19 | +use crate::{AllocBudget, Image, ImageFormat, Info, Limits, Metadata, Pixels}; |
| 20 | use ec_core::{Error, Result}; | 20 | use ec_core::{Error, Result}; |
| 21 | 21 | ||
| 22 | const TAG_WIDTH: u16 = 256; | 22 | const TAG_WIDTH: u16 = 256; |
| @@ -363,6 +363,13 @@ fn lzw(input: &[u8], hint: usize) -> Result<Vec<u8>> { | |||
| 363 | let (mut bit, mut acc, mut have) = (0usize, 0u32, 0u32); | 363 | let (mut bit, mut acc, mut have) = (0usize, 0u32, 0u32); |
| 364 | let mut stack = Vec::with_capacity(4096); | 364 | let mut stack = Vec::with_capacity(4096); |
| 365 | loop { | 365 | loop { |
| 366 | + if out.len() >= hint { | ||
| 367 | + // The declared strip is already full. A bomb-style stream keeps | ||
| 368 | + // emitting codes past this point (the dictionary just keeps | ||
| 369 | + // growing); stopping here is what keeps a KB-sized input from | ||
| 370 | + // expanding into hundreds of megabytes. | ||
| 371 | + return Ok(out); | ||
| 372 | + } | ||
| 366 | while have < width { | 373 | while have < width { |
| 367 | let Some(&byte) = input.get(bit) else { | 374 | let Some(&byte) = input.get(bit) else { |
| 368 | return Ok(out); | 375 | return Ok(out); |
| @@ -431,6 +438,12 @@ fn packbits(input: &[u8], hint: usize) -> Vec<u8> { | |||
| 431 | let mut out = Vec::with_capacity(hint); | 438 | let mut out = Vec::with_capacity(hint); |
| 432 | let mut at = 0usize; | 439 | let mut at = 0usize; |
| 433 | while at < input.len() { | 440 | while at < input.len() { |
| 441 | + if out.len() >= hint { | ||
| 442 | + // Same bomb shape as LZW: a run byte expands to up to 128 bytes | ||
| 443 | + // of output, so a small strip can otherwise inflate far past | ||
| 444 | + // what the declared geometry says it should hold. | ||
| 445 | + break; | ||
| 446 | + } | ||
| 434 | let control = input[at] as i8; | 447 | let control = input[at] as i8; |
| 435 | at += 1; | 448 | at += 1; |
| 436 | if control >= 0 { | 449 | if control >= 0 { |
| @@ -522,9 +535,35 @@ pub fn decode(data: &[u8], limits: Limits) -> Result<Image> { | |||
| 522 | let per_plane = if planar { 1 } else { samples }; | 535 | let per_plane = if planar { 1 } else { samples }; |
| 523 | 536 | ||
| 524 | // Samples land here interleaved, whatever the file's own arrangement was. | 537 | // Samples land here interleaved, whatever the file's own arrangement was. |
| 525 | - let mut raw = vec![0u16; width * height * samples]; | 538 | + // `width`/`height` already passed `limits.check`, but that only bounds |
| 539 | + // pixel count -- a 4-sample 16-bit picture is 8 bytes/pixel, which can | ||
| 540 | + // still cross the allocation limit even inside the pixel limit. | ||
| 541 | + let raw_len = width | ||
| 542 | + .checked_mul(height) | ||
| 543 | + .and_then(|v| v.checked_mul(samples)) | ||
| 544 | + .ok_or_else(|| Error::corrupt("TIFF: sample count overflows"))?; | ||
| 545 | + let mut budget = AllocBudget::default(); | ||
| 546 | + // A decompression-bomb guard on top of `max_alloc`: no legitimate encoder | ||
| 547 | + // writes a file whose declared pixel count decompresses to thousands of | ||
| 548 | + // times the bytes actually on disk (uncompressed is 1x, and LZW/Deflate | ||
| 549 | + // only improve on that). A tag claiming otherwise is sized past the file | ||
| 550 | + // that would have to contain it, not a picture this decoder should spend | ||
| 551 | + // possibly-seconds unpacking one strip of. | ||
| 552 | + let bomb_cap = data.len().saturating_mul(4096).max(1 << 20); | ||
| 553 | + let raw_bytes = limits.check_bytes("TIFF raw samples", raw_len.checked_mul(2))?; | ||
| 554 | + if raw_bytes > bomb_cap { | ||
| 555 | + return Err(Error::unsupported( | ||
| 556 | + "TIFF: a picture out of proportion to its file size", | ||
| 557 | + format!("{raw_bytes} raw bytes claimed from a {}-byte file", data.len()), | ||
| 558 | + )); | ||
| 559 | + } | ||
| 560 | + budget.spend(&limits, "TIFF raw samples", raw_bytes)?; | ||
| 561 | + let mut raw = vec![0u16; raw_len]; | ||
| 526 | 562 | ||
| 527 | - // Strips and tiles differ only in the rectangle one segment covers. | 563 | + // Strips and tiles differ only in the rectangle one segment covers. Tile |
| 564 | + // and rows-per-strip dimensions are header fields too, unconstrained by | ||
| 565 | + // the picture's own width/height, so a segment's decompressed size is | ||
| 566 | + // budgeted before anything is sized from it. | ||
| 528 | let (seg_w, seg_h) = match layout.tile { | 567 | let (seg_w, seg_h) = match layout.tile { |
| 529 | Some((w, h)) if w > 0 && h > 0 => (w as usize, h as usize), | 568 | Some((w, h)) if w > 0 && h > 0 => (w as usize, h as usize), |
| 530 | Some(_) => return Err(Error::corrupt("TIFF: a zero-sized tile")), | 569 | Some(_) => return Err(Error::corrupt("TIFF: a zero-sized tile")), |
| @@ -541,15 +580,58 @@ pub fn decode(data: &[u8], limits: Limits) -> Result<Image> { | |||
| 541 | 580 | ||
| 542 | // A tile is always its full width; a strip is only as wide as the picture, | 581 | // A tile is always its full width; a strip is only as wide as the picture, |
| 543 | // and its last one only as tall as the rows that remain. | 582 | // and its last one only as tall as the rows that remain. |
| 544 | - let row_samples = seg_w * per_plane; | 583 | + let row_samples = seg_w |
| 545 | - let row_bytes = (row_samples * bits as usize).div_ceil(8); | 584 | + .checked_mul(per_plane) |
| 585 | + .ok_or_else(|| Error::corrupt("TIFF: a row wider than usize"))?; | ||
| 586 | + let row_bytes = limits.check_bytes( | ||
| 587 | + "TIFF row", | ||
| 588 | + row_samples | ||
| 589 | + .checked_mul(bits as usize) | ||
| 590 | + .map(|bits| bits.div_ceil(8)), | ||
| 591 | + )?; | ||
| 592 | + // `row` holds one `u16` per *sample*, not per packed byte -- for anything | ||
| 593 | + // under 16 bits that is a bigger allocation than `row_bytes` (up to 16x | ||
| 594 | + // for a 1-bit picture), so it needs its own check rather than trusting | ||
| 595 | + // the packed size to stand in for it. | ||
| 596 | + limits.check_bytes("TIFF row samples", row_samples.checked_mul(2))?; | ||
| 597 | + if row_samples.saturating_mul(2) > bomb_cap { | ||
| 598 | + return Err(Error::unsupported( | ||
| 599 | + "TIFF: a row out of proportion to its file size", | ||
| 600 | + format!("{row_samples} samples/row claimed from a {}-byte file", data.len()), | ||
| 601 | + )); | ||
| 602 | + } | ||
| 546 | let mut row = Vec::with_capacity(row_samples); | 603 | let mut row = Vec::with_capacity(row_samples); |
| 547 | let full = ((1u32 << bits) - 1) as u16; | 604 | let full = ((1u32 << bits) - 1) as u16; |
| 605 | + // `bomb_cap` alone bounds one strip; nothing bounded the strip *count* | ||
| 606 | + // yet, and that is attacker-controlled up to the number of offsets a | ||
| 607 | + // small file can list. A few thousand small-looking strips can still add | ||
| 608 | + // up to gigabytes of real decompression work, so the running total is | ||
| 609 | + // held to the same file-size-proportional ceiling as a single strip. | ||
| 610 | + let mut segment_bytes_total = 0usize; | ||
| 548 | for index in 0..per_plane_segments * planes { | 611 | for index in 0..per_plane_segments * planes { |
| 549 | let plane = index / per_plane_segments; | 612 | let plane = index / per_plane_segments; |
| 550 | let within = index % per_plane_segments; | 613 | let within = index % per_plane_segments; |
| 551 | let (col, band) = (within % across, within / across); | 614 | let (col, band) = (within % across, within / across); |
| 552 | - let expect = row_bytes * seg_h; | 615 | + // The declared strip/tile height is a header field like any other: |
| 616 | + // nothing stops RowsPerStrip or TileLength from claiming far more | ||
| 617 | + // rows than the picture has, which would otherwise size an LZW or | ||
| 618 | + // Deflate hint (and the compute behind it) off a number with no | ||
| 619 | + // relationship to the real image -- a small file claiming a | ||
| 620 | + // billion-row strip decodes only as many rows as `height` actually | ||
| 621 | + // has, never the declared height. | ||
| 622 | + let rows_used = seg_h.min(height.saturating_sub(band * seg_h)); | ||
| 623 | + let expect = limits.check_bytes("TIFF strip", row_bytes.checked_mul(rows_used))?; | ||
| 624 | + segment_bytes_total = segment_bytes_total.saturating_add(expect); | ||
| 625 | + if expect > bomb_cap || segment_bytes_total > bomb_cap { | ||
| 626 | + return Err(Error::unsupported( | ||
| 627 | + "TIFF: strips claim more decompressed data than the file could hold", | ||
| 628 | + format!( | ||
| 629 | + "{segment_bytes_total} bytes claimed across strips from a {}-byte file", | ||
| 630 | + data.len() | ||
| 631 | + ), | ||
| 632 | + )); | ||
| 633 | + } | ||
| 634 | + budget.spend(&limits, "TIFF strip", expect)?; | ||
| 553 | let body = segment(&layout, data, index, expect)?; | 635 | let body = segment(&layout, data, index, expect)?; |
| 554 | for r in 0..seg_h { | 636 | for r in 0..seg_h { |
| 555 | let y = band * seg_h + r; | 637 | let y = band * seg_h + r; |