owasp-java-html-sanitizer 에 대해 알아보자

bloom·2023년 1월 14일
0

사용자가 입력하는 html에 XSS filtering을 할 필요가 있어 owasp-java-html-sanitizer를 이용하게 되었다.

먼저 implementation 은 사용하고자하는 버전에 맞춰 다음과 같이 해주면 된다.

implementation 'com.googlecode.owasp-java-html-sanitizer:owasp-java-html-sanitizer:20220608.1'

기본적인 사용법은 다음과 같다

    fun basicUse(html: String): String? {
        val sanitizer = Sanitizers.BLOCKS
        return sanitizer.sanitize(html)
    }

사용하고자하는 Policy를 설정하고 html을 sanitize를 하도록 한다.

기본적으로 owasp 에서 제공하고 있는 policy는 FORMMATTING, BLOCKS, STYLES, LINKS, IMAGES 등이 있다.

FORMMATING 같은 경우에는 Policy가 다음과 같은 형태로 설정이 되어있다.

  /**
   * A canned policy that allows a number of common formatting elements.
   */
  public HtmlPolicyBuilder allowCommonInlineFormattingElements() {
    return allowElements(
        "b", "i", "font", "s", "u", "o", "sup", "sub", "ins", "del", "strong",
        "strike", "tt", "code", "big", "small", "br", "span", "em");
  }

제공되는 policy 이외에도 커스텀 policy를 사용하고 싶다면 HtmlPolicyBuilder를 사용해서 설정을 하면 된다.

    fun sanitizeHtml(html: String): String? {
        val policyFactory: PolicyFactory = HtmlPolicyBuilder()
            .allowElements(
                "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", "span", "strike", "strong", "sub", "sup", "table", "tbody", "td", "tfoot", "th", "thead",
                "tr", "u", "ul", "input", "link"
            )
            .allowAttributes("alt", "align", "title", "img").onElements("img")
            .allowAttributes("href", "target", "class").onElements("a")
            .allowAttributes("class", "id", "style").onElements("div")
            .allowAttributes("id").onElements("ul")
            .allowAttributes("class").onElements("li")
            .allowAttributes("rel", "href", "media").onElements("link")
            .allowAttributes("type", "src", "class", "alt", "title", "id", "name", "value").onElements("input")
            .allowStandardUrlProtocols()
            .toFactory()

        return policyFactory.sanitize(html)
    }

허용되는 element들을 설정하고 각 element에 허용할 attrubute들을 설정해줄 수 있다.
img 에 src에 url 이 들어가는 경우 허용된 UrlProtocol이 아닌 경우 해당 부분도 제거하게되는데,
이러한 경우를 제거하기 위해 allowStandardUrlProtocols 를 사용하면 http, https, mailto 는 허용되어 제거되지 않는다.

  public HtmlPolicyBuilder allowStandardUrlProtocols() {
    return allowUrlProtocols("http", "https", "mailto");
  }
profile
in spring

0개의 댓글