diff --git a/CHANGES.md b/CHANGES.md index 384886855..d213cc5b9 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -320,6 +320,22 @@ domains as before but look at most 63 characters between their parts; a copy of the old file in the uploads directory is still used if present. +- **A weblog's banned words are plain words, not regular expressions.** With + `weblogAdminsUntrusted=true` (the default), each line of a weblog's banned + words on Weblog Settings matches as literal text, in any case, as a whole + word, including lines that begin with `(`. A word in Chinese, Japanese, + Thai or another script written without spaces matches anywhere in the + text. A line that is only letters, digits and spaces in parentheses, such + as `(casino)`, matches that text anywhere, in any case, so such rules from + earlier versions keep working. Other rules written as regular expressions, + such as `(casino|poker)` or `viagra|cialis`, no longer match what they used + to; Weblog Settings lists them so the weblog admin can rewrite them as + words. The built-in list, the site-wide list in Server Admin, and weblog + rules on sites with `weblogAdminsUntrusted=false` are still regular + expressions. A regular expression rule that takes over a second on one + value, or runs out of stack, is logged; a comment is then treated as spam, + and a referrer is let through. + ### Build and packaging - The Docker image starts Tomcat with `-XX:-UseBASE64Intrinsics`, which diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/WeblogConfig.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/WeblogConfig.java index 22ff667ff..19d0083af 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/WeblogConfig.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/WeblogConfig.java @@ -110,6 +110,7 @@ public String execute() { // load bean with data from weblog getBean().copyFrom(getActionWeblog()); + listRulesMatchedAsText(); return INPUT; } @@ -207,14 +208,38 @@ private void myValidate() { List stringRules = new ArrayList<>(); try { // just for testing/counting, this does not persist rules in any way - Bannedwordslist.populateSpamRules(getBean().getBannedwordslist(), stringRules, regexRules, null); - addMessage("websiteSettings.acceptedBannedwordslist", List.of(""+stringRules.size(), ""+regexRules.size())); + if (!weblogAdminsUntrusted) { + Bannedwordslist.validateRules(getBean().getBannedwordslist()); + } + Bannedwordslist.populateSpamRules(getBean().getBannedwordslist(), stringRules, regexRules, null, + weblogAdminsUntrusted); + if (weblogAdminsUntrusted) { + addMessage("websiteSettings.acceptedBannedwordsAsWords", List.of(""+regexRules.size())); + listRulesMatchedAsText(); + } else { + addMessage("websiteSettings.acceptedBannedwordslist", List.of(""+stringRules.size(), ""+regexRules.size())); + } } catch (Exception e) { addError("websiteSettings.error.processingBannedwordslist", e.getMessage()); } } + /** + * Tells the weblog admin which banned words look like regular + * expressions, since with untrusted weblog admins they are matched as + * plain text; a list from an earlier version may have such lines. + */ + private void listRulesMatchedAsText() { + if (weblogAdminsUntrusted) { + List rules = Bannedwordslist.regexStyleRules(getBean().getBannedwordslist()); + if (!rules.isEmpty()) { + addMessage("websiteSettings.bannedwordsMatchedAsText", String.join(", ", rules)); + } + } + } + + @StrutsParameter(depth = 1) public WeblogConfigBean getBean() { return bean; diff --git a/app/src/main/java/org/apache/roller/weblogger/util/Bannedwordslist.java b/app/src/main/java/org/apache/roller/weblogger/util/Bannedwordslist.java index 37cb56658..4265e0511 100644 --- a/app/src/main/java/org/apache/roller/weblogger/util/Bannedwordslist.java +++ b/app/src/main/java/org/apache/roller/weblogger/util/Bannedwordslist.java @@ -35,7 +35,9 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; +import java.util.EnumSet; import java.util.List; +import java.util.Set; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -326,19 +328,23 @@ public boolean isBannedwordslisted( stringRules.addAll(moreStringRules); stringRules.addAll(bannedwordslistStr); } - if (testStringRules(str, stringRules)) { - return true; - } + try { + if (testStringRules(str, stringRules)) { + return true; + } - // test regex bannedwordslisted - List regexRules = bannedwordslistRegex; - if (moreRegexRules != null && !moreRegexRules.isEmpty()) { - regexRules = new ArrayList<>(); - regexRules.addAll(moreRegexRules); - regexRules.addAll(bannedwordslistRegex); + // test regex bannedwordslisted + List regexRules = bannedwordslistRegex; + if (moreRegexRules != null && !moreRegexRules.isEmpty()) { + regexRules = new ArrayList<>(); + regexRules.addAll(moreRegexRules); + regexRules.addAll(bannedwordslistRegex); + } + return testRegExRules(str, regexRules); + } catch (RuleNotCheckedException e) { + return true; } - return testRegExRules(str, regexRules); - } + } /** * Test string only against rules provided by caller, NOT against built-in bannedwordslist. @@ -348,24 +354,42 @@ public boolean isBannedwordslisted( */ public static boolean matchesRulesOnly( String str, List stringRules, List regexRules) { - return testStringRules(str, stringRules) || testRegExRules(str, regexRules); + return matchesRulesOnly(str, stringRules, regexRules, true); + } + + /** + * Test string only against rules provided by caller, NOT against built-in bannedwordslist. + * @param str String to be checked against rules + * @param stringRules String rules to consider + * @param regexRules Regex rules to consider + * @param uncheckedMatches what to return when a rule can't be checked in + * time: true for a comment, which the weblog owner + * can review, false for a referrer, which would + * refuse the reader the page + */ + public static boolean matchesRulesOnly(String str, List stringRules, + List regexRules, boolean uncheckedMatches) { + if (str == null) { + return false; + } + try { + return testStringRules(str, stringRules) || testRegExRules(str, regexRules); + } catch (RuleNotCheckedException e) { + return uncheckedMatches; + } } /** Test String against the RegularExpression rules. */ private static boolean testRegExRules(String str, List regexRules) { for (Pattern testPattern : regexRules) { - // want to see what it is matching on, but only in debug mode - if (mLogger.isDebugEnabled()) { - Matcher matcher = testPattern.matcher(str); - if (matcher.find()) { + Matcher matcher = testPattern.matcher(new DeadlineText(str)); + if (find(matcher, testPattern.pattern())) { + // want to see what it is matching on, but only in debug mode + if (mLogger.isDebugEnabled()) { mLogger.debug(matcher.group() + " matched by " + testPattern.pattern()); - return true; - } - } else { - if (testPattern.matcher(str).find()) { - return true; } + return true; } } return false; @@ -399,9 +423,9 @@ private static boolean testStringRules(String source, List rules) { Pattern.CASE_INSENSITIVE); Matcher matcher; - matcher = pattern.matcher(source); + matcher = pattern.matcher(new DeadlineText(source)); - matches = matcher.find(); + matches = find(matcher, rule); if (matches) { break; } @@ -426,23 +450,250 @@ private static boolean testStringRules(String source, List rules) { /** Utility method to populate lists based a bannedwordslist in string form */ public static void populateSpamRules( String bannedwordslist, List stringRules, List regexRules, String addendum) { - String weblogWords = bannedwordslist; - weblogWords = (weblogWords == null) ? "" : weblogWords; - String siteWords = (addendum != null) ? addendum : ""; - StringTokenizer toker = new StringTokenizer(siteWords + "\n" + weblogWords, "\n"); + populateSpamRules(bannedwordslist, stringRules, regexRules, addendum, false); + } + + /** + * Populates the rule lists from a weblog's banned words and the site-wide + * addendum. With weblogRulesAsWords, the weblog's own lines are matched as + * plain words (case-insensitive, at word boundaries) rather than as + * regular expressions, so an untrusted weblog admin can't write a rule + * that backtracks; the addendum's rules are still regular expressions. + * A weblog line such as (casino), written for earlier versions, that is + * only letters, digits and spaces in parentheses is matched as that text + * anywhere, case-insensitive, without word edges. + * A regex rule that doesn't compile is logged and matched as a plain + * word; use validateRules() to refuse it when the list is saved. + */ + public static void populateSpamRules(String bannedwordslist, List stringRules, + List regexRules, String addendum, boolean weblogRulesAsWords) { + if (weblogRulesAsWords) { + readRules(addendum, stringRules, regexRules, false); + for (String rule : ruleLines(bannedwordslist)) { + String text = textInParentheses(rule); + regexRules.add(text != null ? textPattern(text) : wordPattern(rule)); + } + } else { + String weblogWords = (bannedwordslist == null) ? "" : bannedwordslist; + String siteWords = (addendum != null) ? addendum : ""; + readRules(siteWords + "\n" + weblogWords, stringRules, regexRules, false); + } + } + + /** + * Checks that each regex rule in a banned words list compiles. + * @throws PatternSyntaxException for the first one that doesn't + */ + public static void validateRules(String bannedwordslist) { + readRules(bannedwordslist, new ArrayList<>(), new ArrayList<>(), true); + } + + /** + * The lines of a weblog's banned words that only mean something as a + * regular expression, so that a weblog admin can be told they are + * matched as plain words. A line that is text in parentheses isn't + * listed, since it still matches that text. + */ + public static List regexStyleRules(String bannedwordslist) { + List rules = new ArrayList<>(); + for (String rule : ruleLines(bannedwordslist)) { + if (textInParentheses(rule) == null + && (rule.startsWith("(") || StringUtils.containsAny(rule, "|\\[*+?{^$"))) { + rules.add(rule); + } + } + return rules; + } + + /** The lines of a list that are rules, without comments or blank lines. */ + private static List ruleLines(String rules) { + List lines = new ArrayList<>(); + StringTokenizer toker = new StringTokenizer(rules == null ? "" : rules, "\n"); while (toker.hasMoreTokens()) { - String token = toker.nextToken().trim(); - if (token.startsWith("#")) { - continue; + String token = stripSpaces(toker.nextToken()); + if (!token.isEmpty() && !token.startsWith("#")) { + lines.add(token); } + } + return lines; + } + + /** + * Removes white space from both ends, including spaces such as U+00A0 + * and U+3000 that trim() keeps and that look blank in a text box. + */ + private static String stripSpaces(String str) { + int start = 0; + int end = str.length(); + while (start < end && isSpace(str.charAt(start))) { + start++; + } + while (end > start && isSpace(str.charAt(end - 1))) { + end--; + } + return str.substring(start, end); + } + + private static boolean isSpace(char c) { + return Character.isWhitespace(c) || Character.isSpaceChar(c); + } + + private static void readRules(String rules, List stringRules, List regexRules, + boolean strict) { + for (String token : ruleLines(rules)) { if (token.startsWith("(")) { - regexRules.add(Pattern.compile(token)); + try { + regexRules.add(Pattern.compile(token)); + } catch (PatternSyntaxException e) { + if (strict) { + throw e; + } + mLogger.warn("Banned words rule is not a valid regex and is matched as plain text: " + + token); + regexRules.add(wordPattern(token)); + } } else { stringRules.add(token); } - } + } } - + + /** Letters, combining marks, digits and spaces in parentheses. */ + private static final Pattern TEXT_IN_PARENTHESES = + Pattern.compile("\\(([\\p{L}\\p{M}\\p{N} ]+)\\)"); + + /** + * The text inside a line such as (casino), which earlier versions + * matched as a regular expression, or null if the line isn't only + * letters, combining marks, digits and spaces in parentheses. + */ + private static String textInParentheses(String rule) { + Matcher matcher = TEXT_IN_PARENTHESES.matcher(rule); + return matcher.matches() && !matcher.group(1).isBlank() ? matcher.group(1) : null; + } + + /** The literal text anywhere, case-insensitive in any script. */ + private static Pattern textPattern(String text) { + return Pattern.compile(Pattern.quote(text), Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); + } + + /** A letter, combining mark, digit or underscore, in any script. */ + private static final String WORD_CHAR = "[\\p{L}\\p{M}\\p{N}_]"; + private static final Pattern WORD_CHAR_PATTERN = Pattern.compile(WORD_CHAR); + + /** + * The literal text, case-insensitive in any script, with a word edge + * check on each end that is a word character; a check next to "(" or + * "/" would need a word character beside it and so would rarely match. + * There is no check next to a letter of a script written without + * spaces, since such a word is rarely at a word edge. + */ + private static Pattern wordPattern(String word) { + StringBuilder regex = new StringBuilder(); + if (needsEdgeCheck(word.codePointAt(0))) { + regex.append("(? SCRIPTS_WITHOUT_SPACES = EnumSet.of( + Character.UnicodeScript.HAN, Character.UnicodeScript.HIRAGANA, + Character.UnicodeScript.KATAKANA, Character.UnicodeScript.THAI, + Character.UnicodeScript.LAO, Character.UnicodeScript.KHMER, + Character.UnicodeScript.MYANMAR); + + /** + * Longest one rule may take to check one value, such as a comment's + * text. A regex rule that backtracks without end would otherwise hold + * the request. The clock is checked as the match reads the text, so a + * regex that repeats without reading it, such as nested counted repeats + * of an empty group, isn't stopped; such rules come only from the + * site-wide list or from trusted weblog admins. + */ + static final long MATCH_TIME_LIMIT_MILLIS = 1000; + + private static boolean find(Matcher matcher, String rule) { + try { + return matcher.find(); + } catch (MatchTimeLimitException e) { + mLogger.warn("Banned words rule took over " + MATCH_TIME_LIMIT_MILLIS + + " ms and the value could not be checked; consider simplifying it: " + rule); + throw new RuleNotCheckedException(); + } catch (StackOverflowError e) { + // a regex such as (a|b)+c recurses once per repetition + mLogger.warn("Banned words rule ran out of stack and the value could not be checked;" + + " consider simplifying it: " + rule); + throw new RuleNotCheckedException(); + } + } + + private static final class MatchTimeLimitException extends RuntimeException { + MatchTimeLimitException() { + super(null, null, false, false); + } + } + + /** A rule could not be checked against the value, which then counts as a match for a comment. */ + private static final class RuleNotCheckedException extends RuntimeException { + RuleNotCheckedException() { + super(null, null, false, false); + } + } + + /** The checked text, 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) { + this(text, System.nanoTime() + MATCH_TIME_LIMIT_MILLIS * 1_000_000L); + } + + private 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 && System.nanoTime() - deadline > 0) { + throw new MatchTimeLimitException(); + } + 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(); + } + } + /** Return pretty list of String and RegEx rules. */ @Override public String toString() { diff --git a/app/src/main/java/org/apache/roller/weblogger/util/BannedwordslistChecker.java b/app/src/main/java/org/apache/roller/weblogger/util/BannedwordslistChecker.java index 0961e2987..af4d0b516 100644 --- a/app/src/main/java/org/apache/roller/weblogger/util/BannedwordslistChecker.java +++ b/app/src/main/java/org/apache/roller/weblogger/util/BannedwordslistChecker.java @@ -58,13 +58,11 @@ public static boolean checkReferrer(Weblog website, String referrerURL) { if (WebloggerConfig.getBooleanProperty("site.bannedwordslist.enable.referrers")) { List stringRules = new ArrayList<>(); List regexRules = new ArrayList<>(); - Bannedwordslist.populateSpamRules( - website.getBannedwordslist(), stringRules, regexRules, null); - if (WebloggerRuntimeConfig.getProperty("spam.bannedwordslist") != null) { - Bannedwordslist.populateSpamRules( - WebloggerRuntimeConfig.getProperty("spam.bannedwordslist"), stringRules, regexRules, null); - } - return Bannedwordslist.matchesRulesOnly(referrerURL, stringRules, regexRules); + Bannedwordslist.populateSpamRules(website.getBannedwordslist(), stringRules, regexRules, + WebloggerRuntimeConfig.getProperty("spam.bannedwordslist"), weblogRulesAsWords()); + // a referrer that can't be checked in time is let through, so a + // slow rule doesn't refuse the reader the page + return Bannedwordslist.matchesRulesOnly(referrerURL, stringRules, regexRules, false); } return false; } @@ -80,7 +78,7 @@ private static boolean testComment(WeblogEntryComment c) { Weblog website = c.getWeblogEntry().getWebsite(); Bannedwordslist.populateSpamRules( website.getBannedwordslist(), stringRules, regexRules, - WebloggerRuntimeConfig.getProperty("spam.bannedwordslist")); + WebloggerRuntimeConfig.getProperty("spam.bannedwordslist"), weblogRulesAsWords()); Bannedwordslist bannedwordslist = Bannedwordslist.getBannedwordslist(); if ( bannedwordslist.isBannedwordslisted(c.getUrl(), stringRules, regexRules) || bannedwordslist.isBannedwordslisted(c.getEmail(), stringRules, regexRules) @@ -89,5 +87,10 @@ private static boolean testComment(WeblogEntryComment c) { ret = true; } return ret; - } + } + + /** Untrusted weblog admins' banned words are matched as words, not regexes. */ + private static boolean weblogRulesAsWords() { + return WebloggerConfig.getBooleanProperty("weblogAdminsUntrusted"); + } } diff --git a/app/src/main/resources/ApplicationResources.properties b/app/src/main/resources/ApplicationResources.properties index deb045f0c..47c7809f7 100644 --- a/app/src/main/resources/ApplicationResources.properties +++ b/app/src/main/resources/ApplicationResources.properties @@ -1785,7 +1785,11 @@ websiteSettings.spamPrevention=Spam Prevention websiteSettings.ignoreUrls=List of words and regex expressions listed one per \ line to be added to the banned words list used to check comments and referrers. websiteSettings.bannedWordsList=Words banned in comments (regex allowed) +websiteSettings.bannedWordsListAsWords=Words banned in comments (one word or phrase per line) websiteSettings.acceptedBannedwordslist=Accepted {0} string and {1} regex banned-words list rules +websiteSettings.acceptedBannedwordsAsWords=Accepted {0} banned-words list rules +websiteSettings.bannedwordsMatchedAsText=These banned words look like regular expressions but are \ +matched as plain text: {0} websiteSettings.error.processingBannedwordslist=Error processing banned-words list: {0} # --- web analytics diff --git a/app/src/main/webapp/WEB-INF/jsps/editor/WeblogConfig.jsp b/app/src/main/webapp/WEB-INF/jsps/editor/WeblogConfig.jsp index 2bb920c14..ee73818e8 100644 --- a/app/src/main/webapp/WEB-INF/jsps/editor/WeblogConfig.jsp +++ b/app/src/main/webapp/WEB-INF/jsps/editor/WeblogConfig.jsp @@ -130,8 +130,14 @@

- + + + + + + <%-- ***** Web analytics settings ***** --%> diff --git a/app/src/test/java/org/apache/roller/weblogger/util/BannedwordslistTest.java b/app/src/test/java/org/apache/roller/weblogger/util/BannedwordslistTest.java index 5406b6b79..cc6f07794 100644 --- a/app/src/test/java/org/apache/roller/weblogger/util/BannedwordslistTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/util/BannedwordslistTest.java @@ -27,8 +27,14 @@ import java.io.File; import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -107,4 +113,173 @@ public void testLongTextIsCheckedQuickly() { }); } + // a weblog's rule that backtracks without end can't hold up the check; + // the text counts as a match, so a comment with it is caught as spam + @Test + public void testRuleThatBacktracksIsStopped() { + String text = "x".repeat(40) + "!"; + // a regex rule, and a word rule, which is also used as a regex + for (String rule : new String[] {"((x+)+)+y", "x((x+)+)+y"}) { + List stringRules = new ArrayList<>(); + List regexRules = new ArrayList<>(); + Bannedwordslist.populateSpamRules(rule, stringRules, regexRules, null); + assertTimeoutPreemptively(Duration.ofSeconds(8), () -> { + assertTrue(Bannedwordslist.matchesRulesOnly(text, stringRules, regexRules), rule); + assertTrue(bannedwordslist.isBannedwordslisted(text, stringRules, regexRules), rule); + }, rule); + } + // the limit applies to each value, not to every check that follows + assertFalse(bannedwordslist.isBannedwordslisted("an ordinary comment")); + } + + // with weblogAdminsUntrusted, a weblog's own rules are matched as words, + // not as regular expressions; the site-wide rules are still regexes + @Test + public void testWeblogRulesAsWords() { + List stringRules = new ArrayList<>(); + List regexRules = new ArrayList<>(); + Bannedwordslist.populateSpamRules("(a|b)\nViagra\n(foo)\nexample.com/", stringRules, regexRules, + "(qq|zz)", true); + assertFalse(Bannedwordslist.matchesRulesOnly("a", stringRules, regexRules)); + assertTrue(Bannedwordslist.matchesRulesOnly("spam (a|b) here", stringRules, regexRules)); + assertTrue(Bannedwordslist.matchesRulesOnly("buy VIAGRA now", stringRules, regexRules)); + assertFalse(Bannedwordslist.matchesRulesOnly("viagraphone", stringRules, regexRules)); + assertTrue(Bannedwordslist.matchesRulesOnly("see (foo) now", stringRules, regexRules)); + assertTrue(Bannedwordslist.matchesRulesOnly("http://example.com/x", stringRules, regexRules)); + assertFalse(Bannedwordslist.matchesRulesOnly("http://example.org/x", stringRules, regexRules)); + // the site-wide rule is still a regex + assertTrue(Bannedwordslist.matchesRulesOnly("zz", stringRules, regexRules)); + + // with the setting off, the weblog's rules are regexes as before + stringRules.clear(); + regexRules.clear(); + Bannedwordslist.populateSpamRules("(a|b)", stringRules, regexRules, null, false); + assertTrue(Bannedwordslist.matchesRulesOnly("a", stringRules, regexRules)); + } + + @Test + public void testWeblogRulesAsUnicodeWords() { + List stringRules = new ArrayList<>(); + List regexRules = new ArrayList<>(); + // "café" is cafe with an acute accent, "élan" is elan + Bannedwordslist.populateSpamRules("café\nélan", stringRules, regexRules, null, true); + assertTrue(Bannedwordslist.matchesRulesOnly("at the café now", stringRules, regexRules)); + assertTrue(Bannedwordslist.matchesRulesOnly("AT THE CAFÉ NOW", stringRules, regexRules)); + assertFalse(Bannedwordslist.matchesRulesOnly("too much caféine", stringRules, regexRules)); + assertTrue(Bannedwordslist.matchesRulesOnly("with ÉLAN", stringRules, regexRules)); + assertFalse(Bannedwordslist.matchesRulesOnly("réélan", stringRules, regexRules)); + } + + // scripts written without spaces between words have no word edges to check + @Test + public void testWeblogRulesInScriptsWithoutSpaces() { + List stringRules = new ArrayList<>(); + List regexRules = new ArrayList<>(); + // "赌场" is casino in Chinese, "カジノ" in Japanese, "คาสิโน" in Thai + Bannedwordslist.populateSpamRules("赌场\nカジノ\nคาสิโน\ncasino", stringRules, regexRules, null, true); + assertTrue(Bannedwordslist.matchesRulesOnly("在线赌场网站", stringRules, regexRules)); + assertTrue(Bannedwordslist.matchesRulesOnly("オンラインカジノです", stringRules, regexRules)); + assertTrue(Bannedwordslist.matchesRulesOnly("เล่นคาสิโนออนไลน์", stringRules, regexRules)); + assertTrue(Bannedwordslist.matchesRulesOnly("赌场casino", stringRules, regexRules)); + assertFalse(Bannedwordslist.matchesRulesOnly("casinos", stringRules, regexRules)); + } + + // a line that looks blank, such as one non-breaking space, is not a rule + @Test + public void testBlankLinesAreNotRules() { + List stringRules = new ArrayList<>(); + List regexRules = new ArrayList<>(); + Bannedwordslist.populateSpamRules("foo\n\u00A0\n\u3000\nbar", stringRules, regexRules, null, true); + assertEquals(2, regexRules.size()); + assertFalse(Bannedwordslist.matchesRulesOnly("price:\u00A010 EUR", stringRules, regexRules)); + + // a browser ends lines with \r\n, so an empty line leaves "\r" + stringRules.clear(); + regexRules.clear(); + Bannedwordslist.populateSpamRules("foo\r\n\r\nbar", stringRules, regexRules, null, false); + assertEquals(List.of("foo", "bar"), stringRules); + assertFalse(Bannedwordslist.matchesRulesOnly("a perfectly ordinary comment", stringRules, regexRules)); + } + + // a line saved as a plain word while weblog admins were untrusted isn't + // always a valid regex once they are trusted; it is then matched as text + @Test + public void testInvalidRegexRuleIsMatchedAsText() { + List stringRules = new ArrayList<>(); + List regexRules = new ArrayList<>(); + Bannedwordslist.populateSpamRules("(18+", stringRules, regexRules, null, false); + assertTrue(Bannedwordslist.matchesRulesOnly("only (18+ here", stringRules, regexRules)); + assertFalse(Bannedwordslist.matchesRulesOnly("only 18 here", stringRules, regexRules)); + // saving the list as regexes still refuses it + assertThrows(PatternSyntaxException.class, () -> Bannedwordslist.validateRules("(18+")); + Bannedwordslist.validateRules("(casino)\nviagra"); + } + + // lines that only mean something as a regex are listed for the weblog admin + @Test + public void testRegexStyleRules() { + assertEquals(List.of("(casino|poker)", "viagra|cialis", "poker-?online", "(18+"), + Bannedwordslist.regexStyleRules("casino\n(casino)\n(casino|poker)\nviagra|cialis\n" + + "# (comment)\nexample.com\npoker-?online\n(online poker)\n(18+\n")); + assertEquals(List.of(), Bannedwordslist.regexStyleRules(null)); + } + + // a weblog line that is only letters, digits and spaces in parentheses, + // as written for earlier versions, matches that text anywhere, in any case + @Test + public void testWeblogRuleInParenthesesMatchesTextAnywhere() { + List stringRules = new ArrayList<>(); + List regexRules = new ArrayList<>(); + Bannedwordslist.populateSpamRules("(casino)\n(Online Poker 24)\n(casino|poker)\n( )", + stringRules, regexRules, null, true); + assertTrue(Bannedwordslist.matchesRulesOnly("http://onlinecasino.example", stringRules, regexRules)); + assertTrue(Bannedwordslist.matchesRulesOnly("BEST CASINOS", stringRules, regexRules)); + assertTrue(Bannedwordslist.matchesRulesOnly("play online poker 24/7", stringRules, regexRules)); + // a line with other regex syntax is still literal text + assertFalse(Bannedwordslist.matchesRulesOnly("poker night", stringRules, regexRules)); + assertTrue(Bannedwordslist.matchesRulesOnly("see (casino|poker)", stringRules, regexRules)); + // parentheses around spaces only are not unwrapped + assertFalse(Bannedwordslist.matchesRulesOnly("an ordinary comment", stringRules, regexRules)); + } + + // each rule has its own time limit, so a long list of plain words + // against a long comment is slow but isn't counted as a match + @Test + public void testTimeLimitIsPerRule() { + StringBuilder rules = new StringBuilder(); + for (int i = 0; i < 20000; i++) { + rules.append("spamword").append(i).append('\n'); + } + List stringRules = new ArrayList<>(); + List regexRules = new ArrayList<>(); + Bannedwordslist.populateSpamRules(rules.toString(), stringRules, regexRules, null, true); + String text = "an ordinary comment ".repeat(500); + assertTimeoutPreemptively(Duration.ofSeconds(60), () -> + assertFalse(Bannedwordslist.matchesRulesOnly(text, stringRules, regexRules))); + } + + // a referrer that can't be checked in time is let through, since the + // reader would otherwise be refused the page + @Test + public void testReferrerThatCantBeCheckedIsNoMatch() { + String text = "x".repeat(40) + "!"; + List stringRules = new ArrayList<>(); + List regexRules = new ArrayList<>(); + Bannedwordslist.populateSpamRules("((x+)+)+y", stringRules, regexRules, null); + assertTimeoutPreemptively(Duration.ofSeconds(8), () -> + assertFalse(Bannedwordslist.matchesRulesOnly(text, stringRules, regexRules, false))); + } + + // a rule that recurses once per repetition can run out of stack on long + // text; the text is then handled as if the time limit had passed + @Test + public void testRuleThatRunsOutOfStack() { + String text = "ab".repeat(50000); + List stringRules = new ArrayList<>(); + List regexRules = new ArrayList<>(); + Bannedwordslist.populateSpamRules("(a|b)+c", stringRules, regexRules, null); + assertTrue(bannedwordslist.isBannedwordslisted(text, stringRules, regexRules)); + assertFalse(Bannedwordslist.matchesRulesOnly(text, stringRules, regexRules, false)); + } + } diff --git a/docs/roller-user-guide.adoc b/docs/roller-user-guide.adoc index 88b392927..f6850d7c4 100644 --- a/docs/roller-user-guide.adoc +++ b/docs/roller-user-guide.adoc @@ -815,12 +815,21 @@ here’s how you do it: ** Go to the Weblog Settings page and scroll down to the bannedwordslist fields -** Enter your spam words, one per line -** Lines that begin with a left parenthesis will be treated as regular -expressions (see the Java API documentation for -_javax.util.regex.Pattern_ for a guide to regular expressions). Don’t -try to use a regular expression unless you really know what you’re -doing. +** Enter your spam words or phrases, one per line. Each one matches +regardless of case, as a whole word: _casino_ matches "Casino" but not +"casinos". A word in Chinese, Japanese, Thai or another script written +without spaces matches anywhere in the text. +** By default (_weblogAdminsUntrusted=true_), every line is matched as +plain text, including lines that begin with a left parenthesis, and Weblog +Settings lists the lines that look like regular expressions. A line that is +only letters, digits and spaces in parentheses, such as _(casino)_, matches +that text anywhere, regardless of case: _(casino)_ matches "casinos" and +"onlinecasino". On a site +where weblog administrators are trusted (_weblogAdminsUntrusted=false_), +lines that begin with a left parenthesis are regular expressions, and other +lines are matched as regular expressions at word boundaries (see the Java +API documentation for _java.util.regex.Pattern_). Don’t try to use a +regular expression unless you really know what you’re doing. == Choosing your weblog theme diff --git a/docs/security-model.md b/docs/security-model.md index accbb118b..62d1edbb8 100644 --- a/docs/security-model.md +++ b/docs/security-model.md @@ -283,7 +283,7 @@ A bug in an optional feature is a vulnerability when the feature is enabled. | Setting | What it changes | | --- | --- | -| `weblogAdminsUntrusted` | `true` (default) sanitizes HTML from weblog members. Set `false` only when every weblog admin is trusted, such as on a solo blog. | +| `weblogAdminsUntrusted` | `true` (default) sanitizes HTML from weblog members and matches a weblog's banned words as plain words rather than regular expressions. Set `false` only when every weblog admin is trusted, such as on a solo blog. | | `themes.customtheme.allowed` | Lets weblog Admins edit templates. Templates stay in the sandbox, but can use a lot of CPU and memory (see Not vulnerabilities). | | `uploads.enabled` | Lets members upload media files. | | `webservices.enableXmlRpc`, `webservices.enableAtomPub` | Turn on the remote publishing APIs. They use the same weblog roles as the UI. |