Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Wiki Markup
The Java classes used by a program are not necessarily loaded upon program startup.  Many JVMs load classes only when they need them.

If untrusted code is permitted to load classes, it may possess the ability to load sensitive classes required by trusted code. If the trusted code has not already loaded these classes, attempts to subsequently do so may result in untrusted classes being substituted for the sensitive classes. Therefore, if a program permits untrusted code to load classes, it must first 'preload' any sensitive classes it needs. Once properly loaded, these sensitive classes may not be 'overrideenoverridden' by untrusted code.

{mc} This text comes from  SCG 2007, it is instructional and maybe useful in an introduction. ~DS
When any method from the following table is invoked on a {{Class}}, {{ClassLoader}} or {{Thread}} object, a comparison is run between the method's immediate caller's class loader and that of the object on which the method is invoked. ([SCG 2007|AA. Bibliography#SCG 07])

|| APIs capable of bypassing SecurityManager's checks ||
| {{Class.newInstance()}} |
| {{Class.getClassLoader()}} |
| {{Class.getClasses()}} |
| {{Class.getField(s)}} |
| {{Class.getMethod(s)}} |
| {{Class.getConstructor(s)}} |
| {{Class.getDeclaredClasses()}} |
| {{Class.getDeclaredField(s)}} |
| {{Class.getDeclaredMethod(s)}} |
| {{Class.getDeclaredConstructor(s)}} |
| {{ClassLoader.getParent()}} |
| {{ClassLoader.getSystemClassLoader()}} |
| {{Thread.getContextClassLoader()}} |

As an example of what constitutes the immediate caller and the object, consider the method {{java.lang.Class.newInstance()}}. Here, the immediate caller is the class that contains this method call whereas the object on which the {{newInstance()}} method is being invoked is referred to as the {{Class}} object ({{classObjectName.newInstance()}}). According to the Java Language Specification \[[JLS 2005|AA. Bibliography#JLS 05]\], the method {{getClass()}} returns the {{Class}} object that represents the class of the object.

If a security manager is present, untrusted code that does not have the permissions to use the API directly is prevented from indirectly using trusted code containing the API call to perform the operation. However, the security manager checks are bypassed if the class loader of the immediate caller is the same as or the delegation ancestor of the class loader of the object on which the API is invoked. Consequently, untrusted callers who do not have the required permissions but are capable of passing the class loader check are able to perform sensitive operations if the trusted code invokes these APIs on their behalf.

The Java SE 6 class loader delegation hierarchy shown below summarizes several cases and highlights those where security checks are bypassed:

!classloaders.jpg!

|| Immediate Caller || ICC\* || Class Object || COC*\* || Class Loader Check || Security Check ||
| C1 | A | C2, C3, C4, C5 | Application, B, C | A is not a delegation ancestor of Application, B or C | Yes |
| C2 | Application | C1 | A | Application is not a delegation ancestor of A | Yes |
| C2 | Application | C3, C4, C5 | B and C | Application is a delegation ancestor of B and C | No |
| C3 | B | C4 | B | The class loader is same for C3 and C4 (B) | No |
| C4 | B | C3 | B | The class loader is same for C4 and C3 (B) | No |
| C5 | C | C1, C2, C3, C4 | Application, A, B, C | C is not a delegation ancestor of Application, A, B or C | Yes |

\* *ICC:* Intermediate caller's class loader
\*\* *COC:* Class object's class loader

Care must be taken when using these APIs that trusted code does not accept {{Class}} objects from untrusted code for further use. For example, if trusted code is loaded by the bootstrap class loader, it can create an instance of a sensitive system class by using the {{newInstance()}} method on the {{Class}} object. If the method that creates the instance is visible to untrusted code, no security manager checks are carried out to prohibit the untrusted code from indirectly creating the class instance (untrusted code must pass the class loader comparison check).

Similarly, instances of trusted {{Class}} objects should not be returned to untrusted code. An untrusted caller can invoke the affected APIs and bypass security checks if its class loader is the same as or the delegation ancestor of the trusted code's class loader.

The table also shows APIs that use the {{ClassLoader}} class object. Class loaders facilitate isolation of trusted components from untrusted ones. They also ensure that the untrusted components do not interfere with each other. The proper choice of the class loader to load a class is of utmost importance. Using untrusted class loaders for performing operations of sensitive nature in trusted code can result in vulnerabilities.

With respect to the {{ClassLoader}} object APIs, security manager checks may also get bypassed depending on the immediate caller's class loader. Consider for instance, the {{ClassLoader.getSystemClassLoader()}} and {{ClassLoader.getParent()}} methods that operate on a {{ClassLoader}} object. In the presence of a security manager, these methods succeed only if the immediate caller's class loader is the delegation ancestor of the current {{ClassLoader}} object's class loader or if the immediate caller's class loader is the same as the current {{ClassLoader}} object's class loader or if the code in the current execution context has the {{getClassLoader}} {{RunTimePermission}}.

Untrusted code can bypass the security checks if its class loader is either the same or a delegation ancestor of the trusted code's class loader. Consequently, care should be taken while specifying the parent of a trusted class loader.  Likewise, trusted code is mustforbidden notto use aany class loader instance supplied by untrusted code. For instance, a class loader instance obtained from untrusted code mustmay notnever be used to load a trusted class that performs some sensitive operation. Also, a trusted class loader that performs security sensitive operations must never be made available to untrusted code by returning its instance.
{mc}


h2. Noncompliant Code Example (Tomcat)

This noncompliant code example illustrates a vulnerability present in several versions of the Tomcat HTTP web server (fixed in v 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 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 limited circumstances.

The noncompliant code example shows the code associated with initialiation 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|AA. Bibliography#Tomcat 09]\].  The code to initialize the {{Digester}} follows:

{code:bgColor=#FFCCCC}
protected static Digester webDigester = null;

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

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

{code: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, boolean xmlNamespaceAware, RuleSet rule) {
  Digester digester = new Digester();
  // ...
  digester.setUseContextClassLoader(true);
  // ...
  return digester;
}
{code}

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:bgColor=#FFCCCC}
public ClassLoader getClassLoader() {
  // ...
  if (this.useContextClassLoader) {
    // Uses the context class loader which was previously set to the WebappClassLoader
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
  }
  return classloader;
}
{code}

Later, the {{Digester.getParser()}} method is internally called by Tomcat to process web.xml and other files:

{code:bgColor=#FFCCCC}
// Digester.getParser() calls this method. It is defined in class Digester
public SAXParserFactory getFactory() {
  if (factory == null) {
    factory = SAXParserFactory.newInstance(); // Uses WebappClassLoader
    // ...
  }
  return (factory);
}
{code}

The underlying problem is that the {{newInstance()}} method is being invoked on behalf of an untrusted web application's class loader, the {{WebappClassLoader}}.  If a web application has previously loaded its own {{javax.xml.parsers.SAXParserFactory}}, then the web application's {{SAXParserFactory}} will be returned by {{getFactory()}}, insteadrather ofthan the standard {{SAXParserFactory}} used by Tomcat.


h2. Compliant Solution (Tomcat)

This compliant solution initializes the {{SAXParserFactory}} when it creates the {{Digester}}. This guarantees that the {{SAXParserFactory}} is constructed using the container's class loader, insteadrather ofthan the {{WebappClassLoader}}.

The {{webDigester}} is also marked final. This prevents any subclasses from assigning a new object reference to {{webDigester}}. See [OBJ04-J. Do not use public static non-final variables] for more infoinformation. It also prevents a race condition where another thread could access {{webDigester}} before it is fully initialized; see [OBJ05-J. Prevent access to partially initialized objects] for more infoinformation.

{code:bgColor=#ccccff}
protected static final Digester webDigester = init();

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

Later, even if the Tomcat server continues stillto usesuse 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 isbeen set during prior initialization and is impossible to replace. Because this is a one-time setting, future attempts to change the parser are futile.

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.


h2. Risk Assessment

Allowing untrusted code to load classes enables untrusted code to replace benign classes with malicious classes.

|| Rule || Severity || Likelihood || Remediation Cost || Priority || Level ||
| SEC04-J | high | probable | medium | {color:red}{*}P12{*}{color} | {color:red}{*}L1{*}{color} |



h3. Automated Detection

TODO


h3. Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the [CERT website|https://www.kb.cert.org/vulnotes/bymetric?searchview&query=FIELD+KEYWORDS+contains+SEC02-J].

h2. Bibliography

| \[[CVE 2008|AA. Bibliography#CVE 08]\] | [CVE-2009-0783|http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-0783] |
| \[[Gong 2003|AA. Bibliography#Gong 03]\] | Section 4.3.2, Class Loader Delegation Hierarchy |
| \[[JLS 2005|AA. Bibliography#JLS 05]\] | Section 4.3.2, "The Class {{Object}}" |
| \[[SCG 2007|AA. Bibliography#SCG 07]\] | Guideline 6-2 Safely invoke standard APIs that bypass SecurityManager checks depending on the immediate caller's class loader |
| \[[Tomcat 2009|AA. Bibliography#Tomcat 09]\] | [Bug ID 29936|https://issues.apache.org/bugzilla/show_bug.cgi?id=29936], API Class {{org.apache.tomcat.util.digester.Digester}}, [Security fix in v 6.0.20|http://tomcat.apache.org/security-6.html] |


----
[!The CERT Oracle Secure Coding Standard for Java^button_arrow_left.png!|SEC03-J. Do not allow tainted variables in doPrivileged blocks]      [!The CERT Oracle Secure Coding Standard for Java^button_arrow_up.png!|14. Platform Security (SEC)]      [!The CERT Oracle Secure Coding Standard for Java^button_arrow_right.png!|void SEC05-J. Do not expose standard APIs that use the immediate caller's class loader instance to untrusted code]