"Applied fix from trunk for revision: 1859877"

------------------------------------------------------------------------
r1859877 | jleroux | 2019-05-24 15:47:08 +0200 (ven. 24 mai 2019) | 10 lignes

Fixed: Services allow arbitrary HTML for parameters with allow-html set to "safe"
(OFBIZ-5254)

This was reopened after discussion at 
https://markmail.org/message/jnaitmwahjcjmdn5

This is a new solution which follows the work done with OFBIZ-6669 and OFBIZ-10187
Roughly said, it uses org.owasp.html.PolicyFactory and org.owasp.html.Sanitizers

Thanks: Christoph Neuroth for report
------------------------------------------------------------------------


git-svn-id: https://svn.apache.org/repos/asf/ofbiz/ofbiz-framework/branches/release18.12@1859878 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Jacques Le Roux
2019-05-24 13:51:26 +00:00
parent d347fa1d62
commit daa2c243a9
22 changed files with 296 additions and 130 deletions
@@ -0,0 +1,53 @@
package org.apache.ofbiz.base.html;
import java.util.regex.Pattern;
import org.owasp.html.HtmlPolicyBuilder;
import org.owasp.html.PolicyFactory;
/**
* Based on the
* <a href="http://www.owasp.org/index.php/Category:OWASP_AntiSamy_Project#Stage_2_-_Choosing_a_base_policy_file">AntiSamy Slashdot example</a>.
* Slashdot (http://www.slashdot.org/) is a techie news site that allows users
* to respond anonymously to news posts with very limited HTML markup. Now
* Slashdot is not only one of the coolest sites around, it's also one that's
* been subject to many different successful attacks. Even more unfortunate is
* the fact that most of the attacks led users to the infamous goatse.cx picture
* (please don't go look it up). The rules for Slashdot are fairly strict: users
* can only submit the following HTML tags and no CSS: {@code <b>}, {@code <u>},
* {@code <i>}, {@code <a>}, {@code <blockquote>}.
*
* Accordingly, we've built a policy file that allows fairly similar
* functionality. All text-formatting tags that operate directly on the font,
* color or emphasis have been allowed.
*/
public class CustomSafePolicy implements SanitizerCustomPolicy {
/**
* A policy that can be used to produce policies that sanitize to HTML sinks via
* {@link PolicyFactory#apply}.
*/
public static final PolicyFactory POLICY_DEFINITION = new HtmlPolicyBuilder()
.allowStandardUrlProtocols()
// Allow title="..." on any element.
.allowAttributes("title").globally()
// Allow href="..." on <a> elements.
.allowAttributes("href").onElements("a")
// Defeat link spammers.
.requireRelNofollowOnLinks()
// Allow lang= with an alphabetic value on any element.
.allowAttributes("lang").matching(Pattern.compile("[a-zA-Z]{2,20}"))
.globally()
// The align attribute on <p> elements can have any value below.
.allowAttributes("align")
.matching(true, "center", "left", "right", "justify", "char")
.onElements("p")
// These elements are allowed.
.allowElements("a", "p", "div", "i", "b", "em", "blockquote", "tt", "strong","br", "ul", "ol", "li")
.toFactory();
@Override
public PolicyFactory getSanitizerPolicy() {
return POLICY_DEFINITION;
}
}
@@ -29,6 +29,7 @@ import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
@@ -116,8 +117,8 @@ public class UtilCodec {
* This method will start a configurable sanitizing process. The sanitizer can
* be turns off through "sanitizer.enable=false", the default value is true. It
* is possible to configure a custom policy using the properties
* "sanitizer.permissive.policy" and "sanitizer.custom.policy.class". The custom
* policy has to implement
* "sanitizer.permissive.policy" and "sanitizer.custom.permissive.policy.class".
* The custom policy has to implement
* {@link org.apache.ofbiz.base.html.SanitizerCustomPolicy}.
*
* @param original
@@ -143,7 +144,7 @@ public class UtilCodec {
PolicyFactory policy = null;
try {
Class<?> customPolicyClass = Class.forName(UtilProperties.getPropertyValue("owasp",
"sanitizer.custom.policy.class"));
"sanitizer.custom.permissive.policy.class"));
Object obj = customPolicyClass.newInstance();
if (SanitizerCustomPolicy.class.isAssignableFrom(customPolicyClass)) {
Method meth = customPolicyClass.getMethod("getSanitizerPolicy");
@@ -153,7 +154,7 @@ public class UtilCodec {
| InvocationTargetException | NoSuchMethodException | SecurityException
| InstantiationException e) {
// Just logging the error and falling back to default policy
Debug.logError(e, "Could not find custom sanitizer policy. Using default instead", module);
Debug.logError(e, "Could not find custom permissive sanitizer policy. Using default instead", module);
}
if (policy != null) {
@@ -355,43 +356,67 @@ public class UtilCodec {
/**
* Uses a black-list approach for necessary characters for HTML.
* <p>
* Does not allow various characters (after canonicalization), including
* "&lt;", "&gt;", "&amp;" (if not followed by a space), and "%" (if not
* followed by a space).
* "&lt;", "&gt;", "&amp;" and "%" (if not followed by a space).
*
* @param value
* @param errorMessageList
* @param valueName field name checked
* @param value value checked
* @param errorMessageList an empty list passed by and modified in case of issues
* @param locale
*/
public static String checkStringForHtmlStrictNone(String valueName, String value, List<String> errorMessageList) {
public static String checkStringForHtmlStrictNone(String valueName, String value, List<String> errorMessageList,
Locale locale) {
if (UtilValidate.isEmpty(value)) {
return value;
}
// canonicalize, strict (error on double-encoding)
try {
value = canonicalize(value, true);
} catch (IntrusionException e) {
// NOTE: using different log and user targeted error messages to allow the end-user message to be less technical
Debug.logError("Canonicalization (format consistency, character escaping that is mixed or double, etc) error for attribute named [" + valueName + "], String [" + value + "]: " + e.toString(), module);
errorMessageList.add("In field [" + valueName + "] found character escaping (mixed or double) that is not allowed or other format consistency error: " + e.toString());
Debug.logError("Canonicalization (format consistency, character escaping that is mixed or double, etc) "
+ "error for attribute named [" + valueName + "], String [" + value + "]: " + e.toString(), module);
String issueMsg = null;
if (locale.equals(new Locale("test"))) { // labels are not available in testClasses Gradle task
issueMsg = "In field [" + valueName + "] found character escaping (mixed or double) "
+ "that is not allowed or other format consistency error: ";
} else {
issueMsg = UtilProperties.getMessage("SecurityUiLabels","PolicyNoneMixedOrDouble",
UtilMisc.toMap("valueName", valueName), locale);
}
errorMessageList.add(issueMsg + e.toString());
}
// check for "<", ">"
if (value.indexOf("<") >= 0 || value.indexOf(">") >= 0) {
errorMessageList.add("In field [" + valueName + "] less-than (<) and greater-than (>) symbols are not allowed.");
String issueMsg = null;
if (locale.equals(new Locale("test"))) {
issueMsg = "In field [" + valueName + "] less-than (<) and greater-than (>) symbols are not allowed.";
} else {
issueMsg = UtilProperties.getMessage("SecurityUiLabels","PolicyNoneLess-thanGreater-than",
UtilMisc.toMap("valueName", valueName), locale);
}
errorMessageList.add(issueMsg);
}
// check for js events
final String onEvent = "on" + StringUtils.substringBetween(value, " on", "=");
final boolean seekSegmentTime = value.contains("seekSegmentTime");
if (null != onEvent || seekSegmentTime) {
if (jsEventList.stream().anyMatch(str -> StringUtils.containsIgnoreCase(str, onEvent)) || seekSegmentTime) {
errorMessageList.add("In field [" + valueName + "] js events are not allowed.");
String onEvent = "on" + StringUtils.substringBetween(value, " on", "=");
if (jsEventList.stream().anyMatch(str -> StringUtils.containsIgnoreCase(str, onEvent))
|| value.contains("seekSegmentTime")) {
String issueMsg = null;
if (locale.equals(new Locale("test"))) {
issueMsg = "In field [" + valueName + "] Javascript events are not allowed.";
} else {
issueMsg = UtilProperties.getMessage("SecurityUiLabels","PolicyNoneJsEvents",
UtilMisc.toMap("valueName", valueName), locale);
}
errorMessageList.add(issueMsg);
}
// TODO: anything else to check for that can be used to get HTML or JavaScript going without these characters?
//
// Another would be https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#US-ASCII_encoding
// But all our Tomcat connectors use UTF-8
// We don't care about Flash now rather deprecated
@@ -401,7 +426,59 @@ public class UtilCodec {
}
/**
* A simple Map wrapper class that will do HTML encoding. To be used for passing a Map to something that will expand Strings with it as a context, etc.
* This method check if the input is safe HTML.
* It is possible to configure a safe policy using the properties
* "sanitizer.safe.policy" and "sanitizer.custom.safe.policy.class".
* The safe policy has to implement
* {@link org.apache.ofbiz.base.html.SanitizerCustomPolicy}.
*
* @param valueName field name checked
* @param value value checked
* @param errorMessageList an empty list passed by and modified in case of issues
* @param locale
*/
public static String checkStringForHtmlSafe(String valueName, String value, List<String> errorMessageList,
Locale locale) {
PolicyFactory policy = null;
try {
Class<?> customPolicyClass = null;
if (locale.equals(new Locale("test"))) {
customPolicyClass = Class.forName("org.apache.ofbiz.base.html.CustomSafePolicy");
} else {
customPolicyClass = Class.forName(UtilProperties.getPropertyValue("owasp",
"sanitizer.custom.safe.policy.class"));
}
Object obj = customPolicyClass.newInstance();
if (SanitizerCustomPolicy.class.isAssignableFrom(customPolicyClass)) {
Method meth = customPolicyClass.getMethod("getSanitizerPolicy");
policy = (PolicyFactory) meth.invoke(obj);
}
} catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException | NoSuchMethodException | SecurityException
| InstantiationException e) {
Debug.logError(e, "Could not find custom safe sanitizer policy. Using default instead."
+ "Beware: the result is not rightly checked!", module);
}
String filtered = policy.sanitize(value);
if (!value.equals(filtered)) {
String issueMsg = null;
if (locale.equals(new Locale("test"))) {
issueMsg = "In field [" + valueName + "] by our input policy, your input has not been accepted "
+ "for security reason. Please check and modify accordingly, thanks.";
} else {
issueMsg = UtilProperties.getMessage("SecurityUiLabels","PolicySafe",
UtilMisc.toMap("valueName", valueName), locale);
}
errorMessageList.add(issueMsg);
}
return value;
}
/**
* A simple Map wrapper class that will do HTML encoding.
* To be used for passing a Map to something that will expand Strings with it as a context, etc.
*/
public static class HtmlEncodingMapWrapper<K> implements Map<K, Object> {
public static <K> HtmlEncodingMapWrapper<K> getHtmlEncodingMapWrapper(Map<K, Object> mapToWrap, SimpleEncoder encoder) {