Unsafe Reflection
ID |
java.unsafe_reflection |
Severity |
high |
Resource |
Injection |
Language |
Java |
Tags |
CWE:470, NIST.SP.800-53, OWASP:2021:A3, PCI-DSS:6.5.1 |
Description
Unsafe Reflection occurs when an application uses reflection in an insecure manner, potentially allowing an attacker to manipulate the class loader or execute arbitrary code. Reflection is powerful, but it must be used carefully to avoid introducing security vulnerabilities.
Rationale
Unsafe Reflection vulnerability (CWE: 470) arises when an application dynamically loads and executes classes determined at runtime without sufficient validation.
This can lead to unauthorized code execution, which represents a severe security threat. For example, if an attacker can influence the class name that a reflection call uses, they can potentially load malicious classes.
Here is an example in Java which demonstrates unsafe reflection:
import java.lang.reflect.Method;
public class UnsafeReflectionExample {
public void invokeClassMethod(String className, String methodName) {
try {
Class<?> clazz = Class.forName(className);
Method method = clazz.getMethod(methodName);
method.invoke(clazz.newInstance());
} catch (Exception e) {
e.printStackTrace();
}
}
}
In the above code, className
and methodName
are supplied externally, and no validation or checks are performed on these inputs. This can allow an attacker to supply a malicious class and method for execution.
Remediation
To remediate unsafe reflection vulnerabilities, follow these guidelines:
-
Validate Input: Always validate the input strings used to form a reflective call. Employ whitelisting strategies to ensure only known and safe class names are used.
-
Least Privilege: Give the minimal permissions necessary for the reflection to operate. This decreases the impact of code execution should an unsafe reflection vulnerability be exploited.
-
Code Review and Testing: Perform thorough code reviews and security testing to identify potential insecure reflection points early in the development process.
-
Use Alternative Designs: Whenever possible, consider alternative designs that do not rely on reflection, which can often be less error-prone and more efficient.
Configuration
The detector has the following configurable parameters:
-
sources
, that indicates the source kinds to check. -
neutralizations
, that indicates the neutralization kinds to check.
Unless you need to change the default behavior, you typically do not need to configure this detector.
References
-
CWE-470 : Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection')
-
Unsafe use of Reflection. in OWASP Vulnerabilities.
-
SEC05-J: Do not use reflection to increase accessibility of classes, methods, or fields, in the SEI CERT Oracle Coding Standard for Java.