当尝试通过 NtAllocateVirtualMemory 分配内存时(它通过 VirtualAlloc 工作,但我想知道它如何通过 NTAPI 工作)并且我不明白原因是什么,我授予了 PAGE_EXECUTE_READ 权限,但我也无法分配
#include <Windows.h>
#define NT_SUCCESS(Status) ((NTSTATUS)(Status) >= 0)
unsigned char buffer[] = {
0x90, // NOP
0x90, // NOP
0xcc, // INT3
0xc3 // RET
};
unsigned int buffer_len = 4;
typedef NTSTATUS(NTAPI* pNtAllocateVirtualMemory)(
HANDLE ProcessHandle,
PVOID* BaseAddress,
ULONG ZeroBits,
PULONG RegionSize,
ULONG AllocationType,
ULONG Protect
);
typedef NTSTATUS(NTAPI* pNtWriteVirtualMemory)(
HANDLE ProcessHandle,
PVOID BaseAddress,
PVOID Buffer,
SIZE_T BufferSize,
PSIZE_T NumberOfBytesWritten
);
int main()
{
PVOID exec_mem;
BOOL rv;
HANDLE rt;
pNtAllocateVirtualMemory ntAllocateVirtualMemory =
(pNtAllocateVirtualMemory)GetProcAddress(GetModuleHandleA("ntdll"), "NtAllocateVirtualMemory");
NTSTATUS status = ntAllocateVirtualMemory(
GetCurrentProcess(),
&exec_mem,
0,
(PULONG)&buffer_len,
MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE
);
if (!NT_SUCCESS(status)) {
return -1;
}
pNtWriteVirtualMemory ntWriteVirtualMemory =
(pNtWriteVirtualMemory)GetProcAddress(GetModuleHandleA("ntdll"), "NtWriteVirtualMemory");
SIZE_T bytesWritten;
status = ntWriteVirtualMemory(
GetCurrentProcess(),
exec_mem,
buffer,
buffer_len,
&bytesWritten
);
rt = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)exec_mem, 0, 0, 0);
WaitForSingleObject(rt, -1);
return 0;
}
我尝试更改权限、长度,尝试将长度作为指针传递,但仍然失败。
根据 Igor Tandetnik 的建议:
ZeroBits
参数应该是ULONG_PTR
当传递给 exec_mem
时,
NtAllocateVirtualMemory
未初始化,包含随机垃圾。