`

Security Managers and Permissions

阅读更多

Once a class has been loaded into the virtual machine and checked by the verifier, the second security mechanism of the Java platform springs into action: the security manager. The security manager is a class that controls whether a specific operation is permitted. Operations checked by the security manager include the following:

  • Creating a new class loader

  • Exiting the virtual machine

  • Accessing a field of another class by using reflection

  • Accessing a file

  • Opening a socket connection

  • Starting a print job

  • Accessing the system clipboard

  • Accessing the AWT event queue

  • Bringing up a top-level window

There are many other checks such as these throughout the Java library.

The default behavior when running Java applications is that no security manager is installed, so all these operations are permitted. The applet viewer, on the other hand, enforces a security policy that is quite restrictive.

For example, applets are not allowed to exit the virtual machine. If they try calling the exit method, then a security exception is thrown. Here is what happens in detail. The exit method of the Runtime class calls the checkExit method of the security manager. Here is the entire code of the exit method:

 

public void exit(int status)
{
   SecurityManager security = System.getSecurityManager();
   if (security != null)
       security.checkExit(status);
   exitInternal(status);
}

 

The security manager now checks if the exit request came from the browser or an individual applet. If the security manager agrees with the exit request, then the checkExit method simply returns and normal processing continues. However, if the security manager doesn't want to grant the request, the checkExit method throws a SecurityException.

The exit method continues only if no exception occurred. It then calls the private native exitInternal method that actually terminates the virtual machine. There is no other way of terminating the virtual machine, and because the exitInternal method is private, it cannot be called from any other class. Thus, any code that attempts to exit the virtual machine must go through the exit method and thus through the checkExit security check without triggering a security exception.

Clearly, the integrity of the security policy depends on careful coding. The providers of system services in the standard library must always consult the security manager before attempting any sensitive operation.

The security manager of the Java platform allows both programmers and system administrators fine-grained control over individual security permissions. We describe these features in the following section. First, we summarize the Java 2 platform security model. We then show how you can control permissions with policy files. Finally, we explain how you can define your own permission types.

 

JDK 1.0 had a very simple security model: Local classes had full permissions, and remote classes were confined to the sandbox. Just like a child that can only play in a sandbox, remote code was only allowed to paint on the screen and interact with the user. The applet security manager denied all access to local resources. JDK 1.1 implemented a slight modification: Remote code that was signed by a trusted entity was granted the same permissions as local classes. However, both versions of the JDK provided an all-or-nothing approach. Programs either had full access or they had to play in the sandbox.

 

A code source is specified by a code base and a set of certificates. The code base specifies the origin of the code. For example, the code base of remote applet code is the HTTP URL from which the applet is loaded. The code base of code in a JAR file is a file URL. A certificate, if present, is an assurance by some party that the code has not been tampered with. We cover certificates later in this chapter.

A permission is any property that is checked by a security manager. The Java platform supports a number of permission classes, each of which encapsulates the details of a particular permission. For example, the following instance of the FilePermission class states that it is okay to read and write any file in the /tmp directory.

 

FilePermission p = new FilePermission("/tmp/*", "read,write");

 

More important, the default implementation of the Policy class reads permissions from a permission file. Inside a permission file, the same read permission is expressed as

 

permission java.io.FilePermission "/tmp/*", "read,write";

 

In the preceding section, you saw that the SecurityManager class has security check methods such as checkExit. These methods exist only for the convenience of the programmer and for backward compatibility. They all map into standard permission checks. For example, here is the source code for the checkExit method:

 

public void checkExit()
{
   checkPermission(new RuntimePermission("exitVM"));
}

 

====================================================================

The policy manager reads policy files that contain instructions for mapping code sources to permissions. Here is a typical policy file:

grant codeBase "http://www.horstmann.com/classes"
{
   permission java.io.FilePermission "/tmp/*", "read,write";
};

 

 

This file grants permission to read and write files in the /tmp directory to all code that was downloaded from http://www.horstmann.com/classes.

You can install policy files in standard locations. By default, there are two locations:

  • The file java.policy in the Java platform home directory

  • The file .java.policy (notice the period at the beginning of the file name) in the user home directory

During testing, we don't like to constantly modify the standard policy files. Therefore, we prefer to explicitly name the policy file that is required for each application. Place the permissions into a separate file, say, MyApp.policy. To apply the policy, you have two choices. You can set a system property inside your applications' main method:

System.setProperty("java.security.policy", "MyApp.policy");

 

Alternatively, you can start the virtual machine as

 

java -Djava.security.policy=MyApp.policy MyApp

 

 

For applets, you instead use

 

appletviewer -J-Djava.security.policy=MyApplet.policy MyApplet.html

 

 

(You can use the -J option of the appletviewer to pass any command-line argument to the virtual machine.)

In these examples, the MyApp.policy file is added to the other policies in effect. If you add a second equal sign, such as

 

java -Djava.security.policy==MyApp.policy MyApp

 

 

then your application uses only the specified policy file, and the standard policy files are ignored.

 

As you saw previously, Java applications by default do not install a security manager. Therefore, you won't see the effect of policy files until you install one. You can, of course, add a line

 

System.setSecurityManager(new SecurityManager());

 

 

into your main method. Or you can add the command-line option -Djava.security.manager when starting the virtual machine.

 

java -Djava.security.manager -Djava.security.policy=MyApp.policy MyApp

 

In the remainder of this section, we show you in detail how to describe permissions in the policy file. We describe the entire policy file format, except for code certificates, which we cover later in this chapter.

A policy file contains a sequence of grant entries. Each entry has the following form:

 

grant codesource
{
   permission1;
   permission2;
   . . .
};

 

The code source contains a code base (which can be omitted if the entry applies to code from all sources) and the names of trusted principals and certificate signers (which can be omitted if signatures are not required for this entry).

The code base is specified as

 

codeBase "url"

 

If the URL ends in a /, then it refers to a directory. Otherwise, it is taken to be the name of a JAR file. For example,

grant codeBase "www.horstmann.com/classes/" { . . . };
grant codeBase "www.horstmann.com/classes/MyApp.jar" { . . . };

 

The code base is a URL and should always contain forward slashes as file separators, even for file URLs in Windows. For example,

grant codeBase "file:C:/myapps/classes/" { . . . };

 

 

================================================================

Here is a sample on it:

 

policy.policy reside in the "user.dir" directory under src like this :

 

grant {
	permission java.io.FilePermission "${user.dir}${/}-", "read,delete,execute";
};

 

SecurityTest.java

package com.tojaoomy.security;

import java.io.File;

public class SecurityTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//before the securityManger is enabled,this call is possible
		System.out.println(System.getProperty("user.dir"));
		System.setProperty("java.security.policy", "src/policy.policy");
		System.setSecurityManager(new SecurityManager());
		
//		SecurityManager manager = System.getSecurityManager();
		File file = new File("test.test");
//		file.delete();
		//this call is no more possible ;an AccessControlException  is throw
		//by default,securityManager can't not inspect the java.util.PropertyPermission
		// so you must customize the policy files
		System.out.println(System.getProperty("user.dir"));

 

As mention previously, you should add the contents like this :

 

permission java.util.PropertyPermission "user.dir", "read";

 

Then policy.policy complete contents are :

 

grant {
	permission java.io.FilePermission "${user.dir}${/}-", "read,delete,execute";
	permission java.util.PropertyPermission "user.dir", "read";
};

 

 

Obviously,alternative,customize the permissions.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics