Write readObject methods defensively

本文探讨了在对象序列化过程中可能出现的安全问题,特别是当序列化的数据被恶意构造时,如何破坏类的不变性,以及如何在readObject方法中进行防御性复制以保护类的安全。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The problem is that the readObject method is effectively another public constructor, and it demands all of the same care as any other constructor. Just as a constructor must check its arguments for validity and make defensive copies of parameters where appropriate, so must a readObject method. If a readObject method fails to do either of these thing, it is a relatively simple matter for an attacker to violate the class's invariant.

Loosely speaking, readObject is a constructor that takes a byte stream as its solo parameter. In normal use, the byte stream is generated by serializing a normally constructed instance. The problem arises when readObject is presented with a byte stream that is artificially constructed to generate an object that voilates the invariant of its class.


private static Object deserialize(byte[] sf){
try{
InputStream is = new ByteArrayInputStream(sf);
ObjectInputStream ois = new ObjectInputStream(is);
return ois.readObject();
}catch(Exception e){
throw new IllegalArgumentException(e);
}
}


The byte array literal used to initialize serializedForm was generated by serializing a normal Period instance and hand-editing the resulting byte stream.
The serialization byte-stream format is described in the Java(TM) Object Serialization Specification.

While the Period instance is created with its invariants intact, it is possible to modify its internal components at will. Once is possession of a mutable Period instance, an attacker might cause great harm by passing the instance on to a class that depends on Period's immutability for its security. This is not so far-fetched: there are classes depend on String's immutability for their security.

When an object is deserialized, it's critical to defensively copy any field containing an object reference that a client must not possess.

Therefore, every serializable immutable class containing private mutable components must defensively copy these components in its readObject method.

A simple litmus test for decideing whether the default readObject method is acceptable for a class:

Would you feel comfortable adding a public constructor that took as parameters the values for each nontransient filed in the object and stored the values in the fields with no validation whatsoever?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值