Home > Back-end >  Modify c binary without recompiling
Modify c binary without recompiling

Time:06-28

Working on a project with a separate dev team, I have the source code, which is a combination of rust and c . It includes a class Agent.

agent.cpp :

/* static */
bool Agent::check() {
  if (check1) {
    return checkCondition()
  }
}
return false;

I would like the modify the binary directly to ensure that Agent::check always returns true. Is it possible?

If I could compile it, I would amend the source code, compule, do a binary diff, and be done with it. Unfortunately I cannot compile it.

CodePudding user response:

Generally speaking, if you want to be able to edit settings on an executable file, without recompiling it, you can accomplish that by using PE Resources.

PE Resources are contained in the .rsrc section of the compiled file. You can easily view and edit them by using PE Editors such as CFF Explorer or Resource Hacker.

You can use the WinAPIs BeginUpdateResource, UpdateResource, EndUpdateResource and similar APIs to read, write, add and delete PE resources at runtime.

// Sample code to add a PE resource 
hRes = BeginUpdateResourceW(filePath, bDeleteExistingResources);
UpdateResourceA(hRes, Resourcetype, ResourceName, 0, ResData, SizeOfData);
EndUpdateResourceA(hRes, false);

Your code, after execution, will read the settings from the resource previously added in runtime.

There are also other methods which do not involve PE resources, such as placing marker placeholder strings inside the code, so that a separate program later on can read the file code and replace these placeholder strings with the appropriate values.

CodePudding user response:

This kind of binary patch (hardcoding the return value of a function that returns by value) is quite easy to do. However binary patching is art form and will require you to learn some assembly reverse-engineering skills for the architecture you are targeting. Here is a good resource to get started: Live Overflow YouTube Channel.

Something important to note: the compiler might have inlined this member function. If that’s the case, you will have to patch the binary in multiple places.

If I may offer some advice: You mention a separate team, which implies you are doing this in professional context. I would strongly advise you tackle this issue from the root cause: either getting your hands on the tools required to compile this code yourself, or have this other team do it for you. While patching a binary is a very interesting skill to master, relying on it for performing tasks that should be as simple as editing one line of source and recompiling seems a bit overkill for me. Not to mention that if someone else in your team needs to do it again in the future for whatever reason, they will likely not be able to do it.

  • Related