[UAC]C++判断某进程是否有管理员权限

BOOL IsAdminProcess(UINT PID)
{
    if (PID <= 0)
        PID = GetCurrentProcessId();
    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, PID);
    if (hProcess == NULL) {//要么没这个进程,要么也有可能是ADMIN权限无法打开
        return TRUE;
    }
    HANDLE hToken;
    DWORD dwAttributes;
    DWORD isAdmin(0);
    if (OpenProcessToken(hProcess, TOKEN_QUERY, &hToken))
    {
        SID_IDENTIFIER_AUTHORITY Authority;
        Authority.Value[5] = 5;

        PSID psidAdmin = NULL;
        if (AllocateAndInitializeSid(&Authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &psidAdmin))
        {
            DWORD dwCount = 0;
            GetTokenInformation(hToken, TokenGroups, NULL, 0, &dwCount);
            TOKEN_GROUPS *pTokenGroups = (TOKEN_GROUPS *)new BYTE[dwCount];
            GetTokenInformation(hToken, TokenGroups, pTokenGroups, dwCount, &dwCount);
            DWORD dwGroupCount = pTokenGroups->GroupCount;
            for (DWORD i = 0; i < dwGroupCount; i++)
            {
                if (EqualSid(psidAdmin, pTokenGroups->Groups[i].Sid))
                {
                    dwAttributes = pTokenGroups->Groups[i].Attributes;
                    isAdmin = (dwAttributes & SE_GROUP_USE_FOR_DENY_ONLY) != SE_GROUP_USE_FOR_DENY_ONLY;
                    break;
                }
            }
            delete[] pTokenGroups;
            FreeSid(psidAdmin);
        }
        CloseHandle(hToken);
    }
    CloseHandle(hProcess);
    return isAdmin;
}
posted @ 2022-08-13 20:54  Icys  阅读(608)  评论(0编辑  收藏  举报