我们正在为我们的网站添加富文本编辑功能,包括添加YouTube视频的功能。但另一方面,我们希望仍然安全并防止XSS / HTML注入。以前我们使用以下代码来转义数据:
ESAPI.encoder().encodeForHTML
ESAPI.encoder().encodeForJavaScript
现在我们必须添加某种允许标签的白名单。有没有办法实现这个功能?
答案 0 :(得分:3)
我们决定在ESAPI上使用Jsoup。现在代码看起来像这样:
protected String encodeHtml(String html) {
return Jsoup.clean(html, getWhitelist());
}
private Whitelist getWhitelist() {
return new Whitelist()
.addTags("a", "b", "blockquote", "br", "caption", "cite", "code", "col", "colgroup", "dd", "div", "dl",
"dt", "em", "h1", "h2", "h3", "h4", "h5", "h6", "i", "img", "li", "ol", "p", "pre", "q",
"small", "strike", "strong", "sub", "sup", "table", "tbody", "td", "tfoot", "th", "thead",
"tr", "u", "ul", "iframe")
.addAttributes("a", "href", "title").addAttributes("blockquote", "cite")
.addAttributes("col", "span", "width").addAttributes("colgroup", "span", "width")
.addAttributes("img", "align", "alt", "height", "src", "title", "width")
.addAttributes("ol", "start", "type").addAttributes("q", "cite")
.addAttributes("table", "summary", "width")
.addAttributes("td", "abbr", "axis", "colspan", "rowspan", "width")
.addAttributes("th", "abbr", "axis", "colspan", "rowspan", "scope", "width")
.addAttributes("ul", "type")
.addProtocols("a", "href", "ftp", "http", "https", "mailto")
.addProtocols("blockquote", "cite", "http", "https").addProtocols("img", "src", "http", "https")
.addProtocols("q", "cite", "http", "https");
}
答案 1 :(得分:1)
没有开箱即用。我看到的唯一选择是扩展库。请特别注意org.owasp.esapi.codecs.HTMLEntityCodec
方法mkCharacterToEntityMap()
这是编解码器告诉编码器类要逃避什么,以及什么不能逃脱的地方。我定义了您自己的Codec
。
然后,您可能需要添加一个方法来扩展DefaultEncoder
类,以便您可以使用您想要使用它的编解码器。也许类似于DefaultEncoder.encodeForHTML(String input, Codec codec)
如果白名单需要更加可配置,那么您可能需要更改它,以便您可以发送"input1|input2|input3"
这样的正则表达式,以便编解码器知道要忽略的内容。您可能希望通过esapi.properties
配置此白名单,以便您的技术支持可以在生产中更改它,而无需完全重新部署。
答案 2 :(得分:0)
ESAPI Validator.getValidSafeHTML()接近让你想要的东西。它目前在引擎盖下使用AntiSamy。你也可以给OWASP Java HTML Sanitizer一个镜头。它的重量非常轻,很少(可能没有)依赖性,维护得很好。
-kevin