简体   繁体   中英

Safety of Class.forName in java

Suppose I have the following:

public class ForNameTest {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException {
        final String s = "java.lang.Integer";
        Object test = Class.forName(s).getConstructors()[0].newInstance(222);
        System.err.println(test);
    }
}

In this code I make an object from the String s whose value is known at compile time, so I believe this code is guaranteed to be free from exploits. Is there any value that "s" could take that would execute arbitrary code? "s" can contain the code that is desired, if desired.

One can probably modify the .class file to replace string "java.lang.Integer" in string pool with "com.something.MaliciousClass" . This class will be loaded and its static initializer will be executed. Even if the constructor parameters do not match.

But if one can modify .class file, then any kind of malicious code can be put in there, there is no point in replacing just one String.

If your string is assigned at compile time, you're probably safe, if you read it from somewhere, make sure it contains what you expect, ie whitelist names of classes that can be instantiated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM