如何防止单例模式被JAVA反射攻击
shimuxi
8年前
<p>单例模式相信大家都知道,用过的人不在少数。之前写过一篇博文《singleton模式四种线程安全的实现》(参见:http://blog.csdn.NET/u013256816/article/details/50427061),讲诉了单例模式的四种写法,并指出占位符模式的写法比较ok,详见如下:</p> <pre> <code class="language-java">package com.effective.singleton; public class Elvis { private static boolean flag = false; private Elvis(){ } private static class SingletonHolder{ private static final Elvis INSTANCE = new Elvis(); } public static Elvis getInstance() { return SingletonHolder.INSTANCE; } public void doSomethingElse() { } }</code></pre> <p>但这都是基于一个条件:确保不会通过反射机制调用私有的构造器。</p> <p>这里举个例子,通过JAVA的反射机制来“攻击”单例模式:</p> <pre> <code class="language-java">package com.effective.singleton; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class ElvisReflectAttack { public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { Class<?> classType = Elvis.class; Constructor<?> c = classType.getDeclaredConstructor(null); c.setAccessible(true); Elvis e1 = (Elvis)c.newInstance(); Elvis e2 = Elvis.getInstance(); System.out.println(e1==e2); } }</code></pre> <p>运行结果:false</p> <p>可以看到,通过反射获取构造函数,然后调用setAccessible(true)就可以调用私有的构造函数,所有e1和e2是两个不同的对象。</p> <p>如果要抵御这种攻击,可以修改构造器,让它在被要求创建第二个实例的时候抛出异常。</p> <p>经修改后:</p> <pre> <code class="language-java">package com.effective.singleton; public class ElvisModified { private static boolean flag = false; private ElvisModified(){ synchronized(ElvisModified.class) { if(flag == false) { flag = !flag; } else { throw new RuntimeException("单例模式被侵犯!"); } } } private static class SingletonHolder{ private static final ElvisModified INSTANCE = new ElvisModified(); } public static ElvisModified getInstance() { return SingletonHolder.INSTANCE; } public void doSomethingElse() { } }</code></pre> <p>测试代码:</p> <pre> <code class="language-java">package com.effective.singleton; import java.lang.reflect.Constructor; public class ElvisModifiedReflectAttack { public static void main(String[] args) { try { Class<ElvisModified> classType = ElvisModified.class; Constructor<ElvisModified> c = classType.getDeclaredConstructor(null); c.setAccessible(true); ElvisModified e1 = (ElvisModified)c.newInstance(); ElvisModified e2 = ElvisModified.getInstance(); System.out.println(e1==e2); } catch (Exception e) { e.printStackTrace(); } } }</code></pre> <p>运行结果:</p> <pre> <code class="language-java">Exception in thread "main" java.lang.ExceptionInInitializerError at com.effective.singleton.ElvisModified.getInstance(ElvisModified.java:27) at com.effective.singleton.ElvisModifiedReflectAttack.main(ElvisModifiedReflectAttack.java:17) Caused by: java.lang.RuntimeException: 单例模式被侵犯! at com.effective.singleton.ElvisModified.<init>(ElvisModified.java:16) at com.effective.singleton.ElvisModified.<init>(ElvisModified.java:7) at com.effective.singleton.ElvisModified$SingletonHolder.<clinit>(ElvisModified.java:22) ... 2 more</code></pre> <p>可以看到,成功的阻止了单例模式被破坏。</p> <p>从JDK1.5开始,实现Singleton还有新的写法,只需编写一个包含单个元素的枚举类型。推荐写法:</p> <pre> <code class="language-java">package com.effective.singleton; public enum SingletonClass { INSTANCE; public void test() { System.out.println("The Test!"); } }</code></pre> <p>测试代码:</p> <pre> <code class="language-java">package com.effective; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import com.effective.singleton.SingletonClass; public class TestMain { public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class<SingletonClass> classType = SingletonClass.class; Constructor<SingletonClass> c = (Constructor<SingletonClass>) classType.getDeclaredConstructor(); c.setAccessible(true); c.newInstance(); } }</code></pre> <p>运行结果:</p> <pre> <code class="language-java">Exception in thread "main" java.lang.NoSuchMethodException: com.effective.singleton.SingletonClass.<init>() at java.lang.Class.getConstructor0(Unknown Source) at java.lang.Class.getDeclaredConstructor(Unknown Source) at com.effective.TestMain.main(TestMain.java:22)</code></pre> <p>由此可见这种写法也可以防止单例模式被“攻击”。</p> <p>而且这种写法也可以防止序列化破坏单例模式,具体不在举例了,有关序列化以及单例模式被序列化破坏可以参考博文《JAVA序列化》(链接:http://blog.csdn.net/u013256816/article/details/50474678)。</p> <p>单元素的枚举类型已经成为实现Singleton模式的最佳方法。</p> <p> </p> <p>来自:http://www.importnew.com/22493.html</p> <p> </p>