00:00

#0903

JavaScript Context Injection

Medium+100 XPA03:2021 InjectionCWE-79
XSSJavaScript Context

Scenario

Your server embeds a user-controlled value directly into a JavaScript string literal in the HTML response: var name = "<OUTPUT>";.

The safeJsonValue function currently only escapes < and >, leaving backslashes, double-quotes, and newlines unescaped.

An attacker can inject "; alert(1); var x=" to break out of the string literal and execute arbitrary JavaScript in the victim's browser.

Injecting into JavaScript string literals is a common server-side XSS vector when applications inline JSON or user data into script blocks. A single unescaped quote or newline can give an attacker full script execution.

Your Tasks

  1. Fix safeJsonValue to escape all characters that could break out of a JavaScript string literal.
  2. Escape in order: \\\, "\", newline → \n, carriage return → \r, </<\/.
  3. Return the escaped string — do not throw.

Examples

Example 1String breakout (bug)

safeJsonValue('"'); alert(1);//')
// var name = ""; alert(1);//"; — script executes!

Example 2Safely escaped (fix)

safeJsonValue('"')
// returns '\"'

Constraints

  • Escape backslash first to avoid double-escaping.
  • The </ sequence must be escaped to prevent premature </script> tag termination.
  • Single quotes do not need escaping in a double-quoted JS string literal.

Hint

References

solution.js
Ln 1, Col 1UTF-8JavaScript
Sandbox ready
0/0/0not run