Tuesday, March 10, 2009

Strings are immutable in Java. Really, Mr. Anderson?

Take a look at the following code, the output is not what you may expect ;)

//MindWarp.java
public class MindWarp 
{
  public static void main(String[] args)
  {
    System.out.println(MR_ANDERSON);
  }
  private static final String MR_ANDERSON = "Adam, RIM Security Researcher";
  private static final Warper warper = new Warper();
//The hackers class ;)
}


//Warper.java - Hacks the String object which is on the heap....
import java.lang.reflect.*;

public class Warper 
{
  private static Field stringValue;
  
static 
{
    try
    {
      stringValue = String.class.getDeclaredField("value");    
//String has a private char [] called "value"
    }
    catch(NoSuchFieldException ex)
    {
//Should deploy a safety net here i.e enumerate a char[] incase the variable inside the String class is not called "value"
        ex.printStackTrace(); 
    }
    if (stringValue != null) {
      stringValue.setAccessible(true); // make field public ;)
    }
  }
  public Warper() {
    try {
//String must be same length, otherwise IndexOutOfBoundsException
      stringValue.set("Adam, RIM Security Researcher", "You have been hacked! ! ! ! !".toCharArray()); 
    } catch(IllegalAccessException ex) {} // shhh
  }
}

No comments: