1166
Example Language: Java (Bad)
if (inputClass.getClass().getName().equals("TrustedClassName")) {
// Do something assuming you trust inputClass
// ...
}
However, multiple classes can have the same name therefore comparing an object's class by name
can allow untrusted classes of the same name as the trusted class to be use to execute unintended
or incorrect code. To compare the class of an object to the intended class the getClass() method
and the comparison operator "==" should be used to ensure the correct trusted class is used, as
shown in the following example.
Example Language: Java (Good)
if (inputClass.getClass() == TrustedClass.class) {
// Do something assuming you trust inputClass
// ...
}
Example 2:
In this example, the Java class, TrustedClass, overrides the equals method of the parent class
Object to determine equivalence of objects of the class. The overridden equals method first
determines if the object, obj, is the same class as the TrustedClass object and then compares the
object's fields to determine if the objects are equivalent.
Example Language: Java (Bad)
public class TrustedClass {
...
@Override
public boolean equals(Object obj) {
boolean isEquals = false;
// first check to see if the object is of the same class
if (obj.getClass().getName().equals(this.getClass().getName())) {
// then compare object fields
...
if (...) {
isEquals = true;
}
}
return isEquals;
}
...
}
However, the equals method compares the class names of the object, obj, and the TrustedClass
object to determine if they are the same class. As with the previous example using the name of the
class to compare the class of objects can lead to the execution of unintended or incorrect code if
the object passed to the equals method is of another class with the same name. To compare the
class of an object to the intended class, the getClass() method and the comparison operator "=="
should be used to ensure the correct trusted class is used, as shown in the following example.
Example Language: Java (Good)
public boolean equals(Object obj) {
...
// first check to see if the object is of the same class
if (obj.getClass() == this.getClass()) {
...
}
...
CWE Version 4.14
CWE-487: Reliance on Package-level Scope
CWE-487: Reliance on Package-level Scope