Why not eval() JSON?

2019-01-18 13:54发布

问题:

As far as I know it is considered bad practice to eval() JSON objects in JavaScript, because of security. I can understand this concern if the JSON comes from another server.

But if the JSON is provided by my own server and is created using PHP's json_encode (let us assume it is not buggy), is it legitimate to simply use eval() to read the JSON in JS or are there any security problem I currently can't think of?

I really don't want to deal with dynamically loading a JSON parser and would be glad to simply use eval().

PS: I will obviously use the native JSON object if it is available, but want to fall back to eval() for IE/Opera.

回答1:

There are a number of ways that your security may be compromised.

  • Man in the middle attacks could theoretically alter the contents of data being delivered to the client.
  • Your server traffic could be intercepted elsewhere and different content could be provided (not quite the same as a MIM attack)
  • Your server could be compromised and the data source could be tampered with.

and these are just the simple examples. XSS is nasty.

"an ounce of prevention is worth a pound of cure"



回答2:

In your scenario, the question becomes, where is PHP getting the javascript to execute from? Is that channel secure, and free from potential user manipulation? What if you don't control that channel directly?



回答3:

Besides the obvious security issues:

  1. Native JSON is faster
  2. You don't need to "load" a JSON parser it's just another function call to the JavaScript engine


回答4:

Tip: in asp.net using JSON is considered bad becuase parsing of DateTime differs between the server and the client so we use a special function to deserialize the date in javascript. I'm not sure if PHP has the same issue but its worth mentioning though.



回答5:

check out this:http://blog.mozilla.com/webdev/2009/02/12/native-json-in-firefox-31/

so at least for firefox you can use the built in json parser



回答6:

Seriously? Some of the guys here are paranoid. If you're delivering the JSON and you know it's safe, it's ok to fallback(*) to eval(); instead of a js lib for IE. After all, IE users have much more to worry about.

And the man-in-the-middle argument is bullsh*t.

(*) the words fallback and safe are in bold because some people here didn't see them.