typedef BOOL(__stdcall *PIsUserAnAdminFunc)();
typedef BOOL(__stdcall *PSHTestTokenMembershipFunc)(
HANDLE, ULONG);
typedef BOOL(__stdcall *PCheckTokenMembershipFunc)(
HANDLE, PSID, PBOOL);
bool TService::IsUserAnAdmin()
{
static HMODULE hShellLib = LoadLibrary(L"SHELL32");
static PIsUserAnAdminFunc ApiIsUserAnAdmin = (PIsUserAnAdminFunc)GetProcAddress(hShellLib, "IsUserAnAdmin");
if (ApiIsUserAnAdmin) {
return ApiIsUserAnAdmin();
}
static PSHTestTokenMembershipFunc ApiTestTokenMembership = (PSHTestTokenMembershipFunc)GetProcAddress(hShellLib, "SHTestTokenMembership");
if (ApiTestTokenMembership) {
return ApiTestTokenMembership(NULL, DOMAIN_ALIAS_RID_ADMINS);
}
static HMODULE hAdvApiLib = LoadLibrary(L"ADVAPI32");
static PCheckTokenMembershipFunc ApiCheckTokenMembership = (PCheckTokenMembershipFunc)GetProcAddress(hAdvApiLib, "CheckTokenMembership");
if (ApiCheckTokenMembership) {
PSID sidToCheck;
static SID_IDENTIFIER_AUTHORITY sidia = SECURITY_NT_AUTHORITY;
if (AllocateAndInitializeSid(&sidia, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &sidToCheck)) {
BOOL bIsMember;
bool bSuccess = ApiCheckTokenMembership(NULL, sidToCheck, &bIsMember);
FreeSid(sidToCheck);
if (bSuccess) {
return bIsMember;
}
}
}
return false;
}