diff --git a/crates/engine/src/kys.rs b/crates/engine/src/kys.rs index 6a0ff99c84..643ed46057 100644 --- a/crates/engine/src/kys.rs +++ b/crates/engine/src/kys.rs @@ -56,7 +56,7 @@ pub fn parse(text: &str) -> Result { return Err("not a keyboard shortcut set (.kys): larger than 4 MiB".into()); } let text = text.trim_start_matches('\u{feff}'); - let doc = roxmltree::Document::parse(text).map_err(|e| format!("not a keyboard shortcut set (.kys): {e}"))?; + let doc = photocraft_io::xml::parse(text, roxmltree::ParsingOptions::default()).map_err(|e| format!("not a keyboard shortcut set (.kys): {e}"))?; let root = doc.root_element(); if root.tag_name().name() != "photoshop-keyboard-shortcuts" { return Err("not a keyboard shortcut set (.kys): no root".into()); @@ -342,6 +342,15 @@ mod tests { assert_eq!(p.alternate_keys.get("image.levels"), Some(&Vec::new())); } + /// A set nested 20 000 deep overflowed the XML parser's recursion (an abort nothing can + /// catch); it is an error now. The small stack makes a regression abort instead of passing. + #[test] + fn deeply_nested_sets_are_an_error_not_a_stack_overflow() { + let xml = format!("{}{}", "".repeat(20_000), "".repeat(20_000)); + let e = std::thread::Builder::new().stack_size(512 * 1024).spawn(move || parse(&xml).err()).unwrap().join().unwrap(); + assert!(e.as_deref().is_some_and(|m| m.contains("nested")), "{e:?}"); + } + #[test] fn a_row_with_the_default_and_a_function_key_keeps_both() { let xml = diff --git a/crates/engine/src/layer_xmp_cmds.rs b/crates/engine/src/layer_xmp_cmds.rs index 4fb4eda32f..742e0adf8d 100644 --- a/crates/engine/src/layer_xmp_cmds.rs +++ b/crates/engine/src/layer_xmp_cmds.rs @@ -33,7 +33,7 @@ fn check_packet(raw: &str) -> Result<()> { if raw.contains('\0') { return Err(bad("`rawData` can't contain NUL characters")); } - let xml = roxmltree::Document::parse(raw).map_err(|e| bad(format!("`rawData` isn't well-formed XML: {e}")))?; + let xml = photocraft_io::xml::parse(raw, roxmltree::ParsingOptions::default()).map_err(|e| bad(format!("`rawData` isn't well-formed XML: {e}")))?; let root = xml.root_element().tag_name(); let xmp = matches!((root.namespace(), root.name()), (Some("adobe:ns:meta/"), "xmpmeta") | (Some("http://www.w3.org/1999/02/22-rdf-syntax-ns#"), "RDF")); if !xmp { diff --git a/crates/engine/src/layer_xmp_cmds/tests.rs b/crates/engine/src/layer_xmp_cmds/tests.rs index 015f739399..5fb67ad13c 100644 --- a/crates/engine/src/layer_xmp_cmds/tests.rs +++ b/crates/engine/src/layer_xmp_cmds/tests.rs @@ -61,6 +61,27 @@ fn sets_reads_and_removes_as_one_undo_step_each() { } } +/// A `rawData` packet nested 20 000 deep overflowed the XML parser's recursion (an abort nothing +/// can catch, from one command param); it is a param error now. The small stack makes a +/// regression abort instead of passing. +#[test] +fn deeply_nested_packets_are_refused_not_a_stack_overflow() { + let (s, a, _) = fixture(8); + let raw = format!("{}{}", "".repeat(20_000), "".repeat(20_000)); + let (s, e) = std::thread::Builder::new() + .stack_size(1024 * 1024) + .spawn(move || { + let mut s = s; + let e = s.execute(ID, json!({"rawData": raw})).err(); + (s, e) + }) + .unwrap() + .join() + .unwrap(); + assert!(matches!(&e, Some(EngineError::BadParams { msg, .. }) if msg.contains("nested")), "{e:?}"); + assert_eq!(xmp(&s, a), None); +} + #[test] fn duplicating_a_layer_copies_its_packet() { let (mut s, a, _) = fixture(8); diff --git a/crates/io/src/camera_raw_xmp.rs b/crates/io/src/camera_raw_xmp.rs index 159e298a06..e621413e82 100644 --- a/crates/io/src/camera_raw_xmp.rs +++ b/crates/io/src/camera_raw_xmp.rs @@ -219,7 +219,7 @@ pub fn load(params: &mut CameraRaw, bytes: &[u8]) -> Result let text = std::str::from_utf8(bytes).map_err(|_| "not a Camera Raw settings file (not UTF-8 text)".to_string())?; // Some writers put a byte order mark or an `` wrapper first; roxmltree takes both. let text = text.trim_start_matches('\u{feff}'); - let doc = roxmltree::Document::parse(text).map_err(|e| format!("not a Camera Raw settings file ({e})"))?; + let doc = crate::xml::parse(text, roxmltree::ParsingOptions::default()).map_err(|e| format!("not a Camera Raw settings file ({e})"))?; let mut next = params.clone(); let mut report = LoadReport::default(); let mut found = false; @@ -360,6 +360,16 @@ mod tests { assert_eq!(r.ignored, vec!["VignetteAmount".to_string(), "RedHue".to_string()]); } + /// A settings file nested 20 000 deep overflowed the XML parser's recursion (an abort nothing + /// can catch); it is an error now. The small stack makes a regression abort instead of passing. + #[test] + fn deeply_nested_settings_are_an_error_not_a_stack_overflow() { + let xml = format!("{}{}", "".repeat(20_000), "".repeat(20_000)); + let e = + std::thread::Builder::new().stack_size(512 * 1024).spawn(move || load(&mut CameraRaw::default(), xml.as_bytes()).err()).unwrap().join().unwrap(); + assert!(e.as_deref().is_some_and(|m| m.contains("nested")), "{e:?}"); + } + #[test] fn save_then_load_round_trips() { let mut p = CameraRaw { diff --git a/crates/io/src/kra.rs b/crates/io/src/kra.rs index af9b238971..d8b3f9a36d 100644 --- a/crates/io/src/kra.rs +++ b/crates/io/src/kra.rs @@ -283,10 +283,10 @@ pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result Result { let v = number(image, a, 0.0)?; diff --git a/crates/io/src/kra/tests.rs b/crates/io/src/kra/tests.rs index 92e951cdb8..711b91364a 100644 --- a/crates/io/src/kra/tests.rs +++ b/crates/io/src/kra/tests.rs @@ -200,6 +200,21 @@ fn export_is_refused() { } } +/// maindoc.xml nested 20 000 deep, directly or through an internal-subset entity the depth check +/// can't see, overflowed the XML parser's recursion (an abort nothing can catch). Both are errors +/// now; the small stack makes a regression abort instead of passing. +#[test] +fn deeply_nested_maindoc_is_an_error_not_a_stack_overflow() { + let (open, close) = ("".repeat(20_000), "".repeat(20_000)); + let direct = maindoc("RGBA", &format!("{open}{close}")); + let entity = format!("]>&e;"); + for (xml, why) in [(direct, "nested"), (entity, "internal DTD")] { + let bytes = archive(&xml, &[]); + let e = std::thread::Builder::new().stack_size(512 * 1024).spawn(move || crate::import("deep.kra", &bytes).err()).unwrap().join().unwrap(); + assert!(matches!(&e, Some(IoError::Kra(m)) if m.contains(why)), "{why}: {e:?}"); + } +} + #[test] fn lzf_decodes_literals_and_overlapping_references() { // "abc" then a 6-byte back-reference 3 back: abcabcabc. diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 44beb59d47..76b39e9270 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -75,6 +75,7 @@ pub mod text_styles_map; pub mod tiff_layers; pub mod vector_map; mod xcf; +pub mod xml; use photocraft_codecs::{CodecError, EncodeOptions}; pub use photocraft_codecs::{DdsCompression, DdsOptions, DpxBits}; diff --git a/crates/io/src/ora.rs b/crates/io/src/ora.rs index 193680d31e..fb7968fbcc 100644 --- a/crates/io/src/ora.rs +++ b/crates/io/src/ora.rs @@ -414,7 +414,7 @@ pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result root")); diff --git a/crates/io/src/ora/tests.rs b/crates/io/src/ora/tests.rs index 922135a42e..66b27f7255 100644 --- a/crates/io/src/ora/tests.rs +++ b/crates/io/src/ora/tests.rs @@ -195,6 +195,16 @@ fn archive(stack: &str, images: &[(&str, Vec)]) -> Vec { z.finish().unwrap() } +/// A stack.xml nested 20 000 deep overflowed the XML parser's recursion (an abort nothing can +/// catch); it is an error now. The small stack makes a regression abort instead of passing. +#[test] +fn deeply_nested_stack_xml_is_an_error_not_a_stack_overflow() { + let stack = format!("{}{}", "".repeat(20_000), "".repeat(20_000)); + let bytes = archive(&stack, &[]); + let e = std::thread::Builder::new().stack_size(512 * 1024).spawn(move || crate::import("deep.ora", &bytes).err()).unwrap().join().unwrap(); + assert!(matches!(&e, Some(IoError::Ora(m)) if m.contains("nested")), "{e:?}"); +} + fn solid_png(w: u32, h: u32, rgba: [u8; 4]) -> Vec { let data = rgba.iter().copied().cycle().take((w * h * 4) as usize).collect(); codecs::encode(&Image::from_raw(w, h, ChannelLayout::Rgba, CSample::U8, data).unwrap(), Format::Png, &Default::default()).unwrap() diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 6363945d7e..6161f56ce3 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -298,7 +298,7 @@ fn inflate(bytes: &[u8]) -> Result, IoError> { /// then `limit + 1`). Comments, CDATA sections, processing instructions and the DOCTYPE add /// nothing; quoted attribute values may hold `>` or `/>`. Malformed markup is only counted /// loosely: the parser rejects it afterwards. -fn nesting_depth(xml: &[u8], limit: usize) -> usize { +pub(crate) fn nesting_depth(xml: &[u8], limit: usize) -> usize { let after = |from: usize, pat: &[u8]| -> usize { xml.get(from..).and_then(|s| s.windows(pat.len()).position(|w| w == pat)).map_or(xml.len(), |p| from.saturating_add(p).saturating_add(pat.len())) }; diff --git a/crates/io/src/xml.rs b/crates/io/src/xml.rs new file mode 100644 index 0000000000..02a493a671 --- /dev/null +++ b/crates/io/src/xml.rs @@ -0,0 +1,115 @@ +//! XML parsing with a nesting cap. roxmltree recurses once per element level, so a few thousand +//! nested tags (a 30 KB file or command param) overflow a 2 MB thread stack, an abort no guard +//! can catch. Every roxmltree caller that reads a file or a param goes through [`parse`]. + +use roxmltree::{Document, ParsingOptions}; + +/// Deepest element nesting accepted, the same as for SVG drawings: real files stay far below. +pub const MAX_DEPTH: usize = crate::svg::MAX_XML_DEPTH; + +/// Parses `text`, refusing nesting deeper than [`MAX_DEPTH`] before roxmltree sees it. +/// +/// With `opts.allow_dtd` an internal DTD subset is refused too: its entities can expand into +/// markup the depth check never sees. An external DOCTYPE (a public or system id) still parses. +pub fn parse<'i>(text: &'i str, opts: ParsingOptions<'i>) -> Result, String> { + if opts.allow_dtd && internal_subset(text.as_bytes()) { + return Err("internal DTD subsets aren't supported".into()); + } + if crate::svg::nesting_depth(text.as_bytes(), MAX_DEPTH) > MAX_DEPTH { + return Err(format!("elements are nested more than {MAX_DEPTH} levels deep")); + } + Document::parse_with_options(text, opts).map_err(|e| e.to_string()) +} + +/// Does the prolog's DOCTYPE have an internal subset (``)? Only the prolog can +/// hold a DOCTYPE; the parser rejects one anywhere else. +fn internal_subset(xml: &[u8]) -> bool { + let mut rest = xml.strip_prefix("\u{feff}".as_bytes()).unwrap_or(xml); + loop { + rest = rest.trim_ascii_start(); + let skip = |rest: &[u8], open: usize, close: &[u8]| -> Option { + let body = rest.get(open..)?; + body.windows(close.len()).position(|w| w == close).map(|p| open.saturating_add(p).saturating_add(close.len())) + }; + let next = if rest.starts_with(b"") + } else if rest.starts_with(b"") + } else if rest.starts_with(b"` ends a DOCTYPE without one. + let mut quote = None; + for &b in rest.iter().skip(9) { + match quote { + Some(q) if b == q => quote = None, + Some(_) => {} + None if b == b'"' || b == b'\'' => quote = Some(b), + None if b == b'[' => return true, + None if b == b'>' => return false, + None => {} + } + } + return false; + } else { + return false; + }; + let Some(next) = next else { return false }; + rest = rest.get(next..).unwrap_or_default(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn nested(levels: usize) -> String { + format!("{}{}", "".repeat(levels), "".repeat(levels)) + } + + fn dtd<'a>() -> ParsingOptions<'a> { + ParsingOptions { allow_dtd: true, ..Default::default() } + } + + #[test] + fn nesting_past_the_cap_is_an_error_not_a_stack_overflow() { + let deep = nested(20_000); + std::thread::Builder::new() + .stack_size(512 * 1024) + .spawn(move || { + for opts in [ParsingOptions::default(), dtd()] { + let e = parse(&deep, opts).err().unwrap_or_else(|| panic!("parsed")); + assert!(e.contains("nested") && e.contains(&MAX_DEPTH.to_string()), "{e}"); + } + }) + .unwrap() + .join() + .unwrap(); + // The root plus MAX_DEPTH - 1 levels is exactly MAX_DEPTH deep. + assert!(parse(&nested(MAX_DEPTH - 1), ParsingOptions::default()).is_ok()); + assert!(parse(&nested(MAX_DEPTH), ParsingOptions::default()).is_err()); + } + + #[test] + fn markup_in_comments_cdata_pis_and_attributes_adds_no_depth() { + let g = "".repeat(2 * MAX_DEPTH); + let xml = format!("\">"); + assert!(parse(&xml, ParsingOptions::default()).is_ok()); + } + + #[test] + fn an_internal_subset_is_refused_an_external_doctype_parses() { + let krita = "\n\n"; + assert!(parse(krita, dtd()).is_ok()); + let deep = format!("]>&e;", "".repeat(20_000), "".repeat(20_000)); + for xml in [ + "]>&e;".to_string(), + "\u{feff} ]>".to_string(), + deep, + ] { + let e = parse(&xml, dtd()).err().unwrap_or_else(|| panic!("parsed {xml:.60}")); + assert!(e.contains("internal DTD"), "{e}"); + } + // Without allow_dtd roxmltree refuses any DOCTYPE itself. + assert!(parse(krita, ParsingOptions::default()).is_err()); + } +}