Take the 2-minute tour ×
Information Security Stack Exchange is a question and answer site for Information security professionals. It's 100% free, no registration required.

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>
share|improve this question

1 Answer 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.

share|improve this answer
    
Which of these are necessary? Of course 4 and 5 are necessary but what about others? –  Andrey Botalov Nov 1 '12 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. –  Mike Samuel Nov 1 '12 at 18:41
    
Why 1 is necessary? Will quoting make it less vulnerable? What is the reason to quote keys besides complying to standard? –  Andrey Botalov Nov 1 '12 at 18:51
    
Regarding 2: Firefox doesn't seem to treat ] as the end of value. Haven't checked in other browsers –  Andrey Botalov Nov 1 '12 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. –  Mike Samuel Nov 1 '12 at 19:09

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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