Enabling and Disabling Privileges in C++

Enabling a privilege in an access token allows the process to perform system-level actions that it could not previously. Your application should thoroughly verify that the privilege is appropriate to the type of account, especially for the following powerful privileges.

Privilege constant/string Display name
Replace a process-level token
Back up files and directories
Debug programs
Adjust memory quotas for a process
Act as part of the operating system

Before enabling any of these potentially dangerous privileges, determine that functions or operations in your code actually require the privileges. For example, very few functions in the operating system actually require the SeTcbPrivilege. For a list of all the available privileges, see Privilege Constants.

The following example shows how to enable or disable a privilege in an access token. The example calls the LookupPrivilegeValue function to get the locally unique identifier (LUID) that the local system uses to identify the privilege. Then the example calls the AdjustTokenPrivileges function, which either enables or disables the privilege that depends on the value of the bEnablePrivilege parameter.

#include <windows.h>
#include <stdio.h>
#pragma comment(lib, "cmcfg32.lib")

BOOL SetPrivilege(
    HANDLE hToken,          // access token handle
    LPCTSTR lpszPrivilege,  // name of privilege to enable/disable
    BOOL bEnablePrivilege   // to enable or disable privilege
    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;
        tp.Privileges[0].Attributes = 0;

    // Enable the privilege or disable all privileges.

    if ( !AdjustTokenPrivileges(
           (PDWORD) NULL) )
          printf("AdjustTokenPrivileges error: %u\n", GetLastError() ); 
          return FALSE; 

    if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)

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

    return TRUE;