Single-case mode-reflection attack solution and principle analysis

First of all, we still take the hungry man model as a chestnut for testing. The code of the hungry man model is as follows:

public class HungrySingleton implements Serializable {

    private static final HungrySingleton instance;

    static {
        instance = new HungrySingleton();
    }
    private HungrySingleton(){
    }

    public static HungrySingleton getInstance(){
        return instance;
    }

    private Object readResolve(){
        return instance;
    }

  1. Write a method for obtaining an instance using reflection and a method for directly obtaining an instance, and compare the return values ​​of the two to see if it is an instance.

code show as below:

public class Testreflection {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class object = HungrySingleton.class;
        Constructor constructor = object.getDeclaredConstructor();
        constructor.setAccessible(true);

        HungrySingleton instance = HungrySingleton.getInstance();
        HungrySingleton newInstance = (HungrySingleton) constructor.newInstance();

        System.out.println(instance);
        System.out.println(newInstance);
        System.out.println(instance == newInstance);

     }
    }

  The result after running is: it can be seen that the result of the two is not an object, then the Hungry Man model is resolutely attacked by reflection.

 

2. So how to solve this reflection attack? We know that this instance is loaded when the class is loaded, because the word instance is generated when the class is loaded, then we can add a judgment in the constructor to perform reflection defense. code show as below:

 

The test results are:

This method has a feature, that is, it is ok to create objects at the moment of class loading, and singletons of static inner classes can also be used.
For those that are not static classes, they also need to be solved, according to the order in which the instances are created. But in any case, reflection can access the methods and variables of the class and modify it, so non
The class that created the object at this moment of class loading cannot prevent reflection attacks.

 

Guess you like

Origin www.cnblogs.com/shenwen/p/12676119.html