December 10th, 2015

Why does OpenProcess return access denied, even if I enable debug privilege?

Many customers ask something like this:

We want to get the creation time of a process, but our call to Open­Process fails with ERROR_ACCESS_DENIED.

struct KernelHandleDeleter
{
 void operator()(HANDLE *h)
 {
  if (h != nullptr) CloseHandle(h);
 }
};

bool GetCreationTimeOfProcess(DWORD pid, FILETIME *creationTime)
{
 std::unique_ptr<HANDLE, KernelHandleDeleter>
    process(OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid));
 if (!process) {
  // GetLastError() returns ERROR_ACCESS_DENIED
  return false;
 }
 FILETIME exitTime, kernelTime, userTime;
 return GetProcessTimes(process, creationTime,
                 &exitTime, &kernelTime, &userTime) != FALSE;
}

It works if the program is running as administrator, but not if the program is running as a standard user. We even enabled debug privilege, but that didn’t help.

You don’t have access because you don’t have PROCESS_ALL_ACCESS permission on the process. PROCESS_ALL_ACCESS is a huge set of permissions, including WRITE_DAC (permission to change permissions), and if all you are doing is getting the process creation time, it’s totally overkill. It’s like getting power of attorney in order to be able to check their cell phone bill. All you need in order to check someone’s cell phone bill is to be listed as an authorized person on their account. You don’t need permission to make like-and-death decisions on their behalf.

Getting the creation time for a process requires PROCESS_QUERY_INFORMATION or PROCESS_QUERY_LIMITED_INFORMATION access. So just ask for the minimum required to accomplish what you need. then you are more likely to get it.

bool GetCreationTimeOfProcess(DWORD pid, FILETIME *creationTime)
{
 std::unique_ptr<HANDLE, KernelHandleDeleter>
    process(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid));
 ...
}
Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.