lundi 1 juillet 2019

Is dynamic injection through Class.forName() method invocation always harmful?

Currently in our application, sonarqube is giving error for below 2 code snippets.

1.

public void method1(String a) {
     Class clazz = Class.forName(a);
     B b = (B) clazz.newInstance();
 }

As per my understanding, in this case sonar is complaining because a hacker can pass a class name at runtime to that method and he\she can execute malicious code using reflection. Now, my question is how the above code will execute if the class passed by the hacker is not in the classpath. Shouldn't it throw ClassNotFoundException\NoClassDefFoundError ? Also, if that class is not implemented or extended by Class B, it will throw ClassCastException ? So, Could you please tell me how this code is not safe ?

2.

public void method2(String fieldName) {
 Class<?> clazz = Class.forName("com.test.TestClass");
 Field field = clazz.getDeclaredField(fieldName);
 //
 }

In this case, sonar is complaining about getDeclaredField(). Could you please let me know whats the harm in calling that method specially when I am not setting the accessibility by calling setAccessible() method.

If at all above mentioned 2 code snippets are harmful, it will be helpful if you can provide the solution.

Thanks





Aucun commentaire:

Enregistrer un commentaire