Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if my program is ran by user as administrator (Vista/Win7, C++) [duplicate]

I saw IsInRole method but I can't find information on how to use it with C++.

like image 605
Vladimir Avatar asked Aug 23 '10 10:08

Vladimir


3 Answers

There's a C++ code snippet in this old answer taken from the UACHelpers project on CodePlex.

like image 115
Rup Avatar answered Nov 20 '22 12:11

Rup


This code solves your problem. Feel free to use it. It works with SE_GROUP_USE_FOR_DENY_ONLY.

/**
  IsGroupMember determines if the current thread or process has a token that contais a given and enabled user group. 

  Parameters
   dwRelativeID: Defines a relative ID (par of a SID) of a user group (e.g. Administrators DOMAIN_ALIAS_RID_ADMINS (544) = S-1-5-32-544)
   bProcessRelative: Defines whether to use the process token (TRUE) instead of the thread token (FALSE). If FALSE and no thread token is present
     the process token will be used though.
   bIsMember: Returns the result of the function. The value returns TRUE if the user is an enabled member of the group; otherwise FALSE.

  Return Value
    If the function succeeds, the return value is TRUE; otherwise FALSE. Call GetLastError for more information.
*/
BOOL IsGroupMember(DWORD dwRelativeID, BOOL bProcessRelative, BOOL* pIsMember)
{
    HANDLE hToken, hDupToken;
    PSID pSid = NULL;
    SID_IDENTIFIER_AUTHORITY SidAuthority = SECURITY_NT_AUTHORITY;

    if (!pIsMember)
    {
        SetLastError(ERROR_INVALID_USER_BUFFER);
        return FALSE;
    }

    if (bProcessRelative || !OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_DUPLICATE, TRUE, &hToken))
    {
        if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_DUPLICATE, &hToken))
        {
            return FALSE;
        }
    }

    if (!DuplicateToken(hToken, SecurityIdentification, &hDupToken))
    {
        CloseHandle(hToken);
        return FALSE;
    }

    CloseHandle(hToken);
    hToken = hDupToken;

    if (!AllocateAndInitializeSid(&SidAuthority, 2,
            SECURITY_BUILTIN_DOMAIN_RID, dwRelativeID, 0, 0, 0, 0, 0, 0,
            &pSid))
    {
        CloseHandle(hToken);
        return FALSE;
    }

    if (!CheckTokenMembership(hToken, pSid, pIsMember))
    {
        CloseHandle(hToken);
        FreeSid(pSid);

        *pIsMember = FALSE;
        return FALSE;
    }

    CloseHandle(hToken);
    FreeSid(pSid);

    return TRUE;
}

BOOL IsUserAdministrator(BOOL* pIsAdmin)
{
    return IsGroupMember(DOMAIN_ALIAS_RID_ADMINS, FALSE, pIsAdmin);
}
like image 42
ChristianWimmer Avatar answered Nov 20 '22 13:11

ChristianWimmer


The documentation of IsUSerAnAdmin explains that it's deprecated since Vista, but points you to CheckTokenMembership. That should do the job for you.

like image 30
MSalters Avatar answered Nov 20 '22 13:11

MSalters