views:

55

answers:

2

Running the following code, I get a StackOverflowError at the getPackage() line. How can I grant permission just to classes inside package I want, if I can't access the getPackage() to check the package?

package myPkg.security;

import java.security.Permission;

import javax.swing.JOptionPane;

public class SimpleSecurityManager extends SecurityManager {

    @Override
    public void checkPermission(Permission perm) {
 Class<?>[] contextArray = getClassContext();
 for (Class<?> c : contextArray) {
     checkPermission(perm, c);
 }
    }

    @Override
    public void checkPermission(Permission perm, Object context) {
 if (context instanceof Class) {
     Class clazz = (Class) context;
     Package pkg = clazz.getPackage(); // StackOverflowError
     String name = pkg.getName();
     if (name.startsWith("java.")) {
  // permission granted
  return;
     }
     if (name.startsWith("sun.")) {
  // permission granted
  return;
     }
     if (name.startsWith("myPkg.")) {
  // permission granted
  return;
     }
 }
 // permission denied
 throw new SecurityException("Permission denied for " + context);
    }

    public static void main(String[] args) {
 System.setSecurityManager(new SimpleSecurityManager());
 JOptionPane.showMessageDialog(null, "test");
    }

}
A: 

If you just want to restrict packages, how about implementing checkPackageAccess and/or checkPackageDefinition instead the generic checkPermission?

nicerobot
I'll add more code depending on the package
Tom Brito
Looks the OP is attempting to grant permission to those of specific packages names. Certainly if the is your policy, you don't want an adversary to insert classes in those packages(!). You probably don't want to put `java.*` under `package.access` (although you could if you wanted to provide your own API - without `Object` or `String`).
Tom Hawtin - tackline
A: 

Solved! Just add to the begin of the first checkPermission method:

if (perm instanceof FilePermission) {
    if (perm.getActions().equals("read")) {
    // grant permission
    return;
    }
}
Tom Brito