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

后端 未结 8 1500
遇见更好的自我
遇见更好的自我 2020-11-27 05:00

I have the following code in my dto class.

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

And I get an error in s

相关标签:
8条回答
  • 2020-11-27 05:35

    In addition to the existing answers, I propose a new version based on Optional class from Java 8.

    public void setBillDate(Date billDate) {
        this.billDate = Optional
                .ofNullable(billDate)
                .map(Date::getTime)
                .map(Date::new)
                .orElse(null);
    }
    
    0 讨论(0)
  • 2020-11-27 05:38

    Date is not immutable, i.e. your billDate can be changed after it has been set on your DTO object. Or, in code:

    Date billDate = new Date();
    dto.setBillDate(billDate);
    billDate.setYear(1990);
    // now, dto.getBillDate().getYear() == 1990
    

    You can make your setter more secure:

    public void setBillDate(Date billDate) {
        this.billDate = (Date)billDate.clone();
    }
    
    0 讨论(0)
  • 2020-11-27 05:39

    Top answer number 37 is not the correct answer : nobody cares about NullPointerExceptions???

    You should try this instead :

    public void setBillDate(Date billDate) {
        this.billDate = billDate == null ? billDate : new Date(billDate.getTime());
    }
    
    0 讨论(0)
  • 2020-11-27 05:42

    Consider using a clone as well. Don't forget null check.

    public void setBillDate(Date billDate) {
        this.billDate = billDate == null ? null : billDate.clone();
    }
    
    0 讨论(0)
  • 2020-11-27 05:49

    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());
    }
    
    0 讨论(0)
  • 2020-11-27 05:59

    Date is mutable

    and you are not creating a copy of Date that came in to you are parameter. So if the client code will change the value of the Date object, it will affect your class too.

    Solution is to create a copy of Date

    public setBillDate(Date billDate){
       this.billDate = new Date(billDate.getTime());
    }
    
    0 讨论(0)
提交回复
热议问题