# V5322. OWASP. Possible reflection injection. Potentially tainted data is used to select class or method.

The analyzer has detected that a class is selected via the reflection mechanism without its validation.

This vulnerability can be categorized under the OWASP Top 10 2021 classification as follows:

- A3:2021-Injection.

The example:

    public void applyAction(HttpServletRequest request) {
      String action = request.getParameter("action");
      String className = action + "Controller";

      Class<?> actionClass = Class.forName(className); // <=

      Object actionClassObject = actionClass.newInstance();
      Method applyMethod = actionClass.getMethod("apply");

      applyMethod.invoke(actionClassObject);
    }

In this example, the server processes a request for an action specified as a string in the request parameter. The action is implemented as a certain class with the `apply` method. However, there is no validation to ensure which specific class is used. In this case, attackers can manipulate the request to select the wrong class, leading to unauthorized actions. This can cause program logic failures or security issues.

In the worst-case scenario, if attackers change `classpath`, they can use reflection to inject malicious code.

To harden security, developers should validate input.

The fixed code:

    private List<String> ALLOWED_TYPES = new ArrayList<>();

    public void validateAndApplyAction(HttpServletRequest request) {
      String action = request.getParameter("action");
      String className = action + "Controller";

      if (!ALLOWED_TYPES.contains(className)) {  // <=
        return;
      }

      Class<?> actionClass = Class.forName(className);

      Object actionClassObject = actionClass.newInstance();
      Method applyMethod = actionClass.getMethod("apply");
      applyMethod.invoke(actionClassObject);
    }

It is also possible for a wrong method to be selected instead of a wrong class:

    public void useMethodWithName(HttpServletRequest request) {
        String methodName = request.getParameter("methodName");
        Method method = this.getClass().getMethod(methodName); // <=
        method.invoke(this);
    }

To prevent the wrong method from being selected, developers can apply the same approach:

    private List<String> ALLOWED_METHODS = new ArrayList<>();

    public void useSafeMethodWithName(HttpServletRequest request) {
        String methodName = request.getParameter("methodName");
        if (ALLOWED_METHODS.contains(methodName)) {                // <=
            Method method = this.getClass().getMethod(methodName);
            method.invoke(this);
        }
    }

This diagnostic is classified as:

CWE-470