What I want to do
What I want to do is inject an existing ELF binary with additional code that runs before the original .text section and then transfers control back to it.
What I can already do
Now, I have the following sorted:
- Insert new ELF section and section header
- Insert new ELF program header that loads the section
- Modify entrypoint in the ELF header to point to my new section's VA entrypoint
- Be able to write POC assembly code, compile with NASM into headerless raw cpu instructions format
- Return control back to original entrypoint
- All the above works and runs well
What I can't do
What I haven't been able to do is use GCC instead of NASM and use the standard library. Take the following example code:
#include <stdio.h>
void foo() {
printf("hello world");
// ignore the fact that this does not return control to the original ELF entry point
}
If I were to compile this with gcc -fPIC -c -o hello.o
and then yank the .text section from the generated object file with objcopy -O binary -j .text hello.o hello.bin
and try to use that as a new section, it simply won't work. hello.bin
will contain the following instructions when inspected with objdump
:
Disassembly of section .data:
00000000 <.data>:
0: 55 push %rbp
1: 48 89 e5 mov %rsp,%rbp
4: 48 8d 3d 00 00 00 00 lea 0x0(%rip),%rdi # 0xb
b: b8 00 00 00 00 mov $0x0,%eax
10: e8 00 00 00 00 callq 0x15
15: 90 nop
16: 5d pop %rbp
17: c3 retq
The above code has a couple of issues. It was yanked from an object file that expects to be linked and relocated into an executable binary that will have .plt
and .got
sections. Through these PLT stubs it will be able to call printf
that will be located in the standard shared library loaded by ld
somewhere in memory.
What I suppose it boils down to
I want GCC to produce an entirely self-contained object file that has a .text
section that does not expect to be relocated, already contains libc
statically and is position independent. So that it can just be put anywhere and do its thing.