Injecting javascript in JSON and security
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 submi开发者_高级运维tted. 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 nativeJSON.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.
<plug shameless="true">
JSON sans eval is designed to avoid problems with malformed JSON while still being efficient at parsing.
This JSON parser does not attempt to validate the JSON, so may return a result given a syntactically invalid input, but does not use eval so is deterministic and is guaranteed not to modify any object other than its return value.
There are a number of JSON parsers in JavaScript at json.org. This implementation should be used whenever security is a concern (when JSON may come from an untrusted source), speed is a concern, and erroring on malformed JSON is not a concern.
</plug>
JSON has traditionally been parsed using an eval()
statement, which is about as insecure as it is possible to get. If you allow this, your application will be insecure.
精彩评论