Unsafe use of Reflection
Description
This application uses reflection APIs to dynamically instantiate classes or invoke methods at runtime based on user-supplied input. Reflection is a powerful programming feature that allows code to inspect and modify program behavior dynamically. However, when class names or method identifiers are derived from untrusted user input without proper validation, attackers can manipulate the application to instantiate arbitrary classes or execute unintended code paths. This vulnerability occurs when externally-controlled data directly determines which classes are loaded or which methods are invoked through reflection mechanisms.
Remediation
Eliminate the use of user input to determine class names or method identifiers in reflection operations. Implement the following controls:
1. Use Indirect Selection (Preferred):
Map user input to predefined, safe options rather than using input directly:
// Instead of: Class.forName(userInput)
Map<String, Class<?>> allowedClasses = new HashMap<>();
allowedClasses.put("option1", SafeClass1.class);
allowedClasses.put("option2", SafeClass2.class);
String userChoice = request.getParameter("type");
Class<?> selectedClass = allowedClasses.get(userChoice);
if (selectedClass != null) {
Object instance = selectedClass.getDeclaredConstructor().newInstance();
}2. Implement Strict Allowlisting:
If reflection is unavoidable, validate input against an explicit allowlist of permitted class names:
Set<String> allowedClassNames = Set.of(
"com.example.SafeClass1",
"com.example.SafeClass2"
);
String className = request.getParameter("class");
if (allowedClassNames.contains(className)) {
Class<?> clazz = Class.forName(className);
// Proceed with reflection
} else {
throw new SecurityException("Invalid class name");
}3. Apply Defense in Depth:
- Restrict reflection to specific packages using namespace validation
- Implement security manager policies to limit reflection capabilities
- Use least privilege principles for application permissions
- Log all reflection operations for security monitoring