Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is eval unsafe in javascript? [duplicate]

Tags:

javascript

Possible Duplicate:
Why exactly is eval evil?

I read people claim that eval is unsafe when run on arbitrary user input code. I understand this in other languages that run on the server that access the filesystem, etc. However, why does this matter when executing code in a browser? After all, can't you just fire up Firebug and write any arbitrary script you want anyway? So then how is eval any different?

like image 800
Joe Armstrong Avatar asked Jan 27 '11 02:01

Joe Armstrong


People also ask

Why eval is dangerous in JavaScript?

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.

Why is eval not safe?

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.

What is a safe alternative to using eval ()?

An alternative to eval is Function() . Just like eval() , Function() takes some expression as a string for execution, except, rather than outputting the result directly, it returns an anonymous function to you that you can call. `Function() is a faster and more secure alternative to eval().

What is the reason JSON eval is not recommended for use?

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


2 Answers

The danger of eval only rears its ugly head when you are serving a script written by alice to user bob for bob's browser to eval.

e.g. if bob enters his password on your page, alice could have written a keylogger in the user input you evaled and arrange for the data to be encoded in a script that bob will (unknowingly) submit to be served to alice. This is, as @Hunter2 has suggested in the comments, an XSS attack.

If you are not serving to other people, you are correct in assuming it is equivalent to firing up firebug

like image 104
tobyodavies Avatar answered Oct 08 '22 22:10

tobyodavies


don't think it is unsafe, for the most paranoid execute eval = null;

like image 24
Kris Ivanov Avatar answered Oct 08 '22 22:10

Kris Ivanov