单例模式的攻击之序列化与反序列化

在单例模式这块,我们花了几个篇幅来讲了里面的道道,使用了几种方式来构建了看似无懈可击的单例。但是真的无懈可击吗?下面几篇文章,我们来聊聊对单例模式的攻击以及该如何防御这些攻击。

破坏单例的可能性有哪些

我们知道要破坏单例,则必须创建对象,那么我们顺着这个思路走,创建对象的方式无非就是new,clone,反序列化,以及反射。

  • new
    单例模式的首要条件就是构造方法私有化,所以new这种方式去破坏单例的可能性是不存在的(在保障线程安全的情况下)
  • clone
    要调用clone方法,那么必须实现Cloneable接口,但是单例模式是不能实现这个接口的,因此排除这种可能性
  • 反序列化
    这个正是本篇文章要讨论的问题,下面详细进行分析。
  • 反射
    且移步下篇文章单例模式的攻击之反射

序列化攻击

为方便测试,我们写个最简单的饿汉式单例模式代码,便于以后测试

/**
 * @Author: ming.wang
 * @Date: 2019/2/20 17:04
 * @Description: 为了演示序列化实现Serializable 接口
 */
public class HungrySingleton implements Serializable {
    private final static HungrySingleton instance;
    static {
        instance=new HungrySingleton();
    }
    private HungrySingleton() {}
    public static HungrySingleton getInstance(){
        return instance;
    }
}

建立一个DestroySingletonTest 测试类,代码如下,简单来说就是采用序列化来破坏单例

/**
 * @Author: ming.wang
 * @Date: 2019/2/21 16:05
 * @Description: 使用反射或反序列化来破坏单例
 */
public class DestroySingletonTest {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //序列化方式破坏单例   测试
        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);
    }
}

我们运行程序,结果打印false,显然单例被破坏了。
那么,我们有什么解决办法能抵挡这种序列化破坏呢?
下面我们对HungrySingleton进行小小的修改 ,添加一个方法readResolve()

public class HungrySingleton implements Serializable {
    private final static HungrySingleton instance;
     ...
     ...
    private Object readResolve()
    {
        return instance;
    }
}

我们重新运行程序,发现此时打印的结果是true。显然,这个小小的改动帮我们抵御了序列化对单例的破坏。
下面我们就简单分析一下,为什么这个改动能够起到扭转乾坤的作用。
我们进入ObjectInputStream.readObject()这个方法体内

....
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();
            }
        }
    }

.....

继续跟进 Object obj = readObject0(false);这个方法

....
  /**
     * 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 分支,我们会走 case TC_OBJECT:这个分支,那么我们继续跟进,在这个分支下调用了checkResolve(readOrdinaryObject(unshared));,我们着重看readOrdinaryObject(unshared)这个方法,跟进去瞅瞅

....
 /**
     * 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;
    }

...

我们抓重点,看下这句代码 obj = desc.isInstantiable() ? desc.newInstance() : null;,我们跟进 desc.isInstantiable()这个方法,看方法注释,简单来说一个类是serializable/externalizable的实例则返回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(),通过查看我们知道这个最终是调用的反射机制生成的新的实例。截止到此时,我们可以解释在未做改动之前,生成了新的实例,单例被破坏的真正原因了。
我们接着分析,既然改动之后,成功抵御了单例的破坏,那么后面肯定有相应的代码实现。我们继续看readOrdinaryObject这个方法。往后看,我们发现了这样一句代码,

...
if (obj != null &&
            handles.lookupException(passHandle) == null &&
            desc.hasReadResolveMethod())
        {
            Object rep = desc.invokeReadResolve(obj);
...
        }
....

接着看desc.hasReadResolveMethod()这个方法,简单来说,就是该类是serializable or externalizable的实例,并且定义了符合要求的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 会发现readResolveMethod = getInheritableMethod( cl, "readResolve", null, Object.class);,符合要求的方法是方法名是readResolve,返回值是Object。
显然定义了符合要求的方法之后,再执行Object rep = desc.invokeReadResolve(obj);反射调用该方法。具体的就是

 private Object readResolve()
    {
        return instance;
    }

这样我们就得到了原来的实例而不是新的实例!!

结论

对于序列化破坏单例,我们的解决方案就是,在单例代码中,增加以下代码

private Object readResolve()
    {
        return instance;
    }

推荐阅读更多精彩内容