Search code examples
javahtmlswingsanitization

Is guarding <, >, and & enough to sanitize HTML in Swing components?


I have an arbitrary string. I want to put MyString in a HTML document like

<html><body>Text bla <b>MyString</b> bla bla</body></html>

I do not want to allow MyString to do any HTML formatting with tags, but I also don't want to escape EVERY character using &charcode; (which is my fallback plan).

Is it enough to replace <, > and & with &lt;, &gt; and &amp; (and newline with <br>)? If not, what else?

Some more context: This is for putting user-provided strings in a formatted way in a JLabel, which also contains other text (so just styling the label is not enough).


Solution

  • As @user2864740 wrote in the comments:

    See Rule #1 from the OWASP cheat-sheet link, which lists 6 characters to escape: &, <, >, ", ', /. Whether or not such are required (in all contexts).

    Escaping these characters seemed to have been enough in my case.