Search code examples
javasecuritygoogle-app-enginepolicyclassloader

Can i deny access to a jvm class by configuring java.policy file?


I wanted to add to my jdk6\jre\lib\security\java.policy file an interdiction to create some classes that are blacklisted by appengine. For example I want my local jvm to throw an exception when the application tries to instantiate javax.naming.NamingException.

It is possible?

I will try to explain my specific problem here. Google offers an service (GAE-google app engine) that has some limitations on what classes can be used. For example doesn't instantiate JNDI classes that are in javax.naming package. They also offer an testing server that can be used to tests this application on my machine, but this server allows such classes and can exacute the code. You find out that you used a blacklisted class only after you upload your application to google. I was thinking if such class blacklist enforcement couldn't be done on the development jvm. Else i'm thinking that this would be easy they might already provide such a policy file.


Solution

  • You could write a small loader application that creates a new, custom classloader. Your application classes could then be loaded using this classloader.

    In the custom classloader, you can then throw ClassNotFoundException when your application tries to access a class that you want to blacklist.

    You will need to overload the load() method. This method will be responsible for throwing the exception on your blacklisted classes ordelegating to the parent Classloader if the class is allowed. A sample implementation:

    public Class loadClass(String name) throws ClassNotFoundException {
        if(name.equals("javax.lang.ClassIDontLike")){
           throw new ClassNotFoundException("I'm sorry, Dave. I'm afraid I can't do that.");
        }
        return super.loadClass(name, false);
    }
    

    (Of course, a real implementation can be way more sophisticated than this)

    Because the classes of your application are loaded through this Classloader, and you are only delegating the loadClass() invokations to the parent classloader when you want to, you can blacklist any classes that you need.

    I am pretty sure that this is the method that Google uses to blacklist classes in their server. They load every app in a specific Classloader. This is also similar to the way that Tomcat isolates the different Web Applications.