I have an online service where users can create json-backed documents. These are then stored on a server and other users can load them. The json is then decoded exactly as it was submitted. Are there any security risks in the event that a user tampers with the json before they submit it and injects arbitrary javascript, which is then executed on the viewers' browser? Is this even possible? that's what I need to know, if this is possible, or arbitrary execution of javascript from a json string is possible.
This depends entirely on a) whether you're scrubbing the JSON on the server side, and (even more) on b) how you're decoding the JSON on the client side when you load it again.
Any code that uses eval()
to deserialize the JSON into a Javascript object is open to exactly the attack you describe.
Any code that uses JSONP to load the JSON (i.e. passing the JSON as a Javascript literal to a named callback function) is open to the attack you describe (it's effectively the same as using eval()
).
Most robust JSON-parsing mechanisms (e.g. json2.js, the jQuery $.parseJSON
function, or native JSON.parse()
functions in browsers that support it) will not accept JSON that doesn't follow the JSON specification. So if you're using a library to parse the JSON string, you may be safe.
No matter how you intend to load the JSON on the client side, it is good practice to scrub any user-submitted content on the server side. In this case, you might use server-side code to check that the JSON is valid (e.g. using json.loads(user_submitted_json)
in Python, and catching errors).
So with some care on both the server side and the client side, you should be able to do this safely.