2014-05-22 81 views
0

我們正在向我們的網站添加Rich Text Editing,包括添加YouTube視頻的功能。但另一方面,我們希望保持安全並防止XSS/HTML注入。以前我們使用下面的代碼爲逃避數據:如何爲Java添加標籤白名單ESAPI

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

現在,我們必須添加某種允許標籤的白名單。有沒有辦法實現這個功能?

回答

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

不開箱即用。我看到的唯一選擇是擴展庫。看看org.owasp.esapi.codecs.HTMLEntityCodec具體的方法

這是編解碼器將告訴編碼器類什麼逃生,什麼不能逃脫。我會定義你自己的Codec

然後,您可能需要添加一個方法來擴展DefaultEncoder類,以便您可以將編解碼器用於您想使用它的位置。也許類似於DefaultEncoder.encodeForHTML(String input, Codec codec)

如果白名單需要更具可配置性,那麼您可能需要對其進行更改,以便您可以發送像"input1|input2|input3"這樣的正則表達式,以便編解碼器知道要忽略的內容。您可能會希望通過esapi.properties配置此白名單,以便您的技術支持可以在生產中更改它,而無需完全重新部署。

0

的ESAPI Validator.getValidSafeHTML()接近讓你想你所期待的。它目前使用AntiSamy引擎蓋。您也可能希望給OWASP Java HTML Sanitizer一個鏡頭。它重量輕,幾乎沒有(可能沒有)依賴關係,並且維護良好。

-kevin

+0

此外,它不能直接在ESAPI的javadoc,但我認爲你可以調整你想要的東西去掉,編碼等,通過「antisamy-esapi.xml」配置文件,這應該是在與您的ESAPI.properties文件相同的目錄。 –