top | item 44727894

(no title)

nekitamo | 7 months ago

Interesting, I also had to solve this problem about a decade ago when writing a binary packer for Android .so libraries. I ended up moving the first few Pheaders around to make space for a new entry in the Elf32_Phdr table, and then used that to inject a new code segment at the end of the file. Due to padding constraints this could sometimes add a significant amount of null bytes to the binary just for padding.

I also made my code execute before the entry point by specifying it as DT_INIT in the dynamic section. This way you don't have to modify the entry point pointer or call it after your unpacking stub is done decompressing the binary in memory.

Your solution with the the thunk is much better and probably avoids a lot of the complexity I encountered in moving segment headers around! Elf is a tight format unlike PE. Not a single byte goes to waste.

Thanks for sharing your project, I learned something today!

PS one interesting piece of trivia I found was that you could strip the section header entirely from an Elf file and the OS would still load and execute it. All it needs is the segment headers. It looks like the section headers are just there as a courtesy to help tools like strip and objcopy.

discuss

order

dillstead|7 months ago

You're right, you definitely can strip away the section headers. Notice that there's always a dynamic segment? If there wasn't, stripping away the section headers would make it very difficult to locate this very important piece of an ELF binary.

I had to make sure that I always inserted a page size multiple of bytes into the executable which can add up to a page of unused padding in addition to the thunk and chunk.