Mutable classes are those which when instantiated, provide a reference such that the contents of the class can be altered at anytime. It is important to provide means for creating copies of mutable class instances as it allows safe passing in and returning of class objects when they are used within method arguments.
...
In this noncompliant example, mutableClass
MutableClass
uses a mutable Date
object. If the caller changes the instance of the Date
object (like incrementing the month), the class implementation no longer remains consistent with its old state. Both, the constructor as well as the getDate
method are susceptible to abuse. This also defies attempts to implement thread safety.
Code Block | ||
---|---|---|
| ||
public final class mutableClassMutableClass { private Date d; public mutableClass(Date d) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { //check permissions } this.d = d; } public Date getDate() { return this.d; } } |
...
Code Block | ||
---|---|---|
| ||
public final class cloneClassCloneClass implements Cloneable { private Date d; public cloneClass(Date d) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { //check permissions } this.d = new Date(d.getTime()); //copy-in } public Object clone() throws CloneNotSupportedException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { //check permissions } final cloneClass cloned = (cloneClass)super.clone(); cloned.d = new Date( d.getTime() ); //copy mutable Date object return cloned; } public Date getDate() { return new Date(this.d.getTime()); //copy and return } } |
At times, a class is labeled final
with no accessible copy methods. Callers can then obtain an instance of the class, create a new instance with the original state and subsequently proceed to use it. Similarly, mutable objects obtained must also be copied when necessary.
Risk Assessment
TODOCreating a mutable class without a clone
method may result in the data of the class becoming corrupted.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
SEC35-J | ?? low ?? | unlikely | ?? medium | P?? | L?? |
Automated Detection
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[Security 06|AA. Java References#Security 06]\]
\[[API 06|AA. Java References#API 06]\] [ |
object.
clone()|http://java.sun.com/ |
javase/6/docs/api/java/lang/Object.html#clone( |
)] |