I came across the following xss fix. The old code was:

this.commentText = new Text(Sanitizer.sanitizeForHtml(commentText.getValue()));

The xss fix code is:

String sanitizedText = Sanitizer.sanitizeForHtml(commentText.getValue()).replace("\n", "\n<br>");

Can you please clarify to me how \n can be used in XSS? and how replacing it with \n<br> will solve the problem?

  • Well, an explanation come to my mind replacing \n to <br> but I can't figure out why it shoud be replace by \n<br> – Xavier59 Sep 20 '16 at 22:32
  • @Xavier59 it might be a mistake from the code author though. If you can post your explanation that may be helpful. – user2192774 Sep 21 '16 at 0:53
  • Which sanitizer is being used? – David Sep 21 '16 at 3:14

It is not meant as a protection against XSS and there is no common context where it would do.

Instead, the authors solve the problem that the newline character (\n) does not display a new line in HTML, so they add the <br> tag to enforce a visible line break.

The authors of the code even explain it in a comment themselves here:

//replacing "\n" with "\n<br>" here is to make comment text support displaying breakline
String sanitizedText = Sanitizer.sanitizeForHtml(commentText.getValue()).replace("\n", "\n<br>");

Imagine the dev want to output user input in a javascript variable.

If the user input with \n it will render as

var input = " hey

Which in a <script> will render as an error and will cause it to be not executed because your string is not terminated ! Instead, replacing \n with <br> will result to the very correct var input = "hey<br />"

  • how this protects from XSS? – user2192774 Sep 21 '16 at 13:16
  • uhhm... the code in the question replaces \n with \n<br>, so there is still a line break in it. – Lukas Sep 21 '16 at 13:32
  • @Lukas See comments on question ;) – Xavier59 Sep 21 '16 at 13:36
  • @Xavier59 Ah, I see! – Lukas Sep 21 '16 at 13:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.