Val's Blog
Lots of stuff for Web 2.0 freaks and Java addicts
Feeds RSS | Atom | RDF
 
 
Jane Cleland-Huang: "Software development should integrate and consider project metrics that assess its financial impact."
[ Login ]

May 2004
SunMonTueWedThuFriSat
       1 
 2  3  4  5  6  7  8 
 9  10  11  12  13  14  15 
 16  17  18  19  20  21  22 
 23  24  25  26  27  28  29 
 30  31      
Apr  |  Today  |  Jun
XML Feeds   Subscribe with Bloglines

Javaranch Sheriff   My LinkedIn Profile
Drop me a line or two   Bloglines Blogroll
JavaRSS   Referers
How cool are you?   My Reviews

Next trips...
JavaOne 2008 (May 6-9, 08)
SpringOne 2008 (Jun 11-12, 08)
Ajax Exp. 2008 (Sep 29-Oct 1, 08)
Top 10 entries (#hits)
(As of Nov 30, 2007)


Top 10 entries (#hits/day)
Come Back (5.032)
(As of Nov 30, 2007)
Recent Blog Entries
Recent Blog Comments
Re: Review of "Marketing Management 12th"
i know marketing management by kotler is good book but the problem is that the management part of this book is totally missing as fare as i know managemet is complete different subject and it should not be mixed i am student of MBA i was looking at ass...

Re: Review of "Pro Spring"
Using simple POJOs + factories without Spring for "echo" and "counter" would be a lot more easier. No need to write those XML files... So, in this case using Spring makes me write a lot more code... (OK, you can generate everything with the help of And...

pls urgent
Hi I am trying to generate the word doc but i m not understanding wats happening any one pls figure it out /* * WordAPI.java * * Created on May 30, 2006, 10:50 AM * * To change this template, choose Tools | Template Manager * and open the te...
Archives (# entries)
Links
Other Blogs
Other Blogs

Reviewing
Reading
Locations of visitors to this page
What they once said...
 

Ever wondered what evil power can be unleashed when using reflection? Do you think private methods are really only accessible from within the declaring class? Do you think that a private field can only be modified from within the declaring class? No? That's what I thought!! In this blog, I will try to demonstrate that it is always important to correctly set the security properties of your applications. For instance, let's look at the following example where we successfully retrieve a private password from another class:

1.  class A {
2.    private static String getPassword() {
3.      return "someHighlyPreciousPassword";
4.    }
5.  }
6.
7. public class Test {
8.   public static void main(String[] args) throws Exception {
9.     Class cl = Class.forName("A");
10.    java.lang.reflect.Method[] m = cl.getDeclaredMethods();
11.    m[0].setAccessible(true);
12.    String password = (String) m[0].invoke(null, null);
13.    System.out.println("I got it:" + password);
14.  }	
15.}
  
Output:
 I got it: someHighlyPreciousPassword
 

Ok, the example is not really sexy. Let's mess up a class that implements the Singleton pattern. In the normal case, a singleton object is supposed to be the only instance of a given class. To achieve this, we usually declare the class constructor private, so that no one can invoke it. Well, as demonstrated below, with reflection we can bypass this restriction and create a second "singleton object".

1.  class A {
2.    public static final A singleton = new A("I'm the only instance of class A");
3.    private String name; 
4.    private A(String name) {
5.      this.name = name;
6.    }
7.    public String toString() {
8.      return this.name;
9.    }
10. }
11.
12. public class Test {
13.   public static void main(String[] args) throws Exception {
14.     Class cl = Class.forName("A");
15.     java.lang.reflect.Constructor[] c = cl.getDeclaredConstructors();
16.     c[0].setAccessible(true);
17.     A anotherA  = (A) c[0].newInstance(new Object[]{"Not anymore!!"});
18.     System.out.println(A.singleton);
19.     System.out.println(anotherA);
20.   }	
21. }
  
Output:
 I'm the only instance of class A
 Not anymore!!
 

Using this technique, you can create an instance of any non-abstract class, even if all its constructors are declared private. For instance, below we create an instance of the Math class even though it is useless since the Math class has no instance method. Still, it is possible to do it.

1.  public class Test {
2.  public static void main(String[] args) throws Exception {
3.      Class cl = Class.forName("java.lang.Math");
4.      java.lang.reflect.Constructor[] c = cl.getDeclaredConstructors();
5.      c[0].setAccessible(true);
6.      Math mathInstance = (Math) c[0].newInstance(null);
7.      System.out.println(mathInstance);
8.    }
9.  }
  
Output:
 java.lang.Math@1cde100
 

Finally, let's mess with the Runtime class which has one private static field for storing the current Runtime instance. This is another example of a badly implemented singleton class. Let's look at the code below. We first retrieve the current runtime object and display it (3-4). Then, we set the Runtime.currentRuntime static field to null, which means that all successive calls to Runtime.getRuntime() will yield null (6-9) since currentRuntime is initialized at class loading time. We then get the currentRuntime field again and display its value (11-12). And finally, we try to use the current runtime to execute a command for displaying the content of the current directory (14). The output talks for itself.

1.  public class Test {
2.    public static void main(String[] args) throws Exception {
3.      Runtime r = Runtime.getRuntime();
4.      System.out.println("Before: Runtime.getRuntime() yields " + r);
5.
6.      Class cl = Class.forName("java.lang.Runtime");
7.      java.lang.reflect.Field f = cl.getDeclaredField("currentRuntime");
8.      f.setAccessible(true);
9.      f.set(null, null);
10.
11.     r = Runtime.getRuntime();
12.     System.out.println("After: Runtime.getRuntime() yields " + r);
13.
14.     r.exec("dir"); //raises NullPointerException!!
15.   }
16. }
  
Output:
 Before: Runtime.getRuntime() yields java.lang.Runtime@cac268
 After: Runtime.getRuntime() yields null
 Exception in thread "main" java.lang.NullPointerException
       at Test.main(Test.java:59)
 

All this could have been avoided if the currentRuntime field had been declared final. Nothing prevents setAccessible(true) to be called on the field (8) but when the set(null, null) method is called, IllegalAccessException is thrown with the message "Field is final".

I'm pretty sure that there is a huge amount of code out there that could be broken this way. Watch out!!
Bottom line: singleton fields should always be declared private static final!!! Moreover, make sure you never grant ReflectPermission and RuntimePermission.accessDeclaredMembers in the java.policy file of your production code.


Nice hack! great :-) Thanks for the tip!
this 'hack' is as old as the hills. why not just link the page you got it from instead of writing a whole article? what a pre-madonna
Hi "anonymous coward", Please note that I did not copy anything from anywhere. When I do so, I usually cite my sources. I didn't know that each piece of information had to come in only one instance on the Internet. I wish you a good hunt for duplicate information on the net. As I see it, uselessness and redundancy is definitely not restricted to information ;)
Time to cite from the C++ FAQ lite [7.6]:

How can I prevent other programmers from violating encapsulation by seeing the private parts of my class?

Not worth the effort — encapsulation is for code, not people. [...] Besides, this is rarely if ever a problem. I don't know any programmers who have intentionally tried to access the private parts of a class. "My recommendation in such cases would be to change the programmer, not the code" [...]

hey there's a game that runs on java but ive been tryin to find out how to hack for passwords on it,think u can help? well if u can hack this game u can hack any game.
"Not worth the effort — encapsulation is for code, not people. [...] Besides, this is rarely if ever a problem. I don't know any programmers who have intentionally tried to access the private parts of a class. "My recommendation in such cases would be to change the programmer, not the code" [...] " The conclusion above is not true. In some cases, you can not "change the programmer". One example is Java SDK. Can you change the programmers over their? But you sometimes do need to reflect singletons in their API.
Sure its a hack :). But sometimes its useful hack for writing test cases of singletons.
hey how can i hack in to runescape? ive been trying and trying well actually ive never hacked anything could you hack into runescape or mayb tell me how to? please i really need help ive been hacked a millions of times and now i want reevenge so im doing some research on how to hack java games and i guess your site has been the best so far but yeah please help me the site im trying to hack is www.runescape.com thanks, eric
Yeah, how do you hack runescape? It's a java based game and i want to know how to hack peoples passwords... please tell me!
Thanks mate! It's proving very useful in a utility class I am writing.
wat is body(wat dose it mean)
Thanks.This piece of code helped me a lot
ive tried many times...they put too many dead ends and loops in their programming, i find it impossible.
Is it possible to use reflection to extend a class with private constructors, say from within the derived class's constructor ?
Reflection is a mechanism in java that allows to to get information about a class without needing to know the type of the class. The program below takes a java class name as a command line argument and shows you all of the methods and field names that...

Read more...


Add a comment

Title
Body
HTML : b, i, blockquote, br, p, pre, a href="", ul, ol, li
Math Quiz 4 + 5 = (Helps stop blog spam)
Name
E-mail address
Website
Remember me Yes  No 

E-mail addresses are not publicly displayed, so please only leave your e-mail address if you would like to be notified when new comments are added to this blog entry (you can opt-out later).

TrackBack to http://radio.javaranch.com/val/addTrackBack.action?entry=1084891793000

 
About this Blog