在單例模式這塊捉捅,我們花了幾個(gè)篇幅來(lái)講了里面的道道撤防,使用了幾種方式來(lái)構(gòu)建了看似無(wú)懈可擊的單例。但是真的無(wú)懈可擊嗎棒口?下面幾篇文章寄月,我們來(lái)聊聊對(duì)單例模式的攻擊以及該如何防御這些攻擊。
破壞單例的可能性有哪些
我們知道要破壞單例无牵,則必須創(chuàng)建對(duì)象漾肮,那么我們順著這個(gè)思路走,創(chuàng)建對(duì)象的方式無(wú)非就是new合敦,clone初橘,反序列化验游,以及反射充岛。
- new
單例模式的首要條件就是構(gòu)造方法私有化,所以new這種方式去破壞單例的可能性是不存在的(在保障線程安全的情況下) - clone
要調(diào)用clone方法耕蝉,那么必須實(shí)現(xiàn)Cloneable接口崔梗,但是單例模式是不能實(shí)現(xiàn)這個(gè)接口的,因此排除這種可能性 - 反序列化
這個(gè)正是本篇文章要討論的問(wèn)題垒在,下面詳細(xì)進(jìn)行分析蒜魄。 - 反射
且移步下篇文章單例模式的攻擊之反射
序列化攻擊
為方便測(cè)試,我們寫(xiě)個(gè)最簡(jiǎn)單的餓漢式單例模式代碼场躯,便于以后測(cè)試
/**
* @Author: ming.wang
* @Date: 2019/2/20 17:04
* @Description: 為了演示序列化實(shí)現(xiàn)Serializable 接口
*/
public class HungrySingleton implements Serializable {
private final static HungrySingleton instance;
static {
instance=new HungrySingleton();
}
private HungrySingleton() {}
public static HungrySingleton getInstance(){
return instance;
}
}
建立一個(gè)DestroySingletonTest 測(cè)試類谈为,代碼如下,簡(jiǎn)單來(lái)說(shuō)就是采用序列化來(lái)破壞單例
/**
* @Author: ming.wang
* @Date: 2019/2/21 16:05
* @Description: 使用反射或反序列化來(lái)破壞單例
*/
public class DestroySingletonTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
//序列化方式破壞單例 測(cè)試
serializeDestroyMethod();
}
private static void serializeDestroyMethod() throws IOException, ClassNotFoundException {
HungrySingleton hungrySingleton=null;
HungrySingleton hungrySingleton_new=null;
hungrySingleton=HungrySingleton.getInstance();
ByteArrayOutputStream bos=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(bos);
oos.writeObject(hungrySingleton);
ByteArrayInputStream bis=new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois=new ObjectInputStream(bis);
hungrySingleton_new= (HungrySingleton) ois.readObject();
System.out.println(hungrySingleton==hungrySingleton_new);
}
}
我們運(yùn)行程序踢关,結(jié)果打印false伞鲫,顯然單例被破壞了。
那么签舞,我們有什么解決辦法能抵擋這種序列化破壞呢秕脓?
下面我們對(duì)HungrySingleton進(jìn)行小小的修改 ,添加一個(gè)方法readResolve()
public class HungrySingleton implements Serializable {
private final static HungrySingleton instance;
...
...
private Object readResolve()
{
return instance;
}
}
我們重新運(yùn)行程序儒搭,發(fā)現(xiàn)此時(shí)打印的結(jié)果是true吠架。顯然,這個(gè)小小的改動(dòng)幫我們抵御了序列化對(duì)單例的破壞搂鲫。
下面我們就簡(jiǎn)單分析一下傍药,為什么這個(gè)改動(dòng)能夠起到扭轉(zhuǎn)乾坤的作用。
我們進(jìn)入ObjectInputStream.readObject()這個(gè)方法體內(nèi)
....
public final Object readObject()
throws IOException, ClassNotFoundException
{
if (enableOverride) {
return readObjectOverride();
}
// if nested read, passHandle contains handle of enclosing object
int outerHandle = passHandle;
try {
Object obj = readObject0(false);
handles.markDependency(outerHandle, passHandle);
ClassNotFoundException ex = handles.lookupException(passHandle);
if (ex != null) {
throw ex;
}
if (depth == 0) {
vlist.doCallbacks();
}
return obj;
} finally {
passHandle = outerHandle;
if (closed && depth == 0) {
clear();
}
}
}
.....
繼續(xù)跟進(jìn) Object obj = readObject0(false);這個(gè)方法
....
/**
* Underlying readObject implementation.
*/
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));
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);
}
}
....
我們看方法體中的switch 分支,我們會(huì)走 case TC_OBJECT:這個(gè)分支拐辽,那么我們繼續(xù)跟進(jìn)褪秀,在這個(gè)分支下調(diào)用了checkResolve(readOrdinaryObject(unshared));,我們著重看readOrdinaryObject(unshared)這個(gè)方法薛训,跟進(jìn)去瞅瞅
....
/**
* Reads and returns "ordinary" (i.e., not a String, Class,
* ObjectStreamClass, array, or enum constant) object, or null if object's
* class is unresolvable (in which case a ClassNotFoundException will be
* associated with object's handle). Sets passHandle to object's assigned
* handle.
*/
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);
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;
}
...
我們抓重點(diǎn)媒吗,看下這句代碼 obj = desc.isInstantiable() ? desc.newInstance() : null;,我們跟進(jìn) desc.isInstantiable()這個(gè)方法,看方法注釋乙埃,簡(jiǎn)單來(lái)說(shuō)一個(gè)類是serializable/externalizable的實(shí)例則返回true闸英。
/**
* Returns true if represented class is serializable/externalizable and can
* be instantiated by the serialization runtime--i.e., if it is
* externalizable and defines a public no-arg constructor, or if it is
* non-externalizable and its first non-serializable superclass defines an
* accessible no-arg constructor. Otherwise, returns false.
*/
boolean isInstantiable() {
requireInitialized();
return (cons != null);
}
為true的話,那么obj=desc.newInstance()介袜,通過(guò)查看我們知道這個(gè)最終是調(diào)用的反射機(jī)制生成的新的實(shí)例甫何。截止到此時(shí),我們可以解釋在未做改動(dòng)之前遇伞,生成了新的實(shí)例辙喂,單例被破壞的真正原因了。
我們接著分析鸠珠,既然改動(dòng)之后巍耗,成功抵御了單例的破壞,那么后面肯定有相應(yīng)的代碼實(shí)現(xiàn)渐排。我們繼續(xù)看readOrdinaryObject這個(gè)方法炬太。往后看,我們發(fā)現(xiàn)了這樣一句代碼驯耻,
...
if (obj != null &&
handles.lookupException(passHandle) == null &&
desc.hasReadResolveMethod())
{
Object rep = desc.invokeReadResolve(obj);
...
}
....
接著看desc.hasReadResolveMethod()這個(gè)方法,簡(jiǎn)單來(lái)說(shuō)亲族,就是該類是serializable or externalizable的實(shí)例,并且定義了符合要求的readResolve 方法可缚,則返回true
...
/**
* Returns true if represented class is serializable or externalizable and
* defines a conformant readResolve method. Otherwise, returns false.
*/
boolean hasReadResolveMethod() {
requireInitialized();
return (readResolveMethod != null);
}
...
什么是符合要求的readResolve 方法呢霎迫?我們搜索readResolve 會(huì)發(fā)現(xiàn)readResolveMethod = getInheritableMethod( cl, "readResolve", null, Object.class);
,符合要求的方法是方法名是readResolve,返回值是Object帘靡。
顯然定義了符合要求的方法之后知给,再執(zhí)行Object rep = desc.invokeReadResolve(obj);
反射調(diào)用該方法。具體的就是
private Object readResolve()
{
return instance;
}
這樣我們就得到了原來(lái)的實(shí)例而不是新的實(shí)例2饽炼鞠!
結(jié)論
對(duì)于序列化破壞單例,我們的解決方案就是轰胁,在單例代碼中谒主,增加以下代碼
private Object readResolve()
{
return instance;
}