2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-05-26 17:14:58 +02:00
Mutable objects are those whose state can be changed. For instance, an array is mutable, but a String is not. Private mutable class members should never be returned to a caller or accepted and stored directly. Doing so leaves you vulnerable to unexpected changes in your class state.
Instead use an unmodifiable ``++Collection++`` (via ``++Collections.unmodifiableCollection++``, ``++Collections.unmodifiableList++``, ...) or make a copy of the mutable object, and store or return the copy instead.
This rule checks that private arrays, collections and Dates are not stored or returned directly.
2021-09-21 15:40:35 +02:00
2023-10-16 16:34:38 +02:00
=== Noncompliant code example
[source,java]
----
class A {
private String [] strings;
public A () {
strings = new String[]{"first", "second"};
}
public String [] getStrings() {
return strings; // Noncompliant
}
public void setStrings(String [] strings) {
this.strings = strings; // Noncompliant
}
}
public class B {
private A a = new A(); // At this point a.strings = {"first", "second"};
public void wreakHavoc() {
a.getStrings()[0] = "yellow"; // a.strings = {"yellow", "second"};
}
}
----
=== Compliant solution
[source,java]
----
class A {
private String [] strings;
public A () {
strings = new String[]{"first", "second"};
}
public String [] getStrings() {
return strings.clone();
}
public void setStrings(String [] strings) {
this.strings = strings.clone();
}
}
public class B {
private A a = new A(); // At this point a.strings = {"first", "second"};
public void wreakHavoc() {
a.getStrings()[0] = "yellow"; // a.strings = {"first", "second"};
}
}
----
2021-09-21 15:40:35 +02:00
2023-05-03 11:06:20 +02:00
== Resources
2021-09-21 15:40:35 +02:00
2024-01-15 17:15:56 +01:00
* CWE - https://cwe.mitre.org/data/definitions/374[CWE-374 - Passing Mutable Objects to an Untrusted Method]
* CWE - https://cwe.mitre.org/data/definitions/375[CWE-375 - Returning a Mutable Object to an Untrusted Caller]
2021-09-21 15:40:35 +02:00
* https://wiki.sei.cmu.edu/confluence/x/OTdGBQ[CERT, OBJ05-J.] - Do not return references to private mutable class members
* https://wiki.sei.cmu.edu/confluence/x/HTdGBQ[CERT, OBJ06-J.] - Defensively copy mutable inputs and mutable internal components
* https://wiki.sei.cmu.edu/confluence/x/VzZGBQ[CERT, OBJ13-J.] - Ensure that references to mutable objects are not exposed
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)
include::../message.adoc[]
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[]
2023-06-22 10:38:01 +02:00
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]