單例模式安全之序列化攻擊
什么是序列化攻擊呢考廉?
簡單說秘豹,一個單例對象經(jīng)過序列化再反序列化后,內(nèi)存中會存在兩個對象昌粤,這樣單例模式就被破壞既绕。
序列化攻擊復(fù)現(xiàn)
序列化攻擊復(fù)過程
- 獲取到單例對象
- 對象序列化持久到磁盤
- 反序列化成對象
這里采用JDK的自帶的序列化方式
單例實現(xiàn)Serializable接口
package com.fine.serialize;
import java.io.Serializable;
/**
* 單例
* volatile 雙重校驗
*
* @author finefine at: 2019-05-03 21:43
*/
public class Singleton implements Serializable {
private static final long serialVersionUID = 1L;
private volatile static Singleton INSTANCE;
private Singleton() {
}
public static Singleton getInstance() {
if (INSTANCE==null){
//同步代碼塊
synchronized (Singleton.class){
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}
測試代碼
package com.fine.serialize;
import java.io.*;
/**
* @author finefine at: 2019-05-03 21:50
*/
public class DeSerailizeAttackTest {
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("object"));
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("object"))) {
//將對象持久化到磁盤中
outputStream.writeObject(singleton);
outputStream.flush();
//從磁盤中反序列化成對象
Singleton singleton1 = (Singleton) inputStream.readObject();
if (singleton == singleton1) {
System.out.println("是同一個對象");
} else {
System.out.println("是兩個不同的對象");
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
結(jié)果輸出了兩個不同的對象
image-20190503221321745
通過debug 可以看到確實是兩個不同的對象
image-20190503221436080
反序列化攻擊源碼分析
反序列化攻擊的問題代碼在此
//默認(rèn)情況下 該方法重新new對象
private Object readOrdinaryObject(boolean unshared)
throws IOException
{
if (bin.readByte() != TC_OBJECT) {
throw new InternalError();
}
ObjectStreamClass desc = readClassDesc(false);
desc.checkDeserialize();
Class<?> cl = desc.forClass();
if (cl == String.class || cl == Class.class
|| cl == ObjectStreamClass.class) {
throw new InvalidClassException("invalid class descriptor");
}
Object obj;
try {
obj = desc.isInstantiable() ? desc.newInstance() : null;
} catch (Exception ex) {
throw (IOException) new InvalidClassException(
desc.forClass().getName(),
"unable to create instance").initCause(ex);
}
passHandle = handles.assign(unshared ? unsharedMarker : obj);
ClassNotFoundException resolveEx = desc.getResolveException();
if (resolveEx != null) {
handles.markException(passHandle, resolveEx);
}
if (desc.isExternalizable()) {
readExternalData((Externalizable) obj, desc);
} else {
readSerialData(obj, desc);
}
handles.finish(passHandle);
//經(jīng)過上面的代碼,新對象已經(jīng)被new 出來了, hasReadResolveMethod這個方法很關(guān)鍵
//下面的邏輯就是說 如果該類存在一個readResolve 方法就會調(diào)用該方法涮坐,并重新替換新的對象凄贩,如果不存在就直接把new出來的對象返回出去
if (obj != null &&
handles.lookupException(passHandle) == null &&
desc.hasReadResolveMethod())
{
Object rep = desc.invokeReadResolve(obj);
if (unshared && rep.getClass().isArray()) {
rep = cloneArray(rep);
}
if (rep != obj) {
// Filter the replacement object
if (rep != null) {
if (rep.getClass().isArray()) {
filterCheck(rep.getClass(), Array.getLength(rep));
} else {
filterCheck(rep.getClass(), -1);
}
}
handles.setObject(passHandle, obj = rep);
}
}
return obj;
}
/**
*
* 返回該類是否有readResolve方法
*/
boolean hasReadResolveMethod() {
requireInitialized();
return (readResolveMethod != null);
}
由于Singleton 類中不存在readResolve ,所以也就導(dǎo)致反序列化出新的對象了袱讹。
解決方法
- 添加readResolve方法
- 使用枚舉類
添加readResolve
Singleton 代碼
package com.fine.serialize;
import java.io.Serializable;
/**
* 單例
* volatile 雙重校驗
*
* @author finefine at: 2019-05-03 21:43
*/
public class Singleton implements Serializable {
private static final long serialVersionUID = 1L;
private volatile static Singleton INSTANCE;
private Singleton() {
}
public static Singleton getInstance() {
if (INSTANCE==null){
//同步代碼塊
synchronized (Singleton.class){
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
//添加的readResolve方法
private Object readResolve() {
return INSTANCE;
}
}
這里測試代碼不用更改疲扎,看看測試結(jié)果
image-20190503225944248
使用枚舉類
單例代碼
package com.fine.serialize;
import java.io.Serializable;
/**
* @author finefine at: 2019-05-03 23:00
*/
public enum SingletonEnum implements Serializable {
INSTANCE;
private static final long serialVersionUID = 2L;
}
測試代碼
package com.fine.serialize;
import java.io.*;
/**
* @author finefine at: 2019-05-03 23:02
*/
public class DeSerailizeEnumAttackTest {
public static void main(String[] args) {
SingletonEnum singleton = SingletonEnum.INSTANCE;
try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("object"));
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("object"))) {
//將對象持久化到磁盤中
outputStream.writeObject(singleton);
outputStream.flush();
//從磁盤中反序列化成對象
SingletonEnum singleton1 = (SingletonEnum) inputStream.readObject();
if (singleton == singleton1) {
System.out.println("是同一個對象");
} else {
System.out.println("是兩個不同的對象");
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
測試結(jié)果
image-20190504000713071
那為什么這里使用枚舉類就可以避免反射攻擊呢?深入源碼分析
JDK 的反序列化都會調(diào)用到這個方法捷雕,readObject0對每種類型反序列化都做了不同的實現(xiàn)椒丧,當(dāng)對枚舉類進(jìn)行反序列化時進(jìn)入到TC_ENUM分支,最終調(diào)用readEnum方法
private Object readObject0(boolean unshared) throws IOException {
boolean oldMode = bin.getBlockDataMode();
if (oldMode) {
int remain = bin.currentBlockRemaining();
if (remain > 0) {
throw new OptionalDataException(remain);
} else if (defaultDataEnd) {
/*
* Fix for 4360508: stream is currently at the end of a field
* value block written via default serialization; since there
* is no terminating TC_ENDBLOCKDATA tag, simulate
* end-of-custom-data behavior explicitly.
*/
throw new OptionalDataException(true);
}
bin.setBlockDataMode(false);
}
byte tc;
while ((tc = bin.peekByte()) == TC_RESET) {
bin.readByte();
handleReset();
}
depth++;
totalObjectRefs++;
try {
switch (tc) {
case TC_NULL:
return readNull();
case TC_REFERENCE:
return readHandle(unshared);
case TC_CLASS:
return readClass(unshared);
case TC_CLASSDESC:
case TC_PROXYCLASSDESC:
return readClassDesc(unshared);
case TC_STRING:
case TC_LONGSTRING:
return checkResolve(readString(unshared));
case TC_ARRAY:
return checkResolve(readArray(unshared));
//枚舉類
case TC_ENUM:
return checkResolve(readEnum(unshared));
//Object
case TC_OBJECT:
return checkResolve(readOrdinaryObject(unshared));
case TC_EXCEPTION:
IOException ex = readFatalException();
throw new WriteAbortedException("writing aborted", ex);
case TC_BLOCKDATA:
case TC_BLOCKDATALONG:
if (oldMode) {
bin.setBlockDataMode(true);
bin.peek(); // force header read
throw new OptionalDataException(
bin.currentBlockRemaining());
} else {
throw new StreamCorruptedException(
"unexpected block data");
}
case TC_ENDBLOCKDATA:
if (oldMode) {
throw new OptionalDataException(true);
} else {
throw new StreamCorruptedException(
"unexpected end of block data");
}
default:
throw new StreamCorruptedException(
String.format("invalid type code: %02X", tc));
}
} finally {
depth--;
bin.setBlockDataMode(oldMode);
}
}
readEnum 最終調(diào)用了Enum.valueOf 返回實例對象
private Enum<?> readEnum(boolean unshared) throws IOException {
if (bin.readByte() != TC_ENUM) {
throw new InternalError();
}
ObjectStreamClass desc = readClassDesc(false);
if (!desc.isEnum()) {
throw new InvalidClassException("non-enum class: " + desc);
}
int enumHandle = handles.assign(unshared ? unsharedMarker : null);
ClassNotFoundException resolveEx = desc.getResolveException();
if (resolveEx != null) {
handles.markException(enumHandle, resolveEx);
}
String name = readString(false);
Enum<?> result = null;
Class<?> cl = desc.forClass();
if (cl != null) {
try {
@SuppressWarnings("unchecked")
//這里找到了實例
Enum<?> en = Enum.valueOf((Class)cl, name);
result = en;
} catch (IllegalArgumentException ex) {
throw (IOException) new InvalidObjectException(
"enum constant " + name + " does not exist in " +
cl).initCause(ex);
}
if (!unshared) {
handles.setObject(enumHandle, result);
}
}
handles.finish(enumHandle);
passHandle = enumHandle;
return result;
}
總結(jié)
經(jīng)過單例模式安全之反射攻擊和本片文章的內(nèi)容救巷,可以發(fā)現(xiàn)壶熏,使用枚舉類實現(xiàn)單例是非常有利的,不用開發(fā)者考慮太多其他的因素浦译。從單例的角度及安全的角度來看久橙,枚舉單例模式有以下三個特點:
- jvm 底層保證線程安全俄占。
- jvm 底層抑制了反射攻擊。
- jdk 序列化方式的特殊處理淆衷,防止了反序列化攻擊。