Imesh Chandrasiri Imesh Chandrasiri - 1 year ago 92
Java Question

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

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.

Answer Source

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());
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download