Java Magic SecurityManager
Introduce something about SecurityManager
Use case of .
Introduce
We can go through sun.misc.Unsafe
Do something terrible ( Operate the bottom layer ).
and SecurityManager Just the opposite , Provide protection , Stop sensitive operations ( Such as io、 The Internet 、 Reflection, etc ).
If the operation does not allow , Throw out “SecurityExeption abnormal .
SecurityManager manager = System.getSecurityManager();
if (manager != null) {
manager.checkAction(action);
}
Some cases
Imagine a scenario : Iterative upgrade of system functions , After we developed some code , Need to submit .
Of course , It’s not safe to run untrusted code , So we need to make sure that the code submitter doesn’t compromise the whole system .
for example ,sumbitter You can read the password and change some entries in the database . What’s worse is , It could fill up the entire file system 、 Memory or consume all threads , And prevent other committers from processing .
SecurityManager
Is to solve these things .
First We can extend this class , Implement some of your own interception strategies :
/**
* Expand SecurityManager Restrict some access operations
*/
public class MySecurityManager extends SecurityManager {
@Override
public void checkRead(FileDescriptor fd) {
throw new SecurityException("File reading is not allowed");
}
@Override
public void checkWrite(FileDescriptor fd) {
throw new SecurityException("File writing is not allowed");
}
@Override
public void checkConnect(String host, int port) {
throw new SecurityException("Socket connections are not allowed");
}
}
then , Set up this security manager at run time .
System.setSecurityManager(new MySecurityManager());
Observed SecurityManager Of check
Prefix method when ,JVM Will do a lot of checking .
although , Security manager is a useful tool for configuring access to subsystems and preventing untrusted code from doing bad things , But some operations are not controlled by the Security Manager .
Memory allocation
Memory allocation is not affected by SecurityManager Management control , If you need to verify that some untrusted code is reliable , Consider using a single JVM And set the maximum memory, for example :java -Xmx128m
.
lib library
You can use SecurityManager.checkPackageAccess
Method to limit the use of the entire package .
Reference resources : http://mishadoff.com/blog/java-magic-part-5-securitymanager/