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
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.