Java Basic Series--securitymanager Getting Started

Source: Internet
Author: User
Tags stack trace disk usage

Reproduced works, can be reproduced, but please mark the source address: http://www.cnblogs.com/yiwangzhibujian/p/6207212.html

First, the purpose of the article

This is an introduction to the Java Security Manager, with the purpose of simply understanding what SecurityManager is, and simply configuring the manager to solve simple problems.

For example, when reading the source code, the discovery of such codes, want to know what to do:

1 SecurityManager security = System.getsecuritymanager (); 2 if NULL {3    security.checkwrite (name); 4 }

Or in the local operation is normal, the server run an error, want to solve the problem:

1Exception in thread "main"Java.security.AccessControlException:access denied (java.lang.RuntimePermission Createsecuritymanager)2At Java.security.AccessControlContext.checkPermission (accesscontrolcontext.java:374)3At Java.security.AccessController.checkPermission (accesscontroller.java:549)4At Java.lang.SecurityManager.checkPermission (securitymanager.java:532)5At Java.lang.securitymanager.<init> (securitymanager.java:282)6At Xia.study._01thread.threadtest.creatthread1 (threadtest.java:18)7At Xia.study._01thread.threadtest.main (threadtest.java:13)

It is necessary to have some basic knowledge of SecurityManager.

Second, SecurityManager application scenario

When running an unknown Java program, the program may have malicious code (delete system files, restart the system, etc.), in order to prevent the running of malicious code on the system, need to control the permissions of the running code, it is necessary to enable the Java Security Manager.

Iii. Manager Profile 3.1 default configuration file

The default security Manager profile is $JAVA _home/jre/lib/security/java.policy, which is used when no configuration file is specified. The contents are as follows:

1 //Standard extensions get all permissions by default2 3Grant CodeBase "file:${{java.ext.dirs}}/*" {4 permission java.security.AllPermission;5 };6 7 //default permissions granted to all domains8 9 Grant {Ten     //allows any thread to stop itself using the Java.lang.Thread.stop () One     //method that takes no argument. A     //Note that this permission are granted by default only to remain -     //backwards compatible. -     //It is strongly recommended so either remove this permission the     //From the policy file or further restrict it to code sources -     //that's 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 un-privileged ports APermission Java.net.SocketPermission "localhost:1024-", "Listen"; at  -     //"Standard" properies the 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"; inPermission Java.util.PropertyPermission "Java.class.version", "read"; -Permission Java.util.PropertyPermission "Os.name", "read"; toPermission Java.util.PropertyPermission "Os.version", "read"; +Permission Java.util.PropertyPermission "Os.arch", "read"; -Permission Java.util.PropertyPermission "File.separator", "read"; thePermission Java.util.PropertyPermission "Path.separator", "read"; *Permission Java.util.PropertyPermission "Line.separator", "read"; $ Panax NotoginsengPermission Java.util.PropertyPermission "Java.specification.version", "read"; -Permission Java.util.PropertyPermission "Java.specification.vendor", "read"; thePermission Java.util.PropertyPermission "Java.specification.name", "read"; +  APermission Java.util.PropertyPermission "Java.vm.specification.version", "read"; thePermission 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"; -};

3.2 Detailed configuration files

See section Fifth, where this configuration file is known.

Iv. Start the security Manager

There are two ways to start security management, and it is recommended to use the boot parameter method.

4.1 Starting parameter mode

Start the security manager with additional parameters when starting the program:

-djava.security.manager

To specify the location of the configuration file at the same time, the example is as follows:

-djava.security.manager-djava.security.policy= "E:/java.policy"
4.2 Encoding mode start

Can also be started by encoding, but not recommended:

System.setsecuritymanager (new SecurityManager ());

Start by the parameters, in essence, also through the code start, but the parameters start using flexible, project start source code as follows (Sun.misc.Launcher):

1 //Finally, install a security manager if requested2String s = system.getproperty ("Java.security.manager");3 if(s! =NULL) {4SecurityManager SM =NULL;5     if(". Equals (s) | |" Default. Equals (s)) {6SM =NewJava.lang.SecurityManager ();7}Else {8         Try {9SM =(SecurityManager) Loader.loadclass (s). newinstance ();Ten}Catch(illegalaccessexception e) { One}Catch(instantiationexception e) { A}Catch(ClassNotFoundException e) { -}Catch(classcastexception e) { -         } the     } -     if(SM! =NULL) { - System.setsecuritymanager (SM); -}Else { +         Throw NewInternalerror ( -"Could not create SecurityManager:" +s); +     } A}

  

It can be found that a default securitymanager will be created;

Five, the configuration file simple Explanation 5.1 configuration Basic Principles

When you enable Security Manager, the configuration follows these basic principles:

    1. No permissions are configured to indicate No.
    2. You can configure only what permissions, and you cannot configure what is forbidden.
    3. The same permission can be configured multiple times, taking the set.
    4. Multiple permissions for a unified resource can be separated by commas.
5.2 Default configuration file interpretation

The first part authorizes:

1 Grant CodeBase "file:${{java.ext.dirs}}/*" {2    permission java.security.AllPermission; 3 };

Authorization is based on the path of the "file:${{java.ext.dirs}}/*" class and Jar package, all permissions.

The second part authorizes:

12     permission Java.lang.RuntimePermission "Stopthread"; 3     ...    4 }

This is a fine-grained authorization to authorize the operation of certain resources. Specifically no longer explained, you can view Javadoc. As Runtimepermission, the authorized operation is viewed Javadoc as follows:

Permission Target Name actions allowed by permissions risks associated with allowing this permission
Createclassloader Creating the class Loader Granting this permission is extremely risky. A malicious application that can instantiate its own classloader might load its own malicious class in the system. These newly loaded classes may be placed in any protected domain by the ClassLoader, which automatically grants the domain permissions to those classes.
getClassLoader Gets the class loader (that is, the class loader that invokes the class) This will give the attacker permission to get the loader for the specific class. This is dangerous because the attacker is able to access the class loader, so the attacker can load other classes that can be used with the ClassLoader. Typically, attackers do not have access to these classes.
Setcontextclassloader Settings for the context class loader used by the thread When you need to find resources that might not exist in the system ClassLoader, the system code and Extension sections use the Context class loader. Granting the Setcontextclassloader permission will allow the code to change the context class loader used by a particular thread, including the system thread.
Enablecontextclassloaderoverride Subclass implementation of the thread context ClassLoader method When you need to find resources that might not exist in the system ClassLoader, the system code and Extension sections use the Context class loader. Granting the Enablecontextclassloaderoverride permission allows subclasses of the thread to override certain methods that are used to get or set the context class loader for a particular thread.
Setsecuritymanager Setting up Security Manager (may replace existing) A security manager is a class that allows an application to implement security policies. Granting Setsecuritymanager permissions will allow the security manager to be used to change the code by installing a different security manager that may have fewer restrictions, so you can skip some of the checks that the legacy security manager enforces.
Createsecuritymanager Create a new security manager Granting code access to protected, sensitive methods may reveal information about other classes or the execution stack.
Getenv. {Variable name} Reads the value of the specified environment variable This permission allows code to read the value of a particular environment variable or determine whether it exists. This authorization is dangerous if the variable contains confidential data.
EXITVM. {Exit Status} Pauses a Java virtual machine with a specified exit state This permission allows an attacker to initiate a denial of service attack by automatically forcing the virtual machine to be paused. Note: the "exitvm.*" permission is automatically granted to all the code that is loaded from the application classpath, allowing these applications to abort themselves. Additionally, the "EXITVM" permission equals "exitvm.*".
Shutdownhooks Registration and cancellation of closed hooks (hook) of virtual institutions This permission allows an attacker to register a malicious shut-off Hook (hook) that prevents the virtual machine from shutting down gracefully.
Setfactory Sets the socket factory used by the ServerSocket or socket, or the stream handler factory used by the URL This permission allows code to set the actual implementation of a socket, server socket, stream handler, or RMI socket factory. An attacker could corrupt the data stream by setting the wrong implementation.
Setio Settings for System.out, system.in, and System.err This permission allows you to change the value of a standard system stream. An attacker could alter system.in to monitor and steal user input, or set System.err to "null" OutputStream to hide all error messages sent to System.err.
Modifythread Modify the thread, for example, by calling the thread's interrupt,stop,suspend,resume,Setdaemon, SetPriority,setName , and Setuncaughtexceptionhandler methods This permission allows an attacker to modify the behavior of any thread in the system.
Stopthread To stop a thread by calling the thread's stop method This permission allows code to stop any thread in the system if the system has granted permission for the code to access the thread. This permission poses a risk because the code might break the system by aborting an existing thread.
Modifythreadgroup Modify the thread group, for example, by calling Threadgroup,,, destroy getParent resume setDaemon setMaxPriority ,, stop and suspend method This permission allows an attacker to create thread groups and set their run priority.
Getprotectiondomain Get the protectiondomain of a class This permission allows code to obtain security policy information for a particular source of code. Although obtaining security policy information is not sufficient to compromise the security of the system, it does provide additional information that the attacker can better locate the target, such as a local file name.
Getfilesystemattributes Get File System Properties This permission allows the code to obtain file system information, such as the amount of disk usage or disk space available to the caller. This is potentially dangerous because it leaks information about the hardware configuration of the system and some information about the caller's privileges to write to the file.
Readfiledescriptor Read File descriptor This permission allows code to read specific files related to the file descriptor read. This is a dangerous operation if the file contains confidential data.
Writefiledescriptor Write file descriptor This permission allows code to write specific files related to the descriptor. This permission is dangerous because it could allow malicious code to spread the virus, or at least fill the entire disk.
LoadLibrary. {Library name} Dynamically link the specified library It is dangerous to allow applets to have permission to load the native codebase because the Java security architecture is not designed to prevent malicious behavior, and it cannot prevent malicious behavior at the native code level.
Accessclassinpackage. {Package Name} When the ClassLoader invokes the SecurityManager checkPackageAccess method, the specified package is accessed through the class loader loadClass method This permission allows code to access classes in those packages that they typically cannot access. Malicious code might use these classes to help them implement attempts to compromise system security.
Defineclassinpackage. {Package Name} When the ClassLoader invokes the SecurityManager checkPackageDefinition method, the class in the specified package is defined through the class loader's defineClass method. This permission allows the code to define classes in a particular package. This is dangerous because malicious code with this permission might define a malicious class in a trusted package, such as java.security or java.lang .
Accessdeclaredmembers To access a declared member of a class This permission allows code to query the class for public, protected, default (package) access, and private fields and/or methods. Although the code can access private and protected fields and method names, it cannot access private/protected field data and cannot call any private methods. In addition, malicious code may use this information to better locate an attack target. Furthermore, it can invoke any public method in the class and/or access public fields. If your code cannot cast an object to a class/interface with these methods and fields, it is often not possible to call these methods and/or access the field, which can be dangerous.
Queueprintjob Start of print job request This may output sensitive information to the printer, or just waste paper.
Getstacktrace Gets the stack trace information for another thread. This permission allows you to get stack trace information for another thread. This operation may allow the execution of a malicious code monitoring thread and discover weaknesses in the application.
Setdefaultuncaughtexceptionhandler Set the default handler that will be used when the thread terminates abruptly due to an uncaught exception This permission allows an attacker to register a malicious, uncaught exception handler that may prevent the thread from terminating
Preferences Represents the permissions required to get access to the java.util.prefs.Preferences. Java.util.prefs.Preferences implements the root of the user or system, which in turn allows the operation to get or update Preferences persistent internal storage. If the user running this code has sufficient OS privileges to read/write internal storage, this permission allows the user to read/write priority internal storage. The actual internal storage may be in a traditional file system directory or in the registry, depending on the platform OS.
5.3 Configurable items

When batch configuration, there are three modes:

    • directory/represents all. class files under the directory directory, excluding. jar files
    • directory/* represents all the. class and. jar files in the directory directory
    • directory/-represents all the. class and. jar files in the directory directory, including subdirectories

System properties can be referenced by ${}, such as:

"File:${{java.ext.dirs}}/*"
Vi. Problem Solving

When there is an error about security management, there are basically two ways to solve it.

6.1 Canceling the security Manager

In general, it is unintentional to start the security manager, so this time only need to shut down the security manager, remove the startup parameters.

6.2 Add appropriate permissions

If there is no right to error, then the error message will have the requested permission and what permissions to request, as follows:

Exception in thread "main" Java.security.AccessControlException:access denied (java.io.FilePermission E:\pack\a\a.txt Write

In the above example, the request resource E:\pack\a\a.txt, the filepermission Write permission is not, therefore rejected.

You can also open all permissions:

12    permission java.security.AllPermission; 3 };

Java Basic Series--securitymanager get Started (go)

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.