Search code examples
javascriptsecurityevaljslint

How do I safely "eval" user code in a webpage?


I'm working on a webapp to teach programming concepts. Webpages have some text about a programming concept, then let the user type in javascript code into a text editor window to try to answer a programming problem. When the user clicks "submit", I analyse the text they've typed to see if they have solved the problem. For example, I ask them to "write a function named f that adds three to its argument".

Here's what I'm doing to analyse the user's text:

  1. Run JSLint on the text with strict settings, in particular without assuming browser or console functions.
  2. If there are any errors, show the errors and stop.
  3. eval(usertext);
  4. Loop through conditions for passing the assignment, eval(condition). An example condition is "f(1)===4". Conditions come from trusted source.
  5. Show passing/failing conditions.

My questions: is this good enough to prevent security problems? What else can I do to be paranoid? Is there a better way to do what I want?

In case it is relevant my application is on Google App Engine with Python backend, uses JQuery, has individual user accounts.


Solution

  • So from what I can tell if you are eval'ing a user's input only for them, this isn't a security problem. Only if their input is eval'd for other users you have a problem.

    Eval'ing a user's input is no worse than them viewing source, looking at HTTP headers, using Firebug to inspect JavaScript objects, etc. They already have access to everything.

    That being said if you do need to secure their code, check out Google Caja http://code.google.com/p/google-caja/