Disclaimer: The old version of the question was confusing SecurityManager
and AccessController
. But now I know I've made a mistake and the question is refined.
The stem is pretty straight forward; I'm looking for a way to limit what a script can do in some ScriptEngine.
I've read some similar questions, old and new. There seems to be a solution for NashornScriptEngine
using a class called ClassFilter
. But I'm looking for a generic way regardless of their scripting engine implementation. Some suggest that Java's AccessController
is the way. So I've started to read and play with AccessController
, so far I've got this:
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
Permissions perms = new Permissions();
ProtectionDomain domain = new ProtectionDomain(new CodeSource( null, (Certificate[]) null ), perms);
AccessControlContext acc = new AccessControlContext(new ProtectionDomain[] { domain });
AccessController.doPrivileged(new PrivilegedAction() {
@Override
public Object run() {
try {
//I want the following line to throw a SecurityException
return engine.eval("var System = Java.type('java.lang.System'); print(System.getProperty('java.home'));");
}
catch (ScriptException e) {
e.printStackTrace();
}
return null;
}},
acc
);
//At the same time I want the following line to work
System.out.println(System.getProperty("java.home"));
And the script runs as if there's no AccessController involved!
So my question is; is AccessController
the way to do this? And if it is, then how should I do it?