Many of the Java APIs use the SecurityManager, what the hell is this thing? Recently see the company's product source code, there are many SecurityManager, AccessControlContext and other related codes, just know that they are related to security, but what is the matter? Spring also has a security framework, what is the connection to Java security? Another experienced developer debugging the program may look at Protectiondomain, Codesource, what are the two?
Java Sandbox
When it comes to Java Security, you have to say the Java sandbox model.
JAVA2 Security Model:
JAVA2 platform, when loading classes, will form a different sandbox, but also according to the relevant security policy, for these sandboxes to generate a different safety policies, these security policies will be checked when the application executes, to protect the resources are malicious operations.
This diagram shows the true execution of Java applications.
1) enforce rule validation at compile time, then generate class file
Java's mandatory rules are:
A:private, protected, default, public. This is known to be related to visibility, which is the protection of memory resources in the application.
B:final variables cannot be changed after initialization
C: variables to be initialized before use
And some other rules that, when validated by these rules, generate a class file, which is commonly said bytecode file.
2 ) ClassLoader Loading class file post-definition class generation Class Object
The ClassLoader is also a hurdle, not that you let it load, it loads, it is also to be validated.
If the hacker wrote some Java files compiled into the Classpath directory, or the JDK to bring some core API to make some modifications, overwriting the original file, so that the program can be very harmful. It is also necessary to check when classes are loaded.
As you can see from this picture, the process of defining a class in the ClassLoader also checks the bytecode, and you can look at the defineclass process in ClassLoader:
protected FinalClass<?> defineclass (String name,byte[] B,intOffintLen, Protectiondomain protectiondomain)throwsclassformaterror{//Check if the ClassLoader is initializedcheck ();//form to generate Protectiondomain and Codesource for this classProtectiondomain =Predefineclass (name, Protectiondomain); Class C=NULL; String Source=defineclasssourcelocation (protectiondomain);//The real process of defining class, this method is native, the process of bytecode checking is also carried out here, here is not seen, but also can not let us see, if we are visible, can be customized, so the check is the same as a dummy. Try{C=DefineClass1 (name, B, off, Len, Protectiondomain, source); } Catch(Classformaterror CfE) {C=Definetransformedclass (name, B, off, Len, Protectiondomain, CFE, source); }//improve the certificate and other informationPostdefineclass (c, Protectiondomain); returnC; }
Since the code level, do not see how to check the bytecode, then at least to understand, what exactly do you check?
D: Check the format of the class file is correct, the JVM specification describes the format of the class file, interested in the website can be downloaded to see. For example, the class file must have the correct length, magic number, and so on.
The magic number is used to determine the file type, and the UNIX system does not determine the file type according to the extension, which is based on the magic number. To know the magic number of a class file and how it is defined, you can refer to the deep understanding of Java Virtual Machine.
The E:final class has no subclasses
F: Native type data has no valid type conversions (e.g.: int to Object)
G: Data of a reference type has no valid type conversions, such as converting a parent class object to a subclass type.
H: There is no operand stack overflow phenomenon
such as
There are actually two kinds of checks, both at run time :
I: array cannot be crossed
J: Data cannot be coerced into other irrelevant types
The protectiondomain associated with this class is also produced during the definition of a class. The Java security module is designed as shown.
But not all ClassLoader will generate Protectiondomain. For example, the class loader I defined in a previous blog post, or Bootstrapclassloader. Only ClassLoader that inherit Securclassloader will generate an associated protectiondomain at DefineClass, In general we will inherit URLClassLoader when we customize ClassLoader, and URLClassLoader inherit Securclassloader, So the classloader we define will generally generate protectiondomain when executing defineclass.
Protectiondomain design model is very important, next to say Accesscontroller and SecurityManager are on the basis of protectiondomain to make a difference. So Protectiondomain is established when the class is loaded.
By default, a jar package corresponds to a protectiondomain.
The Web-based tutorial on Java security is mostly about policy, because it is configured with security policy. We may not be defining permission (the permission defined in Java is enough for us to use), but we need to configure security policies to use these permission to serve us.
3) Application Access related resources
3.1 securitymanager#checkpermission ()
Java provides a security model, how do we use it in the program?
Generally, it is done by SecurityManager, using the following methods:
SecurityManager sm = getSecurityManager (); if NULL ) { // sm.checkpermission ();}
For example:
System.getproperty (String key)
Public Static string GetProperty (String key) { Checkkey (key); = getSecurityManager (); if NULL ) { sm.checkpropertyaccess (key); } return Props.getproperty (key);}
For example:
PublicFileInputStream (File file)throwsfilenotfoundexception {String name= (File! =NULL? File.getpath ():NULL); SecurityManager Security=System.getsecuritymanager (); if(Security! =NULL) {security.checkread (name); } if(Name = =NULL) { Throw NewNullPointerException (); } FD=NewFileDescriptor (); Open (name);}
By default, our program does not have a Java security policy turned on. To see what your application will look like after you open the security policy, you can use the JVM parameter:-djava.security.manager .
If you want to use code to turn on, you can use System.setsecuritymanager (SecurityManager) to start.
In the code, you can check the appropriate permissions by simply writing two or three lines of code as above. So what is the process of their execution?
All methods associated with checking permissions in SecurityManager call the Checkpermission method of SecurityManager, which illustrates the securitymanager#checkpermission ( Permission) Execution of the process.
From this figure can also see the last or Permission#implies function.
3.2 accesscontroller.doprivileged ()
Sometimes we see the use of the Accesscontroller.doprivileged () method in the code, and what does this do?
Consider one of the following scenarios: There is a protectiondomain Codesource is a COM directory, under which there are three directories: Core,modulea,web, in this protectiondomain, There is read permission on all files, only files under the resource directory under the Web directory can have write permission. There is now a need to have write permission on a file in the core directory.
/com |--core |--modulea |--web |--Bean |-- Service | -- DAO|--resource
This is certainly the case in our program: New FileOutputStream (File file). The above has been glued to the FileInputStream (file file) implementation process. This means that checks have no Read permission on the file. Then the corresponding FileOutputStream will certainly have to check whether there is a write permission process. As already known in the above description, there is no write permission for the core, so our demand is not satisfied. What about that?
Accesscontroller.doprivileged () can help rib complete the above tasks.
FileOutputStream fos=null; String filepath= "./com/core/xx"; Fos=accesscontroller.doprivileged (new Priviliegedaction () { public FileOutputStream run () { returnnew FileOutputStream (filepath);}}); if (fos!=null) {// xxxxxxxx}
What the hell is going on here? The following is a paragraph in the Java API Accesscontroller Description:
A caller can is marked as being "privileged" (see Doprivileged and below). When making access control decisions, the Checkpermission method stops checking if it reaches a caller that is 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 are done and checkpermission returns quietly, Ind Icating The requested access is allowed. If The domain does not has the specified permission, an exception is thrown, as usual.
This passage is to the effect that:
If the Doprivileged method is used to mark the caller as privileged, when a check is performed on Accesscontroller.checkpermission (), the check is terminated when the caller is checked. Then make only one judgment: if the domain where the caller is located has the specified permissions.
Securitymanager#checkpermission actually calls Accesscontroller.checkpermission (), so this solution is for securitymanager# The checkpermission is also applicable.
Just for now, Java Security has a lot of details that are not mentioned. This article is just a description of the overall structure of Java security. And some common code explanation, after reading this article, I believe in the past to some confused code, it should now be able to understand seven or eight points.
Java Se:java Security