0

How to properly escape user-controlled input when it's inserted as a value in JSON object?

<script>
  $(document).ready(function() {
    new MyObject({
      key1: "user_input",
      key2: ["user_input1", "user_input2"]
    });
  });
</script>
1

1 Answer 1

1

http://code.google.com/p/json-sanitizer/ takes JSON-like content and converts it to JSON that is safe to evaluate as JavaScript source code and which can be embedded in HTML <script> elements and in XML <![CDATA[...]]> sections.

For example, given

{
  key1: "user_input",
  key2: ["user_input1", "user_input2"]
}

It preserves several properties:

  1. Keys must be properly quoted.
  2. Brackets match.
  3. All JavaScript newline characters (CR, LF, U+2028, U+2029) in strings are \u.... escaped.
  4. Quotes ("), backslashes (\) are \u.... escaped to ensure that strings do not end prematurely.
  5. Angle brackets (< and >) are \u.... escaped as necessary to prevent strings from containing the literal text </script or ]]> which would prevent embedding.
  6. All control characters (actually characters not allowed in XML) are \u.... escaped including U+0-U+1F excluding tab, U+7F, U+FFFE, U+FFFF.
  7. Orphaned UTF-16 surrogates are \u.... escaped.
  8. All escape sequences are converted to valid JSON escape sequences including octal escapes (\012), two-digit hex escaped (\x0A), and single character escapes (\!).

It can be a good idea to \u.... escape things like + to defang UTF-7.

6
  • Which of these are necessary? Of course 4 and 5 are necessary but what about others? Commented Nov 1, 2012 at 18:12
  • 1
    @AndreyBotalov, 2 is necessary, 1 and 8 are necessary for it to be valid JSON. 3 is necessary if evaluated as Javascript, but for it to be valid JSON only CR and LF must be escaped. Of 5, if you're only going to embed in HTML, then you can alternatively escape / as \/ which will defang </script> close tags. Commented Nov 1, 2012 at 18:41
  • Why 1 is necessary? Will quoting make it less vulnerable? What is the reason to quote keys besides complying to standard? Commented Nov 1, 2012 at 18:51
  • Regarding 2: Firefox doesn't seem to treat ] as the end of value. Haven't checked in other browsers Commented Nov 1, 2012 at 18:54
  • @AndreyBotalov, The JSON specification, RFC 4627, requires all keys be quoted. If the keys aren't quoted, it isn't JSON. Also, there are many extensions to JavaScript, so if you don't quote keys you don't know what a JavaScript interpreter with extensions might treat as a keyword. Commented Nov 1, 2012 at 19:09

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.