views:

138

answers:

5

Assume I have a webpage where people submit java source code (a simple class). I want to compile and run the code on my server, but naturally I want to prevent people from harming my server, so how do I disable java.io.* and other functions/libraries of my choice?

A regexp on the source code would be one way, but it would be "nicer" if one could pass some argument to javac or java.

(This could be useful when creating an AI competition or something where one implements a single class, but I want to prevent tampering with the java environment.)

+6  A: 

Hi Paxinum. If you are in complete control of the JVM, then you can use security policies to do this. It's the same approach taken by web browsers when they host applets.

http://java.sun.com/j2se/1.5.0/docs/guide/security/permissions.html

Hope this helps.

Matt Solnit
+2  A: 

Depending on your intent, you might be able to speak with Nick Parlante, who runs javabat.com - it does pretty much exactly what you're describing. I don't know whether he's willing to share his solution, but he might be able to give you some specific help.

CPerkins
In that case, users are very limited. IIRC you can't even do import statements at all. So it may be that his solution is quite simple, but it's definitely worth finding out.
MatrixFrog
+2  A: 

My advice is don't do it. At least, don't do it unless you are willing and prepared to accept the consequences of the machine that runs your server being hacked. And maybe other machines on the same network.

Stephen C
Java IS supposed to be able to provide this level of security as per @Matt's answer, so I'd say if you know what you are doing this is a very legitimate thing to do.
Bill K
But UNLESS you know what you are doing ... don't. And if you are not prepared to live with the consequences of getting it wrong ... don't.
Stephen C
A: 

The Google App Engine uses an approach where classes are white listed - that is, they are probably either not loaded, or the classes themselves changed and the libraries recompiled, so that no IO, or other system calls can be made. perhaps you could try this by recompiling a jvm like http://jikesrvm.org/.

Chii
A: 

You can always run the code in a custom classloader. This allows you full control about what you will accept to load.

Thorbjørn Ravn Andersen