java.lang.security.audit.unsafe-reflection.unsafe-reflection

profile photo of semgrepsemgrep
Author
6,314
Download Count*

If an attacker can supply values that the application then uses to determine which class to instantiate or which method to invoke, the potential exists for the attacker to create control flow paths through the application that were not intended by the application developers. This attack vector may allow the attacker to bypass authentication or access control checks or otherwise cause the application to behave in an unexpected manner.

Run Locally

Run in CI

Defintion

rules:
  - id: unsafe-reflection
    patterns:
      - pattern: |
          Class.forName($CLASS,...)
      - pattern-not: |
          Class.forName("...",...)
      - pattern-not-inside: |
          $CLASS = "...";
          ...
    message: If an attacker can supply values that the application then uses to
      determine which class to instantiate or which method to invoke, the
      potential exists for the attacker to create control flow paths through the
      application that were not intended by the application developers. This
      attack vector may allow the attacker to bypass authentication or access
      control checks or otherwise cause the application to behave in an
      unexpected manner.
    metadata:
      cwe:
        - "CWE-470: Use of Externally-Controlled Input to Select Classes or Code
          ('Unsafe Reflection')"
      owasp:
        - A03:2021 - Injection
      source-rule-url: https://owasp.org/www-community/vulnerabilities/Unsafe_use_of_Reflection
      category: security
      technology:
        - java
      references:
        - https://owasp.org/Top10/A03_2021-Injection
      subcategory:
        - audit
      likelihood: LOW
      impact: LOW
      confidence: LOW
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]
      vulnerability_class:
        - Improper Authorization
    severity: WARNING
    languages:
      - java

Examples

unsafe-reflection.java

package org.learn;

import java.util.ArrayList;

public class DemoForClassName {

    private static void demoCreateThread(String userInput) throws ClassNotFoundException,
            IllegalAccessException, InstantiationException, InterruptedException {
        // ruleid: unsafe-reflection
        Class<?> loadClass = Class.forName(userInput + "MyThread");

        Thread thread = (Thread) loadClass.newInstance();
        thread.start();
        thread.join();
    }

    private static void demoOk() throws ClassNotFoundException,
            IllegalAccessException, InstantiationException, InterruptedException {
        // ok: unsafe-reflection
        Class<?> loadClass = Class.forName("org.learn.MyThread");

        Thread thread = (Thread) loadClass.newInstance();
        thread.start();
        thread.join();
    }

}