"Java Security Technology Exploration Path series: J2SE security Architecture" II: Security Manager

Source: Internet
Author: User

Guo Jia
Email: [Email protected]
Blog: http://blog.csdn.net/allenwells
Github:https://github.com/allenwell

Functions of a security manager

A security manager is a class that allows a program to implement a security policy that checks the access rights of resources that need to be protected and other operational permissions that it requires to protect the system from malicious operations in order to achieve the security policy of the system during the run phase.

The security Manager is responsible for checking the operations that are mainly included in the following:

    • To create a new class loader
    • Exiting a virtual machine
    • Using reflection to access members of another class
    • accessing local connections
    • Open the Socket connection
    • Start a print job
    • Accessing the system Clipboard
    • Accessing the AWT event queue
    • Open a top-level window

Note : When running a Java application, the default setting is to not install the security Manager so that all operations are allowed,

The workflow for the security manager is as follows:

Use of a security manager 1.1 get security Manager
Security security = System.getSecurityManager();
1.2 Start the Security Manager 1.2.1 command line startup
java -Djava.security.manager class_name
1.2.2 Program Startup

You can specify a security policy file by using the-djava.security.policy option when you start the security manager. If you do not specify a path to the policy file, the Security Manager uses the default security policy file, which is located in Java.policy under the %java_home%/jre/lib/security directory.

Note :

    • = indicates that the policy file will work with the default policy file.
    • = = indicates that only this policy file is used.

The policy file contains more than one grant statement, and each grant describes the permissions that some code has for certain operations. When you start the Security Manager, a policy object is generated based on the policy file, and at any time an application can have only one policy object .

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

The default%java_home%/jre/lib/security/java.policy file contents are as follows:

Standard extensions get all permissions by Defaultgrant CodeBase"file:${{java.ext.dirs}}/*"{Permission Java. Security. Allpermission;};Default permissions granted to all Domainsgrant {//allows any thread to stop itself using the Java. Lang. Thread. Stop()//method that takes no argument.        Note that this permission is granted by default for the remain//backwards compatible. It is strongly recommended so either remove this permission//from the This policy fileorFurther restrict it to code sources//So you specify, because Thread. Stop() is potentially unsafe. See the API specification of Java. Lang. Thread. Stop() for more//information. Permission Java. Lang. Runtimepermission "Stopthread";Allows anyone to listen on dynamic ports permission Java. NET. SocketPermission "localhost:0","Listen";//"Standard"Properies that can is read by anyone permission Java. Util. Propertypermission "Java.version","read";Permission Java. Util. Propertypermission "Java.vendor","read";Permission Java. Util. Propertypermission "Java.vendor.url","read";Permission Java. Util. Propertypermission "Java.class.version","read";Permission Java. Util. Propertypermission "Os.name","read";Permission Java. Util. Propertypermission "Os.version","read";Permission Java. Util. Propertypermission "Os.arch","read";Permission Java. Util. Propertypermission "File.separator","read";Permission Java. Util. Propertypermission "Path.separator","read";Permission Java. Util. Propertypermission "Line.separator","read";Permission Java. Util. Propertypermission "Java.specification.version","read";Permission Java. Util. Propertypermission "Java.specification.vendor","read";Permission Java. Util. Propertypermission "Java.specification.name","read";Permission Java. Util. Propertypermission "Java.vm.specification.version","read";Permission Java. Util. Propertypermission "Java.vm.specification.vendor","read";Permission Java. Util. Propertypermission "Java.vm.specification.name","read";Permission Java. Util. Propertypermission "Java.vm.version","read";Permission Java. Util. Propertypermission "Java.vm.vendor","read";Permission Java. Util. Propertypermission "Java.vm.name","read";};
1.3 Close the Security manager
SecurityManager sm=System.getSecurityManager();if(sm!=null){    System.setSecurityManager(null);}

The above code will only take effect if a permission is specified in the {jdk_home}/jre/lib/security directory or in a Java.policy file under another specified directory.

This permission is:

permission java.lang.RuntimePermission"setSecurityManager";
1.4 Security Manager Check
security.checkXXX(...);

After the check is complete, the security manager returns, fails, and the security manager throws SecurityException, noting that the only exception to this convention is Checktoplevelwindow, which returns a Boolean value .

1.5 Security Manager Permission check

The default implementation of all other check () methods in the security manager is to call the Securitymanager.checkpermission () method to determine whether the thread has permission to perform the requested operation.

The checkpermission () method with only a single permission parameter always performs a security check in the context of the currently executing thread.

If checking in a given context needs to be done in a different context, you can use the GetSecurityContext () method and the Checkpermission () method, which contains the context parameters provided by Java, as follows:

null;SecurityManager sm = System.getSecurityManager();ifnull){    context = sm.getSecurityContext();//该方法返回当前调用上下文的一个快照    sm.checkPermission(permission, context);//该方法使用一个上下文对象,以及根据该上下文(不是当前执行线程的上下文)作出访问决策的权限。}

Permissions fall into the following categories:

    • File
    • Sockets
    • Internet
    • Security
    • Run-time
    • Property
    • Awt
    • Reflection
    • Serializable

The corresponding permission classes are:

    • Java.io.FilePermission
    • Java.net.SocketPermission
    • Java.net.NetPermission
    • Java.security.SecurityPermission
    • Java.lang.RuntimePermission
    • Java.util.PropertyPermission
    • Java.awt.AWTPermission
    • Java.lang.reflect
    • Reflectpermission
    • Java.io.SerializablePermission

The hierarchy of the entire permission class is as follows:

Here is an example to illustrate the use of a custom security manager.

import  Java.io.FileInputStream; import  java.io.FileNotFoundException; public  class  securitymanagerdemo  { public  static  void  main  (string[] args) throws  filenotfoundexception {System.out.println ( + Syst         Em.getsecuritymanager ()); FileInputStream FIS = new  fileinputstream ( "C:\\Users\\         Administrator\\my.txt ");    System.out.println (System.getproperty ()); }}

Note : My.txt is a file that already exists and needs to be created in your directory, where the directory is C:\Users\Administrator.

Run directly

Run Securitymanagerdemo directly, the equivalent of no boot security manager, SecurityManager print out null, and can read the Protect.txt file and File.encoding properties correctly. As shown in the following:

Add startup parameters to run

Add Startup Parameters

-Djava.security.manager -Djava.security.policy=C:\\Users\\Administrator\\my.policy//自定义策略文件

Specifies the-djava.security.manager parameter, at which point the SecurityManager prints out as no authorization for null,my.policy, so the accesscontrolexception exception is thrown when the file is read, as shown in:

Create the my.policyand write to the following grant:

grant {permission java.io.FilePermission"C:\\Users\\Administrator\\my.txt""read";permission java.util.PropertyPermission"file.encoding""read";};

This can be read correctly, as shown in the following:

Three implementation of custom security Manager

Implementing a custom security manager generally consists of two steps:

    1. Create a SecurityManager subclass and override some methods as needed.
    2. The policy file is configured according to the permissions of the application code.

Here's an example to illustrate the use of a custom security manager:

The custom class Mysecuritymanager inherits from SecurityManager, overriding the Checkread () method.

publicclass MySecurityManager extends SecurityManager {      @Override      publicvoidcheckRead(String file)     {          //super.checkRead(file, context);          if (file.endsWith("not"))         {            thrownew SecurityException("你没有读取的本文件的权限");            }               }  }  

Write a test class Mysecuritymanagerdemo see if Mysecuritymanager is useful.

import  java.io.FileInputStream; import  java.io.IOException; public  class  mysecuritymanagerdemo  { public  static  void  main  (string[] args) {System.setsecuritymanager (  new Mysecuritymanager ()); try  {FileInputStream FIS = new  fileinputstream (  "not" ); System.out.println (Fis.read ()); } catch  (IOException e) {e.printstacktrace (); } } } 

After the run is finished, the output prints "You do not have permission to read this file", stating that Mysecuritymanager can be used as shown in the results:

"Java Security Technology Exploration Path series: J2SE security Architecture" II: Security Manager

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.