2023-05-03 11:06:20 +02:00
== Why is this an issue?
2020-06-30 12:47:33 +02:00
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.
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
Instead, the ``++instanceof++`` operator or the ``++Class.isAssignableFrom()++`` method should be used to check the object's underlying type.
2020-06-30 12:47:33 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2020-06-30 12:47:33 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2020-06-30 12:47:33 +02:00
----
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;
}
}
----
2023-05-03 11:06:20 +02:00
=== Compliant solution
2020-06-30 12:47:33 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2020-06-30 12:47:33 +02:00
----
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;
}
}
----
2023-05-03 11:06:20 +02:00
== Resources
2021-09-21 15:40:35 +02:00
2022-04-07 08:53:59 -05:00
* https://cwe.mitre.org/data/definitions/486[MITRE, CWE-486] - Comparison of Classes by Name
2021-09-21 15:40:35 +02:00
* https://wiki.sei.cmu.edu/confluence/x/eDdGBQ[CERT, OBJ09-J.] - Compare classes and not class names
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Use an ["instanceof"|"isAssignableFrom()"] comparison instead.
2021-09-20 15:38:42 +02:00
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]