I wonder how I can simply insert an assembly Instruction into a compiled ELF binary. I don't want to hexedit it or something like this.
2 Answers
An ELF binary is a file in the first place. Files consist of bytes. To modify an existing instruction is to change some bytes. The shortest way to do it is via a file editor that works with bytes. Whether it is a "text" or "hex" editor does not matter much as long as it does the job.
If you want to insert an instruction, that is, put it in a new space between existing bytes without overwriting them, an advanced text/hex editor can sometimes do that for you. However, it is very unlikely that a program will keep being valid after that, because other instructions often reference each other through numerical offsets, and such offsets will be off after you shift parts of the code.
Lastly, altering even a single byte may make a binary invalid in a sense that, if it has a checksum or digital signature embedded, it no longer will be correct.
1 Comment
The only and only solutions to these issue is to decide to use one of these techniques:
- Dynamic instrumentation, e.g., Pin, Dyninst, etc.
- Static instrumentation, sometimes called binary rewriting, e.g, Retowrite.
- Lifting the binary code into IR (intermediate representation code) like GCC's RTL or LLVM's IR code then insert your additional code (written in assembly-like IR code) and recompile. (Tools publicly available: egalito)
printf $'\xf3\x90'' | dd of=myfile conv=notrunc bs=1 seek=12345to replace two bytes at byte-offset 12345 with an x86pauseinstruction (rep nop) (untested). Or write a C program tolseek+write. This is obviously less convenient than using a hex editor for a one-off task, but does let you make a script / program to do it for the same file on multiple systems.