Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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)$");
Expand Down Expand Up @@ -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<String> openTags = new Stack<>();

Expand All @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -233,21 +256,21 @@ public static SanitizeResult sanitizer(String html, Pattern allowedTags, Pattern
} else if ("style".equals(attr)) {
// <tag style="......">
// then test properties
Matcher styles = stylePattern.matcher(val);
Matcher styles = stylePattern.matcher(new DeadlineText(val, deadline));
String cleanStyle = "";

while (styles.find()) {
String styleName = styles.group(1).toLowerCase();
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);
Expand Down Expand Up @@ -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 + "</" + poppedTag + ">";
isAcceptedToken = true;
Expand Down Expand Up @@ -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 + "</" + poppedTag + ">";
ret.val = ret.val + "</" + poppedTag + ">";
Expand Down Expand Up @@ -456,6 +481,60 @@ static class SanitizeResult {
public List<String> 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));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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
"<p style=\"" + "a:b ".repeat(20_000) + "\">x</p>",
"<p style=\"background:url(" + "'".repeat(50_000) + "\">x</p>",
"<b" + " ".repeat(50_000) + "x",
"<b>x</b>".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("</i>");
}

/**
* 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 = "<i>" + "<b>".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("<p>Hi <b>there</b></p>alert(1)",
HTMLSanitizer.sanitize("<p>Hi <b>there</b></p><script>alert(1)</script>"));
}
}
Loading