Turn on SecurityManager in Java

  Pi Ke        2013-12-16 05:03:53       8,396        0    

SecurityManager in Java is to check whether the application codes can access some restricted resource such as file, socket etc. This can be used in applications which have high security requirements. With this feature turned on, our system resources can be secured with only permitted operations.

When JVM starts, it will first check whether the SecurityManager is on by checking the system property java.security.manager, if it's on, then an instance of SecurityManager will be created and it can be used to check different permissions. By default the security manager is off, but there are a few ways we can turn on SecurityManager.

1. Specify -Djava.security.manager

When we run a program, we can specify the JVM command -Djava.security.manager to enable the SecurityManager.

java -Djava.security.manager <class_name>

This is the most common way to turn on the SecurityManager. java.security.manager is a system property, you can using System.getProperty("java.security.manager") to check whether the system property is set. Here you may think, we can use System.setProperty("java.security.manager") to turn on SecurityManager, while this is not the case for SecurityManager as we mentioned previously this system property is checked when the JVM starts. If we set the property manually within the program, it will have no effect as the JVM has already started and passed the step checking the system property.

2. Turn on SecurityManager programmably

Now if we really want to turn on the SecurityManager in we programs, we can also achieve this. There is a method in the System class called setSecurityManager() which can do this. The parameter to this method is a SecurityManager instance.

SecurityManager sm=new SecurityManager();
System.setSecurityManager(sm);

With this, we can turn on the SecurityManager. If later we want to turn off the SecurityManager, what should we do? Will below codes work?

SecurityManager sm=System.getSecurityManager();
if(sm!=null){
    System.setSecurityManager(null);
}

The above codes will work only if you also specified a permission in the java.policy file located at ${JAVA_HOME}/lib/security or the location you specified. The permission is:

permission java.lang.RuntimePermission "setSecurityManager";

The above line will allow code to set security manager in use.

3. In a build file

If we want to turn on SecurityManager while we are using Ant to build an application, we can put

<sysproperty key="java.security.manager" value="" />

This is useful when we create unit test cases with Ant

SECURITYMANAGER  ENABLE  PROGRAM 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

Load balancing