fix(io): bound Krita default pixels, XMP nesting, XCF RLE runs, SVG DTDs, annotations, comps warnings, ABR groups

This commit is contained in:
Dylan M. Taylor committed 2026-11-03 11:26:13 +00:00
1 parent 327c4cc82e
commit 59158ffdf2
10 files changed
+98 -24

No files matched your search

+5
View File
@@ -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<AbrImport, String> {
/// [`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<AbrImport, String> {
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);
+38 -16
View File
@@ -140,25 +140,28 @@ fn parse_entries(data: &[u8]) -> Option<Vec<Entry>> {
}
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<Vec<Entry>> {
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() };
+2 -1
View File
@@ -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")))
+8 -4
View File
@@ -230,6 +230,9 @@ pub(crate) fn decode_comps(resource: Option<&[u8]>, doc: &Document) -> (Vec<Laye
// came before (#8093). Only comps that capture visibility take that inherited value; the
// Last Document State entry (comp 0) and the others keep what the entry says.
let mut inherited = true;
// Rejected offsets are counted and reported once per layer: a warning per setting, each
// carrying the layer's name, grew with name length × settings.
let mut out_of_range = 0usize;
for s in settings {
let resolved = s.visible.unwrap_or(inherited);
if s.comps.iter().any(|id| *id != 0) {
@@ -239,10 +242,7 @@ pub(crate) fn decode_comps(resource: Option<&[u8]>, doc: &Document) -> (Vec<Laye
(Some(h), Some(o)) => {
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<Laye
c.states.push(CompLayerState { layer: l.id, visible, position, appearance: None });
}
}
if out_of_range > 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)
+8 -2
View File
@@ -89,16 +89,22 @@ struct Reader<'a, 'c> {
impl Reader<'_, '_> {
fn file(&self, name: &str) -> Result<Option<Vec<u8>>> {
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<Option<Vec<u8>>> {
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<Option<Vec<f32>>> {
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())));
}
+8
View File
@@ -353,6 +353,11 @@ fn parse(bytes: &[u8]) -> Result<Parsed, IoError> {
/// [`parse`] with the font database `fonts` supplies (the tests hand in an empty one).
fn parse_with(bytes: &[u8], fonts: fn() -> Arc<usvg::fontdb::Database>) -> Result<Parsed, IoError> {
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 = {
+13
View File
@@ -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!("<!DOCTYPE svg [<!ENTITY g \"{}{}\">]>", "<g>".repeat(8), "</g>".repeat(8));
let svg = format!("{deep}<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1\" height=\"1\">&g;</svg>");
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}");
}
+7
View File
@@ -382,6 +382,11 @@ fn rle_decode(input: &[u8], bpp: usize, pixels: usize) -> Result<Vec<u8>> {
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);
+8
View File
@@ -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]);
}
+1 -1
View File
@@ -29,7 +29,7 @@ pub fn parse<'i>(text: &'i str, opts: ParsingOptions<'i>) -> Result<Document<'i>
/// 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 `<!DOCTYPE`s a comment holds.
fn internal_subset(xml: &[u8]) -> bool {
pub(crate) fn internal_subset(xml: &[u8]) -> bool {
const DOCTYPE: &[u8] = b"<!DOCTYPE";
let (mut bare, mut double, mut single) = (false, false, false);
for (at, &b) in xml.iter().enumerate() {