Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Parasoft Jtest 2021.1

Mutable classes allow code external to the class to alter their instance or class fields. It is important to provide Provide means for creating copies of mutable classes so that disposable instances of such classes to allow passing their respective class objects to can be passed to untrusted code. This functionality is useful when methods in other classes need to must create copies of the particular class instance . (See guidelines FIO00see OBJ06-J. Defensively copy mutable inputs and mutable internal components and OBJ11OBJ05-J. Defensively copy Do not return references to private mutable class members before returning their references.) 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 The copying mechanism can be advertised by overriding java.lang.Object's clone() method. Use of the clone() method is secure only secure for final classes. Nonfinal classes must either provide a copy constructor or a public static factory method that returns a copy of the instance.; 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. ConsequentlyOn its own, providing copy functionality does not obviate the need of creating for making defensive copies of input inputs received from untrusted code , and of output that is returned to the same. Only a trusted caller can be expected to responsibly use the copy functionality of the class before passing the object instance to or outputs returned to untrusted code.

Noncompliant Code Example

In this noncompliant code example, MutableClass uses a mutable field date of type Date. The instance member Class Date is also a mutable class. The example is noncompliant because the MutableClass objects lack copy functionality.

Code Block
bgColor#FFcccc

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;	
  }
}

If When a trusted caller passes an instance of MutableClass to untrusted code, and the latter changes the instance of the Date object (like untrusted code modifies that instance (perhaps by incrementing the month or changing the timezone), the state of the object no longer remains consistent with its old state. This problem can also 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:

Code Block
bgColor#ccccff
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:

Code Block
bgColor#ccccff
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 implements provides the needed copy functionality by declaring MutableClass to be final, implementing the Cloneable interface, and overrides the providing an Object.clone() method to create that performs a deep copy of the object. :

Code Block
bgColor#ccccff

public final class MutableClass implements Cloneable {
  private Date date;
	
  public MutableClass(Date d) {
    this.date = new Date(d.getTime());  //copy-in 
  }
	
  public Date getDate() {
    return (Date) date.clone(); //copy and return
  }

  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 manually
    return cloned;
  }
}

Wiki MarkupNote 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. When the fields contain data such as unique identifiers or object creation times, the new values of the fields must be calculated and assigned manually in the {{clone()}} method \[[Bloch 2008|AA. Bibliography#Bloch 08]\].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 mutable class that defines a clone() method must be declared final. This ensures that to ensure that untrusted code cannot declare a subclass and override that overrides the clone() method to supply create a spurious instance. The clone() method should copy all internal mutable state as necessary. In necessary—in this compliant solutionexample, the Date object is copied.

Also, if When untrusted code can call accessor methods and pass passing mutable arguments, it is advisable to copy create defensive copies of the arguments before they are stored in any instance fields . (See guideline FIO00see OBJ06-J. Defensively copy mutable inputs and mutable internal components for additional information). ) When retrieving internal mutable state, make a defensive copy of the members must be created that state before returning their references it to untrusted code . (See guideline OBJ11see OBJ05-J. Defensively copy Do not return references to private mutable class members before returning their references.) for additional information).

Defensive copies This would be unnecessary if untrusted code were to call always invoked an object's clone() method to operate on mutable state received from mutable classes and operated only on the cloned copy, however. 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)

Sometimes, When a mutable class's instance fields are declared final with no and lack accessible copy methods. In this case, provide a clone() method should be provided , as shown in this compliant solution. :

Code Block
bgColor#ccccff

public final class MutableClass implements Cloneable {
  private final Date date; // final field 
	
  public MutableClass(Date d) {
    this.date = new Date(d.getTime());  //copy- Copy in 
  }

  public Date getDate() {
    return (Date) date.clone(); //copy Copy and return
  }

  public Object clone() throws CloneNotSupportedException {
    Date d = new (Date();
    d = (Date)date.clone();
    MutableClass cloned = new MutableClass(d);
    return cloned;
  }
} 

Wiki MarkupCallers 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 no accessible copy method may be 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 2007|AA. Bibliography#SCG 07]\].

Compliant Solution (Copy Constructor)

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 classThis compliant solution uses a copy constructor that initializes a MutableClass instance when an argument of the same type (or subtype) is passed to it.

Code Block
bgColor#ccccff

publicclass finalUnmodifiableDateView classextends MutableClassDate { // Copy Constructor 
  private final Date date;
	
  public MutableClassUnmodifiableDateView(MutableClassDate mcdate)  {
    this.date = new Date(mc.date.getTime());
  }

  public MutableClassvoid setTime(Datelong ddate) {
    this.datethrow = new Date(d.getTimeUnsupportedOperationException());  // Copy-in 
  }

  public// DateOverride getDate() {
    return (Date)date.clone(); // Copy and return
  }
}

This approach is useful when the instance fields are declared final. A copy is requested by invoking the copy constructor with an existing MutableClass instance as 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.

Code Block
bgColor#ccccff

all other mutator methods to throw UnsupportedOperationException
}

public final class MutableClass {
  private final Date date;
	
  privatepublic MutableClass(Date d) { // Noninstantiable and nonsubclassable 
    this.date = new Date(d.getTime());  // Copy-in   
  }
 
  public void setDate(Date getDate(d) {
    returnthis.date = (Date)date d.clone(); // Copy and return
  }

  public staticUnmodifiableDateView MutableClass getInstance(MutableClass mc) getDate() {
    return new MutableClass(mc.getDate())UnmodifiableDateView(date);
  }
}

...

Exceptions

OBJ10OBJ04-J-EX1EX0: Sensitive classes should not be cloneable. (See guideline MSC05, per OBJ07-J. Make sensitive classes noncloneable.) Sensitive classes must not let themselves be copied.

Risk Assessment

Creating a mutable class without without providing copy functionality may can result in the data of its instance becoming corrupted when the instance is passed to untrusted code.

Guideline

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

OBJ10

OBJ04-J

low

Low

likely

Likely

medium

Medium

P6

L2

Automated Detection

...

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Bibliography

Wiki Markup
\[[API 2006|AA. Bibliography#API 06]\] [method clone()|http://java.sun.com/javase/6/docs/api/java/lang/Object.html#clone()]
\[[Security 2006|AA. Bibliography#Security 06]\]
\[[SCG 2007|AA. Bibliography#SCG 07]\] Guideline 2-2 Support copy functionality for a mutable class
\[[SCG 2009|AA. Bibliography#SCG 09]\] Guideline 2-3 Support copy functionality for a mutable class
\[[Bloch 2008|AA. Bibliography#Bloch 08]\] Item 39: Make defensive copies when needed and Item 11: Override clone judiciously
\[[MITRE 2009|AA. Bibliography#MITRE 09]\] [CWE ID 374|http://cwe.mitre.org/data/definitions/374.html] "Mutable Objects Passed by Reference", [CWE ID 375|http://cwe.mitre.org/data/definitions/375.html] "Passing Mutable Objects to an Untrusted Method"

Sound automated detection is infeasible in the general case. Heuristic approaches could be useful.

Tool
Version
Checker
Description
CodeSonar4.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

Coverity7.5

FB.EI_EXPOSE_REP2
FB.EI_EXPOSE_REP

Implemented
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
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

MITRE CWE

CWE-374, Passing Mutable Objects to an Untrusted Method
CWE-375, Returning a Mutable Object to an Untrusted Caller

Secure Coding Guidelines for Java SE, Version 5.0

Guideline 6-4 / MUTABLE-4: Support copy functionality for a mutable class

Bibliography

[API 2014]

Method clone()

[Bloch 2008]

Item 39, "Make Defensive Copies When Needed"
Item 11, "Override Clone Judiciously"

[Security 2006]


...

Image Added Image Added Image AddedOBJ09-J. Immutable classes must prohibit extension      08. Object Orientation (OBJ)      OBJ11-J. Defensively copy private mutable class members before returning their references