Search code examples
javareflectionveracode

How to Fix CWE-470: Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection')


I got a 470 on a line in my code and rightfully so as defined by Vera.

Vera says to fix:

Apply strict input validation by using whitelists or indirect selection to ensure that the user is only selecting allowable classes or code.

So I created a strict whitelist of what class name reflection can have access to as a Set<String>

I then wrapped the Class.forName in an

if (whitelist.contains(className) {
   Veracode still fires in here with a 470
}

Anyone know what the fix has to look like for Vera not to fire? I feel I have followed their recommended remediation.


Solution

  • I have managed to resolve it using sanitizer class/method that get className validate and return value from String from hard coded value - for example:

    public class MySanitizer {

    public static String sanitizeClassName(final String className) throws MyException {
    
        if(!className.equals("com.my.MyClass")) 
            throw new MyException("Class not valid: "  + className);
    
        return "com.my.MyClass";
    }