I have been trying to use a custom SecurityManager to sandbox some externally loaded code. The SecurityManager I have works fine. I have taken the same approach as numerous posts here suggested: set the custom manager whenever the potentially dangerous code executes, then revert back to the standard manager. This works fine and does what I want. However, the application is multi-threaded: 2 threads using the custom manager, one using the default one. This leads to the situation where the trusted code m开发者_运维问答ight be prevented from running properly as another thread just set the custom security manager. Is there a way to work around this? Alternatively, is there a better way altogether? I saw some posts talking about using different policies with the same security manager but I could not find a good example of this. Any help greatly appreciated.
Your SecurityManager can check which thread is running. A simple thread local will do this, however, you may want an InheritableThreadLocal so that any additional Threads created "inherit" the threads security level.
You use one securitymanager for your entire application. the java security framework was designed to handle this scenario. the way you get things to work is using the codebases feature of the policy file, which enables you to assign different permissions to different codebases. you can assign your "main" codebase "all permissions" and it will function as normal. you can assign any imported code to a restricted codebase.
this is all heavily documented here, probably the part most relevant to this issue is the policy file information.
Testing the current thread or removing security restrictions is not a good idea. Just as a for instance, suppose the untrusted code has a finaliser that likes to sleep?
精彩评论