diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d352978..15071105 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ ### Fixed +- Refuse to render Markdown whose markup nests deeper than 256 levels, which + cost the sanitizer minutes of CPU per request. - Reject off-origin and scheme-relative `Referer` values when redirecting back after a theme change, closing an open-redirect bypass via `//`-prefixed paths. - Unlink Unix domain socket after shutdown. diff --git a/Cargo.lock b/Cargo.lock index 41e761bf..bbdca368 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2642,6 +2642,7 @@ name = "wastebin_highlight" version = "3.9.0" dependencies = [ "ammonia", + "html5ever", "pulldown-cmark", "syntect", "thiserror", diff --git a/crates/wastebin_highlight/Cargo.toml b/crates/wastebin_highlight/Cargo.toml index 62151e87..21e9dd79 100644 --- a/crates/wastebin_highlight/Cargo.toml +++ b/crates/wastebin_highlight/Cargo.toml @@ -7,6 +7,8 @@ publish = false [dependencies] ammonia = "4" +# The version ammonia parses with: the nesting check has to build the tree the sanitizer does. +html5ever = "0.40" pulldown-cmark = { version = "0.13", default-features = false, features = ["html"] } syntect = { workspace = true } thiserror = { workspace = true } diff --git a/crates/wastebin_highlight/src/highlight.rs b/crates/wastebin_highlight/src/highlight.rs index e4461821..c85b949c 100644 --- a/crates/wastebin_highlight/src/highlight.rs +++ b/crates/wastebin_highlight/src/highlight.rs @@ -17,6 +17,8 @@ pub enum Error { SyntaxParsing(#[from] syntect::parsing::ParsingError), #[error("failed to escaped")] Escape, + #[error("markup nested deeper than {0} levels")] + TooDeeplyNested(usize), } const HIGHLIGHT_LINE_LENGTH_CUTOFF: usize = 2048; diff --git a/crates/wastebin_highlight/src/markdown.rs b/crates/wastebin_highlight/src/markdown.rs index 9396a151..b050890b 100644 --- a/crates/wastebin_highlight/src/markdown.rs +++ b/crates/wastebin_highlight/src/markdown.rs @@ -1,3 +1,5 @@ +mod nesting; + use std::sync::OnceLock; use ammonia::Builder; @@ -5,6 +7,14 @@ use pulldown_cmark::{BlockQuoteKind, CodeBlockKind, CowStr, Event, Options, Pars use crate::highlight::Error; use crate::{Highlighter, Html}; +use nesting::nesting_depth; + +/// Deepest markup nesting handed to the sanitizer. +/// +/// Building the DOM is quadratic in nesting depth, and raw HTML in a paste reaches it verbatim: +/// a megabyte of `
` is a quarter million levels deep and costs minutes of CPU. Prose does not +/// come close to this bound — deeply nested lists sit around a dozen levels. +const MAX_NESTING_DEPTH: usize = 256; /// Render CommonMark `text` to HTML. Fenced code blocks with a known language are syntax /// highlighted via `highlighter`; unknown languages fall back to plain text. @@ -12,6 +22,8 @@ use crate::{Highlighter, Html}; /// Raw HTML embedded in the source is passed through the parser and then sanitized by /// [`ammonia`], so tags like `
` or `` survive while `", + "