I can get the value of the protected field, but the private field throws java.lang.IllegalAccessException
. I think I know why I'm getting this exception, but how is reflection used to exploit the contents of private fields, how do I get around this?
Programmer Hat is on
I have created the following Vulnerable class in a netbeans project. I have made a Jar file to distribute it.
public class Vulnerable {
private int privateSecret;
protected int protectedSecret;
int secret;
public Vulnerable() {
this.protectedSecret = 11;
this.privateSecret = 22;
this.secret = 33;
}
}
Malicious Hacker Hat is now on
I want to know private hidden fields and I want to know what they contain.
I have the Jar file and I have imported it into my Exploit project.
The following class extends Vulnerable and uses reflection to list fields and try to access the values.
public class ExpliotSubClass extends VulnerableCode.Vulnerable {
public List<Field> protectedList = new LinkedList<Field>();
public List<Field> privateList = new LinkedList<Field>();
public void lists() {
Field[] declaredFields = this.getClass().getSuperclass().getDeclaredFields();
for (Field field : declaredFields) {
int modifiers = field.getModifiers();
if (Modifier.isPrivate(modifiers)) {
privateList.add(field);
System.out.println("Private = " + field.getName());
} else if (Modifier.isProtected(modifiers)) {
protectedList.add(field);
System.out.println("Protected= " + field.getName());
}
}
}
public Object get(Field field) {
try {
return field.get(this);
} catch (IllegalArgumentException ex) {
Logger.getLogger(ExpliotSubClass.class.getName()).log(Level.SEVERE,
null,
ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(ExpliotSubClass.class.getName()).log(Level.SEVERE,
null,
ex);
}
return null;
}
}
In order to access private field you have to set it as accessible:
field.setAccessible(true);