PDA

View Full Version : Hooking ZwAllocateVirtualMemory


tadasv
June 2nd, 2009, 14:17
Hi guys. I am trying to hook ZwAllocateVirtualMemory from ntdll.dll. I rewrite first five bytes of ZwAllocateVirtualMemory with jmp to fake function, you can see the fake below. However the hooked function does not work as expected. If I uncomment test function I get stack overflow. Am I missing here something? Thanks.

Code:

void test()
{
/*FILE *f = fopen ("c:\\test.txt", "a";
fprintf (f, "PROCESS: %08X\nBASE: %08X\nZERO BITS: %08X\n"
"SiZE: %08X\nALLOC TYPE: %08X\nPROTECT: %08X\n\n",
hdZwAllocateVirtualMemory.par_process,
hdZwAllocateVirtualMemory.par_baseAddress,
hdZwAllocateVirtualMemory.par_zeroBits,
hdZwAllocateVirtualMemory.par_regionSize,
hdZwAllocateVirtualMemory.par_allocationType,
hdZwAllocateVirtualMemory.par_protect);

fclose (f);*/
}


void __declspec (naked) FakeZwAllocateVirtualMemory()
{
// save parameters
__asm {
mov eax, dword ptr ss:[esp + 4]
mov dword ptr [hdZwAllocateVirtualMemory].par_process, eax
mov eax, dword ptr ss:[esp + 8]
mov dword ptr [hdZwAllocateVirtualMemory].par_baseAddress, eax
mov eax, dword ptr ss:[esp + 12]
mov dword ptr [hdZwAllocateVirtualMemory].par_zeroBits, eax
mov eax, dword ptr ss:[esp + 16]
mov dword ptr [hdZwAllocateVirtualMemory].par_regionSize, eax
mov eax, dword ptr ss:[esp + 20]
mov dword ptr [hdZwAllocateVirtualMemory].par_allocationType, eax
mov eax, dword ptr ss:[esp + 24]
mov dword ptr [hdZwAllocateVirtualMemory].par_protect, eax
}

test();

__asm mov eax, 0x11
__asm jmp dword ptr hdZwAllocateVirtualMemory.exitAddress
}

BanMe
June 2nd, 2009, 15:10
sorry i started to write this code.. but iono what i was thinking..so i redid it..
Code:

#include <windows.h>


void Hook_ZwAllocateVirtualMemory(
__in HANDLE ProcessHandle,
__inout PVOID *BaseAddress,
__in ULONG_PTR ZeroBits,
__inout PSIZE_T RegionSize,
__in ULONG AllocationType,
__in ULONG Protect )
{
__try
{
__asm nop;
__asm nop;
__asm nop;
__asm nop;
__asm nop;
__asm pushad;
__asm mov edi,edi;
__asm lea edx,hdZwAllocateVirtualMemory
__asm mov ecx,6
__asm mov esi,esp
__asm xor edi,edi;
GetParams:
__asm cmp ecx,0;
__asm je GotParams;
__asm add esi,4;
__asm lodsd;
__asm mov dword ptr [edx+edi],eax
__asm add edi,4;
__asm sub ecx,1;
__asm jmp GetParams;
GotParams:
__asm popad;
__asm jmp [OldHandler]
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
__asm popad;
__asm jmp [OldHandler]
}
}

tadasv
June 3rd, 2009, 08:27
Thanks BanMe. What should be the value of ARGS_END? Well as the name implies it should be the address after the last argument. How do I get that? Thanks.

BanMe
June 3rd, 2009, 17:11
i reworked the code so no more ARGS_END..

I feel that this should suite your purposes if hdZwAllocateVirtualMemory's structure looks similar this..

Code:

struct _UNKNOWN_STRUCTURE
{
DWORD par_process;
DWORD par_baseAddress;
DWORD par_zeroBits;
DWORD par_regionSize;
DWORD par_allocationType;
DWORD par_protect;
//...
DWORD exitAddress;
}UNKNOWN_STRUCT,*PUNKNOWN_STRUCT;