Wednesday, June 11, 2008

Limiting permissions to Java programs with policies

I wanted to limit the permissions for a Java program to only connect to a certain host.. and the way to do this is by defining your own policy file, and passing this as an argument to the Java command as follows:

temp.policy
grant {
//permission java.net.SocketPermission "69.147.112.160:80","connect,resolve";
permission java.io.FilePermission "<>", "read, write, delete, execute";
permission java.util.PropertyPermission "*", "read, write";
permission java.lang.RuntimePermission "*";
permission java.lang.reflect.ReflectPermission "*";
};

The above policy will not grant the process any SocketPermissions, however, if you only wanted it to connect to a specific IP address or hostname, you can uncomment the first line, and edit it appropriately.

For more information refer to: http://java.sun.com/developer/onlineTraining/Programming/JDCBook/appA.html

Now to start your program using the above policy file, use:

java -cp some.jar -Djava.security.manager -Djava.security.policy=temp.policy MainClass

No comments: