
Inline adoc files when they are included exactly once. Also fix language tags because this inlining gives us better information on what language the code is written in.
79 lines
1.9 KiB
Plaintext
79 lines
1.9 KiB
Plaintext
== Why is this an issue?
|
|
|
|
There is no requirement that class names be unique, only that they be unique within a package. Therefore trying to determine an object's type based on its class name is an exercise fraught with danger. One of those dangers is that a malicious user will send objects of the same name as the trusted class and thereby gain trusted access.
|
|
|
|
Instead, the ``++instanceof++`` operator or the ``++Class.isAssignableFrom()++`` method should be used to check the object's underlying type.
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,java]
|
|
----
|
|
package computer;
|
|
class Pear extends Laptop { ... }
|
|
|
|
package food;
|
|
class Pear extends Fruit { ... }
|
|
|
|
class Store {
|
|
|
|
public boolean hasSellByDate(Object item) {
|
|
if ("Pear".equals(item.getClass().getSimpleName())) { // Noncompliant
|
|
return true; // Results in throwing away week-old computers
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public boolean isList(Class<T> valueClass) {
|
|
if (List.class.getName().equals(valueClass.getName())) { // Noncompliant
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
----
|
|
|
|
=== Compliant solution
|
|
|
|
[source,java]
|
|
----
|
|
class Store {
|
|
|
|
public boolean hasSellByDate(Object item) {
|
|
if (item instanceof food.Pear) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public boolean isList(Class<T> valueClass) {
|
|
if (valueClass.isAssignableFrom(List.class)) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
* https://cwe.mitre.org/data/definitions/486[MITRE, CWE-486] - Comparison of Classes by Name
|
|
* https://wiki.sei.cmu.edu/confluence/x/eDdGBQ[CERT, OBJ09-J.] - Compare classes and not class names
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Use an ["instanceof"|"isAssignableFrom()"] comparison instead.
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::../comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|