Question summary: How do I modify the code below so that untrusted, dynamically-loaded code runs in a security sandbox while the rest of the application remains unrestricted? Why doesn't URLClassLoader just handle it like it says it does?
EDIT: Updated to respond to Ani B.
EDIT 2: Added updated PluginSecurityManager.
My application has a plug-in mechanism where a third party can provide a JAR containing a class which implements a particular interface. Using URLClassLoader, I am able to load that class and instantiate it, no problem. Because the code is potentially untrusted, I need to prevent it from misbehaving. For example, I run plug-in code in a separate thread so that I can kill it if it goes into an infinite loop or just takes too long. But trying to set a security sandbox for them so that they can't do things like make network connections or access files on the hard drive is making me positively batty. My efforts always result in either having no effect on the plug-in (it has the same permissions as the application) or also restricting the application. I want the main application code to be able to do pretty much anything it wants, but the plug-in code to be locked down.
Documentation and online resources on the subject are complex, confusing and contradictory. I've read in various places (such as this question) that I need to provide a custom SecurityManager, but when I try it I run into problems because the JVM lazy-loads the classes in the JAR. So I can instantiate it just fine, but if I call a method on the loaded object which instantiates another class from the same JAR, it blows up because it's denied the right to read from the JAR.
Theoretically, I could put a check on FilePermission in my SecurityManager to see if it's trying to load out of its own JAR. That's fine,