All,
I'm working on the design of a cloud-based service that will provide the option to execute some "plugin" code submitted by clients. In order to make this work it is essential that the plugins can't threaten system integrity or have any ability to access the data of other clients.
Ideally I'd like it to be possible for clients to submit a simple jar file (containing a class conforming to some pre-defined interface) which would then be run within a sandbox.
The client code should be allowed to:
Take as much CPU time as it needs on a single thread
Perform any calculations using standard java classes (e.g. java.lang.Math, java.util.Random etc.)
Call any libraries bundled in the jar (but which must be subject to the same restrictions)
But I would specifically need to disallow the following:
Spawning new threads (so that server resource can be fairly managed!)
Any access to the file system / IO / network
Any access to native code
Any access to data in the JVM other than that passed to / created by the client code
Any access to reflection on classes other than those in the .jar sandbox
Any ability to call methods on objects outside the sandbox, other than the standard Java libraries
Is it be possible to achieve this with a custom ClassLoader / SecurityManager setup? Or will I need to start looking for a more sophisticated solution (e.g. launching multiple JVMs?)
Managing resource and limiting resources is not possible in java. You can prevent malicious code to access system resources (disk/network and so) or the JVM itself but:
...
Spawning new threads (so that server resource can be fairly managed!)
If i wanna be malicious I am gonna do all my code in the finalizer thread and just block the VM. Same doing protected void finalize(synchronized(Thread.class) {for(;;) LockSupport.park();}} bye-bye new threads.
Eating all the memory, eating all direct memory and so on.
Accessing zip files in my own jar, and expect 'em getting moved away, so the JVM crashes (due to bug(s) in zlib)
If one purposely wants to deny resources, it is just not a feasible task to try and catch the hacker. You'd need to know what to search for and dynamically check/enhance the classes on run-time to disallow the behavior.
Any ability to call methods on objects outside the sandbox, other than the standard Java libraries
What are the standard libraries? Do you know if/when they must possibly execute some code in a privileged method.
Each customer - separate VM w/ full restrictions, process affinity/priority, incl max memory/stack and so on.
I think everything you want to achieve can be done through a custom SecurityManager. In fact it's pretty simple, you just create a class that extends SecurityManager, implement the two checkPermission(..) methods and in the first iteration just throw an SecurityException for everything that comes in (and log what you just denied). Then you allow specific operations until you find yourself in the situation that it's possible to create useful plugins and let your clients play with it. They will complain. Then you have to judge whether to allow them to do whatever they requested or if you want to stick with your rules. Here the difficult part begins...
Related
I have a piece of hardware for which I already have written a small library to provide controls. Previously I used CLI with the program to control the hardware, but now I want to give multiple users access over the network. The control is handled via an object instance, in short, this is non-static and it can't be static as there are runtime configurations as well as important hardware state information to store, but I want to provide control of this hardware to connected sessions. The way I previously had this work was by having my main function set in my serverEndpoint class, and it handled the runtime configuration of the object. This design is messy, and I'd prefer to not organize the code this way, but I've not found any good guides for this elsewhere and I question if perhaps I'm just an atypical use-case or if websockets are the wrong approach, though logically I can't see why that would be. Anyway, my question is how should I provide a handle to this instance to sessions? The hardware control class is already configured to be threadsafe.
Alernatively, my real impetus for reorganizing the code was so that it would be more easily testable, which isn't really possible with the main function located inside the serverEndpoint as far as I'm aware.
I would like to know what the checkCreateClassLoader method does , its not very clear in the java api doc.Yes , let say I have an application and want to avoid someone dumping my classes during run time(using java agent or reflection). Can I use this method for avoiding this . Thanks
MalikDz
Let say I have an application and want to avoid someone dumping my classes during run time(using java agent or reflection). Can I use this method for avoiding this?
No.
First of all "Java Agent" already implies complete control over the runtime environment.
If you have a user running your code on their own machine, they can get at your class files.
If the code is running on your machine (but the user can somehow upload his own JAR files), then you can use a custom Security Manager, maybe in combination with a custom ClassLoader, to disable reflection and probably also access to the bytecode of classes (and also restrict communication channels that would be required to send this "leaked" data back to the user).
In our application, users are able to define Java expressions that are executed by our main engine (those expressions are method calls only: e.g., Math.abs(42) ). They're executed via reflection.
What are the different solutions to prevent those expressions calling for example System.exit (but as well File access and others...) either directly or via a method call that will internally call eventually System.exit ?
Note that several different expressions can be executed in different threads. Preventing for example File access with a SecurityManager does not work as the main engine must still be able to access the File system while the expressions are executed.
You are wrong to say you can't use the SecurityManager -- this is precisely what it's for: hosting untrusted code, as in an Applet container or RMI server. The modern SecurityManager is configured with policy files that grant specific, fine-grained rights, including limited access to the file system. You need to use the SecurityManager, but you need to become an expert in it.
This is an enormous topic; the best thing to do would be to Google "Java security policy files" and just read everything you can.
What you are doing is crazy. Allowing users to execute arbitrary Java code on your machine is an awful idea and there is no way you can make that safe against Hackers who know their stuff.
The only solution I can think of is to create a whitelist of packages and methods that may be used. But trying to blacklist specific actions will never get you there. There is always someone who is smarter than you are when it comes to breaking stuff.
Update: I have now read more about the SecurityManager and it seems that you can controll package access very finely with it, so I'd suggest you to go with Ernest's answer.
The Java security system is the appropriate tool for this. SecurityManager is only a part of this system which you will have to use.
Basically you do not invoke the untrusted code yourself. Instead you will wrap that call into a PrivilegedAction and give that to one of the AccessController.doPrivileged methods. Then the untrusted code will be executed in another ProtectionDomain.
So you have to configure two protection domains: One for your engine with full privileges and one for the untrusted code with reduced privileges.
But as Ernest already mentioned: This is quite complicated stuff and not suited to a Q&A site like this. Read up the appropriate tutorials from Oracle and Co. Use the above keywords for your search.
For example Apache Velocity had a similar problem to solve. They use black listed classes and packages defined in velocity.properties:
# ----------------------------------------------------------------------------
# SECURE INTROSPECTOR
# ----------------------------------------------------------------------------
# If selected, prohibits methods in certain classes and packages from being
# accessed.
# ----------------------------------------------------------------------------
introspector.restrict.packages = java.lang.reflect
# The two most dangerous classes
introspector.restrict.classes = java.lang.Class
introspector.restrict.classes = java.lang.ClassLoader
# Restrict these for extra safety
introspector.restrict.classes = java.lang.Compiler
introspector.restrict.classes = java.lang.InheritableThreadLocal
introspector.restrict.classes = java.lang.Package
introspector.restrict.classes = java.lang.Process
introspector.restrict.classes = java.lang.Runtime
introspector.restrict.classes = java.lang.RuntimePermission
introspector.restrict.classes = java.lang.SecurityManager
introspector.restrict.classes = java.lang.System
introspector.restrict.classes = java.lang.Thread
introspector.restrict.classes = java.lang.ThreadGroup
introspector.restrict.classes = java.lang.ThreadLocal
There are too many things in Java which could cause a problem that you might not be aware of. The safest thing to do is to create a list of classes which are allows and run these via a custom class loader in a separate process (so you can kill it safely)
For serious dangerous code which most people don't even know is there have a look at sun.misc.Unsafe which allows you to
Access random areas of memory.
Create new instance of classes without calling a constructor e.g. new instances of Enums.
lock and unlock an objects monitor discretely. (Without a synchronized block)
Can I avoid third party code from creating new threads, starting new VMs, or leaking data using a customized SecurityManager?
Thread creation results in a call to securityManager.checkAccess(g) where g is a ThreadGroup. That in turn requires SecurityConstants.MODIFY_THREADGROUP_PERMISSION.
The only way to create a new JVM instance is to start a new process. That will require SecurityConstraints.FILE_EXECUTE_ACTION.
So, if your SecurityManager raises an exception for both of those permissions, your first 2 cases are covered.
You'll need to qualify what constitutes "leaking data". Is the concern over accidental or deliberate leaks? Is the concern the untrusted code accessing data, or the untrusted code's data being accessible by other threads, classes, etc?
Nothing much is a full security solution (unless you ask salesmen).
I'd say the SecurityManager can control all this (as was said you don't necessarily need a custom security manager, you can configure a lot simply through a policy). Controlling threads, process execution, enforcing access to private data and network connections (3rd party app sending private data to your competition, etc) - that's what the SecurityManager is for.
However, you need to weigh how much security you need. Consider that with every Java security update Sun fixes maybe 3-4 vulnerabilities (Java 6u15 as an example) in the Java security sandbox. These updates take place about 3-4 times per year (or took, don't know what the Oracle acquisition will do to that). So any of these ~12 annual vulnerabilities could cause your data to be leaked.
If my secrets were very valuable to someone else, I personally would not trust SecurityManager to control potentially malicious 3rd party code running in my environment. (I don't have valuable secrets and I already don't trust Java running in my browser under the SecurityManager to behave.)
You can certainly do the first two things. However, i'm not sure what you mean by "leaking data".
Note, you don't need a customized SecurityManager, you just need a custom policy file.
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