...
Conversely, the assumption that the same codebase will result in the same class in a JVM is error-prone. While the misleading assumption is commonly observed to be true in desktop applications, typically this is not the case with J2EE servlet containers. The containers may use different class loader instances to deploy and recall applications at runtime, without having to restart the JVM. In such situations, two objects, whose classes come from the same codebase, may appear to the JVM to be two different classes. Also note that the equals()
method may not return true
when comparing objects originating from the same codebase.
Noncompliant Code Example
This noncompliant code example compares the name of the class of object h
to the string DefaultAuthenticationHandler
and proceeds depending on the result of the comparison.
...
The main issue is that another class may exist with the same name in the JVM.
Compliant Solution
This compliant solution compares the class object of class h
to the class object of the class that the current class loader loads, instead of comparing just the class names.
...
The call to loadClass()
returns the class having the specified name in the current namespace (of the classloader), and the comparison is correctly performed on the two class objects.
Noncompliant Code Example
This noncompliant code example compares the names of the class objects of classes x
and y
using the equals()
method.
Code Block | ||
---|---|---|
| ||
// Determine whether objects x and y have the same class name if (x.getClass().getName().equals( y.getClass().getName() )) { // Code assumes that the objects have the same class } |
Compliant Solution
This compliant solution correctly compares the two objects' classes.
Code Block | ||
---|---|---|
| ||
// Determine whether objects x and y have the same class if (x.getClass() == y.getClass()) { // Code determines whether the objects have the same class } |
Risk Assessment
Comparing classes using their names may give an attacker supplied class undesirable privileges.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
OBJ34- J | medium | unlikely | low | P6 | L2 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[JVMSpec 99|AA. Java References#JVMSpec 99]\] [§2.8.1 Class Names|http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html] \[[Christudas 05|AA. Java References#Christudas 05]\] \[[Mcgraw 98|AA. Java References#Mcgraw 98]\] \[[Wheeler 03|AA. Java References#Wheeler 03]\] [Java|http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/java.html] \[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 486|http://cwe.mitre.org/data/definitions/486.html] "Comparison of Classes by Name" |
...