恶意代码漏洞 - 可能通过合并对可变对象的引用来公开内部表示

Ime*_*iri 46 java

我的dto类中有以下代码.

public void setBillDate(Date billDate) {
    this.billDate = billDate;
}
Run Code Online (Sandbox Code Playgroud)

而且我在声纳中出现错误,我不知道我在这里做错了什么.

Malicious code vulnerability - May expose internal representation by incorporating reference to mutable object   
Run Code Online (Sandbox Code Playgroud)

该类是一个dto,该方法是自动创建的setter方法.我在这做错了什么.如果有人能解释.这将是一个很大的帮助.

san*_*hat 107

Date 是可变的

使用该setter,有人可以无意中从外部修改日期实例

考虑一下

class MyClass {

   private Date billDate;


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

}
Run Code Online (Sandbox Code Playgroud)

现在有人可以设置它

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 
Run Code Online (Sandbox Code Playgroud)

为避免这种情况,您可能需要在设置之前进行深层复制

public void setBillDate(Date billDate) {
    this.billDate = new Date(billDate.getTime());
}
Run Code Online (Sandbox Code Playgroud)

  • @yathirigan是的.基本上你需要做深度复制,这样外部修改不会影响这个实例中的对象 (2认同)

m.b*_*ski 42

我想知道为什么没有一个解决方案考虑到零.一般的,空安全的解决方案应该如下所示:

public void setBillDate(Date billDate) {
    this.billDate = billDate != null ? new Date(billDate.getTime()) : null;
}
Run Code Online (Sandbox Code Playgroud)

  • 也许是因为你应该避免使用null值,因为它被许多人视为反模式 (4认同)
  • @Zavael 重点是“你不知道课外的人会用这些价值观做什么”。您不能指望每个人都永远不会向您传递空值。 (2认同)

Aks*_*kur 6

一个反驳的论点可能是,为什么人们会无意中修改日期?如果客户端设置该值然后修改它,那么我们的代码应该反映它,不是吗?如果不是的话,那不是很混乱吗?

我宁愿忽略这个 FindBugs 警告。

如果您想这样做,只需在您的 中添加以下 Maven 依赖项pom.xml

<!-- Findbugs -->
        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>annotations</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>annotations</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>jsr305</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
Run Code Online (Sandbox Code Playgroud)

然后在 POJO 中的类或成员字段级别添加这些注释:

@SuppressFBWarnings(value = { "EI_EXPOSE_REP", "EI_EXPOSE_REP2" }, justification = "I prefer to suppress these FindBugs warnings")
Run Code Online (Sandbox Code Playgroud)

干杯

阿克谢