mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
XML: deeply nested ORA, KRA, Camera Raw XMP, .kys and layer XMP are an error, not a crash (#9419)
roxmltree recurses once per element level, so a few thousand nested tags overflow the thread stack, an abort no guard can catch. SVG checked the nesting before parsing; the other five roxmltree callers now go through photocraft_io::xml::parse, which applies the same check (512 levels) and, where a DTD is allowed (KRA), refuses an internal subset whose entities could expand into nesting the check never sees. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
b0622d20ca
commit
027bfb30ed
11 files changed
+189
-8
No files matched your search
@@ -56,7 +56,7 @@ pub fn parse(text: &str) -> Result<KysSet, String> {
|
||||
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 <photoshop-keyboard-shortcuts> 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!("<photoshop-keyboard-shortcuts>{}{}</photoshop-keyboard-shortcuts>", "<a>".repeat(20_000), "</a>".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 =
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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!("<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">{}{}</x:xmpmeta>", "<a>".repeat(20_000), "</a>".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);
|
||||
|
||||
@@ -219,7 +219,7 @@ pub fn load(params: &mut CameraRaw, bytes: &[u8]) -> Result<LoadReport, String>
|
||||
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 `<?xpacket?>` 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!("<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">{}{}</x:xmpmeta>", "<a>".repeat(20_000), "</a>".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 {
|
||||
|
||||
@@ -283,10 +283,10 @@ pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result<Im
|
||||
}
|
||||
let xml = zip.read_by_name("maindoc.xml", MAX_MAINDOC).map_err(|e| invalid(e.to_string()))?;
|
||||
let xml = std::str::from_utf8(&xml).map_err(|_| invalid("maindoc.xml is not UTF-8"))?;
|
||||
// maindoc.xml declares Krita's DTD by public id; roxmltree only reads internal subsets and
|
||||
// guards entity expansion.
|
||||
// maindoc.xml declares Krita's DTD by public id; Krita writes no internal subset, which
|
||||
// `xml::parse` refuses (its entities could hide nesting from the depth check).
|
||||
let opts = roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() };
|
||||
let tree = roxmltree::Document::parse_with_options(xml, opts).map_err(|e| invalid(format!("maindoc.xml: {e}")))?;
|
||||
let tree = crate::xml::parse(xml, opts).map_err(|e| invalid(format!("maindoc.xml: {e}")))?;
|
||||
let image = tree.root_element().children().find(|n| n.has_tag_name("IMAGE")).ok_or_else(|| invalid("maindoc.xml has no IMAGE"))?;
|
||||
let side = |a: &str| -> Result<u32> {
|
||||
let v = number(image, a, 0.0)?;
|
||||
|
||||
@@ -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) = ("<layers>".repeat(20_000), "</layers>".repeat(20_000));
|
||||
let direct = maindoc("RGBA", &format!("{open}{close}"));
|
||||
let entity = format!("<!DOCTYPE DOC [<!ENTITY e \"{open}{close}\">]><DOC><IMAGE width=\"4\" height=\"4\">&e;</IMAGE></DOC>");
|
||||
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.
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -414,7 +414,7 @@ pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result<Im
|
||||
}
|
||||
let xml = zip.read_by_name("stack.xml", MAX_STACK_XML).map_err(|e| invalid(e.to_string()))?;
|
||||
let xml = std::str::from_utf8(&xml).map_err(|_| invalid("stack.xml is not UTF-8"))?;
|
||||
let tree = roxmltree::Document::parse(xml).map_err(|e| invalid(format!("stack.xml: {e}")))?;
|
||||
let tree = crate::xml::parse(xml, roxmltree::ParsingOptions::default()).map_err(|e| invalid(format!("stack.xml: {e}")))?;
|
||||
let image = tree.root_element();
|
||||
if image.tag_name().name() != "image" {
|
||||
return Err(invalid("stack.xml has no <image> root"));
|
||||
|
||||
@@ -195,6 +195,16 @@ fn archive(stack: &str, images: &[(&str, Vec<u8>)]) -> Vec<u8> {
|
||||
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!("<image w=\"4\" h=\"4\">{}{}</image>", "<stack>".repeat(20_000), "</stack>".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<u8> {
|
||||
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()
|
||||
|
||||
@@ -298,7 +298,7 @@ fn inflate(bytes: &[u8]) -> Result<std::borrow::Cow<'_, [u8]>, 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()))
|
||||
};
|
||||
|
||||
@@ -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<Document<'i>, 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 (`<!DOCTYPE x [ … ]>`)? 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<usize> {
|
||||
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"<?") {
|
||||
skip(rest, 2, b"?>")
|
||||
} else if rest.starts_with(b"<!--") {
|
||||
skip(rest, 4, b"-->")
|
||||
} else if rest.starts_with(b"<!DOCTYPE") {
|
||||
// The name and the quoted public/system ids come first; a `[` outside quotes opens
|
||||
// the subset, a `>` 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!("<a>{}{}</a>", "<g>".repeat(levels), "</g>".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 = "<g>".repeat(2 * MAX_DEPTH);
|
||||
let xml = format!("<?xml version=\"1.0\"?><!-- {g} --><a t=\"<> /> >\"><![CDATA[ {g} ]]><?pi {g} ?><b/></a>");
|
||||
assert!(parse(&xml, ParsingOptions::default()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_internal_subset_is_refused_an_external_doctype_parses() {
|
||||
let krita = "<?xml version=\"1.0\"?>\n<!-- c --><!DOCTYPE DOC PUBLIC '-//KDE//DTD krita 2.0//EN' 'http://www.calligra.org/DTD/[krita].dtd'>\n<DOC/>";
|
||||
assert!(parse(krita, dtd()).is_ok());
|
||||
let deep = format!("<!DOCTYPE a [<!ENTITY e \"{}{}\">]><a>&e;</a>", "<g>".repeat(20_000), "</g>".repeat(20_000));
|
||||
for xml in [
|
||||
"<!DOCTYPE a [<!ENTITY e \"x\">]><a>&e;</a>".to_string(),
|
||||
"\u{feff}<?xml version=\"1.0\"?><!-- ' --> <!DOCTYPE a SYSTEM \"a.dtd\" [<!-- ' -->]><a/>".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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user