Reputation: 23591
I need to know if the current process is running as system. In C# I use WindowsIdentity.GetCurrent().IsSystem
to do that, what is the equivalent in C++?
I'm trying to avoid comparing usernames, because different OS has different usernames for SYSTEM account.
Upvotes: 1
Views: 767
Reputation: 23591
I have created an example based on Eryk's idea, and it works:
BOOL IsSystem()
{
HANDLE hToken = NULL;
BOOL result = false;
TOKEN_USER *tokenUser = NULL;
DWORD dwLength = 0;
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken) == 0)
{
DbgPrint("OpenProcessToken(): %d", GetLastError());
goto cleanup;
}
if (GetTokenInformation(hToken, TokenUser, (LPVOID) tokenUser, 0, &dwLength) == 0)
{
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
{
DbgPrint("GetTokenInformation(): %d", GetLastError());
goto cleanup;
}
tokenUser = (TOKEN_USER *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwLength);
if (tokenUser == NULL)
{
goto cleanup;
}
if (GetTokenInformation(hToken, TokenUser, (LPVOID) tokenUser, dwLength, &dwLength) == 0)
{
DbgPrint("GetTokenInformation(): %d", GetLastError());
goto cleanup;
}
result = IsWellKnownSid(tokenUser->User.Sid, WinLocalSystemSid);
}
cleanup:
if (tokenUser != NULL)
{
HeapFree(GetProcessHeap(), NULL, tokenUser);
}
return result;
}
Upvotes: 2