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 8c51ef4203..0e5258c5ba 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, a document whose +//! entities expand to far more than it is long is refused too. use std::collections::HashMap; @@ -30,6 +31,30 @@ 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"; + +/// 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. +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"; + +/// 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 +80,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 @@ -64,7 +89,10 @@ 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. 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(); let (mut i, mut depth) = (0usize, 0usize); @@ -74,6 +102,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() { @@ -105,6 +134,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")?; @@ -114,6 +144,18 @@ 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 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, (Some(_), _) => {} @@ -135,6 +177,11 @@ 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); + // 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; } else if rest.starts_with(b" 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::; @@ -231,6 +278,60 @@ fn close(prefixes: &mut HashMap<&[u8], usize>, prefix: &[u8]) { } } +/// 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" impl Iterator { + text.split(|&c| c == b'&').skip(1).filter_map(|after| after.get(..after.iter().position(|&c| c == b';')?)) +} + +/// What the references of `body` to `entities` cost the parser: the bytes each expands to, and +/// 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 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).saturating_add(steps(name))) + }) + }; + // 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 (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(came); + } + costs = next; + } + cost(&costs, body).1 +} + /// Whether a DOCTYPE declares an entity whose value holds markup (a `<`). pub fn entity_with_markup(decl: &[u8]) -> bool { let mut at = 0; @@ -351,6 +452,63 @@ 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()); + } + // 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); + } + // 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()); + // 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)] { + // 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(); + 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 1c829a0b45..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 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 185070a472..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 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 e39636abf3..e3c070d4df 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, 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). @@ -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 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..378510eb4b 100644 --- a/crates/render/src/picture/svg.rs +++ b/crates/render/src/picture/svg.rs @@ -34,8 +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`], 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, @@ -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 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). @@ -112,6 +114,14 @@ 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), 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 | 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, + })?; 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 +1150,37 @@ 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()); + } + + /// 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() { @@ -1156,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`. @@ -1384,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 a507be43f4..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 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!(