【问题标题】:How to add whitelist of tags for Java ESAPI如何为 Java ESAPI 添加标签白名单
【发布时间】:2014-05-22 14:44:48
【问题描述】:

我们正在向我们的网站添加富文本编辑功能,包括添加 youtube 视频的功能。但另一方面,我们希望保持安全并防止 XSS/HTML 注入。之前我们使用以下代码转义数据:

ESAPI.encoder().encodeForHTML
ESAPI.encoder().encodeForJavaScript

现在我们必须添加某种允许标签的白名单。有没有办法实现这个功能?

【问题讨论】:

    标签: java xss esapi


    【解决方案1】:

    我们决定在 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");
    }
    

    【讨论】:

      【解决方案2】:

      不是开箱即用的。我看到的唯一选择是扩展库。看看org.owasp.esapi.codecs.HTMLEntityCodec具体方法mkCharacterToEntityMap()

      这是编解码器告诉编码器类什么要转义,什么不能转义的地方。我会定义你自己的Codec

      然后您可能需要添加/扩展DefaultEncoder 类的方法,以便您可以在您想使用它的地方使用您的编解码器。也许像DefaultEncoder.encodeForHTML(String input, Codec codec)

      如果白名单需要更加可配置,那么您可能需要更改它,以便您可以发送像 "input1|input2|input3" 这样的正则表达式,这样编解码器就会知道要忽略什么。然后,您可能希望通过 esapi.properties 配置此白名单,以便您的技术支持可以在生产中更改它,而无需完全重新部署。

      【讨论】:

        【解决方案3】:

        ESAPI Validator.getValidSafeHTML() 几乎可以满足您的需求。它目前在后台使用 AntiSamy。您也不妨试试OWASP Java HTML Sanitizer。它的重量很轻,几乎没有(可能没有)依赖项,并且维护得很好。

        -凯文

        【讨论】:

        • 另外,它不是直接在 ESAPI javadoc 中,但我认为您可以通过“antisamy-esapi.xml”配置文件调整您想要删除、编码等的内容,该配置文件应该在与您的 ESAPI.properties 文件相同的目录。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-28
        • 1970-01-01
        • 2020-07-14
        • 2017-06-28
        相关资源
        最近更新 更多