why is CreateProcessWithTokenW failing with ERROR_ACCESS_DENIED

寵の児 提交于 2019-12-03 16:07:52

Through trial and error I figured out that the token you pass to CreateProcessWithTokenW() needs the following access flags (at least on Windows 7 SP1 64-bit):

  • TOKEN_ASSIGN_PRIMARY
  • TOKEN_DUPLICATE
  • TOKEN_QUERY
  • TOKEN_ADJUST_DEFAULT
  • TOKEN_ADJUST_SESSIONID

The last two in bold are very helpfully not mentioned at all in the documentation for CreateProcessWithTokenW().

EDIT: The following code works fine for me (when running elevated):

HANDLE hToken = NULL;
if(OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &hToken))
{
    HANDLE hDuplicate = NULL;
    if(DuplicateTokenEx(hToken, TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID, NULL, SecurityImpersonation, TokenPrimary, &hDuplicate))
    {
        TCHAR szCommandLine[MAX_PATH];
        _tcscpy_s(szCommandLine, MAX_PATH, _T("C:\\Windows\\system32\\notepad.exe"));
        STARTUPINFO StartupInfo;
        ZeroMemory(&StartupInfo, sizeof(STARTUPINFO));
        StartupInfo.cb = sizeof(STARTUPINFO);
        PROCESS_INFORMATION ProcessInformation;
        ZeroMemory(&ProcessInformation, sizeof(PROCESS_INFORMATION));
        if(CreateProcessWithTokenW(hDuplicate, LOGON_WITH_PROFILE, NULL, szCommandLine, 0, NULL, NULL, &StartupInfo, &ProcessInformation))
        {
            WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
            CloseHandle(ProcessInformation.hThread);
            ProcessInformation.hThread = NULL;
            CloseHandle(ProcessInformation.hProcess);
            ProcessInformation.hProcess = NULL;
        }
        CloseHandle(hDuplicate);
        hToken = hDuplicate;
    }
    CloseHandle(hToken);
    hToken = NULL;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!