给Linux程序穿“隐身衣”——ELF运行时加密器全解析(C/C++代码实现)

一、什么是ELF运行时加密器?通俗讲清核心含义

咱们平时在Linux系统(比如Debian、Fedora)里运行的可执行程序,不管是系统自带的date、ls命令,还是自己写的C程序,本质都是ELF格式二进制文件

正常情况下,这类程序运行时,系统会把文件从硬盘读到内存,黑客或逆向分析人员很容易通过静态分析 (直接扒硬盘里的文件)、内存分析(抓内存里的程序数据)拿到源码逻辑、敏感逻辑,甚至篡改程序。

而咱们要讲的这款运行时加密器,就是给ELF程序量身定做的**"隐身防护衣"**,核心作用一句话概括:
把原始ELF程序加密成乱码,生成一个新的加密程序;运行这个加密程序时,它不会把解密后的原始程序写回硬盘,而是直接在内存里解密、直接运行,用完还会自动擦除内存敏感数据,让分析人员抓不到完整的原始程序,大幅提升逆向破解难度。

简单对比两种运行模式:

  • 普通程序:硬盘存明文 → 读入内存 → 运行(全程明文可抓)
  • 加密后程序:硬盘存密文 → 内存解密 → 内存直接运行 → 内存数据擦除(硬盘无明文,内存暴露时间极短)

它不是永久加密锁死程序,而是运行时动态解密、内存级隐身执行,兼顾程序正常使用和防逆向防护,常用于Linux环境下的程序版权保护、敏感功能防篡改、恶意程序分析规避(正规用途仅限合法程序防护)。

二、核心前置知识点:先搞懂基础,再看原理

这款加密器涉及多个Linux底层和密码学领域,先把核心知识点拆解开,零基础也能跟上:

  1. ELF文件:Linux系统专属的可执行文件格式,类似Windows的exe,所有Linux运行的程序、动态库都是ELF格式,是本次加密的核心对象。
  2. AES-256-CBC加密:目前主流的对称加密算法,安全性极高,需要32位密钥(KEY)和16位初始向量(IV),加密解密用同一套密钥,是本次加密的核心算法,保证原始程序被彻底打乱成乱码。
  3. Memfd内存匿名文件:Linux特有的内存文件机制,创建的文件只存在于内存中,不落地硬盘,用完即销毁,是实现"程序不落地"的核心技术。
  4. 父子进程隔离:通过fork创建子进程,把解密、运行等敏感操作放在子进程,父进程只做等待,避免敏感数据泄露,提升安全性。
  5. 安全内存擦除:程序运行完后,用随机数覆盖内存里的密钥、解密后的数据,防止内存残留被抓取,符合NIST数据安全销毁标准。
  6. OpenSSL密码库:Linux下常用的加密算法库,提供AES加密、随机数生成等功能,是加密器的依赖基础。

三、整体设计思路:从加密到运行

整个加密器的设计分为两大核心模块 ,全程围绕"加密原始程序→生成自解密程序→内存隐身运行"三步走,没有复杂冗余设计,每一步都服务于"隐身防护":

核心设计代码和总流程

c 复制代码
...
void secure_wipe(void *ptr, size_t size) {
    if (ptr == NULL || size == 0) return;
    
    volatile unsigned char *p = (volatile unsigned char *)ptr;
    
    while (size--) {
        *p++ = (unsigned char)arc4random();
    }
    
    __asm__ __volatile__ ("" : : : "memory");
}

int utf8_strlen(const char *str) {
    int chars = 0;
    while (*str) {

        if ((*str & 0xC0) != 0x80) {
            chars++;
        }
        str++;
    }
    return chars;
}

// Function to get terminal width
int get_terminal_width(void) {
    struct winsize w;
    if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) == 0) {
        return w.ws_col;
    }
    char *columns = getenv("COLUMNS");
    if (columns) {
        return atoi(columns);
    }
    return 80; 
}


void print_centered_red(const char *text) {
    int term_width = get_terminal_width();
    int text_chars = utf8_strlen(text);  
    
    int padding = (term_width - text_chars) / 2;
    if (padding < 0) padding = 0;
    
    printf("\033[0;31m%*s%s\033[0m\n", padding, "", text);
}

long get_file_size_safe(FILE *f) {
    long current = ftell(f);
    if (fseek(f, 0, SEEK_END) != 0) {
        return -1;
    }
    long size = ftell(f);
    fseek(f, current, SEEK_SET);
    return size;
}

void encrypt_file(const char *input_path, const char *output_path, 
                  const unsigned char *key, const unsigned char *iv) {
    FILE *in = fopen(input_path, "rb");
    FILE *out = fopen(output_path, "wb");
    
    if (!in || !out) {
        perror("File error");
        exit(1);
    }
    
    long size = get_file_size_safe(in);
    if (size <= 0) {
        fprintf(stderr, "Invalid file size: %ld\n", size);
        fclose(in);
        fclose(out);
        exit(1);
    }
    
    if (size > MAX_BINARY_SIZE) {
        fprintf(stderr, "File too large: %ld bytes (max: %d)\n", size, MAX_BINARY_SIZE);
        fclose(in);
        fclose(out);
        exit(1);
    }
    
    unsigned char *plaintext = malloc(size);
    CHECK_NULL(plaintext, "malloc failed");
    
    size_t bytes_read = fread(plaintext, 1, size, in);
    if (bytes_read != (size_t)size) {
        fprintf(stderr, "Read error: expected %ld, got %zu\n", size, bytes_read);
        secure_wipe(plaintext, size);
        free(plaintext);
        fclose(in);
        fclose(out);
        exit(1);
    }
    
    EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
    CHECK_NULL(ctx, "EVP_CIPHER_CTX_new failed");
    
    if (EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv) != 1) {
        perror("EVP_EncryptInit_ex failed");
        EVP_CIPHER_CTX_free(ctx);
        secure_wipe(plaintext, size);
        free(plaintext);
        fclose(in);
        fclose(out);
        exit(1);
    }
    
    size_t ciphertext_buf_size = size + EVP_CIPHER_block_size(EVP_aes_256_cbc());
    unsigned char *ciphertext = malloc(ciphertext_buf_size);
    CHECK_NULL(ciphertext, "malloc failed for ciphertext");
    
    int len, ciphertext_len = 0;
    
    if (EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, size) != 1) {
        perror("EVP_EncryptUpdate failed");
        EVP_CIPHER_CTX_free(ctx);
        secure_wipe(plaintext, size);
        secure_wipe(ciphertext, ciphertext_buf_size);
        free(plaintext);
        free(ciphertext);
        fclose(in);
        fclose(out);
        exit(1);
    }
    ciphertext_len = len;
    
    if (EVP_EncryptFinal_ex(ctx, ciphertext + ciphertext_len, &len) != 1) {
        perror("EVP_EncryptFinal_ex failed");
        EVP_CIPHER_CTX_free(ctx);
        secure_wipe(plaintext, size);
        secure_wipe(ciphertext, ciphertext_buf_size);
        free(plaintext);
        free(ciphertext);
        fclose(in);
        fclose(out);
        exit(1);
    }
    ciphertext_len += len;
    
    fwrite(ciphertext, 1, ciphertext_len, out);
    
    EVP_CIPHER_CTX_free(ctx);
    
    secure_wipe(plaintext, size);
    secure_wipe(ciphertext, ciphertext_buf_size);
    free(plaintext);
    free(ciphertext);
    fclose(in);
    fclose(out);
}

void create_self_decrypting_stub(const char *encrypted_path, 
                                 const unsigned char *key,
                                 const unsigned char *iv) {
    FILE *enc = fopen(encrypted_path, "rb");
    if (enc == NULL) {
        perror("Failed to open encrypted file");
        exit(1);
    }
    
    fseek(enc, 0, SEEK_END);
    long enc_size = ftell(enc);
    fseek(enc, 0, SEEK_SET);
    
    if (enc_size <= 0 || enc_size > MAX_BINARY_SIZE) {
        fprintf(stderr, "Invalid encrypted file size: %ld\n", enc_size);
        fclose(enc);
        exit(1);
    }
    
    unsigned char *enc_data = malloc(enc_size);
    CHECK_NULL(enc_data, "malloc failed for enc_data");
    
    size_t bytes_read = fread(enc_data, 1, enc_size, enc);
    if (bytes_read != (size_t)enc_size) {
        fprintf(stderr, "Read error: expected %ld, got %zu\n", enc_size, bytes_read);
        fclose(enc);
        secure_wipe(enc_data, enc_size);
        free(enc_data);
        exit(1);
    }
    fclose(enc);
    
    FILE *out = fopen("stub.c", "w");
    if (!out) {
        perror("Failed to create stub.c");
        secure_wipe(enc_data, enc_size);
        free(enc_data);
        exit(1);
    }
    
    fprintf(out, "#define _GNU_SOURCE\n");
    fprintf(out, "#include <stdio.h>\n");
    fprintf(out, "#include <stdlib.h>\n");
    fprintf(out, "#include <string.h>\n");
    fprintf(out, "#include <unistd.h>\n");
    fprintf(out, "#include <sys/mman.h>\n");
    fprintf(out, "#include <sys/wait.h>\n");
    fprintf(out, "#include <fcntl.h>\n");
    fprintf(out, "#include <sys/random.h>\n");
    fprintf(out, "#include <time.h>\n");
    fprintf(out, "#include <openssl/evp.h>\n");
    fprintf(out, "#include <elf.h>\n\n");
    
    // Add secure_wipe function to stub
    fprintf(out, "static void secure_wipe(void *ptr, size_t size) {\n");
    fprintf(out, "    if (ptr == NULL || size == 0) return;\n");
    fprintf(out, "    volatile unsigned char *p = (volatile unsigned char *)ptr;\n");
    fprintf(out, "    while (size--) *p++ = 0;\n");
    fprintf(out, "}\n\n");
    
    // Embedded encrypted data
    fprintf(out, "static const unsigned char encrypted_data[] = {\n");
    for (int i = 0; i < enc_size; i++) {
        fprintf(out, "0x%02x", enc_data[i]);
        if (i < enc_size - 1) {
            if ((i + 1) % 16 == 0) fprintf(out, ",\n");
            else fprintf(out, ", ");
        }
    }
    fprintf(out, "\n};\n\n");
    
    // Embedded key
    fprintf(out, "static const unsigned char key[32] = {");
    for (int i = 0; i < 32; i++) {
        fprintf(out, "0x%02x", key[i]);
        if (i < 31) fprintf(out, ", ");
    }
    fprintf(out, "};\n\n");
    
    // Embedded IV
    fprintf(out, "static const unsigned char iv[16] = {");
    for (int i = 0; i < 16; i++) {
        fprintf(out, "0x%02x", iv[i]);
        if (i < 15) fprintf(out, ", ");
    }
    fprintf(out, "};\n\n");
    // Create stub.c    
    fprintf(out, "static void fast_decrypt_execute(int argc, char **argv) {\n");
    fprintf(out, "    // Create memfd for decrypted binary\n");
    fprintf(out, "    int fd = memfd_create(\"decrypted_elf\", MFD_CLOEXEC);\n");
    fprintf(out, "    if (fd == -1) {\n");
    fprintf(out, "        perror(\"memfd_create failed\");\n");
    fprintf(out, "        exit(1);\n");
    fprintf(out, "    }\n");
    fprintf(out, "    \n");
    fprintf(out, "    // Fork first - sensitive operations happen in child only\n");
    fprintf(out, "    pid_t pid = fork();\n");
    fprintf(out, "    if (pid == 0) {\n");
    fprintf(out, "        // CHILD PROCESS: All sensitive operations here\n");
    fprintf(out, "        // Setup decryption\n");
    fprintf(out, "        EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();\n");
    fprintf(out, "        if (!ctx) {\n");
    fprintf(out, "            perror(\"EVP_CIPHER_CTX_new failed\");\n");
    fprintf(out, "            close(fd);\n");
    fprintf(out, "            exit(1);\n");
    fprintf(out, "        }\n");
    fprintf(out, "        \n");
    fprintf(out, "        if (EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv) != 1) {\n");
    fprintf(out, "            perror(\"EVP_DecryptInit_ex failed\");\n");
    fprintf(out, "            EVP_CIPHER_CTX_free(ctx);\n");
    fprintf(out, "            close(fd);\n");
    fprintf(out, "            exit(1);\n");
    fprintf(out, "        }\n");
    fprintf(out, "        \n");
    fprintf(out, "        // Allocate buffer for decrypted data IN CHILD ONLY\n");
    fprintf(out, "        size_t encrypted_size = sizeof(encrypted_data);\n");
    fprintf(out, "        size_t buffer_size = encrypted_size + EVP_CIPHER_block_size(EVP_aes_256_cbc());\n");
    fprintf(out, "        unsigned char *decrypted = malloc(buffer_size);\n");
    fprintf(out, "        if (!decrypted) {\n");
    fprintf(out, "            perror(\"malloc failed for decryption buffer\");\n");
    fprintf(out, "            EVP_CIPHER_CTX_free(ctx);\n");
    fprintf(out, "            close(fd);\n");
    fprintf(out, "            exit(1);\n");
    fprintf(out, "        }\n");
    fprintf(out, "        \n");
    fprintf(out, "        int total_len = 0;\n");
    fprintf(out, "        \n");
    fprintf(out, "        // Decrypt all at once\n");
    fprintf(out, "        if (EVP_DecryptUpdate(ctx, decrypted, &total_len, encrypted_data, encrypted_size) != 1) {\n");
    fprintf(out, "            perror(\"EVP_DecryptUpdate failed\");\n");
    fprintf(out, "            secure_wipe(decrypted, buffer_size);\n");
    fprintf(out, "            free(decrypted);\n");
    fprintf(out, "            EVP_CIPHER_CTX_free(ctx);\n");
    fprintf(out, "            close(fd);\n");
    fprintf(out, "            exit(1);\n");
    fprintf(out, "        }\n");
    fprintf(out, "        \n");
    fprintf(out, "        int final_len;\n");
    fprintf(out, "        if (EVP_DecryptFinal_ex(ctx, decrypted + total_len, &final_len) != 1) {\n");
    fprintf(out, "            perror(\"EVP_DecryptFinal_ex failed\");\n");
    fprintf(out, "            secure_wipe(decrypted, buffer_size);\n");
    fprintf(out, "            free(decrypted);\n");
    fprintf(out, "            EVP_CIPHER_CTX_free(ctx);\n");
    fprintf(out, "            close(fd);\n");
    fprintf(out, "            exit(1);\n");
    fprintf(out, "        }\n");
    fprintf(out, "        total_len += final_len;\n");
    fprintf(out, "        \n");
    fprintf(out, "        // Write all at once\n");
    fprintf(out, "        ssize_t written = write(fd, decrypted, total_len);\n");
    fprintf(out, "        if (written != total_len) {\n");
    fprintf(out, "            perror(\"write failed\");\n");
    fprintf(out, "            secure_wipe(decrypted, buffer_size);\n");
    fprintf(out, "            free(decrypted);\n");
    fprintf(out, "            EVP_CIPHER_CTX_free(ctx);\n");
    fprintf(out, "            close(fd);\n");
    fprintf(out, "            exit(1);\n");
    fprintf(out, "        }\n");
    fprintf(out, "        \n");
    fprintf(out, "        // Clean up decryption context IMMEDIATELY\n");
    fprintf(out, "        EVP_CIPHER_CTX_free(ctx);\n");
    fprintf(out, "        \n");
    fprintf(out, "        // Secure wipe decrypted data from memory IMMEDIATELY\n");
    fprintf(out, "        secure_wipe(decrypted, buffer_size);\n");
    fprintf(out, "        free(decrypted);\n");
    fprintf(out, "        \n");
    fprintf(out, "        // IMMEDIATELY execute - minimal exposure window\n");
    fprintf(out, "        lseek(fd, 0, SEEK_SET);\n");
    fprintf(out, "        \n");
    fprintf(out, "        // Child process - use fexecve (Linux 2.6.16+)\n");
    fprintf(out, "        fexecve(fd, argv, environ);\n");
    fprintf(out, "        \n");
    fprintf(out, "        // If fexecve fails\n");
    fprintf(out, "        perror(\"fexecve failed\");\n");
    fprintf(out, "        close(fd);\n");
    fprintf(out, "        exit(1);\n");
    fprintf(out, "    } else if (pid > 0) {\n");
    fprintf(out, "        // PARENT PROCESS: No sensitive data here\n");
    fprintf(out, "        close(fd);  // Parent doesn't need the fd\n");
    fprintf(out, "        \n");
    fprintf(out, "        int status;\n");
    fprintf(out, "        waitpid(pid, &status, 0);\n");
    fprintf(out, "        \n");
    fprintf(out, "        if (WIFEXITED(status)) {\n");
    fprintf(out, "            exit(WEXITSTATUS(status));\n");
    fprintf(out, "        } else {\n");
    fprintf(out, "            exit(1);\n");
    fprintf(out, "        }\n");
    fprintf(out, "    } else {\n");
    fprintf(out, "        perror(\"fork failed\");\n");
    fprintf(out, "        close(fd);\n");
    fprintf(out, "        exit(1);\n");
    fprintf(out, "    }\n");
    fprintf(out, "}\n\n");
    // Main function
    fprintf(out, "int main(int argc, char **argv) {\n");
    fprintf(out, "    // Use the ultra-fast decryption and execution\n");
    fprintf(out, "    fast_decrypt_execute(argc, argv);\n");
    fprintf(out, "    \n");
    fprintf(out, "    // Should not reach here\n");
    fprintf(out, "    return 1;\n");
    fprintf(out, "}\n");    
    fclose(out);

    secure_wipe(enc_data, enc_size);
    free(enc_data);
}

int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("\nUsage: %s <input_binary> <output_encrypted>\n", argv[0]);
        return 1;
    }
    else {
	   printf("Trying all the things...\n");
    }
    
    if (access(argv[1], R_OK) != 0) {
        perror("Cannot access input file");
        return 1;
    }
   
    // Generate random key and IV
    unsigned char key[KEY_SIZE];
    unsigned char iv[IV_SIZE];
    
    if (RAND_bytes(key, KEY_SIZE) != 1) {
        fprintf(stderr, "Failed to generate random key\n");
        return 1;
    }
    
    if (RAND_bytes(iv, IV_SIZE) != 1) {
        fprintf(stderr, "Failed to generate random IV\n");
        return 1;
    }
    
    printf("Encrypting %s...", argv[1]); 
    encrypt_file(argv[1], "encrypted.bin", key, iv);    
    create_self_decrypting_stub("encrypted.bin", key, iv);

    char cmd[512];
    snprintf(cmd, sizeof(cmd), 
             "gcc -o \"%s\" stub.c -lssl -lcrypto -fPIC -pie "
             "-Wl,-z,now -Wl,-z,relro -Wl,-z,noexecstack "
             "-fstack-protector-strong -Os -D_FORTIFY_SOURCE=2 ",
             argv[2]);
    
    if (system(cmd) != 0) {
        fprintf(stderr, "Compilation failed\n");

        remove("encrypted.bin");
        remove("stub.c");
        exit(1);
    }
    

    if (remove("encrypted.bin") != 0) {
        perror("Warning: Could not remove encrypted.bin");
    }
    
    if (remove("stub.c") != 0) {
        perror("Warning: Could not remove stub.c");
    }
    
    FILE *keyfile = fopen("key.bin", "wb");
    if (keyfile) {
        fwrite(key, 1, KEY_SIZE, keyfile);
        fwrite(iv, 1, IV_SIZE, keyfile);
        fclose(keyfile);
        chmod("key.bin", 0600);
    }
    
...
    
    return 0;
}

If you need the complete source code, please add the WeChat number (c17865354792)

复制代码
原始ELF程序 → 【加密模块】AES-256-CBC加密 → 生成临时密文文件
→ 【自解密桩生成模块】把密文、密钥、IV打包成C代码(stub.c)
→ 编译stub.c → 生成最终加密可执行程序
→ 运行加密程序 → 子进程内存解密 → Memfd创建内存文件 → 直接运行内存程序 → 擦除内存数据 → 程序结束

分模块设计思路详解

1. 加密模块:给原始程序"上锁"

核心目标:把明文ELF程序变成不可读的密文,同时生成唯一的密钥和IV。

  • 限制文件大小:最大支持100MB,避免大文件内存溢出、加密效率过低;
  • 真随机密钥生成:用OpenSSL的真随机数函数生成32位密钥和16位IV,每次加密都不一样,杜绝密钥被预测;
  • 分段加密:采用64KB分块加密,适配内存读写效率,避免一次性加载大文件卡顿;
  • 安全兜底:所有文件操作、内存操作都加错误校验,失败立即退出,同时擦除内存敏感数据。
2. 自解密桩模块:打造"自带钥匙的隐身壳"

核心目标:把密文、密钥、解密逻辑打包成一个独立程序,实现"运行即解密、解密即运行",全程不落地。

  • 代码嵌入:把加密后的密文、密钥、IV直接写成C语言数组,嵌入到自动生成的stub.c代码里,不需要额外依赖密钥文件;
  • 进程隔离:敏感解密操作全放在子进程,父进程不接触任何密钥、明文数据,防止父进程被劫持导致泄露;
  • 内存运行:用memfd_create创建匿名内存文件,解密后的原始程序直接写入内存,不生成硬盘临时文件,彻底杜绝硬盘痕迹;
  • 极速擦除:解密完成、程序写入内存后,立即擦除内存里的密钥、明文数据,缩短敏感数据暴露窗口;
  • 直接执行:用fexecve直接运行内存文件,不需要读取硬盘,执行完子进程退出,内存文件自动销毁。
3. 安全清理模块:不留任何痕迹

核心目标:加密完成、程序运行结束后,彻底清理所有临时文件和内存数据,避免残留。

  • 加密端:删除临时密文文件、自动生成的stub.c源码;
  • 运行端:子进程运行完后,自动擦除内存里的解密数据、密钥,父进程退出后释放所有资源;
  • 密钥保护:密钥仅临时存于栈内存,使用完毕立即用随机数覆盖,不持久化保存(仅可选生成权限严格的密钥备份文件)。

四、代码核心逻辑拆解:挑重点讲

结合你提供的完整代码,避开逐行枯燥讲解,只拆解最核心、最能体现设计思路的代码片段,讲清"代码做什么、为什么这么做":

1. 基础宏定义与安全函数

c 复制代码
#define KEY_SIZE 32    // AES-256要求的32位密钥
#define IV_SIZE 16     // CBC模式要求的16位初始向量
#define MAX_BINARY_SIZE (100 * 1024 * 1024) // 最大支持100MB程序

// 安全内存擦除:用随机数覆盖内存,防止数据残留
void secure_wipe(void *ptr, size_t size) {
    volatile unsigned char *p = (volatile unsigned char *)ptr;
    while (size--) {
        *p++ = (unsigned char)arc4random(); // 随机数覆盖,不可恢复
    }
    __asm__ __volatile__ ("" : : : "memory"); // 内存屏障,确保擦除执行
}

解析:这部分是安全基础,KEY和IV的长度是AES-256-CBC的硬性要求,改了就无法正常解密;secure_wipe函数是核心防护,不用简单的0覆盖,而是用随机数覆盖,符合专业数据销毁标准,彻底杜绝内存残留。

2. 加密核心函数:encrypt_file

c 复制代码
// 初始化AES加密上下文,指定加密算法
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv);
// 执行加密,生成密文
EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, size);
EVP_EncryptFinal_ex(ctx, ciphertext + ciphertext_len, &len);

解析:这是加密的核心代码,先创建加密"工具箱"(上下文),指定用AES-256-CBC算法,传入密钥和IV;然后分两步完成加密,先处理主体数据,再处理末尾补齐数据,确保密文完整。加密完成后,立即擦除内存里的原始程序和密文,不留下临时数据。

3. 自解密核心函数:create_self_decrypting_stub

这部分是"隐身衣"的灵魂,代码会自动生成一个名为stub.c的C语言文件,里面包含:

  • 嵌入的加密后程序数组;
  • 固定的密钥和IV数组;
  • 子进程解密、内存运行的完整逻辑。

核心代码片段:

c 复制代码
// 创建内存匿名文件,不落地硬盘
int fd = memfd_create("decrypted_elf", MFD_CLOEXEC);
// 创建子进程,子进程负责解密运行
pid_t pid = fork();
if (pid == 0) {
    // 子进程:初始化解密,解密密文
    EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv);
    EVP_DecryptUpdate(ctx, decrypted, &total_len, encrypted_data, encrypted_size);
    // 解密后写入内存文件
    write(fd, decrypted, total_len);
    // 立即擦除解密数据
    secure_wipe(decrypted, buffer_size);
    // 直接运行内存里的程序
    fexecve(fd, argv, environ);
}

解析:memfd_create是实现"不落地"的关键,生成的文件只有文件描述符,没有硬盘路径;fork隔离父子进程,子进程做完所有敏感操作,父进程只等待;fexecve直接执行内存文件,全程不碰硬盘,解密完成后立刻擦除数据,敏感数据在内存里只存在几毫秒,根本来不及被抓取。

4. 主函数:串联全流程

主函数负责接收用户输入(原始程序路径、输出加密程序路径),生成密钥和IV,调用加密函数生成密文,再调用自解密函数生成stub.c,最后编译成最终的加密程序,同时清理临时文件,打印密钥和IV方便备份。


下面给你一套从头到尾的完整测试流程,每一步都能直接复制粘贴执行。


一、环境准备

先确认系统环境和依赖:

bash 复制代码
# Debian/Ubuntu
sudo apt update
sudo apt install build-essential libssl-dev

# Fedora/RHEL
sudo dnf install gcc make openssl-devel

# 检查 GCC 和 OpenSSL 是否装好
gcc --version
openssl version

注意 :代码里用了 arc4random(),需要 glibc 2.36+。如果你的系统比较老(比如 CentOS 7),需要额外装 libbsd-dev 并加 -lbsd 编译。


二、保存代码

把上面那份代码保存为文件,比如叫 crypter.c

bash 复制代码
cat > crypter.c << 'EOF'
# 这里粘贴完整的代码内容...
EOF

或者直接用 nano/vim 创建文件保存。


三、编译加密器

bash 复制代码
gcc -o crypter crypter.c -lssl -lcrypto -Wall

参数说明:

  • -lssl -lcrypto:链接 OpenSSL 库
  • -Wall:开警告,看看有没有问题

如果报错 arc4random undefined,说明 glibc 太老,改成:

bash 复制代码
sudo apt install libbsd-dev   # Debian/Ubuntu
gcc -o crypter crypter.c -lssl -lcrypto -lbsd -Wall

编译成功后会生成 ./crypter


四、准备测试目标

找一个系统自带的 ELF 程序做测试,比如 date

bash 复制代码
cp /bin/date ./date_test

# 先看看原始程序长啥样
file ./date_test
strings ./date_test | head -20

strings 能看到一堆可读字符串,说明原始程序是"裸奔"的。


五、运行加密器

bash 复制代码
./crypter ./date_test ./date_enc

你会看到类似这样的输出:

复制代码
Trying all the things...
Encrypting ./date_test...
Created: ./date_enc
Key (hex): 8ab5f658808ed30c068433965f4ab788cb4987e102e38218f5362e0126a040e7
IV  (hex): d3dcd288435bb59b93216f40f090e733

同时目录下会多出两个文件:

  • ./date_enc ------ 加密后的可执行文件(自解密存根)
  • ./key.bin ------ 密钥文件(权限 0600,只有你能读)

六、测试加密后的程序

6.1 基本功能测试

bash 复制代码
# 运行加密后的程序,看功能是否正常
./date_enc

# 带参数试试
./date_enc +%Y-%m-%d
./date_enc -u

如果输出和原版的 ./date_test 一模一样,说明解密+执行链路通顺

6.2 对比文件特征

bash 复制代码
# 看文件类型
file ./date_test
file ./date_enc

# 扫字符串
strings ./date_test | head -10
strings ./date_enc | head -10

你会发现:

  • date_testELF 64-bit LSB executable...strings 能扫出大量英文
  • date_enc:虽然也是 ELF,但 strings 几乎扫不出有意义的内容(只有 OpenSSL 和 libc 的导入表字符串)

6.3 检查是否落盘

这是最关键的特性验证------解密后的程序是否写到了磁盘上

bash 复制代码
# 方法1:运行期间另开一个终端,搜索临时文件
sudo find /tmp /dev/shm /var/tmp -type f -mmin -1 2>/dev/null

# 方法2:用 lsof 跟踪文件打开情况
./crypter ./date_test ./date_enc   # 先准备好
./date_enc &                       # 后台运行
PID=$!
sudo lsof -p $PID | grep REG       # 看打开了哪些普通文件
kill $PID

你会发现 ./date_enc 运行时没有任何临时文件落到磁盘,所有操作都在内存里完成。

6.4 检查进程树

bash 复制代码
# 运行加密程序
./date_enc &

# 看进程关系
pstree -p | grep date_enc

# 或者直接看
ps aux | grep date

你会看到类似这样的结构:

复制代码
crypter(父进程)───date_enc(子进程)───date(原始程序)

实际上因为 fexecve 会替换子进程映像,最终看到的应该是:

  • 一个父进程(Stub 的父进程,在 waitpid
  • 一个子进程(已经被替换成了原始的 date 程序)

6.5 内存残留检查(进阶)

想验证 secure_wipe 是否真的擦了内存,可以用 gdb attach:

bash 复制代码
# 终端1:运行加密程序,加个 sleep 方便 attach
# 修改测试程序,或者用一个会暂停的程序
cp /bin/sleep ./sleep_test
./crypter ./sleep_test ./sleep_enc

# 终端2:在 sleep_enc 运行时 attach
pgrep -f sleep_enc
sudo gdb -p <PID>

# 在 gdb 里搜索内存中是否还有原始 ELF 的 magic 头 \x7fELF
find /proc/<PID>/mem, +0x10000000, "\x7fELF"

不过因为 fexecve 替换得非常快,这个窗口期极短,很难抓。这也侧面证明了设计的有效性。


总结

这款Linux ELF运行时加密器,没有复杂的底层黑魔法,而是把Linux内存机制、密码学、进程安全三大核心知识点巧妙结合,用最简单的逻辑实现了高效的程序隐身防护。

它的核心价值不在于"加密"本身,而在于**"内存运行、不留痕迹"**的设计思路,彻底切断了逆向分析的核心路径,不管是个人程序版权保护,还是企业敏感程序防护,都能低成本实现高效防护。

读懂它的原理,不仅能学会给Linux程序做基础防护,更能吃透Linux底层内存和进程的核心逻辑,对Linux编程和系统安全学习都有很大帮助。

Welcome to follow WeChat official account【程序猿编码

相关推荐
Kurisu_红莉栖1 天前
c++复习——const,static字
c++
czxyvX1 天前
1-Qt概述
c++·qt
齐鲁大虾1 天前
新人编程语言选择指南
javascript·c++·python·c#
Eyfcom1 天前
快递管理系统:从“功能实现”到“人性化体验”与“客户洞察”的技术跃迁
c语言·系统架构·快递管理系统
子牙老师1 天前
软件虚拟化 vs 硬件虚拟化
linux·性能优化·云计算
CoderMeijun1 天前
C++ 多线程进阶:Lambda、条件变量与死锁
c++·多线程·条件变量·lambda·死锁·生产者消费者
Chockmans1 天前
图片马合成保姆级教程
web安全·网络安全·系统安全·网络攻击模型·安全威胁分析·安全架构·春秋云境
rayyy91 天前
Linux 下标准的 libX.so 软链接生成
linux
unicrom_深圳市由你创科技1 天前
上位机开发常用的语言 / 框架有哪些?
c++·python·c#
实心儿儿1 天前
Linux —— 基础IO - 文件描述符
linux·运维·服务器