Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a user has local admin privileges in win32

Tags:

c++

winapi

How do I check if a user has local admin privileges in win32 from c++

like image 943
Tony Edgecombe Avatar asked Feb 24 '09 10:02

Tony Edgecombe


2 Answers

Just found IsUserAnAdmin() in shlobj.h which does the job for me.

like image 90
Tony Edgecombe Avatar answered Sep 28 '22 03:09

Tony Edgecombe


You might need more than that to deal with elevation and such like...

I do it like this....

bool CProcessToken::IsUserAnAdmin() const
{
#if _WIN32_WINNT >= 0x0600 

   bool isAdmin = false;

   DWORD bytesUsed = 0;

   TOKEN_ELEVATION_TYPE tokenElevationType;

   if (!::GetTokenInformation(m_hToken, TokenElevationType, &tokenElevationType, sizeof(tokenElevationType), &bytesUsed))
   {
      const DWORD lastError = ::GetLastError();

      throw CWin32Exception(_T("CProcessToken::IsUserAnAdmin() - GetTokenInformation - TokenElevationType"), lastError);
   }

   if (tokenElevationType == TokenElevationTypeLimited)
   {
      CSmartHandle hUnfilteredToken;

      if (!::GetTokenInformation(m_hToken, TokenLinkedToken, reinterpret_cast<void *>(hUnfilteredToken.GetHandle()), sizeof(HANDLE), &bytesUsed))
      {
         const DWORD lastError = ::GetLastError();

         throw CWin32Exception(_T("CProcessToken::IsUserAnAdmin() - GetTokenInformation - TokenLinkedToken"), lastError);
      }

      BYTE adminSID[SECURITY_MAX_SID_SIZE];

      DWORD sidSize = sizeof(adminSID);

      if (!::CreateWellKnownSid(WinBuiltinAdministratorsSid, 0, &adminSID, &sidSize))
      {
         const DWORD lastError = ::GetLastError();

         throw CWin32Exception(_T("CProcessToken::IsUserAnAdmin() - CreateWellKnownSid"), lastError);
      }

      BOOL isMember = FALSE;

      if (::CheckTokenMembership(hUnfilteredToken, &adminSID, &isMember))
      {
         const DWORD lastError = ::GetLastError();

         throw CWin32Exception(_T("CProcessToken::IsUserAnAdmin() - CheckTokenMembership"), lastError);
      }

      isAdmin = (isMember != FALSE);
   }
   else
   {
      isAdmin = ToBool(::IsUserAnAdmin());         
   }

   return isAdmin;

#else
   return ToBool(::IsUserAnAdmin());         
#endif
}

I can't remember where I got the information from to write that bit of code though...

like image 30
Len Holgate Avatar answered Sep 28 '22 02:09

Len Holgate