OWASP JSON Sanitizer

Revision as of 09:49, 4 February 2014 by Jmanico (Talk | contribs)

Jump to: navigation, search

OWASP Project Header.jpg

Given JSON-like content, converts it to valid JSON.


be conservative in what you do, be liberal in what you accept from others Applied to JSON-like content from others, it will produce well-formed JSON that should satisfy any parser you use.



Many applications have large amounts of code that uses ad-hoc methods to generate JSON outputs. Frequently these outputs all pass through a small amount of framework code before being sent over the network. This small amount of framework code can use this library to make sure that the ad-hoc outputs are standards compliant and safe to pass to (overly) powerful deserializers like Javascript's eval operator.

Applications also often have web service APIs that receive JSON from a variety of sources. When this JSON is created using ad-hoc methods, this library can massage it into a form that is easy to parse.

By hooking this library into the code that sends and receives requests and responses, this library can help software architects ensure system-wide security and well-formedness guarantees.

The sanitizer takes JSON like content, and interprets it as JS eval would. Specifically, it deals with these non-standard constructs.

'...' Single quoted strings are converted to JSON strings.
\xAB Hex escapes are converted to JSON unicode escapes.
\012 Octal escapes are converted to JSON unicode escapes.
0xAB Hex integer literals are converted to JSON decimal numbers.
012 Octal integer literals are converted to JSON decimal numbers.
+.5 Decimal numbers are coerced to JSON's stricter format.
[0,,2] Elisions in arrays are filled with null.
[1,2,3,] Trailing commas are removed.
{foo:"bar"} Unquoted property names are quoted.
//comments JS style line and block comments are removed.
(...) Grouping parentheses are removed.

The sanitizer fixes missing punctuation, end quotes, and mismatched or missing close brackets. If an input contains only white-space then the valid JSON string null is substituted.


  4. The output contains only valid Unicode scalar values (no isolated UTF-16 surrogates) that are allowed in XML unescaped.



The sanitize method will return the input string without allocating a new buffer when the input is already valid JSON that satisfies the properties above. Thus, if used on input that is usually well formed, it has minimal memory overhead.

The sanitize method takes O(n) time where n is the length in UTF-16 code-units.