Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing private static methods from a public static context

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?

like image 461
setzamora Avatar asked Dec 18 '22 08:12

setzamora


2 Answers

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.

like image 92
alamar Avatar answered Dec 25 '22 23:12

alamar


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.

like image 22
troelskn Avatar answered Dec 26 '22 00:12

troelskn