From ce8771e118820a3d3329f25eca88640a4ab42d67 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Wed, 18 Nov 2026 16:56:40 -0700 Subject: [PATCH 1/2] Stop sanitizing weblog HTML that takes over a second When weblogAdminsUntrusted=true, HTMLSanitizer cleans what weblog users write each time it's shown. Some of its regular expressions backtrack on crafted markup (an 80,000-character style attribute took 43 seconds), and it builds its output by concatenation, so large posts take quadratic time. Each sanitize call now has a one-second limit, checked while its expressions read the markup and once per tag. Markup that hits the limit is escaped in full and a warning is logged, so a slow post shows as text instead of holding the request. --- .../roller/weblogger/util/HTMLSanitizer.java | 91 +++++++++++++++++-- .../util/HTMLSanitizerTimeLimitTest.java | 52 +++++++++++ 2 files changed, 136 insertions(+), 7 deletions(-) create mode 100644 app/src/test/java/org/apache/roller/weblogger/util/HTMLSanitizerTimeLimitTest.java diff --git a/app/src/main/java/org/apache/roller/weblogger/util/HTMLSanitizer.java b/app/src/main/java/org/apache/roller/weblogger/util/HTMLSanitizer.java index 56a8db5e7c..d2f87e77d5 100644 --- a/app/src/main/java/org/apache/roller/weblogger/util/HTMLSanitizer.java +++ b/app/src/main/java/org/apache/roller/weblogger/util/HTMLSanitizer.java @@ -45,10 +45,14 @@ a copy of this software and associated documentation files (the import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.apache.commons.validator.routines.UrlValidator; import org.apache.roller.weblogger.config.WebloggerConfig; public class HTMLSanitizer { + private static final Log log = LogFactory.getLog(HTMLSanitizer.class); + public static Boolean xssEnabled = WebloggerConfig.getBooleanProperty("weblogAdminsUntrusted", Boolean.FALSE); public static Pattern forbiddenTags = Pattern.compile("^(script|object|embed|link|style|form|input)$"); @@ -120,6 +124,24 @@ public static SanitizeResult sanitizer(String html) { } public static SanitizeResult sanitizer(String html, Pattern allowedTags, Pattern forbiddenTags) { + try { + return sanitizer(html, allowedTags, forbiddenTags, + System.nanoTime() + TIME_LIMIT_MILLIS * 1_000_000L); + } catch (TimeLimitException e) { + // escape all of it rather than hold the request or let markup through + log.warn("Sanitizing " + html.length() + " characters of HTML took over " + + TIME_LIMIT_MILLIS + " ms, so all of it was escaped"); + SanitizeResult ret = new SanitizeResult(); + ret.html = htmlEncodeApexesAndTags(html); + ret.text = htmlEncodeApexesAndTags(removeLineFeed(html)); + ret.val = ret.html; + ret.isValid = false; + return ret; + } + } + + private static SanitizeResult sanitizer(String html, Pattern allowedTags, Pattern forbiddenTags, + long deadline) { SanitizeResult ret = new SanitizeResult(); Stack openTags = new Stack<>(); @@ -129,13 +151,14 @@ public static SanitizeResult sanitizer(String html, Pattern allowedTags, Pattern // ------------------- LOOP for every token -------------------------- for (String token : tokens) { boolean isAcceptedToken = false; + checkTime(deadline); - Matcher startMatcher = tagStartPattern.matcher(token); - Matcher endMatcher = tagClosePattern.matcher(token); + Matcher startMatcher = tagStartPattern.matcher(new DeadlineText(token, deadline)); + Matcher endMatcher = tagClosePattern.matcher(new DeadlineText(token, deadline)); //-------------------------------------------------------------------------------- COMMENT - if (commentPattern.matcher(token).find()) { + if (commentPattern.matcher(new DeadlineText(token, deadline)).find()) { ret.val = ret.val + token + (token.endsWith("-->") ? "" : "-->"); ret.invalidTags.add(token + (token.endsWith("-->") ? "" : "-->")); continue; @@ -176,7 +199,7 @@ public static SanitizeResult sanitizer(String html, Pattern allowedTags, Pattern // then test properties - Matcher attributes = attributesPattern.matcher(tokenBody); + Matcher attributes = attributesPattern.matcher(new DeadlineText(tokenBody, deadline)); // URL flag boolean foundURL = false; @@ -233,7 +256,7 @@ public static SanitizeResult sanitizer(String html, Pattern allowedTags, Pattern } else if ("style".equals(attr)) { // // then test properties - Matcher styles = stylePattern.matcher(val); + Matcher styles = stylePattern.matcher(new DeadlineText(val, deadline)); String cleanStyle = ""; while (styles.find()) { @@ -241,13 +264,13 @@ public static SanitizeResult sanitizer(String html, Pattern allowedTags, Pattern String styleValue = styles.group(2); // suppress invalid styles values - if (forbiddenStylePattern.matcher(styleValue).find()) { + if (forbiddenStylePattern.matcher(new DeadlineText(styleValue, deadline)).find()) { ret.invalidTags.add(tag + " " + attr + " " + styleValue); continue; } // check if valid url - Matcher urlStyleMatcher = urlStylePattern.matcher(styleValue); + Matcher urlStyleMatcher = urlStylePattern.matcher(new DeadlineText(styleValue, deadline)); if (urlStyleMatcher.find()) { String[] customSchemes = {"http", "https"}; String url = urlStyleMatcher.group(1); @@ -456,6 +479,60 @@ static class SanitizeResult { public List invalidTags = new ArrayList<>(); } + /** + * Longest one sanitize call may take. Some of the expressions above + * backtrack on crafted markup, and the output is built by concatenation. + */ + static final long TIME_LIMIT_MILLIS = 1000; + + private static void checkTime(long deadline) { + if (System.nanoTime() - deadline > 0) { + throw new TimeLimitException(); + } + } + + private static final class TimeLimitException extends RuntimeException { + TimeLimitException() { + super(null, null, false, false); + } + } + + /** Markup being matched, which stops a match once the time limit has passed. */ + private static final class DeadlineText implements CharSequence { + private final CharSequence text; + private final long deadline; + private int reads; + + DeadlineText(CharSequence text, long deadline) { + this.text = text; + this.deadline = deadline; + } + + @Override + public char charAt(int index) { + // checking the clock on every read would slow ordinary matches + if ((++reads & 0x3FF) == 0) { + checkTime(deadline); + } + return text.charAt(index); + } + + @Override + public int length() { + return text.length(); + } + + @Override + public CharSequence subSequence(int start, int end) { + return new DeadlineText(text.subSequence(start, end), deadline); + } + + @Override + public String toString() { + return text.toString(); + } + } + public static String encode(String s) { return convertLineFeedToBR(htmlEncodeApexesAndTags(s == null ? "" : s)); } diff --git a/app/src/test/java/org/apache/roller/weblogger/util/HTMLSanitizerTimeLimitTest.java b/app/src/test/java/org/apache/roller/weblogger/util/HTMLSanitizerTimeLimitTest.java new file mode 100644 index 0000000000..9316be7b8b --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/util/HTMLSanitizerTimeLimitTest.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. The ASF licenses this file to You + * under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. For additional information regarding + * copyright in this work, please see the NOTICE file in the top level + * directory of this distribution. + */ + +package org.apache.roller.weblogger.util; + +import java.time.Duration; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; + +class HTMLSanitizerTimeLimitTest { + + @Test + void slowMarkupIsStoppedAndEscaped() { + String[] inputs = { + // each of these took the sanitizer 40 seconds or more + "

x

", + "

x

", + "x".repeat(400_000), + }; + for (String input : inputs) { + String html = assertTimeoutPreemptively(Duration.ofSeconds(8), + () -> HTMLSanitizer.sanitize(input)); + assertFalse(html.contains("<"), html.substring(0, 40)); + } + } + + @Test + void ordinaryMarkupIsStillSanitized() { + assertEquals("

Hi there

alert(1)", + HTMLSanitizer.sanitize("

Hi there

")); + } +} From c6d2160af0d2f26208d3f5da265eeb301e69c736 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Wed, 18 Nov 2026 21:20:22 -0700 Subject: [PATCH 2/2] Apply the sanitizer time limit while closing open tags The loops that close tags left open build their output by string concatenation and did not check the deadline. Markup with tens of thousands of unclosed tags could get through the main loop just inside the one-second limit and then spend several more seconds closing them. Both loops now check the deadline, so that input is escaped like any other that runs out of time. The time limit test's failure message no longer throws when the output is shorter than 40 characters. --- .../roller/weblogger/util/HTMLSanitizer.java | 2 ++ .../util/HTMLSanitizerTimeLimitTest.java | 34 ++++++++++++++++++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/util/HTMLSanitizer.java b/app/src/main/java/org/apache/roller/weblogger/util/HTMLSanitizer.java index d2f87e77d5..288aa98b8f 100644 --- a/app/src/main/java/org/apache/roller/weblogger/util/HTMLSanitizer.java +++ b/app/src/main/java/org/apache/roller/weblogger/util/HTMLSanitizer.java @@ -351,6 +351,7 @@ private static SanitizeResult sanitizer(String html, Pattern allowedTags, Patter // if found on top ok for (int i = 1; i <= pos; i++) { //pop all elements before tag and close it + checkTime(deadline); String poppedTag = openTags.pop(); cleanToken = cleanToken + ""; isAcceptedToken = true; @@ -378,6 +379,7 @@ private static SanitizeResult sanitizer(String html, Pattern allowedTags, Patter // must close remaining tags while (!openTags.isEmpty()) { //pop all elements before tag and close it + checkTime(deadline); String poppedTag = openTags.pop(); ret.html = ret.html + ""; ret.val = ret.val + ""; diff --git a/app/src/test/java/org/apache/roller/weblogger/util/HTMLSanitizerTimeLimitTest.java b/app/src/test/java/org/apache/roller/weblogger/util/HTMLSanitizerTimeLimitTest.java index 9316be7b8b..a468c71eb8 100644 --- a/app/src/test/java/org/apache/roller/weblogger/util/HTMLSanitizerTimeLimitTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/util/HTMLSanitizerTimeLimitTest.java @@ -40,10 +40,42 @@ void slowMarkupIsStoppedAndEscaped() { for (String input : inputs) { String html = assertTimeoutPreemptively(Duration.ofSeconds(8), () -> HTMLSanitizer.sanitize(input)); - assertFalse(html.contains("<"), html.substring(0, 40)); + assertFalse(html.contains("<"), start(html)); } } + @Test + void closingTagsLeftOpenIsStopped() { + assertStoppedAtTheLimit(""); + } + + @Test + void closingTagsInsideAClosedTagIsStopped() { + assertStoppedAtTheLimit(""); + } + + /** + * Sanitizes more and more open tags, until that takes too long and they + * are escaped. Whatever the machine's speed, one of the sizes leaves the + * tags to be closed when the time is nearly up, and closing them must not + * run past the limit. + */ + private static void assertStoppedAtTheLimit(String end) { + // the margin covers a pause on a busy build machine; closing the + // tags without the limit ran over by more than this + Duration allowed = Duration.ofMillis(HTMLSanitizer.TIME_LIMIT_MILLIS + 1000); + String html = "<"; + for (int n = 20_000; html.contains("<"); n += n / 10) { + String input = "" + "".repeat(n) + end; + html = assertTimeoutPreemptively(allowed, () -> HTMLSanitizer.sanitize(input), + n + " open tags"); + } + } + + private static String start(String html) { + return html.substring(0, Math.min(40, html.length())); + } + @Test void ordinaryMarkupIsStillSanitized() { assertEquals("

Hi there

alert(1)",