Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not eval() JSON?

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.

like image 973
NikiC Avatar asked Nov 24 '10 19:11

NikiC


People also ask

Why is JSON eval not recommended?

Malicious code : invoking eval can crash a computer. For example: if you use eval server-side and a mischievous user decides to use an infinite loop as their username. Terribly slow : the JavaScript language is designed to use the full gamut of JavaScript types (numbers, functions, objects, etc)… Not just strings!

Why is JSON parse () a more secure alternative than eval ()?

You are more vulnerable to attacks if using eval : JSON is a subset of Javascript and json. parse just parses JSON whereas eval would leave the door open to all JS expressions.

What does eval () do in JSON?

The eval() function in JavaScript is used to take an expression and return the string. As a result, it can be used to convert the string into JSON.

Does JSON parse use eval?

This JSON parser does not attempt to validate the JSON, so may return a surprising result given a syntactically invalid input, but it 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.


2 Answers

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?

like image 196
Matthew Vines Avatar answered Sep 21 '22 07:09

Matthew Vines


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"

like image 37
zzzzBov Avatar answered Sep 19 '22 07:09

zzzzBov