Java Reference
In-Depth Information
10.
Do
not
use
the
clone()
method
to
copy
untrusted
method
parameters
Making defensive copies of mutable method parameters mitigates against a variety of se-
curityvulnerabilities; see
The CERT
®
Oracle
®
Secure Coding Standard for Java
™
[Long
2012],“OBJ06-J.Defensivelycopymutableinputsandmutableinternalcomponents,”for
additional information. However, inappropriate use of the
clone()
method can allow an
attacker to exploit vulnerabilities by providing arguments that appear normal but subse-
quently return unexpected values. Such objects may consequently bypass validation and
security checks. When such a class 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
Guideline 15
, “
Do not rely on methods that can
Noncompliant Code Example
This noncompliant code example defines a
validateValue()
method that validates a
time value:
private Boolean validateValue(long time) {
// Perform validation
return true; // If the time is valid
}
private void storeDateInDB(java.util.Date date)
throws SQLException {
final java.util.Date copy = (java.util.Date)date.clone();
if (validateValue(copy.getTime())) {
Connection con =
DriverManager.getConnection(
"jdbc:microsoft:sqlserver://<HOST>:1433",
"<UID>", "<PWD>"
);
PreparedStatement pstmt =
con.prepareStatement("UPDATE ACCESSDB SET TIME = ?");
pstmt.setLong(1, copy.getTime());
// ...
}
}