Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directly Replacing Text in Binary File

I have a compiled executable (binary) file - mybin - which grep indicates contains a positive match with a given text string - Cats.

grep “Cats” mybin
Binary file mybin matches

If I use the -a flag with grep, I can now see the actual match:

grep -a “File” mybin
<lots of text> (QString)Cats <lots of text>

Just to be clear, this is not a plain text string within the binary file i.e. I cannot see it if I open the file with a text editor.

What I want to do is replace occurrences of the string Cats within the binary file with the string Bear and keep the executable as a working executable.

How do I do this without changing it in the source code and recompiling the binary? Is such an operation even possible without corrupting the executable file and its operation?

If it is possible:

  1. How would do I do it?
  2. Are there any pitfalls I need to be aware of, for example the replacement string must be the same length as the original string (e.g. Cats -> Bear is ok but Cats -> Dragons is not).

Any help would be greatly appreciated.

like image 415
Mark Avatar asked Oct 17 '25 20:10

Mark


1 Answers

Maybe, just use perl which works happily with binary files:

perl -pi -e 's/Cats/Dragons/g' mybin

or

perl -pi -e 's/Cats/Dragons/' mybin

or

sed 's/43617473/447261676f6e/g' original_binary > patched_binary

In this command, "43617473" is the hexadecimal representation of "Cats", and "447261676f6e" is the hexadecimal representation of "Dragon". Adjust these values based on your specific case.

perl -pi -e 's/Cats/Dragons/s' original_binary > patched_binary
like image 102
Hansjörg Hofer Avatar answered Oct 19 '25 12:10

Hansjörg Hofer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!