views:

199

answers:

3

I am working on a servlet (runs on tomcat) which receives requests that contains Java Script code, and using the java scripting API framework evaluates/run the code and returns the answer to the user.

Since we are dealing with user generated code, the code can be a good code and it can be bad code. As an example for a bad code can be while(true); which will endlessly loop in the server taking unnecessary resources

my questions

1) how can i discover a bad code? 2) once identified as a bad/malicious code what is the best way to stop the run?

thanks

+7  A: 

My question to you: what counts as bad code?

If you cannot come up with a formal definition of what counts as bad code, you cannot hope to be able to detect it. And since this is probably what your question really meant, I'll put forward my answer - there's no way to do it.

Even a seemingly trivial thing such as whether a program will terminate or not cannot be determined ahead of time, and I'd expect any definition of bad code would be something that couldn't terminate.

Thus to my mind you have one major option: trust your users (or alternatively don't trust them and don't run anything).

Something that might work otherwise is to run the script in a strict sandbox, and terminate it after an appropriate amount of time if it hasn't already finished running. It very much depends on your circumstances as to what is acceptable.

Andrzej Doyle
+1  A: 

There's already a tool that identifies 'bad' JavaScript, JSLint. Obviously the definition of bad code is highly subjective, but JSLint provides a wide range of options, so you should be able to configure it to conform fairly closely to your definition of bad.

You can submit code (and configuration options) to JSLint via the web form linked to above. It should also be possible to submit code (and options) to JSLint programatically, but you should get the author's permission if you plan to do this regularly.

Don
I took "bad" to mean "malicious"/"mischievous" as opposed to "poorly written".
Andrzej Doyle
+2  A: 

You are really jumping down the rabbit hole on this one. There is no way to determine in advance if code is resource intensive or has mailious intent. Even humans have a hard time with that. Having said that there are some things you can do to defend yourself.

  1. Use Rhino instead of Java 6's built-in JS scripting engine as it gives you more options.
  2. Implement a custom context that monitors instruction count. This gives you an opportunity to interrupt scripts that are infinitely looping. See Rhino's ContextFactory class
  3. run your scripts in a separate thread so that you can interrupt scripts stuck in in wait states that don't trigger the Context's intruction count
  4. Implement a security manager: see Overview, API. This will allow you to restrict the script to just those objects it should be interacting with.

I have implemented 1,2, and 3 in Myna and you are welcome to steal code

Mark Porter