Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Malicious code vulnerability - May expose internal representation by incorporating reference to mutable object

Tags:

java

I have the following code in my dto class.

public void setBillDate(Date billDate) {
    this.billDate = billDate;
}

And I get an error in sonar stated as such and I'm not sure what I'm doing wrong here.

Malicious code vulnerability - May expose internal representation by incorporating reference to mutable object   

The class is a dto and the method is automatically created setter method. What am I doing wrong here. if anyone could explain. it would be a great help.

like image 312
Imesh Chandrasiri Avatar asked Sep 23 '13 08:09

Imesh Chandrasiri


2 Answers

Date is mutable

Using that setter, someone can modify the date instance from outside unintentionally

Consider this

class MyClass {

   private Date billDate;


   public void setBillDate(Date billDate) {
      this.billDate = billDate;
   }

}

now some one can set it

MyClass m = new MyClass();

Date dateToBeSet = new Date();
m.setBillDate(dateToBeSet); //The actual dateToBeSet is set to m

dateToBeSet.setYear(...); 
//^^^^^^^^ Un-intentional modification to dateToBeSet, will also modify the m's billDate 

To avoid this, you may want to Deep-copy before setting

public void setBillDate(Date billDate) {
    this.billDate = new Date(billDate.getTime());
}
like image 142
sanbhat Avatar answered Oct 18 '22 11:10

sanbhat


I wonder why none of the solutions takes null into consideration. A general, null-safe solution should look like this:

public void setBillDate(Date billDate) {
    this.billDate = billDate != null ? new Date(billDate.getTime()) : null;
}
like image 39
m.bemowski Avatar answered Oct 18 '22 11:10

m.bemowski