From 6fe049bbda7626a689eccbbd250db117fe50b89b Mon Sep 17 00:00:00 2001 From: gbrochar Date: Mon, 20 Jan 2025 12:28:27 +0100 Subject: [PATCH] fix: no-PIE ELF --- src/woody_woodpacker.c | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/woody_woodpacker.c b/src/woody_woodpacker.c index 6e9ebca..a7cd6ff 100644 --- a/src/woody_woodpacker.c +++ b/src/woody_woodpacker.c @@ -32,6 +32,20 @@ int pack_elf32(t_map file) { return wdy_error("ELF needs to be in 64 bits format"); } + +int get_first_load_segment64( + Elf64_Ehdr elf_header, + Elf64_Phdr *program_headers, + Elf64_Phdr **first_load_segment) { + for (int i = 0; i < elf_header.e_phnum; i++) { + Elf64_Phdr *p_hdr = &program_headers[i]; + if (p_hdr->p_type == PT_LOAD) { + *first_load_segment = p_hdr; + return RET_OK; + } + } + return RET_ERR; +} int get_load_segment64( Elf64_Ehdr elf_header, Elf64_Phdr *program_headers, @@ -91,6 +105,11 @@ int pack_elf64(t_map file) { return wdy_error("cannot fetch program headers table"); } + Elf64_Phdr *first_load_segment; + if (get_first_load_segment64(*elf_header, program_headers, &first_load_segment) == RET_ERR) { + return wdy_error("cannot get first load segment"); + } + Elf64_Phdr *load_segment; if (get_load_segment64(*elf_header, program_headers, &load_segment) == RET_ERR) { return wdy_error("cannot get load segment"); @@ -128,7 +147,7 @@ int pack_elf64(t_map file) { // jump_offset is the index of jump from code cave start // 4 because jump has a 4 byte operand) size_t code_cave_start = code_cave.data - file.data; - int jump_value = elf_header->e_entry - code_cave_start - payload.jump_offset - 4; + int jump_value = elf_header->e_entry - first_load_segment->p_paddr - code_cave_start - payload.jump_offset - 4; ft_memcpy(payload.data + payload.jump_offset, &jump_value, sizeof(jump_value)); if (payload.encrypt != NULL) { @@ -143,7 +162,7 @@ int pack_elf64(t_map file) { payload.encrypt(file, key, *load_segment); free(key); } - elf_header->e_entry = code_cave.data - file.data; + elf_header->e_entry = code_cave.data - file.data + first_load_segment->p_paddr; load_segment->p_filesz += payload.len; load_segment->p_memsz += payload.len; load_segment->p_flags |= PF_W | PF_R;