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?
So I managed to fix the problem here myself. After reading a little more, I found out that the
AccessController
has no effect if theSecurityManager
is not activated. And here's how you activate it:Add two VM options:
-Djava.security.manager -Djava.security.policy=security.policy
Create a
security.policy
file in the project's root folder, with the following content:grant { permission java.security.AllPermission; };
This will activate the
SecurityManager
for your project and grant it all the permissions. In other words, it will just activateSecurityManager
but your code will work as before. Now you can control parts of application's access control using the code given above.