user13806035
user13806035

Reputation:

Changing security policy properties at runtime

Here is my policy file

grant {
    permission java.util.PropertyPermission "*", "read,write";
    permission java.lang.RuntimePermission "createClassLoader";
    permission java.lang.RuntimePermission "setSecurityManager";
    permission java.lang.RuntimePermission "createSecurityManager";
};

Here is the test case:

System.setProperty("java.security.policy", SECURITY_POLICY_BASEDIR + "/create-classloader.policy");
System.setSecurityManager(new SecurityManager());
System.getSecurityManager().checkCreateClassLoader();

System.setProperty("java.security.policy", "default"); // change policy at runtime
System.setSecurityManager(new SecurityManager());
System.getSecurityManager().checkCreateClassLoader(); // expecting a "AccessControlException"

I am expecting a AccessControlException at the last line in snippet 2. Any pointers?

Upvotes: 1

Views: 1413

Answers (1)

Holger
Holger

Reputation: 298153

When the security API was reworked between JDK 1.0 and JDK 1.1, direct instances of the SecurityManager class became a façade. The check methods delegate to AccessController.checkPermission(…) and constructing a new instance of SecurityManager has no effect at all, as these object do not encapsulate any state.

The AccessController class in turn delegates to the current Policy. Policies can change; there’s also a refresh() method to reload the current policy file. But accessing the Policy requires additional permissions.

So when you change your code to

System.setProperty("java.security.policy", SECURITY_POLICY_BASEDIR + "/create-classloader.policy");
System.setSecurityManager(new SecurityManager());
System.getSecurityManager().checkCreateClassLoader();

System.setProperty("java.security.policy", "default"); // change policy at runtime
Policy.getPolicy().refresh();
System.getSecurityManager().checkCreateClassLoader(); // expecting a "AccessControlException"

and add the line

    permission java.security.SecurityPermission "getPolicy";

to your initial policy file, you get your desired java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "createClassLoader") at the second invocation of checkCreateClassLoader().

Upvotes: 4

Related Questions