I'm trying to find a process id by its image name name from kernel mode (Windows). My code is working, but newly created processes sometimes show up delayed/can't be found (up to 60 seconds after their creation). My code looks as follows:
void WaitForProcess()
{
LARGE_INTEGER delay;
HANDLE value = 0;
delay.QuadPart = -20000000;
while (!value)
{
fpDbgPrintEx(0, 0, "Search\n");
fpKeDelayExecutionThread(KernelMode, FALSE, &delay); //Sleep for 2 seconds, then retry
value = HkGetProcessId(675793765); //notepad.exe
}
}
HANDLE GetProcessId(DWORD processHash)
{
HANDLE retVal = 0;
ULONG retLen = 0;
PSYSTEM_PROCESS_INFORMATION processInfo;
PVOID infoBuf = NULL;
WCHAR processName[256];
fpZwQuerySystemInformation(SystemProcessInformation, 0, 0, &retLen);
if (!retLen)
goto Done;
if (!(infoBuf = fpExAllocatePool(NonPagedPool, retLen)))
goto Done;
processInfo = infoBuf;
if (!NT_SUCCESS(fpZwQuerySystemInformation(SystemProcessInformation, processInfo, retLen, &retLen)))
goto Done;
while (processInfo->NextEntryOffset)
{
if (processInfo->ImageName.Buffer && (processInfo->ImageName.Length / sizeof(WCHAR)) < 256)
{
RtlZeroMemory(processName, 256 * sizeof(WCHAR));
memcpy(processName, processInfo->ImageName.Buffer, processInfo->ImageName.Length);
processName[(processInfo->ImageName.Length) / sizeof(WCHAR)] = '\0';
fpDbgPrintEx(0, 0, "Process: %wZ\n", &processInfo->ImageName);
if (HashString(processName) == processHash)
{
retVal = processInfo->UniqueProcessId;
break;
}
}
processInfo = (PSYSTEM_PROCESS_INFORMATION)((DWORD_PTR)processInfo + processInfo->NextEntryOffset);
}
Done:
if (infoBuf)
fpExFreePool(infoBuf);
return retVal;
}
Why does this delay exist? And is there a way to enumerate all processes in real time? Any help is appreciated!