PhotoCraft: An open-source, photo editor written by scratch in pure Rust
ICC parser: checked arithmetic on offsets and counts from the file (#4976) (#5227)
Michael Higginsb059a6d8b314
diff --git a/crates/cms/src/profile.rs b/crates/cms/src/profile.rsindex 99f5710e5..cdd7d5273 100644--- a/crates/cms/src/profile.rs+++ b/crates/cms/src/profile.rs@@ -429,10 +429,18 @@ impl<'a> Reader<'a> {Ok(self.u32(off)? as i32 as f64 / 65536.0)}fn xyz(&self, off: usize) -> Result<[f64; 3], CmsError> {- Ok([self.s15f16(off)?, self.s15f16(off + 4)?, self.s15f16(off + 8)?])+ let r = Reader { b: self.slice(off, 12)? };+ Ok([r.s15f16(0)?, r.s15f16(4)?, r.s15f16(8)?])}}+/// `base + n * size` for a count or offset read from the file, or `Truncated` when it does not+/// fit a `usize`. Such fields reach `u32::MAX`, which overflows on 32-bit targets (wasm32):+/// a panic with overflow checks on, a wrapped offset that reads the wrong bytes without (#4976).+fn extent(base: usize, n: usize, size: usize) -> Result<usize, CmsError> {+ n.checked_mul(size).and_then(|len| base.checked_add(len)).ok_or(CmsError::Truncated)+}+fn sig(s: &[u8; 4]) -> u32 {u32::from_be_bytes(*s)}@@ -572,14 +580,15 @@ fn parse_curve(d: &[u8]) -> Result<(Curve, usize), CmsError> {match r.slice(0, 4)? {b"curv" => {let n = r.u32(8)? as usize;+ // Before any arithmetic on it: `n * 2` overflows a 32-bit `usize` (#4976).+ if n > 1 << 20 {+ return Err(CmsError::Invalid("curve too long".into()));+ }let len = 12 + n * 2;match n {0 => Ok((Curve::Identity, len)),1 => Ok((Curve::Gamma(r.u16(12)? as f64 / 256.0), len)),_ => {- if n > 1 << 20 {- return Err(CmsError::Invalid("curve too long".into()));- }let s = r.slice(12, n * 2)?;let t = s.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]]) as f32 / 65535.0).collect();Ok((Curve::Table(t), len))@@ -684,36 +693,8 @@ fn parse_lut(d: &[u8], a2b: bool) -> Result<Lut, CmsError> {return Err(CmsError::Invalid("bad lutAB dimensions".into()));}let (ob, om, omc, oc, oa) = (r.u32(12)? as usize, r.u32(16)? as usize, r.u32(20)? as usize, r.u32(24)? as usize, r.u32(28)? as usize);- let matrix = |off: usize| -> Result<Stage, CmsError> {- let mut m = vec![0.0; 9];- for (k, v) in m.iter_mut().enumerate() {- *v = r.s15f16(off + k * 4)?;- }- let offset = vec![r.s15f16(off + 36)?, r.s15f16(off + 40)?, r.s15f16(off + 44)?];- Ok(Stage::Matrix { rows: 3, cols: 3, m, offset })- };- let clut = |off: usize, cin: usize, cout: usize| -> Result<Stage, CmsError> {- let mut grid = Vec::with_capacity(cin);- for k in 0..cin {- let g = r.u8(off + k)? as usize;- if g < 1 {- return Err(CmsError::Invalid("zero grid points".into()));- }- grid.push(g);- }- let prec = r.u8(off + 16)? as usize;- let nodes: u128 = grid.iter().map(|g| *g as u128).product();- if nodes * cout as u128 > MAX_CLUT_VALUES as u128 {- return Err(CmsError::Invalid("CLUT too large".into()));- }- let total = nodes as usize * cout;- let data: Vec<f32> = match prec {- 1 => r.slice(off + 20, total)?.iter().map(|b| *b as f32 / 255.0).collect(),- 2 => r.slice(off + 20, total * 2)?.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]]) as f32 / 65535.0).collect(),- _ => return Err(CmsError::Invalid(format!("CLUT precision {prec}"))),- };- Ok(Stage::Clut(Clut::new(grid, cout, data)))- };+ let matrix = |off: usize| lut_ab_matrix(&r, off);+ let clut = |off: usize, cin: usize, cout: usize| lut_ab_clut(&r, off, cin, cout);let mut stages = Vec::new();if ty == b"mAB " {// A curves → CLUT → M curves → matrix → B curves.@@ -760,6 +741,45 @@ fn parse_lut(d: &[u8], a2b: bool) -> Result<Lut, CmsError> {}}+/// The 3×3 matrix and offset of a `mAB `/`mBA ` element at `off`, an offset stored in the file.+fn lut_ab_matrix(r: &Reader, off: usize) -> Result<Stage, CmsError> {+ // One bounds-checked slice, then offsets inside it: `off + 44` need not fit a `usize`.+ let e = Reader { b: r.slice(off, 48)? };+ let mut m = vec![0.0; 9];+ for (k, v) in m.iter_mut().enumerate() {+ *v = e.s15f16(k * 4)?;+ }+ let offset = vec![e.s15f16(36)?, e.s15f16(40)?, e.s15f16(44)?];+ Ok(Stage::Matrix { rows: 3, cols: 3, m, offset })+}++/// The CLUT of a `mAB `/`mBA ` element at `off`, an offset stored in the file.+fn lut_ab_clut(r: &Reader, off: usize, cin: usize, cout: usize) -> Result<Stage, CmsError> {+ // Grid points (16 bytes), precision and padding; the samples follow.+ let head = Reader { b: r.slice(off, 20)? };+ let mut grid = Vec::with_capacity(cin);+ for k in 0..cin {+ let g = head.u8(k)? as usize;+ if g < 1 {+ return Err(CmsError::Invalid("zero grid points".into()));+ }+ grid.push(g);+ }+ let prec = head.u8(16)? as usize;+ let nodes: u128 = grid.iter().map(|g| *g as u128).product();+ if nodes * cout as u128 > MAX_CLUT_VALUES as u128 {+ return Err(CmsError::Invalid("CLUT too large".into()));+ }+ let total = nodes as usize * cout;+ let samples = extent(off, 20, 1)?;+ let data: Vec<f32> = match prec {+ 1 => r.slice(samples, total)?.iter().map(|b| *b as f32 / 255.0).collect(),+ 2 => r.slice(samples, total * 2)?.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]]) as f32 / 65535.0).collect(),+ _ => return Err(CmsError::Invalid(format!("CLUT precision {prec}"))),+ };+ Ok(Stage::Clut(Clut::new(grid, cout, data)))+}+/// Text from `desc` (textDescriptionType), `mluc` (English or first record) or `text`.fn parse_text(d: &[u8]) -> String {let r = Reader { b: d };@@ -775,8 +795,10 @@ fn parse_text(d: &[u8]) -> String {let (Ok(n), Ok(size)) = (r.u32(8), r.u32(12)) else { return String::new() };let mut best: Option<(usize, usize)> = None;for k in 0..(n as usize).min(256) {- let o = 16 + k * size as usize;- let (Ok(lang), Ok(len), Ok(off)) = (r.u16(o), r.u32(o + 4), r.u32(o + 8)) else { break };+ // The record size comes from the file: `k * size` can overflow a 32-bit `usize`.+ let Ok(rec) = extent(16, k, size as usize).and_then(|o| r.slice(o, 12)) else { break };+ let rec = Reader { b: rec };+ let (Ok(lang), Ok(len), Ok(off)) = (rec.u16(0), rec.u32(4), rec.u32(8)) else { break };if best.is_none() || lang == u16::from_be_bytes(*b"en") {best = Some((off as usize, len as usize));if lang == u16::from_be_bytes(*b"en") {@@ -792,3 +814,93 @@ fn parse_text(d: &[u8]) -> String {_ => String::new(),}}++#[cfg(test)]+mod tests {+ use super::*;++ fn be(v: u32) -> [u8; 4] {+ v.to_be_bytes()+ }++ /// #4976: offsets and counts stored in a profile reach `u32::MAX`, which is `usize::MAX` on+ /// 32-bit targets. The arithmetic on them must report a truncated profile, not overflow.+ #[test]+ fn offsets_at_the_top_of_the_address_space_are_truncated_not_overflowed() {+ let bytes = [0u8; 64];+ let r = Reader { b: &bytes };+ for off in [usize::MAX, usize::MAX - 3, usize::MAX - 11, usize::MAX - 19, usize::MAX - 47] {+ assert_eq!(r.xyz(off), Err(CmsError::Truncated), "xyz at {off}");+ assert!(matches!(lut_ab_matrix(&r, off), Err(CmsError::Truncated)), "matrix at {off}");+ assert!(matches!(lut_ab_clut(&r, off, 3, 3), Err(CmsError::Truncated)), "clut at {off}");+ }+ assert_eq!(extent(16, usize::MAX, 12), Err(CmsError::Truncated));+ assert_eq!(extent(usize::MAX, 1, 1), Err(CmsError::Truncated));+ assert_eq!(extent(16, 3, 12), Ok(52));+ }++ #[test]+ fn a_curve_count_is_checked_before_its_length_is_computed() {+ let mut d = b"curv\0\0\0\0".to_vec();+ d.extend(be(u32::MAX));+ assert_eq!(parse_curve(&d).map(|c| c.1), Err(CmsError::Invalid("curve too long".into())));+ // Controls: the identity and a two-point table still parse with their lengths.+ let mut d = b"curv\0\0\0\0".to_vec();+ d.extend(be(0));+ assert_eq!(parse_curve(&d).map(|c| c.1), Ok(12));+ let mut d = b"curv\0\0\0\0".to_vec();+ d.extend(be(2));+ d.extend([0, 0, 0xFF, 0xFF]);+ assert_eq!(parse_curve(&d).map(|c| c.1), Ok(16));+ }++ #[test]+ fn lut_ab_elements_at_hostile_offsets_are_rejected() {+ // A 3→3 lutAtoB with identity B curves at byte 32; then its B-curve, matrix and CLUT+ // offsets in turn point at the end of a 32-bit file.+ let lut = |b: u32, matrix: u32, m: u32, clut: u32, a: u32| {+ let mut d = b"mAB \0\0\0\0".to_vec();+ d.extend([3, 3, 0, 0]);+ for v in [b, matrix, m, clut, a] {+ d.extend(be(v));+ }+ for _ in 0..3 {+ d.extend(b"curv\0\0\0\0");+ d.extend(be(0));+ }+ d+ };+ assert!(parse_lut(&lut(32, 0, 0, 0, 0), true).is_ok(), "the control parses");+ let top = u32::MAX - 8;+ assert!(parse_lut(&lut(top, 0, 0, 0, 0), true).is_err(), "B curves offset");+ assert!(parse_lut(&lut(32, top, 32, 0, 0), true).is_err(), "matrix offset");+ assert!(parse_lut(&lut(32, 0, 0, top, 32), true).is_err(), "CLUT offset");+ }++ #[test]+ fn multilingual_records_with_a_huge_record_size_give_the_first_record() {+ let record = |lang: &[u8; 2], len: u32, off: u32| {+ let mut r = lang.to_vec();+ r.extend(b"US");+ r.extend(be(len));+ r.extend(be(off));+ r+ };+ // Two records of the standard 12 bytes: the English one wins.+ let mut d = b"mluc\0\0\0\0".to_vec();+ d.extend(be(2));+ d.extend(be(12));+ d.extend(record(b"de", 4, 40));+ d.extend(record(b"en", 4, 44));+ d.extend([0, b'D', 0, b'E', 0, b'E', 0, b'N']);+ assert_eq!(parse_text(&d), "EN");+ // A record size of u32::MAX: the second record lies past any file, so the first is used.+ d[12..16].copy_from_slice(&be(u32::MAX));+ assert_eq!(parse_text(&d), "DE");+ // No records at all.+ let mut d = b"mluc\0\0\0\0".to_vec();+ d.extend(be(u32::MAX));+ d.extend(be(u32::MAX));+ assert_eq!(parse_text(&d), "");+ }+}