...
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.
...
This approach is useful when the instance fields are declared final.
Compliant Solution (clone()
)
...
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:
...
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 unmodifiable immutable view class. This class overrides mutable methods to throw an exception, protecting the mutable class.
Code Block | ||
---|---|---|
| ||
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.
...
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 |
| 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] |
...
...