The Evils of Eval


names but still can wreak the same trouble in your code. Two of these are setTimeout and setInterval. The setTimeout function simply adds a delay argument to eval. Instead of being immediately executed, the code argument passed to it is executed after the specified delay time. Similarly, the setInterval function adds an interval argument, and the code is executed every time the amount of time specified by the interval elapses. These calls are functionally equivalent to eval, and you should avoid or remove them whenever possible.

Speaking of "functional" equivalents to eval, there's another you should be aware of: the function constructor. It is possible to define a function by declaring a new function object instead of using the more common function definition syntax (function square(x) { return x * x; }) or function literal syntax (var square = function(x) { return x * x; }). When declaring function objects in this manner, you pass the function body (i.e., the code to be executed) as a parameter to the Function constructor, like this:

var square = new Function('x', 'return x * x;');

If an attacker were able to inject code into the function body parameter.  For instance, if the parameter was built using user input instead of being hardcoded as in the examples above, then he could potentially exploit the weakness.

You might think that your use of eval (or its brethren) is safe, as you're not passing untrusted input to it. The problem is that it can be difficult to tell exactly what input is trusted. Query string parameters and form field values are obviously untrusted user input, but so are headers and cookies. One popular use for eval is to use it to parse JSON strings into JavaScript objects.


About the author

AgileConnection is a TechWell community.

Through conferences, training, consulting, and online resources, TechWell helps you develop and deliver great software every day.