2

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.

5
  • 6
    Well, you have to "hexedit" if you want to modify a binary file. Commented May 10, 2018 at 21:14
  • You might find Agner Fog's Object file converter and disassembler useful. ELF fmt, disassemble -> ASM output, modify and assemble -> ELF fmt. Commented May 11, 2018 at 5:13
  • 1
    @m0skit0: No you don't; you can replace or append bytes in scriptable non-interactive ways, like printf $'\xf3\x90'' | dd of=myfile conv=notrunc bs=1 seek=12345 to replace two bytes at byte-offset 12345 with an x86 pause instruction (rep nop) (untested). Or write a C program to lseek + 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. Commented May 11, 2018 at 6:09
  • Get yourself a copy of "Ida" (hex-rays.com/products/ida), learn to use it and you will be set for life. :-) Commented May 11, 2018 at 7:25
  • What sort of solution would be acceptable to you? Commented May 11, 2018 at 11:14

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

And yet, fixing binaries is a rather common activity - of course, tools like "Ida" are better idea that just a random hex editor (even though a plain old hex editor may also prove of utility in time of dire need :-).
0

The only and only solutions to these issue is to decide to use one of these techniques:

  1. Dynamic instrumentation, e.g., Pin, Dyninst, etc.
  2. Static instrumentation, sometimes called binary rewriting, e.g, Retowrite.
  3. 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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.