Java Reference
In-Depth Information
% java -Djava.security.manager -Djava.security.policy=Server.policy \
com.davidflanagan.examples.net.Server -control password 4000
When you use this command line, the Java interpreter takes the default security
policy and augments it with the policy specified on the command line. Note that if
you use
==
instead of
=
in the command line, the interpreter ignores the default
policy and uses only the policy you've specified. Our
Server.policy
file should
work either way.
The moral of the story is that if you write a Java application, and you want people
who don't trust you to run it, you should figure out exactly what kind of restricted
actions it takes and develop a policy file for it. Then your users can study the pol-
icy file to see what permissions the application requires. If they're willing to grant
those permissions to your code, they can run your program using the
-D
options
shown earlier, secure in the knowledge that your code can't take any dangerous
actions other than those explicitly allowed by your policy file.
To fully understand Java's access control mechanisms, you'll want to read about
the
java.security.Permission
class and its many subclasses. You should also
read about the
java.security.Policy
class. To be able to create policy files of
your own, you'll want to read about the
policytool
program that ships with the
Java SDK from Sun. See
Java in a Nutshell
. If you want to edit policy files by hand
(which is often easiest), see the security documentation that comes with the SDK
for details on the file format.
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 6-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 6−1: SafeServer.java
package com.davidflanagan.examples.security;
import com.davidflanagan.examples.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