Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Please advise why the AdjustTokenPrivileges function below always returns true, thus giving: "AdjustTokenPrivileges error 6" (ie invalid handle)?

stackoverlow is complaining that I didn't explain this enough

I don't know what else to add. I'm new to 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;
}
share|improve this question
    
Does OpenProcessToken() succeed (it won't even compile as posted BTW given missing () for GetCurrentProcess) ? –  hmjd Aug 1 '13 at 7:27
    
@hmjd: It will compile... because HANDLE is void* and will accept anything; even an address to a function ;) –  Jochen Kalmbach Aug 1 '13 at 7:39

1 Answer 1

up vote 1 down vote accepted

You should request for TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY and correctly call the function:

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

And please: Always check for valid return values!

For a complete exaplte see also: How to Shut Down the System

And just for reference: Your function SetPrivilege was copied from Enabling and Disabling Privileges in C++

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.