From b00c3c4acd2437301ef68b9927bbd03d885e7368 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 07:57:39 -0500 Subject: [PATCH 1/6] fix(render): hold an SVG marker image to the XML namespace limit --- crates/data/src/xml.rs | 10 ++++++++-- crates/engine/src/project.rs | 2 +- crates/engine/src/tests.rs | 2 +- crates/render/src/picture.rs | 16 +++++++++++++--- crates/render/src/picture/svg.rs | 31 +++++++++++++++++++++++++++++-- crates/ui-egui/src/markerpick.rs | 2 +- 6 files changed, 53 insertions(+), 10 deletions(-) diff --git a/crates/data/src/xml.rs b/crates/data/src/xml.rs index 8c51ef4203..dbccca5d2e 100644 --- a/crates/data/src/xml.rs +++ b/crates/data/src/xml.rs @@ -30,6 +30,12 @@ pub const NAMESPACE_WORK: u64 = 64; /// namespaces is no threat. const MIN_NAMESPACE_WORK: u64 = 1 << 20; +/// [`check_limits`]'s refusal for namespaces that take too much to resolve. +pub const TOO_MANY_NAMESPACES: &str = "the document's namespace declarations would take more to resolve than its size allows"; + +/// How [`check_limits`]'s refusal for elements nested past [`MAX_DEPTH`] starts. +pub const TOO_DEEP: &str = "the document nests elements more than"; + /// Parses `text` (a leading byte-order mark dropped) with `opts`, once [`check_limits`] passes. pub fn parse<'a>(text: &'a str, opts: ParsingOptions<'a>) -> Result, String> { let mut unbounded = u64::MAX; @@ -55,7 +61,7 @@ pub fn namespace_budget(len: usize) -> u64 { } fn too_much() -> String { - "the document's namespace declarations would take more to resolve than its size allows".to_string() + TOO_MANY_NAMESPACES.to_string() } /// Refuses XML nested deeper than [`MAX_DEPTH`], or whose namespaces would take more than @@ -148,7 +154,7 @@ pub fn check_limits(text: &str, allow_dtd: bool) -> Result { // An element's start tag: to its `>` (quoted values skipped); `/>` closes it at once. depth += 1; if depth > MAX_DEPTH { - return Err(format!("the document nests elements more than {MAX_DEPTH} deep")); + return Err(format!("{TOO_DEEP} {MAX_DEPTH} deep")); } let mut j = i + 1; let mut quote = None::; diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 1c829a0b45..cf4b44f97e 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -2339,7 +2339,7 @@ pub(crate) fn picture_notices_by<'a>( for (names, what) in [ ( too_much_to_read, - "Image markers in {names} are SVGs whose style sheets, element attributes or entities holding tags take more to read than RustGIS allows and are drawn as circles", + "Image markers in {names} are SVGs whose style sheets, element attributes, namespaces or entities holding tags take more to read than RustGIS allows and are drawn as circles", ), ( too_nested, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 185070a472..5ff1822ab9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2959,7 +2959,7 @@ fn svg_image_markers_that_dont_draw_are_said_with_why() { (MarkerRefusal::TooManyBytes, "Image markers in \"Cities\", \"Rivers\" are longer than 2 MiB as base64 and are drawn as circles"), ( MarkerRefusal::SvgTooMuchToRead, - "Image markers in \"Cities\", \"Rivers\" are SVGs whose style sheets, element attributes or entities holding tags take more to read than RustGIS allows and are drawn as circles", + "Image markers in \"Cities\", \"Rivers\" are SVGs whose style sheets, element attributes, namespaces or entities holding tags take more to read than RustGIS allows and are drawn as circles", ), ( MarkerRefusal::SvgTooNested, diff --git a/crates/render/src/picture.rs b/crates/render/src/picture.rs index e39636abf3..6140c78456 100644 --- a/crates/render/src/picture.rs +++ b/crates/render/src/picture.rs @@ -83,8 +83,9 @@ pub enum MarkerRefusal { /// count, `svg::work`), or more elements than `svg::ELEMENTS` (10,000). TooMuchToDraw, /// It is an SVG whose style sheets and `style` attributes, or whose elements' attributes, take - /// more to read than `svg::STYLE_UNITS` and `svg::ATTRIBUTE_PAIRS` allow, or whose entities - /// hold tags, which no count sees. + /// more to read than `svg::STYLE_UNITS` and `svg::ATTRIBUTE_PAIRS` allow, whose namespaces + /// take more to resolve than `rustgis_data::xml::check_limits` allows, or whose entities hold + /// tags, which no count sees. SvgTooMuchToRead, /// It is an SVG with more XML nodes than `svg::XML_NODES` (40,000) or nested deeper than /// `svg::DEPTH` (64). @@ -141,7 +142,7 @@ refusal_phrases! { TooManyBytes => "is longer than 2 MiB as base64", TooManyPixels => "has more pixels than 2048 × 2048", TooMuchToDraw => "is an SVG with more to draw than a 2048 × 2048 image", - SvgTooMuchToRead => "is an SVG whose style sheets, element attributes or entities holding tags take more to read than RustGIS allows", + SvgTooMuchToRead => "is an SVG whose style sheets, element attributes, namespaces or entities holding tags take more to read than RustGIS allows", SvgTooNested => "is an SVG with more than 40,000 XML nodes or nested deeper than 64 levels", SvgUnknownRadius => "is an SVG with a radius whose size RustGIS can't know (in em or ex, or in % of a size in em or ex, or of a nested size in % over 100%)", SvgTooSmall => "is an SVG too small to draw", @@ -928,6 +929,15 @@ mod tests { (svg(&nodes), SvgTooNested), // Its own cause (#2800), not "more to draw": 20,000 declarations in a `style` take too long to read. (svg(&format!(r#""#, "fill: red; ".repeat(20_000))), SvgTooMuchToRead), + // So do namespaces by the thousand around many elements (#3220). + ( + svg(&format!( + "{}", + (0..3000).map(|i| format!(r#" xmlns:n{i}="u{i}""#)).collect::(), + r#""#.repeat(1000) + )), + SvgTooMuchToRead, + ), (svg(r#""#), SvgUnknownRadius), (svg(r#""#), SvgUnknownRadius), // A radius in % of a size in em or ex with no view box, or of a nested one past 100%. diff --git a/crates/render/src/picture/svg.rs b/crates/render/src/picture/svg.rs index a106dabb7d..193f60d813 100644 --- a/crates/render/src/picture/svg.rs +++ b/crates/render/src/picture/svg.rs @@ -34,7 +34,8 @@ pub(super) enum Refusal { /// It has more to draw than the cap given, or more elements than [`ELEMENTS`]. TooMuch, /// Its style sheets and `style` attributes come to more than [`STYLE_UNITS`], the attributes - /// of its elements to more than [`ATTRIBUTE_PAIRS`], or an entity of it holds a tag, whose + /// of its elements to more than [`ATTRIBUTE_PAIRS`], its namespaces to more than + /// [`rustgis_data::xml::check_limits`] allows, or an entity of it holds a tag, whose /// expansion no count sees: more to read than the readers do in time. TooMuchToRead, /// It has more XML nodes than [`XML_NODES`], or nests deeper than [`DEPTH`]. @@ -101,7 +102,8 @@ const NODE: u64 = 100; const STOPS_PER_UNIT: u64 = 16; /// SVG text `text` as XML with an `` root, within what reading its tags may cost: -/// [`XML_NODES`], [`ATTRIBUTE_PAIRS`], no entity holding a tag. +/// [`XML_NODES`], [`ATTRIBUTE_PAIRS`], the namespace work every XML reader allows +/// ([`rustgis_data::xml::check_limits`]), no entity holding a tag. fn parse(text: &str) -> Result, Refusal> { // An entity of a tag expands to tags `attribute_pairs` doesn't see, once for each use (a text // entity, as in an Illustrator file's `xmlns` values, is no way round it). @@ -112,6 +114,13 @@ fn parse(text: &str) -> Result, Refusal> { if attribute_pairs(text) > ATTRIBUTE_PAIRS { return Err(Refusal::TooMuchToRead); } + // Before roxmltree resolves each name among the namespaces around it (#3220). + rustgis_data::xml::check_limits(text, true).map_err(|why| match why.as_str() { + rustgis_data::xml::TOO_MANY_NAMESPACES => Refusal::TooMuchToRead, + why if why.starts_with(rustgis_data::xml::TOO_DEEP) => Refusal::TooNested, + // A DOCTYPE that never ends, which roxmltree refuses too. + _ => Refusal::NotSvg, + })?; let xml = roxmltree::ParsingOptions { allow_dtd: true, nodes_limit: XML_NODES, ..Default::default() }; let doc = roxmltree::Document::parse_with_options(text, xml).map_err(|e| match e { roxmltree::Error::NodesLimitReached => Refusal::TooNested, @@ -1140,6 +1149,24 @@ mod tests { } } + /// Namespaces that take more to resolve than the SVG's size allows are refused before the + /// parser meets them (#3220: 74 KB took 7 s), searched for params too; a few dozen on the + /// root with text entities for them, as an Illustrator file has, are read. + #[test] + fn an_svg_of_namespaces_too_costly_to_resolve_isnt_parsed() { + let declarations: String = (0..3000).map(|i| format!(r#" xmlns:n{i}="u{i}""#)).collect(); + let flood = sized(&declarations, &r#""#.repeat(1000)); + let started = std::time::Instant::now(); + assert_eq!(read(&flood).err(), Some(Refusal::TooMuchToRead)); + assert_eq!(with_params(&flood, &COLOURS), Err(Refusal::TooMuchToRead)); + assert!(started.elapsed() < std::time::Duration::from_secs(1), "{:?}", started.elapsed()); + let entities: String = (0..40).map(|i| format!(r#""#)).collect(); + let used: String = (0..40).map(|i| format!(r#" xmlns:n{i}="&ns{i};""#)).collect(); + let drawn = r#""#.repeat(1000); + let real = format!("{}", sized(&used, &drawn)); + assert!(read(&real).is_ok()); + } + /// Before its values are set, an SVG is held to what [`super::read`] holds one to. #[test] fn an_svg_too_costly_to_read_isnt_searched_for_params() { diff --git a/crates/ui-egui/src/markerpick.rs b/crates/ui-egui/src/markerpick.rs index a507be43f4..c81dc9f52d 100644 --- a/crates/ui-egui/src/markerpick.rs +++ b/crates/ui-egui/src/markerpick.rs @@ -95,7 +95,7 @@ impl MarkerImage { &[("mib", &(rustgis_engine::map::symbology::MAX_PICTURE_BYTES >> 20).to_string())], ), MarkerRefusal::SvgTooMuchToRead => tl!( - "This image can't be a marker: it is an SVG whose style sheets, element attributes or entities holding tags take more to read than RustGIS allows" + "This image can't be a marker: it is an SVG whose style sheets, element attributes, namespaces or entities holding tags take more to read than RustGIS allows" ) .to_string(), MarkerRefusal::SvgTooNested => tl!( From 447b6267e1764b157406970e474fa9c375ddda99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 11:05:41 -0500 Subject: [PATCH 2/6] fix(data, render): bound the text an XML document's entities expand to (#3232) --- crates/data/src/xml.rs | 91 +++++++++++++++++++++++++++++++- crates/engine/src/project.rs | 2 +- crates/engine/src/tests.rs | 2 +- crates/render/src/picture.rs | 6 +-- crates/render/src/picture/svg.rs | 33 ++++++++---- crates/ui-egui/src/markerpick.rs | 2 +- 6 files changed, 120 insertions(+), 16 deletions(-) diff --git a/crates/data/src/xml.rs b/crates/data/src/xml.rs index dbccca5d2e..dbdddf92b2 100644 --- a/crates/data/src/xml.rs +++ b/crates/data/src/xml.rs @@ -33,6 +33,19 @@ const MIN_NAMESPACE_WORK: u64 = 1 << 20; /// [`check_limits`]'s refusal for namespaces that take too much to resolve. pub const TOO_MANY_NAMESPACES: &str = "the document's namespace declarations would take more to resolve than its size allows"; +/// Bytes of text the entities used in a document may expand to, per byte of the document: the +/// parser bounds references within an entity, not how often the document uses it. +const ENTITY_EXPANSION: u64 = 16; + +/// What any document's entities may expand to, however short. +const MIN_ENTITY_EXPANSION: u64 = 1 << 20; + +/// How deep the parser follows an entity's references to others. +const ENTITY_DEPTH: usize = 10; + +/// [`check_limits`]'s refusal for entities that expand to too much text. +pub const TOO_MUCH_ENTITY_TEXT: &str = "the document's entities would expand to more than its size allows"; + /// How [`check_limits`]'s refusal for elements nested past [`MAX_DEPTH`] starts. pub const TOO_DEEP: &str = "the document nests elements more than"; @@ -70,7 +83,9 @@ fn too_much() -> String { /// parser does (one declared again is the same prefix); where it can't tell, it counts too deep /// rather than too shallow, and too much work rather than too little (an attribute with no prefix /// counts as looked up). With a DTD allowed, an entity whose value holds markup is refused too: -/// expanded, it would nest in ways the text doesn't show. Returns the steps of namespace work it counted. +/// expanded, it would nest in ways the text doesn't show; so are entities whose uses after the +/// DOCTYPE (in comments and CDATA too) expand to more than [`ENTITY_EXPANSION`] bytes a byte. +/// Returns the steps of namespace work it counted. pub fn check_limits(text: &str, allow_dtd: bool) -> Result { let b = text.as_bytes(); let (mut i, mut depth) = (0usize, 0usize); @@ -111,6 +126,7 @@ pub fn check_limits(text: &str, allow_dtd: bool) -> Result { let mut j = i + 2; let (mut bracket, mut quote) = (0usize, None::); let mut closed = false; + let mut entities: Vec<(&[u8], &[u8])> = Vec::new(); while let Some(&c) = b.get(j) { if quote.is_none() && b.get(j..).is_some_and(|r| r.starts_with(b"").map(|e| e + 3).ok_or("the document's DOCTYPE has an unclosed comment")?; @@ -120,6 +136,9 @@ pub fn check_limits(text: &str, allow_dtd: bool) -> Result { j = find(j + 2, b"?>").map(|e| e + 2).ok_or("the document's DOCTYPE has an unclosed instruction")?; continue; } + if allow_dtd && quote.is_none() { + entities.extend(b.get(j..).and_then(entity)); + } match (quote, c) { (Some(q), c) if c == q => quote = None, (Some(_), _) => {} @@ -141,6 +160,10 @@ pub fn check_limits(text: &str, allow_dtd: bool) -> Result { if allow_dtd && entity_with_markup(decl) { return Err("the document declares entities holding markup, which aren't read".into()); } + let most = (text.len() as u64).saturating_mul(ENTITY_EXPANSION).max(MIN_ENTITY_EXPANSION); + if !entities.is_empty() && expansion(&entities, b.get(j..).unwrap_or(&[])) > most { + return Err(TOO_MUCH_ENTITY_TEXT.into()); + } i = j + 1; } else if rest.starts_with(b", prefix: &[u8]) { } } +/// The name and quoted value of the general entity `decl` starts by declaring, if it does. +fn entity(decl: &[u8]) -> Option<(&[u8], &[u8])> { + let rest = decl.strip_prefix(b" impl Iterator { + text.split(|&c| c == b'&').skip(1).filter_map(|after| after.get(..after.iter().position(|&c| c == b';')?)) +} + +/// The bytes the references of `body` to `entities` expand to, each entity's own references +/// followed [`ENTITY_DEPTH`] deep; of an entity declared twice, the longer. +fn expansion(entities: &[(&[u8], &[u8])], body: &[u8]) -> u64 { + let mut lengths: HashMap<&[u8], u64> = HashMap::new(); + let total = |lengths: &HashMap<&[u8], u64>, text: &[u8]| { + references(text).filter_map(|name| lengths.get(name)).fold(0u64, |sum, &n| sum.saturating_add(n)) + }; + // One pass a level: a value's own bytes, and what its references came to the level before. + for _ in 0..=ENTITY_DEPTH { + let mut next: HashMap<&[u8], u64> = HashMap::new(); + for &(name, value) in entities { + let length = (value.len() as u64).saturating_add(total(&lengths, value)); + let longest = next.entry(name).or_default(); + *longest = (*longest).max(length); + } + lengths = next; + } + total(&lengths, body) +} + /// Whether a DOCTYPE declares an entity whose value holds markup (a `<`). pub fn entity_with_markup(decl: &[u8]) -> bool { let mut at = 0; @@ -357,6 +417,35 @@ mod tests { assert!(check_limits(&format!("", declarations(500)), false).is_ok()); } + /// A DOCTYPE declaring `entities`, around an `` holding `body`. + fn declaring(entities: &str, body: &str) -> String { + format!("{body}") + } + + /// What entities expand to where they are used is bounded by the document's length: a long one + /// used many times, or short ones nested into a long one, is refused before parsing (#3232), + /// while one used often for little, or declared and never used, is read. + #[test] + fn entity_expansion_is_bounded() { + let long = format!(r#""#, "a".repeat(100_000)); + let nested = format!(r#""#, "x".repeat(100), "&a;".repeat(100), "&b;".repeat(200)); + for doc in [ + declaring(&long, &format!(r#""#, "&e;".repeat(4000))), + declaring(&long, &"&e;".repeat(4000)), + declaring(&nested, "&c;"), + ] { + assert_eq!(check_limits(&doc, true).unwrap_err(), TOO_MUCH_ENTITY_TEXT); + } + let short = format!(r#""#, "a".repeat(10)); + for doc in [declaring(&short, &"&e;".repeat(500)), declaring(&nested, "&b;"), declaring(&long, "")] { + assert!(parse(&doc, ParsingOptions { allow_dtd: true, ..ParsingOptions::default() }).is_ok()); + } + // A service's capabilities are held to it too. + let capabilities = format!(r#""#, "&e;".repeat(4000)); + let refused = crate::ogc::parse("https://x.example/wms", capabilities.as_bytes()).unwrap_err(); + assert!(refused.to_string().contains(TOO_MUCH_ENTITY_TEXT), "{refused}"); + } + /// Every XML reader refuses a document whose namespaces would take too long to resolve. #[test] fn every_reader_refuses_namespace_floods() { diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index cf4b44f97e..93b5640c5c 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -2339,7 +2339,7 @@ pub(crate) fn picture_notices_by<'a>( for (names, what) in [ ( too_much_to_read, - "Image markers in {names} are SVGs whose style sheets, element attributes, namespaces or entities holding tags take more to read than RustGIS allows and are drawn as circles", + "Image markers in {names} are SVGs whose style sheets, element attributes, namespaces or entities take more to read than RustGIS allows and are drawn as circles", ), ( too_nested, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 5ff1822ab9..8bf419e116 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2959,7 +2959,7 @@ fn svg_image_markers_that_dont_draw_are_said_with_why() { (MarkerRefusal::TooManyBytes, "Image markers in \"Cities\", \"Rivers\" are longer than 2 MiB as base64 and are drawn as circles"), ( MarkerRefusal::SvgTooMuchToRead, - "Image markers in \"Cities\", \"Rivers\" are SVGs whose style sheets, element attributes, namespaces or entities holding tags take more to read than RustGIS allows and are drawn as circles", + "Image markers in \"Cities\", \"Rivers\" are SVGs whose style sheets, element attributes, namespaces or entities take more to read than RustGIS allows and are drawn as circles", ), ( MarkerRefusal::SvgTooNested, diff --git a/crates/render/src/picture.rs b/crates/render/src/picture.rs index 6140c78456..e3c070d4df 100644 --- a/crates/render/src/picture.rs +++ b/crates/render/src/picture.rs @@ -84,8 +84,8 @@ pub enum MarkerRefusal { TooMuchToDraw, /// It is an SVG whose style sheets and `style` attributes, or whose elements' attributes, take /// more to read than `svg::STYLE_UNITS` and `svg::ATTRIBUTE_PAIRS` allow, whose namespaces - /// take more to resolve than `rustgis_data::xml::check_limits` allows, or whose entities hold - /// tags, which no count sees. + /// take more to resolve, or whose entities expand to more, than + /// `rustgis_data::xml::check_limits` allows, or whose entities hold tags, which no count sees. SvgTooMuchToRead, /// It is an SVG with more XML nodes than `svg::XML_NODES` (40,000) or nested deeper than /// `svg::DEPTH` (64). @@ -142,7 +142,7 @@ refusal_phrases! { TooManyBytes => "is longer than 2 MiB as base64", TooManyPixels => "has more pixels than 2048 × 2048", TooMuchToDraw => "is an SVG with more to draw than a 2048 × 2048 image", - SvgTooMuchToRead => "is an SVG whose style sheets, element attributes, namespaces or entities holding tags take more to read than RustGIS allows", + SvgTooMuchToRead => "is an SVG whose style sheets, element attributes, namespaces or entities take more to read than RustGIS allows", SvgTooNested => "is an SVG with more than 40,000 XML nodes or nested deeper than 64 levels", SvgUnknownRadius => "is an SVG with a radius whose size RustGIS can't know (in em or ex, or in % of a size in em or ex, or of a nested size in % over 100%)", SvgTooSmall => "is an SVG too small to draw", diff --git a/crates/render/src/picture/svg.rs b/crates/render/src/picture/svg.rs index 193f60d813..a8962bee4f 100644 --- a/crates/render/src/picture/svg.rs +++ b/crates/render/src/picture/svg.rs @@ -35,7 +35,7 @@ pub(super) enum Refusal { TooMuch, /// Its style sheets and `style` attributes come to more than [`STYLE_UNITS`], the attributes /// of its elements to more than [`ATTRIBUTE_PAIRS`], its namespaces to more than - /// [`rustgis_data::xml::check_limits`] allows, or an entity of it holds a tag, whose + /// [`rustgis_data::xml::check_limits`] allows, as what its entities expand to may, or an entity of it holds a tag, whose /// expansion no count sees: more to read than the readers do in time. TooMuchToRead, /// It has more XML nodes than [`XML_NODES`], or nests deeper than [`DEPTH`]. @@ -102,8 +102,8 @@ const NODE: u64 = 100; const STOPS_PER_UNIT: u64 = 16; /// SVG text `text` as XML with an `` root, within what reading its tags may cost: -/// [`XML_NODES`], [`ATTRIBUTE_PAIRS`], the namespace work every XML reader allows -/// ([`rustgis_data::xml::check_limits`]), no entity holding a tag. +/// [`XML_NODES`], [`ATTRIBUTE_PAIRS`], the namespace work and entity expansion every XML reader +/// allows ([`rustgis_data::xml::check_limits`]), no entity holding a tag. fn parse(text: &str) -> Result, Refusal> { // An entity of a tag expands to tags `attribute_pairs` doesn't see, once for each use (a text // entity, as in an Illustrator file's `xmlns` values, is no way round it). @@ -114,9 +114,10 @@ fn parse(text: &str) -> Result, Refusal> { if attribute_pairs(text) > ATTRIBUTE_PAIRS { return Err(Refusal::TooMuchToRead); } - // Before roxmltree resolves each name among the namespaces around it (#3220). + // Before roxmltree resolves each name among the namespaces around it (#3220), and expands + // each use of an entity (#3232). rustgis_data::xml::check_limits(text, true).map_err(|why| match why.as_str() { - rustgis_data::xml::TOO_MANY_NAMESPACES => Refusal::TooMuchToRead, + rustgis_data::xml::TOO_MANY_NAMESPACES | rustgis_data::xml::TOO_MUCH_ENTITY_TEXT => Refusal::TooMuchToRead, why if why.starts_with(rustgis_data::xml::TOO_DEEP) => Refusal::TooNested, // A DOCTYPE that never ends, which roxmltree refuses too. _ => Refusal::NotSvg, @@ -1167,6 +1168,19 @@ mod tests { assert!(read(&real).is_ok()); } + /// A text entity used many times is refused before the parser expands it, searched for params + /// too (#3232: 112 KB took 847 MB). + #[test] + fn an_svg_of_entities_expanding_too_far_isnt_parsed() { + let entity = format!(r#""#, "a".repeat(100_000)); + let rect = format!(r#""#, "&e;".repeat(4000)); + let flood = format!("{}", sized("", &rect)); + let started = std::time::Instant::now(); + assert_eq!(read(&flood).err(), Some(Refusal::TooMuchToRead)); + assert_eq!(with_params(&flood, &COLOURS), Err(Refusal::TooMuchToRead)); + assert!(started.elapsed() < std::time::Duration::from_secs(1), "{:?}", started.elapsed()); + } + /// Before its values are set, an SVG is held to what [`super::read`] holds one to. #[test] fn an_svg_too_costly_to_read_isnt_searched_for_params() { @@ -1183,14 +1197,15 @@ mod tests { } /// What a text entity expands to in `style` attributes is written out only as far as a marker - /// image may be long, then refused: a 100 KB entity in 20 of them would come to 2 MB. + /// image may be long, then refused: a 100 KB entity in 16 of them would come to 1.6 MB. #[test] fn param_values_are_set_in_no_longer_an_svg_than_an_image_may_be() { let long = "a".repeat(100_000); let rects = |n: usize| r#""#.repeat(n); let svg = |n: usize| format!(r#"]>{}"#, sized("", &rects(n))); assert!(with_params(&svg(10), &COLOURS).is_ok_and(|set| set.is_some())); - assert_eq!(with_params(&svg(20), &COLOURS), Err(Refusal::TooMuchToRead)); + assert!(read(&svg(16)).is_ok()); + assert_eq!(with_params(&svg(16), &COLOURS), Err(Refusal::TooMuchToRead)); } /// [`elements`] of `body`. @@ -1411,10 +1426,10 @@ mod tests { assert_eq!(read("").err(), Some(Refusal::NotSvg)); assert_eq!(read("not xml").err(), Some(Refusal::NotSvg)); let laughs = r#"]>&g;"#; - assert_eq!(read(laughs).err(), Some(Refusal::NotSvg)); + assert_eq!(read(laughs).err(), Some(Refusal::TooMuchToRead)); // The same in an attribute's value, quickly. let started = std::time::Instant::now(); - assert_eq!(read(&laughs.replace("&g;", r#""#)).err(), Some(Refusal::NotSvg)); + assert_eq!(read(&laughs.replace("&g;", r#""#)).err(), Some(Refusal::TooMuchToRead)); assert!(started.elapsed() < std::time::Duration::from_secs(1)); assert_eq!(read(&svg(&"".repeat(XML_NODES as usize))).err(), Some(Refusal::TooNested)); let deep = format!("{}{}", "".repeat(2000), "".repeat(2000)); diff --git a/crates/ui-egui/src/markerpick.rs b/crates/ui-egui/src/markerpick.rs index c81dc9f52d..6f7e3c4986 100644 --- a/crates/ui-egui/src/markerpick.rs +++ b/crates/ui-egui/src/markerpick.rs @@ -95,7 +95,7 @@ impl MarkerImage { &[("mib", &(rustgis_engine::map::symbology::MAX_PICTURE_BYTES >> 20).to_string())], ), MarkerRefusal::SvgTooMuchToRead => tl!( - "This image can't be a marker: it is an SVG whose style sheets, element attributes, namespaces or entities holding tags take more to read than RustGIS allows" + "This image can't be a marker: it is an SVG whose style sheets, element attributes, namespaces or entities take more to read than RustGIS allows" ) .to_string(), MarkerRefusal::SvgTooNested => tl!( From 99c13632974181fd0a999ea514c1257904b3a02a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 11:33:30 -0500 Subject: [PATCH 3/6] fix(data): count every entity the parser would declare, once and in linear time (#3232) --- crates/data/src/xml.rs | 56 +++++++++++++++++++++++++++----- crates/render/src/picture/svg.rs | 6 ++-- 2 files changed, 50 insertions(+), 12 deletions(-) diff --git a/crates/data/src/xml.rs b/crates/data/src/xml.rs index dbdddf92b2..cf38701469 100644 --- a/crates/data/src/xml.rs +++ b/crates/data/src/xml.rs @@ -4,7 +4,8 @@ //! [`NAMESPACE_WORK`] times its size to resolve, before parsing it. Nesting thousands of elements //! deep exhausts the stack while the document is parsed or walked, and crafted namespace //! declarations (or attributes) make the parse grow as their number times the elements they stand -//! around; a hostile file must be an error, never a crash. +//! around; a hostile file must be an error, never a crash. Where a DTD is allowed, so are entities +//! that expand to far more than the document is long. use std::collections::HashMap; @@ -84,7 +85,8 @@ fn too_much() -> String { /// rather than too shallow, and too much work rather than too little (an attribute with no prefix /// counts as looked up). With a DTD allowed, an entity whose value holds markup is refused too: /// expanded, it would nest in ways the text doesn't show; so are entities whose uses after the -/// DOCTYPE (in comments and CDATA too) expand to more than [`ENTITY_EXPANSION`] bytes a byte. +/// DOCTYPE (in comments and CDATA too) expand to more than [`ENTITY_EXPANSION`] bytes a byte, and +/// than [`MIN_ENTITY_EXPANSION`]. /// Returns the steps of namespace work it counted. pub fn check_limits(text: &str, allow_dtd: bool) -> Result { let b = text.as_bytes(); @@ -95,6 +97,7 @@ pub fn check_limits(text: &str, allow_dtd: bool) -> Result { let mut declared: Vec> = Vec::new(); let mut prefixes: HashMap<&[u8], usize> = HashMap::new(); let mut work = 0u64; + let mut counted = false; let limit = namespace_budget(text.len()); let find = |from: usize, pat: &[u8]| -> Option { b.get(from..)?.windows(pat.len()).position(|w| w == pat).map(|p| from + p) }; while i < b.len() { @@ -136,8 +139,17 @@ pub fn check_limits(text: &str, allow_dtd: bool) -> Result { j = find(j + 2, b"?>").map(|e| e + 2).ok_or("the document's DOCTYPE has an unclosed instruction")?; continue; } - if allow_dtd && quote.is_none() { - entities.extend(b.get(j..).and_then(entity)); + if quote.is_none() && bracket > 0 { + let at = b.get(j..).unwrap_or(&[]); + // The parser ends these at their first `>`, in quotes or not: so does this, to + // read what follows as it does. + if [&b"").map(|e| e + 1).ok_or("the document's DOCTYPE never ends")?; + continue; + } + if allow_dtd { + entities.extend(entity(at)); + } } match (quote, c) { (Some(q), c) if c == q => quote = None, @@ -161,7 +173,8 @@ pub fn check_limits(text: &str, allow_dtd: bool) -> Result { return Err("the document declares entities holding markup, which aren't read".into()); } let most = (text.len() as u64).saturating_mul(ENTITY_EXPANSION).max(MIN_ENTITY_EXPANSION); - if !entities.is_empty() && expansion(&entities, b.get(j..).unwrap_or(&[])) > most { + // Once: a document has one DOCTYPE, and each count reads all that follows. + if !entities.is_empty() && !std::mem::replace(&mut counted, true) && expansion(&entities, b.get(j..).unwrap_or(&[])) > most { return Err(TOO_MUCH_ENTITY_TEXT.into()); } i = j + 1; @@ -260,12 +273,20 @@ fn close(prefixes: &mut HashMap<&[u8], usize>, prefix: &[u8]) { } } -/// The name and quoted value of the general entity `decl` starts by declaring, if it does. +/// The name and quoted value of the entity `decl` starts by declaring, if it does. A parameter +/// entity (`%`) counts too: roxmltree expands it as a general one. fn entity(decl: &[u8]) -> Option<(&[u8], &[u8])> { - let rest = decl.strip_prefix(b"")] { assert!(parse(&doc, ParsingOptions { allow_dtd: true, ..ParsingOptions::default() }).is_ok()); } + // Declared where the parser reads them: as a parameter entity, which it expands as any + // other, or after a declaration it ends at a `>` inside quotes. + let uses = format!(r#""#, "&e;".repeat(4000)); + let value = "a".repeat(100_000); + for subset in + [format!(r#""#), format!(r#" "#)] + { + let doc = format!("{uses}"); + assert_eq!(check_limits(&doc, true).unwrap_err(), TOO_MUCH_ENTITY_TEXT); + } + // Counted in time that grows with the document's length, however it is broken. + let started = std::time::Instant::now(); + for doc in [format!("", "]>".repeat(50_000)] { + // Refused or not, which the parser decides: only the time is looked at. + let _ = check_limits(&doc, true); + } + assert!(started.elapsed() < std::time::Duration::from_secs(1), "{:?}", started.elapsed()); // A service's capabilities are held to it too. let capabilities = format!(r#""#, "&e;".repeat(4000)); let refused = crate::ogc::parse("https://x.example/wms", capabilities.as_bytes()).unwrap_err(); diff --git a/crates/render/src/picture/svg.rs b/crates/render/src/picture/svg.rs index a8962bee4f..378510eb4b 100644 --- a/crates/render/src/picture/svg.rs +++ b/crates/render/src/picture/svg.rs @@ -34,9 +34,9 @@ pub(super) enum Refusal { /// It has more to draw than the cap given, or more elements than [`ELEMENTS`]. TooMuch, /// Its style sheets and `style` attributes come to more than [`STYLE_UNITS`], the attributes - /// of its elements to more than [`ATTRIBUTE_PAIRS`], its namespaces to more than - /// [`rustgis_data::xml::check_limits`] allows, as what its entities expand to may, or an entity of it holds a tag, whose - /// expansion no count sees: more to read than the readers do in time. + /// of its elements to more than [`ATTRIBUTE_PAIRS`], its namespaces or what its entities + /// expand to more than [`rustgis_data::xml::check_limits`] allows, or an entity of it holds a + /// tag, whose expansion no count sees: more to read than the readers do in time. TooMuchToRead, /// It has more XML nodes than [`XML_NODES`], or nests deeper than [`DEPTH`]. TooNested, From 0dfdc01ddf0c449d1f7d8294480a86623ffe02f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 11:41:40 -0500 Subject: [PATCH 4/6] docs(data): say what bounds a document's entities (#3232) --- crates/data/src/ogc.rs | 4 ++-- crates/data/src/xml.rs | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/data/src/ogc.rs b/crates/data/src/ogc.rs index fee741d618..e2a2c9193d 100644 --- a/crates/data/src/ogc.rs +++ b/crates/data/src/ogc.rs @@ -888,8 +888,8 @@ pub fn parse(url: &str, body: &[u8]) -> Result { /// Parses a service's XML document through [`crate::xml::parse`], which refuses deep nesting /// (a stack-overflow hazard) and, with the DTD allowed here, entities holding markup. fn xml(text: &str, nodes_limit: u32) -> Result, String> { - // WMS 1.1.1 documents start with a DOCTYPE, so DTDs are allowed; roxmltree still refuses - // entity bombs and external entities, and the node count is capped. + // WMS 1.1.1 documents start with a DOCTYPE, so DTDs are allowed; what its entities expand to + // is bounded by `check_limits`, roxmltree reads no external entity, and the node count is capped. let opts = ParsingOptions { allow_dtd: true, nodes_limit, ..ParsingOptions::default() }; crate::xml::parse(text.trim_start(), opts) } diff --git a/crates/data/src/xml.rs b/crates/data/src/xml.rs index cf38701469..e79ade7746 100644 --- a/crates/data/src/xml.rs +++ b/crates/data/src/xml.rs @@ -4,8 +4,8 @@ //! [`NAMESPACE_WORK`] times its size to resolve, before parsing it. Nesting thousands of elements //! deep exhausts the stack while the document is parsed or walked, and crafted namespace //! declarations (or attributes) make the parse grow as their number times the elements they stand -//! around; a hostile file must be an error, never a crash. Where a DTD is allowed, so are entities -//! that expand to far more than the document is long. +//! around; a hostile file must be an error, never a crash. Where a DTD is allowed, a document whose +//! entities expand to far more than it is long is refused too. use std::collections::HashMap; @@ -84,9 +84,9 @@ fn too_much() -> String { /// parser does (one declared again is the same prefix); where it can't tell, it counts too deep /// rather than too shallow, and too much work rather than too little (an attribute with no prefix /// counts as looked up). With a DTD allowed, an entity whose value holds markup is refused too: -/// expanded, it would nest in ways the text doesn't show; so are entities whose uses after the -/// DOCTYPE (in comments and CDATA too) expand to more than [`ENTITY_EXPANSION`] bytes a byte, and -/// than [`MIN_ENTITY_EXPANSION`]. +/// expanded, it would nest in ways the text doesn't show. A document is refused as well when the +/// uses of its entities after the DOCTYPE (in comments and CDATA too) expand to more than both +/// [`ENTITY_EXPANSION`] bytes per byte of it and [`MIN_ENTITY_EXPANSION`]. /// Returns the steps of namespace work it counted. pub fn check_limits(text: &str, allow_dtd: bool) -> Result { let b = text.as_bytes(); From 36686ea81f69434e346e724f2e7b2d78f3a0b422 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 12:06:47 -0500 Subject: [PATCH 5/6] fix(data): count what each entity reference costs the parser (#3232) --- crates/data/src/xml.rs | 39 +++++++++++++++++++++++++++------------ 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/crates/data/src/xml.rs b/crates/data/src/xml.rs index e79ade7746..b8c735bbf4 100644 --- a/crates/data/src/xml.rs +++ b/crates/data/src/xml.rs @@ -34,8 +34,9 @@ const MIN_NAMESPACE_WORK: u64 = 1 << 20; /// [`check_limits`]'s refusal for namespaces that take too much to resolve. pub const TOO_MANY_NAMESPACES: &str = "the document's namespace declarations would take more to resolve than its size allows"; -/// Bytes of text the entities used in a document may expand to, per byte of the document: the -/// parser bounds references within an entity, not how often the document uses it. +/// What the entities used in a document may cost ([`expansion`]: bytes of text and declarations +/// searched), per byte of the document: the parser bounds references within an entity, not how +/// often the document uses it. const ENTITY_EXPANSION: u64 = 16; /// What any document's entities may expand to, however short. @@ -298,24 +299,31 @@ fn references(text: &[u8]) -> impl Iterator { text.split(|&c| c == b'&').skip(1).filter_map(|after| after.get(..after.iter().position(|&c| c == b';')?)) } -/// The bytes the references of `body` to `entities` expand to, each entity's own references -/// followed [`ENTITY_DEPTH`] deep; of an entity declared twice, the longer. +/// What the references of `body` to `entities` cost the parser: the bytes each expands to, and +/// for each reference, those within values too, one step a declaration, as it searches them one by +/// one. Each entity's own references are followed [`ENTITY_DEPTH`] deep; of an entity declared +/// twice, the longer. fn expansion(entities: &[(&[u8], &[u8])], body: &[u8]) -> u64 { - let mut lengths: HashMap<&[u8], u64> = HashMap::new(); - let total = |lengths: &HashMap<&[u8], u64>, text: &[u8]| { - references(text).filter_map(|name| lengths.get(name)).fold(0u64, |sum, &n| sum.saturating_add(n)) + let mut costs: HashMap<&[u8], u64> = HashMap::new(); + let search = entities.len() as u64; + // What `text` comes to: its own bytes, a known reference's `&name;` giving way to its cost. + let cost = |costs: &HashMap<&[u8], u64>, text: &[u8]| { + references(text).filter_map(|name| Some((name, costs.get(name)?))).fold((0u64, 0u64), |(written, sum), (name, &n)| { + (written + name.len() as u64 + 2, sum.saturating_add(n).saturating_add(search)) + }) }; - // One pass a level: a value's own bytes, and what its references came to the level before. + // One pass a level: what each value came to with its references at the level before. for _ in 0..=ENTITY_DEPTH { let mut next: HashMap<&[u8], u64> = HashMap::new(); for &(name, value) in entities { - let length = (value.len() as u64).saturating_add(total(&lengths, value)); + let (written, sum) = cost(&costs, value); + let came = (value.len() as u64).saturating_sub(written).saturating_add(sum); let longest = next.entry(name).or_default(); - *longest = (*longest).max(length); + *longest = (*longest).max(came); } - lengths = next; + costs = next; } - total(&lengths, body) + cost(&costs, body).1 } /// Whether a DOCTYPE declares an entity whose value holds markup (a `<`). @@ -471,6 +479,13 @@ mod tests { let doc = format!("{uses}"); assert_eq!(check_limits(&doc, true).unwrap_err(), TOO_MUCH_ENTITY_TEXT); } + // Each use also costs the parser a search among the declarations, one by one. + let many: String = (0..20_000).map(|i| format!(r#""#)).collect(); + assert_eq!(check_limits(&declaring(&many, &"&e19999;".repeat(20_000)), true).unwrap_err(), TOO_MUCH_ENTITY_TEXT); + // A reference within a value counts as what it expands to, not as its own text too. + let name = "n".repeat(100); + let named = format!(r#""#); + assert!(check_limits(&declaring(&named, &"&b;".repeat(12_000)), true).is_ok()); // Counted in time that grows with the document's length, however it is broken. let started = std::time::Instant::now(); for doc in [format!("", "]>".repeat(50_000)] { From 31bc368d6e76768f0ec73d0d067ff6a61e723bf9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 13:30:37 -0500 Subject: [PATCH 6/6] fix(data): count the entity names the parser reads again (#3232) --- crates/data/src/xml.rs | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/data/src/xml.rs b/crates/data/src/xml.rs index b8c735bbf4..0e5258c5ba 100644 --- a/crates/data/src/xml.rs +++ b/crates/data/src/xml.rs @@ -45,6 +45,10 @@ const MIN_ENTITY_EXPANSION: u64 = 1 << 20; /// How deep the parser follows an entity's references to others. const ENTITY_DEPTH: usize = 10; +/// The bytes of an entity's name that count as one step of that cost: comparing or skipping a name +/// is far quicker than expanding text. +const NAME_BYTES_PER_STEP: u64 = 16; + /// [`check_limits`]'s refusal for entities that expand to too much text. pub const TOO_MUCH_ENTITY_TEXT: &str = "the document's entities would expand to more than its size allows"; @@ -300,16 +304,18 @@ fn references(text: &[u8]) -> impl Iterator { } /// What the references of `body` to `entities` cost the parser: the bytes each expands to, and -/// for each reference, those within values too, one step a declaration, as it searches them one by -/// one. Each entity's own references are followed [`ENTITY_DEPTH`] deep; of an entity declared +/// for each reference, those within values too, the search it makes among the declarations, one by +/// one, and the name it reads (a step each declaration, and each [`NAME_BYTES_PER_STEP`] of a +/// name). Each entity's own references are followed [`ENTITY_DEPTH`] deep; of an entity declared /// twice, the longer. fn expansion(entities: &[(&[u8], &[u8])], body: &[u8]) -> u64 { let mut costs: HashMap<&[u8], u64> = HashMap::new(); - let search = entities.len() as u64; + let steps = |name: &[u8]| name.len() as u64 / NAME_BYTES_PER_STEP; + let search = entities.iter().fold(0u64, |sum, &(name, _)| sum.saturating_add(1 + steps(name))); // What `text` comes to: its own bytes, a known reference's `&name;` giving way to its cost. let cost = |costs: &HashMap<&[u8], u64>, text: &[u8]| { references(text).filter_map(|name| Some((name, costs.get(name)?))).fold((0u64, 0u64), |(written, sum), (name, &n)| { - (written + name.len() as u64 + 2, sum.saturating_add(n).saturating_add(search)) + (written + name.len() as u64 + 2, sum.saturating_add(n).saturating_add(search).saturating_add(steps(name))) }) }; // One pass a level: what each value came to with its references at the level before. @@ -486,6 +492,10 @@ mod tests { let name = "n".repeat(100); let named = format!(r#""#); assert!(check_limits(&declaring(&named, &"&b;".repeat(12_000)), true).is_ok()); + // And a long name is read again each time a value that holds its reference is expanded. + let long_name = "n".repeat(100_000); + let reread = format!(r#""#); + assert_eq!(check_limits(&declaring(&reread, &"&b;".repeat(20_000)), true).unwrap_err(), TOO_MUCH_ENTITY_TEXT); // Counted in time that grows with the document's length, however it is broken. let started = std::time::Instant::now(); for doc in [format!("", "]>".repeat(50_000)] {