A mutable input has the characteristic that its value may change between different accesses. Sometimes a method does not operate directly on the input parameter. This opens a window of opportunities for exploiting race conditions. A "vary; that is, multiple accesses may see differing values. This characteristic enables potential attacks that exploit race conditions. For example, a time-of-check, time-of-use " (TOCTOU) inconsistency results vulnerability may result when a field contains a value that passes the initial validation and security checks but mutates to a different value during actual usage. changes before use.
Returning references to Additionally, an object's state may get corrupted if it returns references to internal mutable components . Accessors must therefore provides an attacker with the opportunity to corrupt the state of the object. Consequently, accessor methods must return defensive copies of internal mutable objects (see OBJ05-J. Do not return references to private mutable class members for more information).
Noncompliant Code Example
A TOCTOU inconsistency exists in this code sample. Since This noncompliant code example contains a TOCTOU vulnerability. Because cookie
is a mutable input, a malicious an attacker may can cause the cookie it to expire between the initial check (the hasExpired()
call) and the actual use (the doLogic()
call).
Code Block | ||
---|---|---|
| ||
import java.net.HttpCookie; public final class MutableDemo { // java.net.HttpCookie is mutable public void UseMutableInputuseMutableInput(HttpCookie cookie) { if (cookie == null) { throw new NullPointerException(); } //check Check ifwhether cookie has expired if (cookie.hasExpired()) { //cookie Cookie is no longer valid,; handle condition by throwing an exception } doLogic(cookie); //cookie Cookie may have expired since time of check resulting in an exceptiondoLogic(cookie); } } |
Compliant Solution
The problem is alleviated by creating a copy of the mutable input and using it to perform operations so that the original object is left unscathed. This can be realized by implementing the {{This compliant solution avoids the TOCTOU vulnerability by copying the mutable input and performing all operations on the copy. Consequently, an attacker's changes to the mutable input cannot affect the copy. Acceptable techniques include using a copy constructor or implementing the Wiki Markup java.lang.Cloneable
}} interface and declaring a {{public}} clone method or by using a copy constructor. Performing a manual copy of object state within the caller becomes necessary if the mutable class is declared {{final}} (that is, it cannot provide an accessible copy method). (See \[[Guideline 2-1 Create a copy of mutable inputs and outputs|http://java.sun.com/security/seccodeguide.html]\].) Note that the input validation must follow after the creation of the copya public clone()
method (for classes not declared final). In cases such as HttpCookie
where the mutable class is declared final—that is, it cannot provide an accessible copy method—perform a manual copy of the object state within the caller (see OBJ04-J. Provide mutable classes with copy functionality to safely allow passing instances to untrusted code for more information). Note that any input validation must be performed on the copy rather than on the original object.
Code Block | ||
---|---|---|
| ||
import java.net.HttpCookie; public final class MutableDemo { // java.net.HttpCookie is mutable public void copyMutableInputuseMutableInput(HttpCookie cookie) { if (cookie == null) { throw new NullPointerException(); } // createCreate copy cookie = (HttpCookie)cookie.clone(); //check Check ifwhether cookie has expired if (cookie.hasExpired()) { //cookie Cookie is no longer valid,; handle condition by throwing an exception } doLogic(cookie); } } |
Compliant Solution
Some copy constructors and clone()
methods perform Sometimes, the copy constructor or the clone
method returns a shallow copy of the original instance. For example, invocation of clone()
on an array results in creation of an array instance that shares references to whose elements have the same elements values as the original instance. A deep copy that involves element duplication can be created as shown next.. This shallow copy is sufficient for arrays of primitive types but fails to protect against TOCTOU vulnerabilities when the elements are references to mutable objects, such as an array of cookies. Such cases require a deep copy that also duplicates the reference objects.
This compliant solution demonstrates correct use both of a shallow copy (for the array of int
) and of a deep copy (for the array of cookies):
Code Block | ||
---|---|---|
| ||
public void deepCopy(int[] ints, HttpCookie[] cookies) { if (ints == null || cookies == null) { throw new NullPointerException(); } // shallowShallow copy int[] intsCopy = ints.clone(); // deepDeep copy HttpCookie[] cookiesCopy = new HttpCookie[cookies.length]; for (int i = 0; i < cookies.length; i++) { // manuallyManually create copy of each element in array cookiesCopy[i] = (HttpCookie)cookies[i].clone(); } doLogic(intsCopy, cookiesCopy); } |
Noncompliant Code Example
When the class of a mutable input type is non-final, a malicious subclass may override the clone
method. This is a serious issue unless the non-final input defends against it. This noncompliant example shows such a vulnerable code snippet.is nonfinal or is an interface, an attacker can write a subclass that maliciously overrides the parent class's clone()
method. The attacker's clone()
method can subsequently subvert defensive copying. This noncompliant code example demonstrates this weakness:
Code Block | ||
---|---|---|
| ||
// java.util.ArrayListCollection is mutable and non-finalan interface public void copyNonFinalInputcopyInterfaceInput(ArrayListCollection<String> listcollection) { doLogic(listcollection.clone()); } |
Compliant Solution
In order to copy mutable inputs having a non-final type, create a This compliant solution protects against potential malicious overriding by creating a new instance of the ArrayList
. This instance can now nonfinal mutable input, using the expected class rather than the class of the potentially malicious argument. The newly created instance can be forwarded to any trusted code capable of modifying it.
Code Block | ||
---|---|---|
| ||
// java.util.ArrayList is mutable and non-final
public void copyNonFinalInput(ArrayList list) {
// create new instance of declared input type
list = new ArrayList(list);
doLogic(list);
}
|
Noncompliant Code Example
This noncompliant code example uses the Collection
interface as an input parameter and directly passes it to doLogic()
.
Code Block | ||
---|---|---|
| ||
// java.util.Collection is an interface
public void copyInterfaceInput(Collection<String> collection) {
doLogic(collection);
}
|
Compliant Solution
This compliant solution instantiates a new ArrayList
and forwards it to the doLogic
method.
Code Block | ||
---|---|---|
| ||
public void copyInterfaceInput(Collection<String> collection) { // convertConvert input to trusted implementation collection = new ArrayList(collection); doLogic(collection); } |
Noncompliant Code Example
This noncompliant code example shows a getDate()
accessor method that returns the sole instance of the private Date
object. An untrusted caller will be able to manipulate the instance as it exposes internal mutable components beyond the trust boundaries of the class.
Code Block | ||
---|---|---|
| ||
class MutableClass {
private Date d;
public MutableClass() {
d = new Date();
}
protected Date getDate() {
return d;
}
}
|
Wiki Markup |
---|
Pugh \[[Pugh 09|AA. Java References#Pugh 09]\] cites a vulnerability discovered by the Findbugs static analysis tool in the early betas of jdk 1.7. The class {{sun.security.x509.InvalidityDateExtension}} returned a {{Date}} instance through a {{public}} accessor, without creating defensive copies. |
Compliant Solution
Do not carry out defensive copying using the clone()
method in constructors, where the (non-system) class can be subclassed by untrusted code. This will limit the malicious code from returning a crafted object when the object's clone()
method is invoked.
Despite this advice, this compliant solution recommends returning a clone of the Date
object. While this should not be done in constructors, it is permissible to use it in accessors. This is because there is no danger of a malicious subclass extending the internal mutable Date
object.
...
bgColor | #ccccff |
---|
...
Some objects appear to be immutable because they have no mutator methods. For example, the java.lang.CharSequence
interface describes an immutable sequence of characters. Note, however, that a variable of type CharSequence
is a reference to an underlying object of some other class that implements the CharSequence
interface; that other class may be mutable. When the underlying object changes, the CharSequence
changes. Essentially, the java.lang.CharSequence
interface omits methods that would permit object mutation through that interface but lacks any guarantee of true immutability. Such objects must still be defensively copied before use. For the case of the java.lang.CharSequence
interface, one permissible approach is to obtain an immutable copy of the characters by using the toString()
method. Mutable fields should not be stored in static variables. When there is no other alternative, create defensive copies of the fields to avoid exposing them to untrusted code.
Risk Assessment
Failing to create a copy of a mutable input may enable an attacker to exploit a TOCTOU vulnerability and at other times, result in a TOCTOU vulnerability or expose internal mutable components to untrusted code.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|
OBJ06-J |
Medium |
Probable |
High | P4 | L3 |
Automated Detection
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Parasoft Jtest |
| CERT.OBJ06.CPCL CERT.OBJ06..MPT CERT.OBJ06.SMO CERT.OBJ06.MUCOP | 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 | ||||||
SonarQube |
| S2384 | Mutable members should not be stored or returned directly Implemented for Arrays, Collections and Dates. |
Related Vulnerabilities
CVE-2012-0507 describes an exploit that managed to bypass Java's applet security sandbox and run malicious code on a remote user's machine. The exploit created a data structure that is normally impossible to create in Java but was built using deserialization, and the deserialization process did not perform defensive copies of the deserialized data. See the code examples in SER07-J. Do not use the default serialized form for classes with implementation-defined invariants for more information.
Related Guidelines
Guideline 6-2 / MUTABLE-2: Create copies of mutable output values |
Bibliography
Item 39, "Make Defensive Copies When Needed" | |
"Returning References to Internal Mutable State" |
...
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[SCG 07|AA. Java References#SCG 07]\] Guideline 2-1 Create a copy of mutable inputs and outputs
\[[Bloch 08|AA. Java References#Bloch 08]\] Item 39: Make defensive copies when needed
\[[Pugh 09|AA. Java References#Pugh 09]\] Returning references to internal mutable state |
FIO07-J. Do not assume infinite heap space 07. Input Output (FIO) SER30-J. Do not serialize sensitive data