ReadProcessMemory() fails with 'handle is invalid' error

Hi,

I want to get the addresses of heaps and particular heap metadata (_HEAP_USERDATA_HEADER) for a specified process. For this, I am trying to get the PEB base address of the process and walk down from there to get the heap information. I retrieve the PEB address using ZwQueryInformationProcess() and then read the process memory starting from PEB base address. I get the PEB base address right but the ReadProcessMemory() fails with error code 6: ‘The handle is invalid’. The OpenProcess() function returns a valid handle though.

I have tried in Windows 8.1, 10 (64 bit) and with both 32 bit (Acrobat reader) and 64 bit (notepad) applications. The code flow for getting ‘image base address’, as I have implemented, is as follows:

if (enableTokenPrivilege(SE_DEBUG_NAME) == FALSE){ … }

hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);

retValue = ZwQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi, sizeof(PROCESS_BASIC_INFORMATION), &retLength);

retValue = ReadProcessMemory(pi.hProcess, (LPCVOID)(pbi.PebBaseAddress+0x10), (LPVOID)ba, 8, &nb_read);
if (!retValue){
printf(“ReadProcessMemory() failed with error %d\n”, GetLastError());
return -1;
}

Can anyone please give a clue about what I am doing wrong? Thanks.

pi.hProcess?

Oh, can’t say how much annoyed I got of myself after seeing this. Thanks a lot for pointing that out. I corrected the line as:
retValue = ReadProcessMemory(hProcess, (LPCVOID)(pbi.PebBaseAddress+0x10), &imageBase, 8, &nb_read);

Now ReadProcessMemory() fails with error 299 (ERROR_PARTIAL_COPY - only part of a ReadProcessMemory or WriteProcessMemory request was completed).

Thanks.

pbi.PebBaseAddress+0x10