Mutable classes allow code external to the class to alter their instance or class fields. Provide means for creating copies of mutable classes so that disposable instances of such classes can be passed to untrusted code. This functionality is useful when methods in other classes must create copies of the particular class instance (see OBJ06-J. Defensively copy mutable inputs and mutable internal components and OBJ05-J. Do not return references to private mutable class members for additional details).
Mutable classes must provide either a copy constructor or a public static factory method that returns a copy of an instance. Alternatively, final classes may advertise their copy functionality by overriding the clone()
method of java.lang.Object
. Use of the clone()
method is secure only for final classes; nonfinal classes must not take this approach.
Trusted callers can be trusted to use the provided copy functionality to make defensive copies before passing object instances to untrusted code. Untrusted callers cannot be trusted to make such defensive copies. Consequently, providing copy functionality does not obviate the need for making defensive copies of inputs received from untrusted code or outputs returned to untrusted code.
Noncompliant Code Example
In this noncompliant code example, MutableClass
uses a mutable field date
of type Date
. Class Date
is also a mutable class. The example is noncompliant because the MutableClass
objects lack copy functionality.
public final class MutableClass { private Date date; public MutableClass(Date d) { this.date = d; } public void setDate(Date d) { this.date = d; } public Date getDate() { return date; } }
When a trusted caller passes an instance of MutableClass
to untrusted code, and the untrusted code modifies that instance (perhaps by incrementing the month or changing the timezone), the object's state can be made inconsistent with respect to its previous state. Similar problems can arise in the presence of multiple threads, even in the absence of untrusted code.
Compliant Solution (Copy Constructor)
This compliant solution uses a copy constructor that initializes a MutableClass
instance when an argument of the same type (or subtype) is passed to it:
public final class MutableClass { // Copy constructor private final Date date; public MutableClass(MutableClass mc) { this.date = new Date(mc.date.getTime()); } public MutableClass(Date d) { this.date = new Date(d.getTime()); // Make defensive copy } public Date getDate() { return (Date) date.clone(); // Copy and return } }
This approach is useful when the instance fields are declared final. Callers request a copy by invoking the copy constructor with an existing MutableClass
instance as its argument.
Compliant Solution (Public Static Factory Method)
This compliant solution exports a public static factory method getInstance()
that creates and returns a copy of a given MutableClass
object instance:
class MutableClass { private final Date date; private MutableClass(Date d) { // Noninstantiable and nonsubclassable this.date = new Date(d.getTime()); // Make defensive copy } public Date getDate() { return (Date) date.clone(); // Copy and return } public static MutableClass getInstance(MutableClass mc) { return new MutableClass(mc.getDate()); } }
This approach is useful when the instance fields are declared final.
Compliant Solution (clone()
)
This compliant solution provides the needed copy functionality by declaring MutableClass
to be final, implementing the Cloneable
interface, and providing an Object.clone()
method that performs a deep copy of the object:
public final class MutableClass implements Cloneable { private Date date; public MutableClass(Date d) { this.date = new Date(d.getTime()); } public Date getDate() { return (Date) date.clone(); } public void setDate(Date d) { this.date = (Date) d.clone(); } public Object clone() throws CloneNotSupportedException { final MutableClass cloned = (MutableClass) super.clone(); cloned.date = (Date) date.clone(); // Manually copy mutable Date object return cloned; } }
Note that the clone()
method must manually clone the Date
object. This step is usually unnecessary when the object contains only primitive fields or fields that refer to immutable objects. However, when the fields contain data such as unique identifiers or object creation times, the clone()
method must calculate and assign appropriate new values for such fields [Bloch 2008].
Mutable classes that define a clone()
method must be declared final
to ensure that untrusted code cannot declare a subclass that overrides the clone()
method to create a spurious instance. The clone()
method should copy all internal mutable state as necessary—in this compliant example, the Date
object.
When untrusted code can call accessor methods passing mutable arguments, create defensive copies of the arguments before they are stored in any instance fields (see OBJ06-J. Defensively copy mutable inputs and mutable internal components for additional information). When retrieving internal mutable state, make a defensive copy of that state before returning it to untrusted code (see OBJ05-J. Do not return references to private mutable class members for additional information).
Defensive copies would be unnecessary if untrusted code always invoked an object's clone()
method on mutable state received from mutable classes and operated only on the cloned copy. Unfortunately, untrusted code has little incentive to do so, and malicious code has every incentive to misbehave. This compliant solution provides a clone()
method to trusted code and also guarantees that the state of the object cannot be compromised when the accessor methods are called directly from untrusted code.
Compliant Solution (clone()
with Final Members)
When a mutable class's instance fields are declared final and lack accessible copy methods, provide a clone()
method, as shown in this compliant solution:
public final class MutableClass implements Cloneable { private final Date date; // final field public MutableClass(Date d) { this.date = new Date(d.getTime()); // Copy in } public Date getDate() { return (Date) date.clone(); // Copy and return } public Object clone() { Date d = (Date) date.clone(); MutableClass cloned = new MutableClass(d); return cloned; } }
Callers can use the clone()
method to obtain an instance of such a mutable class. The clone()
method must create a new instance of the final member class and copy the original state to it. The new instance is necessary because there might not be an accessible copy method available in the member class. If the member class evolves in the future, it is critical to include the new state in the manual copy. Finally, the clone()
method must create and return a new instance of the enclosing class (MutableClass
) using the newly created member instance (d
) [SCG 2009].
Mutable classes that define a clone()
method must be declared final.
Compliant Solution (Unmodifiable Date Wrapper)
If cloning or copying a mutable object is infeasible or expensive, one alternative is to create an immutable view class. This class overrides mutable methods to throw an exception, protecting the mutable class.
class UnmodifiableDateView extends Date { private Date date; public UnmodifiableDateView(Date date) { this.date = date; } public void setTime(long date) { throw new UnsupportedOperationException(); } // Override all other mutator methods to throw UnsupportedOperationException } public final class MutableClass { private Date date; public MutableClass(Date d) { this.date = d; } public void setDate(Date d) { this.date = (Date) d.clone(); } public UnmodifiableDateView getDate() { return new UnmodifiableDateView(date); } }
Exceptions
OBJ04-J-EX0: Sensitive classes should not be cloneable, per OBJ07-J. Sensitive classes must not let themselves be copied.
Risk Assessment
Creating a mutable class without providing copy functionality can result in the data of its instance becoming corrupted when the instance is passed to untrusted code.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
OBJ04-J | Low | Likely | Medium | P6 | L2 |
Automated Detection
Sound automated detection is infeasible in the general case. Heuristic approaches could be useful.
Tool | Version | Checker | Description |
---|---|---|---|
CodeSonar | 4.2 | FB.MALICIOUS_CODE.EI_EXPOSE_REP FB.MALICIOUS_CODE.EI_EXPOSE_REP2 | May expose internal representation by returning reference to mutable object May expose internal representation by incorporating reference to mutable object |
Coverity | 7.5 | FB.EI_EXPOSE_REP2 | Implemented |
Parasoft Jtest | 2024.1 | CERT.OBJ04.CLONE CERT.OBJ04.CPCL CERT.OBJ04.MPT CERT.OBJ04.SMO CERT.OBJ04.MUCOP | Make your 'clone()' method "final" for security Enforce returning a defensive copy in 'clone()' methods Do not pass user-given mutable objects directly to certain types Do not store user-given mutable objects directly into variables Provide mutable classes with copy functionality |
Related Guidelines
CWE-374, Passing Mutable Objects to an Untrusted Method | |
Guideline 6-4 / MUTABLE-4: Support copy functionality for a mutable class |
Bibliography
[API 2014] | |
Item 39, "Make Defensive Copies When Needed" | |
[Security 2006] |
8 Comments
Thomas Hawtin
Because we know that CloneClass.d class is always exactly java.util.Date, we can just call clone() instead of new Date(d.getTime()). The latter is only necessary when dealing with untrusted objects. The example is a bit confused - if we do a security manager check, it is unlikely that the Date object is not malicious.
Dhruv Mohindra
Ok changed to clone() for deep copying:
The security manager check was not used in the context of checking mutable values. Maybe we can just get rid of it for clarity.
Dhruv Mohindra
Here, the security manager checks serve the purpose of checking who is allowed to create a copy of the private data (Sort of an alternative to the incomplete item MSC05-J. Make sensitive classes noncloneable). It will need to use a custom permission should we choose to keep the checks.
I Gede Panca Sutresna
Hi there..
The link FIO00-J. Defensively copy mutable inputs and mutable internal components above should changed to OBJ06-J. Defensively copy mutable inputs and mutable internal components since it's point to that guideline.
Regards,
David Svoboda
fixed
Michael
Hi. Is the case below compliant for this rule?
This case is somewhat similar to the "Compliant Solution (Unmodifiable Date Wrapper)" case above, it provides a cloned Date object to avoid returning original Date object. But the default clone() method is shadow copy, so I think this case should be non-compliant. If the field of "MutableClass" is another object with deep copy clone() method, then this case is compliant. Right?
David Svoboda
Michael:
The overall goal is to prevent multiple classes from sharing a mutable object (Date in this case), where one class might change the object, surprising the other classes. The "Unmodifiable Date Wrapper" compliant solution presumes that the Date passed to the MutableClass constructor is not shared. Your code example is also compliant if the Date passed to its constructor is also not shared. The assumption in the compliant solution was that cloning a Date is expensive (which is not actually true for a java.util.Date object, the example is being hypothetical). So currently the compliant solution is more efficient than your code sample, but your code sample still complies with the rule.
Michael
For the "Compliant Solution (Unmodifiable Date Wrapper)" case above, curious that if there are many mutable fields like "Date" in "MutableClass", do we have to define an unmodifiable view for each field in this solution?