javascript - Why shouldn't the server respond

2019-09-15 17:20发布

问题:

According to this Angular 2 guide:

Don't expect the decoded JSON to be the heroes array directly. This server always wraps JSON results in an object with a data property. You have to unwrap it to get the heroes. This is conventional web API behavior, driven by security concerns.

('Heroes' is an array of objects).
The link in the above paragraph says :

Always return JSON with an Object on the outside
Always have the outside primitive be an object for JSON strings:
Exploitable: [{"object": "inside an array"}]
Not exploitable: {"object": "not inside an array"}
Also not exploitable: {"result": [{"object": "inside an array"}]}

My Question is: Why shouldn't the server return something like a JSON array? Say :
[ "apples" ,"oranges" , "peaches" ]

How is this a security concern ?

回答1:

To avoid JSON Hijacking:

The fact that this is a JSON array is important. It turns out that a script that contains a JSON array is a valid JavaScript script and can thus be executed. A script that just contains a JSON object is not a valid JavaScript file.

For example, if you had a JavaScript file that contained the following JSON: {“Id”:1, “Balance”:3.14} And you had a script tag that referenced that file: <script src="http://example.com/SomeJson"></script>

You would get a JavaScript error in your HTML page. However, through an unfortunate coincidence, if you have a script tag that references a file only containing a JSON array, that would be considered valid JavaScript and the array gets executed.

So allowing JSON to be returned as anything but an object would make it possible to return a JSON array that contained code that could be run on the client level (in a context where the client isn't expecting it to be runnable, could be malicious, etc). Only returning JSON objects prevents this from happening.



回答2:

This was rather bad advice that has since been removed from the angular tutorial.

  1. The linked OWASP Cheet Sheet lists three ways to defend against JSON Hijacking. The one the tutorial picked is the hardest to implement correctly, because one must educate every single developer, and audit every single REST resource, rather than writing a single HttpInterceptor to extend CSRF-defenses to GET requests.
  2. JSON hijacking can only occur due to browser bugs, which tend to be fixed quickly (this does not imply such attacks are impossible, but the easy exploits no longer work in modern browsers)