javasecuritypolicyprincipal

Java System.setSecurityManager() doesn't work well with policy file


I expected that, when use System.setSecurityManager() + policy file, it should work.

Here I've got an intelliJ project, with file/directory structure like this:

--src
    --main
       --java
           --TestPrinciple.java
       --resources
           --demo.policy

And then my code:

public class TestPrincipal {
    public static void main(String[] args) {
        System.setProperty("java.security.policy", "demo.policy");
        System.setProperty("java.security.auth.login.config", "demo.config");
        System.out.println(System.getProperty("java.home"));
        System.setSecurityManager(new SecurityManager());
    }
}

While the demo.policy is:

grant  {
    permission java.util.PropertyPermission "java.home", "read";
};

It runs with exception:

Exception in thread "main" java.security.AccessControlException: access denied ("java.util.PropertyPermission" "java.security.policy" "write")
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:472)
at java.security.AccessController.checkPermission(AccessController.java:884)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
at java.lang.System.setProperty(System.java:792)
at TestPrincipal.main(TestPrincipal.java:6)

Solution

  • Presumably demo.policy doesn't allow the classes permissions to set system properties.

    It's also worth noting that the code sets configuration for the security manager after the security manager has been initialised.

    The simple solution is to set the security manager last.