Is 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

How to make java 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.

This Core Java tutorial was added on 22/03/2010.

Comments on "Is Your Java Code Privileged?" Tutorial:

  1. Baptiste Wicht says:

    Interesting, thanks.

    Using doPrivileged method in an applet, can I write files to the system if the applet is not signed ?

  2. […] getUnsafe which returns the unsafe object. Java’s security manager asks you to make your java source code privileged. I used little bit of reflection and got an instance out. I know there are better ways to get the […]

  3. Anand Garlapati says:

    How to create a policy file for an applet? Can you post one article on policy files?

    Thanks
    Anand Garlapati

  4. kishor says:

    Hi man,

    good work..keep it up.

    It’s just an amazing blog..

  5. Prem Kumar says:

    Thanks for this blog.
    Its very helpful.

    Saved my time

Comments are closed for this "Is Your Java Code Privileged?" tutorial.