package singleton;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.lang.reflect.Constructor;/** * 用反射和反序列化的方法破解單例模式 * @author weiyx15 * */public class SingletonCrack { public static void main(String[] args) throws Exception { // 正常創(chuàng)建單例對象 SingletonLazy s1 = SingletonLazy.getInstance(); SingletonLazy s2 = SingletonLazy.getInstance(); System.out.println(s1); System.out.println(s2); // 用反射破解單例 Class<SingletonLazy> cls = (Class<SingletonLazy>) Class.forName("singleton.SingletonLazy"); // 獲取SingletonLazy類 Constructor<SingletonLazy> cons = cls.getDeclaredConstructor(null); // 獲取SingletonLazy的構(gòu)造方法 cons.setAccessible(true); // 跳過方法的可見性檢查 SingletonLazy s3 = cons.newInstance(); // 調(diào)用構(gòu)造方法生成新對象 SingletonLazy s4 = cons.newInstance(); // 調(diào)用構(gòu)造方法生成新對象 System.out.println(s3); System.out.println(s4); // 用反序列化破解單例 FileOutputStream fos = new FileOutputStream("object.out"); // 文件輸出流 ObjectOutputStream oos = new ObjectOutputStream(fos); // 對象輸出流 oos.writeObject(s1); // 向文件序列化對象 oos.close(); // 關(guān)閉對象輸出流 fos.close(); // 關(guān)閉文件輸出流 FileInputStream fis = new FileInputStream("object.out"); // 文件輸入流 ObjectInputStream ois = new ObjectInputStream(fis); // 對象輸入流 SingletonLazy s5 = (SingletonLazy) ois.readObject(); // 從文件反序列化對象 ois.close(); // 關(guān)閉對象輸入流 fis.close(); // 關(guān)閉文件輸入流 System.out.println(s5); }}
運行結(jié)果
singleton.SingletonLazy@15db9742 // s1singleton.SingletonLazy@15db9742 // s2singleton.SingletonLazy@6d06d69c // s3singleton.SingletonLazy@7852e922 // s4singleton.SingletonLazy@3b07d329 // s5
從運行結(jié)果可以看到,通過反射可以得到私有構(gòu)造方法,從而實例化兩個不同的對象實例{@code singleton.SingletonLazy@6d06d69c}和{@code singleton.SingletonLazy@7852e922}. 通過反序列化,也可以得到新對象{@code singleton.SingletonLazy@3b07d329}.
以懶漢式單例模式的實現(xiàn)為例,解決反射漏洞和反序列化漏洞的方法如下:
package singleton;import java.io.ObjectStreamException;import java.io.Serializable;/** * 排除了反射漏洞和反序列化漏洞的懶漢式單例模式 * @author weiyx15 * */public class SingletonLazySafe implements Serializable{ private static SingletonLazySafe instance; private SingletonLazySafe() { // 防止反射漏洞通過再次調(diào)用私有構(gòu)造方法實例化新的instance if (instance != null) { throw new RuntimeException(); // 拋出運行時異常 } } public static synchronized SingletonLazySafe getInstance() { if (instance == null) // 如果未實例化,則先實例化 { instance = new SingletonLazySafe(); // 調(diào)用getInstance方法后再實例化對象 } return instance; } /** * 從I/O流讀取對象時會調(diào)用readResolve接口 * 在readResolve接口中直接返回instance對象 * 避免反序列化時重新實例化對象 * @return 單例對象 * @throws ObjectStreamException */ private Object readResolve() throws ObjectStreamException { return instance; }