AdjustTokenPrivileges错误6 - 处理无效

时间:2013-08-01 07:22:13

标签: c++ windows winapi visual-c++ privileges

请告知为什么下面的AdjustTokenPrivileges函数总是返回true,从而给出:“AdjustTokenPrivileges error 6”(即句柄无效)?

stackoverlow抱怨我没有解释这个

我不知道还有什么要补充的。我是c ++的新手。

HANDLE hToken;

OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES, &hToken);
SetPrivilege(hToken,L"SeBackupPrivilege",1 );
CloseHandle(hToken);

BOOL SetPrivilege(
HANDLE hToken,          // access token handle
LPCTSTR lpszPrivilege,  // name of privilege to enable/disable
BOOL bEnablePrivilege   // to enable or disable privilege
) 
{
TOKEN_PRIVILEGES oldtp;    /* old token privileges */
TOKEN_PRIVILEGES tp;
DWORD dwSize = sizeof (TOKEN_PRIVILEGES);
LUID luid;

if ( !LookupPrivilegeValue( 
        NULL,            // lookup privilege on local system
        lpszPrivilege,   // privilege to lookup 
        &luid ) )        // receives LUID of privilege
{
    printf("LookupPrivilegeValue error: %u\n", GetLastError() ); 
    return FALSE; 
}

tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
if (bEnablePrivilege)
    tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
else
    tp.Privileges[0].Attributes = 0;

// Enable the privilege or disable all privileges.

if ( !AdjustTokenPrivileges(
       &hToken, 
       FALSE, 
       &tp, 
       sizeof(TOKEN_PRIVILEGES), 
       (PTOKEN_PRIVILEGES) &oldtp, 
       (PDWORD) &dwSize) )
{ 
      printf("AdjustTokenPrivileges error: %u\n", GetLastError() ); //Get error 6 here (ie invalid handle)
      return FALSE; 
} 

if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)

{
      printf("The token does not have the specified privilege. \n");
      return FALSE;
} 

return TRUE;
}

2 个答案:

答案 0 :(得分:1)

您应该请求TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY并正确调用该函数:

if (!OpenProcessToken(GetCurrentProcess(), 
  TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) 
  return FALSE;

并请:始终检查有效的退货值!

有关完整示例,请参阅:How to Shut Down the System

仅供参考:您的功能SetPrivilege已从Enabling and Disabling Privileges in C++

复制

答案 1 :(得分:0)

&hToken -> hToken

if ( !AdjustTokenPrivileges(
       hToken, 
       FALSE, 
       &tp, 
       sizeof(TOKEN_PRIVILEGES), 
       (PTOKEN_PRIVILEGES) &oldtp, 
       (PDWORD) &dwSize) )