Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ELF - Getting a SEGFAULT when changing the entry point

Tags:

c

x86-64

mmap

elf

I'm trying to patch the entry point of an ELF file directly via the e_entry field:

Elf64_Ehdr *ehdr = NULL;
Elf64_Phdr *phdr = NULL;
Elf64_Shdr *shdr = NULL;

if (argc < 2)
{
    printf("Usage: %s <executable>\n", argv[0]);
    exit(EXIT_SUCCESS);
}

fd = open(argv[1], O_RDWR);

if (fd < 0)
{
    perror("open");
    exit(EXIT_FAILURE);
}

if (fstat(fd, &st) < 0)
{
    perror("fstat");
    exit(EXIT_FAILURE);
}

/* map whole executable into memory */
mapped_file = mmap(NULL, st.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

if (mapped_file < 0)
{
    perror("mmap");
    exit(EXIT_FAILURE);
}

// check for an ELF file
check_elf(mapped_file, argv);

ehdr = (Elf64_Ehdr *) mapped_file;
phdr = (Elf64_Phdr *) &mapped_file[ehdr->e_phoff];
shdr = (Elf64_Shdr *) &mapped_file[ehdr->e_shoff];

mprotect((void *)((uintptr_t)&ehdr->e_entry & ~(uintptr_t)4095), 4096, PROT_READ | PROT_WRITE);

if (ehdr->e_type != ET_EXEC)
{
    fprintf(stderr, "%s is not an ELF executable.\n", argv[1]);
    exit(EXIT_FAILURE);
}

printf("Program entry point: %08x\n", ehdr->e_entry);



int text_found = 0;
uint64_t test_addr;
uint64_t text_end;
size_t test_len = strlen(shellcode);
int text_idx;
for (i = 0; i < ehdr->e_phnum; ++i)
{

    if (text_found)
    {
        phdr[i].p_offset += PAGE_SIZE;
        continue;
    }


    if (phdr[i].p_type == PT_LOAD && phdr[i].p_flags == ( PF_R | PF_X))
    {

        test_addr = phdr[i].p_vaddr + phdr[i].p_filesz;
        text_end = phdr[i].p_vaddr + phdr[i].p_filesz;

        printf("TEXT SEGMENT ends at 0x%x\n", text_end);


        puts("Changing entry point...");
        ehdr->e_entry = (Elf64_Addr *) test_addr;

        memmove(test_addr, shellcode, test_len);


        phdr[i].p_filesz += test_len;
        phdr[i].p_memsz += test_len;    

        text_found++;
    }


}

//patch sections

for (i = 0; i < ehdr->e_shnum; ++i)
{
    if (shdr->sh_offset >= test_addr)
        shdr->sh_offset += PAGE_SIZE;

    else
        if (shdr->sh_size + shdr->sh_addr == test_addr)
            shdr->sh_size += test_len;
}

ehdr->e_shoff += PAGE_SIZE;
close(fd);


}

The shellcode in this case is just a bunch of NOPs with an int3 instruction at the end.
I made sure to adjust the segments and sections that come after this new code, but the problem is that as soon as I patch the entry point the program crashes, why is that?

like image 353
Trey Avatar asked Mar 05 '23 01:03

Trey


1 Answers

changing:

memmove(test_addr, shellcode, test_len);

to:

memmove(mapped_file + phdr[i].p_offset + phdr[i].p_filesz, shellcode, test_len);

Seems to fix your problem. test_addr is a virtual address belong to the file you have mapped; you cannot use that directly as a pointer. The bits you want to muck with are the file map address, p_offset and p_filesz.

like image 116
mevets Avatar answered Mar 18 '23 19:03

mevets