Created
January 11, 2019 09:53
-
-
Save Barakat/be6320f29a5d9c3f1e38c72686302c68 to your computer and use it in GitHub Desktop.
Check if the process running under an admin user. Tested on Windows 95-Windows 10 (checks for elevation on Vista+)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Windows.h> | |
#pragma warning(push) | |
#pragma warning(disable: 4996) | |
bool RunningAsAdmin() | |
{ | |
OSVERSIONINFOA os_version_information; | |
os_version_information.dwOSVersionInfoSize = sizeof(os_version_information); | |
GetVersionExA(&os_version_information); | |
// Windows 95/98/ME are not multi-user OSs | |
if (os_version_information.dwPlatformId == 1) | |
{ | |
return true; | |
} | |
const HANDLE process = GetCurrentProcess(); | |
const HANDLE heap = GetProcessHeap(); | |
HANDLE token; | |
bool running_as_admin = false; | |
// Pre-Windows Vista, we only need to check if the user in admin group | |
if (OpenProcessToken(process, TOKEN_QUERY, &token) != FALSE) | |
{ | |
if (os_version_information.dwMajorVersion < 6) | |
{ | |
DWORD required_size; | |
if (GetTokenInformation(token, TokenGroups, NULL, 0, &required_size) == FALSE | |
&& GetLastError() == ERROR_INSUFFICIENT_BUFFER) | |
{ | |
const DWORD token_groups_size = required_size; | |
PTOKEN_GROUPS token_groups = reinterpret_cast<PTOKEN_GROUPS>( | |
HeapAlloc(heap, HEAP_GENERATE_EXCEPTIONS, token_groups_size) | |
); | |
if (GetTokenInformation(token, TokenGroups, token_groups, token_groups_size, &required_size) != FALSE) | |
{ | |
PSID admin_group_sid; | |
SID_IDENTIFIER_AUTHORITY authority = SECURITY_NT_AUTHORITY; | |
if (AllocateAndInitializeSid(&authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, | |
0, 0, 0, 0, 0, 0, | |
&admin_group_sid) != FALSE) | |
{ | |
for (DWORD i = 0; i < token_groups->GroupCount; ++i) | |
{ | |
if (EqualSid(admin_group_sid, token_groups->Groups[i].Sid) != FALSE) | |
{ | |
running_as_admin = true; | |
break; | |
} | |
} | |
FreeSid(admin_group_sid); | |
} | |
} | |
HeapFree(heap, 0, token_groups); | |
} | |
} | |
// On Windows Vista onward, being in admin group is not enough , user must run-as admin | |
else | |
{ | |
struct | |
{ | |
DWORD TokenIsElevated; | |
} token_elevation; | |
DWORD return_length; | |
if (GetTokenInformation(token, | |
static_cast<TOKEN_INFORMATION_CLASS>(20), | |
&token_elevation, | |
sizeof(token_elevation), | |
&return_length) != FALSE) | |
{ | |
running_as_admin = token_elevation.TokenIsElevated != 0; | |
} | |
} | |
CloseHandle(token); | |
} | |
return running_as_admin; | |
} | |
#pragma warning(pop) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment