When Is JavaScript'S Eval() Not Evil

When is JavaScript's eval() not evil?

I'd like to take a moment to address the premise of your question - that eval() is "evil". The word "evil", as used by programming language people, usually means "dangerous", or more precisely "able to cause lots of harm with a simple-looking command". So, when is it OK to use something dangerous? When you know what the danger is, and when you're taking the appropriate precautions.

To the point, let's look at the dangers in the use of eval(). There are probably many small hidden dangers just like everything else, but the two big risks - the reason why eval() is considered evil - are performance and code injection.

  • Performance - eval() runs the interpreter/compiler. If your code is compiled, then this is a big hit, because you need to call a possibly-heavy compiler in the middle of run-time. However, JavaScript is still mostly an interpreted language, which means that calling eval() is not a big performance hit in the general case (but see my specific remarks below).
  • Code injection - eval() potentially runs a string of code under elevated privileges. For example, a program running as administrator/root would never want to eval() user input, because that input could potentially be "rm -rf /etc/important-file" or worse. Again, JavaScript in a browser doesn't have that problem, because the program is running in the user's own account anyway. Server-side JavaScript could have that problem.

On to your specific case. From what I understand, you're generating the strings yourself, so assuming you're careful not to allow a string like "rm -rf something-important" to be generated, there's no code injection risk (but please remember, it's very very hard to ensure this in the general case). Also, if you're running in the browser then code injection is a pretty minor risk, I believe.

As for performance, you'll have to weight that against ease of coding. It is my opinion that if you're parsing the formula, you might as well compute the result during the parse rather than run another parser (the one inside eval()). But it may be easier to code using eval(), and the performance hit will probably be unnoticeable. It looks like eval() in this case is no more evil than any other function that could possibly save you some time.

what does eval do and why its evil?

eval() takes the string it is given, and runs it as if it were plain JavaScript code.

It is considered "evil" because:

  • It over-complicates things - Most cases where eval() is used, there would be a much simpler solution that didn't require it. This example in the question is a perfect case in point: there is absolutely no need for eval() for an expression like this. JS has perfectly good syntax for referencing an object property name as a string (myObject["x"] is the same as myObject.x).

  • It's much harder to debug - It's harder to work with it in a debugger, and even once you have managed to work out what's going on, you have you extra work to do because you have to debug both the eval'd code, and the code that generated the original string to eval.

  • It slows things down - The script compiler cannot pre-compile code in an eval(), because it doesn't know what the code will contain until it gets there. So you lose out on a some of the performance benefits in modern Javascript engines.

  • It is a hacker's dream - eval() runs a string as code. Hackers love this because it's much easier to inject a string into a program than to inject code; but eval() means you can inject a string, and get it to run as code. So eval() makes your code easier to hack. (this is less of an issue for browser-based Javascript than other languages, as JS code is accessible in the browser anyway, so your security model should not be based on your code being immutable, but nevertheless, injection hacks can still be a problem, particularly with cross-site attacks).

Why is using the JavaScript eval function a bad idea?

  1. Improper use of eval opens up your
    code for injection attacks

  2. Debugging can be more challenging
    (no line numbers, etc.)

  3. eval'd code executes slower (no opportunity to compile/cache eval'd code)

Edit: As @Jeff Walden points out in comments, #3 is less true today than it was in 2008. However, while some caching of compiled scripts may happen this will only be limited to scripts that are eval'd repeated with no modification. A more likely scenario is that you are eval'ing scripts that have undergone slight modification each time and as such could not be cached. Let's just say that SOME eval'd code executes more slowly.

Why does eval() exist?

Because sometimes there is a need. All the same reasons for/against using eval in JavaScript can likely be shared with the use of reflection in Java, for example.

However, I agree with everything you quoted in your question. Many reasons for using it are ill-advised, and best done differently - but sometimes, there is still a need, or it is simply the "best choice" over other available alternatives. (I'd focus on the answers to Is there ever a good reason to use eval()? for additional reasons.)

+1 to your question for good research.

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

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

Javascript Eval is evil but in certain situations only?

Strictly speaking, there is nothing actually, phsyically harmful in using eval, because it does nothing more than what the browser's console can already do.

There is a potential danger of injection, but that's the same risk as putting any user-supplied input into a <script> tag, not a particularity of eval.

The main reason to avoid eval is because it has to interpret a string. Now, to be fair, just running a JavaScript file is basically the same as calling a great big eval over the whole file (broadly speaking), because JavaScript is interpreted (or at most compiled at run-time). Therefore, using eval sparsely, where it only gets run, say, when a user clicks on a button, is fine. Noticeable effects will only appear if you end up with eval running frequently, such as in a loop. This is why people will always tell you to pass a function to setTimeout instead of a string, for instance.

That said, there is always an alternative to using eval. It may require rewriting parts of older code, but it's always avoidable.

JSLint eval is evil. alternatives

I wouldn't worry about it since you are only passing these function strings from the server to the client, and are thus in control of what will be evaluated.

On the other hand, if you were going the other direction and doing the evals of client-passed code on the server, that would be an entirely different story...

Update:

As disabling the validation option in your comment may cause you to miss future errors, I would instead suggest passing the function name rather than the entire function and have the function library mirrored on the server and client. Thus, to call the function, you'd use the following code:

var policyFunction = YourLibraryName[this.policies[j].policyFunctionName];
var policyArguments = this.policies[j].policyArguments;

policyFunction.apply(this, policyArguments);

Update 2:

I was able to validate the following code with JSLint successfully, which essentially allows you to "turn off" validation for the vast minority of cases where eval is appropriate. At the same time, JSLint still validates normal eval calls, and all uses of this method should throw up flags for future developers to avoid using it/refactor it out where possible/as time allows.

var EVAL_IS_BAD__AVOID_THIS = eval;
EVAL_IS_BAD__AVOID_THIS(<yourString>);

What is the intended purpose of eval in JavaScript?

eval

Evaluates a string of JavaScript code
without reference to a particular
object.

If you construct an arithmetic expression as a string, you can use eval to evaluate it at a later time. For example, suppose you have a variable x. You can postpone evaluation of an expression involving x by assigning the string value of the expression, say "3 * x + 2", to a variable, and then calling eval at a later point in your script.

Be careful when using eval

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension.



Related Topics



Leave a reply



Submit