Making defensive copies of mutable method parameters mitigate mitigates against a variety of security vulnerabilities; see OBJ06-J. Defensively copy mutable inputs and mutable internal components for additional information. However, inappropriate use of the clone()
method can allow an attacker to exploit vulnerabilities by providing arguments that appear normal but subsequently return unexpected values. Such objects may consequently bypass validation and security checks. When such a class is might be passed as an argument to a method, treat the argument as untrusted, and do not use the clone()
method provided by the class. Also, do not use the clone()
method of nonfinal classes to make defensive copies.
This guideline is a specific instance of OBJ58-JGof 15. Do not rely on methods that can be overridden methods provided by untrusted code.
Noncompliant Code Example
...
Code Block | ||
---|---|---|
| ||
class MaliciousDate extends java.util.Date { @Override public MaliciousDate clone() { // maliciousMalicious code goes here } } |
If, however, the attacker can only provide a malicious date with lessened privileges, the attacker can still produce a malicious date that bypasses validation, bypass validation but still confounds confound the remainder of the program. Consider this example:
...
This malicious date will appear to be a benign date class the first time that getTime()
is invoked. This allows it to bypass validation in the storeDateInDB()
method. However, the time that is actaully actually stored in the database will be incorrect.
...
This compliant solution avoids using the clone()
method. Instead, it creates a new java.util.Date
object that is subsequently used for access control checks and for insertion into the database:
...
This noncompliant code example shows a constructor of the Java core class AtomicReferenceArray
as of present in the Java 1.7.0 update 2:
Code Block | ||||
---|---|---|---|---|
| ||||
public AtomicReferenceArray(E[] array) { // Visibility guaranteed by final field guarantees this.array = array.clone(); } |
This code was subsequently invoked by an the Flashback exploit called Flashback that infected 600,000 Macintosh computers in April 2012.1
Compliant Solution (CVE-2012-0507)
In Java 1.7.0 update 3, this code the constructor was modified to use the Arrays.copyOf()
method instead of the clone()
method, as follows:
Code Block | ||||
---|---|---|---|---|
| ||||
public AtomicReferenceArray(E[] array) { // Visibility guaranteed by final field guarantees this.array = Arrays.copyOf(array, array.length, Object[].class); } |
...