Java Security Model Introduction __java

Source: Internet
Author: User
Tags file permissions

As a language born of the rise of the Internet, Java from the outset with security considerations, how to ensure that the download to the local Java program on the Internet is safe, how to access the Java program permissions to local resources Limited authorization, these security considerations from the outset to affect the Java The design and implementation of language. It can be said that Java in these aspects of exploration and experience, some of the later language and products have brought a positive impact.

This article will introduce the security model in Java and how to use secure access control mechanisms to achieve some specific goals. the security model in Java

In Java, the execution program is divided into two local and remote, and the local code is treated as trustworthy by default, while remote code is considered untrusted. For the local code of the credit, you can access all local resources. For non-credit remote code in the early Java implementation, security relies on the sandbox (Sandbox) mechanism. The sandbox mechanism is to limit the Java code to the specific operational scope of the virtual machine (JVM), and strictly restrict the code's access to the local system's resources, so as to ensure effective isolation of remote code and prevent damage to the local system. As shown in Figure 1, figure 1.jdk1.0 Security Model

But such stringent security mechanisms also pose obstacles to the extension of the program's functionality, such as when users want remote code to access files on the local system. As a result, improvements to the security mechanism have been made in subsequent Java1.1 releases, adding security policies that allow users to specify code access to local resources. As shown in Figure 2, figure 2.jdk1.1 Security Model

In the Java1.2 version, the security mechanism was again improved and code signing was added. Regardless of the local code or remote code, according to the user's security policy settings, the class loader loaded into the virtual machine in different permissions of the operating space, to achieve differentiated code execution rights control. As shown in Figure 3, figure 3.jdk1.2 Security Model

The current implementation of the latest security mechanism introduces the concept of domains (domain). Virtual opportunity loads all the code into different system domains and application domains, and the system domain is specifically responsible for interacting with critical resources, while the individual application domain sections are used by some agents of the system domain to access the various resources that are needed. Different protected domains (Protected domain) in the virtual machine, corresponding to the same permissions (Permission). Class files that exist in different domains have all the permissions of the current domain, as shown in Figure 4: Figure 4. The latest security model

All mentioned above are the basic Java security model concepts, and there are some complex uses of security in application development, the most commonly used API is doprivileged. The Doprivileged method enables a trusted code to gain greater permissions, even more than the application that invokes it, to temporarily access more resources. Sometimes this is very necessary to deal with some special application scenarios. For example, an application might not have direct access to some system resources, but such an application would have to have these resources to complete the function. In this case, the Java SDK provides a doprivileged method for the domain, allowing the program to break through the current domain permission restrictions and temporarily expand access rights. The following sections explain the use of security-related methods in detail.

Back to top Java security Control Implementation

Security-related classes and interfaces in the Java SDK are placed in the Java.security package, which includes both the access control configuration and the implementation of fine-grained access control frameworks, as well as signatures and encryption and decryption implementations. The security access control involved in this paper is mainly related to the access control framework in the security package, where the most commonly used is the Accesscontorller class. You can see how the ACC (Access contorller) mechanism works by using the following illustration.

In the call stack of one thread, when the Accesscontroller Checkpermission method is invoked by the most recent caller (for example, a method in Class A), the basic algorithm that ACC decides to authorize is as follows for all access rights required by the program:

1. If a calling program in the call chain does not have the required permissions, the accesscontrolexception is thrown;

2. Permission is granted if the following conditions are met:

A. The calling program accesses another method that has a program in that permission domain, and this method is marked as having access "privilege";

B. Subsequent objects invoked (directly or indirectly) by the calling program have these permissions.

In the call chain for the example above, it is assumed that the E and F fields do not have X permissions (permission), and that the G field corresponding to the C.class has X permissions, and that the C-Y method using X permission is implemented through Doprivilege. Then, B.class A.class calls the Y method with X permissions. If the Y method does not annotate Doprivilege, then the call to the Y method does not have X permissions.

Another special case is the inheritance problem of the access control context. When one thread creates another new thread, it creates a new stack at the same time. If the current security context, the thread-related security information, is not preserved when a new thread is created, the security access control mechanism will only determine security issues based on the context of the new thread when the new thread invokes the Accesscontroller.checkpermission validation permission. It does not consider the appropriate permissions for its parent thread. This cleanup stack does not in itself pose a security risk to the system, but it makes the source code, especially the system code, easy to write errors. For example, a programmer who is unfamiliar with the security framework implementation may naturally assume that the trust code executed by the child thread inherits the security-restrictive nature of the untrusted code executed by the parent thread. When a controlled resource is accessed from a agenda, an unexpected security vulnerability can result if the security context information for the parent thread is not saved. Because the security constraint data in the missing parent thread causes the child thread to pass the resource to some untrusted code. Therefore, when you create a new thread, you must make sure that you create it with a parent thread, or create code in other forms. In summary, to ensure that the child thread automatically inherits the parent thread's security context, subsequent accesscontroller.checkpermission calls in the thread take into account the security attributes of the inherited parent thread.

Note that the Checkpermission method of the Accesscontroller class will perform a security check in the context of the current executing thread, including the inherited context. The problem occurs when this security check can only be performed in a different context. That is, security checks that should be conducted within a thread context sometimes need to be performed in different contexts. For example, when a thread passes an event to another thread, if the requested event Service requires access to some security-controlled resource, the second thread for which the event Service is requested will have no event to produce the appropriate context for the source thread to complete the required access control decision. To solve this problem, Java provides getcontext methods and AccessControlContext objects in the Accesscontroller class. The GetContext method gets the snapshot (snapshot) of the current call context and then stores it in the returned AccessControlContext object. The sample program that is invoked looks like this: AccessControlContext acc = Accesscontroller.getcontext ();

The GetContext method captures snapshot information for the current context, and then executes the program to make decisions about access control for controlled resources by examining the information in different contexts, comparing snapshot context information with this context information. The problem can be solved as follows: The current thread passes a request event to the second thread while capturing its contextual information and providing it to the latter thread. Slightly differently, the Checkpermission method of the AccessControlContext class itself can determine access control based on the contextual information it carries, rather than on the currently executing thread context. When necessary, the latter thread can perform the appropriate security checks directly by invoking the permission-checking method of the previous thread context snapshot itself. as follows, Acc.checkpermission (permission), the method call above is equivalent to performing the same security check in the context of the previous thread, although the access control check is actually done in the latter thread.

Back to the top of the page code instance used for security control

The above description of security control usage is still more obscure, as described below by a code example.

Create two different projects in the Eclipse development environment: Projectx and Projecty. We give the bin directory in the PROJECTX project permission to write files, in other words, allow all class files that exist in this directory to be free to write files in the bin directory. Then, we will call a file Operation tool class in the PROJECTX project in the Projecty project. This tool class provides two types of interfaces, one is privileged access, the other is normal access. Since the files in the PROJECTY project do not have any write permission to the bin directory in the Projectx project, we can clearly understand how security controls in Java are used with the results of three different ways of accessing the call.

Assume that the PROJECTX project path is D:\workspace\projectX\

 Package learn.java.security; 
 Import Java.io.File; 
 Import java.io.IOException; 
 Import java.security.AccessControlException; 
 Import Java.security.AccessController; 

 Import java.security.PrivilegedAction; public class Fileutil {//Project a path to execute file private final static String Folder_path = "D:\\workspace\\projectx\\bin" 

    ; public static void MakeFile (String fileName) {try {//attempt to create a new file in the path of the execution file for project a files FS 
            = new File (Folder_path + "\" + fileName); 
        Fs.createnewfile (); 
        catch (Accesscontrolexception e) {e.printstacktrace (); 
        catch (IOException e) {e.printstacktrace (); } public static void Doprivilegedaction (final String fileName) {//Create file with privileged access Accesscontro 
                Ller.doprivileged (New privilegedaction<string> () {@Override public String run () { 
                MakeFile (FileName); ReturnNull 
    } 
        }); } 
 }

Assume that the Projecty project path is D:\workspace\projectY\

 Package demo.security; 
 Import Java.io.File; 
 Import java.io.IOException; 

 Import java.security.AccessControlException; 

 Import Learn.java.security.FileUtil; public class Demodoprivilege {public static void main (string[] args) {System.out.println ("*************** 
        ************************"); 

        System.out.println ("I'll show AccessControl functionality ..."); 
        SYSTEM.OUT.PRINTLN ("Preparation Step:turn on system permission check ..."); 
        Open the system security permission check switch System.setsecuritymanager (new SecurityManager ()); 

        System.out.println (); 
        System.out.println ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); 
        System.out.println ("Create a new file named Temp1.txt via privileged action ..."); 
        Create the Temp1.txt file Fileutil.doprivilegedaction ("Temp1.txt") in the execution file path of project A using privileged access mode; 
        System.out.println ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); 

        System.out.println (); System.out.printlN ("/////////////////////////////////////////"); 
        System.out.println ("Create a new file named Temp2.txt via file ..."); try {///Use normal file action to create Temp2.txt file in Project A execution file path files fs = new file ("D:\\work 
            Space\\projectx\\bin\\temp2.txt "); 
        Fs.createnewfile (); 
        catch (IOException e) {e.printstacktrace (); 
        catch (Accesscontrolexception E1) {e1.printstacktrace (); 
        } System.out.println ("/////////////////////////////////////////"); 

        System.out.println (); 
        System.out.println ("-----------------------------------------"); 
        System.out.println ("Create a new file named Temp3.txt via Fileutil"); 
        Directly invoke normal interface to create Temp3.txt file Fileutil.makefile ("Temp3.txt") in Project A execution file path; 
        System.out.println ("-----------------------------------------"); 

        System.out.println (); System.out.println ("***************************************"); } 
 }

The security access Control policy file (MyPolicy.txt) applied is as follows, assuming that the security policy file is placed under the root directory of the PROJECTY project:

Authorize Project A Execute file permissions in this directory for files in the file path
 Grant codebase "File:/d:/workspace/projectx/bin"
 { 
  permission Java.io.FilePermission 
    "d:\\workspace\\projectx\\bin\\*", "Write"; 
 };

You can run the program below, either directly in the Eclipse development environment or through the command line. The command line performs the following, assuming that the current execution directory is the root directory of the projecty.

Java-djava.security.policy=.\\mypolicy.txt-classpath 
 D:\workspace\projecty\bin;d:\workspace\projectx\bin Demo.security.DemoDoPrivilege

The

results are as follows:

 I'll show AccessControl functionality ... Preparation Step:turn on System permission check ... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Create a new file name D Temp1.txt via privileged action ... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~////////////////////////////////////// Create a new file named Temp2.txt via file ... java.security.AccessControlException:Access denied (java.io.FilePer Mission D:\workspace\projectX\bin\temp2.txt Write) at Java.security.AccessController.checkPermission (accesscontr oller.java:108) at Java.lang.SecurityManager.checkPermission (securitymanager.java:533) at Java.lang.SecurityManager.checkWrite (securitymanager.java:963) at Java.io.File.createNewFile (file.java:882) at Demo.security.DemoDoPrivilege.main (demodoprivilege.java:32)////////////////////////////////////////----------- -----------------------------Create a new file named Temp3.txt via Fileutil ... Java.secuRity. Accesscontrolexception:access denied (java.io.FilePermission D:\workspace\projectX\bin\temp3.txt write) at Java. Security. Accesscontroller.checkpermission (accesscontroller.java:108) at Java.lang.SecurityManager.checkPermission ( securitymanager.java:533) at Java.lang.SecurityManager.checkWrite (securitymanager.java:963) at Java.io.File.createNewFile (file.java:882) at Learn.java.security.FileUtil.makeFile (fileutil.java:16) at Demo.security.DemoDoPrivilege.main (demodoprivilege.java:43)----------------------------------------*********** ****************************

Through the results of the program printing, when the bin directory to the PROJECTX project to create temp1.txt,temp2.txt,temp3.txt files, in addition to access through the privileged way to create success, through the normal interface access or direct file operations will fail, The reason for failure is that permission checks are not passed. In contrast to the previous description of the rights check rules, summed up in a sentence is to access the security resources, or call the chain on the full authority, or use privileges. The privilege access mechanism is in fact to the application of the use of backdoor need to be careful, so this also brings new considerations to the implementation of the code, open range must be limited, otherwise it may leave a security risk.


Source: http://www.ibm.com/developerworks/cn/java/j-lo-javasecurity/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.