Home > Articles > Programming > Java

Core Java Security: Class Loaders, Security Managers, and Encryption

  • Print
  • + Share This
Security is a major concern of both the designers and the users of Java technology. This means that unlike other languages and systems, where security was implemented as an afterthought or a reaction to break-ins, security mechanisms are an integral part of Java technology. Cay S. Horstmann and Gary Cornell describe Java's security mechanisms.
This chapter is from the book

When Java technology first appeared on the scene, the excitement was not about a well-crafted programming language but about the possibility of safely executing applets that are delivered over the Internet (see Volume I, Chapter 10 for more information about applets). Obviously, delivering executable applets is practical only when the recipients are sure that the code can't wreak havoc on their machines. For this reason, security was and is a major concern of both the designers and the users of Java technology. This means that unlike other languages and systems, where security was implemented as an afterthought or a reaction to break-ins, security mechanisms are an integral part of Java technology.

Three mechanisms help ensure safety:

  • Language design features (bounds checking on arrays, no unchecked type conversions, no pointer arithmetic, and so on).
  • An access control mechanism that controls what the code can do (such as file access, network access, and so on).
  • Code signing, whereby code authors can use standard cryptographic algorithms to authenticate Java code. Then, the users of the code can determine exactly who created the code and whether the code has been altered after it was signed.

We will first discuss class loaders that check class files for integrity when they are loaded into the virtual machine. We will demonstrate how that mechanism can detect tampering with class files.

For maximum security, both the default mechanism for loading a class and a custom class loader need to work with a security manager class that controls what actions code can perform. You'll see in detail how to configure Java platform security.

Finally, you'll see the cryptographic algorithms supplied in the java.security package, which allow for code signing and user authentication.

As always, we focus on those topics that are of greatest interest to application programmers. For an in-depth view, we recommend the book Inside Java 2 Platform Security: Architecture, API Design, and Implementation, 2nd ed., by Li Gong, Gary Ellison, and Mary Dageforde (Prentice Hall PTR 2003).

Class Loaders

A Java compiler converts source instructions for the Java virtual machine. The virtual machine code is stored in a class file with a .class extension. Each class file contains the definition and implementation code for one class or interface. These class files must be interpreted by a program that can translate the instruction set of the virtual machine into the machine language of the target machine.

Note that the virtual machine loads only those class files that are needed for the execution of a program. For example, suppose program execution starts with MyProgram.class. Here are the steps that the virtual machine carries out.

  1. The virtual machine has a mechanism for loading class files, for example, by reading the files from disk or by requesting them from the Web; it uses this mechanism to load the contents of the MyProgram class file.
  2. If the MyProgram class has fields or superclasses of another class type, their class files are loaded as well. (The process of loading all the classes that a given class depends on is called resolving the class.)
  3. The virtual machine then executes the main method in MyProgram (which is static, so no instance of a class needs to be created).
  4. If the main method or a method that main calls requires additional classes, these are loaded next.

The class loading mechanism doesn't just use a single class loader, however. Every Java program has at least three class loaders:

  • The bootstrap class loader
  • The extension class loader
  • The system class loader (also sometimes called the application class loader)

The bootstrap class loader loads the system classes (typically, from the JAR file rt.jar). It is an integral part of the virtual machine and is usually implemented in C. There is no ClassLoader object corresponding to the bootstrap class loader. For example,


returns null.

The extension class loader loads "standard extensions" from the jre/lib/ext directory. You can drop JAR files into that directory, and the extension class loader will find the classes in them, even without any class path. (Some people recommend this mechanism to avoid the "class path from hell," but see the next cautionary note.)

The system class loader loads the application classes. It locates classes in the directories and JAR/ZIP files on the class path, as set by the CLASSPATH environment variable or the -classpath command-line option.

In Sun's Java implementation, the extension and system class loaders are implemented in Java. Both are instances of the URLClassLoader class.

The Class Loader Hierarchy

Class loaders have a parent/child relationship. Every class loader except for the bootstrap class loader has a parent class loader. A class loader is supposed to give its parent a chance to load any given class and only load it if the parent has failed. For example, when the system class loader is asked to load a system class (say, java.util.ArrayList), then it first asks the extension class loader. That class loader first asks the bootstrap class loader. The bootstrap class loader finds and loads the class in rt.jar, and neither of the other class loaders searches any further.

Some programs have a plugin architecture in which certain parts of the code are packaged as optional plugins. If the plugins are packaged as JAR files, you can simply load the plugin classes with an instance of URLClassLoader.

URL url = new URL("file:///path/to/plugin.jar");
URLClassLoader pluginLoader = new URLClassLoader(new URL[] { url });
Class<?> cl = pluginLoader.loadClass("mypackage.MyClass");

Because no parent was specified in the URLClassLoader constructor, the parent of the pluginLoader is the system class loader. Figure 9-1 shows the hierarchy.

Figure 9-1

Figure 9-1 The class loader hierarchy

Most of the time, you don't have to worry about the class loader hierarchy. Generally, classes are loaded because they are required by other classes, and that process is transparent to you.

Occasionally, you need to intervene and specify a class loader. Consider this example.

  • Your application code contains a helper method that calls Class.forName(classNameString).
  • That method is called from a plugin class.
  • The classNameString specifies a class that is contained in the plugin JAR.

The author of the plugin has the reasonable expectation that the class should be loaded. However, the helper method's class was loaded by the system class loader, and that is the class loader used by Class.forName. The classes in the plugin JAR are not visible. This phenomenon is called classloader inversion.

To overcome this problem, the helper method needs to use the correct class loader. It can require the class loader as a parameter. Alternatively, it can require that the correct class loader is set as the context class loader of the current thread. This strategy is used by many frameworks (such as the JAXP and JNDI frameworks that we discussed in Chapters 2 and 4).

Each thread has a reference to a class loader, called the context class loader. The main thread's context class loader is the system class loader. When a new thread is created, its context class loader is set to the creating thread's context class loader. Thus, if you don't do anything, then all threads have their context class loader set to the system class loader.

However, you can set any class loader by calling

Thread t = Thread.currentThread();

The helper method can then retrieve the context class loader:

Thread t = Thread.currentThread();
ClassLoader loader = t.getContextClassLoader();
Class cl = loader.loadClass(className);

The question remains when the context class loader is set to the plugin class loader. The application designer must make this decision. Generally, it is a good idea to set the context class loader when invoking a method of a plugin class that was loaded with a different class loader. Alternatively, the caller of the helper method can set the context class loader.

Using Class Loaders as Namespaces

Every Java programmer knows that package names are used to eliminate name conflicts. There are two classes called Date in the standard library, but of course their real names are java.util.Date and java.sql.Date. The simple name is only a programmer convenience and requires the inclusion of appropriate import statements. In a running program, all class names contain their package name.

It might surprise you, however, that you can have two classes in the same virtual machine that have the same class and package name. A class is determined by its full name and the class loader. This technique is useful for loading code from multiple sources. For example, a browser uses separate instances of the applet class loader class for each web page. This allows the virtual machine to separate classes from different web pages, no matter what they are named. Figure 9-2 shows an example. Suppose a web page contains two applets, provided by different advertisers, and each applet has a class called Banner. Because each applet is loaded by a separate class loader, these classes are entirely distinct and do not conflict with each other.

Figure 9-2

Figure 9-2 Two class loaders load different classes with the same name

Writing Your Own Class Loader

You can write your own class loader for specialized purposes. That lets you carry out custom checks before you pass the bytecodes to the virtual machine. For example, you can write a class loader that can refuse to load a class that has not been marked as "paid for."

To write your own class loader, you simply extend the ClassLoader class and override the method.

findClass(String className)

The loadClass method of the ClassLoader superclass takes care of the delegation to the parent and calls findClass only if the class hasn't already been loaded and if the parent class loader was unable to load the class.

Your implementation of this method must do the following:

  1. Load the bytecodes for the class from the local file system or from some other source.
  2. Call the defineClass method of the ClassLoader superclass to present the bytecodes to the virtual machine.

In the program of Listing 9-1, we implement a class loader that loads encrypted class files. The program asks the user for the name of the first class to load (that is, the class containing main) and the decryption key. It then uses a special class loader to load the specified class and calls the main method. The class loader decrypts the specified class and all nonsystem classes that are referenced by it. Finally, the program calls the main method of the loaded class (see Figure 9-3).

Figure 9-3

Figure 9-3 The ClassLoaderTest program

For simplicity, we ignore 2,000 years of progress in the field of cryptography and use the venerable Caesar cipher for encrypting the class files.

Our version of the Caesar cipher has as a key a number between 1 and 255. To decrypt, simply add that key to every byte and reduce modulo 256. The Caesar.java program of Listing 9-2 carries out the encryption.

So that we do not confuse the regular class loader, we use a different extension, .caesar, for the encrypted class files.

To decrypt, the class loader simply subtracts the key from every byte. In the companion code for this book, you will find four class files, encrypted with a key value of 3—the traditional choice. To run the encrypted program, you need the custom class loader defined in our ClassLoaderTest program.

Encrypting class files has a number of practical uses (provided, of course, that you use a cipher stronger than the Caesar cipher). Without the decryption key, the class files are useless. They can neither be executed by a standard virtual machine nor readily disassembled.

This means that you can use a custom class loader to authenticate the user of the class or to ensure that a program has been paid for before it will be allowed to run. Of course, encryption is only one application of a custom class loader. You can use other types of class loaders to solve other problems, for example, storing class files in a database.

Listing 9-1. ClassLoaderTest.java

  1. import java.io.*;
  2. import java.lang.reflect.*;
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import javax.swing.*;
  7. /**
  8.  * This program demonstrates a custom class loader that decrypts class files.
  9.  * @version 1.22 2007-10-05
 10.  * @author Cay Horstmann
 11.  */
 12. public class ClassLoaderTest
 13. {
 14.    public static void main(String[] args)
 15.    {
 16.       EventQueue.invokeLater(new Runnable()
 17.          {
 18.             public void run()
 19.             {
 21.                JFrame frame = new ClassLoaderFrame();
 22.                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 23.                frame.setVisible(true);
 24.             }
 25.          });
 26.    }
 27. }
 29. /**
 30.  * This frame contains two text fields for the name of the class to load and the decryption key.
 31.  */
 32. class ClassLoaderFrame extends JFrame
 33. {
 34.    public ClassLoaderFrame()
 35.    {
 36.       setTitle("ClassLoaderTest");
 38.       setLayout(new GridBagLayout());
 39.       add(new JLabel("Class"), new GBC(0, 0).setAnchor(GBC.EAST));
 40.       add(nameField, new GBC(1, 0).setWeight(100, 0).setAnchor(GBC.WEST));
 41.       add(new JLabel("Key"), new GBC(0, 1).setAnchor(GBC.EAST));
 42.       add(keyField, new GBC(1, 1).setWeight(100, 0).setAnchor(GBC.WEST));
 43.       JButton loadButton = new JButton("Load");
 44.       add(loadButton, new GBC(0, 2, 2, 1));
 45.       loadButton.addActionListener(new ActionListener()
 46.          {
 47.             public void actionPerformed(ActionEvent event)
 48.             {
 49.                runClass(nameField.getText(), keyField.getText());
 50.             }
 51.          });
 52.       pack();
 53.    }
 55.    /**
 56.     * Runs the main method of a given class.
 57.     * @param name the class name
 58.     * @param key the decryption key for the class files
 59.     */
 60.    public void runClass(String name, String key)
 61.    {
 62.       try
 63.       {
 64.          ClassLoader loader = new CryptoClassLoader(Integer.parseInt(key));
 65.          Class<?> c = loader.loadClass(name);
 66.          Method m = c.getMethod("main", String[].class);
 67.          m.invoke(null, (Object) new String[] {});
 68.       }
 69.       catch (Throwable e)
 70.       {
 71.          JOptionPane.showMessageDialog(this, e);
 72.       }
 73.    }
 75.    private JTextField keyField = new JTextField("3", 4);
 76.    private JTextField nameField = new JTextField("Calculator", 30);
 77.    private static final int DEFAULT_WIDTH = 300;
 78.    private static final int DEFAULT_HEIGHT = 200;
 79. }
 81. /**
 82.  * This class loader loads encrypted class files.
 83.  */
 84. class CryptoClassLoader extends ClassLoader
 85. {
 86.    /**
 87.     * Constructs a crypto class loader.
 88.     * @param k the decryption key
 89.     */
 90.    public CryptoClassLoader(int k)
 91.    {
 92.       key = k;
 93.    }
 95.    protected Class<?> findClass(String name) throws ClassNotFoundException
 96.    {
 97.       byte[] classBytes = null;
 98.       try
 99.       {
100.          classBytes = loadClassBytes(name);
101.       }
102.       catch (IOException e)
103.       {
104.          throw new ClassNotFoundException(name);
105.       }
107.       Class<?> cl = defineClass(name, classBytes, 0, classBytes.length);
108.       if (cl == null) throw new ClassNotFoundException(name);
109.       return cl;
110.    }
112.    /**
113.     * Loads and decrypt the class file bytes.
114.     * @param name the class name
115.     * @return an array with the class file bytes
116.     */
117.    private byte[] loadClassBytes(String name) throws IOException
118.    {
119.       String cname = name.replace('.', '/') + ".caesar";
120.       FileInputStream in = null;
121.       in = new FileInputStream(cname);
122.       try
123.       {
124.          ByteArrayOutputStream buffer = new ByteArrayOutputStream();
125.          int ch;
126.          while ((ch = in.read()) != -1)
127.          {
128.             byte b = (byte) (ch - key);
129.             buffer.write(b);
130.          }
131.          in.close();
132.          return buffer.toByteArray();
133.       }
134.       finally
135.       {
136.          in.close();
137.       }
138.    }
140.    private int key;
141. }

Listing 9-2. Caesar.java

 1. import java.io.*;
 3. /**
 4.  * Encrypts a file using the Caesar cipher.
 5.  * @version 1.00 1997-09-10
 6.  * @author Cay Horstmann
 7.  */
 8. public class Caesar
 9. {
10.    public static void main(String[] args)
11.    {
12.       if (args.length != 3)
13.       {
14.          System.out.println("USAGE: java Caesar in out key");
15.          return;
16.       }
18.       try
19.       {
20.          FileInputStream in = new FileInputStream(args[0]);
21.          FileOutputStream out = new FileOutputStream(args[1]);
22.          int key = Integer.parseInt(args[2]);
23.          int ch;
24.          while ((ch = in.read()) != -1)
25.          {
26.             byte c = (byte) (ch + key);
27.             out.write(c);
28.          }
29.          in.close();
30.          out.close();
31.       }
32.       catch (IOException exception)
33.       {
34.          exception.printStackTrace();
35.       }
36.    }
37. }
  • ClassLoader getClassLoader()

    gets the class loader that loaded this class.

  • ClassLoader getParent() 1.2

    returns the parent class loader, or null if the parent class loader is the bootstrap class loader.

  • static ClassLoader getSystemClassLoader() 1.2

    gets the system class loader; that is, the class loader that was used to load the first application class.

  • protected Class findClass(String name) 1.2

    should be overridden by a class loader to find the bytecodes for a class and present them to the virtual machine by calling the defineClass method. In the name of the class, use . as package name separator, and don't use a .class suffix.

  • Class defineClass(String name, byte[] byteCodeData, int offset, int length)

    adds a new class to the virtual machine whose bytecodes are provided in the given data range.

  • URLClassLoader(URL[] urls)
  • URLClassLoader(URL[] urls, ClassLoader parent)

    constructs a class loader that loads classes from the given URLs. If a URL ends in a /, it is assumed to be a directory, otherwise it is assumed to be a JAR file.

  • ClassLoader getContextClassLoader() 1.2

    gets the class loader that the creator of this thread has designated as the most reasonable class loader to use when executing this thread.

  • void setContextClassLoader(ClassLoader loader) 1.2

    sets a class loader for code in this thread to retrieve for loading classes. If no context class loader is set explicitly when a thread is started, the parent's context class loader is used.

  • + Share This
  • 🔖 Save To Your Account