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 `
",
+ "
",
+ // A close tag with a scope boundary between it and the element it names is dropped,
+ // and the sanitizer then strips the boundary and keeps what it held.
+ "",
+ "",
+ "",
+ ] {
+ let html = unit.repeat(MAX_NESTING_DEPTH + 10);
+ let depth = nesting_depth(&html);
+ assert!(depth > MAX_NESTING_DEPTH, "{unit:?} measured {depth} deep");
+ }
+ }
+
+ /// An unclosed formatting element is reopened inside every element that follows it, so this
+ /// nests one level deeper each time though no tag is left open. Only three alike are kept to
+ /// reopen, hence the differing attribute.
+ #[test]
+ fn reopened_formatting_elements_are_measured() {
+ let html: String = (0..MAX_NESTING_DEPTH + 10)
+ .map(|i| format!("
"))
+ .collect();
+
+ assert!(nesting_depth(&html) > MAX_NESTING_DEPTH);
+ }
+
+ /// Past the limit the parse stops, rather than going on to build all of a tree it refuses.
+ #[test]
+ fn the_count_stops_one_past_the_limit() {
+ assert_eq!(
+ nesting_depth(&"
".repeat(100_000)),
+ MAX_NESTING_DEPTH + 1
+ );
+ }
+
+ /// The depth is only that of the sanitizer's tree while both come from the same html5ever,
+ /// and nothing else would notice ammonia moving to a different one.
+ #[test]
+ fn the_sanitizer_parses_with_the_same_html5ever() {
+ let lock = include_str!("../../../../Cargo.lock");
+ assert_eq!(lock.matches("name = \"html5ever\"\n").count(), 1);
+ }
+}
diff --git a/crates/wastebin_server/src/errors.rs b/crates/wastebin_server/src/errors.rs
index e4ed6421..2d442fe2 100644
--- a/crates/wastebin_server/src/errors.rs
+++ b/crates/wastebin_server/src/errors.rs
@@ -43,7 +43,10 @@ impl From for StatusCode {
Error::Database(
db::Error::Delete | db::Error::Crypto(crypto::Error::ChaCha20Poly1305Decrypt),
) => StatusCode::FORBIDDEN,
- Error::Database(db::Error::NoPassword) | Error::Id(_) | Error::UrlParsing(_) => {
+ Error::Database(db::Error::NoPassword)
+ | Error::Id(_)
+ | Error::UrlParsing(_)
+ | Error::SyntaxHighlighting(wastebin_highlight::Error::TooDeeplyNested(_)) => {
StatusCode::BAD_REQUEST
}
Error::MalformedForm => StatusCode::UNPROCESSABLE_ENTITY,
diff --git a/crates/wastebin_server/src/handlers/html/rendered.rs b/crates/wastebin_server/src/handlers/html/rendered.rs
index d8c4f893..47883416 100644
--- a/crates/wastebin_server/src/handlers/html/rendered.rs
+++ b/crates/wastebin_server/src/handlers/html/rendered.rs
@@ -327,4 +327,29 @@ mod tests {
Ok(())
}
+
+ /// Markup nested past the limit is the paste's doing, so the refusal is a bad request rather
+ /// than a server failure.
+ #[tokio::test]
+ async fn too_deeply_nested_markup_is_a_bad_request() -> Result<(), Box> {
+ let client = Client::new(StoreCookies(false)).await;
+ let data = Entry {
+ text: "
".repeat(1000),
+ extension: Some(String::from("md")),
+ ..Default::default()
+ };
+
+ let res = client.post_form().form(&data).send().await?;
+ assert_eq!(res.status(), StatusCode::SEE_OTHER);
+ let location = res.headers().get("location").unwrap().to_str()?;
+
+ let res = client
+ .get(&format!("/md{location}"))
+ .header(header::ACCEPT, "text/html; charset=utf-8")
+ .send()
+ .await?;
+ assert_eq!(res.status(), StatusCode::BAD_REQUEST);
+
+ Ok(())
+ }
}