[Esapi-user] String encoding for JSON format

Olivier Jaquemet olivier.jaquemet at jalios.com
Mon Jul 22 10:54:14 UTC 2013


Hi all,

A little "warning" for ESAPI users who would be tempted to use the 
method encodeForJavaScript() to generate JSON format strings.
For example like this (don't do this!) :
   String myJson = "{ text: '" + 
ESAPI.encoder().encodeForJavaScript(someTxt) + "' }"; // BAD

This is a bad idea, for at least 2 reasons :

1. Because it won't generate valid JSON
  encodeForJavaScript() encodes strings using hexadecimal escape 
sequence (\xXXXX), those hex escape sequence are not valid in the JSON 
format as only unicode escape sequence (\uXXXX) are authorized.
Sources
  -   the JSON spec, which only mention unicode escape sequence (\u) 
http://tools.ietf.org/html/rfc4627
  -   json.org http://www.json.org/string.gif
  -   there are even santizer to clean hex sequence in unicode sequence 
: https://code.google.com/p/json-sanitizer/

Thus JSON produced this way would not be valid and would not be parsed 
correctly by strict JSON parser
(eg jackson would throw a JsonParseException: Unrecognized character 
escape 'x')

This warning has always been said here :
http://stackoverflow.com/questions/11584850/encodeforjavascript-with-json-parse-doublequote-woes
But I thought it would be a good reminder now that everyone uses JSON 
everywhere.

2. Because you should always use high level API to export data in a 
specific format.
When you want to generate JSON, XML, SQL, CSV ... or any specific data 
format, you should ALWAYS use a high level API that perfomrs all the 
appropriate encoding that you will always forget from time to time thus 
leading to bad data at best or security hole at worst.

Regards
Olivier Jaquemet


More information about the Esapi-user mailing list