Not able to get executable path for process id 4 (ntoskrnl.exe)

622 Views Asked by At

I have been trying to obtain the executable path by enumerating all processes. I used both GetModuleFileNameExA and QueryFullProcessImageNameA to obtain the path of the executables.

It works for almost everything except few like ntoskrnl.exe (System, Process id: 4). When I use these methods, the HANDLE that's obtained is NOT NULL but the functions fail.

GetLastError turns out to be 31

Is there any problem with the code or any workaround has to be done? NOTE: My EXE is a 32-bit EXE and I have a 64 bit OS. Does this have anything to do with it?

INT32 GetFileNameAndPath(DWORD processId,string &filePath,string &fileName)
{
CHAR path[MAX_PATH];
DWORD size=MAX_PATH;
smatch match;

HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,FALSE,processId);

if(hProcess != NULL)
{
    regex regx("[^\\\\]+$");

    if(GetModuleFileNameExA(hProcess,NULL,path,size) != 0)
    {
        filePath = path;

        if(regex_search(filePath,match,regx))
            fileName = match.str();
    }
    else if(QueryFullProcessImageNameA(hProcess,0,path,&size) != 0)
    {
        filePath = path;

        if(regex_search(filePath,match,regx))
            fileName = match.str();
    }
    else
    {
        cout<<GetLastError();
    }
}

CloseHandle(hProcess);

return SUCCESS;
}
1

There are 1 best solutions below

6
On

Yes! The answer is that you cannot obtain the path of ntoskrnl.exe. I was wondering how task manager does it. I found it after checking it for hours! :P (Shouldn't have taken that much).

Task Manager Screenshot

If you see that screenshot you can see that the process System's Image path name was C:\WINDOWS whereas for conhost.exe it was C:\Windows.

Even windows have hardcoded for that Exe. They have hardcoded it as %Systemroot%\system32\ntoskrnl.exe. Only when you expand Systemroot you get the value as C:\WINDOWS. When you do with API such as GetModuleFileNameEx you get the path as C:\Windows. So technically there isn't a way. And by my assumption, due to security reasons they didn't allow any user to get the path of the Exe.