Java Se: Java Security, javasesecurity

Source: Internet
Author: User

Java Se: Java Security, javasesecurity

Many Java APIs use SecurityManager. What exactly is this? I recently looked at the source code of the company's products. There are also a lot of SecurityManager, AccessControlContext and other related code. I just know that they are related to security, but what exactly are they? Spring also has a Security framework. What is the relationship with Java Security? In addition, experienced developers may check ProtectionDomain and CodeSource when debugging programs. What are the two?

 

Java Sandbox

When talking about Java Security, you have to talk about the Java Sandbox Model.

Java2 Security Model:

 

 

On the Java2 Platform, different sandboxes are formed when classes are loaded, and different security policies are generated for these sandboxes according to the related security policies, these security policies are checked during application execution to protect resources from malicious operations.

 

 

This figure shows the real execution process of the Java application.

1)Enforce rule verification during compilation, and then generateClass file

Java has the following mandatory rules:

A: private, protected, default, public. We all know that visibility is related to the protection of memory resources in applications.

B: The final variable cannot be changed after initialization.

C: You must initialize the variable before using it.

 

And some other rules. After these rules are verified, the class file, also known as bytecode files, is generated.

 

2)ClassLoaderLoadClass filePost-definition class generationClassObject

The class loader is also a hurdle, not to say that you let it load, it loads, it also needs to be verified.

 

If the hacker writes some java files to the classpath directory after compilation, or modifies some of the core APIs in jdk after decompiling to overwrite the original files, this can cause great harm to the program. Therefore, it is also necessary to check when the class is loaded.

 

From this picture, we can see that the class definition process of the class loader will also check the bytecode. Next we can look at the process of defineClass in ClassLoader:

Protected final Class <?> DefineClass (String name, byte [] B, int off, int len, ProtectionDomain protectionDomain) throws ClassFormatError {// check whether the Class Loader initializes check (); // generate the protectionDomain and codesource protectionDomain = preDefineClass (name, protectionDomain) for this Class; Class c = null; String source = defineClassSourceLocation (protectionDomain); // The process of actually defining the Class, this method is native, And the bytecode check process is also carried out here, which is invisible and invisible to us. If we can see it, we can customize it, this check is essentially a virtual setting. Try {c = defineClass1 (name, B, off, len, protectionDomain, source);} catch (ClassFormatError cfe) {c = defineTransformedClass (name, B, off, len, protectionDomain, cfe, source) ;}// certificate information such as postDefineClass (c, protectionDomain); return c ;}

Since we can't see how to check the bytecode at the code level, we can at least take a look at what checks have been done?

D: Check whether the format of the class file is correct. The format of the class file is described in JVM Specification. If you are interested, download it from the official website. For example, the class file must have the correct length and magic number.

The magic number is used to determine the file type. The UNIX system determines the file type either based on the extension or the magic number. If you want to know the magic number of class file and how to define it, refer to "deep understanding of Java Virtual Machine".

E: The final class has no subclass.

F: whether the native type data has illegal type conversion (E. G.: int to Object)

G: whether the data of the reference type has illegal type conversion. For example, convert the parent class object to the subclass type.

H: Is there stack overflow in the number of operations?

.

 

In fact, there are two kinds of checks.RuntimeIn progress:

I: The array cannot be out of bounds.

J: data cannot be forcibly converted to other irrelevant types.

 

When defining a class, a ProtectionDomain associated with the class is also generated. Shows the design of the Java Security module.

 

 

However, not all ClassLoader will generate ProtectionDomain. For example, the Class Loader defined in my previous blog, or bootstrapClassLoader. Only ClassLoader that inherits SecurClassLoader will generate the associated ProtectionDomain when defineClass. Generally, when we customize ClassLoader, We will inherit UrlClassLoader, while UrlClassLoader inherits SecurClassLoader, therefore, the defined ClassLoader generally generates a ProtectionDomain when executing defineClass.

 

The Design Model of ProtectionDomain is very important. The AccessController and SecurityManager mentioned next are based on ProtectionDomain. Therefore, ProtectionDomain is established when the class is loaded.

By default, a jar package corresponds to a ProtectionDomain.

 

The Java Security tutorial on the internet is about Policy at most, because it configures Security policies. We may not define Permission (the Permission defined in Java is enough for us), but we need to configure security policies to use these Permission to serve us.

 

3) applications access related resources

 3.1 SecurityManager # checkPermission ()

Java provides a security model. How can we use it in a program?

Generally, SecurityManager is used for the following operations:

SecurityManager sm = getSecurityManager();if (sm != null) {   // sm.checkPermission();}

For example:

System. getProperty (String key)

public static String getProperty(String key) {    checkKey(key);    SecurityManager sm = getSecurityManager();    if (sm != null) {        sm.checkPropertyAccess(key);     }     return props.getProperty(key);}

For example:

public FileInputStream(File file) throws FileNotFoundException {    String name = (file != null ? file.getPath() : null);    SecurityManager security = System.getSecurityManager();    if (security != null) {        security.checkRead(name);    }    if (name == null) {        throw new NullPointerException();    }    fd = new FileDescriptor();    open(name);}

By default, our program does not enable Java's security policy. You can use the JVM parameter-Djava. security. manager to see what your application will look like after the security policy is enabled.

If you want to enable it using code, you can start it using System. setSecurityManager (securitymanager.

In the code, you only need to write two or three lines of code as easily as above to check the corresponding permissions. So what is their execution process?

 

All methods related to Permission check in SecurityManager call the checkPermission method of SecurityManager. The following sequence diagram illustrates the execution process of SecurityManager # checkPermission (Permission.

 

 

From this figure, we can see that Permission # implies works at the end.

 

3.2 AccessController. doPrivileged ()

Sometimes we can see in the code that the AccessController. doPrivileged () method is used. What does this mean?

 

Assume that the CodeSource of a ProtectionDomain is the com directory, and there are three directories under it: core, moduleA, web, in this ProtectionDomain, all files have the read permission. Only files under the resource Directory under the web directory can have the write permission. You need to have the write permission for a file in the core directory.

/com   |--core   |--moduleA   |--web      |--bean      |--service      |--dao      |--resource

Our program will definitely write like this: new FileOutputStream (File file ). The FileInputStream (File file) implementation process has been pasted out above. That is to say, check whether the object has the read permission. Then, the corresponding FileOutputStream will certainly check whether there is write permission. As we know in the above description, we do not have the write permission for the core, so our requirements cannot be met. What should we do?

AccessController. doPrivileged () can help you complete the preceding tasks.

FileOutputStream fos=null;String filepath=”./com/core/xx”;fos=AccessController.doPrivileged(new PriviliegedAction(){public FileOutputStream run(){    return new FileOutputStream(filepath);}});if(fos!=null){// xxxxxxxx}

What the hell is going on? The following is a line in the AccessController description in Java API:

A caller can be marked as being "privileged" (see doPrivileged and below). When making access control decisions, the checkPermission method stops checking if it reaches a caller that was marked as "privileged" via a doPrivileged call without a context argument (see below for information about a context argument). If that caller's domain has the specified permission, no further checking is done and checkPermission returns quietly, indicating that the requested access is allowed. If that domain does not have the specified permission, an exception is thrown, as usual.

This section is to say:

If the doPrivileged method is used to mark the caller as privileged, the AccessController is executed. when checkPermission () is used for the check, when the caller is checked, the check is terminated and only one judgment is made: If the caller domain has the specified permission, it can be done.

 

SecurityManager # checkPermission actually calls AccessController. checkPermission (). Therefore, this solution is also applicable to SecurityManager # checkPermission.

 

Let's talk about it for the moment. There are still many details about Java Security. This article only describes the overall structure of Java Security. As well as some common code explanations, after reading this article, I believe that some of the Code that has doubts in the past should now be clear.

 

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.