views:

152

answers:

2

Consider this sample class,

class TargetClass {
    private static String SENSITIVE_DATA = "sw0rdfish";

    private static String getSensitiveData() {
        return SENSITIVE_DATA;
    }
}

When I do this,

import java.lang.reflect.Method;

public class ClassPiercing {

    public static void main(String... args) throws Exception {
        Class targetClass = Class.forName("TargetClass");
        Method[] methods = targetClass.getDeclaredMethods();
        methods[0].setAccessible(true);
        String sensitiveData = (String)methods[0].invoke(null, null);
        System.out.println("Sensitive Data: " + sensitiveData);
    }
}

The output is,

Sensitive Data: sw0rdfish

This is dangerous. How do I prevent this from happening?

+7  A: 

Well, use a SecurityManager.

http://java.sun.com/javase/6/docs/api/java/lang/SecurityManager.html

http://java.sun.com/javase/6/docs/technotes/guides/security/permissions.html#ReflectPermission

disabling ReflectPermission should do the trick.

alamar
solves the question but you can still disassemble the class (or just use a text editor to see what's in there)
Carlos Heuberger
Yeah; it's dumb to store a password in a static final field from any perspective.
alamar
It's just an example. You know what the real implication is.
Joset
That's why I've answered :)
alamar
+4  A: 

The point of access control is not to prevent someone from hacking in to your code; It's a matter of signalling intend to other programmers (eg. api design). If you don't trust the other program, you should run use different measures. For example, you could encrypt the data somehow.

troelskn