Running Untrusted Code

Recall the Server example of Chapter 5. That generic server class dynamically loaded and ran Service implementations. Suppose that you are a system administrator in charge of the Server program, and that you don’t trust the programmers who are developing the Service implementations; you’re afraid that they’ll accidentally (or maliciously) include damaging code in their Service classes. Java makes it easy to run these untrusted classes with access-control mechanisms in place, to prevent them from doing anything they shouldn’t.

Access control in Java is performed by the SecurityManager and AccessController classes. When a security manager has been registered, Java checks with it every time it is asked to perform any operation that might be restricted, such as reading or writing a file or establishing a network connection. In Java 1.2 and later, the SecurityManager class uses the AccessController class to perform these access-control checks, and the AccessController in turn refers to a Policy file that describes exactly which Permission objects are granted to what code.

As of Java 1.2, it is quite simple to run code under the watchful eye of a security manager. Simply run the Java interpreter using the -D option to set the java.security.manager property. For example, to run the Server class under a security manager, start it like this:

% java -Djava.security.manager je3.net.Server \
-control password 4000

When you do this, both the Server class and the control ...

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.