Strange behaviour of AccessController.checkPermiss

2019-08-10 21:47发布

问题:

I am trying to learn about Java's permission model. I tried this sample code:

public static void main(String[] args) {
  File file = new File("/etc/passwd");
  try (BufferedReader reader = new BufferedReader(new FileReader(file));) {
    reader.lines().forEach(s -> System.out.println(s));
  } catch (IOException e) {
    e.printStackTrace();
  }
  FilePermission perm = new FilePermission("/etc/passwd", "read");
  AccessController.checkPermission(perm); // throws Exception
}

This prints the contents of /etc/passwd fine, but throws an exception in the end:

Exception in thread "main" java.security.AccessControlException: access denied ("java.io.FilePermission" "" "read")

Why is it that the file read works fine, but a check for the permission gives a negative result?

回答1:

Likely because the JVM doesn't have a SecurityManager configured. Without a SecurityManager configured there will be no AccessController call made.

http://docs.oracle.com/javase/8/docs/technotes/guides/security/spec/security-spec.doc6.html#a19349



回答2:

There's nothing strange here, this is exactly the behavior specified in the javadoc. The checkPermission method will throw if the permission is not granted:

Throws: AccessControlException - if the specified permission is not permitted, based on the current security policy.

while the constructor for FilePermission will not throw if the specified permission is not granted, but only when the input is invalid:

Throws: IllegalArgumentException - If actions is null, empty or contains an action other than the specified possible actions.