Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

I'm planning on throwing together a quick web page for my students to teach them about JavaScript programming. On this page, I'd like to give them a text box and allow them to run JavaScript so that they can see the dynamic nature of the language at work. However, I'm well aware that using eval() on user input is usually a really bad idea. What kind of security risks am I taking on by publishing a page like this? What steps should I take to mitigate these risks?

like image 973
Spitfire Avatar asked Oct 30 '09 17:10

Spitfire


3 Answers

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.

like image 147
Andrzej Doyle Avatar answered Oct 09 '22 06:10

Andrzej Doyle


It will be running on their own machine. Just don't let them save strings and send to other people -- also don't put the values in the URL via a GET (so that it can be emailed).

like image 38
Lou Franco Avatar answered Oct 09 '22 04:10

Lou Franco


I would recommend you to sandbox all the user input evaling, to prevent the evaluated code to access all of the global (window) object properties and methods.

Give a look to the following resources:

  • Sandboxing JavaScript Using <iframe>
  • google-caja
like image 40
Christian C. Salvadó Avatar answered Oct 09 '22 04:10

Christian C. Salvadó