Pregunta

Can somebody tell me the changes should be made in String class API (we can't do that I know) so that following program should print "Earth" ? OR
How can we stop printing "Sun" ? How to stop hacking ?

public class StringAPI {
    public static void main(String[] args) throws IllegalAccessException, NoSuchFieldException {
        Field value = String.class.getDeclaredField("value");
        value.setAccessible(true);
        value.set("Earth", "Sun".toCharArray());
        System.out.println("Earth"); // prints "Sun"
    }
}
¿Fue útil?

Solución

Just launch the JVM with an appropriate security manager which prevents reflection. You should run code you don't trust under a pretty stringent security manager.

You don't need to change the String class - just run in a tighter environment. If you're unable to control the environment like this, chances are you couldn't enforce your own "custom" String class anyway.

As an example:

c:\Users\Jon\Test>java -Djava.security.manager StringAPI
Exception in thread "main" java.security.AccessControlException: access denied 
    ("java.lang.RuntimePermission" "accessDeclaredMembers")
        at java.security.AccessControlContext.checkPermission(Unknown Source)
        at java.security.AccessController.checkPermission(Unknown Source)
        at java.lang.SecurityManager.checkPermission(Unknown Source)
        at java.lang.SecurityManager.checkMemberAccess(Unknown Source)
        at java.lang.Class.checkMemberAccess(Unknown Source)
        at java.lang.Class.getDeclaredField(Unknown Source)
        at StringAPI.main(StringAPI.java:5)

That's just using the default policy (when the security manager is enabled) but you can also specify a custom policy.

Otros consejos

You could add a checksum to the String object that is checked whenever the string is requested from the object. This would only detect a change however.

Once you detect that the inner storage of the value has been changed by comparing its checksum the the stored checksum you have various mechanism available to recover the original value.

It is unlikely that any of this would work on a real system as much of the existing code assumes String is immutable.

Then again - if they hack the checksum too you're still hacked.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top