fix: no-PIE ELF

This commit is contained in:
gbrochar 2025-01-20 12:28:27 +01:00 committed by Gaetan BROCHARD
parent 00ef44ac08
commit 6fe049bbda
1 changed files with 21 additions and 2 deletions

View File

@ -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;