I thought the \ (backslash) character was a dangerous character that you needed to filter out/properly encode to protect against XSS attacks (OWASP says so, too), and I still do, but why?

I found a website that stores the search query when you search the website in a JavaScript variable, like this:

var_name = "query"

It does filter out double quotes, single quotes and semicolons, but I'm able to use things like \n and \r (although \r seems to just render whitespace...) but for some reason I'm just now able to get the alert() called successfully.

I've played around with \n, like putting a few before and after alert(), and also escaping the closing double quote:

var_name = "\n\nalert()\n\n\"

But nothing seems to work. I think I'm missing something obvious here, but if someone could help me out here and clarify this I'd be grateful!

  • Can you inject a single backslash? \n and \r are insufficient for us to know whether it's actually letting through anything dangerous (since that's not a backslash on its own). – Ethan Kaminski Oct 11 '18 at 18:14
  • Oh, sorry. My bad. Yeah, it does let me inject a single backslash on its own. – David Oct 11 '18 at 18:17

Unescaped backslashes can be dangerous, depending on the context.

Let's assume that X and Y are user-controlled (with ' and < escaped, but not \). Then, this is exploitable:

var name = "X"; var id = "Y";

An attacker can set X to \ to escape the first string's closing quote ("), and set Y to ;alert()// to inject the payload and comment out the superfluous ";. The line would then look like this:

var name = "\"; var id = ";alert()//";
           |---string----|        |--comment ...

But this is not exploitable:

var name = "X";
var id = "Y";

Even though an attacker can remove the first closing " here too, a single- or double-quoted string can only span multiple lines if each previous line is ending with \. But in this example, even if the attacker can inject newlines, all they can do is provoke a syntax error, no script injection because they don't control the end of all lines in the string.

OTOH, if these strings were in backtick quotes ("template literals"), they could span multiple lines without issues and the attack would be feasible.

So, if a JS string with unescaped backslashes is XSS-able depends a lot on the context. But in many cases you will need at least two injection points to insert a payload after you used a \ to break out of a string.

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.