Assume I have a singleton class in an external lib to my application. But still I can create instances of that particular class using reflection. Like this
Class clas = Class.forName(Private.class.getName());
for(Constructor c : clas.getDeclaredConstructors()){
c.setAccessible(true);
Private p = (Private) c.newInstance();
System.out.println(p);
}
How can I restrict this ? .
Thanks J
This vulnerability is caused by unsafe use of the reflection mechanisms in programming languages like Java or C#. An attacker may be able to create unexpected control flow paths through the application, potentially bypassing security checks. Exploitation of this weakness can result in a limited form of code injection.
Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.
Java Reflection is quite powerful and can be very useful. Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time.
Because the code is stringly/dynamically based; as soon as reflection is on the scene you can't refactor code with 100% confidence using an IDE's refactoring tools as the IDE cannot pick up the reflective uses. Basically, avoid reflection in general code if at all possible; look for an improved design.
By using a SecurityManager and controlling controlling ReflectPermission("suppressAccessChecks")
(example).
The security manager impacts performances though, and it is rarely used on the server side.
See Hack any Java class using reflection attack and How to set SecurityManager and Java security policy programmatically .
If you're talking about singletons in particular: that's one reason why the best way to implement them is via an enum:
public enum YourSingleton {
INSTANCE;
// methods go here
}
If you're talking about using setAccessible()
in general: If the code is written by someone you don't trust not to do underhanded tricks like that, you shouldn't run it anyway (or run it in a sandbox). Among developers, public/private should be considered metainformation about how the code is intended to be used - not as a security feature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With