I am working on a project where I will let users submit small 'scripts' to the server, and I will execute those scripts. There are many scripting languages which can be embedded into a Java program, such as mvel, ognl, uel, clojure, rhino javascript, etc., but, as far as I can tell, they all allow script writer to call Java constructors, static methods, etc.
I don't want my users to be able to call anything which I don't provide them (usually through some sort of context object). Most of their scripts will be arithmetic and logical expressions, in some cases they will need to traverse object properties (getters/setters) or contents of a Map. I just don't want them to escape the sandbox I provide them.
Any suggestions?
Just :
//Remember old one
ClassLoader orginalClassLoader = Thread.currentThread().getContextClassLoader();
//Set my classloader
ClassLoader myClassLoader = new SecureMVELClassLoader();
Thread.currentThread().setContextClassLoader(myClassLoader);
System.out.println(MVEL.eval("new com.myapp.insecure.InsecureClass()"));
//Set back to original classloader
Thread.currentThread().setContextClassLoader(orginalClassLoader);
and in my classLoader
public class SecureMVELClassLoader extends ClassLoader {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
//some filter logic here
if (name.startsWith("com.myapp.insecure.")) throw new ClassNotFoundException();
return super.loadClass(name);
}
Constructing a functioning sandbox is difficult. What you can do use a custom class loader that only allows lookups to a select few types from its parent.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.