Java: How to use AccessControllerContext? - java

I am trying to design a plugin framework that will sandbox loaded plugins so that they can only perform risky actions through my plugin interfaces.
I need to figure out how to use AccessControllerContext to see what code is calling the methods.
The documentation shows no way to recover the code source or originating class. How can this be done?
Is it possible to set the context for all classes loaded from a particular class loader?

Rather than using an AccessControlContext directly, you should use AccessController.checkPermission, which will check the active security context for you. To control what permissions are granted a class, use ClassLoader.defineClass, and pass a ProtectionDomain containing a PermissionCollection with the appropriate set of permissions. It might be useful to review an Overview of Basic Concepts in the Java Security Architecture document.

Related

How to prevent reflection to access a class or method in java

I have developed an android library and I want to prevent reflection to access my class fields and methods. I remember something about SecurityManager but I don't know if it can help.
How can I achieve such functionality ?
The JVM has security mechanisms that allows you to define restrictions to code through a Java security policy file.
It will use the default one unless you specify otherwise.
Run your application using a SecurityManager and a sufficiently restrictive security policy, policy can be found here:
http://docs.oracle.com/javase/7/docs/technotes/guides/security/PolicyFiles.html
You may find this tutorial useful:
http://docs.oracle.com/javase/tutorial/essential/environment/security.html

Controlling access to loading of a JAVA class at runtime

I have a requirement to restrict access to loading of a particular class of a JAVA application, at runtime. Just wondering whether this is possible using JAVA Security Manager with a security policy. Also, if this is a possibility, I'd like to know how the permission configuration would look like in a JAVA security policy. I'd done some researching on this but couldn't really find any useful solution yet.
These two:
java.security.Permission
java.io.FilePermission
and providing you need to continue the application operating in some way without it you need to load classes using java.lang.ClassLoader and loadClass method to be able to throw it into an if-else to bypass potentially if simple instantiation is not involved.
I managed to come up with a custom permission implementation extending java.security.RuntimePermission class and get my requirement fulfilled. The only overhead (which is unavoidable) associated with the approach of introducing a custom permission is that, you need to hack into all your classloading implementations and add an additional check to evaluate your custom permission.

Java: danger in setting private member field as accessible?

To set the value of a private Field, it needs to be marked as accessible:
field.setAccessible(true);
When will the SecurityManager not allow this? How portable is it to include this in a library? Will it fail when imported into certain contexts?
If you know your library won't be used inside a JVM with the Security Manager enabled, like an applet or a secured application server, then it's fine. But I would try to avoid it if possible.
There are others answers like this link that suggest there's no problem using it. So if you think it's the best approach, and the other options are too cumbersome or directly don't exist, then go ahead.
When will the SecurityManager not allow this?
The javadoc says:
First, if there is a security manager, its checkPermission method is called with a ReflectPermission("suppressAccessChecks") permission.
A SecurityException is raised if flag is true but accessibility of this object may not be changed (for example, if this element object is a Constructor object for the class Class).
As to your other question
How portable is it to include this in a library? Will it fail when imported into certain contexts?
It is portable across JVM implementations because Field is defined in the core library with these semantics. It is not portable across instances because different JVM instances may have differently configured security policies.

How can I monitor the opened URLs via java.net.URL class in a Java program?

I am working on a big (lots of classes) java project and I have it's source code but most of the classes are dynamically created or downloaded via ClassLoaders.
Anyways, I'd like to be able to "override" the java.net.URL class so I could trace down the calls to open a url. I can not use a sniffer because the content is SSL encrypted.
I tried to extend the java.net.URL but it didn't work because its a final class.
I also opened the source to java.net.URL and modified it and could successfully build it, now how can I make the default java classloader to load my modified copy of java.net.URL instead of the original one?
Any suggestions are welcome! Thanks in advance.
An option would be to use AspectJ and weave your extension code into the URL class instead of extending it. That way you don't have to modify any of the original sources and you can still "extend" a final class. The downside of course is, that you add another dependency to your project.
If you have not yet worked with AOP, you may find a short introduction to AOP at my blog: http://whatiscomingtomyhead.wordpress.com/2010/02/06/aspect-oriented-programming-an-introduction/
You can't extent URL, as you have discovered. You may be able to get the JVM to load your custom version of the class, but IMHO that sounds like a nightmare.
Thankfully you can implement a custom URLStreamHandlerFactory and register it by URL.setURLStreamHandlerFactory(). This will allow you to wrap and monitor when URLs open streams, just as you desire.
EDIT
But you won't be able to use this approach if your app already registers one; URLStreamHandlerFactories are 1/app. And many types of app containers use one (e.g. Tomcat), so if you're using one of those you're SOL.
Have you considered using AspectJ? You could set a pointcut on URL constructors and thus be notified of any new URL instance creation.
If you have modified classes in the standard API, you have to prepend the boot class path with your classes (jars or directories), otherwise the VM internal classes will have priority over any classes added to the normal class path. With Sun's VM, you can use the argument -Xbootclasspath/p: to add new classes with a higher priority than the internal implementations.
Another option, without modifying the URL implementation may be to implement a ProxySelector. Opening a URLConnection would cause the URL implementation to query ProxySelector.select(URI uri) for a suitable proxy for the given address. This will even work if you actually are using proxies. You can obtain the system ProxySelector with ProxySelector.getDefault() before you register your own implementation and delegate the select calls to the original implementation after you've tracked the URI, which is passed to the select method.

Disable Java reflection for the current thread

I need to call some semi-trustworthy Java code and want to disable the ability to use reflection for the duration of that code's execution.
try{
// disable reflection somehow
someObject.method();
}
finally{
// enable reflection again
}
Can this be done with a SecurityManager, and if so, how?
Clarification/Context: This is a follow-up to another question about restricting the packages that can be called from JavaScript/Rhino. The accepted answer references a blog entry on how to do that, and it requires two steps, the first one using a Rhino API (ClassShutter), the second one turning off reflection and Class.forName(). I was thinking I can do that second step more cleanly using a SecurityManager (learning about SecurityManager, which as has been pointed out, is a complex beast, along the way).
To sum up, I want (from code, not setting file) to turn off Class.forName() and any access to the whole reflection package.
It depends on what you are trying to restrict.
In general, publicly accessible API is not restricted. However, as long as you don't grant the untrustworthy code the ReflectPermission("suppressAccessChecks") permission, it won't be able to get access to non-public API in another package.
If you have a list of packages to which you want to restrict all access, there are two steps. First, in the Security properties, include the restricted package in the package.access list. Then give your trusted code RuntimePermission("accessClassInPackage." + pkg).
A common way to distinguish your untrusted code is to load it from a different location, and refer to the different codebases in your policy file when granting permissions.
The Java security architecture is very powerful, but I know it is also complicated; if you would like a more concrete example, please describe exactly what calls you want to restrict and I'll try to be more explicit.
To do what you want without modifying the java.policy file and/or the java.security file would be very difficult, maybe impossible. The java.security.Policy represents the information in java.policy, but it doesn't offer write access. You could create your own Policy implementation and install it at runtime as long as any existing SecurityManager permits it.
On the other hand, you can specify a custom java.policy file as a command-line option. If you are providing a complete application with some sort of launcher, that might be easily accomplished. It also provides some transparency to your users. A sophisticated user can review the permissions you'd like to have granted to the application.
Well, you can override SecurityManager.checkMemberAccess and give a stricter definition. However, it doesn't really work like that. What happens for instance if the code defines a finaliser?
On the clarification: Other APIs use reflection and other APIs. For instance, java.beans, LiveConnect and Rhino. An adversary could from within a script, say, create a new Rhino context without the shutter and thereby bootstrap into the full JRE. With an open system, a blacklist can never be finished.
In summary: to use the Java security model you need to work with it, not against it.
I wrote a replacement of ClassShutter that allows fine grained access control, per instance, per method, per field:
http://riven8192.blogspot.com/2010/07/java-rhino-fine-grained-classshutter.html

Categories

Resources