Security risks of using eval() to execute user input in JavaScript

The security risk you’re taking, is that you’re taking input from the user and running it in the context of a script on your site. Imagine if you were a malicious cracker that for whatever reason had full access to modify the JavaScript running on a website. You can do anything that JavaScript running on your domain would have the ability to do (including cookie stealing, XSS, drive-by malware, etc.).

The only thing you can realistically do to mitigate the risks is to not eval() user-provided content. Attempts to sanitise the input to only allow “safe” input are doomed to failure; it’s almost impossible to define what counts as safe, and even harder to actually limit the script to that (given that the potential attacker has an interpreted language with which to disguise his intentions).

Mind you, if this is for educational purposes then one approach is just to make sure that all of the security holes don’t matter. Bad JavaScript cannot destroy your server or steal money from your bank account (unless it’s on your bank’s web page of course). If the site hosting the page has no cookies or sessions worth stealing, and students know it’s just an educational resource, I don’t think there would be anything to worry about. Most of the attacks rely on accessing confidential information stored on your domain, or tricking domain visitors into giving up confidential information somehow (phishing attacks or similar). For your purposes I think you’ll be OK – just don’t do it on a “real” website.

Leave a Comment