I've seen references on Stack Exchange and elsewhere to inserting detours into compiled code. My understanding is that essentially a jmp instruction is inserted and then somehow the patched program is linked with additional code that contains the target of the jmp.
As a concrete but (hopefully) simple example, consider a program.
#include <stdio.h>
void hello(void) {
printf("Hello ");
printf("world!\n");
}
int main(void) {
hello();
}
Suppose I have only a binary compiled from this program. No measures have been taken to strip symbols or obfuscate the program in any way. I want to insert a detour to call code compiled from this function.
#include <stdio.h>
void detour(void) {
printf("detoured ");
}
The output of the patched program should be:
Hello detoured world!
How would I do that? How would I avoid breaking address offsets in the compiled code?
My available compilers are gcc, clang, and icc. My available operating systems are OS X and Ubuntu. Choose whatever you prefer in your answer.
If this can't reasonably be answered here then a brief overview and a pointer to some reading material would also be a good answer.
I'm aware of LD_PRELOAD and ld --wrap. The example was chosen so that those methods do not easily suffice. (You could of course just detour the entire hello() function to one that prints "Hello detoured world!" but lets pretend you don't have the source code and the function is non-trivial.)
Related Questions
I was first going to ask how to simply disassemble and reassemble a compiled program but that has been asked. The response was that it's extremely difficult. My sense from the answers is that it's not a common thing to do. I suspect my assumption that disassembling and reassembling is a necessary step for detouring might not be correct.
Why there are not any disassemblers that can generate re-assemblable asm code?
A similar question on StackOverflow received a lukewarm response. This question is focused just on inserting a detour rather than "modification" in general and I think the audience here will be more receptive.
This Reverse Engineering question asks about modifying binaries in general. A lot of different tools and LD_PRELOAD are mentioned. Some answers say it's possible to do this with a hex editor. I think that's the method I'd be most interested in.
How do I add functionality to an existing binary executable?
Recent examples I have seen that refer to doing such a thing
A blog post.
http://charlessolar.com/post/tag/disassemble
This Stack Overflow question.
https://stackoverflow.com/questions/9449845/how-to-link-object-file-to-executable-compiled-binary
hello()
function above?