咱们平时在Linux系统(比如Debian、Fedora)里运行的可执行程序,不管是系统自带的date、ls命令,还是自己写的C程序,本质都是ELF格式二进制文件。
正常情况下,这类程序运行时,系统会把文件从硬盘读到内存,黑客或逆向分析人员很容易通过静态分析(直接扒硬盘
里的文件)、内存分析(抓内存里的程序数据)拿到源码逻辑、敏感逻辑,甚至篡改程序。
而咱们要讲的这款运行时加密器,就是给ELF程序量身定做的“隐身防护衣”,核心作用一句话概括:把原始ELF程序加密成乱码,生成一个新的加密程序;运行这个加密程序时,它不会把解密后的原始程序写回硬盘,而是直接在内存里解密、直接运行,用完还会自动擦除内存敏感数据,让分析人员抓不到完整的原始程序,大幅提升逆向破解难度。
简单对比两种运行模式:
它不是永久加密锁死程序,而是运行时动态解密、内存级隐身执行,兼顾程序正常使用和防逆向防护,常用于Linux环境下的程序版权保护、敏感功能防篡改、恶意程序分析规避(正规用途仅限合法程序防护)。
这款加密器涉及多个Linux底层和密码学领域,先把核心知识点拆解开,零基础也能跟上:
整个加密器的设计分为两大核心模块,全程围绕“加密原始程序→生成自解密程序→内存隐身运行”三步走,没有复杂冗余设计,每一步都服务于“隐身防护”:
...
voidsecure_wipe(void *ptr, size_t size){
if (ptr == NULL || size == 0) return;
volatileunsignedchar *p = (volatileunsignedchar *)ptr;
while (size--) {
*p++ = (unsignedchar)arc4random();
}
__asm__ __volatile__ ("" : : : "memory");
}
intutf8_strlen(constchar *str){
int chars = 0;
while (*str) {
if ((*str & 0xC0) != 0x80) {
chars++;
}
str++;
}
return chars;
}
// Function to get terminal width
intget_terminal_width(void){
structwinsizew;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) == 0) {
return w.ws_col;
}
char *columns = getenv("COLUMNS");
if (columns) {
return atoi(columns);
}
return80;
}
voidprint_centered_red(constchar *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);
}
longget_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;
}
voidencrypt_file(constchar *input_path, constchar *output_path,
constunsignedchar *key, constunsignedchar *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);
}
unsignedchar *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());
unsignedchar *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);
}
voidcreate_self_decrypting_stub(constchar *encrypted_path,
constunsignedchar *key,
constunsignedchar *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);
}
unsignedchar *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");
elsefprintf(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);
}
intmain(int argc, char *argv[]){
if (argc != 3) {
printf("\nUsage: %s <input_binary> <output_encrypted>\n", argv[0]);
return1;
}
else {
printf("Trying all the things...\n");
}
if (access(argv[1], R_OK) != 0) {
perror("Cannot access input file");
return1;
}
// Generate random key and IV
unsignedchar key[KEY_SIZE];
unsignedchar iv[IV_SIZE];
if (RAND_bytes(key, KEY_SIZE) != 1) {
fprintf(stderr, "Failed to generate random key\n");
return1;
}
if (RAND_bytes(iv, IV_SIZE) != 1) {
fprintf(stderr, "Failed to generate random IV\n");
return1;
}
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);
}
...
return0;
}
If you need the complete source code, please add the WeChat number (c17865354792)
原始ELF程序 → 【加密模块】AES-256-CBC加密 → 生成临时密文文件
→ 【自解密桩生成模块】把密文、密钥、IV打包成C代码(stub.c)
→ 编译stub.c → 生成最终加密可执行程序
→ 运行加密程序 → 子进程内存解密 → Memfd创建内存文件 → 直接运行内存程序 → 擦除内存数据 → 程序结束
核心目标:把明文ELF程序变成不可读的密文,同时生成唯一的密钥和IV。
核心目标:把密文、密钥、解密逻辑打包成一个独立程序,实现“运行即解密、解密即运行”,全程不落地。
核心目标:加密完成、程序运行结束后,彻底清理所有临时文件和内存数据,避免残留。
结合你提供的完整代码,避开逐行枯燥讲解,只拆解最核心、最能体现设计思路的代码片段,讲清“代码做什么、为什么这么做”:
#define KEY_SIZE 32 // AES-256要求的32位密钥
#define IV_SIZE 16 // CBC模式要求的16位初始向量
#define MAX_BINARY_SIZE (100 * 1024 * 1024) // 最大支持100MB程序
// 安全内存擦除:用随机数覆盖内存,防止数据残留
voidsecure_wipe(void *ptr, size_t size){
volatileunsignedchar *p = (volatileunsignedchar *)ptr;
while (size--) {
*p++ = (unsignedchar)arc4random(); // 随机数覆盖,不可恢复
}
__asm__ __volatile__ ("" : : : "memory"); // 内存屏障,确保擦除执行
}
解析:这部分是安全基础,KEY和IV的长度是AES-256-CBC的硬性要求,改了就无法正常解密;secure_wipe函数是核心防护,不用简单的0覆盖,而是用随机数覆盖,符合专业数据销毁标准,彻底杜绝内存残留。
// 初始化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;然后分两步完成加密,先处理主体数据,再处理末尾补齐数据,确保密文完整。加密完成后,立即擦除内存里的原始程序和密文,不留下临时数据。
这部分是“隐身衣”的灵魂,代码会自动生成一个名为stub.c的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直接执行内存文件,全程不碰硬盘,解密完成后立刻擦除数据,敏感数据在内存里只存在几毫秒,根本来不及被抓取。
主函数负责接收用户输入(原始程序路径、输出加密程序路径),生成密钥和IV,调用加密函数生成密文,再调用自解密函数生成stub.c,最后编译成最终的加密程序,同时清理临时文件,打印密钥和IV方便备份。
编译成功后会生成 ./crypter。
找一个系统自带的 ELF 程序做测试,比如 date:
cp /bin/date ./date_test
# 先看看原始程序长啥样
file ./date_test
strings ./date_test | head -20
strings 能看到一堆可读字符串,说明原始程序是"裸奔"的。
./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,只有你能读)# 运行加密后的程序,看功能是否正常
./date_enc
# 带参数试试
./date_enc +%Y-%m-%d
./date_enc -u
如果输出和原版的 ./date_test 一模一样,说明解密+执行链路通顺。
# 看文件类型
file ./date_test
file ./date_enc
# 扫字符串
strings ./date_test | head -10
strings ./date_enc | head -10
你会发现:
date_test:ELF 64-bit LSB executable...,strings 能扫出大量英文date_enc:虽然也是 ELF,但 strings 几乎扫不出有意义的内容(只有 OpenSSL 和 libc 的导入表字符串)这是最关键的特性验证——解密后的程序是否写到了磁盘上:
# 方法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 运行时没有任何临时文件落到磁盘,所有操作都在内存里完成。
# 运行加密程序
./date_enc &
# 看进程关系
pstree -p | grep date_enc
# 或者直接看
ps aux | grep date
你会看到类似这样的结构:
crypter(父进程)───date_enc(子进程)───date(原始程序)
实际上因为 fexecve 会替换子进程映像,最终看到的应该是:
waitpid)date 程序)想验证 secure_wipe 是否真的擦了内存,可以用 gdb attach:
# 终端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【程序猿编码】