I made a program in C that injects some code into a ELF64 binary. I search for some \0 bytes, put the code there and modify the offsets so it loads correctly. When I run the newly created binary, it prints the message saying the code was injected successfully but the moment I jump to the entry point, I get a segfault.
The code I'm trying to inject is:
BITS 64
mov rax, 10
push rax
mov rax, ' Message'
push rax
mov rax, 'Injected'
push rax
mov rax, 1 ;; write(
mov rdi, 1 ;; STDOUT_FILENO,
mov rsi, rsp ;; "Injected Message\n",
mov rdx, 17 ;; 17
syscall ;; );
mov rax, 0x69696969
jmp rax
0x69696969 Is just some default value I change later.
The code I wrote to inject into the binary is:
void ft_inject_payload(t_data *data)
{
unsigned char *ptr;
unsigned int *start_address;
unsigned int increment;
unsigned int i;
ptr = (unsigned char *)data->mmap_ptr;
start_address = (unsigned int *)&g_payload[g_payload_size - 6];
*start_address = data->header->e_entry;
i = data->section_header[data->last_section].sh_offset
+ data->section_header[data->last_section].sh_size;
increment = 0;
while (i % 16 != 0)
{
i++;
increment++;
}
memcpy(&ptr[i], g_payload, g_payload_size);
data->header->e_entry = i;
data->section_header[data->last_section].sh_size
+= g_payload_size + increment;
data->program_header[data->text_segment].p_filesz
+= g_payload_size + increment;
data->program_header[data->text_segment].p_memsz
+= g_payload_size + increment;
}
Here is the binary code of the payload:
unsigned char g_payload[] = {
0xB8, 0x0A, 0x00, 0x00, 0x00, 0x50, 0x48, 0xB8, 0x20, 0x4D, 0x65, 0x73,
0x73, 0x61, 0x67, 0x65, 0x50, 0x48, 0xB8, 0x49, 0x6E, 0x6A, 0x65, 0x63,
0x74, 0x65, 0x64, 0x50, 0xB8, 0x01, 0x00, 0x00, 0x00, 0xBF, 0x01, 0x00,
0x00, 0x00, 0x48, 0x89, 0xE6, 0xBA, 0x11, 0x00, 0x00, 0x00, 0x0F, 0x05,
0xB8, 0x69, 0x69, 0x69, 0x69, 0xFF, 0xE0
};
EDIT I modified the code of the payload to clean the stack and preserve rdx. And for now, I'm still having the same error
New code of the payload:
BITS 64
push rdx
;; Load Message Into the stack
mov rax, 10
push rax
mov rax, ' Message'
push rax
mov rax, 'Injected'
push rax
mov rax, 1 ;; write(
mov rdi, 1 ;; STDOUT_FILENO,
mov rsi, rsp ;; "Injected Message\n",
mov rdx, 17 ;; 17
syscall ;; );
pop rax
pop rax
pop rax
pop rdx
mov rax, 0x69696969
jmp rax