Skip to content

[elf2bin] Segmentation fault #251

@enty8080

Description

@enty8080

Hello,

I wrote a simple code, that should execute binary file from buffer (this code is based on mettle/src/process.c):

#include <sys/types.h>
#include <sys/auxv.h>

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

struct bin_info {
    off_t start_function;
    off_t dynamic_linker_info;
    char magic_number[4];
} __attribute__((packed));

void exec_image(char *image, size_t image_len)
{
    void (*e_entry)(long *, long *);
    long stack[9] = {0};
    long *dynv;

    struct bin_info *image_info = (struct bin_info*)(image + image_len - sizeof(*image_info));
    e_entry = (void *)(image + image_info->start_function);

    stack[0] = 1;
    stack[1] = (intptr_t)"libc.so";
    stack[2] = 0;

    stack[3] = (intptr_t)"LANG=C";
    stack[4] = 0;

    stack[5] = AT_BASE; stack[6] = (intptr_t)image;
    stack[7] = AT_NULL; stack[8] = 0;

    dynv = (void *)(image + image_info->dynamic_linker_info);

    printf("%s: jumping to %p loaded at %p\n", __FUNCTION__, e_entry, image);
    e_entry(stack, dynv);
}

int main(int argc, char *argv[])
{
    if (argc < 2)
    {
        fprintf(stderr, "usage: %s <file>\n", argv[0]);
        return 1;
    }

    FILE *file = fopen(argv[1], "rb");

    if (file == NULL)
        return 1;

    fseek(file, 0L, SEEK_END);
    size_t size = ftell(file);
    rewind(file);

    unsigned char *image = malloc(size);
    if (image == NULL)
        return 1;

    fread(image, sizeof(unsigned char), size, file);

    exec_image(image, size);

    free(image);
    fclose(file);

    return 0;
}

Then I compile this script using gcc main.c -o main

Target is a simple program which should print Hello, world!. I compile it using x86_64-linux-musl-gcc test.c -o test -static -pie -Wl,-z,max-page-size=4096 and then turn it to binary using elf2bin test test.bin.

After executing ./main test.bin I got SEGFAULT:

exec_image: jumping to 0x563d26c378b8 loaded at 0x563d26c37490
Segmentation fault

How can I fix this and what am I doing wrong?
And is there any way to pass an argument of int to main function of test.bin?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions