You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 49 Next »

Making defensive copies of mutable method parameters mitigate 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 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-JG. Do not rely on overridden methods provided by untrusted code.

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());
    // ...
  } 
}	

The storeDateInDB() method accepts an untrusted date argument and attempts to make a defensive copy using the clone() method. This allows an attacker to take control of the program by creating a malicious date class that extends Date and whose clone() method perpetrates the attack by failing to provide proper copy functionality. The attacker creates an object of this type and passes it to storeDateInDB() so that the validation succeeds the first time and subsequently mutates the date to a value of his choice. 

Compliant Solution

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:

private void storeDateInDB(java.util.Date date) throws SQLException {
  final java.util.Date copy = new java.util.Date(date.getTime());
  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());
    // ...
  }
}	

Applicability

Using the clone() method to copy untrusted arguments affords attackers the opportunity to execute arbitrary code.

Bibliography

 


  • No labels