Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reflection framework and security

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

like image 861
Jijoy Avatar asked Apr 16 '10 11:04

Jijoy


People also ask

Is Java reflection a security risk?

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.

What is reflection framework in Java?

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.

Is it good to use reflection in Java?

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.

Should I avoid reflection in Java?

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.


3 Answers

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.

like image 130
Maurice Perry Avatar answered Sep 30 '22 23:09

Maurice Perry


See Hack any Java class using reflection attack and How to set SecurityManager and Java security policy programmatically .

like image 31
Michał Mech Avatar answered Oct 01 '22 00:10

Michał Mech


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.

like image 32
Michael Borgwardt Avatar answered Sep 30 '22 23:09

Michael Borgwardt