Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
class SensitiveHash {
  Hashtable<Integer,String> ht = new Hashtable<Integer,String>();

  void removeEntry(Object key) {
    check("removeKeyPermission");
    ht.remove(key);    
  }

  private void check(String directive) {
    SecurityManager securitysm = System.getSecurityManager();
      if (securitysm != null) {
        securitysm.checkSecurityAccess(directive);
      }
  }
}

...

Two methods, checkPermission(Permission perm) and checkPermission(Permission perm, Object context) were added to the SecurityManager class in J2SE 1.2. The motivations for this change were manifold:

  • The checkPermission() methods eliminated the requirement of hardcoding names of the checks in the method name.
  • They used only one copy of the complicated algorithms and code for examining the Java runtime by using a common checkPermission() method.
  • Newer permissions for resources could be easily added by encapsulating them in a new Permission subclass.

The single argument checkPermission() method uses the context of the currently executing thread environment to perform the checks. If the context has the permission as permissions defined in the local policy file, the check succeeds, otherwise a SecurityException is thrown.

This compliant solution shows the single argument checkPermission() method and allows files in the local directory, with the dtd extension, to be read. DTDPermission is a custom permission that enforces this level of access (See SEC08-J. Define custom security permissions for fine grained security for details on creating custom permissions). Even if the java.io.FilePermission is granted to the application with the action "read", DTD files will be subject to additional access control.

...

There is also another (cleaner and preferable) way to handle the security check from a different context. This is accomplished by taking a snapshot of the current execution context using the java.security.AccessController.getContext() method that returns an AccessControlContext object. The AccessControlContext class itself defines a checkPermission() method that encapsulates a context instead of accepting the current executing context as a parameter. This is shown below.

Code Block
bgColor#ccccff
// Take the snapshot of the required context, store in acc and  pass it to another context
AccessControlContext acc = AccessController.getContext(); 

// Accept acc in another context and invoke checkPermission() on  it
acc.checkPermission(perm); 

...