0

I have a class Client, which has a variable privilege which I cannot edit. I can however edit a class Launcher which extends Client. A method in Client checks the privilege, and I would like to overwrite the privilege variable before that method.

public class Client { // I can't edit this class at all

    private int privilege = 0;

    public void chat(String msg) {
        if (privilege == 3) {
            // send chat packet with privileges to server
        }
    }
}

Then in a seperate file:

public class Launcher extends Client { // I can edit this class
    // This is what I tried... it didn't work
    @Override
    public void chat(String msg) {
        int privilege = 3;
        super.chat(msg);
    }
}

This is part of a game I've decompiled, and I'd like to overwrite the privilege variable (cheat), how can I accomplish this?

1 Answers1

1

You can use reflection to write private fields. Get the field, make it accessible, and assign the value you want. A similar approach can be used to invoke private methods.

@Override
public void chat(String msg)
{
  try {
    Field field = Client.class.getDeclaredField("privilege");
    field.setAccessible(true);
    field.setInt(this, 3);
  }
  catch (Exception ex) {
    throw new RuntimeException("Failed to modify field", ex);
  }
  super.chat(msg);
}
erickson
  • 265,237
  • 58
  • 395
  • 493
  • Worked great, thanks. – Nicholas Mattiacci Jun 21 '16 at 18:54
  • The reflection access modification seems incredibly unsafe (overall not in this specific example). Isn't the point of java's access modifiers to make variables safe in polymorphism? – Eli Sadoff Jun 21 '16 at 18:57
  • @EliSadoff Access modification is a privileged action, and the runtime can be configured to deny its use by untrusted code. – erickson Jun 21 '16 at 18:59
  • @erickson Ah, I didn't realize it was a privileged action; however, I guess I could have inferred that from the `RuntimeException` being thrown. – Eli Sadoff Jun 21 '16 at 19:01