Skip to main content

Restricting code loaded from a URL

3 replies [Last post]
Joined: 2008-04-17

How do I restrict the things that code loaded from a jar can do? I've got code like this
URLClassLoader cl = new URLClassLoader(new URL[] {myurl});
MyObj obj = (MyObj) cl.loadClass("mypackage.MyObjImpl").newInstance();
I want to restrict what mypackage.MyObjImpl.myMethod() can do, but, although I can print out its permissions (via getClass().getProtectionDomain().getPermissions()) and it only seems to have one (reading from its own jar), it can still write local files etc.
I think I need to apply a SecurityManager, but I don't want to restrict all the code in my app, just code from that url.
Any ideas?


Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2008-04-17

Well, I made a bit of progress.
Everything is allowed until you set a security manager,
System.setSecurityManager(new SecurityManager());
and then nothing is.
So I then set a no-op policy,
Policy.setPolicy(new Policy() {});
(or I could have signed my jars and used policytool to give them AllPermissions)
Then I subclassed URLClassLoader with an overridden getPermissions method to give me just the permissions I wanted. This seems to work OK.
Anybody got any comments?


Joined: 2006-02-02

You don't need to do all that.
Instead create your own security policy. Read here: on how it's done.

Joined: 2008-04-17

OK thanks, that's useful.