java-恶意代码漏洞-可能通过合并对可变obj的引用来公开内部表示形式
我的dto类中有以下代码。
public void setBillDate(Date billDate) {
this.billDate = billDate;
}
我在这样的声纳中得到一个错误,我不确定在这里我做错了什么。
Malicious code vulnerability - May expose internal representation by incorporating reference to mutable object
该类是一个dto,该方法是自动创建的setter方法。 我在这里做错了。 如果有人可以解释。 这将是一个很大的帮助。
Imesh Chandrasiri asked 2020-07-17T18:06:20Z
8个解决方案
107 votes
Date是可变的
使用该setter,某人可以无意中从外部修改日期实例
考虑一下
class MyClass {
private Date billDate;
public void setBillDate(Date billDate) {
this.billDate = billDate;
}
}
现在有人可以设置它
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
为避免这种情况,您可能需要在设置之前进行深度复制
public void setBillDate(Date billDate) {
this.billDate = new Date(billDate.getTime());
}
sanbhat answered 2020-07-17T18:06:51Z
42 votes
我不知道为什么所有解决方案都没有考虑到空值。 通用的,空值安全的解决方案应如下所示:
public void setBillDate(Date billDate) {
this.billDate = billDate != null ? new Date(billDate.getTime()) : null;
}
m.bemowski answered 2020-07-17T18:07:11Z
3 votes
Date是可变的
并且您没有创建要传入参数的Date的副本。 因此,如果客户端代码将更改Date对象的值,也会影响您的类。
解决方案是创建Date的副本
public setBillDate(Date billDate){
this.billDate = new Date(billDate.getTime());
}
Narendra Pathai answered 2020-07-17T18:07:40Z
3 votes
也考虑使用克隆。 不要忘记空检查。
public void setBillDate(Date billDate) {
this.billDate = billDate == null ? null : billDate.clone();
}
ashish p answered 2020-07-17T18:08:00Z
3 votes
除了现有答案外,我还提出了一个基于Java 8的基于Optional类的新版本。
public void setBillDate(Date billDate) {
this.billDate = Optional
.ofNullable(billDate)
.map(Date::getTime)
.map(Date::new)
.orElse(null);
}
Nicolas Henneaux answered 2020-07-17T18:08:20Z
1 votes
日期不是一成不变的,即在您的DTO对象上设置billDate之后,就可以对其进行更改。 或者,在代码中:
Date billDate = new Date();
dto.setBillDate(billDate);
billDate.setYear(1990);
// now, dto.getBillDate().getYear() == 1990
您可以使设置者更安全:
public void setBillDate(Date billDate) {
this.billDate = (Date)billDate.clone();
}
isnot2bad answered 2020-07-17T18:08:44Z
1 votes
答案37的答案不是正确的:没有人关心NullPointerExceptions ???
您应该尝试以下方法:
public void setBillDate(Date billDate) {
this.billDate = billDate == null ? billDate : new Date(billDate.getTime());
}
Stéphane Essayie answered 2020-07-17T18:09:08Z
0 votes
一个反驳的论点是,为什么一个人会无意间修改日期? 如果客户设置了值然后修改了它,那么我们的代码应该反映出来,不是吗? 如果不是,那不会令人困惑吗?
我更喜欢忽略此FindBugs警告。
如果要这样做,只需在pom.xml中添加以下Maven依赖项:
com.google.code.findbugs
annotations
3.0.1
provided
com.google.code.findbugs
annotations
3.0.1
provided
com.google.code.findbugs
jsr305
3.0.1
provided
然后在POJO的类或成员字段级别添加这些注释:
@SuppressFBWarnings(value = { "EI_EXPOSE_REP", "EI_EXPOSE_REP2" }, justification = "I prefer to suppress these FindBugs warnings")
干杯
阿克沙伊
Akshay Lokur answered 2020-07-17T18:09:50Z