From 59158ffdf2b3e3b7236e7c1e5ccfd6fa36106e29 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 11:26:13 +0000 Subject: [PATCH] fix(io): bound Krita default pixels, XMP nesting, XCF RLE runs, SVG DTDs, annotations, comps warnings, ABR groups --- crates/io/src/abr_map.rs | 5 +++ crates/io/src/annotations_map.rs | 54 ++++++++++++++++++++++---------- crates/io/src/camera_raw_xmp.rs | 3 +- crates/io/src/comps_map.rs | 12 ++++--- crates/io/src/kra.rs | 10 ++++-- crates/io/src/svg.rs | 8 +++++ crates/io/src/svg/tests.rs | 13 ++++++++ crates/io/src/xcf.rs | 7 +++++ crates/io/src/xcf/tests.rs | 8 +++++ crates/io/src/xml.rs | 2 +- 10 files changed, 98 insertions(+), 24 deletions(-) diff --git a/crates/io/src/abr_map.rs b/crates/io/src/abr_map.rs index a41ba3ac01..83dfd1891f 100644 --- a/crates/io/src/abr_map.rs +++ b/crates/io/src/abr_map.rs @@ -18,6 +18,8 @@ use photocraft_psd::patterns::PsdPattern; /// Largest sampled tip edge kept as is; bigger tips are downsampled to it. pub const MAX_TIP_EDGE: u32 = 2500; +/// Longest group name an import takes: every preset carries a copy of it. +pub const MAX_GROUP_NAME_BYTES: usize = 256; /// Largest texture pattern edge kept as is; bigger patterns are downsampled to it. pub const MAX_PATTERN_EDGE: u32 = 1024; @@ -40,6 +42,9 @@ pub fn read_abr(bytes: &[u8], group: &str) -> Result { /// [`read_abr`] that checks `ctl` before each brush (and reports progress): a cancelled import /// fails with "cancelled". pub fn read_abr_with(bytes: &[u8], group: &str, ctl: &photocraft_raster::Interrupt) -> Result { + if group.len() > MAX_GROUP_NAME_BYTES { + return Err(format!("the group name is longer than {MAX_GROUP_NAME_BYTES} bytes")); + } let f = abr::parse(bytes).map_err(|e| format!("not a readable brush file (.abr): {e}"))?; // Parsing is the small part; mapping (tip decoding) reports 10–100 %. ctl.progress(0.1); diff --git a/crates/io/src/annotations_map.rs b/crates/io/src/annotations_map.rs index 27b6c04477..8631843d7b 100644 --- a/crates/io/src/annotations_map.rs +++ b/crates/io/src/annotations_map.rs @@ -140,25 +140,28 @@ fn parse_entries(data: &[u8]) -> Option> { } let end = start.checked_add(len)?; let raw = data.get(start..end)?; - let kind = r.take(4)?; + // Read the entry from its own span: a text length past the declared end would otherwise + // decode the entries after it (again) into this one's text. + r.p = end; + let mut e = Reader { d: raw, p: 4 }; + let kind = e.take(4)?; if kind != b"txtA" { out.push(Entry::Raw(raw.to_vec())); - r.p = end; continue; } - let open = r.u8()? != 0; - let (_flags, _opt) = (r.u8()?, r.u16()?); - let icon = [r.i32()?, r.i32()?, r.i32()?, r.i32()?]; - let popup = [r.i32()?, r.i32()?, r.i32()?, r.i32()?]; - let space = r.u16()?; - let c = [r.u16()?, r.u16()?, r.u16()?, r.u16()?]; - let author = r.pascal()?; - let _name = r.pascal()?; - let modified = r.pascal()?; - let _data_len = r.u32()?; - let _key = r.take(4)?; - let n = r.u32()? as usize; - let text = decode_text(r.take(n)?); + let open = e.u8()? != 0; + let (_flags, _opt) = (e.u8()?, e.u16()?); + let icon = [e.i32()?, e.i32()?, e.i32()?, e.i32()?]; + let popup = [e.i32()?, e.i32()?, e.i32()?, e.i32()?]; + let space = e.u16()?; + let c = [e.u16()?, e.u16()?, e.u16()?, e.u16()?]; + let author = e.pascal()?; + let _name = e.pascal()?; + let modified = e.pascal()?; + let _data_len = e.u32()?; + let _key = e.take(4)?; + let n = e.u32()? as usize; + let text = decode_text(e.take(n)?); out.push(Entry::Text(Note { author, color: color_from(space, c), @@ -168,7 +171,6 @@ fn parse_entries(data: &[u8]) -> Option> { open, modified, })); - r.p = end; } Some(out) } @@ -443,6 +445,26 @@ mod tests { assert!(parse_anno(&hostile).is_none()); } + #[test] + fn a_text_length_past_the_entry_end_is_unreadable() { + // One txtA entry whose declared length ends before its text: the text would be read + // from the bytes after it (another entry's), as many times as there are such entries. + let mut entry = b"txtA".to_vec(); + entry.extend_from_slice(&[1, 0x1C, 0, 1]); + entry.extend_from_slice(&[0; 32]); // icon + popup + entry.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); // space + colour + entry.extend_from_slice(&[0, 0, 0, 0, 0, 0]); // author, name, modified (empty, padded) + entry.extend_from_slice(&[0, 0, 0, 0]); + entry.extend_from_slice(b"txtC"); + entry.extend_from_slice(&64u32.to_be_bytes()); // 64 bytes of text, none in the entry + let len = (entry.len() + 4) as u32; + let mut b = vec![0, 2, 0, 1, 0, 0, 0, 1]; + b.extend_from_slice(&len.to_be_bytes()); + b.extend_from_slice(&entry); + b.extend_from_slice(&[b'A'; 64]); + assert!(parse_entries(&b).is_none()); + } + #[test] fn scale_resource_roundtrip_and_keep_rules() { let s = MeasurementScale { pixel_length: 150.0, logical_length: 2.0, units: "mm".into() }; diff --git a/crates/io/src/camera_raw_xmp.rs b/crates/io/src/camera_raw_xmp.rs index 65df97e898..c97a5e4268 100644 --- a/crates/io/src/camera_raw_xmp.rs +++ b/crates/io/src/camera_raw_xmp.rs @@ -286,7 +286,8 @@ pub fn is_photocraft_xmp(bytes: &[u8]) -> bool { return false; } let Ok(text) = std::str::from_utf8(bytes) else { return false }; - let Ok(doc) = roxmltree::Document::parse(text.trim_start_matches('\u{feff}')) else { return false }; + // The shared parser refuses nesting that would overflow the stack; such a file is not ours. + let Ok(doc) = crate::xml::parse(text.trim_start_matches('\u{feff}'), Default::default()) else { return false }; doc.descendants() .find(|n| n.is_element() && n.tag_name().namespace() == Some(META_NS) && n.tag_name().name() == "xmpmeta") .and_then(|n| n.attribute((META_NS, "xmptk"))) diff --git a/crates/io/src/comps_map.rs b/crates/io/src/comps_map.rs index 3348061b34..4b527142a5 100644 --- a/crates/io/src/comps_map.rs +++ b/crates/io/src/comps_map.rs @@ -230,6 +230,9 @@ pub(crate) fn decode_comps(resource: Option<&[u8]>, doc: &Document) -> (Vec, doc: &Document) -> (Vec { let p = offset_position(h, o); if p.is_none() { - warnings.push(format!( - "layer \"{}\": layer comp position offset ({}, {}) is out of range; that position was not imported", - l.name, o.0, o.1 - )); + out_of_range += 1; } p } @@ -258,6 +258,10 @@ pub(crate) fn decode_comps(resource: Option<&[u8]>, doc: &Document) -> (Vec 0 { + let name: String = l.name.chars().take(64).collect(); + warnings.push(format!("layer \"{name}\": {out_of_range} layer comp position offset(s) are out of range; those positions were not imported")); + } } let last = (!last.states.is_empty()).then_some(last); (comps, last_applied, last, warnings) diff --git a/crates/io/src/kra.rs b/crates/io/src/kra.rs index d8b3f9a36d..b16f03f478 100644 --- a/crates/io/src/kra.rs +++ b/crates/io/src/kra.rs @@ -89,16 +89,22 @@ struct Reader<'a, 'c> { impl Reader<'_, '_> { fn file(&self, name: &str) -> Result>> { + self.file_up_to(name, MAX_LAYER_FILE) + } + + /// [`file`](Self::file) refusing a member that inflates past `max` bytes. + fn file_up_to(&self, name: &str, max: usize) -> Result>> { let path = format!("{}{name}", self.dir); match self.zip.find(&path) { None => Ok(None), - Some(e) => self.zip.read(e, MAX_LAYER_FILE).map(Some).map_err(|err| invalid(format!("{path}: {err}"))), + Some(e) => self.zip.read(e, max).map(Some).map_err(|err| invalid(format!("{path}: {err}"))), } } /// The default pixel Krita stores next to a tiled file, decoded to `space` samples. fn default_pixel(&self, name: &str, space: Space) -> Result>> { - let Some(bytes) = self.file(&format!("{name}.defaultpixel"))? else { return Ok(None) }; + // One pixel: a member declaring the generic layer-file limit must not be inflated first. + let Some(bytes) = self.file_up_to(&format!("{name}.defaultpixel"), space.pixel_size())? else { return Ok(None) }; if bytes.len() != space.pixel_size() { return Err(invalid(format!("{name}.defaultpixel has {} bytes, expected {}", bytes.len(), space.pixel_size()))); } diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 0728035530..0a1ea3dd22 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -353,6 +353,11 @@ fn parse(bytes: &[u8]) -> Result { /// [`parse`] with the font database `fonts` supplies (the tests hand in an empty one). fn parse_with(bytes: &[u8], fonts: fn() -> Arc) -> Result { let xml = inflate(bytes)?; + // usvg parses with DTDs on, and an internal subset's entities can expand into markup the + // depth check below never sees (it skips quoted declarations). + if crate::xml::internal_subset(&xml) { + return Err(IoError::Svg("internal DTD subsets aren't supported".into())); + } let depth = nesting_depth(&xml, MAX_XML_DEPTH); if depth > MAX_XML_DEPTH { return Err(IoError::Svg(format!("elements are nested more than {MAX_XML_DEPTH} levels deep"))); @@ -592,6 +597,9 @@ fn parse_image_bounded_with( return Err(overrun(IoError::Svg("embedded SVG source exceeds the 16 MiB byte limit".into()))); } let xml = inflate_with_limit(bytes, MAX_BOUNDED_SVG_BYTES).map_err(overrun)?; + if crate::xml::internal_subset(&xml) { + return Err(IoError::Svg("internal DTD subsets aren't supported".into())); + } // Charged before anything can leave the image out, so skipped images still use up the budget. let xml_len = u64::try_from(xml.len()).unwrap_or(u64::MAX); let left = { diff --git a/crates/io/src/svg/tests.rs b/crates/io/src/svg/tests.rs index fd7f2713a7..dca7254554 100644 --- a/crates/io/src/svg/tests.rs +++ b/crates/io/src/svg/tests.rs @@ -907,3 +907,16 @@ fn only_stored_previews_refuse_unreadable_embedded_images() { assert!(import_svg_bounded_with_work("edit", svg.as_bytes(), MAX_RASTER_PIXELS).is_ok()); assert!(import_svg_preview_with_work("preview", svg.as_bytes(), MAX_RASTER_PIXELS).is_err()); } + +/// usvg parses with DTDs on: an internal subset's entities would expand into markup the depth +/// check never counted, top level and inside an embedded SVG image alike. +#[test] +fn internal_dtd_subsets_are_refused_before_parsing() { + let deep = format!("]>", "".repeat(8), "".repeat(8)); + let svg = format!("{deep}&g;"); + let error = import_svg("dtd", svg.as_bytes()).unwrap_err().to_string(); + assert!(error.contains("internal DTD"), "{error}"); + let embedded = image_svg(&embedded_image("image/svg+xml", svg.as_bytes())); + let error = import_svg("dtd", embedded.as_bytes()).unwrap_err().to_string(); + assert!(error.contains("internal DTD"), "{error}"); +} diff --git a/crates/io/src/xcf.rs b/crates/io/src/xcf.rs index e9a6b92a21..288a93e24d 100644 --- a/crates/io/src/xcf.rs +++ b/crates/io/src/xcf.rs @@ -382,6 +382,11 @@ fn rle_decode(input: &[u8], bpp: usize, pixels: usize) -> Result> { if plane.len() + run > pixels { return Err(invalid("an RLE run crosses the end of its tile")); } + // A long run of length 0 consumes input without producing output: a tile of them + // (reachable from many tile pointers) is work the pixel budget never charges. + if run == 0 { + return Err(invalid("an RLE run has no length")); + } if verbatim { let data = input.get(pos..pos + run).ok_or_else(|| invalid("an RLE tile is cut short"))?; pos += run; @@ -500,6 +505,8 @@ impl<'a> Image<'a> { let mut c = self.c.at(ptr); let (_w, _h) = (c.u32()?, c.u32()?); let name = c.string()?; + // As for layers: repeated channel pointers must not retain unbounded copies of one name. + self.meta_budget = self.meta_budget.checked_sub(name.len()).ok_or_else(|| invalid("channel metadata exceeds the budget"))?; let props = props(&mut c)?; let hptr = c.ptr()?; let saved = (self.base_type, self.precision); diff --git a/crates/io/src/xcf/tests.rs b/crates/io/src/xcf/tests.rs index 24481f1956..3b30a725bc 100644 --- a/crates/io/src/xcf/tests.rs +++ b/crates/io/src/xcf/tests.rs @@ -808,3 +808,11 @@ fn duplicate_parasites_keep_order_and_last_value() { assert_eq!(out[0].1, b"second", "last value wins"); assert_eq!(out[1].0, "gimp-image-grid", "insertion order preserved"); } + +#[test] +fn an_rle_run_of_zero_length_is_an_error() { + // Long runs (op 127 / 128) carry a 16-bit length; zero consumes input without producing output. + assert!(rle_decode(&[127, 0, 0, 5, 3, 0, 9], 1, 4).is_err()); + assert!(rle_decode(&[128, 0, 0, 3, 0, 9], 1, 4).is_err()); + assert_eq!(rle_decode(&[127, 0, 4, 9], 1, 4).unwrap(), [9, 9, 9, 9]); +} diff --git a/crates/io/src/xml.rs b/crates/io/src/xml.rs index 13e02004d1..88551d6909 100644 --- a/crates/io/src/xml.rs +++ b/crates/io/src/xml.rs @@ -29,7 +29,7 @@ pub fn parse<'i>(text: &'i str, opts: ParsingOptions<'i>) -> Result /// come first, a `[` outside quotes opens the subset, a `>` ends a DOCTYPE without one. Scans in /// the same quote state go on alike, so one pass keeps just three flags (outside quotes, in `"`, /// in `'`) and stays linear however many ` bool { +pub(crate) fn internal_subset(xml: &[u8]) -> bool { const DOCTYPE: &[u8] = b"