The Evils of Eval

[article]

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.

Tags: 

About the author

Bryan Sullivan's picture Bryan Sullivan

Bryan Sullivan is a security program manager on the Security Development Lifecycle (SDL) team at Microsoft. He is a frequent speaker at industry events, including Black Hat, BlueHat, and RSA Conference. Bryan is also a published author on Web application security topics. His first book, Ajax Security was published by Addison-Wesley in 2007.

AgileConnection is one of the growing communities of the TechWell network.

Featuring fresh, insightful stories, TechWell.com is the place to go for what is happening in software development and delivery.  Join the conversation now!