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 56a8db5e7..288aa98b8 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); @@ -328,6 +351,7 @@ public static SanitizeResult sanitizer(String html, Pattern allowedTags, Pattern // 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; @@ -355,6 +379,7 @@ public static SanitizeResult sanitizer(String html, Pattern allowedTags, Pattern // 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 + ""; @@ -456,6 +481,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 000000000..a468c71eb --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/util/HTMLSanitizerTimeLimitTest.java @@ -0,0 +1,84 @@ +/* + * 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("<"), 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)", + HTMLSanitizer.sanitize("

Hi there

")); + } +}