Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eval is evil... So what should I use instead?

Tags:

An ajax request returns me a standard JSON array filled with my user's inputs. The input has been sanitized, and using the eval() function, I can easily create my javascript object and update my page...

So here's the problem. No matter how hard I try to sanitize the inputs, I'd rather not use the eval() function. I've checked google for ways to use "JSON in AJAX without eval" and have ran accross a bunch of different methods...

Which one should I use? Is there a standard, proven-secure way of doing this?

like image 392
koni Avatar asked Mar 14 '09 19:03

koni


People also ask

Is it OK to use eval?

eval is evil if running on the server using input submitted by a client that was not created by the developer or that was not sanitized by the developer. eval is not evil if running on the client, even if using unsanitized input crafted by the client.

Why is eval harmful?

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!

Which of the following is the reason JSON eval is not recommended for use?

Your server could be compromised and the data source could be tampered with.

When should you use eval JavaScript?

Definition and Usage The eval() method evaluates or executes an argument. If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.


1 Answers

json.org has a nice javascript library

simple usage:

JSON.parse('[{"some":"json"}]'); JSON.stringify([{some:'json'}]); 

Edit: As pointed out in comments, this uses eval if you look through its source (although it looks to be sanitized first)

to avoid it completely, look at json_parse or json-sans-eval

json2.js is insecure, json_parse.js is slow, json-sans-eval.js is non-validating

like image 153
cobbal Avatar answered Sep 17 '22 17:09

cobbal