Search code examples
c++windowswinapiaccess-tokenelevation

Create elevated token with SetTokenInformation returns error 87


I am trying to create an elevated token with SetTokenInformation, but it fails and keeps returning error code 87.

This is my code:

#include <Windows.h>

int main()
{
    HANDLE currentProcessToken, newTok;
    OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &currentProcessToken);
    DuplicateTokenEx(currentProcessToken, TOKEN_ALL_ACCESS, nullptr, SecurityImpersonation, TokenPrimary, &newTok);
    CloseHandle(currentProcessToken);
    TOKEN_ELEVATION elev = { 1 };
    BOOL setTokenInfo = SetTokenInformation(newTok, TokenElevation, &elev, sizeof(TOKEN_ELEVATION));
    DWORD error = GetLastError(); // is 87 which is "the parameter is incorrect"
    return 0;
}

Solution

  • TokenElevation is valid information class only for GetTokenInformation function. you can query are TokenIsElevated but you can not set it. NtSetInformationToken return STATUS_INVALID_INFO_CLASS in this case. the SetTokenInformation convert this error to ERROR_INVALID_PARAMETER. original NTSTATUS error code you can got by calling RtlGetLastNtStatus(). and anyway you can not "elevate" already existing token. this is by design