Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Parasoft Jtest 2021.1

The Java classes used by a program are not necessarily loaded upon program startup. Many Java Virtual Machines (JVMs) load classes only when they need them.

If untrusted code is permitted to load classes, it may possess the ability to load a malicious class. This is a class that shares a fully-qualified name with a benign class that is required by trusted code. When the trusted code tries to load its benign class, the JVM provides it with the malicious class instead. As a result, if a program permits untrusted code to load classes, it must first preload any benign classes it needs. Once loaded, these benign classes cannot be replaced by untrusted code.

Noncompliant Code Example (Tomcat)

This noncompliant code example shows a vulnerability present in several versions of the Tomcat HTTP web server (fixed in version 6.0.20) that allows untrusted web applications to override the default XML parser used by the system to process web.xml, context.xml and tag library descriptor (TLD) files of other web applications deployed on the Tomcat instance. Consequently, untrusted web applications that install a parser could view and/or alter these files under certain circumstances.

The noncompliant code example shows the code associated with initialization of a new Digester instance in the org.apache.catalina.startup.ContextConfig class. "A Digester processes an XML input stream by matching a series of element nesting patterns to execute Rules that have been added prior to the start of parsing" [Tomcat 2009]. The code to initialize the Digester follows:

Code Block
bgColor#FFCCCC
protected static Digester webDigester = null;

if (webDigester == null) {
  webDigester = createWebDigester();
}

The createWebDigester() method is responsible for creating the Digester. This method calls createWebXMLDigester(), which invokes the method DigesterFactory.newDigester(). This method creates the new digester instance and sets a boolean flag useContextClassLoader to true.

Code Block
bgColor#FFCCCC
// This method exists in the class DigesterFactory and is called by 
// ContextConfig.createWebXmlDigester().
// which is in turn called by ContextConfig.createWebDigester()
// webDigester finally contains the value of digester defined
// in this method.
public static Digester newDigester(boolean xmlValidation,
                     

Wiki Markup
When an API (see table below) is invoked on a {{Class}} object, a comparison is run between the immediate caller's class loader and that of the {{Class}} object. The {{Class}} object is the object on which an API is invoked. According to \[[JLS 05|AA. Java References#JLS 05]\]:

The method getClass returns the Class object that represents the class of the object.

APIs capable of bypassing SecurityManager's checks

java.lang.Class.newInstance

java.lang.Class.getClassLoader

java.lang.Class.getClasses

java.lang.Class.getField(s)

java.lang.Class.getMethod(s)

java.lang.Class.getConstructor(s)

java.lang.Class.getDeclaredClasses

java.lang.Class.getDeclaredField(s)

java.lang.Class.getDeclaredMethod(s)

java.lang.Class.getDeclaredConstructor(s)

java.lang.ClassLoader.getParent

java.lang.ClassLoader.getSystemClassLoader

java.lang.Thread.getContextClassLoader

Security manager checks may get bypassed depending on the immediate caller's class loader.
For instance, in the presence of a security manager, the getSystemClassLoader and getParent methods succeed only if the caller's class loader is the delegation ancestor of the current class loader or if the caller's class loader is the same as the current one or if the code in the current execution context has the RunTimePermission, namely "getClassLoader".

Noncompliant Code Example

The createInstance method is the immediate caller of java.lang.Class.newInstance in this noncompliant example. The newInstance method is being invoked on the dateClass Class object. The issue is that the untrustedCode method can trigger the instantiation of a new class even though it should not have the permission to do so. This behavior is not caught by the security manager.

Code Block
bgColor#FFcccc

public class ExceptionExample {
   public static void untrustedCode() {
     Date now = new Date();
     Class<?> dateClass = now.getClass();
     createInstance(dateClass);
    }

    public static void createInstance(Class<?> dateClass) {
      try { // Create another Date object using the Date Class
            Object o = dateClass.newInstance();boolean xmlNamespaceAware,
            if    (o instanceof Date) {
              Date d =RuleSet (Date)o;rule) {
  Digester digester = new Digester();
  // ...
  digester.setUseContextClassLoader(true);
  // System..out.println("The time is: " + d.toString());.
  return digester;
}

The useContextClassLoader flag is used by Digester to decide which ClassLoader to use when loading new classes. When true, it uses the WebappClassLoader, which is untrusted because it loads whatever classes are requested by various web applications.

Code Block
bgColor#FFCCCC
public ClassLoader getClassLoader() {
  // ...
  if (this.useContextClassLoader) {
    // Uses the context class loader which was previously }set
    // to the }WebappClassLoader
    ClassLoader classLoader =
  catch   (InstantiationException ie) { SystemThread.out.printlncurrentThread(ie).toStringgetContextClassLoader());
  }
  return classloader;
}

The Digester.getParser() method is subsequently called by Tomcat to process web.xml and other files:

Code Block
bgColor#FFCCCC
// Digester.getParser() calls this method.  catch (IllegalAccessException iaeIt is defined in class Digester
public SAXParserFactory getFactory() {
  if (factory == null) { System.out.println(iae.toString()); }    	
    }
}

A related issue is described in SEC03-J. Do not allow tainted parameters while using APIs that perform access checks against the immediate caller.

Compliant Solution

Do not accept Class, ClassLoader or Thread instances from untrusted code. If inevitable, safely acquire these instances by ensuring they come from trusted sources. Additionally, make sure to discard tainted inputs from untrusted code. Likewise, objects returned by the affected methods should not be propagated back to the untrusted code.


    factory = SAXParserFactory.newInstance(); // Uses WebappClassLoader
    // ...
  }
  return (factory);
}

The underlying problem is that the newInstance() method is being invoked on behalf of a web application's class loader, the WebappClassLoader, and it loads classes before Tomcat has loaded all the classes it needs. If a web application has loaded its own Trojan javax.xml.parsers.SAXParserFactory, when Tomcat tries to access a SAXParserFactory, it accesses the Trojan SaxParserFactory installed by the web application rather than the standard Java SAXParserFactory that Tomcat depends on.

Note that the Class.newInstance() method Note that the Class.newInstance()} method requires the class to contain a no-argument constructor. If this requirement is not satisfied, a runtime exception results, which indirectly prevents a security breach.

Risk Assessment

Compliant Solution (Tomcat)

In this compliant solution, Tomcat initializes the SAXParserFactory when it creates the Digester. This guarantees that the SAXParserFactory is constructed using the container's class loader rather than the WebappClassLoader.

The webDigester is also declared final. This prevents any subclasses from assigning a new object reference to webDigester. (See rule OBJ10-J. Do not use public static nonfinal fields for more information.) It also prevents a race condition where another thread could access webDigester before it is fully initialized. (See rule OBJ11-J. Be wary of letting constructors throw exceptions for more information.)

Code Block
bgColor#ccccff
protected static final Digester webDigester = init();

protected Digester init() {
  Digester digester = createWebDigester();
  // Does not use the context Classloader at initialization
  digester.getParser(); 
  return digester;
}

Even if the Tomcat server continues to use the WebappClassLoader to create the parser instance when attempting to process the web.xml and other files, the explicit call to getParser() in init() ensures that the default parser has been set during prior initialization and cannot be replaced. Because this is a one-time setting, future attempts to change the parser are futile.

Risk Assessment

Allowing untrusted code to load classes enables untrusted code to replace benign classes with Trojan classesBypassing Securitymanager checks may seriously compromise the security of a Java application.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

SEC02

SEC03-J

high

probable

medium

P12

L1

Automated Detection

...

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[Gong 03|AA. Java References#Gong 03]\] Section 4.3.2, Class Loader Delegation Hierarchy
\[[SCG 07|AA. Java References#SCG 07]\] Guideline 6-2 Safely invoke standard APIs that bypass SecurityManager checks depending on the immediate caller's class loader

ToolVersionCheckerDescription
Parasoft Jtest9.5CERT.SEC03.ACLDo not access the class loader in a web component

Related Guidelines

Secure Coding Guidelines for the Java Programming Language, Version 3.0

Guideline 6-3. Safely invoke standard APIs that bypass SecurityManager checks depending on the immediate caller's class loader

Android Implementation Details

On Android, the use of DexClassLoader or PathClassLoader requires caution.

Bibliography

[CVE 2011]

CVE-2009-0783

[Gong 2003]

Section 4.3.2, Class Loader Delegation Hierarchy

[JLS 2005]

§4.3.2, The Class Object

[Tomcat 2009]

Bug ID 29936, API Class org.apache.tomcat.util.digester.Digester, Security fix in v 6.0.20


...

Image Added      Image Added      Image AddedSEC36-J. Guard doPrivileged blocks against untrusted invocations      01. Platform Security (SEC)      SEC03-J. Do not expose standard APIs that use the immediate caller's class loader instance to untrusted code