Code:
HMODULE CRemoteLoader::GetRemoteModuleHandleA(const char* Module)
{
void* dwModuleHandle = 0;
PPROCESS_BASIC_INFORMATION pbi = NULL;
PEB peb;
PEB_LDR_DATA peb_ldr;
// Try to allocate buffer
HANDLE hHeap = GetProcessHeap();
DWORD dwSize = sizeof(PROCESS_BASIC_INFORMATION);
pbi = (PPROCESS_BASIC_INFORMATION)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, dwSize);
ULONG dwSizeNeeded = 0;
NTSTATUS dwStatus = fnNTQIP(m_hProcess, ProcessBasicInformation, pbi, dwSize, &dwSizeNeeded);
if (dwStatus >= 0 && dwSize < dwSizeNeeded)
{
if (pbi)
HeapFree(hHeap, 0, pbi);
pbi = (PPROCESS_BASIC_INFORMATION)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, dwSizeNeeded);
if (!pbi)
{
#ifdef _DEBUG
printf("Couldn't allocate heap buffer!\n");
#endif
return NULL;
}
dwStatus = fnNTQIP(m_hProcess, ProcessBasicInformation, pbi, dwSizeNeeded, &dwSizeNeeded);
}
// Did we successfully get basic info on process
if (dwStatus >= 0)
{
// Read Process Environment Block (PEB)
if (pbi->PebBaseAddress)
{
SIZE_T dwBytesRead = 0;
if (ReadProcessMemory(m_hProcess, pbi->PebBaseAddress, &peb, sizeof(peb), &dwBytesRead))
{
dwBytesRead = 0;
if (ReadProcessMemory(m_hProcess, peb.Ldr, &peb_ldr, sizeof(peb_ldr), &dwBytesRead))
{
LIST_ENTRY *pLdrListHead = (LIST_ENTRY *)peb_ldr.InLoadOrderModuleList.Flink;
LIST_ENTRY *pLdrCurrentNode = peb_ldr.InLoadOrderModuleList.Flink;
do
{
LDR_DATA_TABLE_ENTRY lstEntry = { 0 };
dwBytesRead = 0;
if (!ReadProcessMemory(m_hProcess, (void*)pLdrCurrentNode, &lstEntry, sizeof(LDR_DATA_TABLE_ENTRY), &dwBytesRead))
{
#ifdef _DEBUG
char dbgOut[1024];
sprintf_s(dbgOut, "CRemoteLoader[GetRemoteModuleHandleA] Could not read list entry from LDR list. Error = %X", GetLastError());
MessageBox(0, dbgOut, "Injectora", MB_ICONERROR);
#endif
if (pbi)
HeapFree(hHeap, 0, pbi);
return NULL;
}
pLdrCurrentNode = lstEntry.InLoadOrderLinks.Flink;
wchar_t wcsBaseDllName[MAX_PATH] = { 0 };
char strBaseDllName[MAX_PATH] = { 0 };
if (lstEntry.BaseDllName.Length > 0)
{
dwBytesRead = 0;
if (ReadProcessMemory(m_hProcess, (LPCVOID)lstEntry.BaseDllName.Buffer, &wcsBaseDllName, lstEntry.BaseDllName.Length, &dwBytesRead))
{
size_t bytesCopied = 0;
wcstombs_s(&bytesCopied, strBaseDllName, wcsBaseDllName, MAX_PATH);
}
}
//wchar_t wcsFullDllName[MAX_PATH] = { 0 };
//char strFullDllName[MAX_PATH] = { 0 };
//if (lstEntry.FullDllName.Length > 0)
//{
// dwBytesRead = 0;
// if (ReadProcessMemory(m_hProcess, (LPCVOID)lstEntry.FullDllName.Buffer, &wcsFullDllName, lstEntry.FullDllName.Length, &dwBytesRead))
// {
// size_t bytesCopied = 0;
// wcstombs_s(&bytesCopied, strFullDllName, wcsFullDllName, MAX_PATH);
// }
//}
if (lstEntry.DllBase != nullptr && lstEntry.SizeOfImage != 0)
{
if (_stricmp(strBaseDllName, Module) == 0)
{
dwModuleHandle = lstEntry.DllBase;
break;
}
}
} while (pLdrListHead != pLdrCurrentNode);
} // Get Ldr
} // Read PEB
} // Check for PEB
}
if (pbi)
HeapFree(hHeap, 0, pbi);
return (HMODULE)dwModuleHandle;
}