Sunday, April 17, 2011

Making your Java Code Privileged?

The java system code that is part of the JDK is considered God and has all the maximum privileges. For example it can read a system property by default. To easily understand it is better to consider java Applets. An Applet cannot read a system property by default because it belongs to different CodeSource and not in same domain as system code. Recall that the system code has all privileges.

Then what do you need to do for Applet to get that privilege? You need to explicitly grant those security privileges by creating a policy file. In that policy you specify what are all the privileges you are granting.

There is another option also. It is opposite of the above. You say that this code doesn’t require any security policy and it is privileged to do the same (anything) as system code. Do you smell something evil here? This is a risky thing to do. Giving away the security is OS dependent. “Privileged code + malicious user + hole in OS” will be a worst thing to tackle.

Therefore you need to keep the code block as minimum as possible, for which you are going to give privilege. You might require this in the following scenarios :


  • To read a file
  • To read a system property
  • To create a network connection to the local machine
  • To get direct access to files that contain fonts

Making you code privileged -
anyMethod() {
        ...other java code here...
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                // put the privileged code here, example:
                System.loadLibrary("awt");
                return null; // in our scenario nothing to return
            }
        });
       ...other code continues...
  }

AccessController API explains more about java privileged code and examples.



No comments:

Post a Comment

Chitika