序列化(构造炸弹)
public void serializable() throws IOException {
Set<Object> root = new HashSet<>();
Set<Object> s1 = root;
Set<Object> s2 = new HashSet<>();
for (int i = 0; i < 100; i++) {
Set<Object> t1 = new HashSet<>();
Set<Object> t2 = new HashSet<>();
t1.add("foo"); // Make t1 unequal to t2
s1.add(t1); s1.add(t2);
s2.add(t1); s2.add(t2);
s1 = t1;
s2 = t2;
}
String filePath="/Users/apple/Desktop/object";
try(ObjectOutputStream objectOutputStream=new ObjectOutputStream(new FileOutputStream(filePath));){
objectOutputStream.writeObject(root);
}
}
先构建一个根节点root,里面存放两个set引用,每个set再存放两个新的set的引用,以此类推,循环100次。
每个节点包含至多3个元素,层次结构大致是一棵树,树的深度为101。共创建201个对象。
反序列化(引爆)
public void deserializable() throws IOException, ClassNotFoundException {
String filePath="/Users/apple/Desktop/object";
try(ObjectInputStream inputStream=new ObjectInputStream(new FileInputStream(filePath))) {
Set<Object> set=(Set<Object>) inputStream.readObject();
}
}
执行这段代码的后果是什么呢?它会一直运行,不会报错。执行次数与树的深度成指数关系,
所以深度为100,大概有
2
100
2^{100}
2100次执行。
原理解释
201个对象,序列化以后就5744个字节,为啥反序列化会执行那么多次?
HashSet 重写了readObject()方法
关键是这段逻辑,众所周知,HashSet 底层使用HashMap实现的
// Read in all elements in the proper order.
for (int i=0; i<size; i++) {
@SuppressWarnings("unchecked")
E e = (E) s.readObject();
map.put(e, PRESENT);
}
所以调用链为
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
hash()里的key是HashSet,继承了AbstractSet的hashCode()方法。
可以看出计算当前对象的hashCode 需要对其所有元素进行累加,
而其元素又是set集合,递归调用。
public int hashCode() {
int h = 0;
Iterator<E> i = iterator();
while (i.hasNext()) {
E obj = i.next();
if (obj != null)
h += obj.hashCode();
}
return h;
}
使用建议
上述例子源自于《effective java》(google 首席架构师所著,必看)。
正如书里建议的那样。
尽可能的不用java序列化,优先考虑json和protocal buffers
如果不得不用
永远不要反序列化不被信任的数据
如果不得不反序列化
就要使用反序列化过滤,java9新增的 object deserilization filtering,这一功能已
移植到ObjectInputFilter