Home > Articles > Programming > Java

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

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
  • CLASS LOADERS
  • BYTECODE VERIFICATION
  • SECURITY MANAGERS AND PERMISSIONS
  • USER AUTHENTICATION
  • DIGITAL SIGNATURES
  • CODE SIGNING
  • ENCRYPTION

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,

String.class.getClassLoader()

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();
t.setContextClassLoader(loader);

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.*;
  6.
  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.             {
 20.
 21.                JFrame frame = new ClassLoaderFrame();
 22.                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 23.                frame.setVisible(true);
 24.             }
 25.          });
 26.    }
 27. }
 28.
 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");
 37.       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
 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.    }
 54.
 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.    }
 74.
 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. }
 80.
 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.    }
 94.
 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.       }
106.
107.       Class<?> cl = defineClass(name, classBytes, 0, classBytes.length);
108.       if (cl == null) throw new ClassNotFoundException(name);
109.       return cl;
110.    }
111.
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.    }
139.
140.    private int key;
141. }

Listing 9-2. Caesar.java

 
 1. import java.io.*;
 2.
 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.       }
17.
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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020