Loading Untrusted Code

Let’s continue our Server example. Suppose now that you want to modify the server so that it can load Service classes over the network from an arbitrary URL. Suppose also that you want to give Service classes the ability to read and write files from a “scratch” directory on the local system. You can accomplish this by writing a simple class that uses URLClassLoader to load service classes and pass them to an instance of the Server class. To make it work, however, you also have to develop an appropriate security policy file.

Example 7-1 shows our SafeServer class. Like the original Server class, this one expects a list of Service classes and port numbers on the command line. But the first command-line argument it expects is the URL from which the service classes should be downloaded.

Example 7-1. SafeServer.java

package je3.security; import je3.net.Server; import java.io.*; import java.net.*; import java.security.*; /** * This class is a program that uses the Server class defined in Chapter 5. * Server would load arbitrary "Service" classes to provide services. * This class is an alternative program to start up a Server in a similar * way. The difference is that this one uses a SecurityManager and a * ClassLoader to prevent the Service classes from doing anything damaging * or malicious on the local system. This allows us to safely run Service * classes that come from untrusted sources. **/ public class SafeServer { public static void main(String[ ] args) ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.