m4b / goblin

An impish, cross-platform binary parsing crate, written in Rust
MIT License
1.17k stars 156 forks source link

Is it possible to modify binary with goblin? #325

Closed MatthewShao closed 1 year ago

MatthewShao commented 2 years ago

Hi, goblin is a really cool project! My use case is to modify the symbol names of elfs according to a set of rules. I went through the doc of goblin::strtab::Strtab, it seems the underlaying bytes are immutable. Is it possible to modify those and write back to the binary, and if so, could you give a simple example? Thanks.

msuiche commented 1 year ago

Looking for a similar answers, can we modify (removing/adding program_headers, adding NOTES, etc.) a parsed Elf object and write the modified file header to a target file.

msuiche commented 1 year ago

Actually, if the structures had methods to know there current offset and to convert structs into [u8] - that would be way enough since they are repr(C)

m4b commented 1 year ago

modifying binaries is a complex question; https://github.com/m4b/faerie is an example of an object file writer using goblin; that being said, modifying an existing binary/executable/shared library is possible, though the various pointers or offsets relied upon in various places would need to be updated.

since goblin assumes someone else owns the incoming bytes, the user could in theory write all this logic to manipulate the bits at whatever offsets it needs to in order to modify the binary, but the user would have to do all the necessary research to figure out what needs to be modified where, etc.

for elf and macho the structs all implement Pwrite so you could populate them with whatever values you want, then write them back into the byte stream, for example.

Anyway, I think the answer is yes, but it will be complicated! If you end up with something like objcopy or a binary modifier using goblin, please share back here, always interested to see new usescases, or problems encountered (with goblin) when doing so, thanks for your interest!

Closing this, but feel free to re-open if you encounter some bug or issue in goblin that prevents you from doing what you want :)

Example of using goblin structs to write them as bytes into some file/Vec<u8>:

https://github.com/m4b/faerie/blob/478931b9291f9f9310cf25d65e046a5b0d05a92a/src/elf.rs#L837-L852