How to sanitize HTML code in Java to prevent XSS attacks?
Asked Answered
B

5

41

I'm looking for class/util etc. to sanitize HTML code i.e. remove dangerous tags, attributes and values to avoid XSS and similar attacks.

I get html code from rich text editor (e.g. TinyMCE) but it can be send malicious way around, ommiting TinyMCE validation ("Data submitted form off-site").

Is there anything as simple to use as InputFilter in PHP? Perfect solution I can imagine works like that (assume sanitizer is encapsulated in HtmlSanitizer class):

String unsanitized = "...<...>...";           // some potentially 
                                              // dangerous html here on input

HtmlSanitizer sat = new HtmlSanitizer();      // sanitizer util class created

String sanitized = sat.sanitize(unsanitized); // voila - sanitized is safe...

Update - the simpler solution, the better! Small util class with as little external dependencies on other libraries/frameworks as possible - would be best for me.


How about that?

Bailly answered 5/8, 2010 at 9:17 Comment(3)
So what you basically want is for clients to be able to submit forms which are then displayed in shape of fx. a guestbook? And you want them to be able to use html but you still want to be able to block malicious users hacking-attempts? Or did I get it all wrong here...?Behr
@Latze: I want clients (users via their browsers) to submit richtext content (html format via rich text editor - TinyMCE) but to check and remove any potentially dangerous (unsafe) content. I don't know what is fx and guestbook that you mention in this context.Bailly
Ah! I will give it a shot, give me a couple of minutesBehr
B
45

You can try OWASP Java HTML Sanitizer. It is very simple to use.

PolicyFactory policy = new HtmlPolicyBuilder()
    .allowElements("a")
    .allowUrlProtocols("https")
    .allowAttributes("href").onElements("a")
    .requireRelNofollowOnLinks()
    .build();

String safeHTML = policy.sanitize(untrustedHTML);
Bibliographer answered 4/8, 2015 at 10:25 Comment(0)
B
16

Thanks to @Saljack's answer. Just to elaborate more to OWASP Java HTML Sanitizer. It worked out really well (quick) for me. I just added the following to the pom.xml in my Maven project:

    <dependency>
        <groupId>com.googlecode.owasp-java-html-sanitizer</groupId>
        <artifactId>owasp-java-html-sanitizer</artifactId>
        <version>20150501.1</version>
    </dependency>

Check here for latest release.

Then I added this function for sanitization:

    private String sanitizeHTML(String untrustedHTML){
        PolicyFactory policy = new HtmlPolicyBuilder()
            .allowAttributes("src").onElements("img")
            .allowAttributes("href").onElements("a")
            .allowStandardUrlProtocols()
            .allowElements(
            "a", "img"
            ).toFactory();

        return policy.sanitize(untrustedHTML); 
    }

More tags can be added by extending the comma delimited parameter in allowElements method.

Just add this line prior passing the bean off to save the data:

    bean.setHtml(sanitizeHTML(bean.getHtml()));

That's it!

For more complex logic, this library is very flexible and it can handle more sophisticated sanitizing implementation.

Brussels answered 25/2, 2016 at 16:42 Comment(0)
G
14

You could use OWASP ESAPI for Java, which is a security library that is built to do such operations.

Not only does it have encoders for HTML, it also has encoders to perform JavaScript, CSS and URL encoding. Sample uses of ESAPI can be found in the XSS prevention cheatsheet published by OWASP.

You could use the OWASP AntiSamy project to define a site policy that states what is allowed in user-submitted content. The site policy can be later used to obtain "clean" HTML that is displayed back. You can find a sample TinyMCE policy file on the AntiSamy downloads page.

Grearson answered 5/8, 2010 at 9:56 Comment(6)
this would require to rebuild architecture of my whole project. i'm not willing to do it. i need something simple without many dependencies and no need to change the way my code is organized (i like it the way it is now). so - i need just a util class to do the work. my question is now updated to clarify that requirement.Bailly
I'm not sure what you mean by rebuilding the architecture of the project. AntiSamy fits in perfectly into your requirement by allowing text editor inputs to be fed into a filtering library driven by a site policy.Grearson
Hmmm. Seems you are right! I just thought it is big and heavy framework like struts, spring etc. and works as some kind of servlet filter ;-). Probably big letters in name ("OWASP") misled me here. BTW: what are exact dependencies of OWASP AntiSamy - what else will I need to use it?Bailly
The AntiSamy POM might give you a hint (the link provided later is from SVN, and should not be used directly). It does need a couple of other libraries, but I'm not sure how they're internally used by AntiSamy. Ref: code.google.com/p/owaspantisamy/source/browse/trunk/Java/…Grearson
Fyi, OWASP Java HTML Sanitizer aims to provide a more efficient, more easily configurable alternative to AntiSamy.Involucrum
Together with a javax.servlet.Filter this solved the problem in my case. I did not have to modify any of the existing code.Mollymollycoddle
W
9

HTML escaping inputs works very well. But in some cases business rules might require you NOT to escape the HTML. Using REGEX is not fit for the task and it is too hard to come up with a good solution using it.

The best solution I found was to use: http://jsoup.org/cookbook/cleaning-html/whitelist-sanitizer

It builds a DOM tree with the provided input and filters any element not previosly allowed by a Whitelist. The API also has other functions for cleaning up html.

And it can also be used with javax.validation @SafeHtml(whitelistType=, additionalTags=)

Wirephoto answered 1/8, 2013 at 16:1 Comment(0)
R
0

Regarding Antisamy, you may want to check this regarding the dependencies:

http://code.google.com/p/owaspantisamy/issues/detail?id=95&can=1&q=redyetidave

Rosmunda answered 23/2, 2011 at 15:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.